@kya-os/checkpoint-shared 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/agent-catalog.d.mts +12 -0
  3. package/dist/agent-catalog.d.mts.map +1 -0
  4. package/dist/agent-catalog.d.ts +12 -0
  5. package/dist/agent-catalog.d.ts.map +1 -0
  6. package/dist/agent-catalog.js +105 -0
  7. package/dist/agent-catalog.mjs +105 -0
  8. package/dist/agent-catalog.mjs.map +1 -0
  9. package/dist/beacon-types/index.d.mts +18 -0
  10. package/dist/beacon-types/index.d.mts.map +1 -1
  11. package/dist/beacon-types/index.d.ts +18 -0
  12. package/dist/beacon-types/index.d.ts.map +1 -1
  13. package/dist/beacon-types/index.js +116 -12
  14. package/dist/beacon-types/index.mjs +105 -13
  15. package/dist/beacon-types/index.mjs.map +1 -1
  16. package/dist/browser-posture-5fPrsxx7.d.mts.map +1 -1
  17. package/dist/browser-posture-CCR1kh5e.d.ts.map +1 -1
  18. package/dist/browser-posture-cookie.js +1 -1
  19. package/dist/browser-posture-cookie.mjs +1 -1
  20. package/dist/browser-posture-cookie.mjs.map +1 -1
  21. package/dist/browser-posture-proof-verifier-DvsOmFrM.js +202 -0
  22. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +180 -0
  23. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +1 -0
  24. package/dist/browser-posture-proof-verifier.d.mts +25 -0
  25. package/dist/browser-posture-proof-verifier.d.mts.map +1 -0
  26. package/dist/browser-posture-proof-verifier.d.ts +25 -0
  27. package/dist/browser-posture-proof-verifier.d.ts.map +1 -0
  28. package/dist/browser-posture-proof-verifier.js +7 -0
  29. package/dist/browser-posture-proof-verifier.mjs +3 -0
  30. package/dist/browser-posture-proof.d.mts +3 -18
  31. package/dist/browser-posture-proof.d.mts.map +1 -1
  32. package/dist/browser-posture-proof.d.ts +3 -18
  33. package/dist/browser-posture-proof.d.ts.map +1 -1
  34. package/dist/browser-posture-proof.js +6 -131
  35. package/dist/browser-posture-proof.mjs +1 -126
  36. package/dist/browser-posture-proof.mjs.map +1 -1
  37. package/dist/browser-posture.js +1 -1
  38. package/dist/browser-posture.mjs +1 -1
  39. package/dist/browser-posture.mjs.map +1 -1
  40. package/dist/browser.d.mts +0 -282
  41. package/dist/browser.d.mts.map +1 -1
  42. package/dist/browser.d.ts +0 -282
  43. package/dist/browser.d.ts.map +1 -1
  44. package/dist/browser.js +1 -1
  45. package/dist/browser.mjs +1 -1
  46. package/dist/browser.mjs.map +1 -1
  47. package/dist/canonical-signer/index.mjs.map +1 -1
  48. package/dist/consent-handoff.d.mts +0 -3
  49. package/dist/consent-handoff.d.mts.map +1 -1
  50. package/dist/consent-handoff.d.ts +0 -3
  51. package/dist/consent-handoff.d.ts.map +1 -1
  52. package/dist/consent-handoff.mjs.map +1 -1
  53. package/dist/default-sign-in-host.d.mts +10 -0
  54. package/dist/default-sign-in-host.d.mts.map +1 -0
  55. package/dist/default-sign-in-host.d.ts +10 -0
  56. package/dist/default-sign-in-host.d.ts.map +1 -0
  57. package/dist/default-sign-in-host.js +72 -0
  58. package/dist/default-sign-in-host.mjs +66 -0
  59. package/dist/default-sign-in-host.mjs.map +1 -0
  60. package/dist/errors/index.d.mts +1 -0
  61. package/dist/errors/index.d.mts.map +1 -1
  62. package/dist/errors/index.d.ts +1 -0
  63. package/dist/errors/index.d.ts.map +1 -1
  64. package/dist/errors/index.js +5 -2
  65. package/dist/errors/index.mjs +5 -2
  66. package/dist/errors/index.mjs.map +1 -1
  67. package/dist/{fetcher-CivUCbhL.d.ts → fetcher-C8qvwdnA.d.ts} +2 -2
  68. package/dist/{fetcher-CivUCbhL.d.ts.map → fetcher-C8qvwdnA.d.ts.map} +1 -1
  69. package/dist/{fetcher-cXQsbm6s.d.mts → fetcher-D2vjr7jB.d.mts} +2 -2
  70. package/dist/{fetcher-cXQsbm6s.d.mts.map → fetcher-D2vjr7jB.d.mts.map} +1 -1
  71. package/dist/gateway-client-ip.d.mts +0 -2
  72. package/dist/gateway-client-ip.d.mts.map +1 -1
  73. package/dist/gateway-client-ip.d.ts +0 -2
  74. package/dist/gateway-client-ip.d.ts.map +1 -1
  75. package/dist/gateway-client-ip.mjs.map +1 -1
  76. package/dist/host-adapter/index.d.mts +1 -1
  77. package/dist/host-adapter/index.d.ts +1 -1
  78. package/dist/host-adapter/index.js +1 -1
  79. package/dist/host-adapter/index.mjs +1 -1
  80. package/dist/{host-adapter-DHyISsIf.mjs → host-adapter-BKdQHwbi.mjs} +2 -2
  81. package/dist/{host-adapter-DHyISsIf.mjs.map → host-adapter-BKdQHwbi.mjs.map} +1 -1
  82. package/dist/{host-adapter-0F8EpbD6.js → host-adapter-bWftXA9T.js} +1 -1
  83. package/dist/{index-CXbOY7gB.d.ts → index-DnFsmr_o.d.ts} +3 -3
  84. package/dist/{index-CXbOY7gB.d.ts.map → index-DnFsmr_o.d.ts.map} +1 -1
  85. package/dist/{index-B3cHxr3O.d.mts → index-rvw5Bz-r.d.mts} +3 -3
  86. package/dist/{index-B3cHxr3O.d.mts.map → index-rvw5Bz-r.d.mts.map} +1 -1
  87. package/dist/index.d.mts +94 -449
  88. package/dist/index.d.mts.map +1 -1
  89. package/dist/index.d.ts +94 -449
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +25 -455
  92. package/dist/index.mjs +17 -422
  93. package/dist/index.mjs.map +1 -1
  94. package/dist/{kya-http-error-codes-UYb1zpGM.js → kya-http-error-codes-B4rUmUEI.js} +2 -0
  95. package/dist/{kya-http-error-codes-7ewV5RuK.d.ts → kya-http-error-codes-C14E4gi3.d.mts} +2 -1
  96. package/dist/kya-http-error-codes-C14E4gi3.d.mts.map +1 -0
  97. package/dist/{kya-http-error-codes-7ewV5RuK.d.mts → kya-http-error-codes-C14E4gi3.d.ts} +2 -1
  98. package/dist/kya-http-error-codes-C14E4gi3.d.ts.map +1 -0
  99. package/dist/{kya-http-error-codes-C2JiWPsi.mjs → kya-http-error-codes-DSBrxNry.mjs} +3 -1
  100. package/dist/kya-http-error-codes-DSBrxNry.mjs.map +1 -0
  101. package/dist/kya-http.d.mts +1 -1
  102. package/dist/kya-http.d.ts +1 -1
  103. package/dist/kya-http.js +1 -1
  104. package/dist/kya-http.mjs +1 -1
  105. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  106. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  107. package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
  108. package/dist/{patterns-B2r7M9wR.js → patterns-CiMpbdAF.js} +1 -1
  109. package/dist/{patterns-B7dQoeE3.mjs → patterns-D4OAsNQY.mjs} +2 -2
  110. package/dist/{patterns-B7dQoeE3.mjs.map → patterns-D4OAsNQY.mjs.map} +1 -1
  111. package/dist/patterns.js +1 -1
  112. package/dist/patterns.mjs +1 -1
  113. package/dist/policy/fetcher.d.mts +1 -1
  114. package/dist/policy/fetcher.d.ts +1 -1
  115. package/dist/policy/schemas.d.mts +1 -1
  116. package/dist/policy/schemas.d.ts +1 -1
  117. package/dist/{schemas-C_3C72SR.d.ts → schemas-CGKHzcMV.d.ts} +21 -21
  118. package/dist/{schemas-C_3C72SR.d.ts.map → schemas-CGKHzcMV.d.ts.map} +1 -1
  119. package/dist/{schemas-02CI7jgm.d.mts → schemas-m-GqyfyO.d.mts} +21 -21
  120. package/dist/{schemas-02CI7jgm.d.mts.map → schemas-m-GqyfyO.d.mts.map} +1 -1
  121. package/dist/tool-protection/index.d.mts +12 -0
  122. package/dist/tool-protection/index.d.mts.map +1 -1
  123. package/dist/tool-protection/index.d.ts +12 -0
  124. package/dist/tool-protection/index.d.ts.map +1 -1
  125. package/dist/tool-protection/index.js +46 -0
  126. package/dist/tool-protection/index.mjs +44 -1
  127. package/dist/tool-protection/index.mjs.map +1 -1
  128. package/fixtures/kya-http/error-codes.json +2 -1
  129. package/package.json +19 -3
  130. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +0 -1
  131. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +0 -1
  132. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["core._coercedNumber","schemas.ZodNumber","core._coercedBoolean","schemas.ZodBoolean","core._coercedDate","schemas.ZodDate","z.enum","z.number","z\n .object","z.string","z.literal","z\n .number","z\n .enum","z\n .enum","z.discriminatedUnion","z.object","z.literal","z.string","z.enum","z\n .enum","z.record","z.unknown","z.date","z\n .enum","z\n .number","z\n .string","z\n .record","z.number","z.array","z.boolean","z\n .object","z\n // Dual-accept (mcp-i → kya-os): accept the canonical engine value\n // `kyaos_handshake` alongside the legacy `mcp_i_handshake` so engine output\n // still validates once upstream flips its emitter.\n .enum","z.union","z.instanceof","z.enum","z.object","z.string","z.boolean","z.array","z.record","z.number","z\n .enum","z.enum","z.object","z.number","z.array","z.string","z.object","z.string","z.number","z.enum","z.object","z.string","z.array","z.number","z.object","z.number","z.enum","z.string","z\n .object","z.array","z.boolean","z.object","z.string","z.record","z\n .object","z.enum","z.boolean","z.number","z.array","z\n .array","z.object","z.boolean","z.any","z\n .object","z.string","z.number","z.array","z.enum","z\n .record","z.object","z.boolean","z.string","z.number","z\n .object","z.array","z.literal","z\n .object","z\n .record","z.unknown","z.record","z.enum","z.date","z.union","z.ipv4","z.ipv6","z.object","z.string","z.enum","z.record","z.number","z.unknown","z.boolean","z\n .object","z.array","z\n .object","Timestamp","z.string","Uuid","z.literal","z\n .string","z\n .object","z.number","z.enum","z.boolean","z.array","Id","z.string","z\n .object","z.literal","z.union","z.number","z.unknown","z\n .object","z\n .array","z\n .object","z.enum","z.object","z.discriminatedUnion","z\n .string","z\n .string","z.enum","z\n .object","z.string","z.literal","z.number","z.boolean","z.array","z\n .array","z.union","z.string","KeyDid","z\n .string","z.enum","z\n .object","z.literal","z\n .array","z.number","z\n .object","z\n .string","z\n .array","z.array","z.boolean","z.object","z.discriminatedUnion","z\n .object","Sha256Digest","z\n .object","z\n .array","z\n .object","Text","z\n .string","PublicUrl","z.object","z.string","z\n .object","z.enum","z.literal","z\n .object","z\n .array","z\n .array","z.string","z.enum","z.object","z.boolean","z.number","z.unknown","z\n .object","z.string","z.array","z.discriminatedUnion","z.literal","z.enum","z.object","z.string","z.date","z.boolean","z.number","z.array","z.record","z.unknown","z.string","z.enum","z\n .enum","z\n .string","z.object","z.number","z.literal","z\n .object","z.array","z.boolean","z.record","z.union","z\n .object","z\n .string","z.discriminatedUnion","z\n .string","z\n .object","z\n .string","z\n .record","z.unknown","z\n .string","z.enum","z\n .object","z.boolean","z.string","z.array","z.object","z.number","z\n .object","z\n .string","z\n .array","z.string","z.NEVER","z\n .array","z.string","z.NEVER","z.string","z.object","z.coerce.number","z.coerce\n .number","z.enum","z.array","z\n .object","z.boolean","z.number","z\n .string","z.discriminatedUnion","z.literal","z.record","z.unknown","AnalyticsQuerySchema","z\n .enum","z.coerce.boolean","z\n .array","z.object","z\n .array","z\n .boolean","z.object","z.boolean","z.array","z.string","z.number","z\n .object","z.record","z.unknown","z.object","z.string","z.literal","z.boolean","z.number","z.enum","z\n .string","z\n .number","z.array","z\n .object","z.object","z.string","z.number","z.enum","z.object","z.number","z.string","z.any","z.literal","DidStringSchema","z\n .string","z.enum","z\n .object","z.boolean","z.string","z.number","z.array","z\n .array","z\n .object","z.object","z.literal","z.discriminatedUnion","z\n .object","z.enum","z.object","z.string","z.number","z\n .object","z.literal","z.array","z.boolean","z\n .array","z.record","z.object","z.enum","z.string","z\n .object","z.boolean","z.array","z.number","z.object","z\n .object","z.string","z.enum","z.array","z.record","z.boolean","z.number","z.enum","z.object","z.string","z.date","z.record","z\n .object","z\n .object","z.boolean","z.number","z.array","z.any","z\n .array","z\n .object","z\n .partialRecord","z\n .array","z.enum","z.object","z.string","z.boolean","z.number","z.array","z.date","z.record","z.unknown","z.object","z.literal","z.boolean","z.string","z.enum","z.array","z.coerce.number","z.object","z.enum","z\n .string","z.coerce\n .number","z.string","z\n .string","z.object","z.string","z\n .object","z.object","z.enum","z.string","z\n .object","z.boolean","z.array","z.number","z.coerce.number","z.enum","z.strictObject","z.string","z.boolean","z.array","z.number","z\n .object","z.string","z.record","z.unknown","z.enum","z.number","z.array","z\n .string","z.object","z.string","z.enum","z.array","z.record","z.boolean","z.number","z\n .array","z\n .string","z\n .object","z\n .object","z\n .number","z\n .record","z.coerce.date","z.object","z.enum","z.string","z.coerce.number","z.coerce.boolean","z.number","z.literal","z.array","z.object","z.array","z.string","z.number","z.enum","z.record","z.any","z.boolean","z.union","z\n .object","z\n .array","z.ZodError","z.ZodError","z\n .object","z.string","z.record","z.literal","z\n .object","z\n .object","z.number","z.discriminatedUnion","z\n .string","z.string","z\n .object","z.enum","z.array","z.number","ED25519_PUBKEY_LENGTH","ED25519_MULTIKEY_LENGTH","z\n .string","z.NEVER","z\n .object","z.string","z.array","Id","z\n .string","Count","z.number","Revision","RecordDigest","AcceptanceId","z.enum","z.discriminatedUnion","z.object","z.literal","z\n .object","z\n .object","z.string","z\n .string","z.array","z\n .discriminatedUnion","z\n .object","z\n .array","z\n .string","z.number","z.string","z.array","z\n .object","z.enum","z.boolean","z.literal","z\n .array","z\n .object","z.object","z.discriminatedUnion","z\n .string","z\n .object","z.enum","z\n .object","z.string","z.boolean","z\n .string","z.literal","z.enum","z\n .string","z\n .string","Timestamp","z.string","z.array","z.NEVER","z\n .object","z.literal","z.number","z.discriminatedUnion","z\n .object","z\n .array","z.object","z\n .string","z\n .object","z.union","z\n .object","z\n .array","z.boolean","z.enum","z\n .object","z.array","z.literal","KeyDid","z.string","z\n .string","z\n .array","z.number","z\n .object","z.object","z\n .object","z.boolean","Timestamp","z.string","z\n .string","z\n .object","z.enum","z.literal","z\n .object","z.boolean","z\n .object","z.number","z\n .array","z\n .object","z.discriminatedUnion","z.object","z.record","z.array","z.string","z.enum","z\n .object","z.number","z.array","z\n .array","z.literal","z.boolean","z\n .object","z.enum","z\n .object","z.boolean","z.array","z.object","z.string","z.string","z\n .object","z.literal","z.enum","z.discriminatedUnion","z\n .object","z.null"],"sources":["../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/compat.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/coerce.js","../src/core/network-assertions.ts","../src/core/risk-score.ts","../src/core/detection-reason-code-schema.ts","../src/core/detection.ts","../src/core/agent.ts","../src/core/confidence.ts","../src/core/verdict-evidence.ts","../src/constants/agents.ts","../src/constants/bots.ts","../src/constants/delegation.ts","../src/constants/errors.ts","../src/constants/limits.ts","../src/constants/rules.ts","../src/events/behavioral.ts","../src/api/request.ts","../src/api/response.ts","../src/types/pixel.ts","../src/utils/zod-helpers.ts","../src/api/event.ts","../src/api/readable-text.ts","../src/api/model-credentials.ts","../src/api/task-a2a.ts","../src/api/task-status-projection.ts","../src/api/task-ingress.ts","../src/api/cli-identity.ts","../src/utils/allowed-domains.ts","../src/api/bulk.ts","../src/constants/ai-traffic-taxonomy.ts","../src/types/entities.ts","../src/schemas/provider-registry.ts","../src/schemas/bouncer.ts","../src/types/organization.ts","../src/mcpi/authorization-host.ts","../src/types/posture-origins-schema.ts","../src/types/posture-report-paths-schema.ts","../src/api/internal.ts","../src/api/signal-exposure.ts","../src/api/fingerprint.ts","../src/types/shopify.ts","../src/events/agent-shield.ts","../src/events/realtime.ts","../src/deploy/index.ts","../src/events/deploy-progress.ts","../src/types/analytics.ts","../src/types/detection-metadata.ts","../src/types/auth.ts","../src/types/fingerprint.ts","../src/types/signing-vendors.generated.ts","../src/types/agent-classification.ts","../src/types/admin.ts","../src/types/admin-overview.ts","../src/utils/agent-runtime-label.ts","../src/utils/correlation-id.ts","../src/schemas/auth.ts","../src/schemas/admin.ts","../src/schemas/consent-policy-endpoint.ts","../src/wire/gateway-internal-tools.ts","../src/schemas/gateway.ts","../src/schemas/index.ts","../src/schemas/analytics.ts","../src/schemas/rules.ts","../src/rules/rule-validator.ts","../src/data/compiled/merged-rules.json","../src/rules/rule-loader.ts","../src/rules/rule-parser.ts","../src/rules/vendor-range-freshness.ts","../src/policy/policy-lint.ts","../src/policy/index.ts","../src/wire/vault.ts","../src/mcpi/org-did.ts","../src/mcpi/user-did.ts","../src/mcpi/principal.ts","../src/mcpi/reported-identity.ts","../src/mcpi/did-key.ts","../src/mcpi/multibase-ed25519.ts","../src/mcpi/delegation-verdict.ts","../src/parsers/jafar.ts","../src/api/artifact-bindings.ts","../src/api/graph-interfaces.ts","../src/api/linear-installation.ts","../src/api/management-session.ts","../src/api/task-grant.ts","../src/api/identity-provisioning.ts","../src/api/delegation-management.ts","../src/api/tracking-readiness.ts","../src/api/cli-registration.ts","../src/index.ts"],"sourcesContent":["// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import { z } from 'zod';\n\nexport const ProxyCollectionStateSchema = z.enum([\n 'current',\n 'unavailable',\n 'stale',\n 'unsupported',\n 'conflicting',\n 'insufficient_support',\n]);\nexport type ProxyCollectionState = z.infer<typeof ProxyCollectionStateSchema>;\n\nconst epochSeconds = z.number().int().min(0).max(253402300799);\nconst percentage = z.number().int().min(0).max(100);\n\n/** Source assertions describe request egress membership, never a visitor identity or fraud verdict. */\nexport const ProxyAssertionSchema = z\n .object({\n // Preserve future kinds; compatibility mapping reports unsupported instead of guessing.\n kind: z.string().min(1),\n source: z.string().min(1),\n subjectScope: z.literal('request_egress'),\n membership: z.enum(['present', 'absent', 'unknown']),\n evidenceGrade: z.enum(['confirmed', 'vendor_reported']),\n collectionState: ProxyCollectionStateSchema,\n /** Unix seconds supplied by the source. Reader fetch time is not source observation time. */\n observedAt: epochSeconds.nullable(),\n expiresAt: epochSeconds.nullable(),\n membershipConfidence: percentage.nullable(),\n sourceReliability: percentage.nullable(),\n fraudProbability: z.number().min(0).max(1).nullable(),\n proxyClass: z.enum(['datacenter', 'unknown']).optional(),\n })\n .strict();\nexport type ProxyAssertion = z.infer<typeof ProxyAssertionSchema>;\n\nconst knownKinds = new Set([\n 'tor_exit',\n 'published_vpn_exit',\n 'observed_proxy',\n 'suspected_residential_proxy',\n 'privacy_relay',\n 'local_tunnel',\n 'hosting',\n]);\n\n/**\n * The default admits only confirmed, current assertions. maxmind_legacy preserves\n * existing vendor positives without claiming that its undated optional file is fresh.\n * Uncertain evidence never produces a confirmed-clean false Boolean.\n */\nexport function mapProxyAssertions(\n proxyAssertions: readonly ProxyAssertion[],\n nowSeconds: number,\n collectionState: ProxyCollectionState,\n compatibility: 'confirmed_current' | 'maxmind_legacy' = 'confirmed_current'\n) {\n const states: ProxyCollectionState[] = [collectionState];\n const eligible: ProxyAssertion[] = [];\n for (const assertion of proxyAssertions) {\n if (!knownKinds.has(assertion.kind)) {\n states.push('unsupported');\n continue;\n }\n states.push(assertion.collectionState);\n const explicitUnknown =\n assertion.collectionState !== 'current' &&\n assertion.collectionState !== 'insufficient_support';\n if (explicitUnknown) {\n states.push(assertion.collectionState);\n continue;\n }\n const dated = assertion.observedAt !== null && assertion.expiresAt !== null;\n const current =\n dated && assertion.observedAt! <= nowSeconds && assertion.expiresAt! > nowSeconds;\n if (dated && !current) {\n states.push('stale');\n continue;\n }\n const confirmed =\n assertion.evidenceGrade === 'confirmed' && assertion.collectionState === 'current' && current;\n const legacy =\n compatibility === 'maxmind_legacy' &&\n assertion.source === 'maxmind-anonymous-ip' &&\n assertion.evidenceGrade === 'vendor_reported' &&\n assertion.collectionState === 'insufficient_support' &&\n assertion.observedAt === null &&\n assertion.expiresAt === null;\n if (confirmed || legacy) eligible.push(assertion);\n else states.push('insufficient_support');\n }\n\n for (const assertion of eligible) {\n if (\n assertion.membership === 'present' &&\n eligible.some((other) => other.kind === assertion.kind && other.membership === 'absent')\n ) {\n states.push('conflicting');\n }\n }\n\n if (proxyAssertions.length === 0) states.push('insufficient_support');\n const proxyCollectionState = (\n [\n 'conflicting',\n 'unsupported',\n 'unavailable',\n 'stale',\n 'insufficient_support',\n 'current',\n ] as const\n ).find((state) => states.includes(state))!;\n const blocked =\n proxyCollectionState !== 'current' && proxyCollectionState !== 'insufficient_support';\n const positive = eligible.filter((assertion) => assertion.membership === 'present');\n const preferred = [\n positive.find((assertion) => assertion.kind === 'tor_exit'),\n positive.find((assertion) => assertion.kind === 'published_vpn_exit'),\n positive.find((assertion) => assertion.kind === 'suspected_residential_proxy'),\n positive.find(\n (assertion) => assertion.kind === 'observed_proxy' && assertion.proxyClass === 'datacenter'\n ),\n positive.find((assertion) => assertion.kind === 'observed_proxy'),\n ].find(Boolean);\n const types = {\n tor_exit: 'tor',\n published_vpn_exit: 'vpn',\n suspected_residential_proxy: 'residential_proxy',\n observed_proxy: preferred?.proxyClass === 'datacenter' ? 'datacenter' : 'unknown',\n } as const;\n const proxy =\n !blocked && preferred\n ? {\n isProxy: true,\n proxyType: types[preferred.kind as keyof typeof types],\n // Preserve the historical compatibility score without inventing source confidence.\n confidence:\n preferred.membershipConfidence ??\n (preferred.evidenceGrade === 'vendor_reported' ? 90 : 0),\n }\n : undefined;\n return { proxy, proxyAssertions, proxyCollectionState };\n}\n","/**\n * `riskScore` (P58/PR-A): the Noisy-Or probability that a request is\n * automated, on the wire, in the DB, and across every SDK.\n *\n * Defined once here so every consumer (pixel/enforce/detect responses, the\n * `detections.risk_score` column, the TS/.NET/Java SDK result projections,\n * the delta report) rescales the SAME source value the SAME way. Distinct\n * from `confidence`: `riskScore` is purely additive and NEVER derived from\n * or fed back into it.\n *\n * `shadow_noisy_or_confidence` is the engine's raw, UNCALIBRATED Noisy-Or\n * combiner score, on a 0-100 scale, stamped onto `detectionDetail.metadata`\n * only under `NoisyOrShadowMode.Shadow`/`Live`\n * (`rust/crates/kya-os-engine/src/api.rs::stamp_scoring_metadata`). Distinct\n * from `shadow_calibrated_confidence`, which the engine also stamps once a\n * curve is configured — `riskScoreFromMetadata` never reads that key\n * (bestbrian, PR #4999: earlier revisions of this comment called\n * `riskScore` \"calibrated\", which was wrong — see `riskScoreSourceFromMetadata`\n * below, which makes that choice an observable wire field instead of a\n * comment). Once a curve is published in production, `PR B` is where the\n * platform reconsiders which metadata key `riskScore` reads from for the\n * live-cutover semantics — this module does not change without a matching\n * decision recorded there.\n */\nimport { z } from 'zod';\n\n/** Wire shape: 0-1, two decimals, `null` when the combiner did not run. */\nexport const RiskScoreSchema = z\n .number()\n .min(0)\n .max(1)\n .nullable()\n .describe(\n 'The Noisy-Or probability that the request is automated (0-1, two decimals), uncalibrated (see riskScoreSource). Null when the combiner did not run (NoisyOrShadowMode.Off, an engine fault, or skipDetection).'\n );\nexport type RiskScore = z.infer<typeof RiskScoreSchema>;\n\n/**\n * Which metadata key `riskScore` was derived from. Always `'uncalibrated'`\n * today: `riskScoreFromMetadata` reads only `shadow_noisy_or_confidence`,\n * the combiner's raw score, never `shadow_calibrated_confidence` — even\n * when a calibration curve is configured and the engine has stamped a\n * calibrated preview alongside it. `riskScore` moving to read the\n * calibrated key is a decision this module's own doc comment says a later\n * PR makes explicitly (bestbrian, PR #4999); this field exists so that\n * switch is an observable wire change the day it happens, not a silent one.\n */\nexport const RiskScoreSourceSchema = z\n .enum(['uncalibrated', 'calibrated'])\n .nullable()\n .describe(\n \"Which metadata key riskScore was derived from: 'uncalibrated' (shadow_noisy_or_confidence, the combiner's raw score — always true today) or 'calibrated' (shadow_calibrated_confidence, not yet wired). Null exactly when riskScore is null.\"\n );\nexport type RiskScoreSource = z.infer<typeof RiskScoreSourceSchema>;\n\n/** The `detectionDetail.metadata` key `riskScore` derives from. */\nexport const SHADOW_NOISY_OR_CONFIDENCE_KEY = 'shadow_noisy_or_confidence';\n\n/**\n * Derives `riskScore` from a raw detection-metadata bag (the engine's\n * `detectionDetail.metadata`, or an ingest route's forwarded copy of the\n * `shadow_*`-filtered subset — both carry `shadow_noisy_or_confidence`\n * under the same key when the combiner ran). Returns `null` — never\n * `0` — when the key is absent, non-numeric, or the input isn't an object:\n * an actual `0` score is a real (if rare) combiner output and must stay\n * distinguishable from \"the combiner did not run\".\n *\n * Clamps to [0, 100] before rounding — a value outside that range (a bad\n * combiner input, a future engine bug) would otherwise overflow the wire\n * schema's [0, 1] domain and the DB column's `numeric(3, 2)` domain\n * (±9.99); Postgres raises 22003 on the latter, and since\n * `persistDetections` batches rows into one multi-row INSERT, a single\n * bad value fails every detection in that batch (bestbrian, PR #4999).\n *\n * Rounds the raw 0-100 value to the nearest whole number before dividing by\n * 100 — equivalent to rounding the final 0-1 value to two decimal places,\n * kept in this exact form so the same formula reads identically next to\n * the .NET (`Math.Round(raw) / 100.0`) and Java (`Math.round(raw) / 100.0`)\n * projections, which must stay in lockstep with this one (both clamp the\n * same way).\n */\nexport function riskScoreFromMetadata(metadata: unknown): number | null {\n if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)) {\n return null;\n }\n const raw = (metadata as Record<string, unknown>)[SHADOW_NOISY_OR_CONFIDENCE_KEY];\n if (typeof raw !== 'number' || !Number.isFinite(raw)) return null;\n const clamped = Math.min(100, Math.max(0, raw));\n return Math.round(clamped) / 100;\n}\n\n/**\n * Companion to `riskScoreFromMetadata`: `null` exactly when `riskScore`\n * is `null` (the combiner did not run), `'uncalibrated'` otherwise — see\n * `RiskScoreSourceSchema`'s doc comment for why this is the only value\n * this function can return today.\n */\nexport function riskScoreSourceFromMetadata(metadata: unknown): RiskScoreSource {\n return riskScoreFromMetadata(metadata) === null ? null : 'uncalibrated';\n}\n\n/**\n * `riskScoreFromMetadata`, stringified for a Drizzle `numeric(3, 2)` insert\n * column — Drizzle types Postgres `numeric` as `string` (never `number`) to\n * avoid float precision loss, so every `detections.riskScore` insert site\n * needs this rather than the bare wire/`number` value above.\n */\nexport function riskScoreColumnValue(metadata: unknown): string | null {\n const score = riskScoreFromMetadata(metadata);\n return score === null ? null : score.toFixed(2);\n}\n","/**\n * The Zod schema for one `detection/*` reason code. Kept apart from the\n * registry (`./detection-reason-codes.ts`), which loads no Zod, so the\n * registry and its mapping (`./detection-reason-mapping.ts`) can be loaded on\n * the request path from the `./reason-codes` lean entry.\n */\nimport { z } from 'zod';\n\nimport { DETECTION_REASON_CODES, type DetectionReasonCode } from './detection-reason-codes';\n\n/** The registry's value tuple, for z.enum. */\nconst REASON_CODE_VALUES = Object.values(DETECTION_REASON_CODES) as [\n DetectionReasonCode,\n ...DetectionReasonCode[],\n];\n\n/** A single `detection/*` code from the DETECTION_REASON_CODES registry. */\nexport const DetectionReasonCodeSchema = z\n .enum(REASON_CODE_VALUES)\n .describe(\n 'A machine-readable detection/* reason code from the DETECTION_REASON_CODES registry (see docs/architecture/detection-reason-codes.generated.md).'\n );\n","/**\n * Core detection types for Checkpoint\n *\n * BREAKING CHANGE v1.40.0: Confidence scores now use 0-100 scale\n * ─────────────────────────────────────────────────────────────\n * Previously: confidence values were 0-1 decimal (e.g., 0.85)\n * Now: confidence values are 0-100 percentage (e.g., 85)\n *\n * Migration guide:\n * - Test fixtures: expectedConfidence: 0.5 → expectedConfidence: 50\n * - API responses: { confidence: 0.85 } → { confidence: 85 }\n * - Threshold configs: confidenceThreshold: 0.7 → confidenceThreshold: 70\n * - Display: Math.round(confidence * 100) → Math.round(confidence)\n */\n\nimport { z } from 'zod';\nimport { ProxyAssertionSchema, ProxyCollectionStateSchema } from './network-assertions';\nexport * from './network-assertions';\n\nimport { RiskScoreSchema, RiskScoreSourceSchema } from './risk-score';\nimport { DetectionReasonCodeSchema } from './detection-reason-code-schema';\n\n/**\n * Detection class enum for clear hierarchy (updated in migration 0029)\n * - Human: Regular human user\n * - AiAgent: AI assistants (ChatGPT, Claude, etc.) - PRIMARY VALUE\n * - Bot: Bots, scrapers, crawlers (includes former 'automation' category)\n * - IncompleteData: Cannot determine due to insufficient data (replaces 'unknown')\n *\n * Legacy types (maintained for backwards compatibility):\n * - Automation: Deprecated - migrated to Bot in migration 0029\n * - Unknown: Deprecated - migrated to IncompleteData in migration 0029\n */\nexport const DetectionClassSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('Human'),\n }),\n z.object({\n type: z.literal('AiAgent'),\n agentType: z.string().optional(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n }),\n z.object({\n type: z.literal('Automation'),\n toolType: z.enum(['Puppeteer', 'Selenium', 'Playwright', 'Custom']).optional(),\n purpose: z.enum(['Testing', 'Scraping', 'Monitoring', 'Analytics', 'Other']).optional(),\n }),\n z.object({\n type: z.literal('Bot'),\n // The engine sets Scraper, SearchEngine, HeadlessBrowser, Tool and\n // HighVelocity; the others are kept for older data.\n // __tests__/core/engine-detection-detail.test.ts pins the engine's values.\n botType: z\n .enum([\n 'SearchEngine',\n 'SocialMedia',\n 'Monitoring',\n 'Scraper',\n 'Security',\n 'Analytics',\n 'HeadlessBrowser',\n 'Tool',\n 'HighVelocity',\n ])\n .optional(),\n legitimacy: z.enum(['Legitimate', 'Suspicious', 'Malicious']).optional(),\n }),\n z.object({\n type: z.literal('IncompleteData'),\n }),\n z.object({\n type: z.literal('Unknown'),\n }),\n]);\nexport type DetectionClass = z.infer<typeof DetectionClassSchema>;\n\n/**\n * Input data for agent detection\n */\nexport const DetectionInputSchema = z.object({\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n ipAddress: z.string().optional(), // Alias for ip\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n body: z.unknown().optional(),\n timestamp: z.date().default(() => new Date()),\n});\nexport type DetectionInput = z.infer<typeof DetectionInputSchema>;\n\n/**\n * Request context for analysis\n */\nexport const RequestContextSchema = z.object({\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n body: z.unknown().optional(),\n timestamp: z.date().default(() => new Date()),\n});\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n\n/**\n * Detection signal from various analysis methods\n * Note: All confidence scores use 0-100 scale for consistency\n *\n * The per-field `.describe()` strings below are the SSOT for the generated\n * signal-exposure reference (`scripts/generate-signal-exposure-docs.ts`,\n * KYA-1107): the generator throws on any undescribed field, and CI fails\n * on a stale generated page, so schema and docs cannot drift.\n */\nexport const DetectionSignalSchema = z.object({\n signalType: z\n .enum(['signature', 'pattern', 'behavioral', 'network', 'fingerprint'])\n .describe(\n 'Evidence plane this signal was observed on: cryptographic signature, User-Agent/header pattern, behavioral interaction, network/IP, or transport fingerprint.'\n ),\n confidence: z\n .number()\n .min(0)\n .max(100)\n .describe(\"This signal's own confidence contribution on the 0-100 scale.\"),\n weight: z\n .number()\n .min(0)\n .max(1)\n .describe(\"This signal's relative weight (0-1) in the combined verdict.\"),\n source: z\n .string()\n .describe(\n \"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.\"\n ),\n explanation: z\n .string()\n .describe('Human-readable explanation of what this signal observed. Prose, not a contract.'),\n metadata: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Optional source-specific structured details (e.g. the matched pattern, the vendor feed name).'\n ),\n});\nexport type DetectionSignal = z.infer<typeof DetectionSignalSchema>;\n\n/**\n * Reasoning step for transparent confidence calculation\n * Note: All confidence scores use 0-100 scale for consistency\n */\nexport const ReasoningStepSchema = z.object({\n signalType: z.string(),\n rawConfidence: z.number().min(0).max(100),\n weight: z.number().min(0).max(1),\n reliability: z.number().min(0).max(1),\n contribution: z.number(),\n explanation: z.string(),\n});\nexport type ReasoningStep = z.infer<typeof ReasoningStepSchema>;\n\n/**\n * Per-stage trace step emitted by the engine on every `verify()` call.\n * Wire keys are camelCase — mirrors `#[serde(rename_all = \"camelCase\")]`\n * on the Rust side (`rust/crates/kya-os-engine/src/types.rs`).\n */\nexport const TraceStepSchema = z.object({\n /**\n * Stable stage identifier. Canonical names: `\"detection\"` (PlainHttp) or\n * `\"identity\"` | `\"signature\"` | `\"revocation\"` | `\"expiration\"` |\n * `\"scope\"` | `\"reputation\"` | `\"policy\"` (MCP-I's 7-stage pipeline).\n * Not a union on the wire — new step names are non-breaking. Mirrors\n * `TraceStep::name` on the Rust side.\n */\n name: z.string(),\n /**\n * Per-step verdict. `\"pass\"` = step ran and succeeded, `\"fail\"` = step\n * ran and rejected, `\"skip\"` = step was skipped (e.g. no identity\n * material on PlainHttp). Mirrors `TraceVerdict` on the Rust side,\n * which serializes lowercase.\n */\n verdict: z.enum(['pass', 'fail', 'skip']),\n /**\n * Stage execution time in microseconds. Mirrors `latency_micros` on the\n * Rust side which carries the `#[serde(rename = \"latencyMicros\")]` wire\n * key.\n */\n latencyMicros: z.number(),\n /**\n * Optional human-readable reason. Always present when verdict is\n * `\"fail\"`.\n */\n reason: z.string().optional(),\n});\nexport type TraceStep = z.infer<typeof TraceStepSchema>;\n\n/**\n * Detailed reasoning for detection decisions\n * Note: All confidence scores use 0-100 scale for consistency\n */\nexport const DetectionReasoningSchema = z.object({\n primaryFactors: z.array(z.string()),\n supportingEvidence: z.array(z.string()),\n confidenceBreakdown: z.record(\n z.string(),\n z.object({\n confidence: z.number().min(0).max(100),\n weight: z.number().min(0).max(1),\n contribution: z.number(),\n })\n ),\n reasoningSteps: z.array(ReasoningStepSchema),\n explanation: z.string(),\n calculationMethod: z.string().default('weighted_aggregation'),\n});\nexport type DetectionReasoning = z.infer<typeof DetectionReasoningSchema>;\n\n/**\n * Engine self-identification — Phase 0.1 of the Checkpoint refactor.\n *\n * Stamped on every DetectionResult so the dashboard can attribute a\n * detection to the specific implementation + ruleset that produced\n * it. Distinguishes package drift (two surfaces on different SDK\n * versions) from implementation divergence (two engines disagreeing\n * on the same rules). Optional for backwards compatibility with\n * SDKs that predate Phase 0.1.\n *\n * Known engine `name` values (kept here so downstream code can rely\n * on string equality without a separate enum import — engine names\n * are forward-compatible additions, never breaking changes). All\n * names use the `checkpoint-` brand prefix; the npm packages still\n * carry the legacy `agentshield-*` names until they're migrated to\n * `checkpoint-*` shims in Phase 1, but the engine string is the\n * customer-visible attribution and must reflect the brand.\n *\n * - 'checkpoint-engine-wasm' post-refactor Rust→WASM (Phase 2)\n * - 'checkpoint-matcher-js' post-refactor pure JS matcher (Phase 2)\n * - 'checkpoint-remote' result came from a remote enforce call\n * - 'checkpoint-edge-pattern' Next.js edge regex tables (pre-Phase-1)\n * - 'checkpoint-edge-wasm' Next.js edge WASM loader (pre-Phase-1)\n * - 'checkpoint-worker-wasm' Cloudflare worker WASM (pre-Phase-1)\n * - 'checkpoint-core' core agent-detector default (pre-Phase-1)\n */\nexport const EngineInfoSchema = z.object({\n name: z.string(),\n version: z.string(),\n rulesetHash: z.string(),\n rulesetVersion: z.string(),\n buildSha: z.string().optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n});\nexport type EngineInfo = z.infer<typeof EngineInfoSchema>;\n\n/**\n * Coarse network-path classification for a request's `trueIp`. `'unknown'`\n * is the host's own \"no verdict\" value — distinct from the whole\n * {@link NetworkContextSchema} being absent (no lookup attempted at all).\n */\nexport const RoutingTypeSchema = z.enum([\n 'residential',\n 'mobile',\n 'datacenter',\n 'hosting',\n 'unknown',\n]);\nexport type RoutingType = z.infer<typeof RoutingTypeSchema>;\n\n/** Coarse proxy/anonymization category, when `ProxyInfo.isProxy` is true. */\nexport const ProxyTypeSchema = z.enum(['vpn', 'tor', 'datacenter', 'residential_proxy', 'unknown']);\nexport type ProxyType = z.infer<typeof ProxyTypeSchema>;\n\n/**\n * Host-supplied proxy/anonymization verdict for a request's `trueIp`.\n * Mirrors the Rust `ProxyInfo` (`rust/crates/kya-os-engine/src/types.rs`).\n */\nexport const ProxyInfoSchema = z.object({\n isProxy: z.boolean(),\n proxyIp: z.string().optional(),\n proxyType: ProxyTypeSchema,\n lastDetected: z.number().optional(),\n /** Provider confidence in the proxy verdict, 0-100. */\n confidence: z.number().int().min(0).max(100),\n});\nexport type ProxyInfo = z.infer<typeof ProxyInfoSchema>;\n\n/**\n * Host-supplied network / IP-intelligence context for a request's\n * `trueIp`. Legacy fields mirror the Rust `NetworkContext` and appear on\n * the engine's `VerifyResult.network` (a sibling of `DetectionDetail`, like\n * `EngineInfo` above — there is no wrapping `VerifyResultSchema`) when the\n * host supplied one, and exposed to Cedar as `context.ip_routing_type` /\n * `context.is_proxy`. Absent-safe: a request with no network context is\n * the normal case, not an error.\n */\nexport const NetworkContextSchema = z.object({\n trueIp: z.string().optional(),\n asn: z.number().int().nonnegative().optional(),\n isp: z.string().optional(),\n routingType: RoutingTypeSchema,\n proxy: ProxyInfoSchema.optional(),\n /**\n * TypeScript-host evidence, retained in detection rows and extended API read-back.\n * Older Rust readers do not echo these additive fields.\n */\n proxyAssertions: z.array(ProxyAssertionSchema).optional(),\n proxyCollectionState: ProxyCollectionStateSchema.optional(),\n});\nexport type NetworkContext = z.infer<typeof NetworkContextSchema>;\n\n/**\n * Descriptive detection detail from the engine.\n *\n * This is the signal layer: what was detected, why, and with what\n * attribution. Enforcement decisions live separately on `Decision`.\n * Enhanced with detailed reasoning, signals, and risk assessment\n */\nexport const DetectionDetailSchema = z.object({\n // Core fields\n /**\n * @deprecated Use detectionClass instead. Will be removed in v2.0.0\n * Migration guide:\n * - isAgent: false → detectionClass: { type: 'Human' }\n * - isAgent: true → check detectionClass for specific type\n */\n isAgent: z.boolean().describe('DEPRECATED: Use detectionClass instead'),\n isBot: z.boolean().optional(), // Backwards compatibility\n /** True when detected bot is an AI crawler (GPTBot, ClaudeBot, etc.) */\n isAiCrawler: z.boolean().optional(),\n\n /**\n * Confidence score (0-100 scale)\n * - 0-30: Low confidence\n * - 31-70: Medium confidence\n * - 71-90: High confidence\n * - 91-100: Very high confidence\n */\n confidence: z.number().min(0).max(100),\n\n /**\n * P58/PR-A: the Noisy-Or probability that the request is automated\n * (0-1, two decimals), uncalibrated (see `riskScoreSource` below).\n * `null` when the combiner did not run. See `RiskScoreSchema` /\n * `riskScoreFromMetadata` — always additive, never derived from or fed\n * back into `confidence` above.\n */\n riskScore: RiskScoreSchema.optional(),\n /** Which metadata key `riskScore` was derived from. See `RiskScoreSourceSchema`. */\n riskScoreSource: RiskScoreSourceSchema.optional(),\n\n // NEW: Clear classification hierarchy\n detectionClass: DetectionClassSchema,\n\n // Detection details with enhanced reasoning\n confidenceLevel: z.enum(['low', 'medium', 'high', 'very_high']).optional(),\n reasons: z.array(z.string()),\n detectedPatterns: z.array(z.string()).optional(),\n\n // NEW: Detection signals and reasoning\n signals: z.array(DetectionSignalSchema).default([]),\n reasoning: DetectionReasoningSchema.optional(),\n\n // Agent information\n detectedAgent: z\n .object({\n type: z.string(),\n name: z.string(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n version: z.string().optional(),\n })\n .optional(),\n botType: z.string().optional(), // Backwards compatibility\n agentType: z.string().optional(),\n\n // Verification and enhanced risk assessment\n verificationMethod: z\n // Dual-accept (mcp-i → kya-os): accept the canonical engine value\n // `kyaos_handshake` alongside the legacy `mcp_i_handshake` so engine output\n // still validates once upstream flips its emitter.\n .enum([\n 'signature',\n 'pattern',\n 'behavioral',\n 'network',\n 'mcp_i_handshake',\n 'kyaos_handshake',\n 'kya-http',\n 'kya-http-delegated',\n // Tier-1 RFC 9421 (Web Bot Auth) verification. The engine emits this\n // on a verified HTTP Message Signature (api.rs Tier-1 path); without\n // it here, Zod-validating a Tier-1 verdict rejects a legitimately\n // signature-verified agent.\n 'tier1_rfc9421',\n // A2A Agent Card security scheme (RFC 9421 keyid, or a JWT bearer\n // against resolved JWKS) cryptographically verified — see\n // docs/architecture/a2a-verification.md.\n 'a2a',\n 'none',\n 'error',\n ])\n .optional(),\n riskLevel: z.string().optional(),\n forgeabilityRisk: z.enum(['low', 'medium', 'high']).optional(),\n // draft-kya-http-02 §1 assurance tier the engine established for this\n // verdict (`anonymous` | `attested-bearer` | `key-bound` | `registered` |\n // `delegated`). Stamped by the engine on every verdict; the canonical\n // ladder is `AssuranceTierSchema` in `../policy/schemas`. Kept a loose\n // string here (like `riskLevel`) to avoid a core→policy module dependency.\n assurance: z.string().optional(),\n\n // NEW: Enhanced risk assessment\n riskAssessment: z\n .object({\n level: z.enum(['low', 'medium', 'high', 'critical']),\n score: z.number().min(0).max(100),\n factors: z.array(z.string()),\n forgeabilityRisk: z.enum(['low', 'medium', 'high']),\n recommendations: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n timestamp: z.union([z.date(), z.number()]).default(() => new Date()),\n requestId: z.string().optional(),\n\n /** Engine self-identification — see EngineInfoSchema. Optional for\n * pre-Phase-0.1 SDKs; dashboard treats absence as \"legacy SDK.\" */\n engine: EngineInfoSchema.optional(),\n\n /** Scopes granted by a verified single-hop delegation (the mcp-i path).\n * Surfaced by the engine so a host can FORWARD them into\n * `context.granted_scopes` (authorize()) without re-decoding the delegation\n * credential — the engine already verified them. Omitted/empty for L1\n * envelopes or any unverified/forged path. Mirrors the Rust\n * `DetectionDetail.granted_scopes` (additive, omitted when empty). */\n grantedScopes: z.array(z.string()).optional(),\n\n /**\n * Detection reason codes (#4874): namespaced detection/* codes, most-\n * significant-evidence first, derived via mapDetectionToReasonCodes.\n * Optional: only producers that opt into signal exposure (currently\n * /api/v1/detect via buildDetectionSignalExposure) populate this.\n */\n reasonCodes: z.array(DetectionReasonCodeSchema).optional(),\n});\nexport type DetectionDetail = z.infer<typeof DetectionDetailSchema>;\n\n/**\n * @deprecated Use DetectionDetailSchema. Kept for one minor release so\n * older host packages can migrate without a coordinated breaking cut.\n */\nexport const DetectionResultSchema = DetectionDetailSchema;\n\n/**\n * @deprecated Use DetectionDetail. Kept for one minor release so older\n * host packages can migrate without a coordinated breaking cut.\n */\nexport type DetectionResult = DetectionDetail;\n\n/**\n * Detection mode configuration\n */\nexport const DetectionModeSchema = z.enum(['strict', 'balanced', 'lenient']);\nexport type DetectionMode = z.infer<typeof DetectionModeSchema>;\n\n/**\n * Custom detection rule\n */\nexport const CustomRuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n pattern: z.union([z.string(), z.instanceof(RegExp)]),\n weight: z.number().min(0).max(1),\n type: z.enum(['userAgent', 'header', 'behavior', 'ip']),\n enabled: z.boolean().default(true),\n});\nexport type CustomRule = z.infer<typeof CustomRuleSchema>;\n\n/**\n * Detection options\n */\nexport const DetectionOptionsSchema = z.object({\n mode: DetectionModeSchema.optional(),\n customRules: z.array(CustomRuleSchema).optional(),\n enablePatternMatching: z.boolean().default(true),\n enableBehaviorAnalysis: z.boolean().default(true),\n enableNetworkAnalysis: z.boolean().default(true),\n confidenceThreshold: z.number().min(0).max(100).default(70),\n});\nexport type DetectionOptions = z.infer<typeof DetectionOptionsSchema>;\n\n/**\n * Utility functions for confidence score conversion\n * All internal processing should use 0-100 scale\n */\nexport const ConfidenceUtils = {\n /**\n * Convert 0-1 scale to 0-100 scale\n */\n fromDecimal(score: number): number {\n return Math.round(Math.max(0, Math.min(1, score)) * 100);\n },\n\n /**\n * Convert 0-1000 scale to 0-100 scale\n */\n fromThousand(score: number): number {\n return Math.round(Math.max(0, Math.min(1000, score)) / 10);\n },\n\n /**\n * Convert 0-100 scale to 0-1 scale (for legacy compatibility)\n */\n toDecimal(score: number): number {\n return Math.max(0, Math.min(100, score)) / 100;\n },\n\n /**\n * Convert 0-100 scale to 0-1000 scale (for WASM compatibility)\n */\n toThousand(score: number): number {\n return Math.round(Math.max(0, Math.min(100, score)) * 10);\n },\n\n /**\n * Normalize any confidence score to 0-100 scale\n */\n normalize(score: number): number {\n if (score <= 1) {\n // Assume 0-1 scale\n return this.fromDecimal(score);\n } else if (score <= 100) {\n // Already 0-100 scale\n return Math.round(Math.max(0, Math.min(100, score)));\n } else {\n // Assume 0-1000 scale\n return this.fromThousand(score);\n }\n },\n\n /**\n * Get confidence level from score\n */\n getLevel(score: number): 'low' | 'medium' | 'high' | 'very_high' {\n const normalizedScore = this.normalize(score);\n if (normalizedScore >= 91) return 'very_high';\n if (normalizedScore >= 71) return 'high';\n if (normalizedScore >= 31) return 'medium';\n return 'low';\n },\n\n /**\n * Format score for display as percentage\n */\n toPercentage(score: number): string {\n return `${this.normalize(score)}%`;\n },\n};\n\n/**\n * Known AI crawler name patterns. Used as a fallback when isAiCrawler is not\n * explicitly set (e.g., pattern-detection paths that don't go through WASM).\n */\nconst AI_CRAWLER_NAMES = [\n 'gptbot',\n 'claudebot',\n 'perplexitybot',\n 'deepseekbot',\n 'bytespider',\n 'ccbot',\n 'google-extended',\n 'cohere',\n 'huggingface',\n 'amazon bedrock',\n 'vertex',\n];\n\n/**\n * Check if an agent name matches a known AI crawler.\n * Use this to set isAiCrawler on detection results from pattern-based paths.\n */\nexport function isKnownAiCrawler(agentName: string | undefined | null): boolean {\n if (!agentName) return false;\n const lower = agentName.toLowerCase();\n return AI_CRAWLER_NAMES.some((crawler) => lower.includes(crawler));\n}\n","/**\n * Agent-specific types and schemas\n */\n\nimport { z } from 'zod';\n\n/**\n * Known AI agent types (AI companies only, not traditional bots)\n */\nexport const AgentTypeSchema = z.enum([\n // OpenAI\n 'openai',\n 'chatgpt',\n // Anthropic\n 'claude',\n 'anthropic',\n // Search AI\n 'perplexity',\n 'phind',\n 'you',\n 'neeva',\n // Big Tech AI\n 'google',\n 'microsoft',\n 'meta',\n 'alibaba',\n // AI Model Providers\n 'mistral',\n 'cohere',\n 'huggingface',\n 'inflection',\n 'stability',\n 'replicate',\n 'together',\n '01ai',\n // Content/Writing AI\n 'writer',\n 'jasper',\n // Additional AI vendors — Engine-Pattern-Codegen-Retirement-1 backfilled\n // these after the SSOT migration surfaced legacy patterns_generated.rs\n // entries (xAI Grok, DeepSeek-User/DeepSeekBot, Amazon Q + NovaAct,\n // KYA Agent) that were never represented in TS. Their patterns lived\n // only in the retired YAML→Rust pipeline; without these types the\n // backfilled `KNOWN_AGENT_PATTERNS` entries would have to coerce to\n // `'unknown'` and lose per-vendor classification downstream.\n 'xai',\n 'deepseek',\n 'amazon',\n 'kya',\n // Unknown AI agent\n 'unknown',\n]);\nexport type AgentType = z.infer<typeof AgentTypeSchema>;\n\n/**\n * Agent information\n */\nexport const AgentInfoSchema = z.object({\n type: AgentTypeSchema,\n name: z.string(),\n version: z.string().optional(),\n provider: z.string().optional(),\n verified: z.boolean().default(false),\n});\nexport type AgentInfo = z.infer<typeof AgentInfoSchema>;\n\n/**\n * Agent pattern for matching\n *\n * F-08 PR-C: each pattern entry now carries its own `category` value.\n * Replaces the previous arrangement where agent-types-sync.service.ts\n * hardcoded `'ai_assistant'` for every KNOWN_AGENT_PATTERNS entry,\n * which conflated training crawlers with interactive AI assistants.\n * Targets the 9-value canonical taxonomy locked by F-03 (#2160) — see\n * AgentCategorySchema in `../types/agent-classification`.\n *\n * Optional for backward compatibility with any external callers; the\n * sync service falls back to `'ai_assistant'` if absent (pre-PR-C\n * behaviour). New entries should always declare a category explicitly.\n */\nexport const AgentPatternSchema = z.object({\n id: z.string(),\n type: AgentTypeSchema,\n name: z.string(),\n patterns: z.array(z.string()),\n headers: z.record(z.string(), z.string()).optional(),\n ipRanges: z.array(z.string()).optional(),\n confidence: z.number().min(0).max(1).default(0.8),\n category: z\n .enum([\n 'ai_assistant',\n 'search_engine',\n 'social_media',\n 'monitoring',\n 'scraper',\n 'automation',\n 'security',\n 'analytics',\n 'unknown',\n ])\n .optional(),\n /**\n * Whether this pattern represents a known, declared, well-behaved\n * crawler / agent. Optional — defaults to `true` for known AI\n * providers in KNOWN_AGENT_PATTERNS (Anthropic's ClaudeBot, OpenAI's\n * GPTBot, etc. all respect robots.txt and declare themselves).\n *\n * F-08 PR-C followup (cursor bot review): without this field,\n * `agent-types-sync.service.ts` derives isLegitimate from category\n * via a hardcoded `ai_assistant | search_engine | social_media` set.\n * That set excludes `scraper`, so well-behaved AI training crawlers\n * (which legitimately live in the `scraper` bucket per F-03's\n * locked taxonomy) would silently flip from isLegitimate=true to\n * false on the next sync. Per-entry isLegitimate prevents that.\n */\n isLegitimate: z.boolean().optional(),\n});\nexport type AgentPattern = z.infer<typeof AgentPatternSchema>;\n\n/**\n * Agent classification result\n */\nexport const AgentClassificationSchema = z.object({\n primary: AgentTypeSchema,\n secondary: z.array(AgentTypeSchema).optional(),\n confidence: z.number().min(0).max(1),\n matchedPatterns: z.array(z.string()),\n});\nexport type AgentClassification = z.infer<typeof AgentClassificationSchema>;\n","/**\n * Confidence and risk assessment types\n */\n\nimport { z } from 'zod';\nimport type { SignalMode, SignalPlane, StabilityTier } from '../signals/types';\n\n/**\n * Confidence levels for detection\n */\nexport const ConfidenceLevelSchema = z.enum(['low', 'medium', 'high', 'very_high']);\nexport type ConfidenceLevel = z.infer<typeof ConfidenceLevelSchema>;\n\n/**\n * Forgeability risk levels\n */\nexport const ForgeabilityRiskSchema = z.enum(['low', 'medium', 'high']);\nexport type ForgeabilityRisk = z.infer<typeof ForgeabilityRiskSchema>;\n\n/**\n * Risk assessment result\n */\nexport const RiskAssessmentSchema = z.object({\n level: z.enum(['low', 'medium', 'high', 'critical']),\n score: z.number().min(0).max(1),\n factors: z.array(z.string()),\n forgeabilityRisk: ForgeabilityRiskSchema,\n recommendations: z.array(z.string()).optional(),\n});\nexport type RiskAssessment = z.infer<typeof RiskAssessmentSchema>;\n\n/**\n * Confidence breakdown by detection method\n */\nexport const ConfidenceBreakdownSchema = z.object({\n patternMatching: z.number().min(0).max(1).optional(),\n behaviorAnalysis: z.number().min(0).max(1).optional(),\n networkAnalysis: z.number().min(0).max(1).optional(),\n signatureVerification: z.number().min(0).max(1).optional(),\n overall: z.number().min(0).max(1),\n});\nexport type ConfidenceBreakdown = z.infer<typeof ConfidenceBreakdownSchema>;\n\n/**\n * Confidence threshold configuration\n * Using 0-1 scale for internal consistency\n */\nexport const ConfidenceThresholdSchema = z.object({\n low: z.number().min(0).max(1).default(0.3),\n medium: z.number().min(0).max(1).default(0.6),\n high: z.number().min(0).max(1).default(0.8),\n veryHigh: z.number().min(0).max(1).default(0.95),\n});\nexport type ConfidenceThreshold = z.infer<typeof ConfidenceThresholdSchema>;\n\n/**\n * Helper function to get confidence level from score\n */\nexport function getConfidenceLevel(\n score: number,\n thresholds?: ConfidenceThreshold\n): ConfidenceLevel {\n const t = thresholds || {\n low: 0.3,\n medium: 0.6,\n high: 0.8,\n veryHigh: 0.95,\n };\n\n if (score >= t.veryHigh) return 'very_high';\n if (score >= t.high) return 'high';\n if (score >= t.medium) return 'medium';\n return 'low';\n}\n\n// ============================================================================\n// CONFIDENCE SCALE UTILITIES\n// ============================================================================\n//\n// IMPORTANT: All Checkpoint confidence scores use a 0.0-1.0 scale internally.\n// - WASM detect_agent() returns: 0.95 (not 95)\n// - Pattern definitions use: 0.70, 0.85, 0.95 (not 70, 85, 95)\n// - Thresholds should be: 0.3, 0.7, 0.9 (not 30, 70, 90)\n//\n// Use these utilities to convert for display or validate incoming values.\n// ============================================================================\n\n/**\n * Convert confidence (0.0-1.0) to percentage (0-100) for display\n *\n * @example\n * const result = detect_agent(metadata); // returns 0.95\n * toPercent(result.confidence) // returns 95\n */\nexport function toPercent(confidence: number): number {\n return Math.round(confidence * 100);\n}\n\n/**\n * Format confidence as percentage string\n *\n * @example\n * formatConfidence(0.95) // \"95%\"\n */\nexport function formatConfidence(confidence: number): string {\n return `${toPercent(confidence)}%`;\n}\n\n/**\n * Validate and normalize confidence to 0.0-1.0 scale.\n * If value > 1, assumes it's in 0-100 scale and converts.\n * Logs warning in development when conversion happens.\n *\n * @example\n * normalizeConfidence(0.95) // 0.95 (unchanged)\n * normalizeConfidence(95) // 0.95 (converted, logs warning)\n */\nexport function normalizeConfidence(value: number, context?: string): number {\n if (value > 1.0) {\n if (process.env.NODE_ENV !== 'production') {\n const location = context ? ` in ${context}` : '';\n console.warn(\n `[AgentShield] Confidence value ${value}${location} appears to be 0-100 scale. ` +\n `Expected 0.0-1.0. Auto-converting to ${value / 100}.`\n );\n }\n return Math.min(value / 100, 1.0);\n }\n return Math.max(0, Math.min(value, 1.0));\n}\n\n// ============================================================================\n// ENTROPY-DERIVED CONFIDENCE (P19)\n// ============================================================================\n//\n// This is a different axis from classification PROBABILITY (P17/P18's\n// calibrated \"how likely is this traffic automated\"). Confidence measures\n// how much evidence we collected, not what we concluded from it. A\n// high-confidence human and a high-confidence bot are both possible; a\n// low-confidence read of either can happen too. Never combine the two\n// into one number, and name them distinctly wherever both appear (see\n// P51 for the UI-facing convention, which this ticket does not set).\n//\n// THE FORMULA, RATIFIED\n// ----------------------\n// Every observed signal contributes information in bits: `-log2(u)` once\n// the P21 frequency table populates `u` (the coincidence probability —\n// how often two unrelated visitors would agree on this read), falling\n// back to a tier-based proxy (TIER_INFO_BITS) until then. A signal whose\n// `mode` is 'never' contributes nothing, matching the registry's own\n// contract that such signals never feed identity.\n//\n// Raw evidence bits are not simply summed, because signals sharing a\n// Merkle `group` (near-duplicate reads of the same underlying source,\n// e.g. a canvas signal and its v2 fork) or the same `plane` (broader\n// subsystem, e.g. two different rendering reads sharing GPU/driver\n// characteristics) co-vary — they are not independent evidence, so\n// summing them at face value would overstate what six correlated reads\n// from one plane tell you versus three genuinely independent ones.\n//\n// Instead, contributions are combined with a two-tier discount, geometric\n// by rank within each tier:\n//\n// groupBits(group) = Σ_i bits_i * GROUP_DISCOUNT^i (i-th largest bits in the group, 0-indexed)\n// planeBits(plane) = Σ_j groupBits_j * PLANE_DISCOUNT^j (j-th largest groupBits in the plane)\n// totalBits = Σ_planes planeBits(plane) (full weight — planes are independent by definition)\n//\n// This is deliberately the maximum weighted sum achievable by any\n// pairing of (sorted) values against (sorted) discount weights — by the\n// rearrangement inequality, sorting descending against descending\n// weights is that maximum. That characterization is what makes the\n// result PROVABLY monotonic: `Σ v_(i) w_i` equals `max over permutations\n// π of Σ v_i w_π(i)`, a pointwise max of functions each linear (hence\n// non-decreasing, since every w_i >= 0) in every v_i. A max of\n// non-decreasing functions is non-decreasing, so totalBits can only\n// rise or hold steady as evidence is added at any level — removing or\n// zeroing out a signal (mode 'never' is exactly a zero-bit signal) can\n// only lower it. That is \"falls when a high-entropy signal is absent\"\n// and \"rises with independent planes\" as a mathematical guarantee, not\n// a property that happens to hold on the test fixtures.\n//\n// Bits are then mapped onto a bounded, asymptotic confidence:\n//\n// confidence = FLOOR + (CEILING - FLOOR) * (1 - e^(-totalBits / SCALE_BITS))\n//\n// This is strictly increasing in totalBits, equals FLOOR exactly at\n// zero bits (no evidence still yields a floor, never a bare zero — a\n// bare zero would read as \"we know literally nothing,\" which is never\n// true; even a non-response carries some information), and approaches\n// but never reaches CEILING (< 1.0) for any finite evidence — certainty\n// is not on offer.\n//\n// GROUP_DISCOUNT (0.5) is steeper than PLANE_DISCOUNT (0.75): a fork of\n// the same read (same group) co-varies more tightly than two different\n// subsystems that merely share a broad plane, so it is discounted harder.\n// TIER_INFO_BITS is an illustrative proxy — every registry entry's\n// `measurement` is still provisional (no shipped agreement-rate data),\n// so these are placeholder bit-counts (a \"high\" tier signal is modeled\n// as roughly as informative as picking 1-of-64; \"medium\" 1-of-8; \"low\"\n// 1-of-2) that P21's real `u` values supersede per-signal the moment\n// they land — no code change required, since `u` is checked first.\n// ============================================================================\n\n/** One observed signal's evidence-relevant metadata, as needed to compute\n * entropy-derived confidence. A structural subset of the P8 signal\n * registry's `SignalDefinition` — any `SignalDefinition` already satisfies\n * this shape — kept narrow so confidence computation doesn't couple to\n * registry bookkeeping (versioning, description, review) it doesn't need.\n */\nexport interface EvidenceSignal {\n /** Where this signal's read sits for grouping correlated evidence. */\n plane: SignalPlane;\n /** Finer-grained grouping within a plane; near-duplicate/forked reads share a group. */\n group: string;\n /** Stability tier, used as the information-content proxy until `u` is populated (P21). */\n tier: StabilityTier;\n /** Governs identity contribution: 'never' signals carry zero evidence weight. */\n mode: SignalMode;\n /** Coincidence probability from the frequency table (P21). Null until populated. */\n u: number | null;\n}\n\n/** Confidence returned for zero observed evidence. Strictly positive: even total\n * silence isn't \"we know literally nothing,\" so it never reads as a bare zero. */\nexport const ENTROPY_CONFIDENCE_FLOOR = 0.02;\n\n/** Asymptotic upper bound. Never reached for any finite evidence — certainty\n * is not on offer, per the ticket's \"bounded, and never exactly 1.0\" requirement. */\nexport const ENTROPY_CONFIDENCE_CEILING = 0.98;\n\n/** Bits of accumulated evidence at which confidence has closed roughly\n * two-thirds of the gap between FLOOR and CEILING (1 - e^-1 ≈ 0.63). */\nconst CONFIDENCE_SCALE_BITS = 8;\n\n/** Decay applied to the 2nd, 3rd, ... signal within the SAME group (rank\n * 0-indexed): near-duplicate reads of one underlying source co-vary tightly. */\nconst GROUP_DISCOUNT = 0.5;\n\n/** Decay applied to the 2nd, 3rd, ... group's contribution within the SAME\n * plane: different subsystems in one broad plane co-vary more loosely than\n * same-group reads do, so the penalty is milder than GROUP_DISCOUNT. */\nconst PLANE_DISCOUNT = 0.75;\n\n/** Illustrative information-content proxy (bits) per stability tier, used\n * only until a signal's real coincidence probability `u` is populated. */\nconst TIER_INFO_BITS: Record<StabilityTier, number> = {\n high: 6,\n medium: 3,\n low: 1,\n};\n\n/** Floor on `u` before taking -log2, so a frequency-table entry of exactly\n * (or effectively) zero can't blow the formula up to +Infinity bits. */\nconst MIN_COINCIDENCE_PROBABILITY = 1e-6;\n\nfunction signalInfoBits(signal: EvidenceSignal): number {\n if (signal.mode === 'never') return 0;\n if (signal.u !== null && Number.isFinite(signal.u)) {\n const u = Math.min(Math.max(signal.u, MIN_COINCIDENCE_PROBABILITY), 1);\n return -Math.log2(u);\n }\n // Unknown tier (or a non-finite `u` with no valid tier to fall back to) —\n // e.g. a future registry tier this build doesn't know about yet, or a\n // malformed evidence object from a caller that bypassed the type system\n // — contributes no evidence rather than poisoning the whole sum to NaN.\n return TIER_INFO_BITS[signal.tier] ?? 0;\n}\n\n/** The rearrangement-inequality-maximal weighted sum: descending values\n * paired against descending powers of `discount`. See the module doc for\n * why this specific combination rule is what makes the formula monotonic. */\nfunction sortedGeometricSum(values: number[], discount: number): number {\n return [...values]\n .sort((a, b) => b - a)\n .reduce((sum, value, rank) => sum + value * discount ** rank, 0);\n}\n\n/**\n * Computes confidence (how much evidence we have) from the signals actually\n * observed for a detection event — never from a platform/OS lookup table.\n * See the module doc above for the ratified formula and its properties.\n *\n * This is NOT a probability that traffic is automated; see P17/P18 for\n * that calibrated, separately-computed number.\n */\nexport function computeEntropyConfidence(observed: readonly EvidenceSignal[]): number {\n const bitsByPlaneAndGroup = new Map<SignalPlane, Map<string, number[]>>();\n\n for (const signal of observed) {\n const bits = signalInfoBits(signal);\n if (bits <= 0) continue;\n\n let groups = bitsByPlaneAndGroup.get(signal.plane);\n if (!groups) {\n groups = new Map();\n bitsByPlaneAndGroup.set(signal.plane, groups);\n }\n const bitsInGroup = groups.get(signal.group);\n if (bitsInGroup) {\n bitsInGroup.push(bits);\n } else {\n groups.set(signal.group, [bits]);\n }\n }\n\n let totalBits = 0;\n for (const groups of bitsByPlaneAndGroup.values()) {\n const groupContributions = Array.from(groups.values(), (bitsInGroup) =>\n sortedGeometricSum(bitsInGroup, GROUP_DISCOUNT)\n );\n // Full weight across planes: planes are independent by definition.\n totalBits += sortedGeometricSum(groupContributions, PLANE_DISCOUNT);\n }\n\n return (\n ENTROPY_CONFIDENCE_FLOOR +\n (ENTROPY_CONFIDENCE_CEILING - ENTROPY_CONFIDENCE_FLOOR) *\n (1 - Math.exp(-totalBits / CONFIDENCE_SCALE_BITS))\n );\n}\n","/**\n * Verdict evidence (P20) — the contributing-signal list behind a detection\n * verdict, as structured output rather than a debug log.\n *\n * P16/P18 combine independent `DetectionSignal`s into one confidence number\n * via a Noisy-Or combiner (`rust/crates/kya-os-engine/src/stages/scoring.rs`):\n * each signal contributes `weight * probability` (`probability` being\n * `confidence / 100`), and the combiner folds those contributions together.\n * That per-signal contribution is exactly the number a reviewer needs to\n * answer \"why did this verdict land where it did\" — and today it is\n * recomputed and discarded inside the combiner, never persisted.\n *\n * `buildVerdictEvidence` re-derives the SAME `weight * probability` term for\n * each signal and returns it as a flat, typed, sorted list: the signal's\n * name, its weight, its probability contribution, and which detection\n * `plane` (`DetectionSignal.signalType`) it came from. This is deliberately\n * NOT the raw `DetectionSignal[]` passed straight through — that already\n * exists (`metadata.enforcement.signals`) as an opaque, unstructured\n * passthrough. Evidence is the derived, reviewable projection of it.\n *\n * SCOPE at the time this module was written: emit + persist only, with\n * dashboard rendering deferred to P51. P51 has since wired this into the\n * `/activity` Inspector and the agent detail sheet's recent-activity rows\n * (`EvidenceList` in `components/features/activity/verdict-evidence-list.tsx`).\n * Unifying this with the identity/fraud-signal \"explainable verdict\" object\n * `novelty.service.ts` (P25) forward-declares is still P38 — out of scope\n * here.\n */\nimport { z } from 'zod';\nimport { DetectionSignalSchema, type DetectionSignal } from './detection';\n\n/**\n * One contributing signal behind a verdict's confidence, as persisted\n * structured output.\n *\n * - `signal` — the signal's machine-readable source identifier\n * (`DetectionSignal.source`), e.g. `\"tier3_ua_pattern\"`.\n * - `plane` — which detection plane produced it (`DetectionSignal.signalType`\n * — signature / pattern / behavioral / network / fingerprint).\n * - `weight` — the signal family's relative trust weight, 0-1.\n * - `probabilityContribution` — `weight * (confidence / 100)`, the exact\n * term the Noisy-Or combiner multiplies together\n * (`1 - Π(1 - probabilityContribution_i)`). Storing this term (rather\n * than raw `weight` + `confidence` separately) is sufficient on its own to\n * reconstruct the combiner's confidence from stored evidence alone,\n * without replaying the original request.\n */\nexport const VerdictEvidenceSchema = z.object({\n signal: z.string(),\n plane: DetectionSignalSchema.shape.signalType,\n weight: z.number().min(0).max(1),\n probabilityContribution: z.number().min(0).max(1),\n});\nexport type VerdictEvidence = z.infer<typeof VerdictEvidenceSchema>;\n\n/** `weight_i * probability_i` — mirrors the Noisy-Or combiner's own inline\n * `contribution` term (`stages::scoring::noisy_or_combine`) so the two can\n * never silently diverge. `probability` is `confidence / 100`, already\n * validated into `[0, 100]` by `DetectionSignalSchema`, so the product is\n * guaranteed to land in `[0, 1]` with no extra clamping needed. */\nfunction signalContribution(signal: DetectionSignal): number {\n return signal.weight * (signal.confidence / 100);\n}\n\n/**\n * Builds the verdict's evidence list from the engine's raw detection\n * signals — allow or block, live or shadow, persisted or not: this is a\n * pure function of `signals` with no I/O of its own, so it emits the exact\n * same evidence regardless of what a caller does with the result\n * afterward (including a caller that never persists it at all).\n *\n * Entries that don't parse as a well-formed `DetectionSignal` (a malformed\n * wire payload, or a future signal-shaped-but-not-quite record) are\n * dropped rather than allowed to poison the list with `NaN`/garbage\n * contributions — mirrors `extractShadowMetadata`'s \"never throws, always\n * returns a safe-to-use value\" contract.\n *\n * Ordering is deterministic — sorted by `(plane, signal)` and never by\n * input/iteration order, since the upstream signal list is assembled\n * differently by different detection paths (PlainHttp classification vs.\n * SDK/gateway self-reports) and must still diff/hash identically for the\n * same logical evidence. `probabilityContribution` descending is the final\n * tiebreak for the (rare) case of two entries sharing both plane and name.\n */\nexport function buildVerdictEvidence(\n signals: readonly unknown[] | null | undefined\n): VerdictEvidence[] {\n if (!signals || signals.length === 0) return [];\n\n const entries: VerdictEvidence[] = [];\n for (const raw of signals) {\n const parsed = DetectionSignalSchema.safeParse(raw);\n if (!parsed.success) continue;\n const signal = parsed.data;\n entries.push({\n signal: signal.source,\n plane: signal.signalType,\n weight: signal.weight,\n probabilityContribution: signalContribution(signal),\n });\n }\n\n entries.sort((a, b) => {\n if (a.plane !== b.plane) return a.plane < b.plane ? -1 : 1;\n if (a.signal !== b.signal) return a.signal < b.signal ? -1 : 1;\n return b.probabilityContribution - a.probabilityContribution;\n });\n\n return entries;\n}\n\n/**\n * Mirrors `UNCALIBRATED_NOISY_OR_PRIOR` in\n * `rust/crates/kya-os-engine/src/stages/scoring.rs` — the Noisy-Or\n * combiner's \"leak\" node, the baseline probability of the outcome even with\n * zero observed evidence. The Rust engine folds this into every live\n * confidence it computes (`noisy_or_confidence_percent` calls\n * `noisy_or_combine(UNCALIBRATED_NOISY_OR_PRIOR, &inputs)`); reconstructing\n * confidence from stored evidence without it silently drops a fixed,\n * predictable amount from every verdict (bestbrian, PR #4747 review:\n * verified by hand against `TWO_SIGNAL_EVIDENCE_FIXTURE` — the un-primed\n * formula returns 94.2, the real engine returns 94.78).\n *\n */\nexport const UNCALIBRATED_NOISY_OR_PRIOR = 0.1;\n\n/**\n * Reconstructs the Noisy-Or confidence (0-100 scale) from a persisted\n * evidence list alone — no access to the original request or the raw\n * signals it was built from. `1 - (1 - prior) * Π(1 - probabilityContribution_i)`,\n * the SAME formula (with the SAME prior) `stages::scoring::noisy_or_combine`\n * computes for the live verdict — this must never diverge from the number\n * the engine actually returned, or \"explainable from stored data\" is a lie\n * by a fixed, predictable margin.\n *\n * Zero evidence reconstructs to the bare prior (10.0 on the 0-100 scale),\n * never a bare 0 — a claim of certainty (\"definitely not automated\") that\n * zero observed evidence never actually supports, exactly as\n * `noisy_or_combine`'s own doc comment argues.\n *\n * This is the acceptance test made concrete: an adverse decision must be\n * explainable from what was stored, without replaying the request.\n */\nexport function reconstructConfidenceFromEvidence(evidence: readonly VerdictEvidence[]): number {\n const probabilityAbsent = evidence.reduce(\n (acc, entry) => acc * (1 - entry.probabilityContribution),\n 1 - UNCALIBRATED_NOISY_OR_PRIOR\n );\n return (1 - probabilityAbsent) * 100;\n}\n","/**\n * Known AI agent patterns and constants\n *\n * F-08 PR-C: each entry now declares its own `category` (per the 9-value\n * canonical taxonomy locked by F-03 #2160). Previously\n * agent-types-sync.service.ts hardcoded `'ai_assistant'` for every entry\n * here, which is what stamped GPTBot / ClaudeBot / etc. as ai_assistant\n * in the agent_types table and ultimately as `detection_class='ai_agent'`\n * in detections (the F-08 bug). With per-entry categories, the sync\n * service routes each entry to the correct bucket directly.\n *\n * Two bundled entries from the prior shape have been split here so a\n * single agent_types row no longer represents both an interactive AI\n * session and a training crawler:\n * - `openai-gptbot` (was: GPTBot + ChatGPT-User + gpt-* models)\n * → `openai-gptbot` (scraper, just GPTBot)\n * + `openai-chatgpt` (ai_assistant, ChatGPT-User + gpt-* models)\n * - `google-bard` (was: Google-Extended + Bard + Google-InspectionTool + gemini + palm)\n * → `google-bard` (ai_assistant), later renamed to `gemini`\n * (migration 0201, id only). Google-Extended is a robots.txt token,\n * not a User-Agent, so it has no row.\n *\n * Mirrors the equivalent split in apps/web/scripts/seed-agent-types-data.ts\n * (claude / claudebot, perplexity / perplexity-bot).\n */\n\nimport { AgentPattern } from '../core/agent';\n\n/**\n * Known AI agent patterns\n */\nexport const KNOWN_AGENT_PATTERNS: AgentPattern[] = [\n // OpenAI — split into crawler vs interactive (PR-C)\n {\n id: 'openai-gptbot',\n type: 'openai',\n name: 'GPTBot',\n patterns: ['GPTBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'openai-chatgpt',\n type: 'openai',\n name: 'ChatGPT',\n // `OAI-SearchBot` backfilled by Engine-Pattern-Codegen-Retirement-1\n // after the legacy YAML→Rust path was retired. Previously detected\n // only via the legacy generator; the new TS SSOT migration would\n // have silently lost it.\n patterns: ['ChatGPT-User', 'OAI-SearchBot'],\n headers: {\n 'X-OpenAI-Assistant': '*',\n },\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n // GPT-Crawler — distinct from GPTBot (OpenAI's official training crawler);\n // tracked separately so the classifier can attribute hits to the\n // right entity. PDM-2 promoted from the INTERACTIVE_AGENT_PATTERNS\n // supplement.\n {\n id: 'openai-gpt-crawler',\n type: 'openai',\n name: 'GPT Crawler',\n patterns: ['GPT-Crawler'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // OpenAI generic vendor fallback — catches UAs that mention OpenAI\n // but use an undocumented sub-token (e.g. `OpenAI-Foo/1.0`,\n // `OpenAI-Web/2.0`). Word-boundary anchored (post-#2599). Lower\n // confidence than the strict per-token entries above. PDM-2.\n {\n id: 'openai-generic',\n type: 'openai',\n name: 'OpenAI',\n patterns: ['OpenAI'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Anthropic — split into interactive assistant vs training crawler.\n // The 'anthropic-ai' UA token used to live in this entry's patterns\n // alongside 'Claude-Web', which made every anthropic-ai crawler hit\n // resolve as ai_assistant. Moved out into the dedicated\n // `anthropic-ai-crawler` entry below so the classifier produces\n // (scraper, bot) for those rows. Same shape as the openai-gptbot /\n // openai-chatgpt split.\n {\n id: 'anthropic-claude',\n type: 'anthropic',\n name: 'Claude',\n patterns: [\n 'Claude-Web',\n 'claude-web',\n // Claude-User is Anthropic's user-initiated fetcher (the assistant\n // pulls a URL on the user's behalf — equivalent to ChatGPT-User).\n // Distinct from ClaudeBot (training crawler, captured separately\n // by `anthropic-claudebot`). anthropic.yaml already lists\n // 'Claude-User' on `anthropic_claude`, so the Rust WASM engine\n // recognizes it; this entry was the only layer where the pattern\n // was missing, which left ~14 real Claude-User sessions on\n // production stamped (bot, …) instead of (ai_agent, ai_assistant).\n 'Claude-User',\n // `Claude-SearchBot` and `claude-code` backfilled by\n // Engine-Pattern-Codegen-Retirement-1 — both were in the retired\n // YAML→Rust pipeline but never represented in TS. Claude-Code is\n // Anthropic's CLI agent (this very tool); Claude-SearchBot is\n // their search-augmented fetcher (parallel to OAI-SearchBot).\n 'Claude-SearchBot',\n 'claude-code',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #e111d65f):\n // the retired YAML→Rust pipeline matched both `claude-code` AND\n // `claude code` (space-separated). Some host wrappers stamp the\n // tool name with a space; the hyphenated form alone misses them.\n 'claude code',\n ],\n headers: {\n 'X-Anthropic-Client': '*',\n },\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'anthropic-claudebot',\n type: 'anthropic',\n name: 'ClaudeBot',\n patterns: ['ClaudeBot', 'claudebot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'anthropic-ai-crawler',\n type: 'anthropic',\n name: 'Anthropic-AI Crawler',\n patterns: ['anthropic-ai'],\n // 0.95, matching every other single-exact-token vendor crawler\n // (openai-gptbot, anthropic-claudebot, meta-externalagent,\n // gemini-deep-research, deepseek-bot). Previously 0.9, tied with\n // anthropic-generic below — classifyByUserAgent picks the first\n // match on a confidence tie (strict `>`, no stable order), so an\n // 'anthropic-ai' UA could resolve to either row depending on DB\n // iteration order, reopening the exact misclassification this\n // taxonomy split retires the token to fix. Caught by Bugbot on\n // #4172 once the migration landing this row made the tie live.\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // Anthropic generic vendor fallback — catches UAs that mention\n // Anthropic but use an undocumented sub-token (e.g. `Anthropic-Web`,\n // future variants). Word-boundary anchored (post-#2599) — only\n // matches when `Anthropic` is a standalone token, not embedded in\n // e.g. `AnthropicAssistant`. Lower confidence than the per-token\n // entries above. PDM-2 promoted from the INTERACTIVE_AGENT_PATTERNS\n // supplement.\n {\n id: 'anthropic-generic',\n type: 'anthropic',\n name: 'Anthropic',\n patterns: ['Anthropic'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Perplexity (training crawler, distinct from the interactive Perplexity-User\n // session captured by perplexity-user below)\n {\n id: 'perplexity-bot',\n type: 'perplexity',\n name: 'PerplexityBot',\n patterns: ['PerplexityBot', 'Perplexica'],\n confidence: 0.9,\n category: 'scraper',\n isLegitimate: true,\n },\n // Interactive Perplexity fetcher — parallel to ChatGPT-User shape;\n // the assistant pulls a URL on a human's behalf. Distinct from\n // PerplexityBot (training crawler). PDM-2 promoted this from the\n // INTERACTIVE_AGENT_PATTERNS supplement that #2599 carved out.\n {\n id: 'perplexity-user',\n type: 'perplexity',\n name: 'Perplexity',\n // `Comet` is Perplexity's AI-powered browser; backfilled into the\n // TS canonical via Engine-Pattern-Codegen-Retirement-1 after the\n // SSOT consolidation surfaced the gap. Previously detected only by\n // the legacy YAML→Rust codegen path; `apps/web/scripts/seed-agent-\n // types-data.ts` listed it as a Perplexity AI detection while\n // `KNOWN_AGENT_PATTERNS` did not. Now structurally enforced.\n patterns: ['Perplexity-User', 'Perplexity-AI'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n // Perplexity generic vendor fallback — catches UAs that mention\n // Perplexity but use an undocumented sub-token (future variants).\n // Lower confidence than the strict per-token entries above, and\n // declared after them: the engine takes the first match in source\n // order, so this only wins on truly unknown shapes. (The DB-side\n // `classifyByUserAgent` path instead picks the highest-confidence\n // match; both agree here.) Word-boundary anchored (post-#2599) so\n // `perplexity` only matches as a standalone token, not embedded.\n {\n id: 'perplexity-generic',\n type: 'perplexity',\n name: 'Perplexity',\n patterns: ['Perplexity'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Google — interactive assistants. `Google-Extended` is a robots.txt\n // product token (Google documents that it has no separate user-agent\n // string; the crawling itself uses Google's regular crawler UAs), so it\n // has no row here.\n {\n // ORDERING NOTE: `gemini-deep-research` MUST appear BEFORE\n // `gemini` (renamed from `google-bard`, migration 0201) so the\n // more-specific 'Gemini-Deep-Research'\n // pattern wins under the engine's first-match-wins iteration over\n // AI_AGENT_PATTERNS. The legacy YAML→Rust output collapsed all\n // Google patterns under a single \"Google AI\" name with identical\n // confidence (0.90), so shadowing was benign; the SSOT migration\n // surfaced different names + confidences (0.95 scraper vs 0.90\n // ai_assistant), making the order load-bearing.\n //\n // Google's user-directed deep-research agent — distinct UA from\n // Bard/Gemini interactive sessions. CT85 (pattern-gaps-and-taxonomy,\n // 2026-09-03): was category 'scraper', which the DB agent_types\n // catalog row (apps/web/scripts/seed-agent-types-data.ts, migration\n // 0231) copied — that mismatched the engine's own ai_agent/95 wire\n // verdict and Google's own docs (a user-directed agent, not a\n // training crawler). Realigned here too so this SSOT, the DB\n // catalog, and the wire all agree — this is the file\n // agent-types-sync.service.ts reads as canonical, so leaving it at\n // 'scraper' would let a future sync silently revert the DB fix.\n id: 'gemini-deep-research',\n type: 'google',\n name: 'Gemini-Deep-Research',\n patterns: ['Gemini-Deep-Research', 'gemini-deep-research'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n // Renamed from 'google-bard' (migration 0201, P4 follow-up). The prior\n // fix (Fix-Gemini-Mislabeled-As-Google-Bard-1) deliberately left the id\n // as `google-bard` and only renamed the human-facing `name` below,\n // because the id is the stable codegen/stored key (Rust pattern ids via\n // build.rs -> known-agent-patterns.json, the agent_types.name DB row,\n // `agent-classification.service.ts`'s directMappings). This PR does the\n // full id rename instead: verified zero live project/org policies\n // (cedar_policy_text, allowed/denied agent-type lists) reference the\n // 'google-bard' slug (checked against a Neon branch off prod main,\n // 2026-08-14), so the earlier narrower fix's risk no longer applies.\n // `agent_types.agent_did` already reads\n // `did:web:knowthat.ai:agents:gemini` — this id rename just catches the\n // codegen/DB slug up to what the DID already assumed.\n id: 'gemini',\n type: 'google',\n name: 'Google Gemini',\n // Engine-Pattern-Codegen-Retirement-1 corrections:\n // - REMOVED `Google-InspectionTool` from this entry. The legacy\n // YAML→Rust pipeline classified Google-InspectionTool as a\n // Googlebot-family search inspection tool (Search Console\n // verification, structured-data testing), not a Bard/Gemini AI\n // session. Moved to `NON_AI_PATTERNS` in\n // `rust/crates/kya-os-engine/src/stages/patterns.rs` under the\n // `Googlebot` family so classification stays SearchCrawler.\n // - ADDED `GoogleAgent-Mariner` (Google's browser-controlling agent\n // product), which was in the retired pipeline, never in TS.\n //\n // Engine-Pattern-Codegen-Retirement-2 (this PR, Bugbot #ae22713a and\n // #6984df6d): bare 'gemini' matched `GeminiiOS` (Google's own\n // Gemini app rendering a page in its in-app webview — a HUMAN, not an\n // agent) as a plain unanchored substring — `build.rs` emits every\n // pattern here into `format!(\"(?i){pattern}\")` with no escaping and no\n // boundary, so a literal `'gemini'` compiles to `Regex::new(\"(?i)gemini\")`,\n // which `.is_match()`-style scanning matches anywhere. That reopened,\n // one layer down, the exact hole migration 0208 closed on the\n // DB-side `classifyByUserAgent` path: this PR's own `lookupAgentDid`\n // fix matches the WASM engine's emitted `name` ('Google Gemini')\n // against `agent_types.displayName` for the enforce/pixel-track\n // routes, which run no TS classifier and never touch\n // `classifyByUserAgent` at all — so `GeminiiOS` could still reach the\n // live `gemini` DID via this second, engine-only path.\n //\n // First attempt was an outright removal, which closed the hole but\n // also dropped genuine coverage: a bare `Gemini/1.0` or\n // `Google-Gemini/1.0` UA carrying no specific model suffix no longer\n // matched anything (caught by Bugbot #6984df6d's follow-up review,\n // and independently by 4 apps/web unit tests asserting exactly that\n // coverage — see git history). Word-boundary anchors close the false\n // positive AND keep the coverage: `\\bgemini\\b` matches `Gemini/1.0`\n // and `Google-Gemini/1.0` (boundary before the leading `G`/after `-`,\n // and before the trailing `/`) but NOT `GeminiiOS` (no boundary\n // between the two `i`s — both are word characters). Model-version\n // names (`gemini-pro`, `palm2`, `LaMDA`) are not UA tokens and are\n // not listed; `\\bgemini\\b` already covers `gemini-pro/1.0`. TS\n // string literals need `\\\\b` (double backslash) to produce a literal\n // `\\b` in the resulting string — `\\b` alone is the JS backspace\n // escape, not a regex boundary.\n patterns: ['Bard', '\\\\bgemini\\\\b', 'GoogleAgent-Mariner'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // NotebookLM's user-triggered fetcher (developers.google.com/search/docs/\n // crawling-indexing/google-user-triggered-fetchers). `\\bgemini\\b` above\n // does not match `Google-GeminiNotebook` (no boundary after `Gemini`), so\n // this row is the only one that claims it.\n {\n id: 'google-notebooklm',\n type: 'google',\n name: 'Google NotebookLM',\n patterns: ['Google-GeminiNotebook'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Microsoft Copilot\n {\n id: 'microsoft-copilot',\n type: 'microsoft',\n name: 'Microsoft Copilot',\n patterns: [\n 'github-copilot',\n 'microsoft-copilot',\n // Word-bounded: a bare substring also matched app and framework\n // tokens that merely contain the word.\n '\\\\bcopilot\\\\b',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #89cfb23d):\n // the retired YAML→Rust pipeline carried `BingPreview/.*ChatGPT`\n // for Bing Copilot UAs. Without this, BingPreview+ChatGPT UAs hit\n // the non-AI `BingPreview` Bingbot rule and resolve as SearchBot.\n // Note: this entry must order BEFORE the Bingbot regex in the\n // composed table — AI patterns lead, so the dispatch order in\n // patterns.rs::AI_AGENT_PATTERNS (AI_PATTERNS_FROM_TS then\n // NON_AI_PATTERNS) preserves the precedence the legacy table\n // gave Microsoft AI at confidence 0.9.\n 'BingPreview/.*ChatGPT',\n ],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Meta AI (LLaMA) — interactive assistant only.\n // Disambiguated from Meta's web crawler (Meta-ExternalAgent) in the\n // dedicated entry below. Pre-split, prod's `meta-ai` agent_types row\n // had 'Meta-ExternalAgent' in its patterns AND category='ai_assistant',\n // which silently classified ~10K Meta-ExternalAgent crawler hits as\n // AI-assistant traffic on Hardware-World alone. Same pattern as the\n // openai-gptbot / openai-chatgpt split.\n {\n id: 'meta-ai',\n type: 'meta',\n name: 'Meta AI',\n patterns: ['Meta-AI'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-muse',\n type: 'meta',\n name: 'Meta Muse',\n patterns: ['Meta-Muse'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-externalagent',\n type: 'meta',\n name: 'Meta-ExternalAgent',\n patterns: ['Meta-ExternalAgent', 'meta-externalagent'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // Meta's user-triggered fetcher (developers.facebook.com/docs/sharing/\n // webmasters/web-crawlers): retrieves individual links at a user's\n // request and may ignore robots.txt. Interactive, so ai_assistant like\n // the other user-initiated fetchers (ChatGPT-User, Claude-User), not\n // the meta-externalagent crawler above.\n {\n id: 'meta-externalfetcher',\n type: 'meta',\n name: 'Meta-ExternalFetcher',\n patterns: ['Meta-ExternalFetcher'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-webindexer',\n type: 'meta',\n name: 'Meta-WebIndexer',\n patterns: ['meta-webindexer'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Cohere — bot variant (training/research crawler)\n {\n id: 'cohere-bot',\n type: 'cohere',\n name: 'CohereBot',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #8007b7a3):\n // the retired YAML→Rust pipeline matched the literal `CohereBot`\n // token; without it the UA falls through to the generic-bot\n // fallback (`bot` substring) and resolves as `Generic Bot` /\n // OtherBot, losing vendor attribution.\n patterns: ['cohere-ai', 'CohereBot'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // HuggingFace — bot variant\n {\n id: 'huggingface-bot',\n type: 'huggingface',\n name: 'HuggingFaceBot',\n patterns: ['HuggingFace', 'transformers'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Mistral AI\n {\n id: 'mistral-ai',\n type: 'mistral',\n name: 'MistralBot',\n patterns: ['mistral'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Inflection AI\n {\n id: 'inflection-pi',\n type: 'inflection',\n name: 'PiBot',\n patterns: ['inflection', 'pi-bot', 'pi.ai'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Stability AI\n {\n id: 'stability-ai',\n type: 'stability',\n name: 'StabilityBot',\n patterns: ['stability-ai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Writer AI\n {\n id: 'writer-ai',\n type: 'writer',\n name: 'WriterBot',\n patterns: ['writerai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Phind — bot variant\n {\n id: 'phind-bot',\n type: 'phind',\n name: 'PhindBot',\n patterns: ['phind', 'phind-codellama'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // You.com — bot variant (you.com / youbot are crawler patterns;\n // the interactive You.com session would be a separate entry if it\n // had a distinct UA, but currently doesn't)\n {\n id: 'you-bot',\n type: 'you',\n name: 'YouBot',\n patterns: ['you.com', 'youbot'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Neeva — bot variant\n {\n id: 'neeva-bot',\n type: 'neeva',\n name: 'NeevaBot',\n patterns: ['neeva', 'neevabot'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Jasper AI\n {\n id: 'jasper-ai',\n type: 'jasper',\n name: 'JasperBot',\n patterns: ['jasper', 'jasperai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Replicate — bot variant\n {\n id: 'replicate-bot',\n type: 'replicate',\n name: 'ReplicateBot',\n patterns: ['replicate'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Together AI\n {\n id: 'together-ai',\n type: 'together',\n name: 'TogetherBot',\n patterns: ['together-ai', 'togetherai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // ─────────────────────────────────────────────────────────────────────\n // Engine-Pattern-Codegen-Retirement-1 backfills.\n //\n // Each entry below was detected by the retired YAML→Rust codegen path\n // (`patterns_generated.rs`) but never represented in TS. The SSOT\n // migration would have silently dropped detection for these vendors.\n // Names + confidences mirror the legacy pipeline so classify_agent /\n // classify_vendor downstream consumers don't see a behavioral shift.\n // ─────────────────────────────────────────────────────────────────────\n\n // xAI Grok — Elon's AI; user-facing assistant + crawler share the\n // same vendor brand, all routed through this single entry. The\n // legacy pipeline emitted them under one \"xAI Grok\" name, so a split\n // would change downstream classification.\n {\n id: 'xai-grok',\n type: 'xai',\n name: 'xAI Grok',\n patterns: ['xAI-Grok', 'GrokBot', 'Grok-DeepSearch'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // DeepSeek — split into interactive (DeepSeek-User) and crawler\n // (DeepSeekBot), parallel to the openai-chatgpt / openai-gptbot\n // and anthropic-claude / anthropic-claudebot splits.\n {\n id: 'deepseek-user',\n type: 'deepseek',\n name: 'DeepSeek AI',\n patterns: ['DeepSeek-User'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'deepseek-bot',\n type: 'deepseek',\n name: 'DeepSeekBot',\n patterns: ['DeepSeekBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Crawlers whose operators publish a User-Agent token: Exa\n // (crawler.exa.ai), AI2 (allenai.org/crawler), Diffbot (diffbot.com/docs/\n // crawl/faq/robots-txt), Kimi (kimi.com/policies/kimi-crawlers). Their\n // vendors are not members of `AgentTypeSchema`, so `type` is 'unknown'.\n // Kimi splits like OpenAI and DeepSeek: `Kimi-User` fetches a page for a\n // person, `KimiBot`/`Kimi-SearchBot` are crawlers.\n {\n id: 'exa-search-bot',\n type: 'unknown',\n name: 'ExaSearchBot',\n patterns: ['ExaSearchBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'ai2-bot',\n type: 'unknown',\n name: 'AI2Bot',\n patterns: ['AI2Bot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'diffbot',\n type: 'unknown',\n name: 'Diffbot',\n patterns: ['Diffbot'],\n confidence: 0.9,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'kimi-user',\n type: 'unknown',\n name: 'Kimi',\n patterns: ['Kimi-User'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'kimi-bot',\n type: 'unknown',\n name: 'KimiBot',\n patterns: ['KimiBot', 'Kimi-SearchBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Amazon Quick — AWS's rendering web crawler (formerly launched as part\n // of the \"Amazon Q\" family, since renamed; docs.aws.amazon.com/quick).\n // UA convention is `amazon-Quick-on-behalf-of-<id>` / AWS's own\n // documented `aws-quick-on-behalf-of-<UUID>`. Declared BEFORE\n // `amazon-q` below: the Rust engine's AI_AGENT_PATTERNS match is\n // first-match-wins in TS source order (see patterns.rs\n // `analyze_user_agent`), and 'Amazon-Quick' is a superstring of\n // 'Amazon-Q' below, so the more specific pattern must be tried first\n // there. `classifyByUserAgent` (TS/DB path) doesn't use source order —\n // it tie-breaks on confidence — so this row's confidence must also\n // stay strictly above `amazon-q`'s (mirrors the anthropic-ai-crawler /\n // anthropic-generic split: specific crawler token > broad label).\n // is_legitimate: AWS's docs describe it as a JS-rendering, non-\n // interactive crawler (no simulated user interaction) — the taxonomy's\n // `scraper` bucket, not `ai_assistant` (real-time human-driven use).\n {\n id: 'amazon-quick',\n type: 'amazon',\n name: 'Amazon Quick',\n patterns: ['Amazon-Quick', 'aws-quick'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Amazon Q + NovaAct — Amazon's AI assistant product family.\n // NovaAct is the AWS-branded browser-controlling agent (parallel to\n // Anthropic's Claude-Code, Google's GoogleAgent-Mariner).\n //\n // Confidence intentionally below `amazon-quick` above, by MORE than the\n // TS/DB path's max multi-pattern bonus (+5 for 2+ pattern matches — see\n // calculateConfidence in agent-classification.service.ts): 0.85 not 0.90.\n // A UA containing both of amazon-q's patterns ('Amazon-Q' — substring-\n // matched by 'Amazon-Quick' — and 'NovaAct', plausible on the same\n // product family's browser-driving traffic) would score 90 + 5 = 95,\n // tying amazon-quick's flat 95 and recreating the exact order-dependent\n // tie this split exists to eliminate (own regression test:\n // agent-classification-amazon-quick-crawler-tie.test.ts). At 0.85 the\n // bonus tops out at 85 + 5 = 90, still short of amazon-quick's 95.\n {\n id: 'amazon-q',\n type: 'amazon',\n name: 'Amazon Q',\n patterns: ['Amazon-Q', 'NovaAct'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // KYA Agent — our own product family. KYA-Agent/<version> is the\n // canonical UA; KYA-OS is the umbrella protocol token; KYA-Compute/\n // is the signed-compute variant. All ai_assistant — none of these\n // are training crawlers.\n //\n // Display name is `'Kya Agent'` (sentence case), NOT `'KYA Agent'`\n // (brand all-caps). Matches every other consumer's expectation: the\n // gateway router docstring refers to the \"Kya Agent\" pattern, and the\n // signed-agent e2e test asserts on `'Kya Agent'` for the unsigned\n // Tier-3 UA path. One source of truth, sentence case.\n {\n id: 'kya-agent',\n type: 'kya',\n name: 'Kya Agent',\n patterns: ['KYA-Agent/', 'KYA-OS', 'KYA-Compute/'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n];\n\n/**\n * Known cloud provider IP ranges (partial list)\n */\nexport const CLOUD_PROVIDER_RANGES = {\n aws: ['52.0.0.0/8', '54.0.0.0/8', '18.0.0.0/8', '35.0.0.0/8'],\n gcp: ['35.190.0.0/16', '35.240.0.0/16', '34.0.0.0/8'],\n azure: ['40.0.0.0/8', '20.0.0.0/8', '13.0.0.0/8'],\n};\n\n/**\n * Common bot user agent patterns. Model-version names (gpt-4, claude-3,\n * llama-3, ...) are not UA tokens and are not listed.\n */\nexport const BOT_USER_AGENT_PATTERNS = [\n /bot/i,\n /crawler/i,\n /spider/i,\n /scraper/i,\n /agent/i,\n /ai\\//i,\n // OpenAI\n /chatgpt/i,\n /openai/i,\n // Anthropic\n /claude/i,\n /anthropic/i,\n // Google\n /gemini/i,\n /bard/i,\n // Mistral\n /mistral/i,\n // Microsoft\n /copilot/i,\n // Other vendors\n /perplexity/i,\n /\\bphind\\b/i,\n // `you.com` is detected as a UA SUBSTRING — the pattern is consumed\n // only by `BOT_USER_AGENT_PATTERNS.some(p => p.test(userAgent))`\n // (UA context, not URL). CodeQL js/regex/missing-regexp-anchor\n // speculated about URL misuse on PR #2576; PR #2591's tightened\n // consuming-class form (`[\\s;()]`) introduced a real false-negative\n // for legit UA shapes containing `/`:\n // - `you.com/1.0` (You.com bot, version-suffixed)\n // - `Mozilla/5.0 you.com/bot` (token-with-version)\n // - `+https://you.com)` (token after URL inside parens)\n // Cursor caught the regression on PR #2591. Reverting to `\\b` —\n // word-boundary is the correct anchor for UA-substring matching;\n // the original CodeQL flag is a context-blind false positive (the\n // codebase does not apply BOT_USER_AGENT_PATTERNS to URL strings).\n // If CodeQL re-flags, dismiss in the UI as \"false positive\" with\n // pointer to this comment.\n /\\byou\\.com\\b/i,\n /\\bneeva\\b/i,\n /jasper/i,\n /replicate/i,\n /together(-?ai)?/i,\n /cohere/i,\n /huggingface/i,\n /transformers/i,\n];\n\n/**\n * Headers commonly used by AI agents\n */\nexport const AI_AGENT_HEADERS = [\n 'X-OpenAI-Assistant',\n 'X-Anthropic-Client',\n 'X-AI-Agent',\n 'X-Bot-Token',\n 'X-Agent-ID',\n 'X-LLM-Request',\n];\n\n/**\n * Suspicious header patterns\n */\nexport const SUSPICIOUS_HEADERS = {\n // Missing standard headers\n missingUserAgent: 'User-Agent header is missing',\n missingAccept: 'Accept header is missing',\n\n // Unusual values\n genericUserAgent: 'User-Agent appears to be generic or spoofed',\n mismatchedHeaders: 'Headers contain conflicting information',\n\n // Known spoofing attempts\n fakeChrome: 'Chrome user agent without expected Chrome headers',\n fakeSafari: 'Safari user agent without expected Safari headers',\n};\n","/**\n * Traditional Bot Constants and Types\n *\n * These are NON-AI bots like search engines, crawlers, and SEO tools.\n * AI agents (Claude, GPT, etc.) should be in agents.ts\n */\n\nimport { z } from 'zod';\n\n/**\n * Traditional bot types (not AI agents)\n */\nexport const BotTypeSchema = z.enum([\n 'search_engine', // googlebot, bingbot, yandexbot\n 'social_media', // facebookbot, twitterbot, linkedinbot\n 'seo_tool', // semrushbot, ahrefsbot, mj12bot\n 'crawler', // generic web crawlers\n 'scraper', // data scrapers\n 'monitoring', // uptime monitors, health checkers\n 'security_scanner', // security scanning tools\n 'unknown_bot',\n]);\n\nexport type BotType = z.infer<typeof BotTypeSchema>;\n\n/**\n * Trusted traditional bots that can be cached\n * These are well-known, legitimate bots with stable patterns\n * NOT for AI agents - those should never be cached\n */\nexport const TRUSTED_BOTS = [\n // Search engines\n 'googlebot', // Google Search\n 'bingbot', // Bing Search\n 'slurp', // Yahoo\n 'duckduckbot', // DuckDuckGo\n 'baiduspider', // Baidu\n 'yandexbot', // Yandex\n 'applebot', // Apple Search\n\n // Social media\n 'facebookexternalhit', // Facebook\n 'twitterbot', // Twitter/X\n 'linkedinbot', // LinkedIn\n 'whatsapp', // WhatsApp\n\n // SEO tools\n 'semrushbot', // SEMrush SEO\n 'ahrefsbot', // Ahrefs SEO\n 'mj12bot', // Majestic SEO\n 'dotbot', // Moz SEO\n];\n\n/**\n * Bot pattern for traditional bot matching\n */\nexport const BotPatternSchema = z.object({\n id: z.string(),\n type: BotTypeSchema,\n name: z.string(),\n patterns: z.array(z.string()),\n confidence: z.number().min(0).max(1).default(0.8),\n});\n\nexport type BotPattern = z.infer<typeof BotPatternSchema>;\n\n/**\n * Traditional bot patterns.\n *\n * NAME VOCABULARY: `name` MUST be the detection engine's pattern name — the\n * string `kya-os-engine` stamps as `agent_name` (see the `NON_AI_PATTERNS`\n * table in `rust/crates/kya-os-engine/src/stages/patterns.rs`). That string\n * becomes `agent_types.display_name` via the sync service, the Cedar\n * principal the policy picker emits, and the `principal.name` every\n * evaluator byte-compares. A name the engine never emits can't be policy-\n * matched. Drift is pinned by `bot-name-vocabulary.spec.ts`, which parses\n * the Rust table at test time; entries the engine has NO name for are\n * allow-listed there and tracked by the codegen-consolidation issue.\n */\nexport const TRADITIONAL_BOT_PATTERNS: BotPattern[] = [\n // Search engines\n {\n id: 'googlebot',\n type: 'search_engine',\n name: 'Googlebot',\n patterns: ['googlebot', 'google-structured-data-testing-tool'],\n confidence: 0.95,\n },\n {\n id: 'bingbot',\n type: 'search_engine',\n name: 'Bingbot',\n patterns: ['bingbot', 'bingpreview', 'msnbot'],\n confidence: 0.95,\n },\n {\n id: 'yandexbot',\n type: 'search_engine',\n name: 'Yandexbot',\n patterns: ['yandexbot', 'yandex'],\n confidence: 0.9,\n },\n\n // Social media\n {\n id: 'facebook',\n type: 'social_media',\n name: 'Meta Crawler',\n patterns: ['facebookexternalhit', 'facebookcatalog', 'Meta-ExternalAgent'],\n confidence: 0.9,\n },\n {\n id: 'twitter',\n type: 'social_media',\n name: 'Twitterbot',\n patterns: ['twitterbot'],\n confidence: 0.9,\n },\n\n // SEO tools\n {\n id: 'semrush',\n type: 'seo_tool',\n name: 'SEMrush',\n patterns: ['semrushbot'],\n confidence: 0.85,\n },\n {\n id: 'ahrefs',\n type: 'seo_tool',\n name: 'Ahrefsbot',\n patterns: ['ahrefsbot'],\n confidence: 0.85,\n },\n\n // Generic crawlers\n {\n id: 'generic-crawler',\n type: 'crawler',\n name: 'Generic Bot',\n patterns: ['crawler', 'spider', 'bot/'],\n confidence: 0.6,\n },\n {\n id: 'generic-scraper',\n type: 'scraper',\n name: 'Generic Scraper',\n patterns: ['scraper', 'python-requests', 'curl/', 'wget/'],\n confidence: 0.7,\n },\n];\n\n/**\n * Check if a user agent is a traditional bot (not AI agent)\n */\nexport function isTraditionalBot(userAgent: string): boolean {\n const lowerUA = userAgent.toLowerCase();\n return TRUSTED_BOTS.some((bot) => lowerUA.includes(bot));\n}\n\n/**\n * Get bot type from user agent\n */\nexport function getBotType(userAgent: string): BotType | null {\n const lowerUA = userAgent.toLowerCase();\n\n for (const pattern of TRADITIONAL_BOT_PATTERNS) {\n if (pattern.patterns.some((p) => lowerUA.includes(p.toLowerCase()))) {\n return pattern.type;\n }\n }\n\n return null;\n}\n","/**\n * Delegation credential lifetime bounds.\n *\n * Shared because the mint and the dashboard MUST agree: the policy page once\n * advertised a project's configured `delegationExpirationDays` (\"good for 7\n * days\") while the credential that flow actually minted was 900 seconds.\n */\n\n/**\n * Maximum lifetime of an `attested-bearer` DelegationCredential, in seconds.\n *\n * A credential with no `cnf` (holder-key) claim is a bearer credential:\n * whoever holds the bytes can use them. The HTTP binding therefore bounds it\n * at 900s, and key-bound remains the default and conformance floor. Raising\n * this hands out longer-lived ambient authority — the exact failure the\n * key-bound design removes — so it is a spec change, not a config knob.\n */\nexport const ATTESTED_BEARER_MAX_TTL_SECONDS = 900;\n","/**\n * Error Codes and Messages\n *\n * Standardized error codes and messages used across all packages\n */\n\n/**\n * Error Code Categories\n */\nexport const ERROR_CATEGORIES = {\n AUTH: 'AUTH',\n VALIDATION: 'VALIDATION',\n DETECTION: 'DETECTION',\n RATE_LIMIT: 'RATE_LIMIT',\n PERMISSION: 'PERMISSION',\n NETWORK: 'NETWORK',\n INTERNAL: 'INTERNAL',\n CONFIGURATION: 'CONFIGURATION',\n WASM: 'WASM',\n SESSION: 'SESSION',\n PIXEL: 'PIXEL',\n API: 'API',\n} as const;\n\n/**\n * Authentication Error Codes\n */\nexport const AUTH_ERRORS = {\n INVALID_API_KEY: 'AUTH_INVALID_API_KEY',\n EXPIRED_API_KEY: 'AUTH_EXPIRED_API_KEY',\n INVALID_TOKEN: 'AUTH_INVALID_TOKEN',\n EXPIRED_TOKEN: 'AUTH_EXPIRED_TOKEN',\n MISSING_CREDENTIALS: 'AUTH_MISSING_CREDENTIALS',\n UNAUTHORIZED: 'AUTH_UNAUTHORIZED',\n // A C3 human management session presented where an API key is required.\n MANAGEMENT_TOKEN_NOT_ACCEPTED: 'AUTH_MANAGEMENT_TOKEN_NOT_ACCEPTED',\n INVALID_PIXEL_ID: 'AUTH_INVALID_PIXEL_ID',\n INVALID_SECRET_KEY: 'AUTH_INVALID_SECRET_KEY',\n} as const;\n\n/**\n * Validation Error Codes\n */\nexport const VALIDATION_ERRORS = {\n INVALID_REQUEST: 'VALIDATION_INVALID_REQUEST',\n MISSING_REQUIRED_FIELD: 'VALIDATION_MISSING_REQUIRED_FIELD',\n INVALID_FIELD_TYPE: 'VALIDATION_INVALID_FIELD_TYPE',\n INVALID_FIELD_VALUE: 'VALIDATION_INVALID_FIELD_VALUE',\n FIELD_TOO_LONG: 'VALIDATION_FIELD_TOO_LONG',\n FIELD_TOO_SHORT: 'VALIDATION_FIELD_TOO_SHORT',\n INVALID_EMAIL: 'VALIDATION_INVALID_EMAIL',\n INVALID_URL: 'VALIDATION_INVALID_URL',\n INVALID_UUID: 'VALIDATION_INVALID_UUID',\n INVALID_IP_ADDRESS: 'VALIDATION_INVALID_IP_ADDRESS',\n INVALID_USER_AGENT: 'VALIDATION_INVALID_USER_AGENT',\n BAD_REQUEST: 'VALIDATION_BAD_REQUEST',\n INVALID_START_DATE: 'VALIDATION_INVALID_START_DATE',\n INVALID_END_DATE: 'VALIDATION_INVALID_END_DATE',\n INVALID_DATE_RANGE: 'VALIDATION_INVALID_DATE_RANGE',\n} as const;\n\n/**\n * Detection Error Codes\n */\nexport const DETECTION_ERRORS = {\n DETECTION_FAILED: 'DETECTION_FAILED',\n INSUFFICIENT_DATA: 'DETECTION_INSUFFICIENT_DATA',\n PATTERN_MATCH_FAILED: 'DETECTION_PATTERN_MATCH_FAILED',\n WASM_NOT_LOADED: 'DETECTION_WASM_NOT_LOADED',\n WASM_EXECUTION_FAILED: 'DETECTION_WASM_EXECUTION_FAILED',\n CONFIDENCE_BELOW_THRESHOLD: 'DETECTION_CONFIDENCE_BELOW_THRESHOLD',\n SIGNATURE_VERIFICATION_FAILED: 'DETECTION_SIGNATURE_VERIFICATION_FAILED',\n} as const;\n\n/**\n * Rate Limit Error Codes\n */\nexport const RATE_LIMIT_ERRORS = {\n RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',\n BURST_LIMIT_EXCEEDED: 'RATE_LIMIT_BURST_EXCEEDED',\n DAILY_LIMIT_EXCEEDED: 'RATE_LIMIT_DAILY_EXCEEDED',\n MONTHLY_LIMIT_EXCEEDED: 'RATE_LIMIT_MONTHLY_EXCEEDED',\n CONCURRENT_LIMIT_EXCEEDED: 'RATE_LIMIT_CONCURRENT_EXCEEDED',\n QUOTA_EXCEEDED: 'RATE_LIMIT_QUOTA_EXCEEDED',\n RATE_LIMITED: 'RATE_LIMITED',\n} as const;\n\n/**\n * Permission Error Codes\n */\nexport const PERMISSION_ERRORS = {\n INSUFFICIENT_PERMISSIONS: 'PERMISSION_INSUFFICIENT',\n RESOURCE_NOT_FOUND: 'PERMISSION_RESOURCE_NOT_FOUND',\n RESOURCE_ACCESS_DENIED: 'PERMISSION_ACCESS_DENIED',\n OPERATION_NOT_ALLOWED: 'PERMISSION_OPERATION_NOT_ALLOWED',\n PROJECT_ACCESS_DENIED: 'PERMISSION_PROJECT_ACCESS_DENIED',\n PIXEL_ACCESS_DENIED: 'PERMISSION_PIXEL_ACCESS_DENIED',\n FORBIDDEN: 'PERMISSION_FORBIDDEN',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n} as const;\n\n/**\n * Network Error Codes\n */\nexport const NETWORK_ERRORS = {\n CONNECTION_FAILED: 'NETWORK_CONNECTION_FAILED',\n TIMEOUT: 'NETWORK_TIMEOUT',\n DNS_RESOLUTION_FAILED: 'NETWORK_DNS_FAILED',\n SSL_ERROR: 'NETWORK_SSL_ERROR',\n PROXY_ERROR: 'NETWORK_PROXY_ERROR',\n UPSTREAM_ERROR: 'NETWORK_UPSTREAM_ERROR',\n} as const;\n\n/**\n * Internal Error Codes\n */\nexport const INTERNAL_ERRORS = {\n INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',\n DATABASE_ERROR: 'INTERNAL_DATABASE_ERROR',\n CACHE_ERROR: 'INTERNAL_CACHE_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_CONFIGURATION_ERROR',\n INITIALIZATION_ERROR: 'INTERNAL_INITIALIZATION_ERROR',\n PROCESSING_ERROR: 'INTERNAL_PROCESSING_ERROR',\n UNKNOWN_ERROR: 'INTERNAL_UNKNOWN_ERROR',\n SERVICE_UNAVAILABLE_TRANSIENT: 'SERVICE_UNAVAILABLE_TRANSIENT',\n TRANSACTION_FAILED: 'TRANSACTION_FAILED',\n DELETE_FAILED: 'DELETE_FAILED',\n PARTITION_RETIREMENT_IN_PROGRESS: 'PARTITION_RETIREMENT_IN_PROGRESS',\n} as const;\n\n/**\n * Session Error Codes\n */\nexport const SESSION_ERRORS = {\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_EXPIRED: 'SESSION_EXPIRED',\n SESSION_INVALID: 'SESSION_INVALID',\n SESSION_CREATION_FAILED: 'SESSION_CREATION_FAILED',\n SESSION_UPDATE_FAILED: 'SESSION_UPDATE_FAILED',\n SESSION_STORAGE_ERROR: 'SESSION_STORAGE_ERROR',\n MAX_SESSIONS_EXCEEDED: 'SESSION_MAX_EXCEEDED',\n} as const;\n\n/**\n * Pixel Error Codes\n */\nexport const PIXEL_ERRORS = {\n PIXEL_NOT_FOUND: 'PIXEL_NOT_FOUND',\n PIXEL_DISABLED: 'PIXEL_DISABLED',\n PIXEL_CONFIGURATION_ERROR: 'PIXEL_CONFIGURATION_ERROR',\n PIXEL_DOMAIN_NOT_ALLOWED: 'PIXEL_DOMAIN_NOT_ALLOWED',\n PIXEL_PATH_SKIPPED: 'PIXEL_PATH_SKIPPED',\n PIXEL_EVENT_INVALID: 'PIXEL_EVENT_INVALID',\n PIXEL_BATCH_TOO_LARGE: 'PIXEL_BATCH_TOO_LARGE',\n MISSING_PIXEL_ID: 'MISSING_PIXEL_ID',\n DETECTION_STORAGE_FAILED: 'DETECTION_STORAGE_FAILED',\n PIXEL_CREATION_FAILED: 'PIXEL_CREATION_FAILED',\n} as const;\n\n/**\n * API Error Codes\n */\nexport const API_ERRORS = {\n ENDPOINT_NOT_FOUND: 'API_ENDPOINT_NOT_FOUND',\n METHOD_NOT_ALLOWED: 'API_METHOD_NOT_ALLOWED',\n VERSION_NOT_SUPPORTED: 'API_VERSION_NOT_SUPPORTED',\n CONTENT_TYPE_NOT_SUPPORTED: 'API_CONTENT_TYPE_NOT_SUPPORTED',\n RESPONSE_TOO_LARGE: 'API_RESPONSE_TOO_LARGE',\n REQUEST_TOO_LARGE: 'API_REQUEST_TOO_LARGE',\n // A route that no longer serves requests and answers 410 Gone, naming\n // its replacement, until it is removed.\n ENDPOINT_RETIRED: 'API_ENDPOINT_RETIRED',\n} as const;\n\n/**\n * Billing Error Codes\n */\nexport const BILLING_ERRORS = {\n LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',\n BILLING_SUSPENDED: 'BILLING_SUSPENDED',\n BILLING_GRACE_PERIOD: 'BILLING_GRACE_PERIOD',\n} as const;\n\n/**\n * Resource Error Codes\n */\nexport const RESOURCE_ERRORS = {\n CONFLICT: 'CONFLICT',\n PROJECT_NOT_FOUND: 'PROJECT_NOT_FOUND',\n REVIEW_REQUIRED: 'REVIEW_REQUIRED',\n} as const;\n\n/**\n * Policy Error Codes\n */\nexport const POLICY_ERRORS = {\n POLICY_FETCH_FAILED: 'POLICY_FETCH_FAILED',\n} as const;\n\n/**\n * Analytics Error Codes\n *\n * Emitted by the project analytics and shopify stats read routes.\n */\nexport const ANALYTICS_ERRORS = {\n INVALID_PERIOD: 'INVALID_PERIOD',\n ANALYTICS_FETCH_ERROR: 'ANALYTICS_FETCH_ERROR',\n STATS_FETCH_ERROR: 'STATS_FETCH_ERROR',\n} as const;\n\n/**\n * Deploy Error Codes\n *\n * Emitted by the managed deploy route and the managed deploy service it\n * wraps. The service-computed codes have no fixed status here (see the\n * NOTE in ERROR_STATUS_CODES).\n */\nexport const DEPLOY_ERRORS = {\n MISSING_USER_IDENTIFIER: 'MISSING_USER_IDENTIFIER',\n USER_NOT_FOUND: 'USER_NOT_FOUND',\n NO_ORGANIZATION: 'NO_ORGANIZATION',\n DEPLOY_FAILED: 'DEPLOY_FAILED',\n WFP_NOT_CONFIGURED: 'WFP_NOT_CONFIGURED',\n NATIVE_ISSUER_PROVISIONING_BUSY: 'NATIVE_ISSUER_PROVISIONING_BUSY',\n NATIVE_ISSUER_PROVISIONING_FAILED: 'NATIVE_ISSUER_PROVISIONING_FAILED',\n} as const;\n\n/**\n * Bare Error Codes\n *\n * Un-prefixed upper-case wire strings shared by several surfaces (pixel,\n * pixel/track, openclaw, deploy, shopify, bouncer, project analytics).\n * Keyed by value with a BARE_ prefix so the key cannot collide with the\n * prefixed groups.\n */\nexport const BARE_ERRORS = {\n BARE_VALIDATION_ERROR: 'VALIDATION_ERROR',\n BARE_INTERNAL_ERROR: 'INTERNAL_ERROR',\n BARE_INVALID_REQUEST: 'INVALID_REQUEST',\n BARE_INVALID_JSON: 'INVALID_JSON',\n BARE_INVALID_START_DATE: 'INVALID_START_DATE',\n BARE_INVALID_END_DATE: 'INVALID_END_DATE',\n BARE_INVALID_DATE_RANGE: 'INVALID_DATE_RANGE',\n BARE_INVALID_DATE: 'INVALID_DATE',\n BARE_UNKNOWN_ERROR: 'UNKNOWN_ERROR',\n BARE_NOT_FOUND: 'NOT_FOUND',\n BARE_FORBIDDEN: 'FORBIDDEN',\n} as const;\n\n/**\n * Lowercase Error Codes\n *\n * Lowercase wire strings are the SPEC-EVENTS wire format used by\n * /api/v1/kya-os/events and /api/v1/kya-os/revocations, and reused by the\n * bouncer family. Keyed by value with a LOWERCASE_ prefix.\n *\n * `invalid_cursor` is the revocation feed's answer to a `since` it did not\n * issue for the key's project; consumers drop their cursor and read the feed\n * from the start on exactly this code.\n */\nexport const LOWERCASE_ERRORS = {\n LOWERCASE_INVALID_JSON: 'invalid_json',\n LOWERCASE_VALIDATION_ERROR: 'validation_error',\n LOWERCASE_INVALID_CURSOR: 'invalid_cursor',\n} as const;\n\n/**\n * Bouncer Error Codes (lower-case wire format)\n *\n * Emitted by the /api/v1/bouncer routes, either inline by the route or via\n * a `BouncerError` subclass thrown from a bouncer service. Only subclass\n * codes that a bouncer route can actually put on the wire are registered\n * here; classes that exist but are never thrown are deliberately absent.\n * Keyed by value with a LOWERCASE_ prefix.\n */\nexport const BOUNCER_LOWERCASE_ERRORS = {\n LOWERCASE_NO_PROJECT: 'no_project',\n LOWERCASE_MISSING_AGENT_DID: 'missing_agent_did',\n LOWERCASE_NOT_CONFIGURED: 'not_configured',\n LOWERCASE_INVALID_CREDENTIAL_CONFIG: 'invalid_credential_config',\n LOWERCASE_PROJECT_NOT_FOUND: 'project_not_found',\n LOWERCASE_PROJECT_MISMATCH: 'project_mismatch',\n LOWERCASE_MISSING_DELEGATION_ID: 'missing_delegation_id',\n LOWERCASE_INVALID_TOKEN: 'invalid_token',\n LOWERCASE_DELEGATION_MISMATCH: 'delegation_mismatch',\n LOWERCASE_TOKENS_NOT_FOUND: 'tokens_not_found',\n LOWERCASE_DECRYPTION_ERROR: 'decryption_error',\n LOWERCASE_NO_PROOFS: 'no_proofs',\n LOWERCASE_BATCH_TOO_LARGE: 'batch_too_large',\n LOWERCASE_NO_PROOFS_PROCESSED: 'no_proofs_processed',\n LOWERCASE_ALL_PROOFS_REJECTED: 'all_proofs_rejected',\n LOWERCASE_UNAUTHORIZED: 'unauthorized',\n LOWERCASE_FORBIDDEN: 'forbidden',\n LOWERCASE_NOT_FOUND: 'not_found',\n // BouncerError subclass codes (apps/web/lib/bouncer/types/index.ts)\n LOWERCASE_CONFIG_NOT_FOUND: 'config_not_found',\n LOWERCASE_AGENT_DENIED: 'agent_denied',\n LOWERCASE_DELEGATION_NOT_FOUND: 'delegation_not_found',\n LOWERCASE_SESSION_NOT_FOUND: 'session_not_found',\n LOWERCASE_PROOF_VALIDATION_ERROR: 'proof_validation_error',\n LOWERCASE_INSUFFICIENT_SCOPES: 'insufficient_scopes',\n LOWERCASE_DELEGATION_VALIDATION_ERROR: 'delegation_validation_error',\n // A grant from before the issuance core: no org status list, so it cannot be re-minted.\n GRANT_PREDATES_ISSUANCE_CORE: 'grant_predates_issuance_core',\n LOWERCASE_INVALID_HTTP_REGISTRATION: 'invalid_http_registration',\n LOWERCASE_POLICY_REVISION_MISMATCH: 'policy_revision_mismatch',\n LOWERCASE_POLICY_REVISION_GRACE_UNAVAILABLE: 'policy_revision_grace_unavailable',\n LOWERCASE_AUTHORIZATION_HOST_UNAVAILABLE: 'authorization_host_unavailable',\n} as const;\n\n/**\n * Delegation OAuth Error Codes (lower-case wire format)\n *\n * Emitted by the bouncer authorize, oauth/start, oauth/callback and\n * oauth/token routes and the shared OAuth rate limiter. Several reuse RFC\n * 6749 vocabulary (`invalid_request`, `invalid_grant`,\n * `unsupported_grant_type`) but travel in the bouncer `{success, error}`\n * envelope, not an RFC 6749 body. Keyed by value with a LOWERCASE_ prefix.\n */\nexport const OAUTH_LOWERCASE_ERRORS = {\n LOWERCASE_INVALID_REQUEST: 'invalid_request',\n LOWERCASE_UNSUPPORTED_GRANT_TYPE: 'unsupported_grant_type',\n LOWERCASE_INVALID_GRANT: 'invalid_grant',\n LOWERCASE_INVALID_DELEGATION: 'invalid_delegation',\n LOWERCASE_INTERNAL_ERROR: 'internal_error',\n LOWERCASE_INVALID_STATE: 'invalid_state',\n LOWERCASE_INVALID_TRANSACTION: 'invalid_transaction',\n LOWERCASE_OAUTH_UNAVAILABLE: 'oauth_unavailable',\n LOWERCASE_OAUTH_NOT_CONFIGURED: 'oauth_not_configured',\n LOWERCASE_OAUTH_CONFIGURATION_UNSUPPORTED: 'oauth_configuration_unsupported',\n LOWERCASE_INVALID_PROVIDER_CONFIG: 'invalid_provider_config',\n LOWERCASE_RATE_LIMIT_EXCEEDED: 'rate_limit_exceeded',\n} as const;\n\n/**\n * Bouncer Error Codes (upper-case wire format)\n *\n * Emitted by the /api/v1/bouncer/projects/{projectId}/* routes and the\n * delegation request status route through `ApiError` / `v1ErrorResponse`.\n */\nexport const BOUNCER_UPPERCASE_ERRORS = {\n INVALID_REQUEST_BODY: 'INVALID_REQUEST_BODY',\n MCPI_CONFIG_NOT_FOUND: 'MCPI_CONFIG_NOT_FOUND',\n CONSENT_CONFIG_NOT_FOUND: 'CONSENT_CONFIG_NOT_FOUND',\n PROJECT_LOOKUP_FAILED: 'PROJECT_LOOKUP_FAILED',\n CONFIG_VALIDATION_ERROR: 'CONFIG_VALIDATION_ERROR',\n CONFIG_FETCH_FAILED: 'CONFIG_FETCH_FAILED',\n CONFIG_UPDATE_FAILED: 'CONFIG_UPDATE_FAILED',\n DEPLOYMENT_NOT_FOUND: 'DEPLOYMENT_NOT_FOUND',\n INVALID_REQUEST_ID: 'INVALID_REQUEST_ID',\n DELEGATION_REQUEST_NOT_FOUND: 'DELEGATION_REQUEST_NOT_FOUND',\n} as const;\n\n/**\n * Audit Ingest Error Codes\n *\n * Route-owned codes of POST /api/v1/audit/entries: credential, size, JSON,\n * rate-limit and submission-envelope failures raised before or around the\n * audit protocol itself.\n */\nexport const AUDIT_ERRORS = {\n AUDIT_CREDENTIAL_REQUIRED: 'AUDIT_CREDENTIAL_REQUIRED',\n AUDIT_REQUEST_TOO_LARGE: 'AUDIT_REQUEST_TOO_LARGE',\n AUDIT_INVALID_JSON: 'AUDIT_INVALID_JSON',\n AUDIT_INVALID_CREDENTIAL: 'AUDIT_INVALID_CREDENTIAL',\n AUDIT_RATE_LIMITED: 'AUDIT_RATE_LIMITED',\n AUDIT_INVALID_SUBMISSION: 'AUDIT_INVALID_SUBMISSION',\n AUDIT_INTERNAL_ERROR: 'AUDIT_INTERNAL_ERROR',\n} as const;\n\n/**\n * Audit Protocol Error Codes\n *\n * The `AUDIT_ERROR_CODES` vocabulary of `@kya-os/mcp`, relayed verbatim as\n * `error.code` by POST /api/v1/audit/entries when the recorder throws an\n * `AuditProtocolError`. This package does not depend on `@kya-os/mcp`, so\n * the strings are copied by hand; a lock test in apps/web asserts the two\n * sets stay equal. The route maps each code to one fixed status. For codes\n * at 500 and above the route replaces the protocol message with a generic\n * one, so ERROR_MESSAGES carries that generic text; below 500 the wire\n * message is protocol-owned and ERROR_MESSAGES is descriptive only.\n */\nexport const AUDIT_PROTOCOL_ERRORS = {\n AUDIT_UNAUTHORIZED_SUBMISSION: 'AUDIT_UNAUTHORIZED_SUBMISSION',\n AUDIT_LEDGER_MISMATCH: 'AUDIT_LEDGER_MISMATCH',\n AUDIT_EPOCH_MISMATCH: 'AUDIT_EPOCH_MISMATCH',\n AUDIT_EVENT_ID_CONFLICT: 'AUDIT_EVENT_ID_CONFLICT',\n AUDIT_INVALID_EVENT: 'AUDIT_INVALID_EVENT',\n AUDIT_EVIDENCE_FAILURE: 'AUDIT_EVIDENCE_FAILURE',\n AUDIT_EVIDENCE_INTEGRITY: 'AUDIT_EVIDENCE_INTEGRITY',\n AUDIT_INVALID_CONFIGURATION: 'AUDIT_INVALID_CONFIGURATION',\n AUDIT_JOURNAL_FAILURE: 'AUDIT_JOURNAL_FAILURE',\n AUDIT_APPEND_CONFLICT_EXHAUSTED: 'AUDIT_APPEND_CONFLICT_EXHAUSTED',\n AUDIT_EVIDENCE_LEGAL_HOLD: 'AUDIT_EVIDENCE_LEGAL_HOLD',\n AUDIT_EVIDENCE_ACCESS_DENIED: 'AUDIT_EVIDENCE_ACCESS_DENIED',\n AUDIT_CHECKPOINT_INVALID: 'AUDIT_CHECKPOINT_INVALID',\n AUDIT_CHECKPOINT_ROLLBACK: 'AUDIT_CHECKPOINT_ROLLBACK',\n AUDIT_CHECKPOINT_CONFLICT: 'AUDIT_CHECKPOINT_CONFLICT',\n AUDIT_CHECKPOINT_PUBLICATION_FAILED: 'AUDIT_CHECKPOINT_PUBLICATION_FAILED',\n AUDIT_PROJECTION_CONFLICT: 'AUDIT_PROJECTION_CONFLICT',\n AUDIT_MIRROR_VERIFICATION_FAILED: 'AUDIT_MIRROR_VERIFICATION_FAILED',\n AUDIT_MIRROR_CONTINUITY_FAILED: 'AUDIT_MIRROR_CONTINUITY_FAILED',\n AUDIT_MIRROR_OUT_OF_ORDER: 'AUDIT_MIRROR_OUT_OF_ORDER',\n} as const;\n\n/**\n * KYA-OS Native HTTP Protocol Error Codes (`kyaos/*`)\n *\n * Emitted by the /api/v1/bouncer/native-http/* handlers and the managed\n * native issuer and propagation-proof services. The wire body is\n * `{ error: \"<code>\" }` with no message, so ERROR_MESSAGES text for these\n * codes is documentation only. Keyed by value with a KYAOS_SLASH_ prefix\n * because the wire strings carry a `/`.\n */\nexport const KYAOS_PROTOCOL_ERRORS = {\n KYAOS_SLASH_ISSUER_FORBIDDEN: 'kyaos/issuer-forbidden',\n KYAOS_SLASH_PROFILE_VIOLATION: 'kyaos/profile-violation',\n KYAOS_SLASH_INVALID_SESSION: 'kyaos/invalid-session',\n KYAOS_SLASH_SESSION_CONFLICT: 'kyaos/session-conflict',\n KYAOS_SLASH_PICKUP_EXPIRED: 'kyaos/pickup-expired',\n KYAOS_SLASH_SCOPE_INSUFFICIENT: 'kyaos/scope-insufficient',\n KYAOS_SLASH_CONSENT_REQUIRED: 'kyaos/consent-required',\n KYAOS_SLASH_PICKUP_PINNED: 'kyaos/pickup-pinned',\n KYAOS_SLASH_AUTHORIZATION_HOST_UNAVAILABLE: 'kyaos/authorization-host-unavailable',\n KYAOS_SLASH_CHAIN_BROKEN: 'kyaos/chain-broken',\n KYAOS_SLASH_DELEGATION_REVOKED: 'kyaos/delegation-revoked',\n KYAOS_SLASH_EXPIRED: 'kyaos/expired',\n KYAOS_SLASH_HOLDER_MISMATCH: 'kyaos/holder-mismatch',\n KYAOS_SLASH_INVALID_SIGNATURE: 'kyaos/invalid-signature',\n KYAOS_SLASH_SESSION_MISMATCH: 'kyaos/session-mismatch',\n KYAOS_SLASH_POLICY_UNAVAILABLE: 'kyaos/policy-unavailable',\n} as const;\n\n/**\n * Gateway Vault Resolve Error Codes\n *\n * Emitted by POST /api/v1/gateway/vault/{projectId}/resolve, and five of them\n * (INVALID_ASSERTION, INVALID_SIGNATURE, ASSERTION_EXPIRED, ASSERTION_REPLAYED,\n * PROJECT_MISMATCH) also by POST /api/v1/vault/{projectId}/resolve, which\n * verifies through the same shared verifier and nonce store\n * (apps/web/lib/vault/). Every emission site passes an explicit message and\n * status, so registering them changes no wire behaviour.\n */\nexport const GATEWAY_VAULT_ERRORS = {\n MALFORMED_REQUEST_BODY: 'MALFORMED_REQUEST_BODY',\n GATEWAY_NOT_CONFIGURED: 'GATEWAY_NOT_CONFIGURED',\n INVALID_ASSERTION: 'INVALID_ASSERTION',\n INVALID_SIGNATURE: 'INVALID_SIGNATURE',\n ASSERTION_EXPIRED: 'ASSERTION_EXPIRED',\n ASSERTION_REPLAYED: 'ASSERTION_REPLAYED',\n PROJECT_MISMATCH: 'PROJECT_MISMATCH',\n ISSUER_MISMATCH: 'ISSUER_MISMATCH',\n USER_DID_MISMATCH: 'USER_DID_MISMATCH',\n TOOL_NAME_MISMATCH: 'TOOL_NAME_MISMATCH',\n SESSION_ID_MISMATCH: 'SESSION_ID_MISMATCH',\n NOT_AUTHORIZED: 'NOT_AUTHORIZED',\n CREDENTIALS_NOT_CONFIGURED: 'CREDENTIALS_NOT_CONFIGURED',\n OAUTH_EXPIRED: 'OAUTH_EXPIRED',\n} as const;\n\n/**\n * Vault Resolve Error Codes\n *\n * The one code unique to POST /api/v1/vault/{projectId}/resolve. The rest of\n * its surface reuses GATEWAY_VAULT_ERRORS, BARE_ERRORS and INTERNAL_ERRORS by\n * key.\n */\nexport const VAULT_ERRORS = {\n NO_AGENT_KEY: 'NO_AGENT_KEY',\n} as const;\n\n/**\n * All Error Codes\n */\nexport const ERROR_CODES = {\n ...AUTH_ERRORS,\n ...VALIDATION_ERRORS,\n ...DETECTION_ERRORS,\n ...RATE_LIMIT_ERRORS,\n ...PERMISSION_ERRORS,\n ...NETWORK_ERRORS,\n ...INTERNAL_ERRORS,\n ...SESSION_ERRORS,\n ...PIXEL_ERRORS,\n ...API_ERRORS,\n ...BILLING_ERRORS,\n ...RESOURCE_ERRORS,\n ...POLICY_ERRORS,\n ...ANALYTICS_ERRORS,\n ...DEPLOY_ERRORS,\n ...BARE_ERRORS,\n ...LOWERCASE_ERRORS,\n ...BOUNCER_LOWERCASE_ERRORS,\n ...OAUTH_LOWERCASE_ERRORS,\n ...BOUNCER_UPPERCASE_ERRORS,\n ...AUDIT_ERRORS,\n ...AUDIT_PROTOCOL_ERRORS,\n ...KYAOS_PROTOCOL_ERRORS,\n ...GATEWAY_VAULT_ERRORS,\n ...VAULT_ERRORS,\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * Error Messages\n */\nexport const ERROR_MESSAGES: Record<ErrorCode, string> = {\n // Authentication\n [AUTH_ERRORS.INVALID_API_KEY]: 'The provided API key is invalid',\n [AUTH_ERRORS.EXPIRED_API_KEY]: 'The API key has expired',\n [AUTH_ERRORS.INVALID_TOKEN]: 'The provided token is invalid',\n [AUTH_ERRORS.EXPIRED_TOKEN]: 'The token has expired',\n [AUTH_ERRORS.MISSING_CREDENTIALS]: 'Authentication credentials are required',\n [AUTH_ERRORS.MANAGEMENT_TOKEN_NOT_ACCEPTED]:\n 'Management session tokens are accepted only by /api/cli/management routes',\n [AUTH_ERRORS.UNAUTHORIZED]: 'You are not authorized to perform this action',\n [AUTH_ERRORS.INVALID_PIXEL_ID]: 'The provided pixel ID is invalid',\n [AUTH_ERRORS.INVALID_SECRET_KEY]: 'The provided secret key is invalid',\n\n // Validation\n [VALIDATION_ERRORS.INVALID_REQUEST]: 'The request is invalid',\n [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 'A required field is missing',\n [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 'Field type is invalid',\n [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 'Field value is invalid',\n [VALIDATION_ERRORS.FIELD_TOO_LONG]: 'Field value exceeds maximum length',\n [VALIDATION_ERRORS.FIELD_TOO_SHORT]: 'Field value is below minimum length',\n [VALIDATION_ERRORS.INVALID_EMAIL]: 'Invalid email address format',\n [VALIDATION_ERRORS.INVALID_URL]: 'Invalid URL format',\n [VALIDATION_ERRORS.INVALID_UUID]: 'Invalid UUID format',\n [VALIDATION_ERRORS.INVALID_IP_ADDRESS]: 'Invalid IP address format',\n [VALIDATION_ERRORS.INVALID_USER_AGENT]: 'Invalid or missing user agent',\n [VALIDATION_ERRORS.BAD_REQUEST]: 'Bad request',\n [VALIDATION_ERRORS.INVALID_START_DATE]: 'Invalid request data',\n [VALIDATION_ERRORS.INVALID_END_DATE]: 'Invalid request data',\n [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 'Invalid request data',\n\n // Detection\n [DETECTION_ERRORS.DETECTION_FAILED]: 'Agent detection failed',\n [DETECTION_ERRORS.INSUFFICIENT_DATA]: 'Insufficient data for detection',\n [DETECTION_ERRORS.PATTERN_MATCH_FAILED]: 'Pattern matching failed',\n [DETECTION_ERRORS.WASM_NOT_LOADED]: 'WASM module is not loaded',\n [DETECTION_ERRORS.WASM_EXECUTION_FAILED]: 'WASM execution failed',\n [DETECTION_ERRORS.CONFIDENCE_BELOW_THRESHOLD]: 'Detection confidence below threshold',\n [DETECTION_ERRORS.SIGNATURE_VERIFICATION_FAILED]: 'Signature verification failed',\n\n // Rate Limiting\n [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 'Rate limit exceeded',\n [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 'Burst limit exceeded',\n [RATE_LIMIT_ERRORS.DAILY_LIMIT_EXCEEDED]: 'Daily request limit exceeded',\n [RATE_LIMIT_ERRORS.MONTHLY_LIMIT_EXCEEDED]: 'Monthly request limit exceeded',\n [RATE_LIMIT_ERRORS.CONCURRENT_LIMIT_EXCEEDED]: 'Concurrent request limit exceeded',\n [RATE_LIMIT_ERRORS.QUOTA_EXCEEDED]: 'Account quota exceeded',\n [RATE_LIMIT_ERRORS.RATE_LIMITED]: 'Too many requests',\n\n // Permissions\n [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 'Insufficient permissions',\n [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 'Resource not found',\n [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 'Access to resource denied',\n [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 'Operation not allowed',\n [PERMISSION_ERRORS.PROJECT_ACCESS_DENIED]: 'Project access denied',\n [PERMISSION_ERRORS.PIXEL_ACCESS_DENIED]: 'Pixel access denied',\n [PERMISSION_ERRORS.FORBIDDEN]: 'Access denied',\n [PERMISSION_ERRORS.PERMISSION_DENIED]: 'Permission denied',\n\n // Network\n [NETWORK_ERRORS.CONNECTION_FAILED]: 'Connection failed',\n [NETWORK_ERRORS.TIMEOUT]: 'Request timeout',\n [NETWORK_ERRORS.DNS_RESOLUTION_FAILED]: 'DNS resolution failed',\n [NETWORK_ERRORS.SSL_ERROR]: 'SSL/TLS error',\n [NETWORK_ERRORS.PROXY_ERROR]: 'Proxy error',\n [NETWORK_ERRORS.UPSTREAM_ERROR]: 'Upstream service error',\n\n // Internal\n [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 'Internal server error',\n [INTERNAL_ERRORS.DATABASE_ERROR]: 'Database error',\n [INTERNAL_ERRORS.CACHE_ERROR]: 'Cache error',\n [INTERNAL_ERRORS.CONFIGURATION_ERROR]: 'Configuration error',\n [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 'Initialization error',\n [INTERNAL_ERRORS.PROCESSING_ERROR]: 'Processing error',\n [INTERNAL_ERRORS.UNKNOWN_ERROR]: 'An unknown error occurred',\n [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]:\n 'A dependency is temporarily unavailable. Retry shortly.',\n [INTERNAL_ERRORS.TRANSACTION_FAILED]:\n 'The deletion failed because of a database error. Nothing was deleted.',\n [INTERNAL_ERRORS.DELETE_FAILED]: 'Failed to delete project',\n [INTERNAL_ERRORS.PARTITION_RETIREMENT_IN_PROGRESS]:\n 'The project data is being archived. Retry shortly.',\n\n // Session\n [SESSION_ERRORS.SESSION_NOT_FOUND]: 'Session not found',\n [SESSION_ERRORS.SESSION_EXPIRED]: 'Session has expired',\n [SESSION_ERRORS.SESSION_INVALID]: 'Session is invalid',\n [SESSION_ERRORS.SESSION_CREATION_FAILED]: 'Failed to create session',\n [SESSION_ERRORS.SESSION_UPDATE_FAILED]: 'Failed to update session',\n [SESSION_ERRORS.SESSION_STORAGE_ERROR]: 'Session storage error',\n [SESSION_ERRORS.MAX_SESSIONS_EXCEEDED]: 'Maximum sessions exceeded',\n\n // Pixel\n [PIXEL_ERRORS.PIXEL_NOT_FOUND]: 'Pixel not found',\n [PIXEL_ERRORS.PIXEL_DISABLED]: 'Pixel is disabled',\n [PIXEL_ERRORS.PIXEL_CONFIGURATION_ERROR]: 'Pixel configuration error',\n [PIXEL_ERRORS.PIXEL_DOMAIN_NOT_ALLOWED]: 'Domain not allowed for this pixel',\n [PIXEL_ERRORS.PIXEL_PATH_SKIPPED]: 'Path is configured to be skipped',\n [PIXEL_ERRORS.PIXEL_EVENT_INVALID]: 'Invalid pixel event',\n [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 'Event batch exceeds maximum size',\n [PIXEL_ERRORS.MISSING_PIXEL_ID]: 'Project ID is required',\n [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 'Failed to store detection data',\n [PIXEL_ERRORS.PIXEL_CREATION_FAILED]: 'Failed to create pixel for project',\n\n // API\n [API_ERRORS.ENDPOINT_NOT_FOUND]: 'API endpoint not found',\n [API_ERRORS.METHOD_NOT_ALLOWED]: 'HTTP method not allowed',\n [API_ERRORS.VERSION_NOT_SUPPORTED]: 'API version not supported',\n [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 'Content type not supported',\n [API_ERRORS.RESPONSE_TOO_LARGE]: 'Response exceeds maximum size',\n [API_ERRORS.REQUEST_TOO_LARGE]: 'Request exceeds maximum size',\n [API_ERRORS.ENDPOINT_RETIRED]: 'This endpoint has been retired',\n\n // Billing\n [BILLING_ERRORS.LIMIT_EXCEEDED]: 'Billing limit exceeded',\n [BILLING_ERRORS.BILLING_SUSPENDED]: 'Account billing suspended',\n [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 'Account in billing grace period',\n\n // Resources\n [RESOURCE_ERRORS.CONFLICT]: 'Resource conflict',\n [RESOURCE_ERRORS.PROJECT_NOT_FOUND]: 'Project not found',\n [RESOURCE_ERRORS.REVIEW_REQUIRED]:\n 'Deploy requires explicit confirmation of the consequential writes it will perform.',\n\n // Policy\n [POLICY_ERRORS.POLICY_FETCH_FAILED]: 'Failed to fetch policy',\n\n // Analytics\n [ANALYTICS_ERRORS.INVALID_PERIOD]: 'Period must be one of: hour, day, week, month',\n [ANALYTICS_ERRORS.ANALYTICS_FETCH_ERROR]: 'Failed to retrieve analytics data',\n [ANALYTICS_ERRORS.STATS_FETCH_ERROR]: 'Failed to retrieve stats',\n\n // Deploy\n [DEPLOY_ERRORS.MISSING_USER_IDENTIFIER]:\n 'Either userEmail or userGithubId is required to identify the user',\n [DEPLOY_ERRORS.USER_NOT_FOUND]:\n 'User not found in Checkpoint. The user must have an existing Checkpoint account to deploy.',\n [DEPLOY_ERRORS.NO_ORGANIZATION]:\n 'User has no organization in Checkpoint. Please complete onboarding first at https://kya.vouched.id',\n [DEPLOY_ERRORS.DEPLOY_FAILED]: 'Deployment failed',\n [DEPLOY_ERRORS.WFP_NOT_CONFIGURED]: 'Managed hosting is not configured',\n [DEPLOY_ERRORS.NATIVE_ISSUER_PROVISIONING_BUSY]:\n 'Native issuer provisioning is busy or temporarily unavailable; retry deployment',\n [DEPLOY_ERRORS.NATIVE_ISSUER_PROVISIONING_FAILED]:\n 'Native issuer provisioning failed; deployment retained for retry',\n\n // Bare (un-prefixed, shared across pixel/openclaw/deploy/shopify/bouncer/analytics)\n [BARE_ERRORS.BARE_VALIDATION_ERROR]: 'Invalid request data',\n [BARE_ERRORS.BARE_INTERNAL_ERROR]: 'Internal server error',\n [BARE_ERRORS.BARE_INVALID_REQUEST]: 'Invalid JSON body',\n [BARE_ERRORS.BARE_INVALID_JSON]: 'Request body must be valid JSON',\n [BARE_ERRORS.BARE_INVALID_START_DATE]:\n 'Invalid startDate format. Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)',\n [BARE_ERRORS.BARE_INVALID_END_DATE]:\n 'Invalid endDate format. Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)',\n [BARE_ERRORS.BARE_INVALID_DATE_RANGE]: 'startDate must be before endDate',\n [BARE_ERRORS.BARE_INVALID_DATE]:\n 'Invalid date format. Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)',\n [BARE_ERRORS.BARE_UNKNOWN_ERROR]: 'Failed to delete project',\n [BARE_ERRORS.BARE_NOT_FOUND]: 'Not found',\n [BARE_ERRORS.BARE_FORBIDDEN]: 'Forbidden',\n\n // Lowercase (kya-os events wire format)\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 'Request body must be valid JSON',\n [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 'Invalid request body',\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_CURSOR]:\n 'The cursor was not issued by this feed for this project; read from the start',\n\n // Bouncer (lower-case wire format)\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROJECT]: 'API key is not associated with a project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_AGENT_DID]: 'agent_did query parameter is required',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_CONFIGURED]: 'Bouncer is not configured for this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_CREDENTIAL_CONFIG]:\n 'Credential provider missing required fields: authEndpoint and responseFields',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_NOT_FOUND]: 'Project not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_MISMATCH]:\n 'API key does not have access to this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_DELEGATION_ID]: 'Delegation ID is required',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_TOKEN]: 'Invalid or expired delegation token',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_MISMATCH]: 'Delegation ID does not match token',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_TOKENS_NOT_FOUND]:\n 'OAuth tokens not available for this delegation',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DECRYPTION_ERROR]: 'Failed to decrypt OAuth tokens',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS]: 'At least one proof is required',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_BATCH_TOO_LARGE]: 'Maximum batch size is 100 proofs',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS_PROCESSED]:\n 'No proofs were processed. This indicates a server error.',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_ALL_PROOFS_REJECTED]:\n 'All proofs were rejected due to validation failures',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_UNAUTHORIZED]: 'API key is not associated with a project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_FORBIDDEN]: 'API key does not have access to this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_FOUND]: 'Session not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_CONFIG_NOT_FOUND]: 'Bouncer config not found for project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AGENT_DENIED]: 'Agent is on the deny list',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_NOT_FOUND]: 'Delegation not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_SESSION_NOT_FOUND]: 'Session not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROOF_VALIDATION_ERROR]: 'Proof validation failed',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INSUFFICIENT_SCOPES]: 'Missing required scopes',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_VALIDATION_ERROR]: 'Delegation validation failed',\n [BOUNCER_LOWERCASE_ERRORS.GRANT_PREDATES_ISSUANCE_CORE]:\n 'The grant predates the issuance core; authorize again',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_HTTP_REGISTRATION]:\n 'Invalid or unsupported native HTTP registration',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_MISMATCH]:\n 'The registered tool protection revision is not the one served to this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_GRACE_UNAVAILABLE]:\n 'The audit record for a registration on the previous tool protection revision could not be written; retry the registration',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AUTHORIZATION_HOST_UNAVAILABLE]:\n 'Authorization host is a project deployment that cannot currently serve consent',\n\n // Delegation OAuth (lower-case wire format)\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_REQUEST]: 'Invalid request body',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_UNSUPPORTED_GRANT_TYPE]:\n 'Only authorization_code grant type is supported',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_GRANT]: 'Invalid or expired authorization code',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_DELEGATION]: 'Delegation not found or inactive',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INTERNAL_ERROR]:\n 'An internal error occurred during token exchange',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_STATE]:\n 'Restart authorization from the requesting agent.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_TRANSACTION]:\n 'Restart authorization from the requesting agent.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_UNAVAILABLE]:\n 'OAuth is temporarily unavailable. Please request a new authorization link.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_NOT_CONFIGURED]:\n 'OAuth provider is not configured. Please configure OAuth in the dashboard.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_CONFIGURATION_UNSUPPORTED]:\n 'The selected provider is not configured for the platform delegation callback.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_PROVIDER_CONFIG]:\n 'OAuth provider is missing authorization endpoint',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_RATE_LIMIT_EXCEEDED]:\n 'Too many requests. Please try again later.',\n\n // Bouncer (upper-case wire format)\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_BODY]: 'Invalid JSON in request body',\n [BOUNCER_UPPERCASE_ERRORS.MCPI_CONFIG_NOT_FOUND]: 'KYA-OS configuration not found',\n [BOUNCER_UPPERCASE_ERRORS.CONSENT_CONFIG_NOT_FOUND]:\n 'Consent configuration not found for this project',\n [BOUNCER_UPPERCASE_ERRORS.PROJECT_LOOKUP_FAILED]: 'Failed to lookup project',\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_VALIDATION_ERROR]: 'Configuration validation failed',\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_FETCH_FAILED]: 'Failed to fetch configuration',\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_UPDATE_FAILED]: 'Failed to update configuration',\n [BOUNCER_UPPERCASE_ERRORS.DEPLOYMENT_NOT_FOUND]: 'No active deployment for this project',\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_ID]: 'Invalid delegation request ID format',\n [BOUNCER_UPPERCASE_ERRORS.DELEGATION_REQUEST_NOT_FOUND]:\n 'No delegation request exists for this ID. It may have expired, or it was never issued.',\n\n // Audit ingest\n [AUDIT_ERRORS.AUDIT_CREDENTIAL_REQUIRED]: 'A source-bound audit ingest credential is required',\n [AUDIT_ERRORS.AUDIT_REQUEST_TOO_LARGE]: 'Audit submission exceeds 6291456 bytes',\n [AUDIT_ERRORS.AUDIT_INVALID_JSON]: 'Request body must be valid JSON',\n [AUDIT_ERRORS.AUDIT_INVALID_CREDENTIAL]: 'Invalid audit ingest credential',\n [AUDIT_ERRORS.AUDIT_RATE_LIMITED]: 'Audit ingest rate limit exceeded',\n [AUDIT_ERRORS.AUDIT_INVALID_SUBMISSION]: 'Invalid audit recorder submission envelope',\n [AUDIT_ERRORS.AUDIT_INTERNAL_ERROR]: 'Audit recorder is temporarily unavailable',\n\n // Audit protocol (relayed from @kya-os/mcp). Below 500 the wire message is\n // protocol-owned; these texts describe the failure class.\n [AUDIT_PROTOCOL_ERRORS.AUDIT_UNAUTHORIZED_SUBMISSION]:\n 'Audit producer is not authorized for this ledger',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_LEDGER_MISMATCH]:\n 'Submission belongs to a different audit ledger than the credential binding',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EPOCH_MISMATCH]: 'Submission belongs to a different ledger epoch',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVENT_ID_CONFLICT]:\n 'Producer event identity was reused with different content',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_EVENT]: 'Audit event failed protocol validation',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_FAILURE]:\n 'Submitted evidence could not be matched or persisted',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_INTEGRITY]:\n 'Evidence ciphertext or metadata digest does not verify',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_CONFIGURATION]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_JOURNAL_FAILURE]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_APPEND_CONFLICT_EXHAUSTED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_LEGAL_HOLD]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_ACCESS_DENIED]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_INVALID]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_ROLLBACK]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_CONFLICT]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_PUBLICATION_FAILED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_PROJECTION_CONFLICT]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_VERIFICATION_FAILED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_CONTINUITY_FAILED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_OUT_OF_ORDER]: 'Audit recorder is temporarily unavailable',\n\n // KYA-OS native HTTP protocol (kyaos/*). The wire carries no message;\n // these texts are documentation only.\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_ISSUER_FORBIDDEN]:\n 'The caller is not an authorized native issuer for this project',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PROFILE_VIOLATION]:\n 'The request does not conform to the KYA-OS native HTTP profile',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SESSION]:\n 'The session is unknown, expired, or not owned by this project',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_CONFLICT]:\n 'The session is already bound to a different registration or grant',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_EXPIRED]: 'The pickup anchor has expired',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SCOPE_INSUFFICIENT]:\n 'The requested scopes exceed what the session allows',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CONSENT_REQUIRED]:\n 'Consent terms must be accepted before a delegation can be issued',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_PINNED]:\n 'The pickup anchor is pinned to a different holder key',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_AUTHORIZATION_HOST_UNAVAILABLE]:\n 'The authorization host cannot currently serve this request',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CHAIN_BROKEN]: 'The propagation chain could not be verified',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_DELEGATION_REVOKED]: 'The delegation has been revoked',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_EXPIRED]: 'The credential or proof has expired',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_HOLDER_MISMATCH]:\n 'The holder does not match the delegation or grant',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SIGNATURE]: 'The signature could not be verified',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_MISMATCH]:\n 'The session does not match the delegation or proof',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_POLICY_UNAVAILABLE]:\n 'The policy revision is currently unavailable',\n\n // Gateway vault resolve (five codes shared with the API-key vault resolve route)\n [GATEWAY_VAULT_ERRORS.MALFORMED_REQUEST_BODY]: 'Malformed JSON body',\n [GATEWAY_VAULT_ERRORS.GATEWAY_NOT_CONFIGURED]:\n 'Gateway public key or trusted DID not configured for this project',\n [GATEWAY_VAULT_ERRORS.INVALID_ASSERTION]: 'Assertion JWT must have 3 parts',\n [GATEWAY_VAULT_ERRORS.INVALID_SIGNATURE]: 'Assertion signature verification failed',\n [GATEWAY_VAULT_ERRORS.ASSERTION_EXPIRED]: 'Assertion is expired or outside the allowed window',\n [GATEWAY_VAULT_ERRORS.ASSERTION_REPLAYED]: 'Assertion nonce has already been used',\n [GATEWAY_VAULT_ERRORS.PROJECT_MISMATCH]: 'Assertion projectId does not match route',\n [GATEWAY_VAULT_ERRORS.ISSUER_MISMATCH]: 'Assertion issuer does not match trusted gateway DID',\n [GATEWAY_VAULT_ERRORS.USER_DID_MISMATCH]: 'Assertion userDid does not match request body userDid',\n [GATEWAY_VAULT_ERRORS.TOOL_NAME_MISMATCH]:\n 'Assertion toolName does not match request body toolName',\n [GATEWAY_VAULT_ERRORS.SESSION_ID_MISMATCH]:\n 'Assertion sessionId does not match request body sessionId',\n [GATEWAY_VAULT_ERRORS.NOT_AUTHORIZED]: 'User is not a member of this organization',\n [GATEWAY_VAULT_ERRORS.CREDENTIALS_NOT_CONFIGURED]: 'Connect your credentials in Checkpoint',\n [GATEWAY_VAULT_ERRORS.OAUTH_EXPIRED]: 'Provider token expired; user must reconnect',\n\n // Vault resolve\n [VAULT_ERRORS.NO_AGENT_KEY]: 'No agent deployment found for this project',\n};\n\n/**\n * HTTP Status Codes for Errors\n */\nexport const ERROR_STATUS_CODES: Partial<Record<ErrorCode, number>> = {\n // 200 OK (billing grace period is a soft warning, not a failure)\n [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 200,\n\n // 400 Bad Request\n [VALIDATION_ERRORS.INVALID_REQUEST]: 400,\n [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 400,\n [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 400,\n [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 400,\n [VALIDATION_ERRORS.BAD_REQUEST]: 400,\n [VALIDATION_ERRORS.INVALID_START_DATE]: 400,\n [VALIDATION_ERRORS.INVALID_END_DATE]: 400,\n [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 400,\n [PIXEL_ERRORS.MISSING_PIXEL_ID]: 400,\n [ANALYTICS_ERRORS.INVALID_PERIOD]: 400,\n [DEPLOY_ERRORS.MISSING_USER_IDENTIFIER]: 400,\n [DEPLOY_ERRORS.NO_ORGANIZATION]: 400,\n [BARE_ERRORS.BARE_VALIDATION_ERROR]: 400,\n [BARE_ERRORS.BARE_INVALID_REQUEST]: 400,\n [BARE_ERRORS.BARE_INVALID_JSON]: 400,\n [BARE_ERRORS.BARE_INVALID_START_DATE]: 400,\n [BARE_ERRORS.BARE_INVALID_END_DATE]: 400,\n [BARE_ERRORS.BARE_INVALID_DATE_RANGE]: 400,\n [BARE_ERRORS.BARE_INVALID_DATE]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_CURSOR]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROJECT]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_AGENT_DID]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_CONFIGURED]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_CREDENTIAL_CONFIG]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_DELEGATION_ID]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_BATCH_TOO_LARGE]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS_PROCESSED]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_ALL_PROOFS_REJECTED]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROOF_VALIDATION_ERROR]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_VALIDATION_ERROR]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_HTTP_REGISTRATION]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_REQUEST]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_UNSUPPORTED_GRANT_TYPE]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_STATE]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_TRANSACTION]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_NOT_CONFIGURED]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_CONFIGURATION_UNSUPPORTED]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_PROVIDER_CONFIG]: 400,\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_BODY]: 400,\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_VALIDATION_ERROR]: 400,\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_ID]: 400,\n [AUDIT_ERRORS.AUDIT_INVALID_JSON]: 400,\n [AUDIT_ERRORS.AUDIT_INVALID_SUBMISSION]: 400,\n [GATEWAY_VAULT_ERRORS.MALFORMED_REQUEST_BODY]: 400,\n [GATEWAY_VAULT_ERRORS.INVALID_ASSERTION]: 400,\n\n // 401 Unauthorized\n [AUTH_ERRORS.INVALID_API_KEY]: 401,\n [AUTH_ERRORS.EXPIRED_API_KEY]: 401,\n [AUTH_ERRORS.INVALID_TOKEN]: 401,\n [AUTH_ERRORS.EXPIRED_TOKEN]: 401,\n [AUTH_ERRORS.MISSING_CREDENTIALS]: 401,\n [AUTH_ERRORS.MANAGEMENT_TOKEN_NOT_ACCEPTED]: 401,\n [AUTH_ERRORS.UNAUTHORIZED]: 401,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_TOKEN]: 401,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_UNAUTHORIZED]: 401,\n [AUDIT_ERRORS.AUDIT_CREDENTIAL_REQUIRED]: 401,\n [AUDIT_ERRORS.AUDIT_INVALID_CREDENTIAL]: 401,\n // Both vault resolve routes verify through one shared verifier, so a failed\n // signature is a 401 on each.\n [GATEWAY_VAULT_ERRORS.INVALID_SIGNATURE]: 401,\n\n // 402 Payment Required\n [BILLING_ERRORS.LIMIT_EXCEEDED]: 402,\n [BILLING_ERRORS.BILLING_SUSPENDED]: 402,\n\n // 403 Forbidden\n [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 403,\n [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 403,\n [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 403,\n [PERMISSION_ERRORS.FORBIDDEN]: 403,\n [PERMISSION_ERRORS.PERMISSION_DENIED]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_MISMATCH]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_MISMATCH]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_FORBIDDEN]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AGENT_DENIED]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INSUFFICIENT_SCOPES]: 403,\n [BOUNCER_LOWERCASE_ERRORS.GRANT_PREDATES_ISSUANCE_CORE]: 409,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_MISMATCH]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_UNAUTHORIZED_SUBMISSION]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_ISSUER_FORBIDDEN]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SCOPE_INSUFFICIENT]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CONSENT_REQUIRED]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_PINNED]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CHAIN_BROKEN]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_DELEGATION_REVOKED]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_HOLDER_MISMATCH]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SIGNATURE]: 403,\n [BARE_ERRORS.BARE_FORBIDDEN]: 403,\n [GATEWAY_VAULT_ERRORS.ASSERTION_EXPIRED]: 403,\n [GATEWAY_VAULT_ERRORS.ASSERTION_REPLAYED]: 403,\n [GATEWAY_VAULT_ERRORS.PROJECT_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.ISSUER_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.USER_DID_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.TOOL_NAME_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.SESSION_ID_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.NOT_AUTHORIZED]: 403,\n [GATEWAY_VAULT_ERRORS.OAUTH_EXPIRED]: 403,\n\n // 404 Not Found\n [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 404,\n [API_ERRORS.ENDPOINT_NOT_FOUND]: 404,\n [API_ERRORS.ENDPOINT_RETIRED]: 410,\n [PIXEL_ERRORS.PIXEL_NOT_FOUND]: 404,\n [SESSION_ERRORS.SESSION_NOT_FOUND]: 404,\n [DEPLOY_ERRORS.USER_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_TOKENS_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_CONFIG_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_SESSION_NOT_FOUND]: 404,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_DELEGATION]: 404,\n [BOUNCER_UPPERCASE_ERRORS.MCPI_CONFIG_NOT_FOUND]: 404,\n [BOUNCER_UPPERCASE_ERRORS.CONSENT_CONFIG_NOT_FOUND]: 404,\n [BOUNCER_UPPERCASE_ERRORS.DEPLOYMENT_NOT_FOUND]: 404,\n [BOUNCER_UPPERCASE_ERRORS.DELEGATION_REQUEST_NOT_FOUND]: 404,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SESSION]: 404,\n [BARE_ERRORS.BARE_NOT_FOUND]: 404,\n [GATEWAY_VAULT_ERRORS.CREDENTIALS_NOT_CONFIGURED]: 404,\n [VAULT_ERRORS.NO_AGENT_KEY]: 404,\n\n // 405 Method Not Allowed\n [API_ERRORS.METHOD_NOT_ALLOWED]: 405,\n\n // 409 Conflict\n [RESOURCE_ERRORS.CONFLICT]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_LEDGER_MISMATCH]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EPOCH_MISMATCH]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVENT_ID_CONFLICT]: 409,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_CONFLICT]: 409,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_MISMATCH]: 409,\n\n // 410 Gone\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_EXPIRED]: 410,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_EXPIRED]: 410,\n\n // NOTE: RESOURCE_ERRORS.PROJECT_NOT_FOUND deliberately has no entry here.\n // The pixel API emits it with 400, while enforce and the policy\n // middleware emit it with 404. There is no single correct status, so it\n // stays unpinned and callers set their own status per surface. Locked by\n // a test in __tests__/errors.test.ts.\n\n // NOTE: DEPLOY_ERRORS.DEPLOY_FAILED, WFP_NOT_CONFIGURED,\n // NATIVE_ISSUER_PROVISIONING_BUSY and NATIVE_ISSUER_PROVISIONING_FAILED\n // deliberately have no entry here. They are computed by the managed\n // deploy service, and the deploy route ships every service code at 400\n // today even though WFP_NOT_CONFIGURED is a server misconfiguration and\n // DEPLOY_FAILED an infrastructure failure. No single status is correct,\n // so they stay unpinned and the route owns the status per surface.\n // Locked by a test in __tests__/errors.test.ts.\n\n // NOTE: OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_GRANT deliberately has no\n // entry here. The OAuth token exchange route emits it at 400 for an\n // invalid or expired authorization code and at 403 when the code does\n // not match the agent or project. No single status is correct, so it\n // stays unpinned and the route owns the status per branch. Locked by a\n // test in __tests__/errors.test.ts.\n\n // NOTE: KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PROFILE_VIOLATION deliberately\n // has no entry here. The native HTTP handler emits it at 415 (wrong\n // content type), 413 (body over 64 KiB) and 400 (unparseable or\n // schema-invalid input), and the issuer and propagation services emit it\n // at 403 for pickup, policy and holder-binding violations. No single\n // status is correct, so it stays unpinned and each emitter owns the\n // status. Locked by a test in __tests__/errors.test.ts.\n\n // 413 Payload Too Large\n [API_ERRORS.REQUEST_TOO_LARGE]: 413,\n [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 413,\n [AUDIT_ERRORS.AUDIT_REQUEST_TOO_LARGE]: 413,\n\n // 415 Unsupported Media Type\n [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 415,\n\n // 422 Unprocessable Entity\n [RESOURCE_ERRORS.REVIEW_REQUIRED]: 422,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_EVENT]: 422,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_FAILURE]: 422,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_INTEGRITY]: 422,\n\n // 429 Too Many Requests\n [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.DAILY_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.RATE_LIMITED]: 429,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_RATE_LIMIT_EXCEEDED]: 429,\n [AUDIT_ERRORS.AUDIT_RATE_LIMITED]: 429,\n\n // 500 Internal Server Error\n [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 500,\n [INTERNAL_ERRORS.DATABASE_ERROR]: 500,\n [INTERNAL_ERRORS.PROCESSING_ERROR]: 500,\n [INTERNAL_ERRORS.TRANSACTION_FAILED]: 500,\n [INTERNAL_ERRORS.DELETE_FAILED]: 500,\n [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 500,\n [PIXEL_ERRORS.PIXEL_CREATION_FAILED]: 500,\n [POLICY_ERRORS.POLICY_FETCH_FAILED]: 500,\n [ANALYTICS_ERRORS.ANALYTICS_FETCH_ERROR]: 500,\n [ANALYTICS_ERRORS.STATS_FETCH_ERROR]: 500,\n [BARE_ERRORS.BARE_INTERNAL_ERROR]: 500,\n [BARE_ERRORS.BARE_UNKNOWN_ERROR]: 500,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DECRYPTION_ERROR]: 500,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INTERNAL_ERROR]: 500,\n [BOUNCER_UPPERCASE_ERRORS.PROJECT_LOOKUP_FAILED]: 500,\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_FETCH_FAILED]: 500,\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_UPDATE_FAILED]: 500,\n [AUDIT_ERRORS.AUDIT_INTERNAL_ERROR]: 500,\n // The audit ingest route's protocolStatus switch falls through to 500 for\n // these ten; pinned explicitly because that is the status it ships.\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_LEGAL_HOLD]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_ACCESS_DENIED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_INVALID]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_ROLLBACK]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_CONFLICT]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_PUBLICATION_FAILED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_PROJECTION_CONFLICT]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_VERIFICATION_FAILED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_CONTINUITY_FAILED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_OUT_OF_ORDER]: 500,\n [GATEWAY_VAULT_ERRORS.GATEWAY_NOT_CONFIGURED]: 500,\n\n // 502 Bad Gateway\n [NETWORK_ERRORS.UPSTREAM_ERROR]: 502,\n\n // 503 Service Unavailable\n [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 503,\n [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]: 503,\n [INTERNAL_ERRORS.PARTITION_RETIREMENT_IN_PROGRESS]: 503,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AUTHORIZATION_HOST_UNAVAILABLE]: 503,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_GRACE_UNAVAILABLE]: 503,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_UNAVAILABLE]: 503,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_CONFIGURATION]: 503,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_JOURNAL_FAILURE]: 503,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_APPEND_CONFLICT_EXHAUSTED]: 503,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_AUTHORIZATION_HOST_UNAVAILABLE]: 503,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_POLICY_UNAVAILABLE]: 503,\n\n // 504 Gateway Timeout\n [NETWORK_ERRORS.TIMEOUT]: 504,\n};\n\n/**\n * Create a standardized error object\n */\nexport function createError(\n code: ErrorCode,\n details?: Record<string, unknown>,\n customMessage?: string\n) {\n return {\n code,\n message: customMessage || ERROR_MESSAGES[code] || 'An error occurred',\n statusCode: ERROR_STATUS_CODES[code] || 500,\n details,\n timestamp: new Date().toISOString(),\n };\n}\n","/**\n * Rate Limits and Plan Limits\n *\n * Defines limits for different subscription plans and API usage\n */\n\nimport { UserPlan } from '../types/entities';\n\n/**\n * Plan-based Rate Limits\n */\nexport const PLAN_RATE_LIMITS: Record<\n UserPlan,\n {\n requestsPerSecond: number;\n requestsPerMinute: number;\n requestsPerHour: number;\n requestsPerDay: number;\n requestsPerMonth: number;\n burstLimit: number;\n concurrentRequests: number;\n }\n> = {\n free: {\n requestsPerSecond: 1,\n requestsPerMinute: 20,\n requestsPerHour: 500,\n requestsPerDay: 1_000,\n requestsPerMonth: 10_000,\n burstLimit: 5,\n concurrentRequests: 2,\n },\n pro: {\n requestsPerSecond: 10,\n requestsPerMinute: 200,\n requestsPerHour: 5_000,\n requestsPerDay: 50_000,\n requestsPerMonth: 1_000_000,\n burstLimit: 20,\n concurrentRequests: 10,\n },\n enterprise: {\n requestsPerSecond: 100,\n requestsPerMinute: 2_000,\n requestsPerHour: 50_000,\n requestsPerDay: -1, // Unlimited\n requestsPerMonth: -1, // Unlimited\n burstLimit: 200,\n concurrentRequests: 100,\n },\n};\n\n/**\n * Plan-based Feature Limits\n */\nexport const PLAN_FEATURE_LIMITS: Record<\n UserPlan,\n {\n projects: number;\n pixelsPerProject: number;\n apiKeys: number;\n teamMembers: number;\n dataRetentionDays: number;\n customDomains: number;\n webhooks: number;\n alertRules: number;\n sessionsTracked: number;\n exportSizeLimit: number; // In MB\n organizations: number;\n }\n> = {\n free: {\n projects: 2,\n pixelsPerProject: 3,\n apiKeys: 2,\n teamMembers: 1,\n dataRetentionDays: 7,\n customDomains: 0,\n webhooks: 0,\n alertRules: 1,\n sessionsTracked: 1_000,\n exportSizeLimit: 10,\n organizations: 1,\n },\n pro: {\n projects: 10,\n pixelsPerProject: 20,\n apiKeys: 20,\n teamMembers: 5,\n dataRetentionDays: 90,\n customDomains: 3,\n webhooks: 5,\n alertRules: 10,\n sessionsTracked: 100_000,\n exportSizeLimit: 100,\n organizations: 5,\n },\n enterprise: {\n projects: -1, // Unlimited\n pixelsPerProject: -1, // Unlimited\n apiKeys: -1, // Unlimited\n teamMembers: -1, // Unlimited\n dataRetentionDays: 365,\n customDomains: -1, // Unlimited\n webhooks: -1, // Unlimited\n alertRules: -1, // Unlimited\n sessionsTracked: -1, // Unlimited\n exportSizeLimit: -1, // Unlimited\n organizations: -1, // Unlimited\n },\n};\n\n/**\n * API Request Limits\n */\nexport const API_REQUEST_LIMITS = {\n maxRequestBodySize: 10 * 1024 * 1024, // 10 MB\n maxResponseBodySize: 50 * 1024 * 1024, // 50 MB\n maxHeadersSize: 8 * 1024, // 8 KB\n maxUrlLength: 2048,\n maxQueryParams: 50,\n maxBatchSize: 100,\n maxFileUploadSize: 100 * 1024 * 1024, // 100 MB\n} as const;\n\n/**\n * Pixel Event Limits\n */\nexport const PIXEL_EVENT_LIMITS = {\n maxEventsPerBatch: 100,\n maxEventSize: 64 * 1024, // 64 KB per event\n maxMetadataSize: 16 * 1024, // 16 KB for metadata\n maxCustomDataFields: 50,\n maxSessionDuration: 24 * 60 * 60 * 1000, // 24 hours in ms\n maxPageViewsPerSession: 1000,\n maxInteractionsPerSession: 10000,\n eventQueueSize: 500,\n flushIntervalMin: 1000, // 1 second\n flushIntervalMax: 60000, // 60 seconds\n} as const;\n\n/**\n * Session Limits\n */\nexport const SESSION_LIMITS = {\n maxSessionsPerUser: 10,\n maxSessionsPerIp: 100,\n sessionTimeoutMin: 60, // 1 minute\n sessionTimeoutMax: 86400, // 24 hours\n idleTimeoutMin: 60, // 1 minute\n idleTimeoutMax: 7200, // 2 hours\n maxSessionDataSize: 64 * 1024, // 64 KB\n maxMetadataFields: 20,\n} as const;\n\n/**\n * Detection Limits\n */\nexport const DETECTION_LIMITS = {\n maxUserAgentLength: 1024,\n maxHeadersCount: 100,\n maxHeaderValueLength: 4096,\n maxIpAddressesPerRequest: 10,\n maxCustomRules: 100,\n maxPatternLength: 500,\n cacheSize: 10000,\n cacheTTL: 3600, // 1 hour in seconds\n maxConcurrentDetections: 1000,\n} as const;\n\n/**\n * Database Limits\n */\nexport const DATABASE_LIMITS = {\n maxQueryResults: 10000,\n maxBulkInsertSize: 1000,\n maxBulkUpdateSize: 500,\n maxBulkDeleteSize: 500,\n maxTransactionDuration: 30000, // 30 seconds\n maxConnectionPoolSize: 20,\n queryTimeout: 10000, // 10 seconds\n} as const;\n\n/**\n * Cache Limits\n */\nexport const CACHE_LIMITS = {\n maxCacheSize: 100 * 1024 * 1024, // 100 MB\n maxCacheEntries: 50000,\n maxKeyLength: 250,\n maxValueSize: 1 * 1024 * 1024, // 1 MB\n defaultTTL: 3600, // 1 hour\n maxTTL: 86400, // 24 hours\n} as const;\n\n/**\n * Webhook Limits\n */\nexport const WEBHOOK_LIMITS = {\n maxRetries: 3,\n retryDelayMs: [1000, 5000, 15000], // Exponential backoff\n requestTimeout: 10000, // 10 seconds\n maxPayloadSize: 256 * 1024, // 256 KB\n maxHeadersCount: 20,\n maxUrlLength: 2048,\n} as const;\n\n/**\n * Export Limits\n */\nexport const EXPORT_LIMITS = {\n maxCsvRows: 1000000,\n maxJsonSize: 100 * 1024 * 1024, // 100 MB\n maxExportDuration: 300000, // 5 minutes\n maxConcurrentExports: 3,\n exportRetentionDays: 7,\n} as const;\n\n/**\n * Security Limits\n */\nexport const SECURITY_LIMITS = {\n maxLoginAttempts: 5,\n lockoutDuration: 900, // 15 minutes in seconds\n passwordMinLength: 8,\n passwordMaxLength: 128,\n tokenLength: 32,\n apiKeyLength: 32,\n secretKeyLength: 64,\n otpLength: 6,\n otpValiditySeconds: 300, // 5 minutes\n maxActiveTokens: 10,\n} as const;\n\n/**\n * Performance Thresholds\n */\nexport const PERFORMANCE_THRESHOLDS = {\n slowQueryMs: 1000,\n slowApiCallMs: 3000,\n slowDetectionMs: 100,\n highMemoryUsageMB: 512,\n highCpuUsagePercent: 80,\n highDiskUsagePercent: 90,\n} as const;\n\n/**\n * Default Pagination\n */\nexport const PAGINATION_DEFAULTS = {\n defaultPageSize: 20,\n maxPageSize: 100,\n defaultOffset: 0,\n maxOffset: 100000,\n} as const;\n\n/**\n * Time Windows\n */\nexport const TIME_WINDOWS = {\n realtime: 60, // 1 minute\n hourly: 3600, // 1 hour\n daily: 86400, // 24 hours\n weekly: 604800, // 7 days\n monthly: 2592000, // 30 days\n yearly: 31536000, // 365 days\n} as const;\n\n/**\n * Helper function to check if a limit is exceeded\n */\nexport function isLimitExceeded(current: number, limit: number): boolean {\n if (limit === -1) return false; // Unlimited\n return current >= limit;\n}\n\n/**\n * Helper function to get remaining quota\n */\nexport function getRemainingQuota(used: number, limit: number): number {\n if (limit === -1) return Number.MAX_SAFE_INTEGER; // Unlimited\n return Math.max(0, limit - used);\n}\n\n/**\n * Helper function to calculate rate limit window\n */\nexport function getRateLimitWindow(windowType: keyof typeof TIME_WINDOWS): {\n start: Date;\n end: Date;\n duration: number;\n} {\n const now = new Date();\n const duration = TIME_WINDOWS[windowType] * 1000; // Convert to milliseconds\n const start = new Date(now.getTime() - duration);\n\n return {\n start,\n end: now,\n duration,\n };\n}\n","/**\n * Rule System Constants\n *\n * Configuration constants for the unified rule system\n */\n\n/**\n * Rule system version\n */\nexport const RULE_VERSION = '1.0.0';\n\n/**\n * Rule validation modes\n */\nexport const VALIDATION_MODES = {\n /** Strict validation - all fields required */\n STRICT: 'strict',\n /** Loose validation - allow extra fields */\n LOOSE: 'loose',\n /** No validation - use with caution */\n NONE: 'none',\n} as const;\n\n/**\n * Rule categories\n */\nexport const RULE_CATEGORIES = {\n USER_AGENT: 'userAgent',\n IP_RANGE: 'ipRange',\n SIGNATURE: 'signature',\n BEHAVIORAL: 'behavioral',\n HEADER: 'header',\n} as const;\n\n/**\n * Confidence thresholds\n */\nexport const CONFIDENCE_THRESHOLDS = {\n /** Very high confidence */\n VERY_HIGH: 0.95,\n /** High confidence */\n HIGH: 0.8,\n /** Medium confidence */\n MEDIUM: 0.6,\n /** Low confidence */\n LOW: 0.4,\n /** Very low confidence */\n VERY_LOW: 0.2,\n} as const;\n\n/**\n * Rule update frequencies\n */\nexport const UPDATE_FREQUENCIES = {\n HOURLY: 'hourly',\n DAILY: 'daily',\n WEEKLY: 'weekly',\n MONTHLY: 'monthly',\n} as const;\n\n/**\n * Rule match actions\n *\n * @deprecated Dead internally as of the gateway-enforcement-step-up branch\n * (zero remaining callers repo-wide) — the doc comment claiming\n * `MATCH_ACTIONS.CHALLENGE` backs the worker's CAPTCHA/challenge action was\n * already stale (see `detection/types.ts`'s own \"Future - CAPTCHA or\n * proof-of-work\" note; the real challenge mechanism is\n * `@challenge_type`/`human_step_up`, unrelated to this enum). Kept\n * `@deprecated` rather than removed (bestbrian P2, 2026-09-09): this is a\n * wildcard-re-exported member of `@kya-os/checkpoint-shared`'s public\n * surface at 1.4.0, so deleting it outright is a breaking change for any\n * external consumer without a major version bump. Remove in the next\n * major.\n */\nexport const MATCH_ACTIONS = {\n /** Block the request */\n BLOCK: 'block',\n /** Allow but log */\n LOG: 'log',\n /** Challenge with CAPTCHA */\n CHALLENGE: 'challenge',\n /** Rate limit the client */\n RATE_LIMIT: 'rate_limit',\n /** Allow the request */\n ALLOW: 'allow',\n} as const;\n\n/**\n * Error messages\n */\nexport const RULE_ERRORS = {\n INVALID_FORMAT: 'Invalid rule format',\n VALIDATION_FAILED: 'Rule validation failed',\n LOAD_FAILED: 'Failed to load rules',\n PARSE_FAILED: 'Failed to parse rules',\n VERSION_MISMATCH: 'Rule version mismatch',\n MISSING_REQUIRED: 'Missing required rule fields',\n} as const;\n\n/**\n * Rule file paths\n */\nexport const RULE_PATHS = {\n /** Source YAML file */\n YAML_SOURCE: 'src/data/default-rules.yaml',\n /** Generated JSON file */\n JSON_OUTPUT: 'dist/rules.json',\n /** Bundled rules path */\n BUNDLED: '@kya-os/checkpoint-shared/dist/rules.json',\n} as const;\n","/**\n * Behavioral event types for detection\n */\n\nimport { z } from 'zod';\n\n/**\n * Mouse movement event\n */\nexport const MouseEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n type: z.enum(['move', 'click', 'down', 'up']).optional(),\n});\nexport type MouseEvent = z.infer<typeof MouseEventSchema>;\n\n/**\n * Keyboard event\n */\nexport const KeyboardEventSchema = z.object({\n keyCode: z.number(),\n key: z.string().optional(),\n timestamp: z.number(),\n type: z.enum(['keydown', 'keyup', 'keypress']).optional(),\n});\nexport type KeyboardEvent = z.infer<typeof KeyboardEventSchema>;\n\n/**\n * Scroll event\n */\nexport const ScrollEventSchema = z.object({\n deltaX: z.number().optional(),\n deltaY: z.number(),\n timestamp: z.number(),\n position: z\n .object({\n x: z.number(),\n y: z.number(),\n })\n .optional(),\n});\nexport type ScrollEvent = z.infer<typeof ScrollEventSchema>;\n\n/**\n * Click event with position\n */\nexport const ClickEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n button: z.enum(['left', 'right', 'middle']).optional(),\n target: z.string().optional(),\n});\nexport type ClickEvent = z.infer<typeof ClickEventSchema>;\n\n/**\n * Touch event for mobile devices\n */\nexport const TouchEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n type: z.enum(['start', 'move', 'end', 'cancel']),\n identifier: z.number().optional(),\n});\nexport type TouchEvent = z.infer<typeof TouchEventSchema>;\n\n/**\n * Aggregated behavioral data\n */\nexport const BehavioralDataSchema = z.object({\n mouseMovements: z.array(MouseEventSchema).default([]),\n keyboardEvents: z.array(KeyboardEventSchema).default([]),\n scrollEvents: z.array(ScrollEventSchema).default([]),\n clickEvents: z.array(ClickEventSchema).default([]),\n touchEvents: z.array(TouchEventSchema).default([]),\n sessionDuration: z.number().optional(),\n pageViews: z.number().optional(),\n interactionRate: z.number().optional(),\n});\nexport type BehavioralData = z.infer<typeof BehavioralDataSchema>;\n\n/**\n * Behavioral analysis result\n */\nexport const BehavioralAnalysisSchema = z.object({\n isHumanLike: z.boolean(),\n confidence: z.number().min(0).max(1),\n patterns: z.array(z.string()),\n anomalies: z.array(z.string()).optional(),\n metrics: z\n .object({\n mouseEntropy: z.number().optional(),\n typingSpeed: z.number().optional(),\n scrollPattern: z.string().optional(),\n interactionComplexity: z.number().optional(),\n })\n .optional(),\n});\nexport type BehavioralAnalysis = z.infer<typeof BehavioralAnalysisSchema>;\n","/**\n * API request schemas\n */\n\nimport { z } from 'zod';\nimport { BehavioralDataSchema } from '../events/behavioral';\n\n/**\n * Detection API request\n */\nexport const DetectionRequestSchema = z.object({\n // Required fields\n userAgent: z.string(),\n\n // Optional fields\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n\n // Behavioral data\n behavioralData: BehavioralDataSchema.optional(),\n\n // Options\n options: z\n .object({\n mode: z.enum(['strict', 'balanced', 'lenient']).optional(),\n includeMetadata: z.boolean().optional(),\n includeBreakdown: z.boolean().optional(),\n })\n .optional(),\n\n // Request metadata\n requestId: z.string().optional(),\n timestamp: z.number().optional(),\n});\nexport type DetectionRequest = z.infer<typeof DetectionRequestSchema>;\n\n/**\n * Batch detection request\n */\nexport const BatchDetectionRequestSchema = z.object({\n requests: z.array(DetectionRequestSchema).min(1),\n options: z\n .object({\n parallel: z.boolean().default(true),\n continueOnError: z.boolean().default(true),\n })\n .default({\n parallel: true,\n continueOnError: true,\n }),\n});\nexport type BatchDetectionRequest = z.infer<typeof BatchDetectionRequestSchema>;\n\n/**\n * Verification request\n */\nexport const VerificationRequestSchema = z.object({\n signature: z.string(),\n payload: z.string(),\n timestamp: z.number(),\n publicKey: z.string().optional(),\n});\nexport type VerificationRequest = z.infer<typeof VerificationRequestSchema>;\n\n/**\n * Pattern update request\n */\nexport const PatternUpdateRequestSchema = z.object({\n patterns: z\n .array(\n z.object({\n id: z.string(),\n name: z.string(),\n pattern: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n })\n )\n .min(1),\n action: z.enum(['add', 'update', 'remove', 'replace']),\n});\nexport type PatternUpdateRequest = z.infer<typeof PatternUpdateRequestSchema>;\n","/**\n * API response schemas\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { ConfidenceBreakdownSchema } from '../core/confidence';\nimport { BehavioralAnalysisSchema } from '../events/behavioral';\n\n/**\n * Standard API response wrapper\n */\nexport const ApiResponseSchema = z.object({\n success: z.boolean(),\n data: z.any().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.any().optional(),\n })\n .optional(),\n metadata: z\n .object({\n timestamp: z.number(),\n requestId: z.string().optional(),\n /**\n * Canonical 32-hex correlation id (`deriveCorrelationId`), for\n * cross-surface correlation independent of the per-call `requestId`\n * above. Also echoed as the `X-KYA-Correlation-Id` response header on\n * routes that derive one.\n */\n correlationId: z.string().optional(),\n version: z.string().optional(),\n })\n .optional(),\n});\nexport type ApiResponse<T = unknown> = Omit<z.infer<typeof ApiResponseSchema>, 'data'> & {\n data?: T;\n};\n\n/**\n * Detection API response\n */\nexport const DetectionResponseSchema = z.object({\n result: DetectionResultSchema,\n breakdown: ConfidenceBreakdownSchema.optional(),\n behavioralAnalysis: BehavioralAnalysisSchema.optional(),\n metadata: z\n .object({\n processingTime: z.number(),\n wasmUsed: z.boolean().optional(),\n cacheHit: z.boolean().optional(),\n })\n .optional(),\n});\nexport type DetectionResponse = z.infer<typeof DetectionResponseSchema>;\n\n/**\n * Batch detection response\n */\nexport const BatchDetectionResponseSchema = z.object({\n results: z.array(\n z.object({\n index: z.number(),\n success: z.boolean(),\n result: DetectionResultSchema.optional(),\n error: z.string().optional(),\n })\n ),\n summary: z.object({\n total: z.number(),\n successful: z.number(),\n failed: z.number(),\n agentsDetected: z.number(),\n }),\n});\nexport type BatchDetectionResponse = z.infer<typeof BatchDetectionResponseSchema>;\n\n/**\n * Verification response\n */\nexport const VerificationResponseSchema = z.object({\n valid: z.boolean(),\n algorithm: z.string().optional(),\n timestamp: z.number(),\n message: z.string().optional(),\n});\nexport type VerificationResponse = z.infer<typeof VerificationResponseSchema>;\n\n/**\n * Health check response\n */\nexport const HealthResponseSchema = z.object({\n status: z.enum(['healthy', 'degraded', 'unhealthy']),\n version: z.string(),\n uptime: z.number().min(0),\n checks: z\n .record(\n z.string(),\n z.object({\n status: z.enum(['pass', 'fail']),\n message: z.string().optional(),\n })\n )\n .optional(),\n});\nexport type HealthResponse = z.infer<typeof HealthResponseSchema>;\n\n/**\n * Statistics response\n */\nexport const StatsResponseSchema = z.object({\n totalRequests: z.number().min(0),\n agentsDetected: z.number().min(0),\n detectionRate: z.number().min(0).max(1),\n averageConfidence: z.number().min(0).max(1),\n topAgents: z.array(\n z.object({\n type: z.string(),\n count: z.number().min(0),\n percentage: z.number().min(0).max(100),\n })\n ),\n timeRange: z.object({\n start: z.number(),\n end: z.number(),\n }),\n});\nexport type StatsResponse = z.infer<typeof StatsResponseSchema>;\n","/**\n * Pixel Tracking Types\n *\n * Types for pixel-based agent detection and event tracking\n * Used by the pixel script, API endpoints, and dashboard\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\n\n/**\n * Client Detection Data Schema\n * Data collected by the checkpoint-detector.js module\n */\nexport const ClientDetectionSchema = z.object({\n // Critical Perplexity detection signals\n headless: z.boolean().optional(),\n canvas: z.string().optional(),\n webrtc: z.string().optional(),\n plugins: z.number().optional(),\n automation: z.string().nullable().optional(),\n webdriver: z.boolean().optional(),\n userAgentData: z\n .object({\n brands: z.array(z.string().max(64)).max(16),\n mobile: z.boolean(),\n platform: z.string().max(64),\n architecture: z.string().max(64).optional(),\n bitness: z.string().max(64).optional(),\n model: z.string().max(64).optional(),\n platformVersion: z.string().max(64).optional(),\n highEntropyStatus: z.literal('not_allowed').optional(),\n })\n .optional(),\n\n // Browser characteristics\n chrome: z.boolean().optional(),\n languages: z.array(z.string()).optional(),\n hardwareConcurrency: z.number().nullable().optional(),\n deviceMemory: z.number().nullable().optional(),\n maxTouchPoints: z.number().optional(),\n platform: z.string().optional(),\n vendor: z.string().optional(),\n screenResolution: z.string().optional(),\n colorDepth: z.number().optional(),\n pixelRatio: z.number().optional(),\n timezone: z.string().optional(),\n timezoneOffset: z.number().optional(),\n cookieEnabled: z.boolean().optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n hasTouch: z.boolean().optional(),\n\n // Interaction metrics\n mouseMovements: z.number().optional(),\n keyboardEvents: z.number().optional(),\n scrollEvents: z.number().optional(),\n clickEvents: z.number().optional(),\n touchEvents: z.number().optional(),\n // Input events dispatched with isTrusted:false (synthetic script/extension\n // input, never real hardware). Provenance signal for content-script agent\n // drivers — see human-promotion-audit.untrustedInputShare.\n untrustedEvents: z.number().optional(),\n // Timing physics, counters only (checkpoint-detector.js). Bucket edges sit\n // below the floor a hand showed on the lab gauntlet; the server derives\n // shares and means (lib/detection/timing-physics.ts). No timestamps,\n // coordinates, or key identity ever ride here. `timingVersion` names the\n // detector's guard set (IME, modifier, multi-touch skips) so rows from\n // different sets can be told apart at calibration.\n timingVersion: z.number().optional(),\n keyDwellCount: z.number().optional(),\n keyDwellUnder5: z.number().optional(),\n keyDwellSumMs: z.number().optional(),\n keyGapCount: z.number().optional(),\n keyGapUnder5: z.number().optional(),\n pressCount: z.number().optional(),\n pressAdjacencyCount: z.number().int().nonnegative().optional(),\n pressAdjacentUnder5: z.number().int().nonnegative().optional(),\n pressUnder10: z.number().optional(),\n pressSumMs: z.number().optional(),\n mouseClicks: z.number().optional(),\n zeroTrailClicks: z.number().optional(),\n // Path kinematics, counters only (checkpoint-detector.js), for the driver\n // that manufactures a hand's timing: coalesced samples per pointermove,\n // and whether consecutive steps repeat their length or their heading.\n // Mouse pointer only; no coordinate rides here. `kinematicsVersion` names\n // the rule set (tolerances, pointer filter) the way `timingVersion` does.\n kinematicsVersion: z.number().optional(),\n pointerMoves: z.number().optional(),\n coalescedMoves: z.number().optional(),\n stepPairs: z.number().optional(),\n equalSteps: z.number().optional(),\n straightSteps: z.number().optional(),\n hasInteraction: z.boolean().optional(),\n\n // Connection info\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .nullable()\n .optional(),\n\n // Performance metrics\n performance: z\n .object({\n navigation: z.number().nullable().optional(),\n memory: z\n .object({\n usedJSHeapSize: z.number().optional(),\n totalJSHeapSize: z.number().optional(),\n jsHeapSizeLimit: z.number().optional(),\n })\n .optional(),\n })\n .nullable()\n .optional(),\n\n // Collection metadata\n collectionTime: z.number().optional(),\n timestamp: z.string().optional(),\n error: z.string().optional(),\n});\nexport type ClientDetection = z.infer<typeof ClientDetectionSchema>;\n\n/**\n * Pixel Tracking Request - Simplified request from pixel beacon\n * Used by the POST /api/v1/pixel endpoint\n */\nexport const PixelTrackingRequestSchema = z.object({\n // Pixel identification\n pixelId: z.string(), // UUID of the pixel\n sessionId: z.string(), // Session identifier\n\n // User identification\n userId: z.string().nullable().optional(), // Identified user ID\n // Prior (typically anonymous) user id for an `identify` alias. When present\n // and different from `userId`, the server COPIES older properties from this\n // profile onto the newly-identified one (properties are never merged across\n // profiles automatically). Mirrors the analytics-SDK `identify(previousId)` arg.\n previousId: z.string().optional(),\n userTraits: z\n .record(z.string(), z.unknown())\n .optional() // User properties/traits\n .refine((traits) => !traits || JSON.stringify(traits).length < 10000, {\n message: 'User traits too large (max 10KB)',\n })\n .refine((traits) => !traits || Object.keys(traits).length < 50, {\n message: 'Too many user trait properties (max 50)',\n })\n .refine(\n (traits) => {\n // Validate trait value types - prevent nested objects that are too deep\n if (!traits) return true;\n const validateDepth = (obj: unknown, depth = 0): boolean => {\n if (depth > 3) return false; // Max nesting depth of 3\n if (typeof obj !== 'object' || obj === null) return true;\n return Object.values(obj as Record<string, unknown>).every((val) =>\n validateDepth(val, depth + 1)\n );\n };\n return validateDepth(traits);\n },\n {\n message: 'User traits contain overly nested objects (max depth 3)',\n }\n ),\n\n // Page context\n url: z.string().url(), // Current page URL\n referrer: z.string().optional(), // Referrer URL\n title: z.string().optional(), // Page title\n\n // Detection data\n userAgent: z.string(), // Browser user agent\n headers: z.record(z.string(), z.string()).optional(), // Any additional headers\n\n // Client info\n screenResolution: z.string().optional(), // \"1920x1080\"\n viewport: z.string().optional(), // \"1200x800\"\n timezone: z.string().optional(), // \"America/New_York\"\n language: z.string().optional(), // \"en-US\"\n platform: z.string().optional(), // navigator.platform\n cookiesEnabled: z.boolean().optional(), // navigator.cookieEnabled\n onLine: z.boolean().optional(), // navigator.onLine\n timezoneOffset: z.number().optional(), // Date.getTimezoneOffset()\n connectionType: z.string().optional(), // navigator.connection.effectiveType\n connectionSpeed: z.number().optional(), // navigator.connection.downlink\n\n // Device identity — cross-subdomain cookie set by pixel.js\n deviceId: z.string().optional(),\n\n // Behavioral (if available)\n timeOnPage: z.number().optional(), // Milliseconds\n mouseMovements: z.number().optional(), // Count of mouse events\n clickCount: z.number().optional(), // Number of clicks\n scrollDepth: z.number().optional(), // Percentage 0-100\n pageLoadTime: z.number().optional(), // performance.timing load duration, ms\n domContentLoadedTime: z.number().optional(), // performance.timing DCL duration, ms\n\n // Client-side detection data (NEW)\n clientDetection: ClientDetectionSchema.optional(),\n\n // Request tracking (client-provided, will be validated server-side)\n requestId: z.string().optional(), // Unique request ID for deduplication\n correlationId: z.string().optional(), // Cross-surface correlation id (validated/normalized server-side)\n\n // Event type for special events\n eventType: z.string().optional(), // 'pageview', 'identify', 'logout', etc.\n\n // Metadata\n timestamp: z.string(), // ISO 8601\n version: z.string().optional(), // Pixel version\n\n // Nonce-bound ingest: the value from the PRIOR 202 response's `nonce`\n // field (see `lib/services/nonce.service.ts` in apps/web). Absent on the\n // first pixel hit of a session; absent, stale, or mismatched on any\n // later hit is a forgery signal, never a 400 — a forged hit is accepted\n // for storage but tagged, not rejected.\n nonce: z.string().max(64).optional(),\n // Declares this client stores and echoes the nonce it's handed (the\n // pixel script always sends `true`; absent means a cached pre-upgrade\n // copy of pixel.js, never something a client turns off) — see\n // `nonce.service.ts`'s missing-nonce rule for why the distinction matters.\n nonceEcho: z.boolean().optional(),\n handoffToken: z.string().max(2048).optional().catch(undefined),\n binding: z.string().max(128).optional(),\n\n // IP anonymization (build item 6). Default false, unlike beacon: Tier 2\n // vendor-IP corroboration needs the full address for pixel traffic — see\n // the pixel route's own doc comment.\n anonymizeIp: z.boolean().optional(),\n});\nexport type PixelTrackingRequest = z.infer<typeof PixelTrackingRequestSchema>;\n\n/**\n * Pixel Tracking Response\n */\nexport const PixelTrackingResponseSchema = z.object({\n success: z.boolean(),\n eventId: z.string().uuid().optional(),\n sessionId: z.string().optional(),\n detection: DetectionResultSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n // Nonce-bound ingest: echo this back as `nonce` on the NEXT pixel hit —\n // see `PixelTrackingRequestSchema`'s `nonce` field doc comment.\n nonce: z.string().max(64).optional(),\n handoff: z.object({ status: z.enum(['adopted', 'rejected', 'unavailable']) }).optional(),\n});\nexport type PixelTrackingResponse = z.infer<typeof PixelTrackingResponseSchema>;\n\n/**\n * Pixel Verification Status\n */\nexport const PixelVerificationStatusSchema = z.object({\n status: z.enum(['verified', 'partial', 'pending', 'failed']),\n message: z.string(),\n verified: z.boolean(),\n lastDetection: z.date().nullable(),\n detectionCount: z.number().int().min(0),\n metadata: z\n .object({\n recentDetections: z.number().int().min(0),\n failedDetections: z.number().int().min(0),\n timeWindow: z.string(),\n })\n .optional(),\n});\nexport type PixelVerificationStatus = z.infer<typeof PixelVerificationStatusSchema>;\n","/**\n * Version-agnostic Zod helper schemas.\n *\n * Zod 4 removes `z.string().ip()`. Every site that needs \"an IP address\"\n * goes through this helper so the Zod 4 flip changed one body, not a dozen\n * call sites. The body below is the Zod 4 form.\n */\n\nimport { z } from 'zod';\n\n/** Accepts a bare IPv4 or IPv6 address. Rejects ports, brackets, and whitespace. */\nexport const ipAddressSchema = z.union([z.ipv4(), z.ipv6()], { error: 'Invalid IP address' });\n","/**\n * Event API schemas for tracking and batch processing\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { BehavioralDataSchema } from '../events/behavioral';\nimport { ClientDetectionSchema } from '../types/pixel';\nimport { ipAddressSchema } from '../utils/zod-helpers';\n\n/**\n * Single Event Tracking Request\n */\nexport const EventTrackingRequestSchema = z.object({\n // Required fields\n pixelId: z.string().uuid(),\n sessionId: z.string().min(1).max(255),\n url: z.string().url(),\n userAgent: z.string().min(1).max(1024),\n\n // Optional fields\n ip: ipAddressSchema.optional(),\n timestamp: z.string().datetime().optional(),\n referrer: z.string().url().optional(),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).optional(),\n\n // Headers for additional context\n headers: z.record(z.string(), z.string()).optional(),\n\n // Behavioral tracking data\n behavioralData: BehavioralDataSchema.optional(),\n\n // Client-side browser fingerprint (headless/automation tells, interaction).\n // Optional + additive: legacy clients that omit it are unaffected.\n clientDetection: ClientDetectionSchema.optional(),\n\n // Page metrics\n timeOnPage: z.number().min(0).optional(),\n scrollDepth: z.number().min(0).max(100).optional(),\n clickCount: z.number().min(0).optional(),\n mouseMovements: z.number().min(0).optional(),\n keystrokes: z.number().min(0).optional(),\n\n // Device/viewport info\n screenResolution: z.string().optional(),\n viewport: z.string().optional(),\n\n // Custom metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type EventTrackingRequest = z.infer<typeof EventTrackingRequestSchema>;\n\n/**\n * Single Event Tracking Response\n */\nexport const EventTrackingResponseSchema = z.object({\n success: z.boolean(),\n eventId: z.string().uuid(),\n sessionId: z.string(),\n detection: DetectionResultSchema,\n\n // Rate limit info\n rateLimit: z\n .object({\n limit: z.number(),\n remaining: z.number(),\n reset: z.number(),\n })\n .optional(),\n\n // Debug info (only in development)\n debug: z\n .object({\n processingTime: z.number(),\n rulesVersion: z.string(),\n serverRegion: z.string().optional(),\n cacheHit: z.boolean().optional(),\n })\n .optional(),\n});\nexport type EventTrackingResponse = z.infer<typeof EventTrackingResponseSchema>;\n\n/**\n * Batch Event Request\n */\nexport const BatchEventRequestSchema = z.object({\n // API key for authentication (required for batch)\n apiKey: z.string().min(32).optional(), // Can be in header instead\n\n // Array of events (max 100)\n events: z.array(EventTrackingRequestSchema).min(1).max(100),\n\n // Processing options\n options: z\n .object({\n parallel: z.boolean().default(true),\n continueOnError: z.boolean().default(true),\n includeDetailed: z.boolean().default(false),\n })\n .optional(),\n});\nexport type BatchEventRequest = z.infer<typeof BatchEventRequestSchema>;\n\n/**\n * Batch Event Response\n */\nexport const BatchEventResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().uuid(),\n\n // Processing results\n results: z.array(\n z.object({\n index: z.number(),\n eventId: z.string().uuid().optional(),\n success: z.boolean(),\n detection: DetectionResultSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n })\n ),\n\n // Summary statistics\n summary: z.object({\n total: z.number(),\n successful: z.number(),\n failed: z.number(),\n agentsDetected: z.number(),\n averageConfidence: z.number().min(0).max(1),\n processingTime: z.number(),\n }),\n\n // Rate limit info\n rateLimit: z\n .object({\n limit: z.number(),\n remaining: z.number(),\n reset: z.number(),\n })\n .optional(),\n});\nexport type BatchEventResponse = z.infer<typeof BatchEventResponseSchema>;\n","/**\n * Text read back in terminals and the dashboard. It may be in any language, but it holds no\n * control characters (terminal escapes and line breaks among them) and no bidirectional\n * formatting characters, which could make it display as other text. The CLI refuses text that\n * breaks this rule, so Checkpoint never produces any.\n */\nexport const READABLE_TEXT = /^[^\\p{Cc}\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]*$/u;\nexport const READABLE_TEXT_MESSAGE = 'No control or bidirectional formatting characters';\n\nconst UNREADABLE = /[\\p{Cc}\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/gu;\n\n/** The same text with each character `READABLE_TEXT` refuses shown as U+FFFD. */\nexport function readableText(value: string): string {\n return value.replace(UNREADABLE, '\\uFFFD');\n}\n","import { z } from 'zod';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\n/**\n * C12: model provider keys an organization owns. An owner or admin stores the organization's own\n * key through the C3 management session; Checkpoint validates it with a free provider call,\n * encrypts it, and never returns it. An installation's model policy names the credential it\n * uses, so a model call is paid by the tenant whose key it names. There is no platform key,\n * switch or project allowlist.\n *\n * Adding and rotating are idempotent by `operationId`: the same operation with the same key\n * returns the recorded result (`duplicate: true`), and with another key it is refused\n * (`OPERATION_CONFLICT`). A client journals the operation with the key's fingerprint, never the\n * key.\n */\nconst Timestamp = z.string().datetime();\nconst Uuid = z.string().uuid();\n\n/** The providers a model credential can be for. */\nexport const ModelCredentialProviderSchema = z.literal('anthropic');\n\n/**\n * `sha256:` and the first 16 lowercase hex characters of SHA-256 over the key's UTF-8 bytes.\n * It identifies a key in receipts and listings without revealing it; a client computes the same\n * value locally with `modelCredentialFingerprint`.\n */\nexport const ModelCredentialFingerprintSchema = z.string().regex(/^sha256:[a-f0-9]{16}$/);\n\nexport function modelCredentialFingerprint(key: string): string {\n return `sha256:${bytesToHex(sha256(new TextEncoder().encode(key))).slice(0, 16)}`;\n}\n\n/** A person's name for a credential: printable ASCII, no space at either end. */\nexport const ModelCredentialLabelSchema = z\n .string()\n .min(1)\n .max(100)\n .regex(/^[\\x21-\\x7E]([\\x20-\\x7E]*[\\x21-\\x7E])?$/);\n\n/** A revocation reason is free text read back in terminals and the dashboard: readable text. */\nconst RevocationReasonSchema = z\n .string()\n .min(1)\n .max(500)\n .regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\n\n/** The secret itself, only ever in an add or rotate request body. Its shape is the provider's. */\nconst ModelApiKey = z\n .string()\n .min(20)\n .max(512)\n .regex(/^[\\x21-\\x7E]+$/);\n\n/** `kya.model-credential.v1`: metadata only. The key never appears in any response. */\nexport const ModelCredentialSchema = z\n .object({\n schema: z.literal('kya.model-credential.v1'),\n credentialId: Uuid,\n organizationId: Uuid,\n provider: ModelCredentialProviderSchema,\n label: ModelCredentialLabelSchema,\n /** The current key's fingerprint; a rotation replaces it and increments `version`. */\n fingerprint: ModelCredentialFingerprintSchema,\n version: z.number().int().positive().max(2147483647),\n status: z.enum(['active', 'revoked']),\n /** When the provider last accepted this key. */\n validatedAt: Timestamp,\n createdByUserId: Uuid,\n createdAt: Timestamp,\n rotatedAt: Timestamp.nullable(),\n /** Who made the latest rotation; set exactly when `rotatedAt` is. */\n rotatedByUserId: Uuid.nullable(),\n revokedAt: Timestamp.nullable(),\n revokedByUserId: Uuid.nullable(),\n revocationReason: RevocationReasonSchema.nullable(),\n })\n .strict()\n .refine((value) => {\n const recorded = [value.revokedAt, value.revokedByUserId, value.revocationReason].map(\n (field) => field !== null\n );\n return value.status === 'revoked' ? recorded.every(Boolean) : recorded.every((isSet) => !isSet);\n }, 'A revoked credential records when, by whom and why; an active one records none of them')\n .refine(\n (value) => (value.rotatedAt === null) === (value.rotatedByUserId === null),\n 'A rotation records when and by whom; an unrotated credential records neither'\n );\nexport type ModelCredential = z.infer<typeof ModelCredentialSchema>;\n\n/** `POST /api/cli/management/projects/{id}/model-credentials`, stored on the project's organization. */\nexport const AddModelCredentialSchema = z\n .object({\n operationId: Uuid,\n provider: ModelCredentialProviderSchema,\n label: ModelCredentialLabelSchema,\n key: ModelApiKey,\n })\n .strict();\n/** `POST …/model-credentials/{credentialId}/rotate`: a new key for the same credential. */\nexport const RotateModelCredentialSchema = z\n .object({ operationId: Uuid, key: ModelApiKey })\n .strict();\n/** `POST …/model-credentials/{credentialId}/revoke`. Revoking again returns the first revocation. */\nexport const RevokeModelCredentialSchema = z\n .object({ reason: z.string().trim().pipe(RevocationReasonSchema) })\n .strict();\nexport type AddModelCredential = z.infer<typeof AddModelCredentialSchema>;\nexport type RotateModelCredential = z.infer<typeof RotateModelCredentialSchema>;\nexport type RevokeModelCredential = z.infer<typeof RevokeModelCredentialSchema>;\n\n/** An add or rotate: the credential after it, and whether this operation had already run. */\nexport const ModelCredentialResultSchema = z\n .object({\n operationId: Uuid,\n credential: ModelCredentialSchema,\n duplicate: z.boolean(),\n })\n .strict();\nexport const ModelCredentialRevocationSchema = z\n .object({\n credential: ModelCredentialSchema,\n wasAlreadyRevoked: z.boolean(),\n })\n .strict()\n .refine(\n (value) => value.credential.status === 'revoked',\n 'A revocation returns a revoked credential'\n );\n/** `GET …/model-credentials`: the organization's credentials, newest first. */\nexport const ModelCredentialListSchema = z\n .object({\n organizationId: Uuid,\n credentials: z.array(ModelCredentialSchema).max(100),\n })\n .strict();\nexport type ModelCredentialResult = z.infer<typeof ModelCredentialResultSchema>;\nexport type ModelCredentialRevocation = z.infer<typeof ModelCredentialRevocationSchema>;\nexport type ModelCredentialList = z.infer<typeof ModelCredentialListSchema>;\n\n/**\n * Definite refusals of these routes and of a model call, all 4xx: nothing was stored, and a model\n * call refused for its credential never reached the provider.\n */\nexport const ModelCredentialRefusalCodeSchema = z.enum([\n /** The same operation was already used with another key. 409. */\n 'OPERATION_CONFLICT',\n /** No such credential in this organization. 404. */\n 'CREDENTIAL_NOT_FOUND',\n /** Rotating a revoked credential. 409. */\n 'CREDENTIAL_REVOKED',\n /** The provider refused the key. 422. */\n 'MODEL_KEY_REJECTED',\n /** The provider could not be asked; nothing was stored, try again. 424. */\n 'MODEL_KEY_UNVERIFIED',\n /** A model call's policy names a credential that is missing, revoked or another tenant's. 409. */\n 'MODEL_CREDENTIAL_UNAVAILABLE',\n]);\n","import { z } from 'zod';\n\n/** Application admission profile for the A2A 1.0 JSON-RPC binding. This is not a\n * replacement for the normative upstream proto or a complete A2A SDK schema. */\nexport const KYA_A2A_EXTENSION = 'https://kya-os.ai/a2a/task-source/v1';\nconst Id = z.string().min(1).max(255);\nconst Tenant = z.string().regex(/^[0-9a-f-]{36}:[1-9][0-9]{0,9}$/);\nexport const A2ARpcEnvelopeSchema = z\n .object({\n jsonrpc: z.literal('2.0'),\n id: z.union([Id, z.number().int().safe()]),\n method: Id,\n params: z.unknown(),\n })\n .strict();\nconst Send = z\n .object({\n tenant: Tenant,\n message: z\n .object({\n messageId: Id,\n role: z.literal('ROLE_USER'),\n parts: z\n .array(\n z\n .object({\n text: z.string().min(1).max(7000),\n mediaType: z.literal('text/plain').optional(),\n })\n .strict()\n )\n .min(1)\n .max(32),\n taskId: z.string().uuid().optional(),\n contextId: z.string().uuid().optional(),\n })\n .strict(),\n configuration: z\n .object({\n returnImmediately: z.literal(true),\n historyLength: z.number().int().min(0).max(1000).optional(),\n acceptedOutputModes: z\n .array(z.enum(['application/json', 'text/plain']))\n .min(1)\n .max(2)\n .optional(),\n })\n .strict(),\n })\n .strict();\nconst Get = z\n .object({\n tenant: Tenant,\n id: z.string().uuid(),\n historyLength: z.number().int().min(0).max(1000).optional(),\n })\n .strict();\nconst Cancel = z.object({ tenant: Tenant, id: z.string().uuid() }).strict();\nexport const A2ATaskRequestSchema = z.discriminatedUnion('method', [\n z.object({ method: z.literal('SendMessage'), params: Send }).strict(),\n z.object({ method: z.literal('GetTask'), params: Get }).strict(),\n z.object({ method: z.literal('CancelTask'), params: Cancel }).strict(),\n]);\nexport type A2ATaskRequest = z.infer<typeof A2ATaskRequestSchema>;\n\n/** Canonical standard base64 with padding: the unused bits of the last symbol are zero, so a\n * value decodes to exactly one byte string and re-encodes to itself. */\nconst StandardBase64 =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/;\nconst base64ByteLength = (value: string) =>\n (value.length / 4) * 3 - (value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0);\nconst HttpsUrl = z\n .string()\n .max(2048)\n .refine((value) => {\n try {\n return new URL(value).protocol === 'https:';\n } catch {\n return false;\n }\n }, 'targetUri must be an https URL');\n\n/**\n * B09-P3 `kya.a2a.signed-request.v1`: the exact RFC 9421 request Checkpoint verified for one A2A\n * delivery, so a receiving workbench can verify the sender's signature without trusting Checkpoint.\n * Every header member is the exact string received; `targetUri` is the exact target verified;\n * `body` is the standard base64 of the exact request body bytes (at most the 8 KiB A2A limit).\n * The kya-http/2 signature covers, joined by \"\\n\" with no trailing newline:\n * `\"@method\": POST`, `\"@authority\": <host[:port] of targetUri>`, `\"@target-uri\": <targetUri>`,\n * `\"content-digest\": <contentDigest>`, `\"content-type\": <contentType>` and\n * `\"@signature-params\": <signatureInput without its leading \"kya=\">`.\n */\nexport const A2ASignedRequestSchema = z\n .object({\n schema: z.literal('kya.a2a.signed-request.v1'),\n method: z.literal('POST'),\n targetUri: HttpsUrl,\n contentType: z.string().max(255),\n contentDigest: z.string().regex(/^sha-256=:[A-Za-z0-9+/]{43}=:$/),\n signatureInput: z.string().max(1024),\n signature: z.string().regex(/^kya=:[A-Za-z0-9+/]{86}==:$/),\n body: z\n .string()\n .max(10924)\n .regex(StandardBase64, 'body must be standard base64 with padding')\n .refine((value) => {\n const bytes = base64ByteLength(value);\n return bytes >= 1 && bytes <= 8192;\n }, 'body must decode to 1..8192 bytes'),\n })\n .strict();\nexport type A2ASignedRequest = z.infer<typeof A2ASignedRequestSchema>;\n\nexport const A2ATaskStateSchema = z.enum([\n 'TASK_STATE_UNSPECIFIED',\n 'TASK_STATE_SUBMITTED',\n 'TASK_STATE_WORKING',\n 'TASK_STATE_COMPLETED',\n 'TASK_STATE_FAILED',\n 'TASK_STATE_CANCELED',\n 'TASK_STATE_INPUT_REQUIRED',\n 'TASK_STATE_REJECTED',\n]);\nexport type A2ATaskState = z.infer<typeof A2ATaskStateSchema>;\nexport interface A2ATaskProjection {\n id: string;\n contextId: string;\n status: { state: A2ATaskState };\n metadata: {\n kyaTaskSource: {\n operationId: string;\n sourceRevision: number;\n ownerEpoch: number;\n deliveryState: string;\n cancellationRequested: boolean;\n authorization: 'requires_task_approval';\n completionBasis: 'none' | 'recorded_host_receipt';\n resultDigest?: string;\n evidenceRefs?: string[];\n executionState?: string;\n };\n };\n}\n\n/** Out-of-band discovery profile returned to the installation administrator.\n * RFC 9421 holder signatures require the extension; they are not bearer auth. */\nexport function createKyaA2AAgentCard(endpoint: string, tenant: string) {\n const url = new URL(endpoint);\n if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)\n throw new Error('A2A endpoint must be an exact HTTPS target');\n Tenant.parse(tenant);\n return {\n name: 'KYA accountable task intake',\n description:\n 'Queue bounded work, send steering and request cancellation. Execution requires separately admitted authority. This text-only asynchronous profile requires the KYA extension.',\n version: '1.0.0',\n supportedInterfaces: [\n { url: endpoint, protocolBinding: 'JSONRPC', protocolVersion: '1.0', tenant },\n ],\n capabilities: {\n streaming: false,\n pushNotifications: false,\n extendedAgentCard: false,\n extensions: [\n {\n uri: KYA_A2A_EXTENSION,\n required: true,\n description:\n 'KYA HTTP/2 Ed25519 holder proof over the exact JSON body and target; registered actors only. Source text never grants authority.',\n params: {\n methods: ['SendMessage', 'GetTask', 'CancelTask'],\n maxRequestBytes: 8192,\n returnImmediatelyRequired: true,\n historyReturned: false,\n authentication: {\n profile: 'kya-http/2',\n headers: ['Signature-Input', 'Signature', 'Content-Digest', 'Content-Type'],\n bearerSupported: false,\n },\n retry:\n 'Reuse the same messageId and unchanged parameters with a fresh HTTP proof after an uncertain acknowledgement.',\n },\n },\n ],\n },\n defaultInputModes: ['text/plain'],\n defaultOutputModes: ['application/json'],\n skills: [\n {\n id: 'accountable-work',\n name: 'Accountable work',\n description:\n 'Submit and inspect durable tasks; completion identifies a recorded host receipt, with separate artifact and acceptance verification.',\n tags: ['tasks', 'governance', 'evidence'],\n },\n ],\n };\n}\n","import { z } from 'zod';\n\nexport const TaskProjectionStateSchema = z.enum([\n 'queued',\n 'delivered',\n 'approved',\n 'running',\n 'unknown',\n 'awaiting_acceptance',\n 'accepted',\n 'published',\n]);\nexport const TaskProjectionEvidenceSchema = z\n .object({\n record: z.enum([\n 'source_intent',\n 'delivery_attempt',\n 'publication_binding',\n 'admission',\n 'action',\n 'result_receipt',\n 'activity',\n ]),\n id: z.string().min(1).max(255),\n state: z.string().min(1).max(64),\n // Null means the legacy record has no trustworthy transition timestamp.\n observedAt: z.string().datetime().nullable(),\n basis: z.enum([\n 'checkpoint_commit',\n 'host_receipt',\n 'lead_acknowledgment',\n 'provider_ack',\n 'provider_lookup',\n ]),\n })\n .strict();\n/** Metadata projection. Accepted means receipt acceptance, not human quality approval. */\nexport const TaskStatusProjectionSchema = z\n .object({\n schema: z.literal('kya.task.status-projection.v1'),\n taskId: z.string().uuid(),\n installationId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n provider: z.enum(['linear', 'github', 'discord', 'didcomm', 'a2a']),\n sessionId: z.string().min(1).max(255),\n sourceRevision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n ownerEpoch: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n state: TaskProjectionStateSchema,\n since: z.string().datetime().nullable(),\n cancellationRequested: z.boolean(),\n uncertain: z.array(TaskProjectionEvidenceSchema).max(64),\n evidence: z.array(TaskProjectionEvidenceSchema).min(1).max(64),\n projectedAt: z.string().datetime(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if ((value.state === 'unknown') !== value.uncertain.length > 0)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Uncertainty must take precedence' });\n if (value.since !== null && Date.parse(value.since) > Date.parse(value.projectedAt))\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Transition cannot follow observation',\n });\n if (![...value.evidence, ...value.uncertain].some((e) => e.observedAt === value.since))\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Transition needs record provenance' });\n for (const item of value.uncertain) {\n if (\n !value.evidence.some(\n (e) =>\n e.record === item.record &&\n e.id === item.id &&\n e.state === item.state &&\n e.observedAt === item.observedAt &&\n e.basis === item.basis\n )\n )\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Uncertainty must identify projection evidence',\n });\n }\n for (const items of [value.evidence, value.uncertain]) {\n if (new Set(items.map((e) => JSON.stringify([e.record, e.id]))).size !== items.length)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate record evidence' });\n }\n });\nexport type TaskProjectionState = z.infer<typeof TaskProjectionStateSchema>;\nexport type TaskProjectionEvidence = z.infer<typeof TaskProjectionEvidenceSchema>;\nexport type TaskStatusProjection = z.infer<typeof TaskStatusProjectionSchema>;\n\n/** A tenant-scoped page of projections, most recently created task first. */\nexport const TaskStatusProjectionListSchema = z\n .object({\n tasks: z.array(TaskStatusProjectionSchema).max(100),\n projectedAt: z.string().datetime(),\n })\n .strict();\n\n/** The conditions the activity drain needs to send; each names the reason it can fail. */\nexport const LinearActivityGateSchema = z.enum([\n 'installation_disabled',\n 'installation_disconnected',\n 'owner_epoch_changed',\n 'destination_changed',\n 'publication_binding_invalid',\n 'publication_binding_expired',\n 'approver_not_admin',\n 'github_custody_lost',\n]);\nexport const LinearActivityObservationSummarySchema = z\n .object({\n method: z.enum(['send', 'provider_lookup']),\n result: z.enum(['delivered', 'rejected', 'uncertain', 'absent', 'mismatch', 'unavailable']),\n observedAt: z.string().datetime(),\n httpStatus: z.number().int().min(100).max(599).nullable(),\n })\n .strict();\n/**\n * An outbox entry the drain will not send as things stand: a failing gate, or an unproven\n * delivery that only a provider lookup can resolve. Metadata only, never activity content.\n */\nexport const LinearObsoleteActivitySchema = z\n .object({\n schema: z.literal('kya.linear.obsolete-activity.v1'),\n activityId: z.string().uuid(),\n installationId: z.string().uuid(),\n operationId: z.string().uuid(),\n sessionId: z.string().min(1).max(255),\n kind: z.enum(['result', 'progress']),\n deliveryState: z.enum(['pending', 'claimed', 'unknown']),\n attemptCount: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),\n createdAt: z.string().datetime(),\n stateChangedAt: z.string().datetime().nullable(),\n reasons: z\n .array(z.union([LinearActivityGateSchema, z.literal('delivery_unproven')]))\n .min(1)\n .max(9),\n lastObservation: LinearActivityObservationSummarySchema.nullable(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (new Set(value.reasons).size !== value.reasons.length)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate reason' });\n // Only an unproven delivery is uncertain; a pending entry that never left is not.\n if (value.reasons.includes('delivery_unproven') === (value.deliveryState === 'pending'))\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unproven means unknown delivery' });\n });\nexport const LinearObsoleteActivityListSchema = z\n .object({\n activities: z.array(LinearObsoleteActivitySchema).max(200),\n projectedAt: z.string().datetime(),\n })\n .strict();\nexport type TaskStatusProjectionList = z.infer<typeof TaskStatusProjectionListSchema>;\nexport type LinearActivityGate = z.infer<typeof LinearActivityGateSchema>;\nexport type LinearObsoleteActivity = z.infer<typeof LinearObsoleteActivitySchema>;\nexport type LinearObsoleteActivityList = z.infer<typeof LinearObsoleteActivityListSchema>;\n","import { z } from 'zod';\nimport { ModelCredentialFingerprintSchema } from './model-credentials';\nimport { A2ASignedRequestSchema } from './task-a2a';\n\nconst BoundedId = z.string().min(1).max(255);\n// Receipts carry the same bounded identities and token shape as their requests.\nconst DestinationDid = z.string().startsWith('did:').max(512);\nconst KeyDid = z.string().startsWith('did:key:').max(512);\nconst ClaimToken = z\n .string()\n .length(64)\n .regex(/^[a-f0-9]{64}$/);\n// The publication service mints this branch from the immutable task binding digest.\nconst PublicationBranch = z\n .string()\n .length(35)\n .regex(/^kya\\/linear-[a-f0-9]{24}$/);\nconst Repository = z\n .string()\n .max(255)\n .regex(/^[a-zA-Z0-9_.-]+\\/[a-zA-Z0-9_.-]+$/);\nexport const TaskSourceProviderSchema = z.enum(['linear', 'github', 'discord', 'didcomm', 'a2a']);\nexport const TaskStandingCapabilitySchema = z.enum([\n 'task.execute',\n 'model.invoke',\n 'github.branch.write',\n 'github.pull_request.draft',\n]);\nconst TaskModelIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/);\n/** Fixed allocation per call, not a provider price estimate or a guaranteed billing ceiling. */\nexport const TaskModelPolicySchema = z\n .object({\n provider: z.literal('anthropic'),\n /** The organization's own model credential that pays for these calls (`model-credentials`). */\n credentialId: z.string().uuid(),\n models: z\n .array(TaskModelIdSchema)\n .min(1)\n .max(20)\n .refine((values) => new Set(values).size === values.length, 'Duplicate models'),\n maxOutputTokens: z.number().int().min(1).max(64000),\n maxRequestBytes: z.number().int().min(1).max(262144),\n reservedCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n })\n .strict();\nexport type TaskModelPolicy = z.infer<typeof TaskModelPolicySchema>;\n/** Initial text-only Messages profile. No caller endpoints, keys, hosted tools or streaming. */\nexport const TaskModelMessagesSchema = z\n .object({\n model: TaskModelIdSchema,\n max_tokens: z.number().int().min(1).max(64000),\n messages: z\n .array(\n z\n .object({ role: z.enum(['user', 'assistant']), content: z.string().min(1).max(262144) })\n .strict()\n )\n .min(1)\n .max(1000),\n system: z.string().max(262144).optional(),\n temperature: z.number().min(0).max(1).optional(),\n stream: z.literal(false).optional(),\n })\n .strict();\nexport type TaskModelMessages = z.infer<typeof TaskModelMessagesSchema>;\nexport const TaskModelStatusSchema = z\n .object({\n admissionId: z.string().uuid(),\n operationId: z.string().uuid(),\n ownerEpoch: z.number().int().positive(),\n })\n .strict();\nexport const TaskModelInvokeSchema = TaskModelStatusSchema.extend({\n request: TaskModelMessagesSchema,\n}).strict();\nexport type TaskModelInvoke = z.infer<typeof TaskModelInvokeSchema>;\nexport type TaskModelStatus = z.infer<typeof TaskModelStatusSchema>;\nconst ModelTokenCount = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();\nexport const TaskModelUsageSchema = z\n .object({\n newInputTokens: ModelTokenCount,\n cacheReadInputTokens: ModelTokenCount,\n cacheWriteInputTokens: ModelTokenCount,\n cacheWrite5mInputTokens: ModelTokenCount,\n cacheWrite1hInputTokens: ModelTokenCount,\n totalInputTokens: ModelTokenCount,\n outputTokens: ModelTokenCount,\n coverage: z.enum(['complete', 'partial', 'unknown']),\n })\n .strict();\nexport const TaskModelReceiptSchema = z\n .object({\n schema: z.literal('kya.task.model-receipt.v1'),\n admissionId: z.string().uuid(),\n admissionDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n operationId: z.string().uuid(),\n requestDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n provider: z.literal('anthropic'),\n model: TaskModelIdSchema,\n /** The admitted policy's credential, and the fingerprint of its key at call time. */\n credentialId: z.string().uuid(),\n credentialFingerprint: ModelCredentialFingerprintSchema,\n reservedCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n usage: TaskModelUsageSchema.nullable(),\n outputDigest: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/)\n .optional(),\n // MODEL_REFUSED: the request provably did not run (never sent, or a definite provider\n // refusal). Its allocation stays spent, but it does not make the admission uncertain.\n code: z.enum(['MODEL_STARTED', 'MODEL_COMPLETED', 'MODEL_REFUSED', 'MODEL_OUTCOME_UNKNOWN']),\n durationMs: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),\n requestStartedAtMs: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),\n costBasis: z.literal('unknown'),\n billingVerified: z.literal(false),\n })\n .strict();\nexport type TaskModelReceipt = z.infer<typeof TaskModelReceiptSchema>;\n// Rust refuses a repeated capability too (task_control.rs `capabilities`).\nconst StandingCapabilities = z\n .array(TaskStandingCapabilitySchema)\n .min(1)\n .max(4)\n .refine((values) => new Set(values).size === values.length, 'Duplicate capability');\nexport const TaskStandingPolicySchema = z\n .object({\n maxConcurrentOperations: z.number().int().min(1).max(100),\n maxAttemptsPerTask: z.number().int().min(1).max(10),\n workers: z\n .array(\n z\n .object({\n did: KeyDid,\n capabilities: StandingCapabilities,\n })\n .strict()\n )\n .min(1)\n .max(100),\n })\n .strict();\n/**\n * An owner-approved set of leads for pooled routing. One eligible lead is selected per task, at\n * the lead's own claim, and persisted before delivery; `maxConcurrentTasks` bounds how many\n * unfinished tasks a lead may hold. Leads receive tasks; workers remain `standingApproval`.\n */\nexport const TaskLeadPoolSchema = z\n .object({\n leads: z\n .array(\n z\n .object({\n did: KeyDid,\n maxConcurrentTasks: z.number().int().min(1).max(100),\n })\n .strict()\n )\n .min(2)\n .max(32),\n })\n .strict()\n .refine(\n (pool) => new Set(pool.leads.map((lead) => lead.did)).size === pool.leads.length,\n 'Each pool lead appears once'\n );\nexport type TaskLeadPool = z.infer<typeof TaskLeadPoolSchema>;\n\nexport const LinearInstallationWorkflowSchema = z\n .object({\n destinationDid: DestinationDid,\n ownerEpoch: z.number().int().positive().max(2147483647),\n allowedActorIds: z.array(BoundedId).min(1).max(100),\n allowedRepositories: z.array(Repository).min(1).max(50),\n maxRuntimeSeconds: z.number().int().positive().max(86400),\n maxOperations: z.number().int().positive().max(10000),\n maxCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n allowDraftPullRequest: z.boolean().default(false),\n executionMode: z.enum(['review_required', 'work_to_draft_pr']).default('review_required'),\n standingApproval: TaskStandingPolicySchema.optional(),\n modelPolicy: TaskModelPolicySchema.optional(),\n // Absent means direct routing to destinationDid, which then never falls back to anyone else.\n leadPool: TaskLeadPoolSchema.optional(),\n })\n .strict()\n .refine(\n (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 60000,\n 'Workflow exceeds delivery envelope bound'\n )\n // The addressable destination (DIDComm and A2A recipient) must itself be a qualified lead.\n .refine(\n (value) =>\n !value.leadPool || value.leadPool.leads.some((lead) => lead.did === value.destinationDid),\n 'A pooled destination must be one of its leads'\n );\nexport type LinearInstallationWorkflow = z.infer<typeof LinearInstallationWorkflowSchema>;\n\n/**\n * Whether the policy lets `did` lead this installation's tasks: the pool's leads, or the direct\n * destination. Checkpoint also requires a pooled lead to hold a live C10 workload enrollment.\n */\nexport function isAuthorizedLead(\n workflow: Pick<LinearInstallationWorkflow, 'destinationDid' | 'leadPool'>,\n did: string\n): boolean {\n return workflow.leadPool\n ? workflow.leadPool.leads.some((lead) => lead.did === did)\n : workflow.destinationDid === did;\n}\n\n/**\n * An owner/admin reassignment of one pooled task. `expectedLeadEpoch` fences a concurrent\n * reassignment; a null `leadDid` returns the task to the pool for the next eligible claim.\n */\nexport const ReassignTaskLeadSchema = z\n .object({\n expectedLeadEpoch: z.number().int().nonnegative().max(2147483647),\n leadDid: KeyDid.nullable(),\n })\n .strict();\nexport const TaskLeadAssignmentSchema = z\n .object({\n installationId: z.string().uuid(),\n taskId: z.string().uuid(),\n leadDid: KeyDid.nullable(),\n leadEpoch: z.number().int().positive().max(2147483647),\n })\n .strict();\nexport type ReassignTaskLead = z.infer<typeof ReassignTaskLeadSchema>;\nexport type TaskLeadAssignment = z.infer<typeof TaskLeadAssignmentSchema>;\n\nexport const ConfigureLinearInstallationSchema = z\n .object({\n projectId: z.string().uuid(),\n workspaceId: BoundedId,\n oauthClientId: BoundedId,\n appUserId: BoundedId,\n webhookId: BoundedId,\n webhookSecret: z.string().min(16).max(4096),\n accessToken: z.string().min(1).max(8192),\n enabled: z.boolean().default(true),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict();\n\nexport const GitHubTaskSourceConfigSchema = z\n .object({\n provider: z.literal('github'),\n githubInstallationId: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n repository: Repository.transform((value) => value.toLowerCase()),\n agentUserId: z.string().regex(/^[1-9][0-9]{0,19}$/),\n webhookSecret: z.string().min(16).max(4096),\n })\n .strict();\nexport const DiscordTaskSourceConfigSchema = z\n .object({\n provider: z.literal('discord'),\n applicationId: z.string().regex(/^[1-9][0-9]{16,19}$/),\n publicKeyHex: z.string().regex(/^[a-fA-F0-9]{64}$/),\n guildId: z.string().regex(/^[1-9][0-9]{16,19}$/),\n channelIds: z\n .array(z.string().regex(/^[1-9][0-9]{16,19}$/))\n .min(1)\n .max(100),\n commandName: z.string().regex(/^[a-z0-9_-]{1,32}$/),\n })\n .strict();\nexport const DidCommTaskSourceConfigSchema = z\n .object({\n provider: z.literal('didcomm'),\n recipientDid: z.string().startsWith('did:key:').max(255),\n })\n .strict();\nexport const A2ATaskSourceConfigSchema = z\n .object({ provider: z.literal('a2a'), recipientDid: z.string().startsWith('did:key:').max(255) })\n .strict();\nexport const DidCommTaskSourceBindingSchema = z\n .object({\n schema: z.literal('kya.task.source-binding.v1'),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n installationId: z.string().uuid(),\n ownerEpoch: z.number().int().positive().max(2147483647),\n })\n .strict();\n/** A native message's context is strict: its source binding and, optionally, the repository. */\nconst DidCommSourceContext = z\n .object({\n kyaTaskSource: DidCommTaskSourceBindingSchema,\n repo: Repository.optional(),\n })\n .strict();\nconst DidCommSourceEnvelope = z.object({\n id: z.string().uuid(),\n from: z.string().startsWith('did:key:').max(255),\n to: z.array(z.string().startsWith('did:key:').max(255)).length(1),\n created_time: z.number().int().positive(),\n expires_time: z.number().int().positive(),\n thid: BoundedId,\n pthid: BoundedId.optional(),\n});\nconst DidCommTaskBody = { taskId: BoundedId, context: DidCommSourceContext };\nexport const DidCommTaskSourceMessageSchema = z.discriminatedUnion('type', [\n DidCommSourceEnvelope.extend({\n type: z.literal('https://kya-os.ai/didcomm/task/assign'),\n body: z\n .object({\n ...DidCommTaskBody,\n description: z.string().min(1).max(190000),\n priority: z.enum(['low', 'normal', 'urgent']).optional(),\n relayTimeoutMs: z.number().int().positive().max(86400000).optional(),\n })\n .strict(),\n }).strict(),\n DidCommSourceEnvelope.extend({\n type: z.literal('https://kya-os.ai/didcomm/task/steer'),\n body: z\n .object({\n ...DidCommTaskBody,\n instruction: z.string().min(1).max(190000),\n priority: z.enum(['low', 'normal', 'urgent']).optional(),\n })\n .strict(),\n }).strict(),\n DidCommSourceEnvelope.extend({\n type: z.literal('https://kya-os.ai/didcomm/task/cancel'),\n body: z.object(DidCommTaskBody).strict(),\n }).strict(),\n]);\nexport const TaskSourceProviderConfigSchema = z.discriminatedUnion('provider', [\n GitHubTaskSourceConfigSchema,\n DiscordTaskSourceConfigSchema,\n DidCommTaskSourceConfigSchema,\n A2ATaskSourceConfigSchema,\n]);\nexport const ConfigureTaskSourceInstallationSchema = z\n .object({\n projectId: z.string().uuid(),\n source: TaskSourceProviderConfigSchema,\n /** Setup only: encrypted server custody, never included in source or workload responses. */\n discordBotToken: z.string().min(1).max(8192).optional(),\n enabled: z.boolean().default(true),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict();\n\n/** Authenticated source material, never an executable authorization. */\nexport const TaskSourceIntentSchema = z\n .object({\n schema: z.literal('kya.task.source-intent.v1'),\n taskId: z.string().uuid(),\n operationId: z.string().uuid(),\n installationId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n sessionId: BoundedId,\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n destinationDid: DestinationDid,\n kind: z.enum(['created', 'prompted', 'stop']),\n source: z\n .object({\n provider: TaskSourceProviderSchema,\n workspaceId: BoundedId,\n actorId: BoundedId,\n issueId: BoundedId.optional(),\n })\n .strict(),\n untrustedInput: z\n .string()\n .max(200000)\n .refine(\n (value) =>\n new TextEncoder().encode(value).byteLength <= 200000 &&\n new TextEncoder().encode(JSON.stringify(value)).byteLength <= 400000,\n 'Source input exceeds the UTF-8 or encoded response bound'\n ),\n inputDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n workflow: LinearInstallationWorkflowSchema,\n authorization: z.literal('requires_task_approval'),\n /** B09-P3: the exact signed A2A request Checkpoint verified for this delivery. Only an A2A\n * source carries it; an A2A revision recorded before retention began has none. */\n delivery: A2ASignedRequestSchema.optional(),\n })\n .strict()\n .refine((intent) => intent.delivery === undefined || intent.source.provider === 'a2a', {\n message: 'Only an A2A source carries its signed request',\n path: ['delivery'],\n });\nexport type TaskSourceIntent = z.infer<typeof TaskSourceIntentSchema>;\n\n/** Scope is derived from authenticated workload authority, never request-body tenancy. */\nexport const TaskMailboxScopeSchema = z\n .object({\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n destinationDid: DestinationDid,\n ownerEpoch: z.number().int().positive(),\n })\n .strict();\nexport type TaskMailboxScope = z.infer<typeof TaskMailboxScopeSchema>;\nexport const TaskMailboxClaimRequestSchema = z\n .object({\n ownerEpoch: z.number().int().positive().max(2147483647),\n acceptedProviders: z.array(TaskSourceProviderSchema).min(1).max(5).default(['linear']),\n claimId: z.string().uuid().optional(),\n claimToken: ClaimToken.optional(),\n })\n .strict()\n .refine(\n (value) => Boolean(value.claimId) === Boolean(value.claimToken),\n 'claimId and claimToken must be supplied together'\n );\nexport const TaskMailboxStatusRequestSchema = z\n .object({\n ownerEpoch: z.number().int().positive().max(2147483647),\n claimId: z.string().uuid(),\n })\n .strict();\nexport const TaskMailboxClaimSchema = z\n .object({\n claimId: z.string().uuid(),\n claimToken: ClaimToken,\n claimExpiresAt: z.string().datetime(),\n deliveryState: z.enum(['claimed', 'accepted', 'unknown', 'cancelled']),\n intent: TaskSourceIntentSchema,\n })\n .strict();\nexport type TaskMailboxClaim = z.infer<typeof TaskMailboxClaimSchema>;\nexport const TaskMailboxStatusSchema = z\n .object({\n claimId: z.string().uuid(),\n operationId: z.string().uuid(),\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n deliveryState: z.enum(['pending', 'claimed', 'accepted', 'unknown', 'cancelled']),\n outcome: z.enum(['claimed', 'accepted', 'not_delivered', 'unknown']),\n claimExpiresAt: z.string().datetime(),\n })\n .strict();\nexport type TaskMailboxStatus = z.infer<typeof TaskMailboxStatusSchema>;\nexport const TaskMailboxSettlementSchema = z\n .object({\n claimId: z.string().uuid(),\n operationId: z.string().uuid(),\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n claimToken: ClaimToken,\n outcome: z.enum(['accepted', 'not_delivered', 'unknown']),\n })\n .strict();\nexport type TaskMailboxSettlement = z.infer<typeof TaskMailboxSettlementSchema>;\n\nconst Sha256Digest = z.string().regex(/^sha256:[a-f0-9]{64}$/);\nconst PublicationBindingFields = {\n sourceOperationId: z.string().uuid(),\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n specRevision: z.number().int().positive(),\n manifestDigest: Sha256Digest,\n executionOperationId: z.string().min(1).max(255),\n};\nexport const ApproveTaskPublicationSchema = z\n .object({\n ...PublicationBindingFields,\n reporterDid: KeyDid,\n repository: Repository,\n baseSha: z.string().regex(/^[a-f0-9]{40}$/),\n expiresAt: z.string().datetime(),\n publishDraftPullRequest: z.boolean().default(false),\n })\n .strict();\nexport const FleetPullRequestReceiptSchema = z\n .object({\n schema: z.literal('kya.fleet.pull-request.v1'),\n taskId: z.string().uuid(),\n number: z.number().int().positive(),\n headSha: z.string().regex(/^[a-f0-9]{40}$/),\n })\n .strict();\nexport const TaskMailboxResultSchema = z\n .object({\n ...PublicationBindingFields,\n outcome: z.enum(['completed', 'failed', 'cancelled']),\n artifact: FleetPullRequestReceiptSchema.optional(),\n })\n .strict();\nexport type TaskMailboxResult = z.infer<typeof TaskMailboxResultSchema>;\nexport const ApprovedTaskPublicationSchema = ApproveTaskPublicationSchema.extend({\n schema: z.literal('kya.task.publication-binding.v1'),\n branch: PublicationBranch,\n approvedByUserId: z.string().uuid(),\n approvedAt: z.string().datetime(),\n githubInstallationId: z.number().int().positive().optional(),\n}).strict();\nexport type ApprovedTaskPublication = z.infer<typeof ApprovedTaskPublicationSchema>;\n\nexport const TaskStandingLimitsSchema = z\n .object({\n maxRuntimeSeconds: z.number().int().min(1).max(86400),\n maxCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n maxOperations: z.number().int().min(1).max(10000),\n })\n .strict();\nexport const TaskStandingAdmissionRequestBaseSchema = z\n .object({\n ...PublicationBindingFields,\n workerDid: KeyDid,\n repository: Repository,\n baseSha: z.string().regex(/^[a-f0-9]{40}$/),\n attemptNumber: z.number().int().min(1).max(10),\n capabilities: StandingCapabilities,\n limits: TaskStandingLimitsSchema,\n modelPolicy: TaskModelPolicySchema.optional(),\n })\n .strict();\nexport const validModelAdmission = (value: {\n capabilities: string[];\n modelPolicy?: TaskModelPolicy;\n limits: { maxCostMicrousd: number };\n}) =>\n value.capabilities.includes('model.invoke') === Boolean(value.modelPolicy) &&\n (!value.modelPolicy || value.modelPolicy.reservedCostMicrousd <= value.limits.maxCostMicrousd);\nexport const TaskStandingAdmissionRequestSchema = TaskStandingAdmissionRequestBaseSchema.refine(\n validModelAdmission,\n 'Model capability requires a bounded policy'\n);\nexport type TaskStandingAdmissionRequest = z.infer<typeof TaskStandingAdmissionRequestSchema>;\n/** The v1 receipt before its model refinement, so a later protocol can extend it. */\nexport const TaskStandingAdmissionReceiptBaseSchema = TaskStandingAdmissionRequestBaseSchema.omit({\n workerDid: true,\n})\n .extend({\n schema: z.literal('kya.task.admission.v1'),\n admissionId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n installationId: z.string().uuid(),\n leadDid: DestinationDid,\n holderDid: KeyDid,\n branch: PublicationBranch,\n notBefore: z.string().datetime(),\n expiresAt: z.string().datetime(),\n policyProvenance: z.literal('administrator_registered'),\n requiresOnlineActionGate: z.literal(true),\n credentialExport: z.literal(false),\n })\n .strict();\nexport const TaskStandingAdmissionSchema = TaskStandingAdmissionReceiptBaseSchema.refine(\n validModelAdmission,\n 'Model capability requires a bounded policy'\n);\nexport type TaskStandingAdmission = z.infer<typeof TaskStandingAdmissionSchema>;\nexport const TaskStandingActionSchema = z\n .object({\n admissionId: z.string().uuid(),\n operationId: z.string().uuid(),\n ownerEpoch: z.number().int().positive(),\n action: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('task.start') }).strict(),\n z\n .object({\n kind: z.literal('model.invoke'),\n provider: z.literal('anthropic'),\n model: TaskModelIdSchema,\n requestDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n maxOutputTokens: z.number().int().min(1).max(64000),\n })\n .strict(),\n z\n .object({\n kind: z.literal('task.finish'),\n outcome: z.enum(['completed', 'failed', 'cancelled', 'unknown']),\n })\n .strict(),\n z\n .object({\n kind: z.literal('github.commit'),\n expectedHeadSha: z.string().regex(/^[a-f0-9]{40}$/),\n message: z.string().min(1).max(2000),\n files: z\n .array(\n z\n .object({\n path: z.string().min(1).max(1000),\n content: z.string().max(200000).nullable(),\n })\n .strict()\n )\n .min(1)\n .max(100),\n })\n .strict(),\n z\n .object({\n kind: z.literal('github.pull_request.draft'),\n headSha: z.string().regex(/^[a-f0-9]{40}$/),\n })\n .strict(),\n ]),\n })\n .strict();\nexport type TaskStandingAction = z.infer<typeof TaskStandingActionSchema>;\nexport const TaskStandingReconcileSchema = TaskStandingActionSchema.extend({\n originalOwnerEpoch: z.number().int().positive(),\n}).strict();\nexport type TaskStandingReconcile = z.infer<typeof TaskStandingReconcileSchema>;\n\nexport * from './task-status-projection';\n","import { z } from 'zod';\n\n// A read projection of existing identity/deployment records. This contract does\n// not confer authority and never treats stored deployment status as a live probe.\nconst Text = z\n .string()\n .min(1)\n .max(500)\n .refine((s) =>\n [...s].every((character) => {\n const code = character.charCodeAt(0);\n return code >= 32 && code !== 127;\n })\n );\nconst PublicUrl = z\n .string()\n .url()\n .refine((value) => {\n const url = new URL(value);\n return (\n ['http:', 'https:'].includes(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.search &&\n !url.hash\n );\n });\nexport const CliIdentityQuerySchema = z.object({ projectId: z.string().min(1).max(255) }).strict();\nexport const CliIdentityServiceSchema = z\n .object({\n id: Text,\n kind: z.enum(['registry', 'authorization_host', 'mcp']),\n url: PublicUrl.nullable(),\n status: z.enum(['configured', 'active_recorded', 'inactive_recorded', 'not_configured']),\n observed_at: z.string().datetime().nullable(),\n })\n .strict();\nexport const CliIdentitySummarySchema = z\n .object({\n version: z.literal(1),\n observed_at: z.string().datetime(),\n project: z.object({ id: Text, name: Text }).strict(),\n organization: z\n .object({\n id: Text,\n name: Text,\n slug: Text,\n did_web: Text.refine((value) => value.startsWith('did:web:')).nullable(),\n did_webvh: Text.refine((value) => value.startsWith('did:webvh:')).nullable(),\n registry_state: z.enum(['registered', 'not_registered']),\n })\n .strict()\n .nullable(),\n services: z\n .array(CliIdentityServiceSchema)\n .max(102)\n .refine(\n (services) => new Set(services.map((service) => service.id)).size === services.length\n ),\n })\n .strict()\n .refine(\n (summary) =>\n !summary.organization ||\n (summary.organization.registry_state === 'registered') ===\n Boolean(summary.organization.did_webvh),\n 'Registration state must match the stored registry DID'\n );\nexport type CliIdentitySummary = z.infer<typeof CliIdentitySummarySchema>;\nexport type CliIdentityService = z.infer<typeof CliIdentityServiceSchema>;\n","import { z } from 'zod';\nimport { isPublicSuffixLike } from '../posture-origins';\n\n/**\n * A pixel's `configuration.allowedDomains`: the page hosts a pixel accepts\n * events from (`/api/v1/event` compares them to the event URL's hostname).\n *\n * Stored form is a bare, lowercase, punycoded host (`shop.example.com`) or a\n * leftmost wildcard (`*.example.com`, which covers `example.com` itself and\n * every subdomain, never a look-alike such as `evilexample.com`).\n *\n * The comparison side, `URL.hostname`, is always lowercase with no scheme,\n * port or path, so an entry stored as `*.Example.com`, `https://example.com`\n * or `example.com:443` never matched and 403'd every event. Entries are now\n * normalized on write, and legacy rows are normalized again on read so they\n * stop failing without a backfill.\n */\n\nconst WILDCARD_PROBE_LABEL = 'allowed-domain-wildcard-probe';\nexport const MAX_ALLOWED_DOMAIN_LENGTH = 300;\n/**\n * Most entries one pixel may list. Generous on purpose: each event checks\n * its host against every entry, and the list was uncapped before, so a\n * smaller cap could refuse an existing pixel's next save.\n */\nexport const MAX_ALLOWED_DOMAINS = 1000;\n/** One DNS label after URL's lowercasing and punycoding. `_` occurs in real subdomains. */\nconst HOST_LABEL = /^[a-z0-9_-]{1,63}$/;\nconst DEFAULT_PORTS = new Set(['80', '443']);\n\ninterface ParsedAllowedDomain {\n host: string;\n wildcard: boolean;\n /** A non-default port the entry carried, or ''. */\n port: string;\n}\n\n/** URL accepts empty labels and characters such as `;` or `,`, which no page host has. */\nfunction isHostName(host: string): boolean {\n // URL has already validated a bracketed IPv6 literal.\n if (host.startsWith('[') && host.endsWith(']')) return true;\n return host.split('.').every((label) => HOST_LABEL.test(label));\n}\n\nfunction parseAllowedDomain(entry: string): ParsedAllowedDomain | { error: string } {\n const trimmed = typeof entry === 'string' ? entry.trim() : '';\n if (!trimmed) return { error: 'Enter a domain such as shop.example.com' };\n if (trimmed.length > MAX_ALLOWED_DOMAIN_LENGTH) {\n return { error: `Must be at most ${MAX_ALLOWED_DOMAIN_LENGTH} characters` };\n }\n const schemeMatch = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(trimmed);\n const scheme = schemeMatch ? schemeMatch[1].toLowerCase() : 'https';\n if (scheme !== 'https' && scheme !== 'http') {\n return { error: 'Use a domain name, e.g. shop.example.com' };\n }\n const rest = schemeMatch ? trimmed.slice(schemeMatch[0].length) : trimmed;\n const wildcard = rest.startsWith('*.');\n const withoutWildcard = wildcard ? rest.slice(2) : rest;\n if (!withoutWildcard || withoutWildcard.includes('*')) {\n return { error: 'A wildcard is only allowed as the first label, e.g. *.example.com' };\n }\n let url: URL;\n try {\n // Parsed with the entry's own scheme so its default port (80 or 443)\n // drops out, and with a probe label standing in for `*` so URL still\n // lowercases and punycodes the rest of the host.\n url = new URL(`${scheme}://${wildcard ? `${WILDCARD_PROBE_LABEL}.` : ''}${withoutWildcard}`);\n } catch {\n return { error: 'Not a valid domain' };\n }\n if (url.username || url.password) return { error: 'Domains cannot contain a username' };\n let host = url.hostname.replace(/\\.$/, '');\n if (wildcard) {\n if (!host.startsWith(`${WILDCARD_PROBE_LABEL}.`)) return { error: 'Not a valid domain' };\n host = host.slice(WILDCARD_PROBE_LABEL.length + 1);\n }\n if (!isHostName(host)) return { error: 'Not a valid domain' };\n // 80 and 443 count as default whatever the scheme: an entry with no scheme\n // is parsed as https, where URL would keep `:80`.\n return { host, wildcard, port: DEFAULT_PORTS.has(url.port) ? '' : url.port };\n}\n\nfunction format(parsed: ParsedAllowedDomain): string {\n return `${parsed.wildcard ? '*.' : ''}${parsed.host}`;\n}\n\n/**\n * `*.com`, `*.co.uk`, `*.myshopify.com`: a wildcard that admits sites the\n * customer does not control. Same rule as posture origins, so the two\n * allowlists refuse the same entries.\n */\nfunction isPublicSuffixWildcard(parsed: ParsedAllowedDomain): boolean {\n return parsed.wildcard && isPublicSuffixLike(parsed.host);\n}\n\n/**\n * Strict write-time normalization. Returns the stored form, or an error for\n * junk: another scheme, userinfo, a misplaced wildcard, a host with an empty\n * label or a character no host has, a non-default port (the check compares\n * host names only, so a port would suggest a restriction that is never\n * enforced), or a wildcard over a public suffix.\n *\n * @example\n * normalizeAllowedDomainForWrite('HTTPS://Shop.Example.com:443/cart') // { ok: true, value: 'shop.example.com' }\n * normalizeAllowedDomainForWrite('*.Example.com.') // { ok: true, value: '*.example.com' }\n */\nexport function normalizeAllowedDomainForWrite(\n entry: string\n): { ok: true; value: string } | { ok: false; error: string } {\n const parsed = parseAllowedDomain(entry);\n if ('error' in parsed) return { ok: false, error: parsed.error };\n if (parsed.port) {\n return {\n ok: false,\n error: 'Ports are not supported; the check matches the host name only',\n };\n }\n if (isPublicSuffixWildcard(parsed)) {\n return {\n ok: false,\n error: `*.${parsed.host} would include sites you do not control; list your own hosts instead`,\n };\n }\n return { ok: true, value: format(parsed) };\n}\n\n/**\n * Lenient read-time normalization for entries already stored: strips a\n * scheme, path, port and trailing dot and lowercases, so a legacy entry\n * such as `https://Example.com:443/` still matches. Undefined for entries\n * that cannot be a host at all (they then match nothing, as before).\n *\n * It never widens what a pixel accepts to a public suffix. A malformed\n * wildcard over one (`*.COM`, `https://*.co.uk`) matched nothing before, and\n * cleaning it up would admit every site under it, which writes now refuse.\n * So it stays undefined. One already stored in exact form (`*.com`) matched\n * before this normalization existed and is returned unchanged.\n */\nexport function normalizeStoredAllowedDomain(entry: unknown): string | undefined {\n if (typeof entry !== 'string') return undefined;\n const parsed = parseAllowedDomain(entry);\n if ('error' in parsed) return undefined;\n const normalized = format(parsed);\n if (isPublicSuffixWildcard(parsed) && entry !== normalized) return undefined;\n return normalized;\n}\n\n/**\n * Whether a page host is admitted by a pixel's allowed domains. Exact\n * entries match the host exactly; `*.example.com` matches `example.com`\n * and any subdomain, on a label boundary.\n *\n * @example\n * hostMatchesAllowedDomains('shop.example.com', ['*.Example.com']) // true\n * hostMatchesAllowedDomains('evilexample.com', ['*.example.com']) // false\n */\nexport function hostMatchesAllowedDomains(hostname: string, allowedDomains: unknown[]): boolean {\n const host = hostname.toLowerCase().replace(/\\.$/, '');\n if (!host) return false;\n return allowedDomains.some((raw) => {\n const entry = normalizeStoredAllowedDomain(raw);\n if (!entry) return false;\n if (!entry.startsWith('*.')) return host === entry;\n const base = entry.slice(2);\n return host === base || host.endsWith(`.${base}`);\n });\n}\n\n/**\n * Normalizes a whole list for a write: stored forms in first-seen order with\n * duplicates removed, plus each junk entry's index and reason. Linear in the\n * list's length.\n *\n * @example\n * normalizeAllowedDomainList(['Example.com', 'a..b', 'example.com'])\n * // { values: ['example.com'], errors: [{ index: 1, message: 'Not a valid domain' }] }\n */\nexport function normalizeAllowedDomainList(entries: readonly string[]): {\n values: string[];\n errors: Array<{ index: number; message: string }>;\n} {\n const values = new Set<string>();\n const errors: Array<{ index: number; message: string }> = [];\n entries.forEach((entry, index) => {\n const result = normalizeAllowedDomainForWrite(entry);\n if (result.ok) values.add(result.value);\n else errors.push({ index, message: result.error });\n });\n return { values: [...values], errors };\n}\n\n/**\n * `allowedDomains` on a pixel write: at most {@link MAX_ALLOWED_DOMAINS}\n * entries, each normalized to its stored form (duplicates removed), and each\n * junk entry reported at its index so the route's 400 says which one and\n * why. The cap is checked first, so an oversized list is refused without\n * normalizing any entry.\n */\nexport const AllowedDomainsSchema = z\n .array(z.string())\n .max(MAX_ALLOWED_DOMAINS, `At most ${MAX_ALLOWED_DOMAINS} allowed domains`)\n .transform((entries, ctx) => {\n const { values, errors } = normalizeAllowedDomainList(entries);\n errors.forEach(({ index, message }) =>\n ctx.addIssue({ code: 'custom', message, path: [index] })\n );\n return values;\n });\n","/**\n * Bulk Operations API schemas\n *\n * Standard schemas for bulk CRUD operations across all resources\n */\n\nimport { z } from 'zod';\nimport { AllowedDomainsSchema } from '../utils/allowed-domains';\n\nexport const MAX_BULK_BATCH_SIZE = 100;\n\n/**\n * Bulk operation types\n */\nexport const BulkOperationTypeSchema = z.enum(['create', 'update', 'delete']);\n\n/**\n * Bulk operation options\n */\nexport const BulkOperationOptionsSchema = z.object({\n /** Continue processing remaining items on failure */\n continueOnError: z.boolean().default(true).optional(),\n /** Execute all operations in a single transaction (all-or-nothing) */\n transactional: z.boolean().default(false).optional(),\n /** Validate only without executing (dry run) */\n validateOnly: z.boolean().default(false).optional(),\n /** Preview what would be deleted without executing (alias for validateOnly on delete) */\n dryRun: z.boolean().default(false).optional(),\n});\n\n/**\n * Base bulk request schema\n */\nexport const BaseBulkRequestSchema = z.object({\n operation: BulkOperationTypeSchema,\n options: BulkOperationOptionsSchema.optional(),\n});\n\n/**\n * Bulk result item\n */\nexport const BulkResultItemSchema = z.object({\n index: z.number(),\n success: z.boolean(),\n data: z.unknown().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n })\n .optional(),\n});\nexport type BulkResultItem = z.infer<typeof BulkResultItemSchema>;\n\n/**\n * Bulk response\n */\nexport const BulkResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().uuid(),\n summary: z.object({\n total: z.number(),\n succeeded: z.number(),\n failed: z.number(),\n skipped: z.number(),\n }),\n results: z.array(BulkResultItemSchema),\n metadata: z\n .object({\n processingTime: z.number(),\n transactional: z.boolean(),\n dryRun: z.boolean().optional(),\n })\n .optional(),\n});\nexport type BulkResponse = z.infer<typeof BulkResponseSchema>;\n\n/**\n * Bulk delete preview stats for a single project\n */\nexport const BulkDeletePreviewStatsSchema = z.object({\n projectId: z.string().uuid(),\n friendlyId: z.string().nullable(),\n name: z.string(),\n counts: z.object({\n detections: z.number(),\n pixels: z.number(),\n apiKeys: z.number(),\n members: z.number(),\n bouncerConfigs: z.number(),\n delegations: z.number(),\n bouncerProofs: z.number(),\n bouncerSessions: z.number(),\n userAccounts: z.number(),\n userProfiles: z.number(),\n }),\n totalRecords: z.number(),\n});\nexport type BulkDeletePreviewStats = z.infer<typeof BulkDeletePreviewStatsSchema>;\n\n/**\n * Bulk delete response with optional preview\n */\nexport const BulkDeleteResponseSchema = BulkResponseSchema.extend({\n preview: z.array(BulkDeletePreviewStatsSchema).optional(),\n});\nexport type BulkDeleteResponse = z.infer<typeof BulkDeleteResponseSchema>;\n\n/**\n * Projects Bulk Request\n */\nexport const ProjectsBulkCreateItemSchema = z.object({\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\n\nexport const ProjectsBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n webhookUrl: z.string().url().nullable().optional(),\n webhookSecret: z.string().nullable().optional(),\n })\n .optional(),\n});\n\nexport const ProjectsBulkDeleteItemSchema = z.object({\n /** Project UUID to delete */\n id: z.string().uuid(),\n /** Skip confirmation for automated cleanup (admin only) */\n force: z.boolean().optional(),\n});\n\nexport const ProjectsBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(ProjectsBulkCreateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(ProjectsBulkUpdateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(ProjectsBulkDeleteItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n ])\n);\nexport type ProjectsBulkRequest = z.infer<typeof ProjectsBulkRequestSchema>;\n\n/**\n * Pixels Bulk Request\n */\nexport const PixelsBulkCreateItemSchema = z.object({\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n isActive: z.boolean().default(true),\n configuration: z\n .object({\n allowedDomains: AllowedDomainsSchema.default([]),\n collectBehavioral: z.boolean().default(true),\n enableFingerprinting: z.boolean().default(true),\n enableSessionTracking: z.boolean().default(true),\n sampleRate: z.number().min(0).max(1).default(1),\n })\n .optional(),\n});\n\nexport const PixelsBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n isActive: z.boolean().optional(),\n configuration: z\n .object({\n allowedDomains: AllowedDomainsSchema.optional(),\n collectBehavioral: z.boolean().optional(),\n enableFingerprinting: z.boolean().optional(),\n enableSessionTracking: z.boolean().optional(),\n sampleRate: z.number().min(0).max(1).optional(),\n })\n .optional(),\n});\n\nexport const PixelsBulkDeleteItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const PixelsBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(PixelsBulkCreateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(PixelsBulkUpdateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(PixelsBulkDeleteItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n ])\n);\nexport type PixelsBulkRequest = z.infer<typeof PixelsBulkRequestSchema>;\n\n/**\n * API Keys Bulk Request\n */\nexport const ApiKeysBulkCreateItemSchema = z.object({\n name: z.string().min(1).max(255),\n projectId: z.string().uuid().optional(),\n permissions: z.array(z.enum(['read', 'write', 'admin'])).default(['read']),\n rateLimits: z\n .object({\n requestsPerSecond: z.number().min(1).optional(),\n requestsPerMinute: z.number().min(1).optional(),\n requestsPerHour: z.number().min(1).optional(),\n requestsPerDay: z.number().min(1).optional(),\n })\n .optional(),\n expiresAt: z.string().datetime().optional(),\n});\n\nexport const ApiKeysBulkRevokeItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const ApiKeysBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n permissions: z.array(z.enum(['read', 'write', 'admin'])).optional(),\n rateLimits: z\n .object({\n requestsPerSecond: z.number().min(1).optional(),\n requestsPerMinute: z.number().min(1).optional(),\n requestsPerHour: z.number().min(1).optional(),\n requestsPerDay: z.number().min(1).optional(),\n })\n .optional(),\n expiresAt: z.string().datetime().optional().nullable(),\n});\n\nexport const ApiKeysBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(ApiKeysBulkCreateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(ApiKeysBulkUpdateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(ApiKeysBulkRevokeItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n ])\n);\nexport type ApiKeysBulkRequest = z.infer<typeof ApiKeysBulkRequestSchema>;\n\n/**\n * Bulk operation error codes\n */\nexport const BULK_ERROR_CODES = {\n BATCH_TOO_LARGE: 'BATCH_TOO_LARGE',\n INVALID_OPERATION: 'INVALID_OPERATION',\n TRANSACTION_FAILED: 'TRANSACTION_FAILED',\n TRANSACTION_ABORTED: 'TRANSACTION_ABORTED',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n PARTIAL_FAILURE: 'PARTIAL_FAILURE',\n LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',\n OWNERSHIP_ERROR: 'OWNERSHIP_ERROR',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n DELETE_FAILED: 'DELETE_FAILED',\n SKIPPED: 'SKIPPED',\n NOT_FOUND: 'NOT_FOUND',\n} as const;\n","/**\n * Buckets an `agent_daily_rollup` row `(agent_type, detection_class)` into\n * the admin overview's four-bucket AI traffic taxonomy, reproducing the\n * internal \"Customers & Installations\" report's overlay.\n *\n * Name wins over class: historical rows stamped training crawlers\n * (ClaudeBot, GPTBot) as `ai_agent`, so the overlay name lists below take\n * precedence over the stored `detection_class` before either falls back to\n * `KNOWN_AGENT_PATTERNS` and then to the class itself.\n */\n\nimport { KNOWN_AGENT_PATTERNS } from './agents';\nimport type { AgentPattern } from '../core/agent';\nimport type { TrafficTaxonomyBucket } from '../types/admin-overview';\nimport type { DetectionClassEnum } from '../utils/detection-class';\n\n/**\n * Training / indexing crawlers run by AI vendors. Values are the exact names\n * stored in detections.agent_type: KNOWN_AGENT_PATTERNS `name`s for the TS\n * classifier path and the engine's emitted names (which keep their spaces,\n * e.g. 'Bytedance Crawler') for the WASM path.\n *\n */\nexport const REPORT_AI_CRAWLER_NAMES: readonly string[] = [\n 'GPTBot',\n 'ClaudeBot',\n 'Anthropic-AI Crawler',\n 'PerplexityBot',\n 'Google-Extended',\n 'Gemini-Deep-Research',\n 'Meta-ExternalAgent',\n 'Meta AI',\n 'CohereBot',\n 'DeepSeekBot',\n 'MistralBot',\n 'Amazonbot',\n 'Amazon Bedrock',\n 'Common Crawl',\n 'Bytedance Crawler',\n];\n/** Interactive assistants / agents acting for a person. */\nexport const REPORT_AI_AGENT_NAMES: readonly string[] = [\n 'ChatGPT',\n 'ChatGPT-User',\n 'OpenAI',\n 'Claude',\n 'Claude-User',\n 'Anthropic',\n 'Perplexity',\n 'Perplexity-User',\n 'Google Gemini',\n 'Microsoft Copilot',\n 'DeepSeek AI',\n 'xAI Grok',\n 'Amazon Q',\n 'Kya Agent',\n];\n\n// Built once at module scope: lowercase membership sets for the overlay\n// lists, and a lowercase name-or-id lookup into KNOWN_AGENT_PATTERNS.\nconst CRAWLER_NAME_SET = new Set(REPORT_AI_CRAWLER_NAMES.map((name) => name.toLowerCase()));\nconst AGENT_NAME_SET = new Set(REPORT_AI_AGENT_NAMES.map((name) => name.toLowerCase()));\n\n/**\n * Build a lowercase name-or-id lookup over `patterns`, first-wins: the first\n * match in source order wins so a later entry that reuses a name cannot\n * silently change a bucket. Exported so the rule is testable on synthetic\n * input.\n */\nexport function buildKnownPatternLookup(\n patterns: readonly AgentPattern[]\n): ReadonlyMap<string, AgentPattern> {\n const map = new Map<string, AgentPattern>();\n for (const entry of patterns) {\n const nameKey = entry.name.toLowerCase();\n const idKey = entry.id.toLowerCase();\n if (!map.has(nameKey)) map.set(nameKey, entry);\n if (!map.has(idKey)) map.set(idKey, entry);\n }\n return map;\n}\n\nconst KNOWN_PATTERN_BY_NAME_OR_ID = buildKnownPatternLookup(KNOWN_AGENT_PATTERNS);\n\n/**\n * Classify a rollup row's `(agent_type, detection_class)` pair into a\n * {@link TrafficTaxonomyBucket}. An unidentified agent (`agent_type` null,\n * stored as 'Unknown' by the rollup) falls to the class fallback, so an\n * `ai_agent`-classed unidentified row counts as an AI agent and a\n * `bot`-classed one as other automation.\n */\nexport function classifyAgentTaxonomy(\n agentType: string | null | undefined,\n detectionClass: DetectionClassEnum | string | null | undefined\n): TrafficTaxonomyBucket {\n if (detectionClass === 'human') return 'human';\n\n const normalized = agentType?.trim().toLowerCase();\n if (normalized) {\n if (CRAWLER_NAME_SET.has(normalized)) return 'ai_crawler';\n if (AGENT_NAME_SET.has(normalized)) return 'ai_agent';\n\n const known = KNOWN_PATTERN_BY_NAME_OR_ID.get(normalized);\n if (known) {\n return (known.category ?? 'ai_assistant') === 'ai_assistant' ? 'ai_agent' : 'ai_crawler';\n }\n }\n\n return detectionClass === 'ai_agent' ? 'ai_agent' : 'other_automation';\n}\n","/**\n * Database Entity Types\n *\n * Shared types for database entities used across the dashboard,\n * API, and other packages in the monorepo.\n */\n\nimport { z } from 'zod';\nimport { ipAddressSchema } from '../utils/zod-helpers';\nimport { AllowedDomainsSchema } from '../utils/allowed-domains';\n\n/**\n * User Plan Levels\n */\nexport const UserPlanSchema = z.enum(['free', 'pro', 'enterprise']);\nexport type UserPlan = z.infer<typeof UserPlanSchema>;\n\n/**\n * API Key Permissions\n */\nexport const ApiKeyPermissionSchema = z.enum(['read', 'write', 'admin', 'forward']);\nexport type ApiKeyPermission = z.infer<typeof ApiKeyPermissionSchema>;\n\n/**\n * User Entity\n */\nexport const UserSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email(),\n name: z.string().nullish(),\n image: z.string().url().nullish(),\n emailVerified: z.date().nullish(),\n plan: UserPlanSchema.default('free'),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type User = z.infer<typeof UserSchema>;\n\n/**\n * Project Settings\n */\nexport const ProjectSettingsSchema = z.object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n // A caller-controlled configuration value, not a feature flag: raises a\n // project's beacon-ingest rate-limit ceiling above its plan's fixed\n // per-minute default (`PLAN_RATE_LIMITS[plan].requestsPerMinute`), for a\n // high-traffic tenant whose real visitor volume concentrates behind one\n // shared IP (e.g. a corporate NAT).\n beaconRateLimitPerMinute: z.number().int().positive().optional(),\n // Additional page origins browser posture may be issued for, beyond the\n // primary derived from `domain` (see `../posture-origins`). Lenient on\n // read: readers re-validate through `readPostureOriginsSetting`.\n postureOrigins: z.array(z.string()).optional(),\n postureReportPaths: z.array(z.string()).optional(),\n beaconIngestMode: z.enum(['origin', 'worker']).optional(),\n});\nexport type ProjectSettings = z.infer<typeof ProjectSettingsSchema>;\n\n/**\n * Project Entity\n */\nexport const ProjectSchema = z.object({\n id: z.string().uuid(),\n friendlyId: z.string().nullable().optional(), // Human-readable project ID for URLs\n userId: z.string().uuid(),\n name: z.string().min(1).max(255),\n domain: z.string().optional(),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ProjectSettingsSchema. prefault parses it, as Zod 3 did.\n settings: ProjectSettingsSchema.prefault({}),\n // Setup Flow v2 step 1 (\"What brings you here?\") selections, if this\n // project was created via that flow — see CreateProjectSchema's own\n // doc comment. Null/absent for every other creation path.\n setupGoals: z.array(z.string()).nullable().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Project = z.infer<typeof ProjectSchema>;\n\n/**\n * Pixel Configuration\n */\nexport const PixelConfigurationSchema = z.object({\n enabled: z.boolean().default(true),\n skipPaths: z.array(z.string()).default([]),\n // Normalized on write (lowercase host or `*.host`, no scheme/port/path);\n // junk is a 400 naming the entry. See utils/allowed-domains.ts.\n allowedDomains: AllowedDomainsSchema.default([]),\n blockedAgents: z.array(z.string()).default([]),\n batchSize: z.number().min(1).max(100).default(10),\n flushInterval: z.number().min(100).max(60000).default(5000),\n enableBehavioralTracking: z.boolean().default(true),\n enableSessionReplay: z.boolean().default(false),\n customHeaders: z.record(z.string(), z.string()).default({}),\n});\nexport type PixelConfiguration = z.infer<typeof PixelConfigurationSchema>;\n\n/**\n * Pixel Entity\n */\nexport const PixelSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n secretKey: z.string().min(32),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside PixelConfigurationSchema. prefault parses it, as Zod 3 did.\n configuration: PixelConfigurationSchema.prefault({}),\n isActive: z.boolean().default(true),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Pixel = z.infer<typeof PixelSchema>;\n\n/**\n * Pixel Statistics\n */\nexport const PixelStatsSchema = z.object({\n totalEvents: z.number().int().min(0),\n agentsDetected: z.number().int().min(0),\n uniqueSessions: z.number().int().min(0),\n averageConfidence: z.number().min(0).max(1),\n lastEventAt: z.date().optional(),\n periodStart: z.date(),\n periodEnd: z.date(),\n});\nexport type PixelStats = z.infer<typeof PixelStatsSchema>;\n\n/**\n * API Key Rate Limits\n */\nexport const ApiKeyRateLimitsSchema = z.object({\n requestsPerSecond: z.number().min(1).default(10),\n requestsPerMinute: z.number().min(1).default(100),\n requestsPerHour: z.number().min(1).default(1000),\n requestsPerDay: z.number().min(1).default(10000),\n burstLimit: z.number().min(1).default(20),\n});\nexport type ApiKeyRateLimits = z.infer<typeof ApiKeyRateLimitsSchema>;\n\n/**\n * API Key Entity\n */\nexport const ApiKeySchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n projectId: z.string().uuid().optional(),\n name: z.string().min(1).max(255),\n key: z.string().min(32),\n permissions: z.array(ApiKeyPermissionSchema).default(['read']),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ApiKeyRateLimitsSchema. prefault parses it, as Zod 3 did.\n rateLimits: ApiKeyRateLimitsSchema.prefault({}),\n lastUsedAt: z.date().optional(),\n expiresAt: z.date().optional(),\n createdAt: z.date(),\n revokedAt: z.date().optional(),\n});\nexport type ApiKey = z.infer<typeof ApiKeySchema>;\n\n/**\n * Detection Log Entity\n */\nexport const DetectionLogSchema = z.object({\n id: z.string().uuid(),\n pixelId: z.string().uuid(),\n projectId: z.string().uuid(),\n isAgent: z.boolean(),\n confidence: z.number().min(0).max(100), // Stored as 0-100 in DB\n agentType: z.string().optional(),\n userAgent: z.string().optional(),\n ipAddress: ipAddressSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n sessionId: z.string().optional(),\n createdAt: z.date(),\n});\nexport type DetectionLog = z.infer<typeof DetectionLogSchema>;\n\n/**\n * Session Entity (for NextAuth)\n */\nexport const SessionSchema = z.object({\n sessionToken: z.string(),\n userId: z.string().uuid(),\n expires: z.date(),\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\n/**\n * Account Entity (for OAuth providers)\n */\nexport const AccountSchema = z.object({\n userId: z.string().uuid(),\n type: z.string(),\n provider: z.string(),\n providerAccountId: z.string(),\n refresh_token: z.string().optional(),\n access_token: z.string().optional(),\n expires_at: z.number().optional(),\n token_type: z.string().optional(),\n scope: z.string().optional(),\n id_token: z.string().optional(),\n session_state: z.string().optional(),\n});\nexport type Account = z.infer<typeof AccountSchema>;\n\n/**\n * Verification Token Entity\n */\nexport const VerificationTokenSchema = z.object({\n identifier: z.string(),\n token: z.string(),\n expires: z.date(),\n});\nexport type VerificationToken = z.infer<typeof VerificationTokenSchema>;\n","/**\n * Provider Registry Re-exports\n *\n * This file re-exports types and schemas from @kya-os/provider-registry,\n * providing Checkpoint with a single source of truth for provider definitions\n * and eliminating type fragmentation bugs.\n *\n * ## Why This File Exists\n *\n * Prior to this integration, Checkpoint defined its own provider types that\n * diverged from the canonical types in provider-registry:\n * - Checkpoint used 'credential' while provider-registry uses 'password'\n * - Field names differed: 'authorizationUrl' vs 'authorizationEndpoint'\n * - Schemas were duplicated rather than shared\n *\n * ## Migration Notes\n *\n * For backward compatibility, we provide aliases:\n * - `AuthProviderType` = `ProviderAuthType` (with 'credential' mapped to 'password')\n *\n * @module provider-registry\n */\n\n// ==============================================================================\n// RE-EXPORT FROM @kya-os/provider-registry\n// ==============================================================================\n\n// Types only. The registry's runtime values (AUTH_MODES, PROVIDER_AUTH_TYPES,\n// the provider schemas and validators) are on the\n// `@kya-os/checkpoint-shared/provider-registry` entry instead: importing the\n// registry loads @kya-os/contracts, @kya-os/consent and a second Zod, which\n// the root entry should not make every consumer pay for.\nexport type {\n ProviderAuthType,\n ConsentProviderType,\n ProviderDefinition as ProviderRegistryDefinition,\n ProviderConfig,\n OAuthProviderConfig,\n CredentialProviderConfig,\n AuthMode,\n IProviderRegistry,\n RegistryLogger,\n} from '@kya-os/provider-registry';\n\n// ==============================================================================\n// BACKWARD COMPATIBILITY ALIASES\n// ==============================================================================\n\n/**\n * Backward compatibility alias for AuthProviderType.\n *\n * Checkpoint previously used 'credential' instead of 'password'.\n * This type alias allows existing code to continue working.\n *\n * @deprecated Use `ProviderAuthType` from provider-registry directly.\n * This alias maps:\n * - 'credential' → 'password' (canonical name)\n * - 'oauth2' → 'oauth2' (unchanged)\n */\nexport type LegacyAuthProviderType = 'oauth2' | 'credential';\n\n/**\n * Maps legacy auth type values to canonical provider-registry values.\n *\n * @example\n * ```typescript\n * import { mapLegacyAuthType } from '@kya-os/checkpoint-shared';\n *\n * const canonicalType = mapLegacyAuthType('credential'); // 'password'\n * ```\n */\nexport function mapLegacyAuthType(\n legacyType: LegacyAuthProviderType | string\n): 'oauth2' | 'password' | string {\n switch (legacyType) {\n case 'credential':\n case 'credentials':\n return 'password';\n case 'oauth2':\n return 'oauth2';\n default:\n return legacyType;\n }\n}\n\n/**\n * Maps canonical provider-registry auth types to legacy Checkpoint types.\n *\n * Useful when maintaining backward compatibility with existing API responses.\n *\n * @example\n * ```typescript\n * import { mapToLegacyAuthType } from '@kya-os/checkpoint-shared';\n *\n * const legacyType = mapToLegacyAuthType('password'); // 'credential'\n * ```\n */\nexport function mapToLegacyAuthType(canonicalType: string): 'oauth2' | 'credential' | string {\n switch (canonicalType) {\n case 'password':\n return 'credential';\n case 'oauth2':\n return 'oauth2';\n default:\n return canonicalType;\n }\n}\n\n// ==============================================================================\n// AUTHORIZATION MODE CONSTANTS (from provider-registry)\n// ==============================================================================\n\n/**\n * Authorization modes supported by Checkpoint Bouncer.\n *\n * These are aligned with consent UI auth modes and provider capabilities.\n *\n * Note: This is re-exported from @kya-os/provider-registry for consistency.\n * The canonical source is AUTH_MODES from provider-registry.\n */\nexport const AUTHORIZATION_MODES = {\n /** OAuth2 authentication flow */\n OAUTH: 'oauth',\n /** Username/password credential authentication */\n CREDENTIAL: 'credential',\n /** Consent-only - no authentication required */\n CONSENT_ONLY: 'consent-only',\n // Future modes (aligned with provider-registry):\n // PASSKEY: 'passkey',\n // MAGIC_LINK: 'magic-link',\n // OTP: 'otp',\n // IDV: 'idv',\n} as const;\n\nexport type AuthorizationMode = (typeof AUTHORIZATION_MODES)[keyof typeof AUTHORIZATION_MODES];\n","/**\n * Bouncer Schemas\n *\n * Zod schemas for Agent Bouncer KYA-OS protocol validation.\n *\n * ## Provider Registry Integration\n *\n * As of v0.3.0, this module imports core provider types from @kya-os/provider-registry\n * to eliminate type fragmentation between Checkpoint and KYA-OS.\n *\n * Key types imported:\n * - `ProviderAuthType` (canonical: 'oauth2' | 'password' | 'passkey' | etc.)\n * - `ProviderDefinition` (canonical provider metadata structure)\n * - `OAuthProviderConfig`, `CredentialProviderConfig` (canonical configs)\n *\n * For backward compatibility, we alias:\n * - `AuthProviderType` → maps 'credential' to 'password' internally\n */\n\nimport { z } from 'zod';\n\n// Import canonical types from provider-registry\nimport {\n type ProviderAuthType,\n type ConsentProviderType,\n mapLegacyAuthType,\n mapToLegacyAuthType,\n} from './provider-registry';\n\n// Re-export for consumers\nexport { mapLegacyAuthType, mapToLegacyAuthType };\n\n/**\n * Hex color validation regex - accepts #RRGGBB format only (6 hex digits)\n * Used for consent branding colors where we append alpha values like \"20\" or \"40\"\n * Note: 3-char hex (#RGB) is NOT allowed because appending alpha creates invalid 5-char CSS (#RGB20)\n * Note: 8-char hex (#RRGGBBAA) is NOT allowed because appending alpha would create invalid 10-char CSS\n */\nconst hexColorRegex = /^#[0-9A-Fa-f]{6}$/;\n\n/**\n * HTTP(S)-only URL validator.\n *\n * `z.string().url()` alone accepts dangerous pseudo-protocols like\n * `javascript:`, `data:`, `vbscript:`, and `file:` because the underlying\n * URL constructor parses them as valid URLs. When these values are later\n * rendered into `<a href>` or `<img src>` on a public page, they become\n * stored-XSS vectors.\n *\n * This validator parses the URL and explicitly requires the protocol to\n * be `http:` or `https:`. Used for every customer-editable URL field that\n * eventually gets rendered to a browser (logoUrl, termsUrl, mcpServerUrl,\n * etc.).\n *\n * Defense in depth — the render layer (`sanitizeDisplayUrl` in\n * apps/web/lib/utils/url-security.ts) also sanitizes at render time, so\n * legacy/direct-DB values don't bypass this.\n *\n * IMPORTANT: `maxLength` is opt-in with NO DEFAULT on purpose. Earlier\n * versions of this helper defaulted to 500 characters, which silently\n * capped fields that previously had no length cap — notably `authUrl` in\n * `DelegationPollingStatusSchema` and `mcpServerUrl` / `mcpWorkerUrl` in\n * `BouncerConfigSchema`. OAuth authorization URLs with scopes + PKCE +\n * state + redirect_uri routinely exceed 500 characters, so those fields\n * must NOT be capped. Always pass `maxLength` explicitly at the call site\n * and match the field's original constraint.\n *\n * @param maxLength - Optional maximum URL length. Pass only if the field\n * had a length cap before; pass nothing to preserve \"no length limit\".\n * @returns A zod schema that accepts only http(s) URLs\n */\nexport function httpUrlSchema(maxLength?: number) {\n const base = maxLength !== undefined ? z.string().url().max(maxLength) : z.string().url();\n return base.refine(\n (value) => {\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n },\n { message: 'URL must use http:// or https:// protocol' }\n );\n}\n\n/**\n * OAuth Provider Types\n */\nexport const OAuthProviderTypeSchema = z.enum(['oauth2', 'oidc', 'custom']);\nexport type OAuthProviderType = z.infer<typeof OAuthProviderTypeSchema>;\n\n/**\n * OAuth Connection Status\n */\nexport const OAuthConnectionStatusSchema = z.enum(['connected', 'disconnected', 'error']);\nexport type OAuthConnectionStatus = z.infer<typeof OAuthConnectionStatusSchema>;\n\n// ==============================================================================\n// MULTI-PROVIDER OAUTH TYPES (CRED-001)\n// Provider Registry Integration: Types aligned with @kya-os/provider-registry\n// ==============================================================================\n\n/**\n * Auth Provider Type - determines the authentication method.\n *\n * **Provider Registry Integration:**\n * - Canonical types: 'oauth2' | 'password' (from provider-registry)\n * - Legacy alias: 'credential' maps to 'password' internally\n *\n * For new code, prefer using 'password' for credential-based auth.\n * The 'credential' value is accepted for backward compatibility.\n *\n * @see PROVIDER_AUTH_TYPES from @kya-os/provider-registry for canonical values\n */\nexport const AuthProviderTypeSchema = z\n .enum(['oauth2', 'credential', 'password'])\n .transform((val) => {\n // Map legacy 'credential' to canonical 'password'\n if (val === 'credential') return 'password';\n return val;\n });\n\n/**\n * Auth Provider Type (input) - what clients can send\n * Accepts both canonical ('password') and legacy ('credential') values\n */\nexport type AuthProviderTypeInput = 'oauth2' | 'credential' | 'password';\n\n/**\n * Auth Provider Type (canonical) - normalized output type\n * Always 'oauth2' or 'password' after schema transformation\n */\nexport type AuthProviderType = 'oauth2' | 'password';\n\n/**\n * Legacy type alias for backward compatibility\n * @deprecated Use AuthProviderType directly\n */\nexport type LegacyAuthProviderType = 'oauth2' | 'credential';\n\n// Re-export the canonical type from provider-registry\nexport type { ProviderAuthType, ConsentProviderType };\n\n// ==============================================================================\n// PROVIDER SECRET METADATA (Provider Registry Alignment)\n// ==============================================================================\n\n/**\n * Secret name constraints: alphanumeric, underscores, max 128 chars\n * Pattern: KYA_{env}_{projectSlug}_{providerId}_{secretType}\n */\nexport const SecretNameSchema = z\n .string()\n .regex(/^[A-Z][A-Z0-9_]{2,127}$/, 'Secret name must be uppercase alphanumeric with underscores')\n .max(128);\nexport type SecretName = z.infer<typeof SecretNameSchema>;\n\n/**\n * Provider Secret Metadata - references to secrets stored in secure storage\n *\n * SECURITY: This schema stores ONLY metadata and secret names, NEVER actual secret values.\n * Secret values are resolved at runtime from Cloudflare Worker Secrets.\n */\nexport const ProviderSecretMetadataSchema = z.object({\n // Secret references (use consistent naming: *SecretName)\n clientIdSecretName: SecretNameSchema.optional(),\n clientSecretName: SecretNameSchema.optional(),\n apiKeySecretName: SecretNameSchema.optional(),\n // Rotation tracking\n clientSecretVersion: z.number().int().positive().optional(),\n lastRotatedAt: z.string().datetime().optional(),\n});\nexport type ProviderSecretMetadata = z.infer<typeof ProviderSecretMetadataSchema>;\n\n/**\n * Base Auth Provider - common fields for all provider types\n */\nexport const BaseAuthProviderSchema = z.object({\n displayName: z.string().max(100).optional(),\n status: OAuthConnectionStatusSchema.default('disconnected'),\n});\nexport type BaseAuthProvider = z.infer<typeof BaseAuthProviderSchema>;\n\n/**\n * OAuth2 Provider Configuration\n * Stores all configuration for an OAuth2 provider\n */\nexport const OAuth2ProviderSchema = BaseAuthProviderSchema.extend({\n type: z.literal('oauth2'),\n clientId: z.string().max(255),\n clientSecret: z.string().optional(), // Encrypted, never returned in GET - TO BE DEPRECATED\n authEndpoint: z.string().max(500),\n tokenEndpoint: z.string().max(500),\n userInfoUrl: httpUrlSchema(500).optional(), // User info endpoint for identity resolution\n /**\n * Optional dot-path field mapping into the `userInfoUrl` response for\n * merchant identity extraction (native consent merchant-oauth leg).\n * When absent, extraction defaults to: userId ← first present of\n * `sub`/`id`/`customerId`; userEmail ← `email`.\n */\n userInfoFields: z\n .object({\n userId: z.string().max(255).optional(), // JSON dot-path to the customer id\n userEmail: z.string().max(255).optional(), // JSON dot-path to the customer email\n })\n .optional(),\n redirectUri: z.string().max(500),\n scopes: z.array(z.string()).optional(),\n supportsPKCE: z.boolean().optional(),\n // Phase 3 fields\n customParams: z.record(z.string(), z.string()).optional(),\n tokenEndpointAuthMethod: z.enum(['client_secret_post', 'client_secret_basic']).optional(),\n responseType: z.string().optional(),\n grantType: z.string().optional(),\n // Provider Registry Alignment: Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type OAuth2Provider = z.infer<typeof OAuth2ProviderSchema>;\n\n/**\n * Credential Provider Configuration\n * Stores configuration for username/password, email/password, or cookie-based authentication\n *\n * Supports:\n * - JSON token responses (JWT, Bearer tokens)\n * - Cookie-based sessions (like HardwareWorld)\n * - Custom response validation\n */\nexport const CredentialProviderSchema = BaseAuthProviderSchema.extend({\n type: z.literal('credential'),\n authEndpoint: z.string().max(500),\n\n // Request configuration\n requestBodyTemplate: z.record(z.string(), z.string()).optional(), // Field mapping for request body\n\n // Response field mapping\n responseFields: z.object({\n // Session/auth token - can be JWT, session cookie, or any auth identifier\n sessionToken: z.string(), // JSON path to auth token (renamed from accessToken for clarity)\n userId: z.string().optional(), // JSON path to user ID\n userEmail: z.string().optional(), // JSON path to user email (for delegation records)\n userDisplayName: z.string().optional(), // JSON path to display name (for consent screens)\n expiresIn: z.string().optional(), // JSON path to token expiry (optional for cookie-based)\n }),\n\n // Success validation - verify the login actually succeeded\n successCheck: z\n .object({\n path: z.string(), // JSON path to check (e.g., \"success\", \"status\")\n expectedValue: z.union([z.string(), z.boolean(), z.number()]), // Expected value (e.g., true, \"ok\", 200)\n })\n .optional(),\n\n // Custom headers for API requests\n headers: z.record(z.string(), z.string()).optional(),\n\n // Token usage configuration (CRED-002)\n // Tells xmcp-i how to use the session token for subsequent API calls\n tokenUsage: z.enum(['cookie', 'bearer', 'header']).optional().default('cookie'),\n tokenHeader: z.string().max(100).optional(), // Custom header name if tokenUsage === 'header'\n cookieFormat: z.string().max(500).optional(), // Cookie format template, e.g., \"CIX={{token}}; customerCookie={{token}}\"\n apiHeaders: z.record(z.string(), z.string()).optional(), // Additional headers for API calls\n\n // Consent overrides for credential forms (CRED-002)\n consentOverrides: z\n .object({\n branding: z\n .object({\n primaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #2563EB)')\n .optional(),\n secondaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #DBEAFE)')\n .optional(),\n logoUrl: httpUrlSchema(500).optional(),\n companyName: z.string().max(255).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n })\n .partial()\n .optional(),\n terms: z\n .object({\n url: httpUrlSchema(500).optional(),\n text: z.string().max(500).optional(),\n required: z.boolean().optional(),\n version: z.string().max(50).optional(),\n })\n .partial()\n .optional(),\n formTitle: z.string().max(255).optional(),\n formDescription: z.string().max(1000).optional(),\n identityFieldLabel: z.string().max(255).optional(),\n passwordFieldLabel: z.string().max(255).optional(),\n submitButtonText: z.string().max(100).optional(),\n })\n .optional(),\n // Provider Registry Alignment: Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type CredentialProvider = z.infer<typeof CredentialProviderSchema>;\n\n/**\n * Configured Provider Union - can be OAuth2 or Credential\n * Named to avoid conflict with AuthProvider in types/auth.ts\n */\nexport const ConfiguredProviderSchema = z.discriminatedUnion('type', [\n OAuth2ProviderSchema,\n CredentialProviderSchema,\n]);\nexport type ConfiguredProvider = z.infer<typeof ConfiguredProviderSchema>;\n\n/**\n * OAuth Providers Map - keyed by provider ID (github, google, custom, etc.)\n */\nexport const OAuthProvidersMapSchema = z.record(z.string(), ConfiguredProviderSchema);\nexport type OAuthProvidersMap = z.infer<typeof OAuthProvidersMapSchema>;\n\n/**\n * Add/Update Provider Request Schema\n * Used for PUT /api/internal/bouncer/config/[projectId]/providers/[providerId]\n */\nexport const AddUpdateProviderRequestSchema = ConfiguredProviderSchema;\nexport type AddUpdateProviderRequest = z.infer<typeof AddUpdateProviderRequestSchema>;\n\n/**\n * Scope Definition\n */\nexport const ScopeSchema = z.object({\n name: z.string().min(1).max(100),\n description: z.string().max(500).optional(),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n category: z.string().max(50).optional(),\n});\nexport type Scope = z.infer<typeof ScopeSchema>;\n\n/**\n * CRISP Budget Configuration\n */\nexport const CRISPBudgetSchema = z.object({\n requestsPerHour: z.number().int().positive().optional(),\n requestsPerDay: z.number().int().positive().optional(),\n tokensPerHour: z.number().int().positive().optional(),\n tokensPerDay: z.number().int().positive().optional(),\n computeUnitsPerHour: z.number().int().positive().optional(),\n computeUnitsPerDay: z.number().int().positive().optional(),\n});\nexport type CRISPBudget = z.infer<typeof CRISPBudgetSchema>;\n\n/**\n * Consent Branding Configuration\n */\nexport const ConsentBrandingSchema = z.object({\n primaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #2563EB)')\n .optional(),\n secondaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #DBEAFE)')\n .optional(),\n logoUrl: httpUrlSchema(500).optional(),\n companyName: z.string().max(255).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n});\nexport type ConsentBranding = z.infer<typeof ConsentBrandingSchema>;\n\n/**\n * Consent Terms Configuration\n */\nexport const ConsentTermsSchema = z.object({\n url: httpUrlSchema(500).optional(),\n text: z.string().max(500).optional(),\n required: z.boolean().optional(),\n version: z.string().max(50).optional(),\n privacyUrl: httpUrlSchema(500).optional(),\n});\nexport type ConsentTerms = z.infer<typeof ConsentTermsSchema>;\n\n/**\n * Consent UI Configuration\n */\nexport const ConsentUISchema = z.object({\n title: z.string().max(255).optional(),\n description: z.string().max(1000).optional(),\n expirationText: z.string().max(500).optional(),\n cancelButtonText: z.string().max(100).optional(),\n submitButtonText: z.string().max(100).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n popupEnabled: z.boolean().optional(),\n autoClose: z.boolean().optional(),\n});\nexport type ConsentUI = z.infer<typeof ConsentUISchema>;\n\n/**\n * Consent Custom Field Configuration\n */\nexport const ConsentCustomFieldSchema = z.object({\n name: z.string().max(100),\n label: z.string().max(255),\n type: z.enum(['text', 'textarea', 'checkbox']),\n required: z.boolean(),\n});\nexport type ConsentCustomField = z.infer<typeof ConsentCustomFieldSchema>;\n\n/**\n * Consent metadata used for cache busting + UX hints\n */\nexport const ConsentConfigMetadataSchema = z.object({\n version: z.number().int().min(1).default(1),\n updatedAt: z.string().datetime().nullable().optional(),\n bumpedAt: z.string().datetime().nullable().optional(),\n});\nexport type ConsentConfigMetadata = z.infer<typeof ConsentConfigMetadataSchema>;\n\n/**\n * First-Contact Scope Cap section 3: the two risk tiers that require a\n * minimum Sensitive/Critical trust tier before a capability can be offered.\n * Shared by the Rule 1 refine below (`ConsentCapabilitySchema`) and the\n * Rule 2/3 refine on `ConsentConfigSchema`, so the tier boundary is defined\n * once instead of repeated as an inline check at each site.\n */\nfunction requiresSensitiveTier(riskLevel: 'low' | 'medium' | 'high' | 'critical'): boolean {\n return riskLevel === 'high' || riskLevel === 'critical';\n}\n\n/**\n * Capability — operator-authored capability row shown to the user during\n * consent. The `cedar` field holds the policy fragment (with `{{agent_did}}`,\n * `{{user_did}}`, `{{org}}`, `{{deployment}}` placeholders) that the runtime\n * binds and attaches to the issued delegation VC.\n */\nexport const ConsentCapabilitySchema = z\n .object({\n id: z\n .string()\n .min(1)\n .max(64)\n .regex(\n /^[a-z][a-z0-9._-]*$/,\n 'Capability id must be lowercase alphanumeric with `.`, `_`, or `-`'\n ),\n label: z.string().min(1).max(80),\n description: z.string().min(1).max(280),\n icon: z.enum([\n 'search',\n 'cart',\n 'card',\n 'pin',\n 'pin-new',\n 'shield',\n 'key',\n 'tools',\n 'user',\n 'calendar',\n 'lock',\n 'eye',\n 'send',\n 'package',\n 'neutral',\n ]),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']),\n defaultOn: z.boolean(),\n cedar: z\n .string()\n .min(1)\n .max(8000)\n .refine(\n (value) => /^\\s*(permit|forbid)\\s*\\(/.test(value),\n 'Cedar fragment must begin with `permit (` or `forbid (`'\n ),\n scopes: z.array(z.string().min(1).max(120)).min(1).max(20),\n category: z.string().max(80).optional(),\n })\n // First-Contact Scope Cap section 3, Rule 1: a high/critical capability can\n // never default on. Operators may still author one (probe-only, opt-in),\n // they just cannot pre-check the box for a grant that requires a\n // Sensitive/Critical tier. Reject at parse so this can never reach storage.\n //\n // Blast radius beyond direct capability edits: the write path\n // (UpdateBouncerConfigSchema) validates the WHOLE consentConfig on every\n // PUT/PATCH, so a stored row that already violates this rule (one exists\n // in prod today, pre-dating this floor) rejects ANY save that round-trips\n // it unchanged too -- including the dashboard editor's Cache Refresh\n // (ConsentScreenEditor.tsx's handleCacheRefresh, which merges + resubmits\n // the full stored config just to bump a cache-busting timestamp). That is\n // the intended fail-closed behavior, not a bug, but it is a wider surface\n // than \"editing capabilities\" -- an operator on an already-violating\n // project cannot even refresh the cache until the violating row is fixed.\n .superRefine((capability, ctx) => {\n if (requiresSensitiveTier(capability.riskLevel) && capability.defaultOn) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['defaultOn'],\n 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).`,\n });\n }\n });\nexport type ConsentCapability = z.infer<typeof ConsentCapabilitySchema>;\n\n/**\n * Group of capabilities. Renders as a section in the consent screen.\n */\nexport const ConsentCapabilityGroupSchema = z.object({\n id: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z][a-z0-9._-]*$/),\n label: z.string().min(1).max(80),\n capabilities: z.array(ConsentCapabilitySchema).min(1).max(20),\n});\nexport type ConsentCapabilityGroup = z.infer<typeof ConsentCapabilityGroupSchema>;\n\n/**\n * Agent identity tile data shared between consent + gateway screens.\n */\nexport const ConsentAgentMetadataSchema = z.object({\n name: z.string().min(1).max(80),\n did: z.string().min(1).max(500),\n vendor: z.string().max(80).optional(),\n surfaceLabel: z.string().max(40).optional(),\n // Display-only. NOT authoritative for grant decisions: First-Contact\n // Scope Cap Rules 2 and 3 read first contact and verification from\n // server state (see FirstContactScopeCap resolver in\n // apps/web/lib/bouncer/services), never from this field, because it\n // sits inside the same config object an operator writes. Kept here only\n // so already-stored configs (and any future display use) keep parsing.\n verified: z.boolean(),\n logoUrl: httpUrlSchema(500).optional(),\n // Display-only, same as `verified` above: not consulted for grant\n // decisions.\n connectedAt: z.string().datetime().optional(),\n});\nexport type ConsentAgentMetadata = z.infer<typeof ConsentAgentMetadataSchema>;\n\n/**\n * Brand copy for one input the consent page asks a person to fill in. Copy\n * only: which inputs appear is the project's consent policy's call (its\n * sign-in methods and assurance providers), never this config's.\n */\nexport const ConsentInputCopySchema = z.object({\n label: z.string().max(80).optional(),\n /** A typed field's placeholder, or the hint line under it where the step has one. */\n hint: z.string().max(200).optional(),\n});\n\nexport const ConsentSignInCopySchema = z.object({\n /** The address field of the email-code and email-and-password sign-ins. */\n email: ConsentInputCopySchema.optional(),\n password: ConsentInputCopySchema.optional(),\n /** The RPPS number step (`registry:fr-rpps`); `prompt` is its heading. */\n rpps: ConsentInputCopySchema.extend({ prompt: z.string().max(120).optional() }).optional(),\n});\nexport type ConsentSignInCopy = z.infer<typeof ConsentSignInCopySchema>;\n\n/** A consent policy names a handful of scopes; this only bounds the stored map. */\nconst MAX_SCOPE_LABELS = 50;\n\n/**\n * The brand's name for a scope no authored capability covers, keyed by the\n * literal scope. Copy only: unlike a capability, a label here never makes a\n * scope grantable (`allowedScopesFor` does not read it) and carries no Cedar.\n */\nexport const ConsentScopeLabelsSchema = z\n .record(z.string().min(1).max(120), z.string().min(1).max(80))\n .refine(\n (labels) => Object.keys(labels).length <= MAX_SCOPE_LABELS,\n `At most ${MAX_SCOPE_LABELS} scope labels`\n );\n\n/**\n * Full Consent Configuration\n */\nexport const ConsentConfigSchema = z.object({\n branding: ConsentBrandingSchema.optional(),\n terms: ConsentTermsSchema.optional(),\n ui: ConsentUISchema.optional(),\n customFields: z.array(ConsentCustomFieldSchema).optional(),\n metadata: ConsentConfigMetadataSchema.optional(),\n expirationDays: z.number().int().min(1).max(365).optional(),\n // Humanized capability layout (Peter's mockup). When present the deployed\n // server renders the new design-language consent screen; when absent the\n // legacy raw-scope checkboxes are shown.\n capabilities: z.array(ConsentCapabilityGroupSchema).max(20).optional(),\n // Populated server-side only: `UpdateBouncerConfigSchema` (the one\n // write path) unconditionally rejects a write that sets this, so an\n // operator can never self-attest an agent's identity or verification\n // status. Display-only; see `ConsentAgentMetadataSchema` above. NOT\n // consulted by First-Contact Scope Cap Rules 2/3, which read server\n // state instead (apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts).\n agentMetadata: ConsentAgentMetadataSchema.optional(),\n // First-Contact Scope Cap section 3, Rules 2 and 3 opt-in. Per-project,\n // defaults to off/absent so every existing config, and every config that\n // hasn't explicitly opted in, renders byte-identically to before this\n // field existed. Flip to `true` on one project's consentConfig (a\n // normal PUT/PATCH) to turn the probe gate on for that project.\n //\n // This flag is read at RENDER time, not enforced by this schema: Rules 2\n // and 3 are not write-time properties of a config, they depend on who is\n // in front of the screen right now, which this schema has no way to\n // know. See `applyFirstContactScopeCap` in\n // apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts for\n // the actual enforcement, which resolves first contact and verification\n // from server state (delegations, and a verification seam that returns\n // `indeterminate` until a real agent-verification source exists).\n firstContactScopeCapEnabled: z.boolean().optional(),\n consentTheme: z.enum(['light', 'dark']).optional(),\n headlineVerb: z.string().min(1).max(40).optional(),\n revocationPath: z.string().min(1).max(120).optional(),\n inactivityDays: z.number().int().min(1).max(3650).optional(),\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The RESOLVED bare\n // host where this project's consent screen + delegation pickup live (null\n // column → platform default). Surfaced so the consent PEP and the gateway\n // challenge emitter build consent_uri / pickup_uri from config, never a\n // hardcoded host. Populated server-side by `loadConsentConfig`.\n authorizationHost: z.string().min(1).max(255).optional(),\n signInCopy: ConsentSignInCopySchema.optional(),\n scopeLabels: ConsentScopeLabelsSchema.optional(),\n});\nexport type ConsentConfig = z.infer<typeof ConsentConfigSchema>;\n\n/**\n * Tool Consent Overrides (CRED-002)\n * Per-tool customization for consent pages\n */\nexport const ToolConsentOverridesSchema = z\n .object({\n branding: ConsentBrandingSchema.partial().optional(),\n terms: ConsentTermsSchema.partial().optional(),\n headerText: z.string().max(255).optional(),\n description: z.string().max(1000).optional(),\n })\n .optional();\nexport type ToolConsentOverrides = z.infer<typeof ToolConsentOverridesSchema>;\n\n/**\n * Bouncer Config (for GET response)\n */\nexport const BouncerConfigSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n\n // Authorization settings\n reputationThreshold: z.number().int().min(0).max(100).default(76),\n allowedScopes: z.array(z.string()).default([]),\n deniedAgents: z.array(z.string()).default([]),\n\n // CRISP budget settings\n crispEnabled: z.boolean().default(false),\n crispBudget: CRISPBudgetSchema.nullable().optional(),\n\n // Multi-provider OAuth configuration (CRED-001)\n oauthProviders: OAuthProvidersMapSchema.default({}),\n defaultProvider: z.string().max(50).nullable().optional(),\n\n // Legacy OAuth configuration (deprecated - use oauthProviders)\n oauthClientId: z.string().max(255).nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(), // Encrypted\n oauthRedirectUri: httpUrlSchema(500).nullable().optional(),\n oauthAuthEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthTokenEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthProviderType: OAuthProviderTypeSchema.default('oauth2'),\n oauthScopes: z.array(ScopeSchema).default([]),\n oauthConnectionStatus: OAuthConnectionStatusSchema.default('disconnected'),\n lastScopesSync: z.string().datetime().nullable().optional(),\n\n // Delegation configuration\n delegationExpirationDays: z.number().int().positive().default(7),\n\n // Consent page configuration\n consentConfig: ConsentConfigSchema.optional(),\n\n // Tool discovery\n discoveredTools: z.record(z.string(), z.unknown()).default({}),\n mcpServerUrl: httpUrlSchema().nullable().optional(),\n mcpWorkerUrl: httpUrlSchema().nullable().optional(),\n\n // Organization settings\n isEnabled: z.boolean().default(false),\n updatedAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n});\nexport type BouncerConfig = z.infer<typeof BouncerConfigSchema>;\n\n/**\n * Update Bouncer Config (for PUT request body)\n */\nexport const UpdateBouncerConfigSchema = z\n .object({\n // Authorization settings\n reputationThreshold: z.number().int().min(0).max(100).optional(),\n allowedScopes: z.array(z.string()).optional(),\n deniedAgents: z.array(z.string()).optional(),\n\n // CRISP budget settings\n crispEnabled: z.boolean().optional(),\n crispBudget: CRISPBudgetSchema.nullable().optional(),\n\n // Multi-provider OAuth configuration (CRED-001)\n defaultProvider: z.string().max(50).nullable().optional(),\n\n // Legacy OAuth configuration (deprecated - use providers endpoint)\n oauthClientId: z.string().max(255).nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(), // Will be encrypted by API\n oauthRedirectUri: httpUrlSchema(500).nullable().optional(),\n oauthAuthEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthTokenEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthProviderType: OAuthProviderTypeSchema.optional(),\n oauthConnectionStatus: OAuthConnectionStatusSchema.optional(),\n\n // Delegation configuration\n delegationExpirationDays: z.number().int().positive().optional(),\n\n // Consent page configuration\n consentConfig: ConsentConfigSchema.optional(),\n\n // MCP Server URL (for manual configuration)\n mcpServerUrl: httpUrlSchema().nullable().optional(),\n\n // Organization settings\n isEnabled: z.boolean().optional(),\n })\n .strict()\n // First-Contact Scope Cap section 3: `agentMetadata` represents facts\n // about a specific requesting agent (identity, verification, connection\n // age), not an operator preference. It has no legitimate writer today (no\n // admin UI, no other backend job sets it), so this is the only place it\n // could ever reach storage. If an operator could submit it here, they\n // could self-attest `verified: true` and any `connectedAt` in the same\n // write that defines their capabilities, defeating Rules 2/3 entirely\n // since nothing else re-checks that claim against a real agent. Reject it\n // unconditionally so a stored `agentMetadata`, if one ever exists, can\n // only have come from a future render-assembly step, never the operator.\n .superRefine((data, ctx) => {\n if (data.consentConfig?.agentMetadata !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['consentConfig', 'agentMetadata'],\n message:\n '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.',\n });\n }\n });\nexport type UpdateBouncerConfig = z.infer<typeof UpdateBouncerConfigSchema>;\n\n/**\n * Refresh Scopes Request\n */\nexport const RefreshScopesRequestSchema = z\n .object({\n mcpServerUrl: httpUrlSchema().optional(),\n })\n .strict();\nexport type RefreshScopesRequest = z.infer<typeof RefreshScopesRequestSchema>;\n\n/**\n * Delegation Status\n */\nexport const DelegationStatusSchema = z.enum(['active', 'expired', 'revoked']);\nexport type DelegationStatus = z.infer<typeof DelegationStatusSchema>;\n\n/**\n * Delegation (for GET response)\n */\nexport const DelegationSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n agentDid: z.string().max(500),\n agentName: z.string().max(255).nullable().optional(),\n // User identification - userDid is primary for KYA-OS, others for backward compatibility\n userDid: z.string().max(500).nullable().optional(), // DID of authorizing user (did:key or did:web)\n userId: z.string().max(500).nullable().optional(), // Internal application user ID\n userIdentifier: z.string().max(500).nullable().optional(), // Human-readable (email)\n scopes: z.array(z.string()),\n constraints: z.record(z.string(), z.unknown()).nullable().optional(),\n status: DelegationStatusSchema.default('active'),\n issuedAt: z.string().datetime(),\n expiresAt: z.string().datetime().nullable().optional(),\n revokedAt: z.string().datetime().nullable().optional(),\n revocationReason: z.string().max(500).nullable().optional(),\n credentialJwt: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).default({}),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n});\nexport type Delegation = z.infer<typeof DelegationSchema>;\n\n/**\n * Bouncer Proof Outcome\n */\nexport const BouncerOutcomeSchema = z.enum(['success', 'failed', 'blocked', 'error']);\nexport type BouncerOutcome = z.infer<typeof BouncerOutcomeSchema>;\n\n/**\n * Bouncer Proof (for GET response)\n */\nexport const BouncerProofSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n delegationId: z.string().uuid().nullable().optional(),\n sessionId: z.string().max(100),\n agentDid: z.string().max(500),\n userIdentifier: z.string().max(500).nullable().optional(),\n toolName: z.string().max(255),\n toolArgs: z.record(z.string(), z.unknown()).nullable().optional(),\n toolResult: z.record(z.string(), z.unknown()).nullable().optional(),\n scopes: z.array(z.string()).nullable().optional(),\n signature: z.string(),\n publicKey: z.string(),\n timestamp: z.number().int(), // Unix timestamp\n nonce: z.string().max(100),\n crispDelta: z.record(z.string(), z.unknown()).nullable().optional(),\n outcome: BouncerOutcomeSchema.default('success'),\n errorMessage: z.string().nullable().optional(),\n createdAt: z.string().datetime(),\n});\nexport type BouncerProof = z.infer<typeof BouncerProofSchema>;\n\n/**\n * Delegation Polling Status\n */\nexport const DelegationPollingStatusSchema = z.object({\n status: z.enum(['pending', 'completed', 'expired', 'error']),\n delegationJwt: z.string().optional(), // Only present when status is 'completed'\n authUrl: httpUrlSchema().optional(), // Only present when status is 'pending'\n errorMessage: z.string().optional(), // Only present when status is 'error'\n expiresAt: z.string().datetime().optional(),\n});\nexport type DelegationPollingStatus = z.infer<typeof DelegationPollingStatusSchema>;\n\n/**\n * Custom URL validator that allows:\n * - Valid URLs (standard URL format)\n * - Empty strings (for optional endpoints)\n * - Placeholder URLs (URLs with {placeholder} patterns like {shop}, {domain})\n */\nconst urlOrPlaceholderSchema = z.string().refine(\n (val) => {\n if (val === '') return true; // Empty string is allowed\n // Check if it's a valid URL\n try {\n new URL(val);\n return true;\n } catch {\n // If not a valid URL, check if it's a placeholder URL (contains {placeholder})\n // Placeholder URLs follow URL structure but have {placeholder} segments\n // Example: https://{shop}.myshopify.com/admin/oauth/authorize\n const placeholderUrlPattern = /^https?:\\/\\/[^\\s]+$/;\n return placeholderUrlPattern.test(val) && val.includes('{') && val.includes('}');\n }\n },\n {\n message:\n 'Must be a valid URL, empty string, or placeholder URL (e.g., https://{shop}.example.com)',\n }\n);\n\n/**\n * OAuth Mode - determines how the OAuth flow is handled\n * - 'direct': KYA-OS handles OAuth directly with IDP (PKCE support, no secret needed)\n * - 'proxy': KYA-OS routes through Checkpoint (keeps client_secret secure server-side)\n */\nexport const OAuthModeSchema = z.enum(['direct', 'proxy']);\nexport type OAuthMode = z.infer<typeof OAuthModeSchema>;\n\n/**\n * OAuth Provider Metadata Schema\n * Used for /api/v1/bouncer/projects/{projectId}/providers endpoint\n */\nexport const OAuthProviderMetadataSchema = z.object({\n clientId: z.string().nullable(),\n // SECURITY: clientSecret is intentionally NOT returned in API responses\n // Agents receive only hasClientSecret flag and metadata.clientSecretName for runtime resolution\n hasClientSecret: z.boolean(), // Boolean for quick detection\n authorizationUrl: urlOrPlaceholderSchema, // Allow valid URLs, empty strings, or placeholder URLs\n tokenUrl: urlOrPlaceholderSchema, // Allow valid URLs, empty strings, or placeholder URLs\n userInfoUrl: urlOrPlaceholderSchema.optional(), // Optional per contracts interface\n supportsPKCE: z.boolean(),\n requiresClientSecret: z.boolean(),\n proxyMode: z.boolean().optional(), // Optional per contracts interface (deprecated - use mode)\n scopes: z.array(z.string()).optional(), // Optional per contracts interface\n defaultScopes: z.array(z.string()).optional(), // Optional per contracts interface\n // Phase 3 fields (all optional for backward compatibility)\n customParams: z.record(z.string(), z.string()).optional(),\n tokenEndpointAuthMethod: z.enum(['client_secret_post', 'client_secret_basic']).optional(),\n responseType: z.string().optional(),\n grantType: z.string().optional(),\n // KYA-OS coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)\n configured: z.boolean().optional(), // Whether this provider is configured for the project\n mode: OAuthModeSchema.optional(), // OAuth flow mode: 'direct' (PKCE) or 'proxy' (Checkpoint)\n // KYA-OS Provider Registry: Secret resolution metadata\n metadata: z\n .object({\n clientSecretName: z.string().optional(),\n clientIdSecretName: z.string().optional(),\n apiKeySecretName: z.string().optional(),\n clientSecretVersion: z.number().optional(),\n lastRotatedAt: z.string().optional(),\n })\n .optional(),\n});\nexport type OAuthProviderMetadata = z.infer<typeof OAuthProviderMetadataSchema>;\n\n/**\n * Providers API Response Schema\n * Used for /api/v1/bouncer/projects/{projectId}/providers endpoint\n */\nexport const ProvidersResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n providers: z.record(z.string(), OAuthProviderMetadataSchema),\n configuredProvider: z.string().nullable(),\n }),\n metadata: z.object({\n requestId: z.string(),\n timestamp: z.string().datetime(),\n }),\n});\nexport type ProvidersResponse = z.infer<typeof ProvidersResponseSchema>;\n\n/**\n * OAuth Tokens Response Schema\n * Used for GET /api/v1/bouncer/delegations/{delegationId}/tokens endpoint\n */\nexport const OAuthTokensResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n oauth_access_token: z.string(),\n oauth_refresh_token: z.string().nullable(),\n oauth_expires_at: z.string().datetime().nullable(), // ISO 8601\n oauth_expires_in: z.number().nullable(), // Seconds\n oauth_token_type: z.string(), // Token type (e.g., \"Bearer\")\n oauth_scope: z.string().nullable(), // Granted scopes (space-separated string)\n }),\n metadata: z.object({\n requestId: z.string(),\n timestamp: z.string().datetime(),\n }),\n});\nexport type OAuthTokensResponse = z.infer<typeof OAuthTokensResponseSchema>;\n\n// ==============================================================================\n// PROVIDERS CONFIG ENVELOPE (Provider Registry Alignment)\n// ==============================================================================\n\n/**\n * Checkpoint Provider Definition Schema\n *\n * This is the Checkpoint-specific provider definition used in API responses\n * and configuration. It has field naming differences from the canonical\n * @kya-os/provider-registry ProviderDefinition:\n *\n * | Checkpoint Field | Provider Registry Field | Notes |\n * |---------------------|----------------------------|--------------------------|\n * | type | authType | Both accept 'password' |\n * | authorizationUrl | oauthConfig.authorizationEndpoint | Nested in registry |\n * | tokenUrl | oauthConfig.tokenEndpoint | Nested in registry |\n * | userInfoUrl | oauthConfig.userInfoEndpoint | Nested in registry |\n *\n * For mapping between formats, use `toProviderRegistryFormat()` and\n * `fromProviderRegistryFormat()` helper functions.\n *\n * SECURITY: This schema NEVER contains actual secret values.\n * Only metadata.clientSecretName (reference to secure storage) is included.\n *\n * @see ProviderRegistryDefinition from @kya-os/provider-registry for canonical format\n */\nexport const ProviderDefinitionSchema = z.object({\n id: z.string().min(1),\n type: AuthProviderTypeSchema,\n displayName: z.string().optional(),\n configured: z.boolean().default(false),\n // OAuth2 specific fields (flat structure for API compat)\n authorizationUrl: z.string().optional(),\n tokenUrl: z.string().optional(),\n userInfoUrl: z.string().optional(),\n supportsPKCE: z.boolean().optional(),\n requiresClientSecret: z.boolean().optional(),\n // Credentials (only clientId is safe - NEVER clientSecret)\n clientId: z.string().nullable().optional(),\n hasClientSecret: z.boolean().default(false),\n // Scopes\n scopes: z.array(z.string()).optional(),\n defaultScopes: z.array(z.string()).optional(),\n // Mode\n mode: z.enum(['direct', 'proxy']).optional(),\n // Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type ProviderDefinition = z.infer<typeof ProviderDefinitionSchema>;\n\n/**\n * Canonical provider definition from @kya-os/provider-registry\n *\n * Re-exported for consumers who need the canonical format.\n * Use `toProviderRegistryFormat()` to convert Checkpoint format.\n */\nexport type { ProviderRegistryDefinition } from './provider-registry';\n\n/**\n * Providers Config Source Metadata\n * Tracks where the config came from for debugging and auditing\n */\nexport const ProvidersConfigSourceSchema = z.object({\n projectId: z.string().uuid(),\n projectFriendlyId: z.string(),\n deployId: z.string().uuid().optional(),\n generatedAt: z.string().datetime(),\n agentShieldVersion: z.string(),\n});\nexport type ProvidersConfigSource = z.infer<typeof ProvidersConfigSourceSchema>;\n\n/**\n * Providers Config Envelope\n *\n * The full signed configuration document served to KYA-OS agents.\n * Includes HMAC signature for tamper detection.\n *\n * SECURITY:\n * - NEVER contains actual secret values (clientSecret, apiKey, etc.)\n * - Agents MUST verify HMAC signature before loading\n * - Agents resolve secrets from secure storage at runtime using metadata.clientSecretName\n */\nexport const ProvidersConfigEnvelopeSchema = z.object({\n // Version for atomic updates (incrementing integer)\n version: z.number().int().positive(),\n // Source metadata for debugging and auditing\n source: ProvidersConfigSourceSchema,\n // Provider definitions (keyed by provider ID)\n providers: z.record(z.string(), ProviderDefinitionSchema),\n // HMAC signature for tamper detection (SHA-256 hex)\n signature: z\n .string()\n .regex(/^[a-f0-9]{64}$/)\n .optional(),\n // Which fields are included in the signature\n signedFields: z.array(z.string()).optional(),\n});\nexport type ProvidersConfigEnvelope = z.infer<typeof ProvidersConfigEnvelopeSchema>;\n\n// ==============================================================================\n// FORMAT CONVERSION HELPERS (Provider Registry <-> Checkpoint)\n// ==============================================================================\n\nimport type { ProviderRegistryDefinition } from './provider-registry';\n\n/**\n * Convert Checkpoint ProviderDefinition to canonical @kya-os/provider-registry format.\n *\n * Use this when sending provider config to KYA-OS agents that expect the canonical format.\n *\n * @example\n * ```typescript\n * const agentShieldProvider: ProviderDefinition = { ... };\n * const canonicalProvider = toProviderRegistryFormat(agentShieldProvider);\n * // Now canonicalProvider has nested oauthConfig structure\n * ```\n */\nexport function toProviderRegistryFormat(provider: ProviderDefinition): ProviderRegistryDefinition {\n const { type, authorizationUrl, tokenUrl, userInfoUrl, ...rest } = provider;\n\n // type is already 'oauth2' | 'password' after schema transformation\n // (legacy 'credential' is transformed to 'password' by AuthProviderTypeSchema)\n const authType: 'oauth2' | 'password' = type;\n\n // Base definition\n const result: ProviderRegistryDefinition = {\n id: rest.id,\n authType,\n displayName: rest.displayName,\n defaultScopes: rest.defaultScopes || rest.scopes,\n metadata: rest.metadata as Record<string, unknown>,\n };\n\n // Add OAuth config if OAuth provider\n if (authType === 'oauth2' && (authorizationUrl || tokenUrl)) {\n result.oauthConfig = {\n authorizationEndpoint: authorizationUrl || '',\n tokenEndpoint: tokenUrl || '',\n userInfoEndpoint: userInfoUrl,\n supportsPKCE: rest.supportsPKCE,\n requiresClientSecret: rest.requiresClientSecret,\n defaultScopes: rest.defaultScopes || rest.scopes,\n };\n }\n\n return result;\n}\n\n/**\n * Supported auth types that can be converted to Checkpoint ProviderDefinition.\n * Other types (passkey, magic_link, otp, etc.) are not yet supported.\n */\nexport type SupportedProviderAuthType = 'oauth2' | 'password';\n\n/**\n * Check if a provider auth type is supported by Checkpoint.\n */\nexport function isSupportedAuthType(\n authType: ProviderAuthType\n): authType is SupportedProviderAuthType {\n return authType === 'oauth2' || authType === 'password';\n}\n\n/**\n * Convert canonical @kya-os/provider-registry format to Checkpoint ProviderDefinition.\n *\n * Use this when receiving provider config from external sources in canonical format.\n *\n * **Note:** Only 'oauth2' and 'password' auth types are currently supported.\n * Providers with other auth types (passkey, magic_link, otp, etc.) will throw an error.\n * Use `isSupportedAuthType()` to check before calling this function.\n *\n * @throws {Error} If the provider's auth type is not supported\n *\n * @example\n * ```typescript\n * import { defaultProviderRegistry } from '@kya-os/provider-registry';\n *\n * const canonicalProvider = defaultProviderRegistry.getProvider('github');\n * if (canonicalProvider && isSupportedAuthType(canonicalProvider.authType)) {\n * const agentShieldProvider = fromProviderRegistryFormat(canonicalProvider);\n * // Now agentShieldProvider has flat structure for Checkpoint APIs\n * }\n * ```\n */\nexport function fromProviderRegistryFormat(\n provider: ProviderRegistryDefinition\n): ProviderDefinition {\n // Validate auth type is supported\n if (!isSupportedAuthType(provider.authType)) {\n throw new Error(\n `Auth type '${provider.authType}' is not yet supported in AgentShield. ` +\n `Provider '${provider.id}' cannot be converted. ` +\n `Supported types: 'oauth2', 'password'.`\n );\n }\n\n return {\n id: provider.id,\n type: provider.authType, // Now type-safe: only 'oauth2' | 'password'\n displayName: provider.displayName,\n configured: false, // External providers need configuration\n authorizationUrl: provider.oauthConfig?.authorizationEndpoint,\n tokenUrl: provider.oauthConfig?.tokenEndpoint,\n userInfoUrl: provider.oauthConfig?.userInfoEndpoint,\n supportsPKCE: provider.oauthConfig?.supportsPKCE,\n requiresClientSecret: provider.oauthConfig?.requiresClientSecret,\n clientId: null,\n hasClientSecret: false,\n scopes: provider.defaultScopes,\n defaultScopes: provider.defaultScopes,\n metadata: provider.metadata as ProviderSecretMetadata,\n };\n}\n\n/**\n * Safely convert canonical format to Checkpoint format, returning null for unsupported types.\n *\n * Use this when you want to gracefully skip unsupported providers instead of throwing.\n */\nexport function fromProviderRegistryFormatSafe(\n provider: ProviderRegistryDefinition\n): ProviderDefinition | null {\n if (!isSupportedAuthType(provider.authType)) {\n return null;\n }\n return fromProviderRegistryFormat(provider);\n}\n","/**\n * Organization Types and Interfaces\n *\n * Types related to organization management, validation, and errors\n */\n\nimport { z } from 'zod';\nimport { httpUrlSchema } from '../schemas/bouncer';\n\nconst organizationDomainSchema = z\n .string()\n .trim()\n .toLowerCase()\n .min(1, 'Domain is required')\n .max(255, 'Domain must be less than 255 characters')\n .regex(\n /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/,\n 'Domain must be a valid hostname'\n );\n\nconst clearableOptionalString = <TSchema extends z.ZodTypeAny>(schema: TSchema) =>\n schema.nullable().optional();\n\nconst HOSTNAME_REGEX = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;\n\n/**\n * Accepted org logo values:\n * - an http(s) image URL (manually pasted), OR\n * - a `d:<domain>` token, which the app resolves to a logo.dev CDN URL at\n * read time (the auto-fetch-from-domain path), OR\n * - '' (and, at the field level, null) to clear.\n *\n * Implemented as a single refined string (not a `z.union`) to avoid Zod\n * union-inference pitfalls (TS2345). The `d:` form is validated against the\n * same hostname rule as claimed domains so a junk value can't be persisted.\n */\nconst organizationLogoSchema = z\n .string()\n .max(500)\n .refine(\n (v) => {\n if (v === '') return true; // explicit clear\n if (v.startsWith('d:')) return HOSTNAME_REGEX.test(v.slice(2));\n return httpUrlSchema(500).safeParse(v).success;\n },\n { message: 'Logo must be an http(s) URL or a d:domain token' }\n );\n\n/**\n * Organization-level SSO provider and policy settings.\n */\nexport const OrganizationSsoProviderSchema = z.enum(['rippling', 'saml']);\nexport type OrganizationSsoProvider = z.infer<typeof OrganizationSsoProviderSchema>;\n\nexport const OrganizationSsoModeSchema = z.enum(['optional', 'required']);\nexport type OrganizationSsoMode = z.infer<typeof OrganizationSsoModeSchema>;\n\nexport const OrganizationSsoSettingsSchema = z\n .object({\n enabled: z.boolean().optional(),\n mode: OrganizationSsoModeSchema.optional(),\n provider: OrganizationSsoProviderSchema.optional(),\n loginUrl: clearableOptionalString(z.string().url('SSO login URL must be a valid URL').max(500)),\n metadataUrl: clearableOptionalString(\n z.string().url('Metadata URL must be a valid URL').max(1000)\n ),\n metadataXml: clearableOptionalString(\n z.string().min(1, 'Metadata XML cannot be empty').max(500000)\n ),\n idpEntityId: clearableOptionalString(z.string().max(1000)),\n idpSsoUrl: clearableOptionalString(z.string().url('IdP SSO URL must be a valid URL').max(1000)),\n domains: z.array(organizationDomainSchema).max(50).optional(),\n allowPasswordFallback: z.boolean().optional(),\n autoProvisionMembers: z.boolean().optional(),\n /**\n * ISO-8601 timestamp of the last successful \"Test connection\". Lets the\n * verified state survive navigation (it's persisted JSON, re-parsed on\n * read — must stay a string, not z.date()). Cleared (null) when a\n * connection-affecting field changes, so a stale verification can't show\n * as current.\n */\n lastVerifiedAt: clearableOptionalString(z.string().datetime()),\n })\n .superRefine((value, ctx) => {\n // Validate strict login URL requirements only when callers explicitly submit\n // a full \"required SSO with no fallback\" configuration in this payload.\n // Partial updates are merged server-side with existing settings.\n const explicitlyRequiresSso =\n value.enabled === true && value.mode === 'required' && value.allowPasswordFallback === false;\n\n if (explicitlyRequiresSso && !value.loginUrl && !value.idpSsoUrl) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['loginUrl'],\n message:\n 'SSO login URL is required when mode is required and password fallback is disabled',\n });\n }\n });\n\n/**\n * Organization settings schema\n */\nexport const OrganizationSettingsSchema = z.object({\n maxProjects: z.number().optional(),\n maxMembers: z.number().optional(),\n /** Whether this is a personal/default organization created for a user */\n isPersonalOrg: z.boolean().optional(),\n sso: OrganizationSsoSettingsSchema.optional(),\n features: z\n .object({\n advancedAnalytics: z.boolean().optional(),\n customBranding: z.boolean().optional(),\n ssoEnabled: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type OrganizationSettings = z.infer<typeof OrganizationSettingsSchema>;\n\n/**\n * Organization role schema and type\n * Single source of truth for runtime validation and TypeScript types.\n * Adding a role here will update both; used when parsing DB role values.\n */\nexport const OrganizationRoleSchema = z.enum(['owner', 'admin', 'member']);\nexport type OrganizationRole = z.infer<typeof OrganizationRoleSchema>;\n\n/**\n * Base organization interface\n */\nexport interface Organization {\n id: string;\n name: string;\n slug: string;\n logoUrl?: string | null;\n settings: OrganizationSettings;\n /**\n * The org's designated primary project — the deterministic default anchor for\n * navigation (land on a chosen project) and the gateway merchant-consent flow.\n * Nullable: unset, or the referenced project was hard-deleted (FK ON DELETE\n * SET NULL). It may still point at a SOFT-deleted project, so resolve through\n * `resolveOrgPrimaryProject` before relying on it rather than reading raw.\n */\n primaryProjectId?: string | null;\n deletedAt?: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Organization with member information\n */\nexport interface OrganizationWithMembers extends Organization {\n members: OrganizationMember[];\n memberCount: number;\n projectCount: number;\n}\n\n/**\n * Organization member interface\n */\nexport interface OrganizationMember {\n organizationId: string;\n userId: string;\n role: OrganizationRole;\n joinedAt: Date;\n user?: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n };\n}\n\n/**\n * User organizations response\n */\nexport interface UserOrganizations {\n organizations: (Organization & { role: OrganizationRole })[];\n defaultOrganizationId?: string;\n}\n\n/**\n * Create organization input with enhanced validation\n */\nexport const CreateOrganizationInputSchema = z.object({\n name: z\n .string()\n .min(2, 'Organization name must be at least 2 characters')\n .max(100, 'Organization name must be less than 100 characters')\n .trim()\n .regex(\n /^[a-zA-Z0-9\\s\\-&.,]+$/,\n 'Organization name can only contain letters, numbers, spaces, hyphens, ampersands, periods, and commas'\n )\n .transform((val) => val.trim()),\n slug: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9-]+$/, 'Slug can only contain lowercase letters, numbers, and hyphens')\n .optional(),\n settings: OrganizationSettingsSchema.optional(),\n});\n\nexport type CreateOrganizationInput = z.infer<typeof CreateOrganizationInputSchema>;\n\n/**\n * Update organization input\n */\nexport const UpdateOrganizationInputSchema = z.object({\n name: z\n .string()\n .min(2, 'Organization name must be at least 2 characters')\n .max(100, 'Organization name must be less than 100 characters')\n .trim()\n .regex(\n /^[a-zA-Z0-9\\s\\-&.,]+$/,\n 'Organization name can only contain letters, numbers, spaces, hyphens, ampersands, periods, and commas'\n )\n .transform((val) => val.trim())\n .optional(),\n logoUrl: organizationLogoSchema.nullable().optional(),\n // REASON: single refined string (max 500) — http(s) URL, d:<hostname>, or '' to clear.\n settings: OrganizationSettingsSchema.optional(),\n});\n\nexport type UpdateOrganizationInput = z.infer<typeof UpdateOrganizationInputSchema>;\n\n/**\n * Organization error codes\n */\nexport enum OrganizationErrorCode {\n NAME_DUPLICATE = 'ORG_NAME_DUPLICATE',\n SLUG_DUPLICATE = 'ORG_SLUG_DUPLICATE',\n NOT_FOUND = 'ORG_NOT_FOUND',\n ACCESS_DENIED = 'ORG_ACCESS_DENIED',\n LIMIT_EXCEEDED = 'ORG_LIMIT_EXCEEDED',\n INVALID_NAME = 'ORG_INVALID_NAME',\n OPERATION_FAILED = 'ORG_OPERATION_FAILED',\n}\n\n/**\n * Organization suggestion for similar names\n */\nexport interface OrganizationSuggestion {\n id: string;\n name: string;\n slug: string;\n similarity: number; // 0-100 percentage\n}\n\n/**\n * Validation helpers\n */\nexport function normalizeOrganizationName(name: string): string {\n return name.trim().toLowerCase();\n}\n","/**\n * Authorization Host resolution — draft-kya-http-02 §7 (H1.1 #3244).\n *\n * The **Authorization Host** is the per-project host that renders the\n * delegation consent screen and serves delegation pickup. Every PEP\n * (Policy Enforcement Point) config payload — routing entry, gateway\n * config, policy config, bouncer config — carries the RESOLVED host so a\n * PEP can build a challenge's `consent_uri` / `pickup_uri` against it.\n * Per spec §7, PEPs MUST read it from config and never hardcode it.\n *\n * Representation: a **bare host** (no scheme, no trailing slash), matching\n * the spec's `authorization_host` field (e.g. `auth.merchant.com`). The\n * challenge emitter (H2.1-WF) prepends `https://` and the path, exactly as\n * the golden fixtures show: `authorization_host=\"auth.merchant.com\"` →\n * `consent_uri=\"https://auth.merchant.com/consent?sid=…\"`.\n *\n * Resolution rule:\n * - project value set → org-branded host (e.g. `authenticate.acme.com`)\n * - project value null → the platform default host\n *\n * This module is intentionally pure (no env access): each caller supplies\n * its own `platformDefaultHost` so the Next.js web app (NEXT_PUBLIC_APP_URL)\n * and the Fly gateway can each resolve against the host they front. The\n * `DEFAULT_AUTHORIZATION_HOST` constant is the last-resort fallback when a\n * caller has no configured origin.\n */\n\n/**\n * Last-resort platform Authorization Host (bare host) when a caller passes no\n * `platformDefaultHost`. Mirrors the web app's production origin\n * (`https://kya.vouched.id`) reduced to its host.\n *\n * NOTE for non-web callers (Fly gateway, edge worker): you MUST pass your own\n * `platformDefaultHost` to {@link resolveAuthorizationHost}. This constant is a\n * web-origin fallback only — relying on it from another deployment silently\n * brands every unset project as the web app instead of the host you front.\n */\nexport const DEFAULT_AUTHORIZATION_HOST = 'kya.vouched.id';\n\n/**\n * Reduce an origin or host string to a normalized bare host: strips any\n * `http(s)://` scheme and trailing slashes, then lower-cases it. Hosts are\n * case-insensitive, so lower-casing keeps two equivalent configs byte-identical\n * on the wire (the golden fixtures are lower-case). Idempotent on values that\n * are already bare + lower-case.\n *\n * `https://Kya.Vouched.id/` → `kya.vouched.id`\n * `authenticate.acme.com` → `authenticate.acme.com`\n *\n * Normalization only — it does NOT validate. Use {@link isValidAuthorizationHost}\n * at the write boundary to reject paths, userinfo, whitespace, and bad labels.\n */\nexport function toBareHost(value: string): string {\n const withoutScheme = value.trim().replace(/^https?:\\/\\//i, '');\n // Strip trailing slashes with a linear scan rather than `/\\/+$/` — that\n // anchored, unbounded-repetition regex is a polynomial-ReDoS vector on\n // host strings with many trailing slashes (CodeQL js/polynomial-redos).\n let end = withoutScheme.length;\n while (end > 0 && withoutScheme.charCodeAt(end - 1) === 47 /* '/' */) {\n end--;\n }\n return withoutScheme.slice(0, end).toLowerCase();\n}\n\n/**\n * Validate that a value is a usable Authorization Host: it becomes the\n * authority of an `https://<host>/…` challenge URI, so anything that smuggles\n * a path, query, fragment, userinfo (`@`), or whitespace would silently produce\n * a broken or misdirected consent URL. After scheme/slash normalization the\n * value must be a bare `host[:port]` of RFC 1123 labels (`:port` allowed for\n * dev). Reject everything else at the write boundary.\n *\n * `authenticate.acme.com` → true\n * `localhost:3000` → true\n * `authenticate.acme.com/evil` → false (path)\n * `legit.com@evil.com` → false (userinfo)\n * `bad host.com` / `-acme.com` → false (whitespace / bad label)\n */\nexport function isValidAuthorizationHost(value: string): boolean {\n const bare = toBareHost(value);\n if (!bare || bare.length > 255) return false;\n // No path / query / fragment / userinfo / backslash / whitespace.\n if (/[/\\\\?#@\\s]/.test(bare)) return false;\n\n const parts = bare.split(':');\n if (parts.length > 2) return false; // at most one `:port`\n const [host, port] = parts;\n if (port !== undefined) {\n // A port must be 1-65535. The `1*5DIGIT` shape alone let \"99999\" through;\n // range-check it so an out-of-range port can't become a URL authority.\n if (!/^\\d{1,5}$/.test(port)) return false;\n const portNum = Number(port);\n if (portNum < 1 || portNum > 65535) return false;\n }\n if (host.length === 0 || host.length > 253) return false;\n\n // RFC 1123 labels: 1-63 of [a-z0-9-], no leading/trailing hyphen. The bounded\n // {0,61} keeps this linear (no catastrophic backtracking).\n const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n return host.split('.').every((l) => label.test(l));\n}\n\n/**\n * Resolve a project's effective Authorization Host as a bare host.\n *\n * @param authorizationHost - the `projects.authorization_host` column value\n * (null/blank → use the platform default).\n * @param platformDefaultHost - the caller's platform origin or host, used\n * when the project has no override. Defaults to\n * {@link DEFAULT_AUTHORIZATION_HOST}.\n */\nexport function resolveAuthorizationHost(\n authorizationHost: string | null | undefined,\n platformDefaultHost: string = DEFAULT_AUTHORIZATION_HOST\n): string {\n const override = authorizationHost?.trim();\n return toBareHost(override && override.length > 0 ? override : platformDefaultHost);\n}\n","import { z } from 'zod';\nimport {\n MAX_POSTURE_ORIGINS,\n MAX_POSTURE_ORIGIN_LENGTH,\n validatePostureOrigins,\n} from '../posture-origins';\n\n/**\n * `settings.postureOrigins` on a project write: the additional page origins\n * browser posture may be issued for. Validated and NORMALIZED by the one\n * shared resolver (`../posture-origins`), so what the settings APIs store is\n * exactly what the issuer and gateway later match. Each rejected entry\n * surfaces as its own issue at `[index]` with a readable message, which the\n * routes return in their 400 `details`.\n */\nexport const PostureOriginsSchema = z\n .array(z.string().max(MAX_POSTURE_ORIGIN_LENGTH))\n .max(MAX_POSTURE_ORIGINS)\n .transform((origins, ctx) => {\n const result = validatePostureOrigins(origins);\n if (result.ok) return result.origins;\n for (const error of result.errors) {\n ctx.addIssue({\n code: 'custom',\n message: error.message,\n path: error.index >= 0 ? [error.index] : [],\n });\n }\n return z.NEVER;\n });\n","import { z } from 'zod';\n\nexport const MAX_POSTURE_REPORT_PATHS = 50;\nexport const MAX_POSTURE_REPORT_PATH_LENGTH = 200;\n\nconst WHITESPACE = /\\s/;\n\nfunction isAllowedPathCharacter(char: string): boolean {\n const code = char.charCodeAt(0);\n return code > 0x1f && code !== 0x7f && char !== '?' && char !== '#' && !WHITESPACE.test(char);\n}\n\nexport function normalizePostureReportPath(input: string): string | null {\n const trimmed = input.trim();\n if (trimmed.length > MAX_POSTURE_REPORT_PATH_LENGTH || !trimmed.startsWith('/')) return null;\n return [...trimmed].every(isAllowedPathCharacter) ? trimmed : null;\n}\n\nexport const PostureReportPathsSchema = z\n .array(z.string().max(MAX_POSTURE_REPORT_PATH_LENGTH * 2))\n .max(MAX_POSTURE_REPORT_PATHS)\n .transform((paths, ctx) => {\n const normalized: string[] = [];\n let valid = true;\n paths.forEach((path, index) => {\n const value = normalizePostureReportPath(path);\n if (value === null) {\n valid = false;\n ctx.addIssue({\n code: 'custom',\n message: `Enter a path that starts with / and has no spaces, ? or # (up to ${MAX_POSTURE_REPORT_PATH_LENGTH} characters)`,\n path: [index],\n });\n return;\n }\n if (!normalized.includes(value)) normalized.push(value);\n });\n return valid ? normalized : z.NEVER;\n });\n\nexport function readPostureReportPathsSetting(settings: unknown): string[] {\n if (!settings || typeof settings !== 'object') return [];\n const raw = (settings as { postureReportPaths?: unknown }).postureReportPaths;\n if (!Array.isArray(raw)) return [];\n const paths: string[] = [];\n for (const entry of raw.slice(0, MAX_POSTURE_REPORT_PATHS)) {\n if (typeof entry !== 'string') continue;\n const value = normalizePostureReportPath(entry);\n if (value !== null && !paths.includes(value)) paths.push(value);\n }\n return paths;\n}\n","/**\n * Internal API Schemas\n *\n * Schemas for internal dashboard API endpoints\n * Used for validation and type safety in internal routes\n */\n\nimport type { JWK } from 'jose';\nimport { z } from 'zod';\nimport { PAGINATION_DEFAULTS } from '../constants';\nimport {\n ApiKeyPermissionSchema,\n ApiKeyRateLimitsSchema,\n PixelConfigurationSchema,\n} from '../types/entities';\nimport {\n CreateOrganizationInputSchema,\n UpdateOrganizationInputSchema,\n} from '../types/organization';\nimport { isValidAuthorizationHost } from '../mcpi/authorization-host';\nimport { PostureOriginsSchema } from '../types/posture-origins-schema';\nimport { PostureReportPathsSchema } from '../types/posture-report-paths-schema';\n\n/**\n * Flexible Project ID Schema\n * Accepts UUID format, kta- format, and friendly ID format\n *\n * \"Friendly ID format\" covers two shapes: a slug-suffix pair (e.g.\n * \"my-project-a1b2c3\") minted only to disambiguate a name collision, and a\n * bare slug with no suffix (e.g. \"my-project\"): the common case, minted by\n * apps/web's resolveUniqueFriendlyProjectId whenever a project's name is\n * unique. The bare-slug branch is capped at 20 characters to match\n * slugify()'s own truncation (apps/web/lib/utils/project-id.ts), so this\n * doesn't also swallow unrelated garbage (e.g. a truncated UUID) that\n * happens to be lowercase-alnum-and-hyphens shaped.\n */\nexport const ProjectIdSchema = z.string().refine(\n (val) => {\n // UUID v4 format\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n // Legacy kta- format (kta-XXXXXX where X is alphanumeric)\n const ktaIdRegex = /^kta-[a-z0-9]{6}$/;\n // Friendly ID format (slug-suffix, e.g., \"my-project-a1b2c3\")\n const friendlyIdRegex = /^[a-z0-9-]+-[a-z0-9]{6}$/;\n // Bare slug, no suffix (e.g. \"my-project\")\n const bareSlugRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n return (\n uuidRegex.test(val) ||\n ktaIdRegex.test(val) ||\n friendlyIdRegex.test(val) ||\n (val.length <= 20 && bareSlugRegex.test(val))\n );\n },\n {\n message:\n 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., \"my-project-a1b2c3\" or \"my-project\")',\n }\n);\n\n/**\n * Flexible Organization ID Schema\n * Accepts UUID format and slug format (e.g., \"kya-os-kerjid\")\n * Mirrors ProjectIdSchema pattern for consistency\n */\nexport const OrganizationIdSchema = z.string().refine(\n (val) => {\n // UUID v4 format (all versions, not just v4)\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n // Organization slug format (lowercase alphanumeric with hyphens, e.g., \"kya-os-kerjid\")\n const slugRegex = /^[a-z0-9-]+$/i;\n return uuidRegex.test(val) || slugRegex.test(val);\n },\n {\n message: 'Invalid organization ID format. Must be a UUID or slug (e.g., \"kya-os-kerjid\")',\n }\n);\n\n/**\n * Common Query Parameters Schema\n * Used across multiple internal endpoints for pagination and filtering\n */\nexport const QuerySchema = z.object({\n page: z.coerce.number().min(1).default(1).optional(),\n limit: z.coerce\n .number()\n .min(1)\n .max(PAGINATION_DEFAULTS.maxPageSize)\n .default(PAGINATION_DEFAULTS.defaultPageSize)\n .optional(),\n sortBy: z.string().optional(),\n order: z.enum(['asc', 'desc']).default('desc').optional(),\n search: z.string().optional(),\n});\nexport type QueryParams = z.infer<typeof QuerySchema>;\n\n/**\n * Non-sensitive KYA-OS configuration projection returned by organization-wide\n * deployment inventory endpoints. Values are deliberately empty; consumers\n * use only the keys to count configured providers and discovered tools.\n */\nexport interface KyaosDeploymentInventoryConfig {\n oauthProviders: Record<string, Record<string, never>>;\n discoveredTools: Record<string, Record<string, never>>;\n}\n\n/**\n * Projects Schemas\n */\nexport const CreateProjectSchema = z.object({\n name: z.string().min(1).max(255),\n domain: z.string().optional(), // Changed: removed .url() validation to be more lenient\n organizationId: z.string().uuid().optional(), // Optional - backend uses auth session as fallback\n // Setup Flow v2 step 1 (\"What brings you here?\") — the stable\n // SetupV2NeedDef.id keys the user selected (apps/web's\n // lib/setup-v2/flow-types.ts owns the id -> label/product mapping; this\n // shared package only validates shape, not membership, matching\n // settings.allowedOrigins/blockedAgents below). Optional: only the\n // setup-v2 flow ever sends it.\n setupGoals: z.array(z.string().min(1).max(100)).max(50).optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\nexport type CreateProjectRequest = z.infer<typeof CreateProjectSchema>;\n\nexport const UpdateProjectSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n domain: z.string().optional(), // Changed: removed .url() validation to be more lenient\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The org-branded\n // bare host (e.g. `authenticate.acme.com`) that renders consent + serves\n // delegation pickup for this project. Empty string clears it → the web-app\n // platform default. This value becomes a challenge URI authority, so it's\n // validated strictly (no path / userinfo / whitespace / bad labels) rather\n // than left lenient like `domain` — see `isValidAuthorizationHost`.\n authorizationHost: z\n .string()\n .max(255)\n .refine((v) => v === '' || isValidAuthorizationHost(v), {\n message:\n 'Authorization host must be a bare hostname (e.g. authenticate.acme.com), optionally with a :port — no scheme path, \"@\", or spaces',\n })\n .optional(),\n // Detection retention window (project settings page). Min 7 enforced\n // here (application layer), not a DB CHECK — see schema.ts's column\n // comment. Default lives on the column (365), not here, so an update\n // that omits this field never resets an existing project's window.\n detectionRetentionDays: z.number().int().min(7).max(3650).optional(),\n // Per-project consent for publishing this project's agent site-visit\n // interactions to Know That AI's PUBLIC activity feed (project settings\n // page). Omitted on update leaves the column's own default/current value\n // untouched, same convention as detectionRetentionDays above.\n publishSiteVisitToKnowThatAi: z.boolean().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n beaconRateLimitPerMinute: z.number().int().positive().optional(),\n // Additional page origins browser posture may be issued for, beyond\n // the primary derived from `domain`. Replaces the stored list; send\n // `[]` to clear it. Normalized by the shared resolver.\n postureOrigins: PostureOriginsSchema.optional(),\n postureReportPaths: PostureReportPathsSchema.optional(),\n })\n .optional(),\n});\nexport type UpdateProjectRequest = z.infer<typeof UpdateProjectSchema>;\n\n/**\n * Pixels Schemas\n */\nexport const CreatePixelSchema = z.object({\n projectId: ProjectIdSchema,\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n isActive: z.boolean().default(true),\n configuration: PixelConfigurationSchema.optional(),\n});\nexport type CreatePixelRequest = z.infer<typeof CreatePixelSchema>;\n\nexport const UpdatePixelSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n isActive: z.boolean().optional(),\n configuration: PixelConfigurationSchema.optional(),\n});\nexport type UpdatePixelRequest = z.infer<typeof UpdatePixelSchema>;\n\n/**\n * API Keys Schemas\n */\n\nexport const CreateApiKeySchema = z.object({\n name: z.string().min(1).max(255),\n projectId: ProjectIdSchema.optional(),\n permissions: z.array(ApiKeyPermissionSchema).default(['read']),\n rateLimits: ApiKeyRateLimitsSchema.optional(),\n expiresAt: z.string().datetime().optional(),\n});\nexport type CreateApiKeyRequest = z.infer<typeof CreateApiKeySchema>;\n\nexport const UpdateApiKeySchema = z.object({\n name: z.string().min(1).max(255).optional(),\n permissions: z.array(ApiKeyPermissionSchema).optional(),\n rateLimits: ApiKeyRateLimitsSchema.optional(),\n expiresAt: z.string().datetime().optional().nullable(),\n});\nexport type UpdateApiKeyRequest = z.infer<typeof UpdateApiKeySchema>;\n\n/**\n * Marketplace Provisioning Schemas\n *\n * Contract for the internal `POST/DELETE /api/provisioning/keys` endpoint that the\n * KYA-OS Integrations Platform (Vercel/Netlify/… adapters) calls to mint and revoke a\n * per-resource KYA-OS project + API key. Idempotent on (source, externalId, resourceId).\n */\n\n/** Provider kinds that can drive provisioning. Grows as adapters are added. */\nexport const MarketplaceSourceSchema = z.enum([\n 'vercel',\n 'shopify',\n 'netlify',\n 'railway',\n 'shopware',\n 'mixer',\n]);\nexport type MarketplaceSource = z.infer<typeof MarketplaceSourceSchema>;\n\n/** Enforcement posture — mirrors the SDK's `enforcementMode` ('observe' = detect-only). */\nexport const ProvisioningModeSchema = z.enum(['observe', 'enforce']);\nexport type ProvisioningMode = z.infer<typeof ProvisioningModeSchema>;\n\n/** Backend-verifiable installer identity. Caller-supplied verification flags confer no authority. */\nexport const ProvisioningIdentityProofSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('vercel-oidc'), token: z.string().min(1).max(16384) }),\n z.object({ type: z.literal('railway-oauth'), accessToken: z.string().min(1).max(16384) }),\n z.object({ type: z.literal('checkpoint-account-link'), token: z.string().min(1).max(16384) }),\n]);\nexport type ProvisioningIdentityProof = z.infer<typeof ProvisioningIdentityProofSchema>;\n\n/** A signed account-link capability issued only from the installer's authenticated session. */\nexport const ProvisioningAccountLinkRequestSchema = z.object({\n source: MarketplaceSourceSchema,\n externalId: z.string().min(1).max(255),\n resourceId: z.string().min(1).max(255).optional(),\n});\nexport type ProvisioningAccountLinkRequest = z.infer<typeof ProvisioningAccountLinkRequestSchema>;\n\nexport const ProvisioningAccountLinkResponseSchema = z.object({\n identityProof: z.object({ type: z.literal('checkpoint-account-link'), token: z.string().min(1) }),\n expiresIn: z.literal(600),\n});\nexport type ProvisioningAccountLinkResponse = z.infer<typeof ProvisioningAccountLinkResponseSchema>;\n\nexport const ProvisionKeyRequestSchema = z.object({\n identityProof: ProvisioningIdentityProofSchema.optional(),\n source: MarketplaceSourceSchema,\n /** Provider installation/configuration id (e.g. Vercel configurationId). */\n externalId: z.string().min(1).max(255),\n /**\n * Provider resource id (e.g. one Vercel project); idempotency key with (source, externalId).\n * Single-resource providers repeat `externalId` here rather than inventing a sentinel — a\n * Shopware shop, for instance, has no sub-resource comparable to a Vercel project, so its\n * triple is ('shopware', shopId, shopId). Intentional, not a caller bug.\n */\n resourceId: z.string().min(1).max(255),\n /** Human-readable label for the dashboard (e.g. \"Vercel / team_xxx / my-project\"). */\n label: z.string().min(1).max(200),\n /** Installer email must match the identity established by identityProof. */\n owner: z.object({\n email: z.string().email(),\n name: z.string().min(1).max(255).optional(),\n }),\n /** Recorded on the provision for the dashboard; the SDK's enforcementMode is code-level today. */\n mode: ProvisioningModeSchema.default('observe'),\n /**\n * Org the installer chose in the adapter UI. Treated as a HINT: the backend binds the\n * installation to it and mints there only when the resolved user OWNS or ADMINISTERS it\n * (matching the orgs the list endpoint surfaces) — otherwise it falls back to the personal\n * org (owner/admin backstop in `mintWithinTx`). Omitted = legacy behavior (personal/default\n * org).\n */\n organizationId: z.string().uuid().optional(),\n /** Optional non-secret provider context (teamId, userId, resource name). */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ProvisionKeyRequest = z.infer<typeof ProvisionKeyRequestSchema>;\n\nexport const ProvisionKeyResponseSchema = z.object({\n /**\n * Plaintext API key — injected by the adapter as CHECKPOINT_API_KEY. Returned once on mint;\n * on idempotent re-provision the same key is returned (decrypted from storage).\n */\n apiKey: z.string().min(1),\n /** The KYA-OS project the key is scoped to. */\n projectId: z.string().uuid(),\n /** The API key row id (revoke is keyed by source/externalId/resourceId, not this). */\n apiKeyId: z.string().uuid(),\n organizationId: z.string().uuid(),\n /** True when an existing provision was returned rather than a new one created. */\n idempotent: z.boolean(),\n});\nexport type ProvisionKeyResponse = z.infer<typeof ProvisionKeyResponseSchema>;\n\n/**\n * Request for `POST /api/provisioning/sso-link` — the \"Open in Provider\" handoff.\n * The backend verifies `ownerEmail` using provider evidence or an authenticated account-link ticket.\n */\nexport const SsoLinkRequestSchema = z.object({\n identityProof: ProvisioningIdentityProofSchema.optional(),\n source: MarketplaceSourceSchema,\n /** Provider installation/configuration id (e.g. Vercel configurationId). */\n externalId: z.string().min(1).max(255),\n /** Optional provider resource id — present → deep-link to that project; absent → org landing. */\n resourceId: z.string().min(1).max(255).optional(),\n /** Installer email must match the identity established by identityProof. */\n ownerEmail: z.string().email(),\n});\nexport type SsoLinkRequest = z.infer<typeof SsoLinkRequestSchema>;\n\nexport const SsoLinkResponseSchema = z.object({\n /** Ready-to-redirect URL: the integration 302s the browser here. Establishes the session and lands on the friendly-id dashboard route. */\n url: z.string().min(1),\n});\nexport type SsoLinkResponse = z.infer<typeof SsoLinkResponseSchema>;\n\n/**\n * DELETE query for `/api/provisioning/keys`. Omitting `resourceId` revokes ALL keys for the\n * installation (the uninstall path); supplying it revokes a single resource.\n */\nexport const RevokeProvisionQuerySchema = z.object({\n source: MarketplaceSourceSchema,\n externalId: z.string().min(1).max(255),\n resourceId: z.string().min(1).max(255).optional(),\n});\nexport type RevokeProvisionQuery = z.infer<typeof RevokeProvisionQuerySchema>;\n\nexport const RevokeProvisionResponseSchema = z.object({\n /** Number of provisions revoked (0 if nothing matched — DELETE is idempotent). */\n revoked: z.number().int().nonnegative(),\n});\nexport type RevokeProvisionResponse = z.infer<typeof RevokeProvisionResponseSchema>;\n\n/**\n * Provisioning Organization-Selection Schemas\n *\n * Contract for the service-authenticated org chooser the KYA-OS Integrations adapter\n * (Vercel/…) drives so an installer can pick which Checkpoint org to link — or create a\n * new one — instead of always landing in their default/personal org. The end user is\n * identified ONLY by the verified `email` (the account-linking key); never a session.\n * - `POST /api/provisioning/organizations/list` → { organizations }\n * - `POST /api/provisioning/organizations` → { organization }\n * Both authenticate with the `sk_service_provisioning_` service key and wrap the payloads\n * below in the standard `{ success, data }` envelope at the route.\n */\n\n/** Roles the adapter may bind an installation to — an installer can only choose an org they administer. */\nexport const ProvisioningOrganizationRoleSchema = z.enum(['owner', 'admin']);\nexport type ProvisioningOrganizationRole = z.infer<typeof ProvisioningOrganizationRoleSchema>;\n\n/** One org the resolved user owns or administers (the adapter's `OrganizationSummary`). */\nexport const ProvisioningOrganizationSummarySchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n slug: z.string(),\n role: ProvisioningOrganizationRoleSchema,\n});\nexport type ProvisioningOrganizationSummary = z.infer<typeof ProvisioningOrganizationSummarySchema>;\n\n/** List a user's administrable orgs by verified email. No user match ⇒ `{ organizations: [] }`. */\nexport const ListProvisioningOrganizationsRequestSchema = z.object({\n source: MarketplaceSourceSchema.optional(),\n externalId: z.string().min(1).max(255).optional(),\n resourceId: z.string().min(1).max(255).optional(),\n identityProof: ProvisioningIdentityProofSchema.optional(),\n email: z.string().email(),\n});\nexport type ListProvisioningOrganizationsRequest = z.infer<\n typeof ListProvisioningOrganizationsRequestSchema\n>;\n\nexport const ListProvisioningOrganizationsResponseSchema = z.object({\n organizations: z.array(ProvisioningOrganizationSummarySchema),\n});\nexport type ListProvisioningOrganizationsResponse = z.infer<\n typeof ListProvisioningOrganizationsResponseSchema\n>;\n\n/**\n * Create an org for a (found-or-created) user by verified email. `name`/`slug` reuse the\n * dashboard's `CreateOrganizationInputSchema` validators so the service + session paths\n * accept exactly the same input.\n */\nexport const CreateProvisioningOrganizationRequestSchema = z.object({\n source: MarketplaceSourceSchema.optional(),\n externalId: z.string().min(1).max(255).optional(),\n resourceId: z.string().min(1).max(255).optional(),\n identityProof: ProvisioningIdentityProofSchema.optional(),\n email: z.string().email(),\n name: CreateOrganizationInputSchema.shape.name,\n slug: CreateOrganizationInputSchema.shape.slug,\n});\nexport type CreateProvisioningOrganizationRequest = z.infer<\n typeof CreateProvisioningOrganizationRequestSchema\n>;\n\nexport const CreateProvisioningOrganizationResponseSchema = z.object({\n /** The just-created org; `role` is always `owner` (the creator is inserted as owner). */\n organization: ProvisioningOrganizationSummarySchema,\n});\nexport type CreateProvisioningOrganizationResponse = z.infer<\n typeof CreateProvisioningOrganizationResponseSchema\n>;\n\n/**\n * Organizations Schemas\n * Using enhanced schemas from organization types\n */\nexport const CreateOrganizationSchema = CreateOrganizationInputSchema;\nexport type CreateOrganizationRequest = z.infer<typeof CreateOrganizationSchema>;\n\nexport const UpdateOrganizationSchema = UpdateOrganizationInputSchema;\nexport type UpdateOrganizationRequest = z.infer<typeof UpdateOrganizationSchema>;\n\n/**\n * Analytics Schemas\n */\nexport const AnalyticsQuerySchema = z.object({\n projectId: ProjectIdSchema.optional(),\n pixelId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n timeWindow: z\n .enum(['realtime', 'hourly', 'daily', 'weekly', 'monthly'])\n .default('daily')\n .optional(),\n groupBy: z.enum(['hour', 'day', 'week', 'month']).optional(),\n aiAgentsOnly: z.coerce.boolean().optional(),\n});\nexport type AnalyticsQueryRequest = z.infer<typeof AnalyticsQuerySchema>;\n\nexport const ExportAnalyticsSchema = z.object({\n projectId: ProjectIdSchema.optional(),\n organizationId: z.string().uuid().optional(),\n pixelId: z.string().uuid().optional(),\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n format: z.enum(['csv', 'json']).default('csv'),\n sections: z\n .array(z.enum(['overview', 'traffic', 'agents', 'confidence', 'sessions']))\n .optional()\n .default(['overview', 'traffic', 'agents']),\n includeRawData: z.boolean().optional().default(false),\n showAIAgentsOnly: z.boolean().optional().default(false),\n});\nexport type ExportAnalyticsRequest = z.infer<typeof ExportAnalyticsSchema>;\n\n/**\n * Settings Schemas\n */\nexport const UpdateSettingsSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n // No `email`: roles are derived from the stored address (partner service\n // and superadmin allowlists), so it must not change without proof of the\n // new mailbox. PUT /api/internal/settings refuses a body that carries one.\n // Note: Plan updates would typically be handled through billing/subscription endpoints\n});\nexport type UpdateSettingsRequest = z.infer<typeof UpdateSettingsSchema>;\n\nexport const DeleteAccountSchema = z.object({\n confirmation: z.literal('DELETE_MY_ACCOUNT'),\n});\nexport type DeleteAccountRequest = z.infer<typeof DeleteAccountSchema>;\n\n/**\n * Specialized Query Schemas\n */\nexport const ProjectsQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'updatedAt', 'name']).default('createdAt').optional(),\n // Accept both UUID and slug format for organization ID\n organizationId: OrganizationIdSchema.optional(),\n});\nexport type ProjectsQueryParams = z.infer<typeof ProjectsQuerySchema>;\n\nexport const PixelsQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'updatedAt', 'name']).default('createdAt').optional(),\n projectId: ProjectIdSchema.optional(),\n isActive: z.coerce.boolean().optional(),\n});\nexport type PixelsQueryParams = z.infer<typeof PixelsQuerySchema>;\n\nexport const ApiKeysQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'lastUsedAt', 'name']).default('createdAt').optional(),\n projectId: ProjectIdSchema.optional(),\n organizationId: z.string().uuid().optional(),\n includeRevoked: z.coerce.boolean().default(false).optional(),\n});\nexport type ApiKeysQueryParams = z.infer<typeof ApiKeysQuerySchema>;\n\n/**\n * Response Schemas\n */\nexport const PaginatedResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.boolean(),\n data: z.array(itemSchema),\n pagination: z.object({\n page: z.number(),\n limit: z.number(),\n total: z.number(),\n totalPages: z.number(),\n hasMore: z.boolean(),\n }),\n });\n\nexport const SingleItemResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.boolean(),\n data: itemSchema,\n });\n\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false),\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }),\n});\nexport type ErrorResponse = z.infer<typeof ErrorResponseSchema>;\n\n/**\n * Generic Response Types\n */\nexport type SuccessResponse<T> = {\n success: true;\n data: T;\n};\n\nexport type PaginatedData<T> = {\n items: T[];\n pagination: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n };\n};\n\nexport type PaginatedResponse<T> = {\n success: true;\n data: T[];\n pagination: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n // Optional field for client-side filtered results\n filteredCount?: number;\n };\n};\n\n/**\n * Analytics Response Types\n */\nexport type TimeSeriesPoint = {\n timestamp: string | Date;\n total: number;\n agents: number;\n humans: number;\n avgConfidence: number;\n // Session-based metrics\n totalSessions: number;\n agentSessions: number;\n humanSessions: number;\n // Separated bot and AI agent sessions\n botSessions: number;\n aiAgentSessions: number;\n};\n\nexport type AgentTypeDistribution = {\n agentType: string;\n count: number;\n uniqueSessions: number;\n avgConfidence: number;\n // Surfaced from the agent_types leftJoin so callers can filter on the\n // canonical category (e.g. 'ai_assistant') without re-running the JS\n // string heuristic in `lib/utils/agent-category.ts`. Optional because\n // a leftJoin miss returns null at runtime; consumers treat falsy as\n // \"unknown\" (#2275). Other join columns the route emits\n // (agentTypeId, displayName, isLegitimate, lastSeen) are intentionally\n // omitted — downstream consumers model those locally with stricter\n // shapes that conflict with the leftJoin nullability.\n category?: string;\n};\n\nexport type PixelStatsData = {\n pixel: {\n id: string;\n name: string;\n };\n detectionCount: number;\n agentCount: number;\n};\n\nexport type ConfidenceRange = {\n range: string;\n count: number;\n};\n\nexport type AnalyticsOverview = {\n totalDetections: number;\n totalAgents: number;\n averageConfidence: number;\n uniqueSessions: number;\n // Add unique session breakdowns to avoid double-counting\n uniqueAgentSessions?: number;\n uniqueHumanSessions?: number;\n uniqueBotSessions?: number;\n uniqueAIAgentSessions?: number;\n uniqueIncompleteDataSessions?: number;\n mostActiveHour?: {\n hour: number;\n detections: number;\n label: string;\n };\n detectionChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n sessionChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n aiAgentChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n botChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n humanChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n};\n\nexport type AnalyticsDetailRange = {\n start: string;\n end: string;\n lastDay: string;\n};\n\nexport type AnalyticsUnavailableField = {\n field:\n | 'hourlyDistribution'\n | 'mostActiveHour'\n | 'confidenceDistribution'\n | 'topPages'\n | 'topPixels';\n reason: 'raw_detail_history';\n requestedRange: AnalyticsDetailRange;\n availableRange: AnalyticsDetailRange | null;\n};\n\nexport type AnalyticsSessionCounting = 'per_utc_day';\n\nexport type AnalyticsMeta = {\n source?: string;\n aiAgentsOnly?: boolean;\n lastUpdated?: string;\n rollupCount?: number;\n current?: boolean;\n sessionCounting?: AnalyticsSessionCounting;\n};\n\nexport type AnalyticsData = {\n overview: AnalyticsOverview;\n timeSeries: TimeSeriesPoint[];\n agentTypes: AgentTypeDistribution[];\n topPixels: PixelStatsData[];\n confidenceDistribution: ConfidenceRange[];\n dateRange: {\n start: string;\n end: string;\n };\n unavailable?: AnalyticsUnavailableField[];\n _meta?: AnalyticsMeta;\n};\n\n/**\n * Project Response Types\n */\nexport type ProjectWithStats = {\n id: string;\n friendlyId?: string | null;\n userId: string;\n organizationId?: string | null;\n name: string;\n domain?: string | null;\n /**\n * `projects.authorization_host`: the bare host consent is served on, or null\n * for the platform default. Returned by GET /api/internal/projects/[id].\n */\n authorizationHost?: string | null;\n /** Detection retention window in days (project settings page). Default 365, minimum 7. */\n detectionRetentionDays?: number;\n /** Whether this project's site-visit interactions publish to Know That AI's public activity feed. Default true. */\n publishSiteVisitToKnowThatAi?: boolean;\n /** Set once \"Browser posture\" is enabled for this project — never the private key itself. */\n postureKeyId?: string | null;\n posturePublicKey?: JWK | null;\n /** Cloudflare Turnstile site key (gateway-enforcement-step-up, build item\n * 6) — public, safe to send to the dashboard. Presence is the\n * \"configured\" flag; the secret key never leaves the server. */\n turnstileSiteKey?: string | null;\n settings: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n userAccessLevel?: 'owner' | 'admin' | 'editor' | 'viewer' | null;\n stats: {\n pixelCount: number;\n detectionCount: number;\n sessionCount: number;\n weeklySessionCount: number;\n weeklyAgentSessionCount: number;\n lastDetection: Date | null;\n recentDetections?: number;\n recentAgents?: number;\n /**\n * Per-day session counts over the trailing 7 days (oldest first).\n * Always length 7 — days with no rollup row fill as 0 so the\n * sparkline renders a continuous timeline rather than a gappy\n * one. Drives the project card's sparkline.\n */\n dailySessions?: number[];\n /**\n * Total sessions in the **previous** 7-day window (days 8-14 ago).\n * Used to derive the week-over-week trend % on the project card.\n *\n * Note: this is the value used as the DENOMINATOR of the\n * trend calculation. When zero, no honest % can be computed\n * (division undefined) — the renderer drops the trend pill.\n */\n prevWeekSessionCount?: number;\n };\n};\n\n/**\n * Pixel Response Types\n */\nexport type PixelWithStats = {\n id: string;\n projectId: string;\n name: string;\n secretKey: string;\n configuration: Record<string, unknown>;\n isActive: boolean;\n createdAt: Date;\n updatedAt: Date;\n // Matches the actual shape returned by GET /api/internal/pixels:\n // `detectionCount` is the trigger-maintained ALL-TIME total and\n // `lastDetection` the trigger-maintained last-detection timestamp (both\n // denormalized pixels columns, no detections scan); `recentDetections` is\n // a live 24h rolling count. There is no per-agent/per-session breakdown\n // at this endpoint (see `/api/internal/pixels/[pixelId]` for the richer\n // single-pixel shape, which this type does not describe).\n stats?: {\n detectionCount: number;\n recentDetections: number;\n lastDetection: Date | null;\n };\n};\n\n/**\n * Settings Response Types\n */\nexport type UserUsage = {\n projects: {\n used: number;\n limit: number;\n percentage: number;\n };\n pixels: {\n used: number;\n limit: number;\n percentage: number;\n };\n apiKeys: {\n used: number;\n limit: number;\n percentage: number;\n };\n};\n\nexport type PlanLimits = {\n projects: number;\n pixelsPerProject: number;\n apiKeys: number;\n teamMembers: number;\n dataRetentionDays: number;\n customDomains: number;\n webhooks: number;\n alertRules: number;\n sessionsTracked: number;\n exportSizeLimit: number;\n};\n\nexport type PlanFeatures = {\n customDomains: boolean;\n webhooks: boolean;\n alertRules: boolean;\n teamMembers: boolean;\n unlimitedProjects: boolean;\n unlimitedPixels: boolean;\n unlimitedApiKeys: boolean;\n};\n\n/**\n * Dashboard Stats Types\n */\nexport type DashboardStatItem = {\n current: number;\n previous?: number;\n percentageChange?: number;\n};\n\nexport type DashboardStatsResponse = {\n domains: {\n current: number;\n activeProjects: number;\n inactiveProjects: number;\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n totalSessions: DashboardStatItem & {\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n agentSessions: DashboardStatItem & {\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n sessionBreakdown?: {\n botSessions: number;\n humanSessions: number;\n incompleteDataSessions: number;\n };\n /**\n * Distinct agent types seen in the last 7 days across the org's\n * projects. Computed from a 14-day detections scan with PG `FILTER`\n * clauses so `current` and `previous` are produced in a single pass.\n * Optional fields preserve backwards compatibility with older\n * response payloads that emitted `current` only.\n */\n uniqueAgents?: DashboardStatItem;\n /**\n * Distinct users seen in the last 7 days across the org's AI-agent\n * detections. Same 14-day single-scan strategy as uniqueAgents.\n * Tier-coalesced identity (email > userId > ipAddress > 'unattributed').\n */\n uniqueUsers?: DashboardStatItem;\n};\n\nexport const DashboardStatsRequestSchema = z.object({\n organizationId: z.string().uuid().optional(),\n});\nexport type DashboardStatsRequest = z.infer<typeof DashboardStatsRequestSchema>;\n\n/* ─────────────────────────────────────────────────────────────────────\n Home-rail rollups — single payload for the four rollup-backed v2\n home-rail widgets (NOW, AGENT MIX, ACTIVE HOURS, CONFIDENCE).\n Service: apps/web/lib/services/analytics/home-rail-rollups.service.ts\n Route: GET /api/internal/home-rail/rollups\n ────────────────────────────────────────────────────────────────── */\n\n/** YYYY-MM-DD slot inside the 7-day sparkline / heatmap window. */\nexport interface HomeRailDailyPoint {\n /** UTC date as YYYY-MM-DD — same shape as the rollup column. */\n date: string;\n totalSessions: number;\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n /** 24-element histogram of distinct sessions per hour-of-day (UTC). */\n hourDistribution: number[];\n}\n\n/** Aggregated metrics over a 7-day window. */\nexport interface HomeRailWindowAggregate {\n totalSessions: number;\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n totalDetections: number;\n highConfidenceDetections: number;\n /**\n * Detection-weighted avg confidence — sum of (per-day avg × per-day\n * detections) / sum of detections. Reads honest even when one day\n * has 10x the traffic of the others.\n *\n * Cross-class — includes both ai_agent and bot detections, matching\n * how `organization_rollups.avg_confidence` is computed. For an\n * AI-only confidence number, use `HomeRailRollupsResponse.aiAgent7d`.\n */\n avgConfidence: number;\n}\n\n/**\n * AI-agent-only aggregate over the same 7-day window as `current7d`.\n *\n * Sourced from `agent_daily_rollup` filtered to `detection_class =\n * 'ai_agent'`, summed across all of the org's projects in the window.\n * Uses `totalConfidenceSum / detections` for the detection-weighted\n * average — same shape as `agent_daily_rollup.avg_confidence` math in\n * top-agents.service.ts.\n *\n * Why a separate aggregate (not a field on `current7d`)?\n * - `current7d` reads from `organization_rollups`, whose confidence\n * column is cross-class by design (and the schema comment warns\n * against narrowing only the numerator).\n * - `agent_daily_rollup` has the per-class breakdown we need, but\n * it's keyed per (project, agent_type, class, date) instead of\n * (org, date) — different scan, different aggregate.\n *\n * `high_confidence_detections` is *not* available per-class in the\n * rollups today, so the AI-only response only carries the avg and\n * the total. Surfacing a ratio bar honestly would require a new\n * column + backfill (F-05 follow-up).\n */\nexport interface HomeRailAiAgentAggregate {\n totalDetections: number;\n avgConfidence: number;\n}\n\nexport interface HomeRailRollupsResponse {\n today: HomeRailDailyPoint;\n current7d: HomeRailWindowAggregate;\n previous7d: HomeRailWindowAggregate;\n /** 7 daily points covering the current 7d window, ordered oldest → newest. */\n trend7d: HomeRailDailyPoint[];\n /**\n * AI-agent-only aggregate over the current 7d window. Powers\n * `ConfidenceWidget`, which deliberately scopes to AI agents (the\n * cross-class number in `current7d.avgConfidence` reads as\n * \"AI + bot confidence\" and was confusing operators).\n */\n aiAgent7d: HomeRailAiAgentAggregate;\n /** Newest `refreshedAt` across the read rows; null when no rows exist. */\n refreshedAt: string | null;\n /** Current 7d window bounds, UTC dates as YYYY-MM-DD. */\n windowStart: string;\n windowEnd: string;\n}\n\n// Accepts slug or UUID — matches the route's\n// `PermissionService.resolveOrganizationAccess` resolver and the\n// dashboard's URL pattern (orgs are navigated via slugs). The previous\n// `z.string().uuid()` constraint would have rejected every dashboard\n// call at runtime had any consumer validated input against this shared\n// schema (cursor-bot flagged the divergence on 6ceea5f24).\nexport const HomeRailRollupsRequestSchema = z.object({\n organizationId: OrganizationIdSchema,\n});\nexport type HomeRailRollupsRequest = z.infer<typeof HomeRailRollupsRequestSchema>;\n\nexport type SettingsData = {\n user: {\n id: string;\n email: string;\n name?: string | null;\n image?: string | null;\n plan?: string | null;\n emailVerified?: Date | null;\n createdAt: Date;\n updatedAt: Date;\n };\n usage: UserUsage;\n planLimits: PlanLimits;\n features: PlanFeatures;\n};\n\n/**\n * API Key Response Types\n */\nexport type ApiKeyWithProject = {\n id: string;\n userId: string;\n projectId?: string | null;\n name: string;\n key: string;\n permissions: string[];\n rateLimits: Record<string, unknown>;\n lastUsedAt?: Date | null;\n expiresAt?: Date | null;\n createdAt: Date;\n revokedAt?: Date | null;\n project?: {\n id: string;\n name: string;\n } | null;\n};\n","/**\n * Detection signal exposure: the wire shape of the \"full signal set\"\n * block on the `/api/v1/enforce` detection response (KYA-1107, \"Adobe\n * Golden Snapshot\").\n *\n * Every enforce detection payload carries these fields in addition to the\n * condensed summary fields. Additive only: consumers must ignore keys they\n * do not know (every current consumer was verified lenient to unknown keys\n * before this became unconditional).\n *\n * This schema is the SSOT for the exposed shape:\n * - the generated reference (`docs/architecture/detection-signal-exposure.generated.md`)\n * is derived from the `.describe()` strings here by\n * `scripts/generate-signal-exposure-docs.ts`, CI-gated so docs and wire\n * cannot drift (`detection-signal-exposure-check.yml`, same pattern as\n * the error-code and reason-code registries);\n * - the golden example `fixtures/detection/signal-exposure-example.json`\n * is parsed against it in `__tests__/signal-exposure.test.ts`.\n *\n * Extension point: `signals[]` is deliberately the ONLY place new detection\n * capabilities surface. A future signal family (request-velocity, platform\n * bot-management corroboration, …) ships as new `signals[].source` values\n * plus new `detection/*` reason codes (both additive), so this shape never\n * needs a breaking change to absorb them.\n */\nimport { z } from 'zod';\n\nimport { ConfidenceLevelSchema } from '../core/confidence';\nimport { DetectionSignalSchema } from '../core/detection';\nimport { DetectionReasonCodeSchema } from '../core/detection-reason-code-schema';\nimport { RiskScoreSchema, RiskScoreSourceSchema } from '../core/risk-score';\n\nexport { DetectionReasonCodeSchema };\n\n/**\n * The exposure block, spread flat onto the enforce response's\n * `detection` object (NOT nested) so it stays symmetric with the gateway\n * plane's detection detail, where `signals` already rides inline.\n */\nexport const DetectionSignalExposureSchema = z.object({\n signals: z\n .array(DetectionSignalSchema)\n .describe(\n \"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.\"\n ),\n reasonCodes: z\n .array(DetectionReasonCodeSchema)\n .min(1)\n .describe(\n '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.'\n ),\n confidenceLevel: ConfidenceLevelSchema.optional().describe(\n \"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).\"\n ),\n isAiCrawler: z\n .boolean()\n .optional()\n .describe(\n 'True when the engine classified the client as an AI training crawler (GPTBot, ClaudeBot, …) rather than an interactive agent. Omitted when the engine did not run.'\n ),\n riskScore: RiskScoreSchema.optional().describe(\n 'The Noisy-Or probability that the request is automated (0-1, two decimals), uncalibrated (see riskScoreSource), derived from detectionDetail.metadata.shadow_noisy_or_confidence. Null when the combiner did not run. Distinct from `confidence` above, which is never derived from it.'\n ),\n riskScoreSource: RiskScoreSourceSchema.optional().describe(\n \"Which metadata key riskScore was derived from: 'uncalibrated' (always true today) or 'calibrated' (not yet wired). Null exactly when riskScore is null.\"\n ),\n});\nexport type DetectionSignalExposure = z.infer<typeof DetectionSignalExposureSchema>;\n","/**\n * Fingerprint API Types and Schemas\n *\n * Comprehensive type definitions for the fingerprinting system\n * used to detect and analyze bot/AI agent characteristics\n */\n\nimport { z } from 'zod';\n\n/**\n * Fingerprint analysis result\n */\nexport const FingerprintAnalysisSchema = z.object({\n // Detection results\n hasChromiumHeaders: z.boolean(),\n hasBrowserHeaders: z.boolean(),\n hasSecFetchHeaders: z.boolean(),\n isAutomated: z.boolean(),\n suspiciousPatterns: z.array(z.string()),\n confidence: z.number().min(0).max(1),\n detectedAgent: z.string(),\n\n // Additional detection flags\n isLikelyBot: z.boolean().optional(),\n isLikelyAI: z.boolean().optional(),\n isLikelyClaude: z.boolean().optional(),\n\n // Detailed detection\n detection: z\n .object({\n isAutomatedBrowser: z.boolean().optional(),\n isPuppeteer: z.boolean().optional(),\n isPlaywright: z.boolean().optional(),\n isHeadless: z.boolean().optional(),\n hasWebDriverApi: z.boolean().optional(),\n isLikelyMCPTool: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type FingerprintAnalysis = z.infer<typeof FingerprintAnalysisSchema>;\n\n/**\n * Comprehensive fingerprint response\n */\nexport const FingerprintResponseSchema = z.object({\n timestamp: z.string(),\n method: z.string(),\n url: z.string(),\n path: z.string(),\n queryParams: z.record(z.string(), z.string()),\n headers: z.record(z.string(), z.string()),\n headerCount: z.number(),\n ip: z.string(),\n httpVersion: z.string(),\n\n // Analysis results\n fingerprint: FingerprintAnalysisSchema,\n\n // Detailed analysis\n analysis: z.object({\n userAgent: z.string(),\n acceptHeader: z.string(),\n acceptLanguage: z.string(),\n acceptEncoding: z.string(),\n hasReferer: z.boolean(),\n hasCookies: z.boolean(),\n hasAuthorization: z.boolean(),\n secChUa: z.string(),\n secChUaMobile: z.string(),\n secChUaPlatform: z.string(),\n secFetchSite: z.string(),\n secFetchMode: z.string(),\n secFetchDest: z.string(),\n }),\n\n // Detection summary\n detection: z.object({\n isLikelyBot: z.boolean(),\n isLikelyAI: z.boolean(),\n agentType: z.string(),\n confidence: z.string(),\n }),\n\n // For POST requests\n body: z.unknown().optional(),\n bodyType: z.string().optional(),\n contentType: z.string().optional(),\n});\n\nexport type FingerprintResponse = z.infer<typeof FingerprintResponseSchema>;\n\n/**\n * TLS fingerprint data\n */\nexport const TLSFingerprintSchema = z.object({\n version: z.string().optional(),\n cipherSuites: z.array(z.string()).optional(),\n extensions: z.array(z.string()).optional(),\n supportedGroups: z.array(z.string()).optional(),\n signatureAlgorithms: z.array(z.string()).optional(),\n ja3: z.string().optional(),\n ja3s: z.string().optional(),\n});\n\nexport type TLSFingerprint = z.infer<typeof TLSFingerprintSchema>;\n\n/**\n * Network timing data\n */\nexport const NetworkTimingSchema = z.object({\n dns: z.number().optional(),\n tcp: z.number().optional(),\n tls: z.number().optional(),\n ttfb: z.number().optional(),\n download: z.number().optional(),\n total: z.number().optional(),\n});\n\nexport type NetworkTiming = z.infer<typeof NetworkTimingSchema>;\n","/**\n * Shopify Integration Types\n *\n * Type definitions for Shopify app integration endpoints and data structures\n */\n\nimport { z } from 'zod';\nimport { PostureOriginsSchema } from './posture-origins-schema';\n\n/**\n * Shopify Project Provision Request\n */\nexport const ShopifyProjectProvisionRequestSchema = z.object({\n domain: z.string().min(1).max(255),\n email: z.string().email(),\n name: z.string().min(1).max(255),\n source: z.string().optional().default('shopify_app'),\n});\n\nexport type ShopifyProjectProvisionRequest = z.infer<typeof ShopifyProjectProvisionRequestSchema>;\n\n/**\n * Shopify Project Provision Result\n */\nexport const ShopifyProjectProvisionResultSchema = z.object({\n projectId: z.string().uuid(),\n friendlyId: z.string(),\n pixelId: z.string().uuid(),\n apiKey: z.string(),\n domain: z.string(),\n status: z.literal('active'),\n createdAt: z.string().datetime(),\n // User account information (for Shopify merchants)\n user: z.object({\n email: z.string().email(),\n userId: z.string().uuid(),\n accountCreated: z.boolean(), // true = new account, false = existing\n welcomeEmailSent: z.boolean(),\n setupTokenExpiry: z.string().datetime().nullable(),\n }),\n});\n\nexport type ShopifyProjectProvisionResult = z.infer<typeof ShopifyProjectProvisionResultSchema>;\n\n/**\n * Shopify Threat Information\n * Now represents a session (grouped by consolidated_session_id) rather than individual detections\n */\nexport const ShopifyThreatSchema = z.object({\n sessionId: z.string(), // consolidated_session_id for session grouping\n timestamp: z.string().datetime(), // lastSeen timestamp for the session\n type: z.string(), // agent type (e.g., \"ChatGPT\", \"Claude\")\n ip: z.string(),\n userAgent: z.string(),\n action: z.string(),\n pagesVisited: z.number().int().nonnegative(), // Count of unique pages visited in session\n});\n\nexport type ShopifyThreat = z.infer<typeof ShopifyThreatSchema>;\n\n/**\n * Pagination Information\n */\nexport const PaginationInfoSchema = z.object({\n page: z.number().int().positive(),\n limit: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n hasMore: z.boolean(),\n});\n\n/** The three session classes of the ai_agent > bot > human priority partition. */\nexport const ShopifySessionClassSchema = z.enum(['ai_agent', 'bot', 'human']);\n\n/**\n * One visit (consolidated session) of the stats window, returned with\n * `include=sessions`. Carries no IP, user agent or device data.\n */\nexport const ShopifySessionSchema = z.object({\n sessionId: z.string().describe('Consolidated session id (UUID).'),\n firstSeenAt: z\n .string()\n .datetime()\n .describe('ISO-8601 instant of the first detection of the session in the window.'),\n lastSeenAt: z\n .string()\n .datetime()\n .describe('ISO-8601 instant of the latest detection of the session in the window.'),\n eventCount: z\n .number()\n .int()\n .nonnegative()\n .describe('Detections of the session in the window, every class included.'),\n detectionClass: ShopifySessionClassSchema.describe(\n 'Session class by priority: ai_agent if any detection is an AI agent, else bot if any is a bot, else human.'\n ),\n agentName: z\n .string()\n .nullable()\n .describe('Agent type of the latest detection of the session class that names one.'),\n agentCategory: z.string().nullable().describe('Agent category of that same detection.'),\n geoCountry: z\n .string()\n .nullable()\n .describe('ISO 3166-1 alpha-2 country of the latest detection that has one.'),\n uniquePathCount: z\n .number()\n .int()\n .nonnegative()\n .describe('Distinct request paths of the session in the window.'),\n paths: z.array(z.string()).describe('Distinct request paths in first-arrival order, at most 25.'),\n});\n\nexport type ShopifySession = z.infer<typeof ShopifySessionSchema>;\n\n/** Pagination of `sessions`. `total` is exact; `totalPages` stops at the highest page accepted (200). */\nexport const ShopifySessionsPaginationSchema = z.object({\n page: z.number().int().positive(),\n limit: z.number().int().positive(),\n total: z\n .number()\n .int()\n .nonnegative()\n .describe(\n 'Sessions matching `sessionsClass` in the window: equal to the headline count for that class (`totalRequests` with no class).'\n ),\n totalPages: z\n .number()\n .int()\n .nonnegative()\n .describe('`min(ceil(total / limit), 200)`: the last page `sessionsPage` accepts.'),\n hasMore: z.boolean().describe('True when `page < totalPages`.'),\n});\n\nexport type ShopifySessionsPagination = z.infer<typeof ShopifySessionsPaginationSchema>;\n\nexport const ShopifyStatsResponseSchema = z.object({\n totalRequests: z.number().int().nonnegative(),\n blockedBots: z.number().int().nonnegative(),\n allowedRequests: z.number().int().nonnegative(),\n crawlerSessions: z.number().int().nonnegative().optional(),\n humanSessions: z.number().int().nonnegative().optional(),\n unidentifiedSessions: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe(\n 'Sessions in the window with no ai_agent, bot or human detection and at least one incomplete-data detection that carries the no_evidence basis: an idle visitor the engine had nothing to weigh. They are counted in `totalRequests` and `humanSessions`, so this says how many of the human sessions the engine could not classify. Sessions whose incomplete-data detections all have another reason, such as suspicious headers, are in no counter. A window over 31 days is counted the same way, one UTC day at a time, from the daily rollups. Omitted when the session split is unavailable: a window over 31 days served from a cached result that predates the split, and older deployments.'\n ),\n threatLevel: z.enum(['low', 'medium', 'high']),\n recentThreats: z.array(ShopifyThreatSchema),\n pagination: PaginationInfoSchema,\n sessions: z.array(ShopifySessionSchema).optional(),\n sessionsPagination: ShopifySessionsPaginationSchema.optional(),\n});\n\nexport type ShopifyStatsResponse = z.infer<typeof ShopifyStatsResponseSchema>;\n\n/**\n * Shopify Project Settings Update Request\n */\nexport const ShopifyProjectSettingsUpdateSchema = z.object({\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n // The store's domains (primary + custom), synced by the Shopify app so\n // shoppers on a custom domain get browser posture. Replaces the stored\n // list; the app merges with what is already there before sending.\n postureOrigins: PostureOriginsSchema.optional(),\n })\n .optional(),\n});\n","/**\n * Shared SDK event contracts.\n */\n\nimport { z } from 'zod';\nimport type { RequestContext } from '../core/detection';\n\n/**\n * Context attached to SDK lifecycle events.\n */\nexport type SdkEventContext = RequestContext;\n\n/**\n * Cookie/header-backed session data emitted when an AI agent session continues.\n */\nexport const SdkSessionDataSchema = z.object({\n id: z.string(),\n agent: z.string(),\n confidence: z.number(),\n detectedAt: z.number(),\n expires: z.number(),\n});\nexport type SdkSessionData = z.infer<typeof SdkSessionDataSchema>;\n\nexport type SdkMetricValue = string | number | boolean | null | undefined;\nexport type SdkMetricTags = Record<string, SdkMetricValue>;\n","/**\n * Real-time event types\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\n\n/**\n * Real-time event types\n */\nexport const RealtimeEventTypeSchema = z.enum([\n 'detection',\n 'blocked',\n 'allowed',\n 'error',\n 'pattern_update',\n 'config_change',\n 'stats_update',\n]);\nexport type RealtimeEventType = z.infer<typeof RealtimeEventTypeSchema>;\n\n/**\n * Base real-time event\n */\nexport const RealtimeEventSchema = z.object({\n type: RealtimeEventTypeSchema,\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.any(),\n});\nexport type RealtimeEvent = z.infer<typeof RealtimeEventSchema>;\n\n/**\n * Detection event\n */\nexport const DetectionEventSchema = z.object({\n type: z.literal('detection'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n result: DetectionResultSchema,\n request: z.object({\n userAgent: z.string(),\n ipAddress: z.string().optional(),\n url: z.string().optional(),\n }),\n }),\n});\nexport type DetectionEvent = z.infer<typeof DetectionEventSchema>;\n\n/**\n * Block event\n */\nexport const BlockEventSchema = z.object({\n type: z.literal('blocked'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n reason: z.string(),\n agentType: z.string(),\n confidence: z.number(),\n ipAddress: z.string().optional(),\n url: z.string().optional(),\n }),\n});\nexport type BlockEvent = z.infer<typeof BlockEventSchema>;\n\n/**\n * Stats update event\n */\nexport const StatsUpdateEventSchema = z.object({\n type: z.literal('stats_update'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n period: z.enum(['minute', 'hour', 'day']),\n totalRequests: z.number(),\n agentsDetected: z.number(),\n averageConfidence: z.number(),\n }),\n});\nexport type StatsUpdateEvent = z.infer<typeof StatsUpdateEventSchema>;\n\n/**\n * Event emitter interface\n */\nexport interface EventEmitter {\n emit(event: RealtimeEvent): void;\n on(type: RealtimeEventType, handler: (event: RealtimeEvent) => void): void;\n off(type: RealtimeEventType, handler: (event: RealtimeEvent) => void): void;\n}\n","/**\n * Managed Agent Deployment + Compute Process Contracts (checkpoint-owned subset)\n *\n * Schemas for the managed hosting tier (agents on Fly.io) and the\n * `@kya-os/compute` ⇄ Checkpoint heartbeat/config/control protocol.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/agent-deployment` +\n * `@kya-os/contracts/compute` as part of the E6 / C-series decommission\n * (#2914 / #2917). Only the symbols re-exported by\n * `apps/web/lib/types/molti-deploy-contracts.ts` (plus their transitive deps —\n * `DidStringSchema`, the compute command sub-schemas) are ported.\n *\n * @module @kya-os/checkpoint-shared/deploy\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Cross-repo endpoint contract\n// ============================================================================\n\n/**\n * The KYA-OS activity-events ingest path (SPEC-EVENTS v0.1 batch endpoint).\n *\n * This is a CROSS-REPO CONTRACT. The Tier 2 worker runtime\n * (`@kya-os/mcp-i-cloudflare`) POSTs `tool.invoked` (and the other SPEC-EVENTS\n * types) to `${AGENTSHIELD_API_URL}${KYA_OS_EVENTS_PATH}`, authenticated by the\n * project API key. Checkpoint serves the batch ingest at this exact path\n * (`apps/web/app${KYA_OS_EVENTS_PATH}/route.ts`) and fans events out into the\n * `detections` table behind `/activity`.\n *\n * Managed deploy deliberately injects NO `KYA_OS_EVENTS_*` secret and relies on\n * this derivation instead, so the two sides agree only by matching this literal.\n * Changing it on either side silently drops all managed activity — it is pinned\n * by a contract test. Keep this value and the worker's derivation in sync.\n */\nexport const KYA_OS_EVENTS_PATH = '/api/v1/kya-os/events';\n\n// ============================================================================\n// Shared Schemas\n// ============================================================================\n\n/**\n * Validated DID string schema.\n * Reusable across all contract files that reference agent DIDs.\n *\n * Format: `did:<method>:<method-specific-id>`\n * - method: 1+ lowercase alphanumeric chars\n * - method-specific-id: 1+ non-whitespace chars\n *\n * Examples: `did:key:z6Mk...`, `did:web:example.com`\n */\nexport const DidStringSchema = z\n .string()\n .min(8, 'DID must be at least 8 characters')\n .regex(/^did:[a-z0-9]+:\\S+$/, 'DID must match format did:<method>:<method-specific-id>');\n\n/**\n * Fly.io deployment regions.\n * Enumerated to prevent arbitrary strings from being accepted.\n * @see https://fly.io/docs/reference/regions/\n */\nexport const FlyRegionSchema = z.enum([\n 'ams', // Amsterdam, Netherlands\n 'arn', // Stockholm, Sweden\n 'atl', // Atlanta, Georgia (US)\n 'bog', // Bogotá, Colombia\n 'bos', // Boston, Massachusetts (US)\n 'cdg', // Paris, France\n 'den', // Denver, Colorado (US)\n 'dfw', // Dallas, Texas (US)\n 'ewr', // Secaucus, NJ (US)\n 'eze', // Ezeiza, Argentina\n 'fra', // Frankfurt, Germany\n 'gdl', // Guadalajara, Mexico\n 'gig', // Rio de Janeiro, Brazil\n 'gru', // São Paulo, Brazil\n 'hkg', // Hong Kong\n 'iad', // Ashburn, Virginia (US)\n 'jnb', // Johannesburg, South Africa\n 'lax', // Los Angeles, California (US)\n 'lhr', // London, United Kingdom\n 'mad', // Madrid, Spain\n 'mia', // Miami, Florida (US)\n 'nrt', // Tokyo, Japan\n 'ord', // Chicago, Illinois (US)\n 'otp', // Bucharest, Romania\n 'phx', // Phoenix, Arizona (US)\n 'qro', // Querétaro, Mexico\n 'scl', // Santiago, Chile\n 'sea', // Seattle, Washington (US)\n 'sin', // Singapore\n 'sjc', // San Jose, California (US)\n 'syd', // Sydney, Australia\n 'waw', // Warsaw, Poland\n 'yul', // Montreal, Canada\n 'yyz', // Toronto, Canada\n]);\n\nexport type FlyRegion = z.infer<typeof FlyRegionSchema>;\n\n/**\n * Hosting mode discriminator — differentiates between deploy backends:\n * - `byok`: self-managed deploy in the customer's own Cloudflare account\n * (customer runs the deploy themselves).\n * - `managed`: platform-managed deploy in our Cloudflare account via Workers\n * for Platforms (dispatch namespace).\n * - `managed-byoa`: platform-managed deploy that lands in the customer's own\n * (\"bring your own account\") Cloudflare account via the standard Workers API,\n * after the org connects Cloudflare over OAuth/token (KYA-906-C).\n */\nexport const HostingModeSchema = z.enum(['byok', 'managed', 'managed-byoa']);\n\nexport type HostingMode = z.infer<typeof HostingModeSchema>;\n\n// ============================================================================\n// Protocol audit deployment contract\n// ============================================================================\n\nexport const AuditAssuranceProfileSchema = z.enum(['AAP-0', 'AAP-1', 'AAP-2', 'AAP-3', 'AAP-4']);\nexport const AuditDeliveryModeSchema = z.enum(['best-effort', 'buffered', 'required']);\n\n/**\n * Serializable request contract shared by the wizard and every deploy lane.\n * `requestedProfile` is intent, never an assurance claim. Only readiness\n * evaluation against observed runtime capabilities yields `effectiveProfile`.\n */\nexport const AuditDeploymentConfigSchema = z\n .object({\n enabled: z.boolean(),\n requestedProfile: AuditAssuranceProfileSchema,\n delivery: AuditDeliveryModeSchema,\n evidenceMode: z.enum(['none', 'encrypted-separate', 'encrypted-inline']),\n retentionClass: z.string().min(1).max(128),\n retentionDays: z.number().int().min(0).max(3650),\n residency: z.enum(['inherit-project', 'us', 'eu', 'global']),\n keyCustody: z.enum(['none', 'checkpoint-managed', 'customer-managed-kms']),\n recorderTopology: z.enum(['none', 'self-hosted', 'managed', 'verified-mirror']),\n })\n .strict()\n .superRefine((value, context) => {\n if (!value.enabled && value.requestedProfile !== 'AAP-0') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['requestedProfile'],\n message: 'Disabled audit configuration must request AAP-0',\n });\n }\n if (value.enabled && value.requestedProfile === 'AAP-0') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['requestedProfile'],\n message: 'Enabled audit configuration must request AAP-1 or higher',\n });\n }\n if (Number(value.requestedProfile.slice(-1)) >= 2 && value.delivery === 'best-effort') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['delivery'],\n message: 'AAP-2 or higher cannot use best-effort delivery',\n });\n }\n if (!value.enabled && (value.keyCustody !== 'none' || value.recorderTopology !== 'none')) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Disabled audit configuration cannot claim key custody or recorder topology',\n });\n }\n });\n\nexport type AuditDeploymentConfig = z.infer<typeof AuditDeploymentConfigSchema>;\nexport type AuditAssuranceProfile = z.infer<typeof AuditAssuranceProfileSchema>;\n\n/** Applied only when a user starts a new platform-managed deployment. */\nexport const NEW_MANAGED_AUDIT_DEPLOYMENT_DEFAULT: Readonly<AuditDeploymentConfig> = Object.freeze({\n enabled: true,\n requestedProfile: 'AAP-2',\n delivery: 'buffered',\n evidenceMode: 'encrypted-separate',\n retentionClass: 'integrity-ledger',\n retentionDays: 365,\n residency: 'inherit-project',\n keyCustody: 'checkpoint-managed',\n recorderTopology: 'managed',\n});\n\n/**\n * Missing audit config in an already persisted manifest is always AAP-0.\n * This prevents a dashboard or redeploy from silently upgrading old workers.\n */\nexport const ABSENT_AUDIT_DEPLOYMENT_CONFIG: Readonly<AuditDeploymentConfig> = Object.freeze({\n enabled: false,\n requestedProfile: 'AAP-0',\n delivery: 'best-effort',\n evidenceMode: 'none',\n retentionClass: 'none',\n retentionDays: 0,\n residency: 'inherit-project',\n keyCustody: 'none',\n recorderTopology: 'none',\n});\n\nexport const AuditRuntimeCapabilitiesSchema = z\n .object({\n recorderTopology: z.enum(['none', 'self-hosted', 'managed', 'verified-mirror']),\n delivery: AuditDeliveryModeSchema,\n journalDurability: z.enum(['none', 'ephemeral', 'durable']),\n atomicAppend: z.boolean(),\n sourceHighWater: z.boolean(),\n merkleCheckpoints: z.boolean(),\n independentObservation: z.boolean(),\n supportingAnchors: z.array(z.enum(['worm', 'rfc3161', 'scitt'])),\n evidenceRetention: z.enum(['none', 'inline', 'separate']),\n })\n .strict();\n\nexport type AuditRuntimeCapabilities = z.infer<typeof AuditRuntimeCapabilitiesSchema>;\n\nexport const AuditRuntimeCanaryResultSchema = z\n .object({\n passed: z.boolean(),\n observedAt: z.number().int().nonnegative(),\n capabilities: AuditRuntimeCapabilitiesSchema,\n checks: z\n .array(\n z\n .object({\n id: z.string().min(1).max(128),\n passed: z.boolean(),\n })\n .strict()\n )\n .min(1),\n bundleHash: z.string().min(1).max(256).optional(),\n })\n .strict()\n .superRefine((value, context) => {\n if (value.passed !== value.checks.every((check) => check.passed)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['passed'],\n message: 'Canary result must equal the aggregate of its mechanical checks',\n });\n }\n });\n\nexport type AuditRuntimeCanaryResult = z.infer<typeof AuditRuntimeCanaryResultSchema>;\n\nexport function requiredAuditRuntimeCanaryChecks(capabilities: AuditRuntimeCapabilities): string[] {\n const checks = [\n 'recorder_round_trip',\n 'verified_receipt',\n 'idempotent_retry',\n 'event_identity_conflict',\n 'source_state',\n ];\n if (capabilities.delivery === 'buffered') checks.push('buffered_outbox');\n if (capabilities.evidenceRetention !== 'none') checks.push('evidence_write_verified');\n return checks;\n}\n\nexport const AuditDeploymentReadinessSchema = z\n .object({\n requestedProfile: AuditAssuranceProfileSchema,\n effectiveProfile: AuditAssuranceProfileSchema,\n status: z.enum(['disabled', 'ready', 'degraded']),\n capabilities: AuditRuntimeCapabilitiesSchema.nullable(),\n canary: AuditRuntimeCanaryResultSchema.nullable(),\n reasonCodes: z.array(z.string().min(1).max(128)),\n })\n .strict();\n\nexport type AuditDeploymentReadiness = z.infer<typeof AuditDeploymentReadinessSchema>;\n\nconst PROFILE_BY_LEVEL = ['AAP-0', 'AAP-1', 'AAP-2', 'AAP-3', 'AAP-4'] as const;\n\nexport function resolveAuditDeploymentReadiness(\n config: AuditDeploymentConfig | undefined,\n capabilities: AuditRuntimeCapabilities | undefined,\n canary?: AuditRuntimeCanaryResult\n): AuditDeploymentReadiness {\n const requested = AuditDeploymentConfigSchema.parse(config ?? ABSENT_AUDIT_DEPLOYMENT_CONFIG);\n const observedCanary = canary ? AuditRuntimeCanaryResultSchema.parse(canary) : null;\n if (!requested.enabled) {\n return {\n requestedProfile: 'AAP-0',\n effectiveProfile: 'AAP-0',\n status: 'disabled',\n capabilities: capabilities ?? null,\n canary: observedCanary,\n reasonCodes: ['audit_not_configured'],\n };\n }\n const observedCapabilities = capabilities ?? observedCanary?.capabilities;\n if (!observedCapabilities) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: null,\n canary: observedCanary,\n reasonCodes: ['runtime_capabilities_unavailable'],\n };\n }\n const observed = AuditRuntimeCapabilitiesSchema.parse(observedCapabilities);\n if (!observedCanary) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: null,\n reasonCodes: ['runtime_canary_required'],\n };\n }\n if (\n !observedCanary.passed ||\n JSON.stringify(observedCanary.capabilities) !== JSON.stringify(observed)\n ) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: [\n observedCanary.passed ? 'runtime_canary_capability_mismatch' : 'runtime_canary_failed',\n ],\n };\n }\n const passedChecks = new Set(\n observedCanary.checks.filter((check) => check.passed).map((check) => check.id)\n );\n if (requiredAuditRuntimeCanaryChecks(observed).some((check) => !passedChecks.has(check))) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: ['runtime_canary_incomplete'],\n };\n }\n let maximum = 0;\n const reasons: string[] = [];\n if (observed.recorderTopology !== requested.recorderTopology) {\n reasons.push('recorder_topology_mismatch');\n }\n const deliveryRank = { 'best-effort': 0, buffered: 1, required: 2 } as const;\n if (deliveryRank[observed.delivery] < deliveryRank[requested.delivery]) {\n reasons.push('delivery_mode_mismatch');\n }\n const expectedEvidence =\n requested.evidenceMode === 'none'\n ? 'none'\n : requested.evidenceMode === 'encrypted-inline'\n ? 'inline'\n : 'separate';\n if (expectedEvidence !== observed.evidenceRetention) {\n reasons.push('evidence_retention_mismatch');\n }\n // These are explicit deployment-contract mismatches, not merely unavailable\n // higher-assurance services. Never activate a recorder against mechanics\n // weaker than (or topologically different from) the binding it was given.\n if (reasons.length > 0) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: reasons,\n };\n }\n if (observed.recorderTopology !== 'none' && observed.journalDurability !== 'none') maximum = 1;\n else reasons.push('recorder_or_journal_unavailable');\n if (\n maximum >= 1 &&\n observed.journalDurability === 'durable' &&\n observed.atomicAppend &&\n observed.delivery !== 'best-effort'\n ) {\n maximum = 2;\n } else if (Number(requested.requestedProfile.slice(-1)) >= 2) {\n reasons.push('durable_atomic_buffered_append_unavailable');\n }\n if (maximum >= 2 && observed.merkleCheckpoints && observed.sourceHighWater) maximum = 3;\n else if (Number(requested.requestedProfile.slice(-1)) >= 3) {\n reasons.push('checkpoint_or_source_high_water_unavailable');\n }\n if (maximum >= 3 && observed.independentObservation && observed.supportingAnchors.length > 0) {\n maximum = 4;\n } else if (Number(requested.requestedProfile.slice(-1)) >= 4) {\n reasons.push('independent_observation_or_anchor_unavailable');\n }\n const requestedLevel = Number(requested.requestedProfile.slice(-1));\n const effectiveLevel = Math.min(requestedLevel, maximum);\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: PROFILE_BY_LEVEL[effectiveLevel]!,\n status: effectiveLevel === requestedLevel && reasons.length === 0 ? 'ready' : 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: reasons,\n };\n}\n\n/**\n * Deploy step status — reuses same status enum as BYOK.\n */\nexport const ManagedDeployStepStatusSchema = z.enum([\n 'pending',\n 'in_progress',\n 'completed',\n 'failed',\n 'skipped',\n]);\n\nexport type ManagedDeployStepStatus = z.infer<typeof ManagedDeployStepStatusSchema>;\n\n// ============================================================================\n// Heartbeat Protocol (@kya-os/compute ⇄ AgentShield)\n// ============================================================================\n\n/**\n * Heartbeat request body.\n * Sent by compute process: POST /api/v1/molti/agents/{did}/heartbeat\n * Auth: X-Heartbeat-Token header\n */\nexport const HeartbeatRequestSchema = z.object({\n /** Agent DID this heartbeat is for */\n agentDid: DidStringSchema,\n /** Current compute process status */\n status: z.enum(['starting', 'running', 'error', 'stopping']),\n /** @kya-os/compute package version (from package.json) */\n computeVersion: z.string().min(1).max(50),\n /** Installed OpenClaw version (from npm ls) */\n openclawVersion: z.string().max(50).optional(),\n /** Fly machine ID (from FLY_MACHINE_ID env var) */\n machineId: z.string().max(255).optional(),\n /** Seconds since compute process started */\n uptimeSeconds: z.number().nonnegative().optional(),\n /** Current RSS memory in MB */\n memoryMb: z.number().nonnegative().optional(),\n});\n\nexport type HeartbeatRequest = z.infer<typeof HeartbeatRequestSchema>;\n\n// ============================================================================\n// Compute Commands (Discriminated Union)\n// ============================================================================\n\n/**\n * Stop command — graceful shutdown, no payload accepted.\n */\nexport const StopCommandSchema = z\n .object({\n type: z.literal('stop'),\n })\n .strict();\n\n/**\n * Restart command — restart the compute process, no payload accepted.\n */\nexport const RestartCommandSchema = z\n .object({\n type: z.literal('restart'),\n })\n .strict();\n\n/**\n * Update config command — triggers config re-fetch, no payload accepted.\n */\nexport const UpdateConfigCommandSchema = z\n .object({\n type: z.literal('update_config'),\n })\n .strict();\n\n/**\n * Update version command — requires target version in payload.\n */\nexport const UpdateVersionCommandSchema = z\n .object({\n type: z.literal('update_version'),\n payload: z.object({\n /** Target OpenClaw version to install */\n version: z.string().min(1).max(50),\n }),\n })\n .strict();\n\n/**\n * Command that Agent Shield can send to the compute process\n * via the heartbeat response.\n *\n * Discriminated union by `type` field:\n * - `stop` / `restart` / `update_config` — no payload\n * - `update_version` — requires `{ version: string }` payload\n */\nexport const ComputeCommandSchema = z.discriminatedUnion('type', [\n StopCommandSchema,\n RestartCommandSchema,\n UpdateConfigCommandSchema,\n UpdateVersionCommandSchema,\n]);\n\nexport type ComputeCommand = z.infer<typeof ComputeCommandSchema>;\n\n/**\n * Heartbeat response from Agent Shield.\n * Returned by: POST /api/v1/molti/agents/{did}/heartbeat\n */\nexport const HeartbeatResponseSchema = z.object({\n /** Always true for successful heartbeats */\n ack: z.literal(true),\n /** Pending commands for the compute process to execute */\n commands: z.array(ComputeCommandSchema).default([]),\n /** ISO timestamp of last config change (compute compares to detect updates) */\n configUpdatedAt: z.string().datetime().optional(),\n});\n\nexport type HeartbeatResponse = z.infer<typeof HeartbeatResponseSchema>;\n\n// ============================================================================\n// Config Bundle\n// ============================================================================\n\n/**\n * Config bundle returned by Agent Shield to the compute process.\n * Fetched on boot: GET /api/v1/molti/deployments/{did}/config-bundle\n * Auth: X-Heartbeat-Token header (for managed) or X-API-Key (for BYOK)\n *\n * **Private Key Delivery**: The agent's private key is NOT included in the config bundle.\n * It is delivered as the `AGENT_PRIVATE_KEY` environment variable at Fly machine creation\n * time and persists in the machine's env. This avoids transmitting the key on every\n * config fetch and keeps it out of the config-bundle response surface.\n */\nexport const ConfigBundleSchema = z.object({\n /** Schema version — 2 for managed bundles */\n version: z.number().int().positive(),\n /** Kill switch — if true, compute must exit immediately */\n killed: z.boolean(),\n /** Target OpenClaw version to install */\n openclawVersion: z.string().min(1).max(50),\n /** Agent personality/system prompt file contents (max 100KB) */\n soulFile: z.string().max(100_000).nullable(),\n /** Gateway auth token for OpenClaw */\n gatewayToken: z.string().min(1).max(500),\n /** Channel configurations */\n channels: z.object({\n telegram: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n })\n .optional(),\n discord: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n })\n .optional(),\n slack: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n appToken: z.string().optional(),\n })\n .optional(),\n whatsapp: z\n .object({\n enabled: z.boolean(),\n })\n .strict()\n .optional(),\n }),\n /** AI provider configuration — key is decrypted, sent over TLS */\n aiProvider: z.object({\n type: z.enum(['anthropic', 'openai']),\n apiKey: z.string().min(1).max(500),\n /**\n * Optional base URL override. When set, OpenClaw routes all provider\n * traffic through this URL instead of the provider's default endpoint.\n * Used by managed deployments where AgentShield issues a per-deployment\n * gateway token and proxies to the upstream provider with budget tracking.\n */\n baseUrl: z.string().url().optional(),\n }),\n /**\n * Optional OpenClaw heartbeat interval (`agents.defaults.heartbeat.every`).\n * Drives how often OpenClaw wakes the agent for HEARTBEAT.md processing —\n * the primary token-cost lever. Examples: \"30m\" (active), \"6h\" (idle),\n * \"off\" (dormant — heartbeat disabled entirely). When absent, the patcher\n * preserves whatever value already lives in openclaw.json (OpenClaw's\n * built-in default of \"30m\").\n */\n heartbeatEvery: z.string().min(1).max(20).optional(),\n /**\n * Optional override for `agents.defaults.model.primary` (e.g.\n * \"anthropic/claude-haiku-4-5\" for idle agents). When absent, the patcher\n * derives the model from `aiProvider.type` as before. Format must be\n * \"<provider>/<model-id>\".\n */\n modelOverride: z.string().min(1).max(100).optional(),\n /** ISO timestamp of last config modification */\n updatedAt: z.string().datetime(),\n});\n\nexport type ConfigBundle = z.infer<typeof ConfigBundleSchema>;\n\n// ============================================================================\n// Control Server (WebSocket :18790)\n// ============================================================================\n\n/**\n * Status frame pushed from compute control server to dashboard.\n * Sent on connect + every 5 seconds.\n */\nexport const ControlStatusSchema = z.object({\n /** Whether the agent runtime is healthy */\n healthy: z.boolean(),\n /** Seconds since compute process started */\n uptimeSeconds: z.number().nonnegative(),\n /** Installed OpenClaw version */\n openclawVersion: z.string().min(1).max(50),\n /** @kya-os/compute version */\n computeVersion: z.string().min(1).max(50),\n /** Number of active WS connections to control server */\n activeConnections: z.number().int().nonnegative(),\n /** Current RSS memory in MB */\n memoryMb: z.number().nonnegative(),\n /** CPU usage percentage (0-100) */\n cpuPercent: z.number().nonnegative().max(100),\n});\n\nexport type ControlStatus = z.infer<typeof ControlStatusSchema>;\n","/**\n * Deploy Progress Event Types\n *\n * Types for real-time deployment progress tracking via SSE.\n * Used by the one-click deploy feature to stream step-by-step updates.\n *\n * @module events/deploy-progress\n */\n\nimport { z } from 'zod';\nimport { AuditDeploymentConfigSchema } from '../deploy';\n\n/**\n * All possible deployment steps in order\n */\nexport const DEPLOY_STEPS = [\n { id: 'github_verify', label: 'Verifying your GitHub connection', order: 1 },\n { id: 'repo_check', label: 'Checking your repository name', order: 2 },\n { id: 'project_create', label: 'Creating your project', order: 3 },\n { id: 'api_key', label: 'Generating your API key', order: 4 },\n { id: 'scaffold', label: 'Generating your server files', order: 5 },\n { id: 'kta_register', label: 'Setting up your agent identity', order: 6 },\n { id: 'repo_create', label: 'Creating your GitHub repository', order: 7 },\n { id: 'commit_files', label: 'Committing your server code', order: 8 },\n { id: 'add_secrets', label: 'Securing your repository secrets', order: 9 },\n { id: 'cloudflare_deploy', label: 'Deploying your server to Cloudflare', order: 10 },\n { id: 'complete', label: 'Deployment complete!', order: 11 },\n] as const;\n\n/**\n * Step ID enum\n */\nexport const DeployStepIdSchema = z.enum([\n 'github_verify',\n 'repo_check',\n 'project_create',\n 'api_key',\n 'scaffold',\n 'kta_register',\n 'repo_create',\n 'commit_files',\n 'add_secrets',\n 'cloudflare_deploy',\n 'complete',\n]);\nexport type DeployStepId = z.infer<typeof DeployStepIdSchema>;\n\n/**\n * Step status\n */\nexport const DeployStepStatusSchema = z.enum([\n 'pending',\n 'running',\n 'complete',\n 'error',\n 'skipped',\n]);\nexport type DeployStepStatus = z.infer<typeof DeployStepStatusSchema>;\n\n/**\n * Individual step state\n */\nexport const DeployStepStateSchema = z.object({\n id: DeployStepIdSchema,\n status: DeployStepStatusSchema,\n message: z.string().optional(),\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n});\nexport type DeployStepState = z.infer<typeof DeployStepStateSchema>;\n\n/**\n * Full deployment progress event\n */\nexport const DeployProgressEventSchema = z.object({\n type: z.literal('deploy_progress'),\n deploymentId: z.string(),\n timestamp: z.number(),\n currentStep: DeployStepIdSchema,\n steps: z.array(DeployStepStateSchema),\n result: z\n .object({\n repoUrl: z.string(),\n repoFullName: z.string(),\n deployUrl: z.string(),\n projectId: z.string(),\n /** Human-readable project ID for URL construction */\n friendlyId: z.string().nullable().optional(),\n /** kyaosDeployments row id — drives the live-step \"Go to server\" deployment-detail link. */\n deploymentId: z.string().optional(),\n /** Full API key - only shown once at completion! */\n apiKey: z.string(),\n /** Preview (sk_...xxx) for display after initial view */\n apiKeyPreview: z.string(),\n cloudflareUrl: z.string().optional(),\n cloudflareDeployed: z.boolean().optional(),\n /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */\n cloudflareError: z.string().optional(),\n /** Agent DID (decentralized identifier) - did:web for reputation enabled, did:key for disabled */\n agentDid: z.string().optional(),\n /** Whether agent was registered with Know That AI for reputation tracking */\n ktaRegistered: z.boolean().optional(),\n /** Claim URL for KTA registration (only when using cli-register with did:web) */\n ktaClaimUrl: z.string().optional(),\n })\n .optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n step: DeployStepIdSchema.optional(),\n })\n .optional(),\n});\nexport type DeployProgressEvent = z.infer<typeof DeployProgressEventSchema>;\n\n/**\n * Deployment metadata stored in Redis\n */\nexport const DeploymentMetadataSchema = z.object({\n id: z.string(),\n userId: z.string(),\n organizationId: z.string(),\n repoName: z.string(),\n template: z.string(),\n platform: z.string(),\n /** Hosting mode: 'managed' (Checkpoint hosted) or 'byok' (Bring Your Own Cloudflare) */\n hostingMode: z.enum(['managed', 'byok']).optional().default('byok'),\n /** 'repo-only' scaffolds + pushes the repo but never triggers the Cloudflare worker upload, regardless of connection state (defaults to 'cloudflare') */\n deployTarget: z.enum(['cloudflare', 'repo-only']).optional(),\n status: z.enum(['pending', 'running', 'complete', 'error']),\n /** Enable reputation tracking via Know That AI (defaults to true) */\n enableReputation: z.boolean().optional(),\n /** Requested audit posture. Old stored metadata may omit this and resolves to AAP-0 at use. */\n audit: AuditDeploymentConfigSchema.optional(),\n /** Existing project ID to deploy to (if provided, skips project creation) - Unified Project Schema v1.3 */\n existingProjectId: z.string().uuid().optional(),\n /** Pre-generated source supplied by another intake flow (for example OpenAPI). */\n generatedFiles: z\n .array(\n z.object({\n path: z.string(),\n content: z.string(),\n isBase64: z.boolean().optional(),\n })\n )\n .optional(),\n /** Identity paired with pre-generated source. */\n generatedIdentity: z\n .object({\n did: z.string(),\n // Optional so historical metadata already sitting in Redis without a\n // kid still parses. The producing route always populates it now (see\n // KYA-956 phase 3); the deploy pipeline treats a missing kid as a\n // scaffold-time failure rather than injecting a broken identity.\n kid: z.string().optional(),\n publicKey: z.string(),\n privateKey: z.string(),\n })\n .optional(),\n /** Validated source-specific secrets forwarded to GitHub/Cloudflare. */\n additionalSecrets: z.record(z.string(), z.string()).optional(),\n /** Semantic source type used for descriptions and registry metadata. */\n agentType: z.string().optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n /** Result data (populated on completion) */\n result: z\n .object({\n /** GitHub repo URL (BYOK deploy only) */\n repoUrl: z.string().optional(),\n /** GitHub repo full name e.g. \"user/repo\" (BYOK deploy only) */\n repoFullName: z.string().optional(),\n /** GitHub Actions deploy URL (BYOK deploy only) */\n deployUrl: z.string().optional(),\n projectId: z.string(),\n /** Human-readable project ID for URL construction */\n friendlyId: z.string().nullable().optional(),\n /** kyaosDeployments row id — powers the live-step deployment-detail link (all sources). */\n deploymentId: z.string().optional(),\n /** API key preview e.g. \"sk_...xxx\" (BYOK deploy only) */\n apiKeyPreview: z.string().optional(),\n cloudflareUrl: z.string().optional(),\n cloudflareDeployed: z.boolean().optional(),\n /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */\n cloudflareError: z.string().optional(),\n agentDid: z.string().optional(),\n ktaRegistered: z.boolean().optional(),\n ktaClaimUrl: z.string().optional(),\n })\n .optional(),\n});\nexport type DeploymentMetadata = z.infer<typeof DeploymentMetadataSchema>;\n\n/**\n * Helper to get step info by ID\n */\nexport function getStepInfo(stepId: DeployStepId) {\n return DEPLOY_STEPS.find((s) => s.id === stepId);\n}\n\n/**\n * Helper to get step order\n */\nexport function getStepOrder(stepId: DeployStepId): number {\n const step = DEPLOY_STEPS.find((s) => s.id === stepId);\n return step?.order ?? 0;\n}\n\n/**\n * Calculate completion percentage\n */\nexport function calculateDeployProgress(\n currentStep: DeployStepId,\n status: DeployStepStatus\n): number {\n const totalSteps = DEPLOY_STEPS.length - 1; // Exclude 'complete' step\n const currentOrder = getStepOrder(currentStep);\n\n if (currentStep === 'complete') return 100;\n\n // If running, we're partially through the step\n if (status === 'running') {\n return Math.round(((currentOrder - 0.5) / totalSteps) * 100);\n }\n\n // If complete, we've finished this step\n if (status === 'complete') {\n return Math.round((currentOrder / totalSteps) * 100);\n }\n\n return Math.round(((currentOrder - 1) / totalSteps) * 100);\n}\n\n/**\n * Build initial steps state (all pending)\n */\nexport function buildInitialStepsState(): DeployStepState[] {\n return DEPLOY_STEPS.map((step) => ({\n id: step.id as DeployStepId,\n status: 'pending' as const,\n }));\n}\n\n/**\n * Update steps state for a given step\n */\nexport function updateStepsState(\n currentSteps: DeployStepState[],\n stepId: DeployStepId,\n status: DeployStepStatus,\n options?: { message?: string; error?: { code: string; message: string } }\n): DeployStepState[] {\n const now = Date.now();\n\n return currentSteps.map((step) => {\n if (step.id === stepId) {\n return {\n ...step,\n status,\n message: options?.message,\n error: options?.error,\n startedAt: status === 'running' ? now : step.startedAt,\n completedAt: status === 'complete' || status === 'error' ? now : step.completedAt,\n };\n }\n return step;\n });\n}\n","/**\n * Analytics Types\n *\n * Types for analytics data, exports, and monitoring\n */\n\nimport { z } from 'zod';\n\n/**\n * Analytics export parameters\n */\nexport const AnalyticsExportParamsSchema = z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('json'),\n dateRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n filters: z\n .object({\n projectId: z.string().uuid().optional(),\n pixelId: z.string().uuid().optional(),\n isAgent: z.boolean().optional(),\n agentTypes: z.array(z.string()).optional(),\n minConfidence: z.number().min(0).max(100).optional(),\n })\n .optional(),\n fields: z.array(z.string()).optional(), // Specific fields to export\n includeMetadata: z.boolean().default(false),\n compression: z.boolean().default(false),\n});\nexport type AnalyticsExportParams = z.infer<typeof AnalyticsExportParamsSchema>;\n\n/**\n * Legacy analytics rollup shapes stored in the web app's analytics_rollups JSONB\n * column. Keep these shared so background services and admin routes agree on\n * the persisted structure while the legacy rollup service is migrated away.\n */\nexport type AnalyticsRollupPeriod = 'daily' | 'weekly' | 'monthly';\n\nexport interface LegacyAnalyticsSessionMetrics {\n total: number;\n unique: number;\n events: number;\n avgDuration: number;\n}\n\nexport interface LegacyAnalyticsAiDetectionMetrics {\n total: number;\n aiAgents: number;\n bots: number;\n humans: number;\n aiRate: number;\n botRate: number;\n humanRate: number;\n}\n\nexport interface LegacyAnalyticsEventMetrics {\n total: number;\n uniquePaths: number;\n avgPerSession: number;\n}\n\nexport interface LegacyAnalyticsRollupMetrics {\n sessions: LegacyAnalyticsSessionMetrics;\n aiDetection: LegacyAnalyticsAiDetectionMetrics;\n events: LegacyAnalyticsEventMetrics;\n}\n\nexport interface LegacyAnalyticsCalculatedMetrics {\n sessionMetrics: LegacyAnalyticsSessionMetrics;\n aiMetrics: LegacyAnalyticsAiDetectionMetrics;\n eventMetrics: LegacyAnalyticsEventMetrics;\n}\n\nexport interface LegacyAnalyticsIndustryAverages {\n avgSessions: number;\n avgEvents: number;\n avgAiRate: number;\n avgDuration: number;\n}\n\nexport interface LegacyAnalyticsIndustryTrendDay {\n date: string;\n totalSessions: number;\n aiSessions: number;\n aiRate: number;\n organizations: number;\n}\n\nexport interface LegacyAnalyticsAgentBreakdownItem {\n name: string | null;\n category: string | null;\n count: number;\n}\n\nexport interface LegacyAnalyticsAgentCategoryBreakdown {\n category: string;\n total: number;\n agents: Array<{\n name: string | null;\n count: number;\n }>;\n}\n\nexport interface LegacyAnalyticsAgentTypeBreakdown {\n byAgent: LegacyAnalyticsAgentBreakdownItem[];\n byCategory: LegacyAnalyticsAgentCategoryBreakdown[];\n topAgents: Array<{\n name: string | null;\n count: number;\n }>;\n}\n\nexport interface LegacyAnalyticsPeriodMetrics {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n}\n\nexport interface LegacyAnalyticsGrowthMetrics {\n weekOverWeek: {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n };\n monthOverMonth: {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n };\n current: {\n weekSessions: number;\n weekAiRate: number;\n monthSessions: number;\n monthAiRate: number;\n };\n}\n\nexport type AnalyticsCacheParamValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | { readonly [key: string]: AnalyticsCacheParamValue }\n | readonly AnalyticsCacheParamValue[];\nexport type AnalyticsCacheParams = Record<string, AnalyticsCacheParamValue>;\nexport type AnalyticsCacheType = 'realtime' | 'frequent' | 'historical';\n\nexport interface AnalyticsCacheStats {\n [cacheName: string]: {\n size: number;\n calculatedSize: number;\n };\n}\n\nexport interface AnalyticsPreloadQueryFunction<T = unknown> {\n type: string;\n params: AnalyticsCacheParams;\n fn: () => Promise<T>;\n}\n\nexport type TrafficPatternGranularity = 'hour' | 'day' | 'week';\n\nexport interface TrafficTimeSeriesPoint {\n timestamp: string;\n totalSessions: number;\n totalEvents: number;\n uniqueIPs: number | null;\n avgEventsPerSession: number;\n aiAgentSessions: number;\n humanSessions: number;\n}\n\nexport interface TrafficTopPage {\n path: string;\n visits: number;\n uniqueSessions: number;\n uniqueVisitors: number;\n avgTimeOnPage: number;\n fromAI: number;\n fromHuman: number;\n}\n\nexport interface TrafficNavigationPath {\n fromPage: string;\n toPage: string;\n count: number;\n}\n\nexport interface OrganizationTrafficPatterns {\n timeSeries: TrafficTimeSeriesPoint[];\n topPages: TrafficTopPage[];\n navigationPaths: TrafficNavigationPath[];\n}\n\nexport interface OrganizationTrafficPatternsSummary {\n organizationId: string;\n organizationName: string;\n patterns: OrganizationTrafficPatterns;\n}\n\nexport interface SystemWideTrafficPatterns extends OrganizationTrafficPatterns {\n byOrganization: OrganizationTrafficPatternsSummary[];\n}\n\nexport type TrafficPatterns = OrganizationTrafficPatterns | SystemWideTrafficPatterns;\n\nexport interface SessionFrequencyDay {\n date: string;\n newSessions: number;\n returningSessions: number;\n totalSessions: number;\n returnRate: number;\n uniqueVisitors: number;\n}\n\nexport interface SessionFrequencyPatterns {\n daily: SessionFrequencyDay[];\n summary: {\n totalNewSessions: number;\n totalReturningSessions: number;\n averageReturnRate: number;\n };\n}\n\nexport interface PeakTrafficHour {\n hour: number;\n sessions: number;\n events: number;\n aiPercentage: number;\n}\n\nexport interface PeakTrafficDay {\n day: string;\n sessions: number;\n events: number;\n aiPercentage: number;\n}\n\nexport interface TrafficSpike {\n timestamp: string;\n sessions: number;\n magnitude: number;\n composition: {\n ai: number;\n human: number;\n };\n}\n\nexport interface PeakTrafficPatterns {\n peakHours: PeakTrafficHour[];\n peakDays: PeakTrafficDay[];\n trafficSpikes: TrafficSpike[];\n statistics?: {\n meanSessions: number;\n stdDeviation: number;\n spikeThreshold: number;\n };\n}\n\nexport interface AgentNavigationBehavior {\n agentTypes: Array<{\n type: string;\n sessions: number;\n eventsPerSession: number;\n uniquePathsVisited: number;\n avgTimeOnPage: number;\n }>;\n topPagesByAgent: Array<{\n path: string;\n agentType: string;\n visits: number;\n }>;\n}\n","/**\n * Detection Metadata Types\n *\n * Type definitions for detection metadata stored in the database\n */\n\nimport { z } from 'zod';\n\n/**\n * Detection metadata stored in database JSONB field\n * This represents the metadata field in the detections table\n */\nexport const DatabaseDetectionMetadataSchema = z.object({\n // Agent information\n detectedAgent: z\n .object({\n type: z.string(),\n name: z.string(),\n })\n .optional(),\n\n // Verification details\n verificationMethod: z.enum(['signature', 'pattern', 'mcp_i', 'none']).optional(),\n riskLevel: z.enum(['low', 'medium', 'high', 'unknown']).optional(),\n\n // Detection details\n reasons: z.array(z.string()).optional(),\n\n // Request context\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Browser fingerprint data\n clientDetection: z\n .object({\n headless: z.boolean().optional(),\n webrtc: z.boolean().optional(),\n canvas: z.string().optional(),\n plugins: z.number().optional(),\n automation: z.boolean().optional(),\n chrome: z.boolean().optional(),\n languages: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Additional metadata\n agent: z.string().optional(),\n processingTime: z.number().optional(),\n cached: z.boolean().optional(),\n});\n\nexport type DatabaseDetectionMetadata = z.infer<typeof DatabaseDetectionMetadataSchema>;\n","/**\n * Authentication Session\n */\nexport interface AuthSession {\n user: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n emailVerified?: Date | null;\n defaultOrganizationId?: string;\n currentOrganizationId?: string;\n organizationRole?: 'owner' | 'admin' | 'member';\n };\n expires: string;\n}\n\n/**\n * Authentication Error Types\n */\nexport enum AuthErrorType {\n INVALID_CREDENTIALS = 'INVALID_CREDENTIALS',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n EMAIL_NOT_VERIFIED = 'EMAIL_NOT_VERIFIED',\n ACCOUNT_DISABLED = 'ACCOUNT_DISABLED',\n ACCOUNT_LOCKED = 'ACCOUNT_LOCKED',\n PASSWORD_EXPIRED = 'PASSWORD_EXPIRED',\n INVALID_TOKEN = 'INVALID_TOKEN',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n EMAIL_ALREADY_EXISTS = 'EMAIL_ALREADY_EXISTS',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n PASSWORDS_DO_NOT_MATCH = 'PASSWORDS_DO_NOT_MATCH',\n OAUTH_ACCOUNT_NOT_LINKED = 'OAUTH_ACCOUNT_NOT_LINKED',\n OAUTH_ERROR = 'OAUTH_ERROR',\n RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',\n}\n\n/**\n * Authentication Response\n */\nexport interface AuthResponse {\n success: boolean;\n message?: string;\n user?: AuthSession['user'];\n token?: string;\n redirectUrl?: string;\n error?: {\n type: AuthErrorType;\n message: string;\n };\n}\n\n/**\n * Sign Up Response\n */\nexport interface SignUpResponse extends AuthResponse {\n requiresEmailVerification?: boolean;\n verificationEmailSent?: boolean;\n}\n","/**\n * Fingerprint Types and Schemas\n *\n * Comprehensive type definitions for the AI fingerprinting system\n * Supporting multiple integration types and detection methods\n */\n\nimport { z } from 'zod';\n\n// Re-export legacy types for backward compatibility\nexport * from './fingerprint-legacy';\n\n// Integration types that determine what data is available\nexport const IntegrationTypeSchema = z.enum([\n 'pixel', // Client-side pixel (minimal data)\n 'beacon', // Enhanced beacon (more client data)\n 'noscript', // Server-side only (headers + IP)\n 'middleware', // Full request context\n 'express', // Node.js server integration\n 'edge', // Edge runtime data\n 'wasm', // Full WASM detection\n]);\n\nexport type IntegrationType = z.infer<typeof IntegrationTypeSchema>;\n\nexport interface CanvasFingerprintData {\n supported: boolean;\n hash?: string;\n dataUrl?: string;\n renderTime?: number;\n error?: string;\n}\n\nexport interface WebGLFingerprintData {\n supported: boolean;\n vendor?: string;\n renderer?: string;\n extensions?: string[];\n error?: string;\n}\n\nexport interface AudioFingerprintData {\n supported: boolean;\n sampleRate?: number;\n channelCount?: number;\n fingerprint?: string;\n error?: string;\n}\n\nexport interface BrowserFingerprintScreenData {\n resolution: string;\n colorDepth: number;\n pixelRatio: number;\n orientation: string;\n}\n\nexport interface BrowserFingerprintFeatures {\n webWorker: boolean;\n serviceWorker: boolean;\n webAssembly: boolean;\n webRTC: boolean;\n notifications: boolean;\n bluetooth: boolean;\n battery: boolean;\n}\n\nexport interface BrowserFingerprintTouchSupport {\n maxTouchPoints: number;\n touchEvent: boolean;\n touchStart: boolean;\n}\n\nexport interface BrowserFingerprintConnectionData {\n effectiveType?: string;\n rtt?: number;\n downlink?: number;\n saveData?: boolean;\n}\n\nexport interface BrowserClientSideFingerprintData {\n canvas?: CanvasFingerprintData;\n webgl?: WebGLFingerprintData;\n audio?: AudioFingerprintData;\n screen?: BrowserFingerprintScreenData;\n features?: BrowserFingerprintFeatures;\n touchSupport?: BrowserFingerprintTouchSupport;\n connection?: BrowserFingerprintConnectionData;\n timezone?: string;\n languages?: string[];\n plugins?: string[];\n cookiesEnabled?: boolean;\n localStorage?: boolean;\n sessionStorage?: boolean;\n doNotTrack?: string | null;\n hardwareConcurrency?: number;\n deviceMemory?: number;\n fonts?: string[];\n}\n\n// Comprehensive collected data from fingerprinting\nexport const CollectedDataSchema = z.object({\n id: z.string().uuid(),\n testId: z.string().optional(), // Query parameter for lookup\n integrationType: IntegrationTypeSchema,\n timestamp: z.date(),\n\n // What each integration can see\n availableData: z.object({\n // ALWAYS available (all integrations)\n core: z.object({\n userAgent: z.string(),\n ip: z.string(),\n url: z.string(),\n method: z.string(),\n timestamp: z.date(),\n }),\n\n // HEADERS (noscript, middleware, express, edge)\n headers: z.record(z.string(), z.string()).optional(),\n\n // CLIENT-SIDE (pixel, beacon only)\n clientSide: z\n .object({\n canvas: z\n .object({\n supported: z.boolean(),\n hash: z.string().optional(),\n dataUrl: z.string().optional(),\n renderTime: z.number().optional(),\n })\n .optional(),\n webgl: z\n .object({\n supported: z.boolean(),\n vendor: z.string().optional(),\n renderer: z.string().optional(),\n extensions: z.array(z.string()).optional(),\n })\n .optional(),\n audio: z\n .object({\n supported: z.boolean(),\n sampleRate: z.number().optional(),\n channelCount: z.number().optional(),\n fingerprint: z.string().optional(),\n })\n .optional(),\n screen: z\n .object({\n resolution: z.string(),\n colorDepth: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().optional(),\n })\n .optional(),\n timezone: z.string().optional(),\n languages: z.array(z.string()).optional(),\n fonts: z.array(z.string()).optional(),\n plugins: z.array(z.string()).optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n cookiesEnabled: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n hardwareConcurrency: z.number().optional(),\n deviceMemory: z.number().optional(),\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .optional(),\n // Touch and input capabilities\n touchSupport: z\n .object({\n maxTouchPoints: z.number(),\n touchEvent: z.boolean(),\n touchStart: z.boolean(),\n })\n .optional(),\n // Browser features\n features: z\n .object({\n webWorker: z.boolean(),\n serviceWorker: z.boolean(),\n webAssembly: z.boolean(),\n webRTC: z.boolean(),\n notifications: z.boolean(),\n bluetooth: z.boolean(),\n battery: z.boolean(),\n })\n .optional(),\n })\n .optional(),\n\n // SERVER-SIDE ENHANCED (middleware, express)\n serverEnhanced: z\n .object({\n tls: z\n .object({\n version: z.string(),\n cipher: z.string(),\n ja3: z.string().optional(), // TLS fingerprint\n ja3s: z.string().optional(), // Server TLS fingerprint\n })\n .optional(),\n httpVersion: z.string(),\n protocol: z.string(),\n requestSize: z.number().optional(),\n cookies: z.record(z.string(), z.string()).optional(),\n sessionData: z.any().optional(),\n // Visitor geo comes from Vercel/Cloudflare edge headers, which give a\n // country and usually a region and city, and never a coordinate pair\n // or timezone. Only `country` is guaranteed when the object is\n // present; the rest are omitted when the edge did not supply them.\n // They were all required until the producer stopped returning a\n // hardcoded San Francisco for every request.\n geoLocation: z\n .object({\n country: z.string(),\n region: z.string().optional(),\n city: z.string().optional(),\n latitude: z.number().optional(),\n longitude: z.number().optional(),\n timezone: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n\n // BEHAVIORAL (pixel, beacon with time)\n behavioral: z\n .object({\n timeOnPage: z.number(),\n mouseMovements: z.number(),\n mouseClicks: z.number(),\n keystrokes: z.number(),\n scrollEvents: z.number(),\n scrollDepth: z.number(),\n touchEvents: z.number().optional(),\n visibility: z\n .array(\n z.object({\n hidden: z.boolean(),\n timestamp: z.number(),\n })\n )\n .optional(),\n performance: z\n .object({\n loadTime: z.number(),\n domReady: z.number(),\n firstPaint: z.number().optional(),\n firstContentfulPaint: z.number().optional(),\n })\n .optional(),\n interactions: z\n .array(\n z.object({\n type: z.string(),\n timestamp: z.number(),\n target: z.string().optional(),\n })\n )\n .optional(),\n })\n .optional(),\n }),\n\n // Detection results from different engines\n detectionResults: z\n .object({\n // partialRecord, not record: Zod 4 makes an enum-keyed record exhaustive, and\n // these are per-integration results where any subset of integrations may be present.\n wouldDetectAs: z\n .partialRecord(\n IntegrationTypeSchema,\n z.object({\n isAgent: z.boolean(),\n confidence: z.number(),\n agentType: z.string().optional(),\n reasons: z.array(z.string()),\n processingTime: z.number().optional(),\n })\n )\n .optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z\n .object({\n collectionDuration: z.number().optional(),\n errors: z.array(z.string()).optional(),\n warnings: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\nexport type CollectedData = z.infer<typeof CollectedDataSchema>;\n\n// Fingerprint record stored in database\nexport const FingerprintRecordSchema = z.object({\n id: z.string().uuid(),\n testId: z.string().optional(),\n timestamp: z.date(),\n\n // Core fingerprint data\n integrationType: IntegrationTypeSchema,\n userAgent: z.string(),\n ipAddress: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Fingerprint hashes\n canvasHash: z.string().optional(),\n webglHash: z.string().optional(),\n audioHash: z.string().optional(),\n\n // Full collected data\n collectedData: CollectedDataSchema,\n\n // Classification results\n classification: z\n .object({\n aiType: z.string().optional(),\n vendor: z.string().optional(),\n confidence: z.number(),\n matchedRules: z.array(z.string()).optional(),\n patterns: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Association\n profileId: z.string().uuid().optional(),\n notes: z.string().optional(),\n tags: z.array(z.string()).optional(),\n\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nexport type FingerprintRecord = z.infer<typeof FingerprintRecordSchema>;\n\n// Export request/response types for API\nexport const CollectFingerprintRequestSchema = z.object({\n testId: z.string().optional(),\n integrationType: IntegrationTypeSchema,\n data: z.any(), // Will be validated based on integration type\n});\n\nexport const CollectFingerprintResponseSchema = z.object({\n success: z.boolean(),\n sessionId: z.string(),\n fingerprintId: z.string(),\n message: z.string().optional(),\n});\n\nexport const TestDetectionRequestSchema = z.object({\n // `fingerprints.id` is a uuid column, so a value that is not one cannot\n // address a row; refusing it here makes it a 400 rather than a Postgres\n // error surfacing as a 500.\n fingerprintId: z.string().uuid(),\n // Omit the member to test every integration type. An EMPTY array would run\n // nothing and write a 0/0 mean (NaN) into an integer column, so it is a 400.\n integrationTypes: z\n .array(IntegrationTypeSchema)\n .min(1, 'integrationTypes must list at least one integration type, or be omitted entirely')\n .optional(),\n});\n\n// Helper function to generate test ID\nexport function generateTestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `test-${timestamp}-${random}`;\n}\n\n// Helper to check if integration supports client-side data\nexport function supportsClientSide(integration: IntegrationType): boolean {\n return ['pixel', 'beacon'].includes(integration);\n}\n\n// Helper to check if integration supports headers\nexport function supportsHeaders(integration: IntegrationType): boolean {\n return ['noscript', 'middleware', 'express', 'edge', 'wasm'].includes(integration);\n}\n\n// Helper to check if integration supports enhanced server data\nexport function supportsServerEnhanced(integration: IntegrationType): boolean {\n return ['middleware', 'express'].includes(integration);\n}\n","// GENERATED FILE — do not hand-edit.\n//\n// Source of truth: rust/crates/kya-os-engine/data/vendor-keys/*.json —\n// the RFC 9421 vendor key directories the engine actually pins and\n// verifies at the edge. Regenerate with:\n//\n// pnpm tsx scripts/sync-signing-vendors.ts\n//\n// apps/web/tests/unit/lib/signing-vendors-parity.test.ts fails the build\n// when this list drifts from the directory, so adding or removing a\n// vendor key file forces this manifest (and therefore every derived\n// `signatureSupport` flag) to follow. Existing agent_types rows in\n// deployed databases still need a data migration when the list changes —\n// the sync script prints a reminder.\n\n/** Vendors with a pinned, edge-verified RFC 9421 signing-key directory. */\nexport const PINNED_SIGNING_VENDORS: readonly string[] = ['openai'];\n","/**\n * Agent Classification Types\n *\n * Centralized type definitions for agent classification system\n */\n\nimport { z } from 'zod';\n\nimport { PINNED_SIGNING_VENDORS } from './signing-vendors.generated';\n\n/**\n * True iff any of the agent's signature-vendor aliases has a pinned,\n * edge-verified RFC 9421 key directory in the engine\n * (rust/crates/kya-os-engine/data/vendor-keys, via the generated\n * manifest). This is the ONLY way `signatureSupport` may become true —\n * hand-seeding it let `claude` claim verified signatures for months\n * while Anthropic published no keys and the engine pinned none.\n */\nexport function hasPinnedSigningVendor(aliases: readonly string[] | undefined): boolean {\n return aliases?.some((alias) => PINNED_SIGNING_VENDORS.includes(alias)) ?? false;\n}\n\n/**\n * Agent categories for classification\n */\nexport const AgentCategorySchema = z.enum([\n 'ai_assistant', // ChatGPT, Claude, Gemini, Perplexity\n 'search_engine', // Googlebot, Bingbot, DuckDuckBot\n 'social_media', // Facebook, Twitter, LinkedIn crawlers\n 'monitoring', // Uptime monitors, health checkers\n 'scraper', // Web scrapers, data extractors\n 'automation', // Puppeteer, Playwright, Selenium\n 'security', // Security scanners, vulnerability testers\n 'analytics', // Analytics bots, SEO tools\n 'unknown', // Unclassified agents\n]);\nexport type AgentCategory = z.infer<typeof AgentCategorySchema>;\n\n/**\n * Operator-facing vocabulary for `agent_category`.\n *\n * ## Why this lives here\n *\n * Beside `AgentCategorySchema`, not in a UI package, because the same\n * words have to hold across the dashboard, the gateway, exports, the\n * public API, and the .NET plane. A display map that lives in one app is\n * a map the other surfaces will silently disagree with.\n *\n * `Record<AgentCategory, …>` is load-bearing: TypeScript refuses to\n * compile a missing key, so widening the enum without designing its copy\n * cannot ship. The previous web-only map had a `titleCase` fallback that\n * silently invented a label for any new value, which is exactly the drift\n * this replaces.\n *\n * ## What `unknown` means, and why it is labelled \"Other\"\n *\n * `agent_category` answers *which named family is this*. It is a\n * DIFFERENT axis from `detection_class`, which answers *is this human, an\n * agent, or a bot*. A miss on `detection_class` is a detection gap and\n * has its own value (`incomplete_data`). A miss here is an ATTRIBUTION\n * gap: the request was detected and classified, we just have not matched\n * it to a named vendor.\n *\n * `getAgentCategory` (apps/web/lib/utils/agent-category.ts) writes\n * `'unknown'` for exactly two cases: traffic matched only a generic\n * bot/crawler/spider/scraper signature, and the final default. Both are\n * \"real traffic, no vendor attributed\" — the ordinary long tail of the\n * internet, not a failure. Labelling it \"Unrecognized\" or \"Uncategorized\"\n * describes the engine as having failed at something it did not attempt,\n * and reads as weakness on a chart where it is routinely the largest\n * slice.\n *\n * \"Other\" is the sibling term to the eight named families and carries no\n * such claim. Where the bucket deserves a second look (it is where an\n * agent nobody has written a signature for shows up first) that belongs\n * in prose and drill-in, not compressed into a bar label.\n */\nexport interface AgentCategoryMeta {\n /** Title-case form for chart axes, table cells, chips, filters. */\n label: string;\n /**\n * Lower-case form for mid-sentence prose (\"led by search engine\n * traffic\"). Acronyms keep their casing — lowercasing \"AI\" is a worse\n * error than an odd-looking capital.\n */\n inline: string;\n /**\n * One-line operator-facing definition. Single source for tooltips and\n * for the knowledge-base article, so the docs cannot drift from the\n * code the way they did before.\n */\n definition: string;\n}\n\nexport const AGENT_CATEGORY_META: Record<AgentCategory, AgentCategoryMeta> = {\n ai_assistant: {\n label: 'AI assistant',\n inline: 'AI assistant',\n definition: 'An AI assistant acting for a person in real time (ChatGPT, Claude, Perplexity).',\n },\n search_engine: {\n label: 'Search engine',\n inline: 'search engine',\n definition: 'An indexing crawler that makes your pages findable (Googlebot, Bingbot).',\n },\n social_media: {\n label: 'Social media',\n inline: 'social media',\n definition: 'A crawler building link previews for a social platform.',\n },\n monitoring: {\n label: 'Monitoring',\n inline: 'monitoring',\n definition: 'An uptime or health checker polling your endpoints.',\n },\n scraper: {\n label: 'Scraper',\n inline: 'scraper',\n definition:\n 'Bulk content extraction, including AI training crawlers such as GPTBot and ClaudeBot.',\n },\n automation: {\n label: 'Automation',\n inline: 'automation',\n definition: 'A headless browser or scripted driver (Puppeteer, Playwright, Selenium).',\n },\n security: {\n label: 'Security',\n inline: 'security',\n definition: 'A vulnerability scanner or security research crawler.',\n },\n analytics: {\n label: 'Analytics',\n inline: 'analytics',\n definition: 'An SEO or analytics tool sampling your pages.',\n },\n unknown: {\n label: 'Other',\n inline: 'other',\n definition:\n 'Detected and classified traffic that has not been attributed to a named vendor, ' +\n 'usually because it matched only a generic bot signature. Not a detection failure, ' +\n 'and worth sampling periodically: a new agent lands here before anyone writes a ' +\n 'signature for it.',\n },\n};\n\n/**\n * Non-canonical values reach the formatters only from pre-CHECK-constraint\n * rows in old snapshots and jsonb (`ai_crawler` is the known example, see\n * `docs/taxonomy/canonical-entities.md`).\n *\n * They get underscores expanded and nothing else. Expanding keeps them\n * readable where they land mid-sentence; NOT title-casing them is the\n * point, because inventing a polished label is exactly how an undesigned\n * value slips into the UI looking official. A stray `ai crawler` among\n * `AI assistant` and `Search engine` is legible and visibly not one of\n * the family.\n */\nfunction formatUnrecognizedValue(value: string): string {\n return value.replace(/_/g, ' ');\n}\n\n/**\n * Sentinels a previous revision briefly wrote into the category axis.\n *\n * #4875 replaced the `COALESCE`'s inline `'unknown'` with `__uncategorized__`\n * / `__unidentified__`. That shipped, so the strings are now sitting in\n * persisted chat history as jsonb, and history has no backfill. Dropping the\n * mapping when the sentinels were removed would leave rehydrated turns\n * rendering the raw `uncategorized` and treating the bucket as a real family\n * rather than the catch-all.\n *\n * Reads stay tolerant even though writes never produce these again.\n */\nconst LEGACY_CATEGORY_SENTINELS = new Set(['__uncategorized__', '__unidentified__']);\n\n/**\n * Render an `agent_category` value for display.\n *\n * `null` / `undefined` fold into the catch-all: `getAgentCategory` returns\n * NULL for humans and no-signal rows, which should never reach a category\n * chart, but folding beats crashing or rendering blank if one does.\n */\nexport function formatAgentCategory(value: string | null | undefined): string {\n if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.label;\n const meta = AGENT_CATEGORY_META[value as AgentCategory];\n return meta ? meta.label : formatUnrecognizedValue(value);\n}\n\n/** Lower-case form of {@link formatAgentCategory} for use inside a sentence. */\nexport function formatAgentCategoryInline(value: string | null | undefined): string {\n if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.inline;\n const meta = AGENT_CATEGORY_META[value as AgentCategory];\n return meta ? meta.inline : formatUnrecognizedValue(value);\n}\n\n/**\n * Display name for an agent whose `agent_type` was never resolved.\n *\n * Deliberately NOT one of the category words. This appears on the\n * top-agents table, a different surface from the category bars, so it\n * never sits beside them and does not need to be told apart from them by\n * spelling. Callers should prefer the agent's CATEGORY when they have one\n * (\"Scraper\" says more than \"Unnamed agent\") and fall back to this only\n * when both name and category are missing.\n */\nexport const UNNAMED_AGENT_LABEL = 'Unnamed agent';\n\n/**\n * Agent type definition (full entity)\n * Named as AgentTypeDefinition to avoid conflict with existing AgentType enum\n */\nexport const AgentTypeDefinitionSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n description: z.string().optional(),\n isLegitimate: z.boolean(),\n confidenceThreshold: z.number().min(0).max(100),\n detectionPatterns: z.array(z.string()),\n signatureSupport: z.boolean(),\n // Vendor tokens (own name + company aliases, e.g. ['chatgpt','openai']) matched\n // against a host-VERIFIED RFC 9421 Signature-Agent value to attribute a signed\n // agent to this type at ingest. Optional/additive; empty or absent ⇒ this type is\n // not resolvable by signature (only signatureSupport vendors carry aliases).\n signatureVendorAliases: z.array(z.string()).optional(),\n documentationUrl: z.string().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type AgentTypeDefinition = z.infer<typeof AgentTypeDefinitionSchema>;\n\n/**\n * Agent classification result\n */\nexport const AgentClassificationResultSchema = z.object({\n agentTypeId: z.string().uuid(),\n agentType: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n confidence: z.number().min(0).max(100),\n isLegitimate: z.boolean(),\n signatureVerified: z.boolean().optional(),\n matchedPatterns: z.array(z.string()),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AgentClassificationResult = z.infer<typeof AgentClassificationResultSchema>;\n\n/**\n * Agent classification request\n */\nexport const AgentClassificationRequestSchema = z.object({\n userAgent: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n ipAddress: z.string().optional(),\n sessionId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AgentClassificationRequest = z.infer<typeof AgentClassificationRequestSchema>;\n\n/**\n * Agent statistics for analytics\n */\nexport const AgentStatisticsSchema = z.object({\n agentTypeId: z.string().uuid(),\n agentType: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n detectionCount: z.number(),\n sessionCount: z.number(),\n averageConfidence: z.number(),\n lastSeen: z.date(),\n isLegitimate: z.boolean(),\n percentageOfTotal: z.number().optional(),\n});\nexport type AgentStatistics = z.infer<typeof AgentStatisticsSchema>;\n\n/**\n * Helper functions\n */\n\n/**\n * Check if an agent category is considered legitimate\n */\nexport function isLegitimateCategory(category: AgentCategory): boolean {\n const legitimateCategories: AgentCategory[] = [\n 'ai_assistant',\n 'search_engine',\n 'social_media',\n 'monitoring',\n 'analytics',\n ];\n return legitimateCategories.includes(category);\n}\n\n/**\n * Get display color for agent category (for UI)\n */\nexport function getCategoryColor(category: AgentCategory): string {\n const colors: Record<AgentCategory, string> = {\n ai_assistant: '#10b981', // green\n search_engine: '#3b82f6', // blue\n social_media: '#8b5cf6', // purple\n monitoring: '#06b6d4', // cyan\n scraper: '#ef4444', // red\n automation: '#f97316', // orange\n security: '#dc2626', // dark red\n analytics: '#6366f1', // indigo\n unknown: '#6b7280', // gray\n };\n return colors[category] || '#6b7280';\n}\n\n/**\n * Get category badge variant for UI\n */\nexport function getCategoryBadgeVariant(\n category: AgentCategory\n): 'default' | 'success' | 'warning' | 'destructive' {\n switch (category) {\n case 'ai_assistant':\n case 'search_engine':\n return 'success';\n case 'social_media':\n case 'monitoring':\n case 'analytics':\n return 'default';\n case 'scraper':\n case 'automation':\n case 'security':\n return 'destructive';\n case 'unknown':\n default:\n return 'warning';\n }\n}\n\n/**\n * Default agent types (for initialization)\n */\nexport const DEFAULT_AGENT_TYPES: Partial<AgentTypeDefinition>[] = [\n {\n name: 'chatgpt',\n displayName: 'ChatGPT',\n category: 'ai_assistant',\n description: 'OpenAI ChatGPT Browser',\n isLegitimate: true,\n confidenceThreshold: 95,\n signatureSupport: hasPinnedSigningVendor(['chatgpt', 'openai']),\n signatureVendorAliases: ['chatgpt', 'openai'],\n detectionPatterns: ['GPTBot', 'ChatGPT-User', 'x-gpt-signature'],\n },\n {\n name: 'claude',\n displayName: 'Claude',\n category: 'ai_assistant',\n description: 'Anthropic Claude Assistant',\n isLegitimate: true,\n confidenceThreshold: 95,\n // Derived FALSE today: Anthropic publishes no web-bot-auth key\n // directory (verified 2026-08-26) and the engine pins no anthropic\n // key. Flips automatically once anthropic.json lands in vendor-keys\n // and the manifest is regenerated.\n signatureSupport: hasPinnedSigningVendor(['claude', 'anthropic']),\n signatureVendorAliases: ['claude', 'anthropic'],\n detectionPatterns: ['Claude-Web', 'Claude-User', 'anthropic-ai', 'x-claude-signature'],\n },\n {\n name: 'perplexity',\n displayName: 'Perplexity',\n category: 'ai_assistant',\n description: 'Perplexity AI Assistant',\n isLegitimate: true,\n confidenceThreshold: 90,\n signatureSupport: false,\n detectionPatterns: ['PerplexityBot', 'Perplexica'],\n },\n {\n name: 'googlebot',\n displayName: 'Googlebot',\n category: 'search_engine',\n description: 'Google Search Crawler',\n isLegitimate: true,\n confidenceThreshold: 95,\n signatureSupport: false,\n detectionPatterns: ['Googlebot', 'Googlebot-Image', 'Googlebot-Video'],\n },\n {\n name: 'puppeteer',\n displayName: 'Puppeteer',\n category: 'automation',\n description: 'Headless Chrome Automation',\n isLegitimate: false,\n confidenceThreshold: 75,\n signatureSupport: false,\n detectionPatterns: ['HeadlessChrome', 'Puppeteer'],\n },\n];\n","/**\n * Admin API Types\n *\n * Types for administrative endpoints and operations\n */\n\nimport { z } from 'zod';\n\n/**\n * Project Reset Request Schema\n */\nexport const projectResetRequestSchema = z.object({\n confirmation: z.literal('RESET_PROJECT_DATA'),\n dryRun: z.boolean().optional().default(false),\n preserveMembers: z.boolean().optional().default(true),\n includeFingerprints: z.boolean().optional().default(true),\n});\n\nexport type ProjectResetRequest = z.infer<typeof projectResetRequestSchema>;\n\n/**\n * Project Reset Statistics\n */\nexport interface ProjectResetStats {\n detectionsDeleted: number;\n pixelsDeleted: number; // @deprecated Always 0 - pixels are never deleted during reset\n apiKeysDeleted: number;\n activityLogsDeleted: number;\n permissionCacheCleared: number;\n fingerprintLogsDeleted: number;\n onboardingProgressDeleted: number;\n membersRemoved: number;\n}\n\n/**\n * Project Reset Response\n */\nexport interface ProjectResetResponse {\n success: boolean;\n dryRun: boolean;\n project: {\n id: string;\n name: string;\n domain: string | null;\n friendlyId: string | null;\n };\n stats: ProjectResetStats;\n message: string;\n totalRecordsAffected: number;\n timestamp: string;\n}\n\n/**\n * Project Reset Preview Response\n */\nexport interface ProjectResetPreviewResponse {\n project: {\n id: string;\n name: string;\n domain: string | null;\n friendlyId: string | null;\n createdAt: Date;\n };\n preview: ProjectResetStats;\n totalRecords: number;\n message: string;\n requiredConfirmation: string;\n options: {\n preserveMembers: {\n description: string;\n default: boolean;\n };\n includeFingerprints: {\n description: string;\n default: boolean;\n };\n dryRun: {\n description: string;\n default: boolean;\n };\n };\n}\n\n/**\n * Admin Route Context\n * Used for admin-specific routes that require superadmin access\n */\nexport interface AdminRouteContext {\n adminId: string;\n adminEmail: string;\n isAdmin: boolean;\n}\n\n/**\n * Admin Project Route Context\n * Used for admin project management routes\n */\nexport interface AdminProjectRouteContext extends AdminRouteContext {\n params: {\n projectId: string;\n };\n}\n\n/**\n * User-Organization Assignment Types\n */\n\n/**\n * User Organization Assignment\n */\nexport interface UserOrganizationAssignment {\n userId: string;\n organizationId: string;\n role: 'owner' | 'admin' | 'member';\n joinedAt: Date;\n organizationName: string;\n organizationSlug: string;\n}\n\n/**\n * Assignment Change Request Schema\n */\nexport const assignmentChangeRequestSchema = z.object({\n userId: z.string().uuid('Invalid user ID'),\n organizationId: z.string().uuid('Invalid organization ID'),\n role: z.enum(['owner', 'admin', 'member'], {\n error: 'Role must be owner, admin, or member',\n }),\n action: z.enum(['assign', 'remove', 'update_role']),\n});\n\nexport type AssignmentChangeRequest = z.infer<typeof assignmentChangeRequestSchema>;\n\n/**\n * Batch Assignment Request Schema\n */\nexport const batchAssignmentRequestSchema = z.object({\n userIds: z.array(z.string().uuid()).min(1, 'At least one user ID required'),\n organizationId: z.string().uuid('Invalid organization ID'),\n role: z.enum(['owner', 'admin', 'member']),\n action: z.enum(['assign', 'remove']),\n});\n\nexport type BatchAssignmentRequest = z.infer<typeof batchAssignmentRequestSchema>;\n\n/**\n * Organization Membership Response\n */\nexport interface OrganizationMembershipResponse {\n success: boolean;\n data: UserOrganizationAssignment[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n hasNext: boolean;\n hasPrev: boolean;\n };\n error?: {\n code: string;\n message: string;\n details?: unknown;\n };\n}\n\n/**\n * Extended Audit Log Entry for User-Organization Operations\n */\nexport interface UserOrgAuditLogEntry {\n id: string;\n adminId: string;\n adminEmail: string;\n action: string;\n targetType: 'user' | 'organization' | 'system' | 'project';\n targetId?: string;\n details: {\n userId?: string;\n userEmail?: string;\n organizationId?: string;\n organizationName?: string;\n previousRole?: string;\n newRole?: string;\n role?: string;\n reason?: string;\n [key: string]: unknown;\n };\n ipAddress?: string;\n userAgent?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Audit Log Query Request Schema\n */\nexport const auditLogQuerySchema = z.object({\n page: z.coerce.number().min(1).default(1).optional(),\n limit: z.coerce.number().min(1).max(100).default(50).optional(),\n adminId: z.string().uuid().optional(),\n action: z.string().optional(),\n targetType: z.enum(['user', 'organization', 'system', 'project']).optional(),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n search: z.string().optional(),\n});\n\nexport type AuditLogQueryRequest = z.infer<typeof auditLogQuerySchema>;\n\nexport type GrowthConfigurationType = 'bouncer' | 'enterprise' | 'support' | 'integration';\n\nexport type GrowthOpportunityType = GrowthConfigurationType;\n\nexport type GrowthPriority = 'low' | 'medium' | 'high' | 'critical';\n\nexport interface GrowthBouncerThresholds {\n minAiTrafficRate: number;\n aiTrafficSpikeMultiplier: number;\n highAiTrafficThreshold: number;\n consistentHighTrafficDays: number;\n criticalAiTrafficRate: number;\n}\n\nexport interface GrowthEnterpriseThresholds {\n highVolumeThreshold: number;\n rapidGrowthRate: number;\n multiDomainCount: number;\n largeTeamSize: number;\n multiProjectCount: number;\n highPercentileThreshold: number;\n minEnterpriseIndicators: number;\n}\n\nexport interface GrowthSupportThresholds {\n inactiveDays: number;\n minSupportIndicators: number;\n criticalSupportScore: number;\n}\n\nexport interface GrowthIntegrationThresholds {\n minSessionsForBenefit: number;\n minAiRateForBenefit: number;\n}\n\nexport interface GrowthConfigurationThresholdMap {\n bouncer: GrowthBouncerThresholds;\n enterprise: GrowthEnterpriseThresholds;\n support: GrowthSupportThresholds;\n integration: GrowthIntegrationThresholds;\n}\n\nexport type GrowthConfigurationThreshold = GrowthConfigurationThresholdMap[GrowthConfigurationType];\n\nexport interface GrowthAgentConcentration {\n name: string;\n percentage: number;\n}\n\nexport interface GrowthBouncerOpportunityDetails {\n avgAiRate: number;\n latestAiRate: number;\n weekOverWeekChange: number;\n highTrafficDays: number;\n topAgents: GrowthAgentConcentration[];\n}\n\nexport interface GrowthBouncerOpportunityMetrics {\n sessionVolume: number;\n aiDetections: number;\n trend: 'increasing' | 'stable';\n}\n\nexport interface GrowthEnterpriseOpportunityDetails {\n sessionVolume: number;\n growthRate: number;\n domainCount: number;\n memberCount: number;\n projectCount: number;\n percentileRank: number | null;\n}\n\nexport interface GrowthEnterpriseOpportunityMetrics {\n weeklyVolume: number;\n monthlyGrowth: number;\n enterpriseIndicators: number;\n}\n\nexport interface GrowthSupportOpportunityDetails {\n unverifiedCount: number;\n inactiveCount: number;\n patterns: Record<string, number>;\n}\n\nexport interface GrowthSupportOpportunityMetrics {\n supportIndicators: number;\n integrationHealth: 'none' | 'partial' | 'healthy';\n}\n\nexport interface GrowthIntegrationOpportunityDetails {\n pixelCount: number;\n domainCount: number;\n wasmEnabled: boolean;\n}\n\nexport interface GrowthIntegrationOpportunityMetrics {\n sessionVolume: number;\n aiRate: number;\n}\n\ninterface BaseGrowthOpportunity<\n TType extends GrowthOpportunityType,\n TDetails extends object,\n TMetrics extends object,\n> {\n type: TType;\n score: number;\n priority: GrowthPriority;\n reason: string;\n details: TDetails;\n metrics: TMetrics;\n}\n\nexport type GrowthOpportunityDetails =\n | BaseGrowthOpportunity<\n 'bouncer',\n GrowthBouncerOpportunityDetails,\n GrowthBouncerOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'enterprise',\n GrowthEnterpriseOpportunityDetails,\n GrowthEnterpriseOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'support',\n GrowthSupportOpportunityDetails,\n GrowthSupportOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'integration',\n GrowthIntegrationOpportunityDetails,\n GrowthIntegrationOpportunityMetrics\n >;\n\nexport interface GrowthRecommendationPerformance {\n sessionGrowthRate?: number | null;\n sessionCount?: number | null;\n overallPercentile?: number | null;\n}\n\nexport interface GrowthRecommendationAnalytics {\n totalSessions?: number | null;\n averageDuration?: number | null;\n bounceRate?: number | null;\n timestamp?: string | number | Date | null;\n}\n\nexport interface GrowthRecommendationOnboarding {\n createdAt?: Date | string | null;\n hasActiveProjects: boolean;\n hasPixels: boolean;\n activePixels: number;\n teamSize: number;\n}\n\nexport interface GrowthRecommendationIntegration {\n projectCount: number;\n pixelCount: number;\n activePixels: number;\n}\n\nexport interface GrowthRecommendationContext {\n organizationId: string;\n performance?: GrowthRecommendationPerformance | null;\n analytics?: GrowthRecommendationAnalytics | null;\n onboarding?: GrowthRecommendationOnboarding;\n integration?: GrowthRecommendationIntegration;\n}\n\nexport type AdminExecutiveSummaryPeriod = '7d' | '30d' | '90d' | 'all';\n\nexport interface AdminExecutiveSummaryResponse {\n period: AdminExecutiveSummaryPeriod;\n /**\n * Counted exactly as the admin overview counts (its exclusion rules, customer\n * orgs only, deleted orgs and projects left out), so the two pages agree.\n */\n platformHealth: {\n totals: {\n /** Customer orgs: not deleted, at least one counted member, no test name. */\n orgs: number;\n /** Live projects in customer orgs. */\n projects: number;\n /** The overview's \"Signed up\", counted side. */\n users: number;\n /** Accounts the overview's exclusion rules leave out of `users`. */\n usersExcluded: number;\n /** Counted users who signed up in the period. */\n signupsInPeriod: number;\n /** Customer orgs created in the period. */\n newOrgsInPeriod: number;\n };\n /** The overview's \"Onboarded\": counted users whose org has a verified, working installation. */\n onboarded: number;\n /** The overview's \"Active users\": used the dashboard in the last 30 days, whatever the period. */\n activeUsers: {\n /** null when the dashboard activity source is unavailable. */\n last30d: number | null;\n };\n /** The overview's warnings for these numbers, shown with them. */\n warnings: string[];\n };\n enforce: {\n checkpoints: Record<string, unknown> | undefined;\n sessions: Record<string, unknown> | undefined;\n proofs: Record<string, unknown> | undefined;\n topAgents: Array<{\n agentName: string;\n proofCount: number;\n successCount: number;\n blockedCount: number;\n }>;\n };\n govern: {\n deployments: Record<string, unknown> | undefined;\n delegations: Record<string, unknown> | undefined;\n managedUsage: Record<string, unknown> | undefined;\n oneClickDeploys: {\n total: number;\n cfDeployed: number;\n newInPeriod: number;\n byTemplate: Array<{\n template: string | null;\n count: number;\n }>;\n };\n pendingApprovals: Record<string, unknown> | undefined;\n customDomains: Record<string, unknown> | undefined;\n };\n molti: {\n status: Record<string, unknown> | undefined;\n health: Record<string, unknown> | undefined;\n hostingBreakdown: Array<{\n hostingMode: string | null;\n region: string;\n aiProvider: string | null;\n count: number;\n }>;\n };\n detect: {\n trend: {\n currentPeriod: number | null;\n previousPeriod: number | null;\n changePercent: number | null;\n };\n classification: Array<{\n class: string;\n count: number;\n }>;\n pixels: Record<string, unknown> | undefined;\n };\n growthPipeline: {\n leads: {\n total: number;\n inPeriod: number;\n uncontacted: number;\n bySource: Array<{\n source: string | null;\n count: number;\n }>;\n };\n assessments: {\n total: number;\n inPeriod: number;\n withEmail: number;\n byTier: Array<{\n tier: string | null;\n count: number;\n }>;\n };\n integrations: Record<string, unknown> | undefined;\n };\n generatedAt: string;\n}\n\n/**\n * Every user, org and project count here is the admin overview's own: its\n * exclusion rules, customer orgs only, deleted orgs and projects left out.\n */\nexport interface AdminMetricsResponse {\n totals: {\n /** The overview's \"Signed up\", counted side. */\n users: number;\n /** Customer orgs. */\n organizations: number;\n /** Live projects in customer orgs. */\n projects: number;\n };\n /** Counted users by plan. */\n planDistribution: Array<{\n plan: string | null;\n count: number;\n }>;\n /** Counted users with and without a verified email. */\n verificationStats: {\n verified: number;\n unverified: number;\n };\n /**\n * The overview's installation-based \"Onboarded\": counted users whose org has\n * a verified, working installation, and the counted users who aren't.\n */\n onboardingStats: {\n onboarded: number;\n notOnboarded: number;\n };\n /** Counted users who signed up each day of the last 30 (UTC dates). */\n signupTrends: Array<{\n date: string;\n count: number;\n }>;\n /** Customer orgs by their number of counted members: up to 5, 6 to 20, over 20. */\n organizationSizes: {\n small: number;\n medium: number;\n large: number;\n };\n /** Traffic totals cover every project; the two org counts are customer orgs only. */\n detection: {\n totalDetectionsToday: number;\n totalDetections7d: number;\n totalDetections30d: number;\n aiAgentRate: number;\n /** Customer orgs whose live projects had rollup traffic in the last 30 days. */\n activeOrgsWithTraffic: number;\n /** Customer orgs with a gateway checkpoint on a live project. */\n orgsWithEnforcement: number;\n };\n enforcement: {\n totalDecisions: number;\n blocked: number;\n allowed: number;\n challenged: number;\n blockRate: number;\n allowRate: number;\n topBlockedAgents: Array<{ agentName: string; count: number }>;\n topAllowedAgents: Array<{ agentName: string; count: number }>;\n dataQuality: {\n partial: boolean;\n includedSources: string[];\n omittedSources: string[];\n message: string | null;\n };\n };\n timestamp: string;\n}\n\nexport interface AdminSessionDurationBucket {\n range: string;\n min: number;\n max: number;\n count: number;\n percentage: number;\n}\n\nexport interface AdminOrganizationSessionAnalytics {\n organizationId: string;\n organizationName: string;\n metrics: {\n totalSessions: number;\n uniqueSessions: number;\n averageDuration: number;\n medianDuration: number;\n minDuration: number;\n maxDuration: number;\n distribution: AdminSessionDurationBucket[];\n bounceRate: number;\n pagesPerSession: number;\n isSampled: boolean;\n sampleSize?: number;\n };\n comparison: {\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n incompleteDataSessions?: number;\n aiAgentPercentage: number;\n botPercentage: number;\n humanPercentage: number;\n incompleteDataPercentage?: number;\n };\n patterns: {\n peakHours: unknown[];\n mostVisitedPages: unknown[];\n navigationPatterns: unknown[];\n };\n trends: {\n sessionGrowth: number;\n durationTrend: number;\n bounceRateTrend: number;\n };\n}\n\nexport interface AdminSessionIndustryAverages {\n averageSessionDuration: number;\n averageBounceRate: number;\n averagePagesPerSession: number;\n averageSessionsPerOrg: number;\n medianSessionDuration: number;\n distribution: {\n aiAgentPercentage: number;\n botPercentage: number;\n humanPercentage: number;\n incompleteDataPercentage?: number;\n };\n}\n\nexport interface AdminSessionAnomaly {\n organizationId: string;\n organizationName: string;\n reasons: string[];\n severity: 'low' | 'medium' | 'high';\n metrics: {\n sessions: number;\n duration: number;\n bounceRate: number;\n aiPercentage: number;\n botPercentage: number;\n };\n}\n\nexport interface AdminSessionInsights {\n topPerformers: Array<{\n organizationName: string;\n reason: string;\n metrics: {\n bounceRate: number;\n pagesPerSession: number;\n };\n }>;\n needsAttention: Array<{\n organizationName: string;\n reason: string;\n recommendation: string;\n }>;\n opportunities: Array<{\n organizationName: string;\n opportunity: string;\n description: string;\n }>;\n trends: {\n growingOrganizations: Array<{\n organizationName: string;\n growth: number;\n }>;\n decliningOrganizations: Array<{\n organizationName: string;\n decline: number;\n }>;\n };\n}\n\nexport interface AdminSessionAnalyticsResponse {\n success: true;\n data: {\n organizations: AdminOrganizationSessionAnalytics[];\n industryAverages: AdminSessionIndustryAverages;\n anomalies: AdminSessionAnomaly[];\n insights: AdminSessionInsights;\n dateRange: {\n start: string;\n end: string;\n };\n metadata: {\n totalOrganizations: number;\n sortBy: 'sessions' | 'duration' | 'bounceRate' | 'growth';\n sortOrder: 'asc' | 'desc';\n };\n };\n}\n","/**\n * Wire contract for GET /api/admin/overview.\n *\n * `meta.warnings` carries every methodology caveat the response embeds\n * (attribution gaps, partial sections, stale rollups, and so on) so the\n * dashboard never hides one behind a silently-dropped field. All\n * timestamps are ISO-8601 strings; all dates are YYYY-MM-DD strings.\n */\n\nimport { z } from 'zod';\n\n/** Supported lookback windows for the admin overview. */\nexport const ADMIN_OVERVIEW_WINDOWS = ['7d', '30d', '90d'] as const;\nexport type AdminOverviewWindow = (typeof ADMIN_OVERVIEW_WINDOWS)[number];\n/** Window applied when the request omits one. */\nexport const DEFAULT_ADMIN_OVERVIEW_WINDOW: AdminOverviewWindow = '30d';\n/** Row cap applied to each list section when the request omits `listLimit`. */\nexport const ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT = 100;\n/** Hard ceiling on `listLimit`, regardless of what the request asks for. */\nexport const ADMIN_OVERVIEW_LIST_LIMIT_MAX = 500;\n\n/**\n * Split on '-' and round-trip through `Date.UTC` so a value like\n * 2026-02-30 (day overflow) or 2026-13-01 (month overflow) is rejected\n * instead of silently rolling into the next month or year.\n */\nfunction isCalendarDate(value: string): boolean {\n const [year, month, day] = value.split('-').map(Number);\n if (!year || !month || !day) return false;\n const date = new Date(Date.UTC(year, month - 1, day));\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n );\n}\n\n/** Query params for GET /api/admin/overview (parsed from URLSearchParams, so numbers are coerced). */\nexport const adminOverviewQuerySchema = z.object({\n window: z.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),\n // YYYY-MM-DD, must be a real calendar date (reject 2026-02-30, 2026-13-01, '2026-1-5', ISO datetimes)\n compareTo: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .refine(isCalendarDate, {\n message: 'compareTo must be a real calendar date in YYYY-MM-DD form',\n })\n .optional(),\n listLimit: z.coerce\n .number()\n .int()\n .min(1)\n .max(ADMIN_OVERVIEW_LIST_LIMIT_MAX)\n .default(ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT),\n});\nexport type AdminOverviewQuery = z.infer<typeof adminOverviewQuerySchema>;\n\n/** How a headline delta's `previous` value was computed. */\nexport const ADMIN_DELTA_BASES = ['created_at', 'rollup', 'none'] as const;\nexport type AdminDeltaBasis = (typeof ADMIN_DELTA_BASES)[number];\n/** A headline number with its value as of `compareTo`. previous is null when no prior value is computable (basis 'none'). */\nexport interface AdminDelta {\n current: number;\n previous: number | null;\n basis: AdminDeltaBasis;\n}\n\n/** The kinds of instrumentation an organization can have installed. */\nexport const INSTALLATION_KINDS = [\n 'agent',\n 'pixel',\n 'middleware',\n 'dns_gateway',\n 'mcp_server',\n 'beacon',\n] as const;\nexport type InstallationKind = (typeof INSTALLATION_KINDS)[number];\n/** The distinct installation records tracked, one level more specific than InstallationKind (middleware splits by runtime). */\nexport const INSTALLATION_TYPES = [\n 'pixel',\n 'middleware_node',\n 'middleware_dotnet',\n 'middleware_jvm',\n 'middleware_android',\n 'middleware_ios',\n 'middleware_no_traffic',\n 'dns_gateway',\n 'beacon',\n] as const;\nexport type InstallationType = (typeof INSTALLATION_TYPES)[number];\n/** The four buckets the admin overview classifies every traffic event into. */\nexport const TRAFFIC_TAXONOMY_BUCKETS = [\n 'human',\n 'ai_agent',\n 'ai_crawler',\n 'other_automation',\n] as const;\nexport type TrafficTaxonomyBucket = (typeof TRAFFIC_TAXONOMY_BUCKETS)[number];\n/** Order is precedence: a user matching several rules is attributed to the first. */\nexport const EXCLUSION_BUCKETS = [\n 'vouched',\n 'internal_team',\n 'test_pattern',\n 'shopify_review',\n 'cohort',\n] as const;\nexport type ExclusionBucket = (typeof EXCLUSION_BUCKETS)[number];\n/** The independently-fetchable sections of the admin overview response. */\nexport const ADMIN_OVERVIEW_SECTIONS = [\n 'ladder',\n 'installations',\n 'traffic',\n 'lists',\n 'hiAi',\n 'accounts',\n] as const;\nexport type AdminOverviewSection = (typeof ADMIN_OVERVIEW_SECTIONS)[number];\n/** Cache states a section can report in `meta.cache.status`. */\nexport const ADMIN_OVERVIEW_CACHE_STATUSES = ['hit', 'stale', 'miss', 'bypass'] as const;\nexport type AdminOverviewCacheStatus = (typeof ADMIN_OVERVIEW_CACHE_STATUSES)[number];\n\n/** events in the bucket, share = events / totalEvents (0 when totalEvents is 0), totalEvents = denominator for the whole scope. */\nexport interface TaxonomyTotals {\n events: number;\n share: number;\n totalEvents: number;\n}\nexport type TaxonomyBreakdown = Record<TrafficTaxonomyBucket, TaxonomyTotals>;\n\n/** The customer-acquisition funnel headline row, each stage a delta against `compareTo`. */\nexport interface AdminOverviewLadder {\n emailsCollected: AdminDelta;\n users: AdminDelta;\n signedInProxy: AdminDelta;\n onboarded: AdminDelta;\n activated: AdminDelta;\n}\n\n/** One per InstallationKind, customer-scoped. activeInWindow = installs with activity inside the window. orgCount = distinct customer organizations behind those installs (an org with 3 middleware pixels still counts once). */\nexport interface InstallationCard {\n kind: InstallationKind;\n total: AdminDelta;\n activeInWindow: number;\n orgCount: number;\n}\n/** Count of installations of one InstallationType, split into customer-owned vs excluded. */\nexport interface InstallationTypeCount {\n type: InstallationType;\n customer: number;\n excluded: number;\n total: number;\n}\n/** The installations section: per-kind summary cards plus the finer-grained type breakdown. */\nexport interface AdminOverviewInstallations {\n cards: InstallationCard[];\n byType: InstallationTypeCount[];\n}\n\n/**\n * Keys for the by-service traffic table. By-service traffic is attributed\n * per project installation profile: a project with exactly one\n * InstallationKind lands under that kind, a project with more than one kind\n * lands in 'mixed' (counting it under a single kind would double count), and\n * a project with none lands in 'none'.\n */\nexport const SERVICE_TRAFFIC_KEYS = [...INSTALLATION_KINDS, 'mixed', 'none'] as const;\nexport type ServiceTrafficKey = (typeof SERVICE_TRAFFIC_KEYS)[number];\n\n/** attribution is always 'project-profile' until the rollups carry a source dimension; the server adds a standing warning. */\nexport interface ServiceTrafficRow {\n service: ServiceTrafficKey;\n events: number;\n share: number;\n projects: number;\n attribution: 'project-profile';\n}\n/** One project's traffic for the window, broken into the four taxonomy buckets. */\nexport interface SiteTrafficRow {\n projectId: string;\n projectName: string;\n domain: string | null;\n organizationId: string;\n organizationName: string;\n events: number;\n share: number;\n buckets: Record<TrafficTaxonomyBucket, number>;\n}\n/** The traffic section: taxonomy breakdowns, per-service rollups, and the per-site list. */\nexport interface AdminOverviewTraffic {\n taxonomy: { window: TaxonomyBreakdown; allTime: TaxonomyBreakdown };\n byService: ServiceTrafficRow[];\n /** Capped by listLimit; bySiteTotal is the uncapped count. */\n bySite: SiteTrafficRow[];\n bySiteTotal: number;\n /** Earliest rollup date (YYYY-MM-DD); allTime means \"since this date\". null when no rollups exist. */\n coverageFrom: string | null;\n}\n\n/** An onboarded user who is a member of an org with at least one installation. */\nexport interface ActivatedUserRow {\n userId: string;\n email: string;\n name: string | null;\n organizationId: string;\n organizationName: string;\n installationKinds: InstallationKind[];\n onboardingCompletedAt: string | null;\n createdAt: string;\n}\n/**\n * Every new user, NOT gated on onboarding/installation status at all —\n * unlike `ActivatedUserRow`'s two lists (both scoped to a qualifying org's\n * membership), this is the raw `users` population itself: a user with zero\n * org membership and zero installs still appears here, with `organizationId`/\n * `organizationName` null and `installationKinds` empty. Exists to close the\n * gap where a legitimate signup with no installs was invisible in every\n * other per-person list.\n */\nexport interface NewSignupRow {\n userId: string;\n email: string;\n name: string | null;\n /** The user's earliest-joined organization, if any; null for a user with no org membership at all. */\n organizationId: string | null;\n organizationName: string | null;\n installationKinds: InstallationKind[];\n createdAt: string;\n}\n/**\n * The three person-level funnel stages the admin Customer Journey view\n * classifies every non-excluded user into. Deliberately three, not four:\n * the schema has no \"installed\" step distinct from \"onboarded\" (see\n * `orgActiveInstallationsCte`'s doc comment: activated is a strictly\n * stronger condition over the SAME verified-installation evidence\n * `orgInstallationsCte` checks, not a separate install event), so a row is\n * exactly one of:\n * - `signed_up`: a non-excluded user with no qualifying (onboarded) org.\n * - `onboarded`: member of a qualifying org (see `ActivatedUserRow`'s own\n * doc comment for what \"qualifying\" means) that is NOT also activated.\n * - `activated`: member of a qualifying org that also satisfies\n * `orgActiveInstallationsCte` (verified AND active in the window).\n * The admin Customer Journey page labels the `onboarded` stage \"Installed\"\n * in its own UI copy (plainer for a fast scan) while this type keeps the\n * same word Overview's ladder already uses for the identical population,\n * so the two never drift into two different predicates under two different\n * names.\n */\nexport type CustomerJourneyStage = 'signed_up' | 'onboarded' | 'activated';\n\n/**\n * One row per non-excluded user, for the admin Customer Journey view: the\n * per-person drill-down behind the aggregate ladder/funnel-breakdown numbers\n * already on `/admin`: same population, same exclusion rules, same\n * onboarded/activated predicates, just one row per person instead of one\n * count per stage. `organizationId`/`organizationName` are the org this\n * row's stage is attributed to (the qualifying org for `onboarded`/\n * `activated`, or the user's earliest-joined org of any kind for\n * `signed_up`, mirroring `NewSignupRow`'s `first_membership` for a user\n * with no qualifying org); both are null for a user with no org membership\n * at all.\n */\nexport interface CustomerJourneyRow {\n userId: string;\n email: string;\n name: string | null;\n organizationId: string | null;\n organizationName: string | null;\n /** Distinct members of organizationId; null when organizationId is null. */\n teamSize: number | null;\n /**\n * Installations configured for the attributed org, from the same source\n * the ladder's own rows use. Not gated on the verified/counted-kind\n * predicate that decides `stage`: an org can appear here with an\n * unverified pixel, or with the `agent` kind, even though neither counts\n * toward `onboarded`/`activated`. [] when the attributed org has none.\n */\n installationKinds: InstallationKind[];\n stage: CustomerJourneyStage;\n /**\n * Days since this row entered its current stage. null when not\n * computable: always for `activated` (no per-user activation timestamp\n * exists today, so this is never fabricated from a proxy), and for\n * `onboarded` when the qualifying org's install came from a teammate\n * (this user's own `onboardingCompletedAt` was never set, and the\n * installation tables only carry \"last seen/detected\" timestamps, not\n * \"first verified\" ones, so no honest fallback exists either).\n */\n daysInStage: number | null;\n /** True once daysInStage reaches or exceeds the stage's threshold (inclusive at the boundary). Always false when daysInStage is null. */\n stalled: boolean;\n createdAt: string; // ISO\n}\n\n/** One `pixels` row joined to its project and org; `type` is derived from the middleware marker and engine probe. */\nexport interface PixelInstallationRow {\n pixelId: string;\n pixelName: string;\n type: InstallationType;\n projectId: string;\n projectName: string;\n domain: string | null;\n organizationId: string;\n organizationName: string;\n scope: 'customer' | 'excluded';\n detectionCount: number;\n lastDetectionAt: string | null;\n activeInWindow: boolean;\n createdAt: string;\n}\n/** An email that never became a user, sourced from `email_leads` or `assessments.lead_email`; sourceDetail is the raw source string. */\nexport interface LeadRow {\n email: string;\n source: 'email_lead' | 'assessment';\n sourceDetail: string | null;\n company: string | null;\n firstSeenAt: string;\n lastSeenAt: string;\n}\n/** How many users and organizations one exclusion rule (bucket) removed from the counts. */\nexport interface ExclusionAuditRow {\n bucket: ExclusionBucket;\n users: number;\n organizations: number;\n}\n/** A server-capped list: rows.length <= listLimit, total is the uncapped count. */\nexport interface AdminOverviewList<T> {\n rows: T[];\n total: number;\n}\n/**\n * A Hi-AI report requested by email, linked to the exact host that was\n * audited (apps/web/app/api/hi-ai/share/route.ts inserts `sourceUrl` from\n * the already-validated `host` at request time). `sourceUrl` is null for a\n * row recorded before that column existed, until\n * `scripts/backfill-hi-ai-lead-source-url.ts` fills it in from the legacy\n * `referer` header.\n */\nexport interface HiAiLeadRow {\n email: string;\n sourceUrl: string | null;\n createdAt: string;\n}\n/**\n * One host audited through the public Hi-AI tool (`/hi-ai/<host>`), sourced\n * from Amplitude `Page Viewed` events rather than a database row —\n * unattributed to any person, unlike {@link HiAiLeadRow}: this counts every\n * visit, with or without an email capture. `visits` is unique visitors in\n * the selected window (Amplitude `uniques`).\n */\nexport interface HiAiAuditRow {\n host: string;\n visits: number;\n}\n/** The Hi-AI section: leads linked to a person (email -> audited host) alongside the unattributed per-host audit breakdown. */\nexport interface AdminOverviewHiAi {\n leads: AdminOverviewList<HiAiLeadRow>;\n audits: AdminOverviewList<HiAiAuditRow>;\n}\n/**\n * The lists section shown below the headline numbers. `activatedUsers`,\n * `installationUsers`, `pixelInstallations`, and `leads` are server-capped by\n * listLimit; `exclusionAudit` is one row per ExclusionBucket and is not\n * capped.\n */\nexport interface AdminOverviewLists {\n activatedUsers: AdminOverviewList<ActivatedUserRow>;\n /**\n * Every member of a customer org with >=1 installation, regardless of\n * whether that individual user has personally completed the onboarding\n * wizard — the superset `activatedUsers` is filtered down from. Tag a row\n * to a specific installation kind client-side via\n * `installationKinds.includes(kind)`.\n */\n installationUsers: AdminOverviewList<ActivatedUserRow>;\n /**\n * Every new user, not gated on onboarding/installation status at all — a\n * strict superset of `installationUsers`' membership. See `NewSignupRow`.\n */\n newSignups: AdminOverviewList<NewSignupRow>;\n pixelInstallations: AdminOverviewList<PixelInstallationRow>;\n leads: AdminOverviewList<LeadRow>;\n exclusionAudit: ExclusionAuditRow[];\n}\n\n/** Everything the UI needs to explain the numbers, including every methodology caveat in `warnings`. */\nexport interface AdminOverviewMeta {\n generatedAt: string;\n window: AdminOverviewWindow;\n windowStart: string;\n windowEnd: string;\n /** The compareTo date the deltas were computed against, or null when no compareTo was given. */\n previousSnapshotAt: string | null;\n partial: boolean;\n failedSections: AdminOverviewSection[];\n warnings: string[];\n exclusions: { version: string; hash: string; buckets: ExclusionBucket[] };\n cache: { status: AdminOverviewCacheStatus; ageSeconds: number | null };\n rollupFreshness: { refreshedAt: string | null; fresh: boolean; ageSeconds: number | null };\n durationsMs: Partial<Record<AdminOverviewSection | 'total', number>>;\n}\n\n/**\n * Headline numbers that show \"N counted · M excluded\" and open a drill-down\n * of every account behind them. The first five mirror the ladder steps\n * (signedIn is the ladder's signedInProxy); the last three are the KYA-1147\n * people numbers.\n */\nexport const ADMIN_TRUSTED_METRICS = [\n 'emailsCollected',\n 'users',\n 'signedIn',\n 'onboarded',\n 'activated',\n 'activeUsers',\n 'peopleInOrgs',\n 'installedOrgs',\n] as const;\nexport type AdminTrustedMetric = (typeof ADMIN_TRUSTED_METRICS)[number];\n\n/**\n * Why an account a user-level exclusion did not catch is still left out:\n * every org that would count it is test-named (`test_org`), or, for an org\n * row, none of its members is a counted person (`no_counted_members`).\n */\nexport const ADMIN_ORG_EXCLUSION_REASONS = ['test_org', 'no_counted_members'] as const;\n\n/** `counted`, or the first rule that left the account out (user buckets take precedence). */\nexport const ADMIN_ACCOUNT_STATUSES = [\n 'counted',\n ...EXCLUSION_BUCKETS,\n ...ADMIN_ORG_EXCLUSION_REASONS,\n] as const;\nexport type AdminAccountStatus = (typeof ADMIN_ACCOUNT_STATUSES)[number];\n\nexport interface AdminCountSplit {\n counted: number;\n excluded: number;\n}\n\n/** One day of dashboard activity, `date` as YYYY-MM-DD. */\nexport interface AdminDailyActive {\n date: string;\n counted: number;\n excluded: number;\n}\n\n/**\n * Dashboard activity from Amplitude (`_active`, platform Web), the same\n * source the /cpun report uses for MAU. `available: false` means the source\n * could not be read: the card says \"unavailable\", never 0.\n */\nexport interface AdminActiveUsersSummary {\n available: boolean;\n /** Mean of `daily` per day, unrounded. Null when unavailable. */\n dailyAverage: { counted: number; excluded: number } | null;\n daily: AdminDailyActive[];\n}\n\n/** Overview section: the split behind every trusted metric. A null split means its source was unavailable. */\nexport interface AdminOverviewAccounts {\n splits: Record<AdminTrustedMetric, AdminCountSplit | null>;\n activeUsers: AdminActiveUsersSummary;\n}\n\n/** GET /api/admin/overview/accounts query. */\n/** Drill-down status filter: everyone, any exclusion, or one status. */\nexport const ADMIN_ACCOUNTS_STATUS_FILTERS = [\n 'all',\n 'excluded',\n ...ADMIN_ACCOUNT_STATUSES,\n] as const;\nexport type AdminAccountsStatusFilter = (typeof ADMIN_ACCOUNTS_STATUS_FILTERS)[number];\n\n/**\n * GET /api/admin/overview/accounts query. `status` filters on the server,\n * so the row cap applies to the filtered list and an exclusion is never cut\n * off by counted rows.\n */\nexport const adminAccountsQuerySchema = z.object({\n metric: z.enum(ADMIN_TRUSTED_METRICS),\n window: z.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),\n status: z.enum(ADMIN_ACCOUNTS_STATUS_FILTERS).default('all'),\n});\n\n/** 30-day activity behind one account or org. Dashboard fields are null when Amplitude is unavailable. */\nexport interface AdminAccountActivity {\n /** Days with dashboard activity in the last 30. */\n dashboardActiveDays: number | null;\n /** Most recent dashboard day in the last 30, YYYY-MM-DD. */\n lastDashboardDay: string | null;\n /** Most recent action this person took that the app logged (activity_logs). */\n lastActionAt: string | null;\n /** Live projects across the person's (or org's) orgs. */\n projects: number;\n /** Detections on those projects in the last 30 days (daily rollup). */\n detections30d: number;\n apiKeyLastUsedAt: string | null;\n}\n\nexport interface AdminPersonRow {\n subject: 'person';\n /** User id. */\n id: string;\n email: string;\n name: string | null;\n organizationId: string | null;\n organizationName: string | null;\n status: AdminAccountStatus;\n createdAt: string;\n /** YYYY-MM-DD: the later of the last dashboard day and the last logged action. */\n lastActiveAt: string | null;\n activity: AdminAccountActivity;\n}\n\n/** emailsCollected only: an address that never became an account. */\nexport interface AdminLeadRow {\n subject: 'lead';\n /** The lowercased email. */\n id: string;\n email: string;\n status: AdminAccountStatus;\n createdAt: string;\n}\n\nexport interface AdminOrgRow {\n subject: 'org';\n /** Organization id. */\n id: string;\n name: string;\n status: AdminAccountStatus;\n /** Members split by the user-level exclusion rules. */\n members: AdminCountSplit;\n createdAt: string;\n /** YYYY-MM-DD: the latest day any member was active. */\n lastActiveAt: string | null;\n activity: AdminAccountActivity;\n}\n\nexport type AdminAccountRow = AdminPersonRow | AdminLeadRow | AdminOrgRow;\n\n/** The full GET /api/admin/overview/accounts payload. */\nexport interface AdminAccountsResponse {\n metric: AdminTrustedMetric;\n window: AdminOverviewWindow;\n /**\n * False when the source behind the number could not be read (activeUsers\n * with Amplitude down). `rows`, `total` and `split` are then empty and mean\n * \"unknown\", not 0.\n */\n available: boolean;\n rows: AdminAccountRow[];\n /** The status filter `rows` was read with. */\n status: AdminAccountsStatusFilter;\n /** Every account behind the metric, whatever the filter. */\n total: number;\n /** Accounts matching `status`, before the row cap. */\n matching: number;\n split: AdminCountSplit;\n byStatus: Partial<Record<AdminAccountStatus, number>>;\n /** True when `rows` stops short of `matching`. */\n truncated: boolean;\n dashboardActivity: { available: boolean };\n warnings: string[];\n generatedAt: string;\n}\n\n/** The full GET /api/admin/overview payload. */\nexport interface AdminOverviewResponse {\n ladder: AdminOverviewLadder;\n installations: AdminOverviewInstallations;\n traffic: AdminOverviewTraffic;\n lists: AdminOverviewLists;\n hiAi: AdminOverviewHiAi;\n accounts: AdminOverviewAccounts;\n meta: AdminOverviewMeta;\n}\n","/**\n * Display-time Claude runtime delineation.\n *\n * The user-visible problem: every Claude assistant runtime — Claude Code (the\n * CLI), Claude on the web, the user-initiated fetcher, the search assistant —\n * collapses into one undifferentiated \"Claude\" row, so the dashboard can't tell\n * an operator *which* Claude touched their site. The ratified taxonomy north-star\n * (`docs/architecture/agent-identity-taxonomy.md` §3.1) is explicit that this is\n * \"one product, one vendor, three runtimes — NOT three catalog rows.\" So we do\n * NOT split `agent_types`; we refine the *rendered* label from the request's\n * User-Agent at display time.\n *\n * Pure and display-only: these helpers MUST NEVER influence `category` /\n * `detection_class` / classification — they only change the string shown to a\n * human. Keyed off the real `anthropic-claude` SSOT tokens in\n * `constants/agents.ts`; mirrors the UA→variant precedent in\n * `apps/web/lib/agents/canonical-ids.ts` (which already splits claude-code vs\n * claude-desktop for the connect flow).\n *\n * @module utils/agent-runtime-label\n */\n\n/** Canonical display name of the single Claude product row (SSOT `anthropic-claude`, name: 'Claude'). */\nconst CLAUDE_CANONICAL_DISPLAY = 'Claude';\n\n/**\n * The retired-duplicate Claude twin keeps `display_name` of the form\n * \"Claude (deprecated duplicate — see <uuid>)\" (only its `name` slug is mutated\n * with `-DEPRECATED-`). Per-event surfaces that aren't WHERE-guarded can still\n * render a historical detection FK'd to it, so the gate matches the twin too —\n * refining it cleans the ugly label down to a real runtime label.\n */\nconst CLAUDE_DEPRECATED_TWIN = /^Claude \\(deprecated/i;\n\n/**\n * True when a *displayed* agent label refers to the canonical Claude product\n * (or its retired twin). Deliberately does NOT match the separate catalog rows\n * \"ClaudeBot\" (training crawler) or \"Anthropic AI Crawler\" — those are distinct\n * agents, not Claude runtimes, and must keep their own labels.\n */\nexport function isClaudeProductLabel(displayName: string | null | undefined): boolean {\n if (!displayName) return false;\n const d = displayName.trim();\n return d === CLAUDE_CANONICAL_DISPLAY || CLAUDE_DEPRECATED_TWIN.test(d);\n}\n\n/**\n * The Claude UA-token vocabulary, exported so KYA-1099's runtime_surface\n * derivation (`apps/web/lib/services/detections/claude-runtime-surface.ts`)\n * shares this ONE tokenization with the display label above, rather than\n * hand-copying the token list into a second, independently-maintained regex.\n * Case-insensitive; `userAgent` is lowercased once per call.\n */\nexport function hasClaudeCodeToken(userAgent: string | null | undefined): boolean {\n const ua = (userAgent ?? '').toLowerCase();\n return ua.includes('claude-code') || ua.includes('claude code');\n}\n\nexport function hasClaudeUserToken(userAgent: string | null | undefined): boolean {\n return (userAgent ?? '').toLowerCase().includes('claude-user');\n}\n\nexport function hasClaudeSearchBotToken(userAgent: string | null | undefined): boolean {\n return (userAgent ?? '').toLowerCase().includes('claude-searchbot');\n}\n\n/**\n * Map a Claude request's User-Agent (plus, KYA-1099, the persisted\n * `detections.runtime_surface`) to its runtime sub-label. Always returns a\n * \"Claude…\"-prefixed string (never a non-Claude label), so a caller that has\n * already established the agent is Claude can use the result directly.\n *\n * Token source (`constants/agents.ts` `anthropic-claude.patterns`):\n * - `claude-code` AND `Claude-User` (Claude Code's OWN WebFetch UA embeds\n * both) → \"Claude Code (web fetch)\"\n * - `claude-code` / `claude code` alone → \"Claude Code\" (the CLI)\n * - `Claude-SearchBot` → \"Claude SearchBot\"\n * - `Claude-User` alone → \"Claude (web fetch)\" (assistant browsing for a user)\n * - `Claude-Web` / model UAs / unknown → \"Claude\"\n *\n * `runtimeSurface` (KYA-1099 W1/W2, optional — existing callers compile\n * unchanged) is consulted ONLY when none of the UA tokens above matched: a\n * plain `curl`/`Wget` (or Claude Desktop) request carries no\n * Claude-identifying UA token at all — including an EMPTY UA, checked here\n * too (Bugbot KYA-1099 review: an empty UA used to short-circuit to bare\n * \"Claude\" before runtimeSurface was ever read; KYA-1099 W7's session-grain\n * rows have no UA at ALL, so this path is their only signal) — so a request\n * that a VERIFIED delegation (not a UA guess — see\n * `resolve-delegation-rung-agent-type.ts`) resolved to Claude still gets a\n * runtime-flavored label:\n * - `runtimeSurface === 'cli'` AND UA starts with `curl/` → \"Claude Code (curl)\"\n * - `runtimeSurface === 'cli'` AND UA starts with `Wget/`/`wget/` → \"Claude Code (wget)\"\n * - `runtimeSurface === 'cli'`, anything else → \"Claude Code\"\n * - `runtimeSurface === 'native_app'` → \"Claude Desktop\"\n * - `runtimeSurface === 'browser'` → \"Claude (browser)\"\n *\n * The `claude-cowork` branch is DORMANT (Part C, capture-first): Claude Cowork\n * has no published User-Agent as of 2026-06 (it runs in a sandboxed VM behind a\n * MITM proxy; absent from Anthropic's crawler docs). The branch is keyed on a\n * placeholder token and must be reconfirmed against real traffic before it can\n * fire on anything live.\n */\nexport function claudeRuntimeLabel(\n userAgent: string | null | undefined,\n runtimeSurface?: string | null\n): string {\n const ua = (userAgent ?? '').toLowerCase();\n if (ua) {\n const hasClaudeCode = hasClaudeCodeToken(ua);\n const hasClaudeUser = hasClaudeUserToken(ua);\n if (hasClaudeCode && hasClaudeUser) return 'Claude Code (web fetch)';\n if (hasClaudeCode) return 'Claude Code';\n if (ua.includes('claude-cowork')) return 'Claude Cowork'; // Part C: placeholder token, capture-first\n if (hasClaudeSearchBotToken(ua)) return 'Claude SearchBot';\n if (hasClaudeUser) return 'Claude (web fetch)';\n }\n if (runtimeSurface === 'cli') {\n if (ua.startsWith('curl/')) return 'Claude Code (curl)';\n if (ua.startsWith('wget/')) return 'Claude Code (wget)';\n return 'Claude Code';\n }\n if (runtimeSurface === 'native_app') return 'Claude Desktop';\n // KYA-1099 W7 — session rows have no UA at all (the carrier is the only\n // signal), so 'browser' needs its own label here too, not just 'cli'/\n // 'native_app'.\n if (runtimeSurface === 'browser') return 'Claude (browser)';\n return 'Claude';\n}\n\n/**\n * Refine a displayed agent label: when it's the canonical Claude product (or its\n * retired twin), return the UA-derived (+ KYA-1099 runtime_surface-derived)\n * runtime sub-label; otherwise return the label unchanged. Idempotent —\n * re-applying to an already-refined label (e.g. \"Claude Code\") is a no-op,\n * because the gate fires only on exact \"Claude\" or the deprecated twin.\n * Preserves `null` / `undefined` so it can sit directly on a nullable display\n * column. `runtimeSurface` is optional and additive — existing 2-arg call\n * sites compile and behave unchanged.\n */\nexport function refineClaudeDisplayLabel<T extends string | null | undefined>(\n displayName: T,\n userAgent: string | null | undefined,\n runtimeSurface?: string | null\n): T | string {\n return isClaudeProductLabel(displayName)\n ? claudeRuntimeLabel(userAgent, runtimeSurface)\n : displayName;\n}\n\n/**\n * `refineClaudeDisplayLabel` for a SESSION-grain row (KYA-1099 W7):\n * `unified_agent_sessions` carries no raw User-Agent at all, so every\n * session-row read path (`activity-lens.service.ts`, `recent-agent-sessions\n * .service.ts`, `agent-session-detail.service.ts`) was pinning `userAgent` to\n * `null` at the call site. Pinning it here instead means each of those three\n * call sites, and any future one, can't accidentally pass a stale/wrong UA to\n * a session-grain row.\n */\nexport function refineSessionGrainClaudeLabel<T extends string | null | undefined>(\n displayName: T,\n runtimeSurface: string | null | undefined\n): T | string {\n return refineClaudeDisplayLabel(displayName, null, runtimeSurface);\n}\n","/**\n * Isomorphic request correlation-id derivation.\n *\n * Every detection surface — the Cloudflare gateway worker, the published SDK\n * middleware (Next.js / Express), the Next.js detector route, and the browser\n * beacon — needs the SAME canonical id for a request so its records can be\n * correlated across surfaces. This module is the single producer of that id:\n * one 32-hex `correlation_id` derived from request headers, with a fixed\n * precedence and a guaranteed-valid output.\n *\n * Precedence (first match wins):\n * 1. W3C `traceparent` trace-id (the 32-hex middle segment), rejecting the\n * all-zero \"invalid\" sentinel,\n * 2. the `x-kya-correlation-id` header,\n * 3. a caller-provided `fallback` (e.g. an existing per-surface request id),\n * 4. a freshly minted UUIDv4 (dashes stripped → 32-hex).\n *\n * Edge/Node/browser safe: the mint path uses `globalThis.crypto.randomUUID`,\n * available on Node 18+, Cloudflare Workers, and browsers. Header lookup accepts\n * a `Headers` instance OR a plain record (case-insensitive), so it works on\n * every surface without callers pre-normalizing.\n */\n\nimport { z } from 'zod';\n\n/** Header carrying our canonical 32-hex correlation id between surfaces. */\nexport const CORRELATION_ID_HEADER = 'x-kya-correlation-id';\n\n/** Canonical stored shape: 32 lowercase hex chars. */\nexport const CorrelationIdSchema = z.string().regex(/^[0-9a-f]{32}$/);\n\n/**\n * W3C `traceparent` grammar: `version-traceId-spanId-flags`.\n * Only `trace` is used downstream; `ver`/`span`/`flags` are matched but ignored.\n */\nconst TRACEPARENT_RE =\n /^(?<ver>[0-9a-f]{2})-(?<trace>[0-9a-f]{32})-(?<span>[0-9a-f]{16})-(?<flags>[0-9a-f]{2})$/;\n\n/** The W3C \"invalid\" trace-id sentinel — must never be used as a correlation id. */\nconst ZERO_TRACE_ID = '0'.repeat(32);\n\n/**\n * Case-insensitive single-header lookup over both a `Headers` instance and a\n * plain record. For a record, keys are matched case-insensitively and a\n * `string[]` value resolves to its first element. Returns `null` for a missing\n * or empty value.\n */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | null {\n const lower = name.toLowerCase();\n\n if (typeof (headers as Headers).get === 'function') {\n const value = (headers as Headers).get(lower);\n return value && value.length > 0 ? value : null;\n }\n\n const record = headers as Record<string, string | string[] | undefined>;\n for (const key of Object.keys(record)) {\n if (key.toLowerCase() !== lower) continue;\n const raw = record[key];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value && value.length > 0 ? value : null;\n }\n return null;\n}\n\n/**\n * Normalize any candidate to canonical 32-hex (lowercase, dashes stripped) or\n * `null` if it does not validate. Both bare 32-hex strings and dashed UUIDs\n * funnel through here.\n */\nfunction normalizeHex(value: string | null | undefined): string | null {\n if (typeof value !== 'string' || value.length === 0) return null;\n const candidate = value.toLowerCase().replace(/-/g, '');\n const parsed = CorrelationIdSchema.safeParse(candidate);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Extract the trace-id from a `traceparent` value, or `null` when it is absent,\n * malformed, or carries the all-zero invalid sentinel. The extracted trace-id is\n * already canonical 32 lowercase hex by the grammar.\n */\nfunction extractTraceId(traceparent: string | null): string | null {\n if (!traceparent) return null;\n const match = TRACEPARENT_RE.exec(traceparent);\n const trace = match?.groups?.trace;\n if (!trace || trace === ZERO_TRACE_ID) return null;\n return trace;\n}\n\n/**\n * Normalize any candidate to 32-hex, or `null` if it isn't valid. Lowercases and\n * strips dashes (so a canonical UUID is accepted) before validating against\n * {@link CorrelationIdSchema}.\n */\nexport function toStoredCorrelationId(value: string | null | undefined): string | null {\n return normalizeHex(value);\n}\n\n/**\n * Derive the correlation id for a request, by precedence:\n * 1. W3C `traceparent` trace-id (the 32-hex middle segment; reject the\n * all-zero \"invalid\" sentinel),\n * 2. `x-kya-correlation-id` header,\n * 3. the provided `fallback` (e.g. an existing per-surface request id),\n * 4. a freshly minted UUIDv4 (dashes stripped → 32-hex).\n * Always returns a valid 32-hex string. Accepts a `Headers` instance OR a\n * plain record (case-insensitive lookup) so it works on every surface.\n *\n * NOTE on a client-supplied BODY id: `fallback` is the LOWEST trusted source\n * (below transport `traceparent` / header). Surfaces vary intentionally on where\n * a client-body correlation id sits: the pixel surfaces (pixel identify / track,\n * log-detection) trust their own SDK's body id ABOVE traceparent — they pass it\n * as a pre-check, not via `fallback` — while bouncer (proof.service) trusts the\n * inbound transport `traceparent` over a client claim and passes the body id AS\n * the `fallback`. That asymmetry is a deliberate per-surface trust decision, not\n * a uniform rule — match the surface's existing pattern when adding a caller.\n */\n/**\n * Extract a correlation id that was PROPAGATED on the request headers (W3C\n * `traceparent` trace-id, else `x-kya-correlation-id`), or `null` when neither\n * is present. Unlike {@link deriveCorrelationId} this NEVER falls back or mints —\n * use it when a minted id would be useless, e.g. an alias anchor that must match\n * an id actually stamped on another surface's row rather than a fresh orphan.\n */\nexport function extractCorrelationIdFromHeaders(\n headers: Headers | Record<string, string | string[] | undefined>\n): string | null {\n const fromTrace = extractTraceId(getHeader(headers, 'traceparent'));\n if (fromTrace) return fromTrace;\n\n return normalizeHex(getHeader(headers, CORRELATION_ID_HEADER));\n}\n\nexport function deriveCorrelationId(\n headers: Headers | Record<string, string | string[] | undefined>,\n fallback?: string | null\n): string {\n const fromHeaders = extractCorrelationIdFromHeaders(headers);\n if (fromHeaders) return fromHeaders;\n\n const fromFallback = normalizeHex(fallback);\n if (fromFallback) return fromFallback;\n\n return globalThis.crypto.randomUUID().replace(/-/g, '').toLowerCase();\n}\n","/**\n * Authentication Validation Schemas\n *\n * Zod schemas for validating authentication-related data\n * Used across the application for consistent validation\n */\n\nimport { z } from 'zod';\n\n/**\n * Base password validation schema\n * Enforces password security requirements\n */\nexport const passwordSchema = z\n .string()\n .min(8, 'Password must be at least 8 characters long')\n .max(128, 'Password must not exceed 128 characters')\n .regex(\n /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)/,\n 'Password must contain at least one lowercase letter, one uppercase letter, and one number'\n );\n\n/**\n * Sign in validation schema\n */\nexport const signInSchema = z.object({\n email: z.string().email('Invalid email address'),\n password: z.string().min(1, 'Password is required'),\n});\n\n/**\n * Sign up validation schema\n */\nexport const signUpSchema = z\n .object({\n email: z.string().email('Invalid email address'),\n name: z.string().optional(),\n password: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.password === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\n\n/**\n * Password reset request validation schema\n */\nexport const forgotPasswordSchema = z.object({\n email: z.string().email('Invalid email address'),\n});\n\n/**\n * Password reset confirmation validation schema\n * Validates token and ensures passwords match\n */\nexport const resetPasswordSchema = z\n .object({\n token: z.string().min(1, 'Token is required'),\n password: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.password === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\n\n/**\n * Change password validation schema\n * For authenticated users changing their password\n */\nexport const changePasswordSchema = z\n .object({\n currentPassword: z.string().optional(), // Optional for OAuth users setting first password\n newPassword: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.newPassword === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\n\n/**\n * Email verification validation schema\n */\nexport const verifyEmailSchema = z.object({\n token: z.string().min(1, 'Token is required'),\n});\n\n/**\n * Type exports for use in TypeScript\n */\nexport type SignInData = z.infer<typeof signInSchema>;\nexport type SignUpData = z.infer<typeof signUpSchema>;\nexport type ForgotPasswordData = z.infer<typeof forgotPasswordSchema>;\nexport type ResetPasswordData = z.infer<typeof resetPasswordSchema>;\nexport type ChangePasswordData = z.infer<typeof changePasswordSchema>;\nexport type VerifyEmailData = z.infer<typeof verifyEmailSchema>;\n","/**\n * Admin API Validation Schemas\n *\n * Schemas for admin-specific endpoints\n * Used for validation and type safety in admin routes\n */\n\nimport { z } from 'zod';\n\n/**\n * Performance recalculation request schema\n * Used for POST /api/admin/organizations/[id]/performance\n */\nexport const PerformanceRecalculationRequestSchema = z.object({\n periodType: z.enum(['daily', 'weekly', 'monthly']).optional().default('weekly'),\n});\nexport type PerformanceRecalculationRequest = z.infer<typeof PerformanceRecalculationRequestSchema>;\n\n/**\n * Growth opportunity status update schema\n * Used for PATCH /api/admin/growth-opportunities\n */\nexport const GrowthOpportunityUpdateSchema = z.object({\n opportunityId: z.string().min(1, 'Opportunity ID is required'),\n status: z.enum(['active', 'contacted', 'converted', 'dismissed']).optional(),\n assignedTo: z.string().nullable().optional(),\n notes: z.string().nullable().optional(),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n dismissedReason: z.string().nullable().optional(),\n});\nexport type GrowthOpportunityUpdate = z.infer<typeof GrowthOpportunityUpdateSchema>;\n\n/**\n * Growth batch identification request schema\n * Used for POST /api/admin/growth-opportunities\n */\nexport const GrowthBatchRequestSchema = z\n .object({\n runBatch: z.boolean().optional().default(false),\n organizationIds: z.array(z.string()).optional(),\n })\n .refine((data) => data.runBatch || (data.organizationIds && data.organizationIds.length > 0), {\n message: 'Either runBatch must be true or organizationIds must be provided',\n });\nexport type GrowthBatchRequest = z.infer<typeof GrowthBatchRequestSchema>;\n\n/**\n * Growth configuration thresholds schema\n * Used for PUT /api/admin/growth-configurations\n */\nexport const GrowthConfigurationThresholdsSchema = z\n .object({\n // Bouncer thresholds\n minAiTrafficRate: z.number().min(0).max(100).optional(),\n highAiTrafficThreshold: z.number().min(0).max(100).optional(),\n aiTrafficSpikeMultiplier: z.number().min(1).optional(),\n consistentHighTrafficDays: z.number().int().min(1).optional(),\n criticalAiTrafficRate: z.number().min(0).max(100).optional(),\n\n // Enterprise thresholds\n highVolumeThreshold: z.number().int().min(1).optional(),\n rapidGrowthRate: z.number().min(0).optional(),\n multiDomainCount: z.number().int().min(1).optional(),\n largeTeamSize: z.number().int().min(1).optional(),\n multiProjectCount: z.number().int().min(1).optional(),\n highPercentileThreshold: z.number().min(0).max(100).optional(),\n minEnterpriseIndicators: z.number().int().min(1).optional(),\n\n // Support thresholds\n minIntegrationMethods: z.number().int().min(1).optional(),\n maxInactivePixels: z.number().int().min(0).optional(),\n inactiveDays: z.number().int().min(1).optional(),\n minSupportIndicators: z.number().int().min(1).optional(),\n criticalSupportScore: z.number().min(0).optional(),\n\n // Integration thresholds\n minSessionsForBenefit: z.number().int().min(1).optional(),\n minAiRateForBenefit: z.number().min(0).max(100).optional(),\n })\n .strict();\nexport type GrowthConfigurationThresholds = z.infer<typeof GrowthConfigurationThresholdsSchema>;\n\n/**\n * Growth configuration update request schema\n */\nexport const GrowthConfigurationUpdateSchema = z.object({\n configType: z.enum(['bouncer', 'enterprise', 'support', 'integration']),\n thresholds: GrowthConfigurationThresholdsSchema,\n});\nexport type GrowthConfigurationUpdate = z.infer<typeof GrowthConfigurationUpdateSchema>;\n\n/**\n * Growth configuration reset request schema\n */\nexport const GrowthConfigurationResetSchema = z.object({\n configType: z.enum(['bouncer', 'enterprise', 'support', 'integration', 'all']),\n});\nexport type GrowthConfigurationReset = z.infer<typeof GrowthConfigurationResetSchema>;\n\n/**\n * Admin query parameters validation\n */\nexport const AdminQueryParamsSchema = z.object({\n limit: z.coerce.number().min(1).max(500).optional().default(100),\n offset: z.coerce.number().min(0).optional().default(0),\n sortBy: z.string().optional(),\n sortOrder: z.enum(['asc', 'desc']).optional().default('desc'),\n});\nexport type AdminQueryParams = z.infer<typeof AdminQueryParamsSchema>;\n\n/**\n * Growth opportunities query parameters\n */\nexport const GrowthOpportunitiesQuerySchema = AdminQueryParamsSchema.extend({\n type: z.enum(['bouncer', 'enterprise', 'support', 'integration']).optional(),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n status: z.enum(['active', 'contacted', 'converted', 'dismissed']).optional(),\n assignedTo: z.string().optional(),\n});\nexport type GrowthOpportunitiesQuery = z.infer<typeof GrowthOpportunitiesQuerySchema>;\n\n/**\n * Recommendation query parameters\n * Used for GET /api/admin/recommendations\n */\nexport const RecommendationQuerySchema = z.object({\n organizationId: z.string().min(1).optional(),\n type: z.enum(['bouncer', 'enterprise', 'support', 'integration']).optional(),\n minConfidence: z.coerce.number().min(0).max(1).optional(),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n});\nexport type RecommendationQuery = z.infer<typeof RecommendationQuerySchema>;\n\n/**\n * Recommendation generation request schema\n * Used for POST /api/admin/recommendations\n */\nexport const RecommendationGenerationSchema = z.object({\n organizationId: z.string().min(1, 'Organization ID is required'),\n forceRefresh: z.boolean().optional().default(false),\n});\nexport type RecommendationGeneration = z.infer<typeof RecommendationGenerationSchema>;\n","import { z } from 'zod';\n\n/**\n * Wire shape of `GET /api/v1/kya-os/consent-policy`, defined once here. The\n * response is the project's consent policy as a client needs to render and\n * pre-check it; it is authenticated with the project API key.\n *\n * `etag` is the BARE hash (lowercase hex). The HTTP `ETag` header carries the\n * same value as a quoted strong validator, `\"<etag>\"`, on 200 and 304.\n * `riskLevel` is ConsentConfig's capability risk set, unchanged.\n */\nexport const ConsentPolicyRiskLevelSchema = z.enum(['low', 'medium', 'high', 'critical']);\nexport type ConsentPolicyRiskLevel = z.infer<typeof ConsentPolicyRiskLevelSchema>;\n\nexport const ConsentPolicyCapabilitySchema = z.strictObject({\n scope: z.string().min(1),\n defaultOn: z.boolean(),\n riskLevel: ConsentPolicyRiskLevelSchema,\n});\n\nexport const ConsentPolicyResponseSchema = z.strictObject({\n allowedScopes: z.array(z.string().min(1)).optional(),\n maxGrantSeconds: z.number().int().positive().optional(),\n capabilities: z.array(ConsentPolicyCapabilitySchema).optional(),\n etag: z.string().regex(/^[0-9a-f]{64}$/),\n});\nexport type ConsentPolicyResponse = z.infer<typeof ConsentPolicyResponseSchema>;\n","/**\n * Wire contract for the Fly gateway's internal tools endpoints\n * (#2029, #2027).\n *\n * Routes:\n * GET /api/gateway/internal/tools/:orgId\n * — org-level aggregated tool list from the 60s cache\n * POST /api/gateway/internal/tools/:orgId/discover\n * — user-scoped single-upstream discovery (Phase 4 #1990)\n *\n * These are Fly → Vercel bodies. The Vercel dashboard's proxy\n * routes and hooks validate incoming responses against these\n * schemas, and the gateway route handlers validate their outgoing\n * body to keep both sides pinned to the same shape.\n */\n\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// Discovered tool (shared shape across endpoints)\n// ---------------------------------------------------------------------------\n\nexport const discoveredToolSchema = z\n .object({\n name: z.string(),\n description: z.string().optional(),\n /**\n * JSON-schema object describing the tool's arguments. Shape\n * comes from the upstream MCP server and varies widely —\n * permissive `record(unknown)` rather than pinning the JSON\n * Schema draft here. The Tool Testing Panel renders a\n * skeleton from whatever it gets.\n */\n inputSchema: z.record(z.string(), z.unknown()).optional(),\n })\n .strict();\n\nexport type DiscoveredTool = z.infer<typeof discoveredToolSchema>;\n\n// ---------------------------------------------------------------------------\n// Per-upstream error — new in #2027's partial-success envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Categorized failure mode for a single upstream during org-level\n * aggregation. The dashboard uses the `code` to drive retry\n * behavior and the user-facing label; `message` surfaces in the\n * tooltip so operators can diagnose.\n */\nexport const upstreamDiscoveryErrorSchema = z\n .object({\n code: z.enum([\n /** Upstream returned 401/403 or the MCP handshake was rejected. */\n 'auth_failed',\n /** Upstream was healthy but refused tools/list (e.g. requires per-user auth). */\n 'per_user_auth_required',\n /** Upstream timed out during the handshake or tools/list call. */\n 'timeout',\n /** MCP handshake failed — protocol negotiation, bad JSON, etc. */\n 'handshake_failed',\n /** Upstream returned a non-MCP error shape we couldn't classify. */\n 'unknown',\n ]),\n message: z.string(),\n /** Upstream HTTP status if we got one. */\n status: z.number().int().optional(),\n })\n .strict();\n\nexport type UpstreamDiscoveryError = z.infer<typeof upstreamDiscoveryErrorSchema>;\n\n// ---------------------------------------------------------------------------\n// GET /api/gateway/internal/tools/:orgId — aggregated list\n// ---------------------------------------------------------------------------\n\n/**\n * Partial-success envelope (#2027). `tools` carries every tool the\n * gateway successfully discovered; `upstreamCounts` is the\n * histogram by slug; `errors` is a sparse map of upstream slug →\n * categorized failure for every upstream that *couldn't* contribute\n * tools this call. An empty `errors` map means full success.\n *\n * Callers render per-upstream error state from `errors` instead of\n * collapsing a failed upstream to a silent `0` count. Before #2027\n * the gateway cached empty results as success and the dashboard\n * had no signal that an upstream was broken.\n */\nexport const gatewayInternalToolsListSchema = z\n .object({\n totalCount: z.number().int().min(0),\n upstreamCounts: z.record(z.string(), z.number().int().min(0)),\n tools: z.array(discoveredToolSchema),\n /**\n * Sparse map keyed by upstream slug. Empty / absent when every\n * upstream contributed successfully. Present as an empty object\n * when serialized — always-object keeps the shape stable for\n * consumers that read `Object.keys(errors).length`.\n */\n errors: z.record(z.string(), upstreamDiscoveryErrorSchema),\n })\n .strict();\n\nexport type GatewayInternalToolsList = z.infer<typeof gatewayInternalToolsListSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /api/gateway/internal/tools/:orgId/discover — user-scoped\n// ---------------------------------------------------------------------------\n\nexport const gatewayInternalDiscoverSuccessSchema = z\n .object({\n tools: z.array(discoveredToolSchema),\n })\n .strict();\n\nexport type GatewayInternalDiscoverSuccess = z.infer<typeof gatewayInternalDiscoverSuccessSchema>;\n\nexport const gatewayInternalDiscoverErrorSchema = z\n .object({\n error: z.string(),\n })\n .strict();\n\nexport type GatewayInternalDiscoverError = z.infer<typeof gatewayInternalDiscoverErrorSchema>;\n","/**\n * Gateway Schemas\n *\n * Zod schemas for gateway configuration, upstream server validation,\n * and tool call audit records.\n *\n * SSRF Protection: The safeUrl validator blocks private/reserved IPs\n * at config time. Runtime DNS resolution checks (in GatewayProxy) are\n * still required to defeat DNS rebinding and redirect-based bypasses.\n */\n\nimport { z } from 'zod';\n\nimport { discoveredToolSchema } from '../wire/gateway-internal-tools';\n\n// ---------------------------------------------------------------------------\n// SSRF-safe URL validator\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a hostname or IP string resolves to a private, reserved,\n * or link-local address that must never be used as an upstream target.\n *\n * This is a config-time check on the literal URL string. It does NOT\n * replace runtime DNS resolution validation (needed for DNS rebinding\n * and redirect attacks).\n */\n/**\n * Exported for direct unit testing of the defense-in-depth path. Production\n * code should go through `safeUrl` instead — the WHATWG URL parser does most\n * IPv4 normalization up front, but this function still has to be correct on\n * its own so the blocklist holds if a runtime's URL parser ever changes.\n */\nexport function isPrivateOrReservedHost(hostname: string): boolean {\n const lower = hostname.toLowerCase();\n\n // Block localhost and any *.localhost subdomain.\n // Per RFC 6761 the entire `.localhost` TLD is reserved and compliant\n // resolvers map all names under it to loopback (e.g. evil.localhost → 127.0.0.1).\n if (lower === 'localhost' || lower === 'localhost.') return true;\n if (lower.endsWith('.localhost') || lower.endsWith('.localhost.')) return true;\n\n // Strip IPv6 brackets for uniform parsing\n const bare = lower.startsWith('[') && lower.endsWith(']') ? lower.slice(1, -1) : lower;\n\n // IPv6 loopback\n if (bare === '::1' || bare === '0:0:0:0:0:0:0:1') return true;\n\n // IPv6 unspecified / all-zeros (::) — routes to localhost on most systems,\n // analogous to IPv4 0.0.0.0\n if (bare === '::' || bare === '0:0:0:0:0:0:0:0') return true;\n\n // IPv6 ULA (fc00::/7 → fc00:: – fdff::)\n if (/^f[cd][0-9a-f]{2}:/.test(bare)) return true;\n\n // IPv6 link-local (fe80::/10 → fe80:: – febf::) — direct analog of\n // IPv4 169.254.x.x, same class of bug as reaching the cloud metadata endpoint\n if (/^fe[89ab][0-9a-f]:/.test(bare)) return true;\n\n // IPv4-mapped IPv6 (::ffff:x.x.x.x or ::ffff:0a00:0001 etc.)\n const v4MappedMatch = bare.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (v4MappedMatch) {\n return isPrivateIPv4(v4MappedMatch[1]);\n }\n // Hex form: ::ffff:XXYY:ZZWW\n const v4MappedHexMatch = bare.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n if (v4MappedHexMatch) {\n const hi = parseInt(v4MappedHexMatch[1], 16);\n const lo = parseInt(v4MappedHexMatch[2], 16);\n const a = (hi >> 8) & 0xff;\n const b = hi & 0xff;\n const c = (lo >> 8) & 0xff;\n const d = lo & 0xff;\n return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n }\n\n // Dotted-quad IPv4 — per WHATWG URL spec and historical BSD convention,\n // each octet may independently be decimal, octal (leading zero), or hex\n // (`0x` prefix). Examples: `127.0.0.1`, `0177.0.0.01`, `0x7f.0.0.1`,\n // `0177.0x0.0.01`. This unified handler replaces three separate branches\n // that had a subtle ordering bug — the old decimal check matched any\n // string of digit characters, so `0177.0.0.01` fell through and was\n // parsed as decimal 177 instead of octal 127.\n const dottedParts = bare.split('.');\n if (dottedParts.length === 4) {\n const octets: number[] = [];\n let allValid = true;\n for (const part of dottedParts) {\n const n = parseIPv4Octet(part);\n if (n === null || n < 0 || n > 255) {\n allValid = false;\n break;\n }\n octets.push(n);\n }\n if (allValid) {\n return isPrivateIPv4(octets.join('.'));\n }\n }\n\n // Single-integer IPv4 encodings (no dots) — per BSD/WHATWG conventions,\n // a bare 32-bit integer is equivalent to its dotted-quad representation.\n // Examples: `0x7f000001` (hex), `017700000001` (octal), `2130706433` (decimal)\n // all mean `127.0.0.1`.\n //\n // Order matters: hex (`0x` prefix) and octal (leading `0`) must be tested\n // before decimal, otherwise `/^(0|[1-9]\\d*)$/` would eat the literal `0`\n // (harmless but the octal and hex branches have their own shape).\n if (/^0x[0-9a-f]+$/i.test(bare)) {\n const num = parseInt(bare, 16);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n if (/^0[0-7]+$/.test(bare)) {\n const num = parseInt(bare, 8);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n if (/^(0|[1-9]\\d*)$/.test(bare)) {\n const num = parseInt(bare, 10);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n\n return false;\n}\n\n/**\n * Parses a single IPv4 octet in decimal, octal (leading zero), or hex\n * (`0x` prefix). Returns null for anything that isn't a valid octet in any\n * of the three bases. Used by the dotted-quad handler to defeat\n * octal/hex-encoded SSRF bypasses like `0177.0.0.01` → `127.0.0.1`.\n */\nfunction parseIPv4Octet(part: string): number | null {\n if (/^0x[0-9a-f]+$/i.test(part)) {\n return parseInt(part, 16);\n }\n if (/^0[0-7]+$/.test(part)) {\n return parseInt(part, 8);\n }\n if (/^(0|[1-9]\\d*)$/.test(part)) {\n return parseInt(part, 10);\n }\n return null;\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n const parts = ip.split('.').map(Number);\n if (parts.some((p) => p > 255)) return false;\n\n const [a, b] = parts;\n\n // 0.0.0.0/8 — entire range routes to localhost on Linux/Unix\n if (a === 0) return true;\n\n // 127.0.0.0/8 (loopback)\n if (a === 127) return true;\n\n // 10.0.0.0/8\n if (a === 10) return true;\n\n // 172.16.0.0/12\n if (a === 172 && b >= 16 && b <= 31) return true;\n\n // 192.168.0.0/16\n if (a === 192 && b === 168) return true;\n\n // 169.254.0.0/16 (link-local, includes cloud metadata 169.254.169.254)\n if (a === 169 && b === 254) return true;\n\n // 100.64.0.0/10 (RFC 6598 Shared Address Space / CGNAT) — may reach\n // internal services in AWS VPCs and other cloud environments.\n // Matches the existing blocklist in apps/web/lib/utils/url-security.ts.\n if (a === 100 && b >= 64 && b <= 127) return true;\n\n return false;\n}\n\nfunction numToIPv4(num: number): string {\n return [(num >>> 24) & 0xff, (num >>> 16) & 0xff, (num >>> 8) & 0xff, num & 0xff].join('.');\n}\n\n/**\n * Zod refinement that rejects URLs pointing at private/reserved addresses.\n * Only http and https schemes are permitted.\n */\nexport const safeUrl = z\n .string()\n .url()\n .superRefine((val, ctx) => {\n let parsed: URL;\n try {\n parsed = new URL(val);\n } catch {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid URL' });\n return;\n }\n\n // Scheme allowlist\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Scheme \"${parsed.protocol.replace(':', '')}\" is not allowed; use http or https`,\n });\n return;\n }\n\n if (isPrivateOrReservedHost(parsed.hostname)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL points to a private or reserved IP address',\n });\n }\n });\n\n// ---------------------------------------------------------------------------\n// Slug regex — no consecutive underscores (__ is reserved as namespace sep)\n// ---------------------------------------------------------------------------\n\n/**\n * Upstream slug regex — lowercase alphanumerics with single underscores\n * between groups. No leading/trailing underscores. No consecutive `__`\n * (reserved as the namespace separator in the gateway proxy's\n * `parseNamespacedTool`).\n *\n * Single source of truth. Imported by:\n * - `upstreamServerSchema.slug` (this file) — admin-time validation\n * - `apps/gateway/src/lib/namespace.ts` — `slugify` output contract\n *\n * If this regex ever tightens (e.g. forbid leading digits, require min\n * length), both consumers pick up the change automatically.\n */\nexport const SLUG_REGEX = /^[a-z0-9]+(_[a-z0-9]+)*$/;\n\n// ---------------------------------------------------------------------------\n// Upstream Server Schema\n// ---------------------------------------------------------------------------\n\nexport const upstreamServerSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(100),\n slug: z.string().regex(SLUG_REGEX, {\n message:\n 'Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)',\n }),\n url: safeUrl,\n transport: z.enum(['http', 'sse']).default('http'),\n authType: z.enum(['none', 'vault', 'static']).default('none'),\n envVarNames: z.array(z.string()).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Static-header credential plane (hygiene-scorecard gap #1)\n //\n // `staticHeaders` (plaintext) is DEPRECATED as an at-rest field —\n // kept here only so `.parse()` doesn't silently drop rows written\n // before this fix while they wait to be re-encrypted. It remains the\n // wire-input field name (the admin form still submits plaintext\n // header values; the PUT handler encrypts them into\n // `staticHeadersEncrypted` before persisting and opportunistically\n // migrates any legacy plaintext it finds on every save that touches\n // an upstream). Never populated in an API response.\n staticHeaders: z.record(z.string(), z.string()).optional(),\n // AES-256-GCM ciphertext (base64: iv|ciphertext|authTag) of the\n // JSON-serialized staticHeaders map — the at-rest form going\n // forward. Encrypt/decrypt via `@kya-os/checkpoint-db/crypto`'s\n // `encryptStaticHeaders`/`resolveStaticHeaders`. Never populated in\n // an API response — see `staticHeaderKeys` for the redacted view.\n staticHeadersEncrypted: z.string().nullable().optional(),\n // Read-only projection of the configured header NAMES (never\n // values). Populated by the gateway-mcp config GET/PUT response\n // serializer (`redactGatewayConfig`) so the dashboard can render\n // \"N headers configured\" without ever receiving secret material or\n // ciphertext. Ignored on write — `upstreamServerInputSchema` omits it.\n staticHeaderKeys: z.array(z.string()).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // #1600 Phase 1 Part 2 — credential flow method selection\n //\n // `supportedAuthMethods` declares which of the two user-facing\n // credential-entry flows this upstream exposes to end users. The\n // admin picks this at upstream-create time; the user credential\n // modal reads it to decide whether to render the \"Connect GitHub\"\n // OAuth button, the paste-a-token form, or both (hybrid).\n //\n // Default `['paste']` keeps every pre-#1600 upstream row working\n // unchanged on read: the modal shows only the paste form, which\n // is what Bouncer + existing vault-authType upstreams expect.\n //\n // `oauthProvider` is only meaningful when `supportedAuthMethods`\n // includes `'oauth'`. It names a provider in the static registry\n // at `apps/web/lib/gateway/oauth-providers.ts`. Validation here\n // is the narrow enum of known IDs — the same set declared in\n // `OAUTH_PROVIDER_IDS` on the registry side.\n //\n // Intentionally omitted: per-upstream custom scope overrides.\n // Scopes live on the registry entry's `defaultScopes` field and\n // are NOT admin-configurable in v1 — see the operator setup doc\n // at `content/docs/govern/connections-github.mdx` for the\n // rationale (scope sprawl hesitancy).\n // ─────────────────────────────────────────────────────────────────\n supportedAuthMethods: z.array(z.enum(['paste', 'oauth'])).default(['paste']),\n oauthProvider: z.enum(['github', 'slack', 'notion', 'linear']).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Stateless (UCP-style) upstreams\n //\n // Some MCP-transport endpoints reject `initialize` and `tools/list`\n // outright and treat every POST as an independent request — UCP\n // servers (ucp.dev) such as the Shopify Global Catalog are the\n // motivating case. `sessionMode: 'stateless'` tells the gateway to\n // skip the initialize handshake and the per-user session cache for\n // this upstream, and to serve its tool list ONLY from a persisted\n // manifest (live discovery cannot succeed by design, and attempting\n // it would feed the health tracker until the upstream is marked\n // down). Absent means the standard MCP handshake — optional rather\n // than defaulted so the field stays optional on the inferred type\n // and pre-existing rows/fixtures parse unchanged.\n //\n // `ucpProfileUrl` is the UCP agent-profile document the gateway\n // injects as `arguments.meta[\"ucp-agent\"].profile` on tools/call\n // when the caller didn't supply its own — UCP servers reject calls\n // without it. `safeUrl` (not a plain URL check) because the value\n // is fetched by third-party upstreams and must never point at a\n // private/internal host.\n // ─────────────────────────────────────────────────────────────────\n sessionMode: z.enum(['standard', 'stateless']).optional(),\n ucpProfileUrl: safeUrl.optional(),\n\n enabled: z.boolean().default(true),\n // No default on purpose: A `.default('healthy')` here made every upstream render a\n // false green \"Healthy\" dot. `undefined` means \"never checked\" and\n // consumers must render a neutral \"Unchecked\" state for it.\n healthStatus: z.enum(['healthy', 'degraded', 'down']).optional(),\n consecutiveFailures: z.number().int().min(0).default(0),\n\n // ─────────────────────────────────────────────────────────────────\n // v1.1 KTA Trust Layer forward-compat (see #1549)\n // All fields nullable/optional. v1 code does NOT populate or read these.\n // v1.1 Phase A populates them from KTA registry lookups on upstream add.\n // DO NOT wire these to KTA in this sprint.\n // ─────────────────────────────────────────────────────────────────\n ktaRegistryId: z.string().nullable().optional(),\n ktaVerifiedOperator: z.boolean().nullable().optional(),\n ktaReputationScore: z.number().min(0).max(5).nullable().optional(),\n ktaFlaggedIssues: z\n .array(\n z.object({\n severity: z.enum(['info', 'warning', 'critical']),\n category: z.string(),\n message: z.string(),\n })\n )\n .nullable()\n .optional(),\n ktaLastFetchedAt: z.string().datetime().nullable().optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Per-upstream project lifecycle (Option A — #1566)\n // Links this upstream to a dedicated Checkpoint project for\n // per-upstream detection, policy, and audit isolation.\n // ─────────────────────────────────────────────────────────────────\n projectId: z.string().uuid().nullable().optional(),\n\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The RESOLVED bare\n // host for this upstream's project — where the Hono gateway points a\n // Delegation challenge's consent_uri / pickup_uri. Forward contract: the\n // wire shape is established here in H1.1; the gateway populates it per\n // upstream from `projects.authorization_host` when its challenge emitter\n // lands (H2.1-WF), resolved out-of-band from `DbGatewayConfigProvider` so\n // that provider keeps its single-query invariant. Never authored by the\n // dashboard. The same resolved value is already live on the per-project\n // policy config the gateway worker fetches (`/api/internal/policies`), which\n // is AUTHORITATIVE — consumers prefer it and treat this copy as a hint.\n authorizationHost: z.string().max(255).nullable().optional(),\n});\n\nexport type UpstreamServer = z.infer<typeof upstreamServerSchema>;\n\n/**\n * Input variant — id/slug optional for new upstreams (auto-generated by PUT\n * handler). Also omits server-managed project ownership and the two\n * server-managed static-headers fields:\n * `staticHeadersEncrypted` (ciphertext — clients never author this\n * directly) and `staticHeaderKeys` (a read-only projection echoed back on\n * GET/PUT responses). The plaintext `staticHeaders` field is intentionally\n * NOT omitted — it's still how the admin form submits new/changed header\n * values; the PUT handler encrypts it before persisting.\n */\nexport const upstreamServerInputSchema = upstreamServerSchema\n .omit({ projectId: true, staticHeadersEncrypted: true, staticHeaderKeys: true })\n .extend({\n id: z.string().uuid().optional(),\n slug: z\n .string()\n .regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/, {\n message:\n 'Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)',\n })\n .optional(),\n });\nexport type UpstreamServerInput = z.infer<typeof upstreamServerInputSchema>;\n\n// ---------------------------------------------------------------------------\n// Upstream Tool Manifest — DB row shape\n// ---------------------------------------------------------------------------\n\n/**\n * Shape of a cached tool manifest row (`upstream_tool_manifests` table).\n * The gateway reads this at runtime to serve org-level `tools/list`\n * without needing a per-user OAuth token — the manifest was captured\n * at add-time using the viewing user's credential, which is the only\n * moment in the flow where per-user auth is available to us.\n *\n * Validated on writes from the dashboard and on reads by the Fly\n * gateway; the table's `tools` column is `jsonb` so nothing DB-side\n * enforces the shape.\n */\nexport const upstreamToolManifestSchema = z\n .object({\n upstreamId: z.string().uuid(),\n orgId: z.string().uuid(),\n tools: z.array(discoveredToolSchema),\n discoveredByUserId: z.string().uuid().nullable().optional(),\n discoveredAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n })\n .strict();\n\nexport type UpstreamToolManifest = z.infer<typeof upstreamToolManifestSchema>;\n\n/**\n * Insert/upsert variant — omits DB-managed timestamps so callers can\n * pass the payload they actually own. The DB defaults `discovered_at`\n * and `updated_at` to `now()` on insert; updates bump `updated_at`\n * explicitly via the write path.\n */\nexport const upstreamToolManifestInputSchema = z\n .object({\n upstreamId: z.string().uuid(),\n orgId: z.string().uuid(),\n tools: z.array(discoveredToolSchema),\n discoveredByUserId: z.string().uuid().nullable().optional(),\n })\n .strict();\n\nexport type UpstreamToolManifestInput = z.infer<typeof upstreamToolManifestInputSchema>;\n\n// ---------------------------------------------------------------------------\n// Gateway Config Schema\n// ---------------------------------------------------------------------------\n\nexport const oauthClientSchema = z.object({\n clientId: z.string().min(1),\n name: z.string().min(1),\n redirectUris: z.array(z.string().url()).min(1),\n});\n\nexport type OAuthClient = z.infer<typeof oauthClientSchema>;\n\n// Defaults for nested config objects — single source of truth to prevent\n// inner-field and outer-object defaults from drifting apart.\nconst DEFAULT_RATE_LIMITS = { toolCallsPerMinute: 600 } as const;\nconst DEFAULT_EXTERNAL_ACCESS = {\n enabled: false,\n allowedDids: [] as string[],\n externalScopes: {} as Record<string, string[]>,\n} as const;\n\nexport const gatewayConfigSchema = z.object({\n enabled: z.boolean().default(false),\n upstreamServers: z.array(upstreamServerSchema).default([]),\n roleScopes: z.record(z.string(), z.array(z.string())).optional(),\n oauthClients: z.array(oauthClientSchema).default([]),\n rateLimits: z\n .object({\n toolCallsPerMinute: z\n .number()\n .int()\n .positive()\n .default(DEFAULT_RATE_LIMITS.toolCallsPerMinute),\n })\n .default(DEFAULT_RATE_LIMITS),\n externalAccess: z\n .object({\n enabled: z.boolean().default(DEFAULT_EXTERNAL_ACCESS.enabled),\n allowedDids: z.array(z.string()).default(DEFAULT_EXTERNAL_ACCESS.allowedDids),\n externalScopes: z\n .record(z.string(), z.array(z.string()))\n .default(DEFAULT_EXTERNAL_ACCESS.externalScopes),\n })\n .default(DEFAULT_EXTERNAL_ACCESS),\n // T6 #2899 M2 — per-org fleet-server endpoint. When set, the gateway's\n // DiscoveryUpstreamProvider injects a synthetic `fleet` upstream so\n // callers can dispatch tools by capability or name (not just raw DID).\n // Validated via `safeUrl` so a misconfigured endpoint targeting\n // private-network IPs cannot become an SSRF pivot.\n fleetEndpoint: safeUrl.optional(),\n});\n\nexport type GatewayConfig = z.infer<typeof gatewayConfigSchema>;\n/** Gateway config input variant for PUT — uses optional id/slug */\nexport const gatewayConfigInputSchema = gatewayConfigSchema.extend({\n upstreamServers: z.array(upstreamServerInputSchema).default([]),\n});\n\n// ---------------------------------------------------------------------------\n// Gateway Tool Call Schema (audit record — mirrors gateway_tool_calls table)\n// ---------------------------------------------------------------------------\n\nexport const gatewayToolCallSchema = z.object({\n id: z.string().uuid(),\n orgId: z.string().uuid(),\n projectId: z.string().uuid().nullable().optional(),\n userId: z.string().uuid().nullable().optional(),\n userEmail: z.string().email(),\n sessionId: z.string().min(1).max(100),\n upstreamId: z.string().uuid(),\n upstreamName: z.string().min(1).max(255),\n toolName: z.string().min(1).max(500),\n prefixedName: z.string().min(1).max(500),\n argsHash: z.string().max(64).nullable().optional(),\n status: z.enum(['success', 'error', 'denied', 'timeout']).default('success'),\n latencyMs: z.number().int().min(0).nullable().optional(),\n errorMessage: z.string().nullable().optional(),\n // Provenance identity (Phase 2, #1979)\n clientDid: z.string().max(500).nullable().optional(),\n clientName: z.string().max(100).nullable().optional(),\n serverDid: z.string().max(500).nullable().optional(),\n agentName: z.string().max(255).nullable().optional(),\n delegationId: z.string().max(255).nullable().optional(),\n attestationHash: z.string().max(64).nullable().optional(),\n verificationMethod: z.string().max(50).nullable().optional(),\n createdAt: z.coerce.date().default(() => new Date()),\n});\n\nexport type GatewayToolCall = z.infer<typeof gatewayToolCallSchema>;\n\n// ---------------------------------------------------------------------------\n// Gateway Connections Summary (derived aggregate over gateway_tool_calls)\n// ---------------------------------------------------------------------------\n\n/**\n * One distinct agent/client observed calling the gateway within the lookback\n * window. Identity is keyed on `clientDid` (canonical) falling back to\n * `agentName` when a client hasn't presented a DID.\n */\nexport const gatewayConnectedAgentSchema = z.object({\n clientDid: z.string().nullable(),\n clientName: z.string().nullable(),\n agentName: z.string().nullable(),\n lastSeenAt: z.coerce.date(),\n callCount: z.number().int().min(1),\n /** Calls carrying an attestation hash — the cryptographically signed subset. */\n verifiedCalls: z.number().int().min(0),\n});\n\nexport type GatewayConnectedAgent = z.infer<typeof gatewayConnectedAgentSchema>;\n\n/**\n * Aggregate of the agents/clients that have connected *in* to an org's gateway\n * over a lookback window, derived from `gateway_tool_calls`. Powers the\n * Connections hub hero (\"agents in\" side) — distinct from the upstream servers\n * the org reaches *out* to (those live in `GatewayConfig.upstreamServers`).\n */\nexport const gatewayConnectionsSummarySchema = z.object({\n orgId: z.string().uuid(),\n windowHours: z.number().int().positive(),\n /** Distinct agents (by clientDid|agentName) active in the window. */\n distinctAgents: z.number().int().min(0),\n /** Total gateway tool calls in the window. */\n totalCalls: z.number().int().min(0),\n agents: z.array(gatewayConnectedAgentSchema),\n});\n\nexport type GatewayConnectionsSummary = z.infer<typeof gatewayConnectionsSummarySchema>;\n","/**\n * Schemas Export\n *\n * Central export point for all Zod schemas\n * These schemas are used for runtime validation across all packages\n *\n * ## Provider Registry Integration\n *\n * As of v0.3.0, provider types are imported from @kya-os/provider-registry\n * to ensure type parity between Checkpoint and KYA-OS. See provider-registry.ts\n * for re-exports and backward compatibility helpers.\n */\n\n// Detection schemas\nexport {\n DetectionInputSchema,\n RequestContextSchema,\n DetectionDetailSchema,\n DetectionResultSchema,\n DetectionModeSchema,\n CustomRuleSchema,\n DetectionOptionsSchema,\n} from '../core/detection';\n\n// Agent schemas\nexport {\n AgentTypeSchema,\n AgentInfoSchema,\n AgentPatternSchema,\n AgentClassificationSchema,\n} from '../core/agent';\n\n// Confidence schemas\nexport {\n ConfidenceLevelSchema,\n ForgeabilityRiskSchema,\n ConfidenceBreakdownSchema,\n} from '../core/confidence';\n\n// API schemas\nexport { BatchDetectionRequestSchema, VerificationRequestSchema } from '../api/request';\n\nexport {\n ApiResponseSchema,\n DetectionResponseSchema,\n BatchDetectionResponseSchema,\n VerificationResponseSchema,\n HealthResponseSchema,\n StatsResponseSchema,\n} from '../api/response';\n\n// Internal API schemas\nexport {\n CreateApiKeySchema,\n UpdateApiKeySchema,\n CreateOrganizationSchema,\n UpdateOrganizationSchema,\n CreateProjectSchema,\n UpdateProjectSchema,\n AnalyticsQuerySchema,\n ApiKeysQuerySchema,\n ProjectsQuerySchema,\n PixelsQuerySchema,\n ProjectIdSchema,\n ExportAnalyticsSchema,\n} from '../api/internal';\n\n// Event schemas\nexport {\n MouseEventSchema,\n KeyboardEventSchema,\n ScrollEventSchema,\n ClickEventSchema,\n TouchEventSchema,\n BehavioralDataSchema,\n BehavioralAnalysisSchema,\n} from '../events/behavioral';\n\nexport {\n RealtimeEventTypeSchema,\n RealtimeEventSchema,\n DetectionEventSchema,\n BlockEventSchema,\n StatsUpdateEventSchema,\n} from '../events/realtime';\n\n// Entity schemas\nexport {\n UserPlanSchema,\n ApiKeyPermissionSchema,\n UserSchema,\n ProjectSettingsSchema,\n ProjectSchema,\n PixelConfigurationSchema,\n PixelSchema,\n PixelStatsSchema,\n ApiKeyRateLimitsSchema,\n ApiKeySchema,\n DetectionLogSchema,\n SessionSchema,\n AccountSchema,\n VerificationTokenSchema,\n} from '../types/entities';\n\n// Pixel schemas\nexport {\n PixelTrackingRequestSchema,\n PixelTrackingResponseSchema,\n PixelVerificationStatusSchema,\n} from '../types/pixel';\n\n// Auth schemas\nexport {\n passwordSchema,\n signInSchema,\n signUpSchema,\n forgotPasswordSchema,\n resetPasswordSchema,\n changePasswordSchema,\n verifyEmailSchema,\n type SignInData,\n type SignUpData,\n type ForgotPasswordData,\n type ResetPasswordData,\n type ChangePasswordData,\n type VerifyEmailData,\n} from './auth';\n\n// Admin schemas\nexport {\n PerformanceRecalculationRequestSchema,\n GrowthOpportunityUpdateSchema,\n GrowthBatchRequestSchema,\n GrowthConfigurationThresholdsSchema,\n GrowthConfigurationUpdateSchema,\n GrowthConfigurationResetSchema,\n AdminQueryParamsSchema,\n GrowthOpportunitiesQuerySchema,\n RecommendationQuerySchema,\n RecommendationGenerationSchema,\n type PerformanceRecalculationRequest,\n type GrowthOpportunityUpdate,\n type GrowthBatchRequest,\n type GrowthConfigurationThresholds,\n type GrowthConfigurationUpdate,\n type GrowthConfigurationReset,\n type AdminQueryParams,\n type GrowthOpportunitiesQuery,\n type RecommendationQuery,\n type RecommendationGeneration,\n} from './admin';\n\n// Bouncer schemas\nexport {\n OAuthProviderTypeSchema,\n OAuthConnectionStatusSchema,\n OAuthModeSchema,\n ScopeSchema,\n CRISPBudgetSchema,\n BouncerConfigSchema,\n UpdateBouncerConfigSchema,\n RefreshScopesRequestSchema,\n DelegationStatusSchema,\n DelegationSchema,\n BouncerOutcomeSchema,\n BouncerProofSchema,\n DelegationPollingStatusSchema,\n OAuthProviderMetadataSchema,\n ProvidersResponseSchema,\n OAuthTokensResponseSchema,\n // Multi-provider OAuth types (CRED-001)\n AuthProviderTypeSchema,\n BaseAuthProviderSchema,\n OAuth2ProviderSchema,\n CredentialProviderSchema,\n ConfiguredProviderSchema,\n OAuthProvidersMapSchema,\n AddUpdateProviderRequestSchema,\n // Provider Definition (Provider Registry aligned)\n ProviderDefinitionSchema,\n // Consent schemas (CRED-002)\n ConsentBrandingSchema,\n ConsentTermsSchema,\n ConsentUISchema,\n ConsentConfigSchema,\n ConsentConfigMetadataSchema,\n ConsentCapabilitySchema,\n ConsentCapabilityGroupSchema,\n ConsentAgentMetadataSchema,\n ConsentInputCopySchema,\n ConsentSignInCopySchema,\n ConsentScopeLabelsSchema,\n ToolConsentOverridesSchema,\n // Format conversion helpers (Provider Registry <-> Checkpoint)\n toProviderRegistryFormat,\n fromProviderRegistryFormat,\n fromProviderRegistryFormatSafe,\n isSupportedAuthType,\n mapLegacyAuthType,\n mapToLegacyAuthType,\n type SupportedProviderAuthType,\n type OAuthProviderType,\n type OAuthConnectionStatus,\n type OAuthMode,\n type Scope,\n type CRISPBudget,\n type BouncerConfig,\n type UpdateBouncerConfig,\n type RefreshScopesRequest,\n type DelegationStatus,\n type Delegation,\n type BouncerOutcome,\n type BouncerProof,\n type DelegationPollingStatus,\n type OAuthProviderMetadata,\n type ProvidersResponse,\n type OAuthTokensResponse,\n // Multi-provider OAuth types (CRED-001)\n type AuthProviderType,\n type AuthProviderTypeInput,\n type LegacyAuthProviderType,\n type BaseAuthProvider,\n type OAuth2Provider,\n type CredentialProvider,\n type ConfiguredProvider,\n type OAuthProvidersMap,\n type AddUpdateProviderRequest,\n // Provider Definition types\n type ProviderDefinition,\n type ProviderRegistryDefinition,\n // Canonical types from provider-registry\n type ProviderAuthType,\n type ConsentProviderType,\n // Consent types (CRED-002)\n type ConsentBranding,\n type ConsentTerms,\n type ConsentUI,\n type ConsentConfig,\n type ConsentConfigMetadata,\n type ConsentCapability,\n type ConsentCapabilityGroup,\n type ConsentAgentMetadata,\n type ConsentSignInCopy,\n type ToolConsentOverrides,\n} from './bouncer';\n\n// Consent policy endpoint\nexport {\n ConsentPolicyRiskLevelSchema,\n ConsentPolicyCapabilitySchema,\n ConsentPolicyResponseSchema,\n type ConsentPolicyRiskLevel,\n type ConsentPolicyResponse,\n} from './consent-policy-endpoint';\n\n// Gateway schemas\nexport {\n SLUG_REGEX,\n safeUrl,\n isPrivateOrReservedHost,\n upstreamServerSchema,\n oauthClientSchema,\n gatewayConfigSchema,\n gatewayConfigInputSchema,\n upstreamServerInputSchema,\n gatewayToolCallSchema,\n gatewayConnectedAgentSchema,\n gatewayConnectionsSummarySchema,\n type UpstreamServer,\n type OAuthClient,\n type GatewayConfig,\n type GatewayToolCall,\n type GatewayConnectedAgent,\n type GatewayConnectionsSummary,\n} from './gateway';\n\n// Provider Registry exports (canonical types from @kya-os/provider-registry)\n// NOTE: Runtime registry (defaultProviderRegistry) should be imported directly\n// from @kya-os/provider-registry in server-side code to avoid bundling issues.\n// The registry's runtime values are on `@kya-os/checkpoint-shared/provider-registry`.\nexport {\n AUTHORIZATION_MODES,\n type AuthMode,\n type AuthorizationMode,\n // Type definitions for registry (runtime should be imported directly)\n type IProviderRegistry,\n type RegistryLogger,\n // Canonical config types\n type OAuthProviderConfig,\n type CredentialProviderConfig,\n type ProviderConfig,\n} from './provider-registry';\n\n/**\n * Schema validation utilities\n */\nimport { z } from 'zod';\n\n/**\n * Validate data against a schema\n */\nexport function validate<T>(\n schema: z.ZodSchema<T>,\n data: unknown\n): { success: true; data: T } | { success: false; error: z.ZodError } {\n const result = schema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, error: result.error };\n}\n\n/**\n * Validate and throw on error\n */\nexport function validateOrThrow<T>(schema: z.ZodSchema<T>, data: unknown): T {\n return schema.parse(data);\n}\n\n/**\n * Create a partial schema (all fields optional)\n */\nexport function partial<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.partial();\n}\n\n/**\n * Create a strict schema (no additional properties)\n */\nexport function strict<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.strict();\n}\n","/**\n * Analytics Schemas\n *\n * Schemas for analytics API endpoints\n * Used for validation and type safety in analytics routes\n */\n\nimport { z } from 'zod';\n\n/**\n * Base Analytics Query Schema\n * Extended by specific analytics endpoints\n */\nexport const AnalyticsQuerySchema = z.object({\n duration: z.enum(['week', 'month', 'quarter', 'year']).optional().default('week'),\n groupBy: z.enum(['day', 'hour', 'week', 'month']).optional().default('day'),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n});\nexport type AnalyticsQuery = z.infer<typeof AnalyticsQuerySchema>;\n\n/**\n * Sessions Analytics Query Schema\n * Used for session-specific analytics endpoints\n */\nexport const AnalyticsSessionsQuerySchema = z.object({\n duration: z.enum(['week', 'month']).optional().default('week'),\n groupBy: z.enum(['day', 'hour']).optional().default('day'),\n});\nexport type AnalyticsSessionsQuery = z.infer<typeof AnalyticsSessionsQuerySchema>;\n\n/**\n * Agent Sources Analytics Query Schema\n * Used for agent source analytics endpoints\n */\nexport const AnalyticsAgentSourcesQuerySchema = z.object({\n duration: z.enum(['week', 'month', 'quarter']).optional().default('week'),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n sortBy: z.enum(['count', 'name', 'confidence']).optional().default('count'),\n order: z.enum(['asc', 'desc']).optional().default('desc'),\n});\nexport type AnalyticsAgentSourcesQuery = z.infer<typeof AnalyticsAgentSourcesQuerySchema>;\n\n/**\n * Agent Types Analytics Query Schema\n * Used for agent type analytics endpoints\n */\nexport const AnalyticsAgentTypesQuerySchema = z.object({\n duration: z.enum(['week', 'month', 'quarter']).optional().default('week'),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n includeRaw: z.coerce.boolean().optional().default(false),\n});\nexport type AnalyticsAgentTypesQuery = z.infer<typeof AnalyticsAgentTypesQuerySchema>;\n\n/**\n * Analytics Export Query Schema\n * Used for data export endpoints\n */\nexport const AnalyticsExportQuerySchema = z.object({\n format: z.enum(['csv', 'json', 'excel']).optional().default('csv'),\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n includeMetadata: z.coerce.boolean().optional().default(false),\n includeRawData: z.coerce.boolean().optional().default(false),\n});\nexport type AnalyticsExportQuery = z.infer<typeof AnalyticsExportQuerySchema>;\n\n/**\n * Real-time Analytics Query Schema\n * Used for real-time analytics endpoints\n */\nexport const AnalyticsRealtimeQuerySchema = z.object({\n timeWindow: z.enum(['1h', '6h', '24h']).optional().default('1h'),\n refreshInterval: z.coerce.number().min(5).max(300).optional().default(30), // seconds\n});\nexport type AnalyticsRealtimeQuery = z.infer<typeof AnalyticsRealtimeQuerySchema>;\n\n/**\n * Analytics Time Series Data Schema\n * Response schema for time series data\n */\nexport const AnalyticsTimeSeriesSchema = z.object({\n timestamp: z.string().datetime(),\n totalDetections: z.number().nonnegative(),\n agentDetections: z.number().nonnegative(),\n humanDetections: z.number().nonnegative(),\n uniqueSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n});\nexport type AnalyticsTimeSeries = z.infer<typeof AnalyticsTimeSeriesSchema>;\n\n/**\n * Analytics Summary Stats Schema\n * Response schema for summary statistics\n */\nexport const AnalyticsSummarySchema = z.object({\n totalAgentDetections: z.number().nonnegative(),\n totalDetections: z.number().nonnegative(),\n uniqueAgentSessions: z.number().nonnegative(),\n totalSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n agentDetectionsChange: z.number(),\n agentDetectionsChangeCount: z.number(),\n totalDetectionsChange: z.number(),\n totalDetectionsChangeCount: z.number(),\n agentSessionsChange: z.number(),\n agentSessionsChangeCount: z.number(),\n});\nexport type AnalyticsSummary = z.infer<typeof AnalyticsSummarySchema>;\n\n/**\n * Analytics Chart Data Schema\n * Response schema for chart data points\n */\nexport const AnalyticsChartDataSchema = z.object({\n month: z.string(), // Display label (e.g., \"Jan 15\", \"3 PM\")\n timestamp: z.string().datetime(),\n agentDetections: z.number().nonnegative(),\n totalDetections: z.number().nonnegative(),\n humanDetections: z.number().nonnegative(),\n uniqueSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n});\nexport type AnalyticsChartData = z.infer<typeof AnalyticsChartDataSchema>;\n\n/**\n * Analytics Sessions Response Schema\n * Complete response schema for sessions analytics\n */\nexport const AnalyticsSessionsResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n chartData: z.array(AnalyticsChartDataSchema),\n stats: AnalyticsSummarySchema,\n period: z.enum(['week', 'month']),\n dateRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n }),\n});\nexport type AnalyticsSessionsResponse = z.infer<typeof AnalyticsSessionsResponseSchema>;\n\n/**\n * Agent Type Distribution Schema\n * Used for agent type analytics\n */\nexport const AgentTypeDistributionSchema = z.object({\n agentType: z.string(),\n count: z.number().nonnegative(),\n uniqueSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n percentage: z.number().min(0).max(100),\n});\nexport type AgentTypeDistribution = z.infer<typeof AgentTypeDistributionSchema>;\n\n/**\n * Agent Source Distribution Schema\n * Used for agent source analytics\n */\nexport const AgentSourceDistributionSchema = z.object({\n source: z.string(),\n count: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n percentage: z.number().min(0).max(100),\n userAgents: z.array(z.string()).optional(),\n});\nexport type AgentSourceDistribution = z.infer<typeof AgentSourceDistributionSchema>;\n\n/**\n * Confidence Distribution Schema\n * Used for confidence distribution analytics\n */\nexport const ConfidenceDistributionSchema = z.object({\n range: z.string(), // e.g., \"0.8-0.9\", \"0.9-1.0\"\n count: z.number().nonnegative(),\n percentage: z.number().min(0).max(100),\n});\nexport type ConfidenceDistribution = z.infer<typeof ConfidenceDistributionSchema>;\n","/**\n * Rule Validation Schemas\n *\n * Zod schemas for runtime validation of detection rules\n * Ensures rule integrity at build time and runtime\n */\n\nimport { z } from 'zod';\n\n/**\n * User agent rule schema\n */\nexport const UserAgentRuleSchema = z.object({\n patterns: z.array(z.string().min(1)).min(1),\n confidence: z.number().min(0).max(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n});\n\n/**\n * IP range rule schema\n */\nexport const IpRangeRuleSchema = z.object({\n ranges: z.array(z.string().regex(/^(\\d{1,3}\\.){3}\\d{1,3}\\/\\d{1,2}$/)).min(1),\n confidence: z.number().min(0).max(1),\n provider: z.string().optional(),\n lastUpdated: z.string().optional(),\n});\n\n/**\n * Signature rule schema\n */\nexport const SignatureRuleSchema = z.object({\n publicKey: z.string().min(1),\n algorithm: z.enum([\n 'RS256',\n 'RS384',\n 'RS512',\n 'HS256',\n 'HS384',\n 'HS512',\n 'ES256',\n 'ES384',\n 'ES512',\n ]),\n headerName: z.string().min(1),\n confidence: z.number().min(0).max(1),\n issuer: z.string().optional(),\n});\n\n/**\n * Behavioral threshold schema\n */\nexport const BehavioralThresholdSchema = z.object({\n minTimeOnPage: z.number().min(0).optional(),\n maxRequestsPerSecond: z.number().min(0).optional(),\n minMouseMovements: z.number().min(0).optional(),\n minKeyboardEvents: z.number().min(0).optional(),\n maxScrollVariance: z.number().min(0).optional(),\n timeWindow: z.number().min(0).optional(),\n});\n\n/**\n * Behavioral pattern schema\n */\nexport const BehavioralPatternSchema = z.object({\n name: z.string().min(1),\n type: z.enum(['rapid_requests', 'no_interaction', 'perfect_scrolling', 'sequential_access']),\n config: z.record(z.string(), z.any()),\n confidenceModifier: z.number().min(-1).max(1),\n});\n\n/**\n * Behavioral rules schema\n */\nexport const BehavioralRulesSchema = z.object({\n thresholds: BehavioralThresholdSchema,\n patterns: z.array(BehavioralPatternSchema).optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Header rule schema\n */\nexport const HeaderRuleSchema = z.object({\n name: z.string().min(1),\n pattern: z.string().optional(),\n required: z.boolean().optional(),\n suspiciousIfMissing: z.boolean().optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Header rules schema\n */\nexport const HeaderRulesSchema = z.object({\n suspicious: z.array(HeaderRuleSchema),\n required: z.array(HeaderRuleSchema),\n forbidden: z.array(HeaderRuleSchema).optional(),\n});\n\n/**\n * IP range collection schema\n * Flexible to handle both old (with providers) and new (direct) structures\n */\nexport const IpRangeCollectionSchema = z.union([\n // Old structure with providers\n z.object({\n providers: z.record(z.string(), IpRangeRuleSchema),\n updateUrl: z.string().url().optional(),\n updateFrequency: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n cacheDuration: z.number().min(0).optional(),\n }),\n // New merged structure - IP ranges directly as properties\n z.record(z.string(), IpRangeRuleSchema).refine(\n (val) => {\n // Ensure at least one valid IP range entry exists\n return Object.values(val).some(\n (v) => v && typeof v === 'object' && 'ranges' in v && Array.isArray(v.ranges)\n );\n },\n { message: 'At least one valid IP range entry required' }\n ),\n]);\n\n/**\n * Complete detection rules schema\n */\nexport const DetectionRulesSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n lastUpdated: z.string(),\n metadata: z\n .object({\n author: z.string().optional(),\n description: z.string().optional(),\n minVersion: z.string().optional(),\n source: z.string().optional(),\n })\n .optional(),\n rules: z.object({\n userAgents: z.record(z.string(), UserAgentRuleSchema),\n ipRanges: IpRangeCollectionSchema,\n signatures: z.record(z.string(), SignatureRuleSchema),\n behavioral: BehavioralRulesSchema,\n headers: HeaderRulesSchema,\n }),\n});\n\n/**\n * Rule load options schema\n */\nexport const RuleLoadOptionsSchema = z.object({\n /** @deprecated Refused at runtime; see `RuleLoader.loadRules`. */\n cdnUrl: z.string().url().optional(),\n forceRefresh: z.boolean().optional(),\n cacheDuration: z.number().min(0).optional(),\n validationMode: z.enum(['strict', 'loose', 'none']).optional(),\n});\n\n/**\n * Rule validation result schema\n */\nexport const RuleValidationResultSchema = z.object({\n valid: z.boolean(),\n errors: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n type: z.string(),\n })\n )\n .optional(),\n warnings: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n })\n )\n .optional(),\n});\n\n/**\n * Rule update event schema\n */\nexport const RuleUpdateEventSchema = z.object({\n previousVersion: z.string(),\n newVersion: z.string(),\n timestamp: z.string(),\n changes: z\n .object({\n added: z.array(z.string()),\n modified: z.array(z.string()),\n removed: z.array(z.string()),\n })\n .optional(),\n});\n\n/**\n * Rule match result schema\n */\nexport const RuleMatchResultSchema = z.object({\n matched: z.boolean(),\n rule: z.string().optional(),\n category: z.enum(['userAgent', 'ipRange', 'signature', 'behavioral', 'header']).optional(),\n confidence: z.number().min(0).max(1).optional(),\n details: z.record(z.string(), z.any()).optional(),\n});\n\n/**\n * Type exports inferred from schemas\n */\nexport type UserAgentRule = z.infer<typeof UserAgentRuleSchema>;\nexport type IpRangeRule = z.infer<typeof IpRangeRuleSchema>;\nexport type SignatureRule = z.infer<typeof SignatureRuleSchema>;\nexport type BehavioralThreshold = z.infer<typeof BehavioralThresholdSchema>;\nexport type BehavioralPattern = z.infer<typeof BehavioralPatternSchema>;\nexport type BehavioralRules = z.infer<typeof BehavioralRulesSchema>;\nexport type HeaderRule = z.infer<typeof HeaderRuleSchema>;\nexport type HeaderRules = z.infer<typeof HeaderRulesSchema>;\nexport type IpRangeCollection = z.infer<typeof IpRangeCollectionSchema>;\nexport type DetectionRules = z.infer<typeof DetectionRulesSchema>;\nexport type RuleLoadOptions = z.infer<typeof RuleLoadOptionsSchema>;\nexport type RuleValidationResult = z.infer<typeof RuleValidationResultSchema>;\nexport type RuleUpdateEvent = z.infer<typeof RuleUpdateEventSchema>;\nexport type RuleMatchResult = z.infer<typeof RuleMatchResultSchema>;\n\n/**\n * Validate detection rules\n */\nexport function validateRules(rules: unknown): RuleValidationResult {\n try {\n DetectionRulesSchema.parse(rules);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n type: e.code,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: '',\n message: 'Unknown validation error',\n type: 'unknown',\n },\n ],\n };\n }\n}\n\n/**\n * Validate and parse rules with type safety\n */\nexport function parseRules(rules: unknown): DetectionRules {\n return DetectionRulesSchema.parse(rules);\n}\n\n/**\n * Validate rules with loose mode (allows extra fields)\n */\nexport function validateRulesLoose(rules: unknown): RuleValidationResult {\n try {\n DetectionRulesSchema.passthrough().parse(rules);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n type: e.code,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: '',\n message: 'Unknown validation error',\n type: 'unknown',\n },\n ],\n };\n }\n}\n","/**\n * Rule Validator\n *\n * Validates detection rules against schemas\n */\n\nimport { z } from 'zod';\nimport { DetectionRulesSchema, validateRules, validateRulesLoose } from '../schemas/rules';\nimport { DetectionRules, RuleValidationResult } from '../types/rules';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Rule validation utilities\n */\nexport class RuleValidator {\n /**\n * Validate rules with specified mode\n */\n static validate(\n rules: unknown,\n mode: 'strict' | 'loose' | 'none' = 'strict'\n ): RuleValidationResult {\n switch (mode) {\n case 'strict':\n return validateRules(rules);\n case 'loose':\n return validateRulesLoose(rules);\n case 'none':\n return { valid: true };\n default:\n return validateRules(rules);\n }\n }\n\n /**\n * Validate and throw on error\n */\n static validateOrThrow(\n rules: unknown,\n mode: 'strict' | 'loose' | 'none' = 'strict'\n ): DetectionRules {\n const result = this.validate(rules, mode);\n\n if (!result.valid) {\n const errors = result.errors?.map((e) => `${e.path}: ${e.message}`).join(', ');\n throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);\n }\n\n return rules as DetectionRules;\n }\n\n /**\n * Parse and validate rules\n */\n static parse(rules: unknown): DetectionRules {\n try {\n return DetectionRulesSchema.parse(rules);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errors = error.issues.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ');\n throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if rules are valid\n */\n static isValid(rules: unknown): boolean {\n return this.validate(rules).valid;\n }\n\n /**\n * Validate rule version compatibility\n */\n static validateVersion(rules: DetectionRules, minVersion: string): boolean {\n const [ruleMajor, ruleMinor, rulePatch] = rules.version.split('.').map(Number);\n const [minMajor, minMinor, minPatch] = minVersion.split('.').map(Number);\n\n if (ruleMajor > minMajor) return true;\n if (ruleMajor < minMajor) return false;\n\n if (ruleMinor > minMinor) return true;\n if (ruleMinor < minMinor) return false;\n\n return rulePatch >= minPatch;\n }\n\n /**\n * Validate confidence scores\n */\n static validateConfidenceScores(rules: DetectionRules): boolean {\n // Check user agent confidence scores\n for (const rule of Object.values(rules.rules.userAgents)) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check IP range confidence scores\n // Handle both old (with providers) and new (direct) structures\n const ipRanges =\n 'providers' in rules.rules.ipRanges ? rules.rules.ipRanges.providers : rules.rules.ipRanges;\n\n for (const rule of Object.values(ipRanges)) {\n // Skip non-rule entries\n if (!rule || typeof rule !== 'object' || !('confidence' in rule)) continue;\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check signature confidence scores\n for (const rule of Object.values(rules.rules.signatures)) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check behavioral confidence\n if (rules.rules.behavioral.confidence < 0 || rules.rules.behavioral.confidence > 1) {\n return false;\n }\n\n // Check header confidence scores\n for (const rule of [...rules.rules.headers.suspicious, ...rules.rules.headers.required]) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Get validation errors as formatted string\n */\n static formatErrors(result: RuleValidationResult): string {\n if (result.valid) {\n return '';\n }\n\n const errors = result.errors || [];\n return errors.map((e) => ` - ${e.path}: ${e.message}`).join('\\n');\n }\n\n /**\n * Get validation warnings as formatted string\n */\n static formatWarnings(result: RuleValidationResult): string {\n const warnings = result.warnings || [];\n return warnings.map((w) => ` - ${w.path}: ${w.message}`).join('\\n');\n }\n}\n","","/**\n * Rule Loader\n *\n * Loads the detection rules compiled into the package.\n * NO FALLBACKS - Fail fast if rules cannot be loaded\n *\n * Remote rule delivery is not done here. Rules fetched over the network are\n * only accepted when a signature verifies against keys compiled into the\n * engine.\n */\n\nimport { DetectionRules, RuleLoadOptions } from '../types/rules';\nimport { RuleValidator } from './rule-validator';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Rule loader class - Singleton pattern\n */\nexport class RuleLoader {\n private static instance: RuleLoader | null = null;\n private rules: DetectionRules | null = null;\n\n /**\n * Private constructor for singleton\n */\n private constructor() {}\n\n /**\n * Get singleton instance\n */\n static getInstance(): RuleLoader {\n if (!this.instance) {\n this.instance = new RuleLoader();\n }\n return this.instance;\n }\n\n /**\n * Load rules synchronously from bundled JSON\n * This is the primary method for middleware packages\n * NO FALLBACKS - If this fails, the package should not work\n */\n static loadSync(): DetectionRules {\n try {\n // Load compiled rules - FAIL FAST if missing\n // NO fallback to prevent using stale/buggy rules\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const rules = require('../data/compiled/merged-rules.json');\n\n // Validate the rules - fail fast if invalid\n const validated = RuleValidator.validateOrThrow(rules, 'strict');\n\n return validated;\n } catch (error) {\n // NO FALLBACK - Fail immediately\n throw new Error(\n `${RULE_ERRORS.LOAD_FAILED}: Cannot load detection rules from merged-rules.json. ` +\n `This is likely a package build issue - run 'npm run compile-rules' to regenerate. ` +\n `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n /**\n * Load the bundled rules, memoised for the life of the loader.\n *\n * A `cdnUrl` is refused: schema validation alone would accept any\n * well-formed document from whoever controls the URL.\n */\n async loadRules(options: RuleLoadOptions = {}): Promise<DetectionRules> {\n if (options.cdnUrl !== undefined) {\n throw new Error(\n `${RULE_ERRORS.LOAD_FAILED}: cdnUrl is not supported; unsigned remote rules are not ` +\n `accepted. Use a signed rule bundle.`\n );\n }\n if (options.forceRefresh || !this.rules) {\n this.rules = RuleLoader.loadSync();\n }\n return this.rules;\n }\n\n /**\n * Get current loaded rules\n */\n getRules(): DetectionRules | null {\n return this.rules;\n }\n\n /**\n * Clear the memoised rules\n */\n clearCache(): void {\n this.rules = null;\n }\n\n /**\n * Reset singleton instance (mainly for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearCache();\n this.instance = null;\n }\n }\n}\n\n// `loadRulesSync` convenience function was removed in Phase-D.8.\n// All consumers now call `RuleLoader.loadSync()` directly. The class\n// surface didn't change.\n\n/**\n * Export convenience function for async loading\n */\nexport async function loadRulesAsync(options?: RuleLoadOptions): Promise<DetectionRules> {\n const loader = RuleLoader.getInstance();\n return loader.loadRules(options);\n}\n","/**\n * Rule Parser\n *\n * Parses YAML/JSON rule definitions\n */\n\nimport * as yaml from 'js-yaml';\nimport { DetectionRules } from '../types/rules';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Parse rule content (YAML or JSON)\n */\nexport class RuleParser {\n /**\n * Parse rule content from string\n */\n static parse(content: string): DetectionRules {\n if (!content || content.trim().length === 0) {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n\n // Try to detect format\n const trimmed = content.trim();\n\n try {\n // Try JSON first (faster)\n if (trimmed.startsWith('{')) {\n return JSON.parse(trimmed);\n }\n\n // Try YAML\n const parsed = yaml.load(trimmed);\n\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n\n return parsed as DetectionRules;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n // Format error message to match test expectations\n if (\n errorMessage.includes('JSON') ||\n errorMessage.includes('Unexpected') ||\n errorMessage.includes('Expected')\n ) {\n throw new Error('Parse failed: Invalid JSON');\n }\n throw new Error(`Parse failed: ${errorMessage}`);\n }\n }\n\n /**\n * Parse JSON rules\n */\n static parseJSON(content: string): DetectionRules {\n try {\n return JSON.parse(content);\n } catch (error) {\n throw new Error('Parse failed: Invalid JSON');\n }\n }\n\n /**\n * Parse YAML rules\n */\n static parseYAML(content: string): DetectionRules {\n try {\n const parsed = yaml.load(content);\n // Check if parsed result is a plain object (not array, string, number, etc.)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n return parsed as DetectionRules;\n } catch (error) {\n // If we threw INVALID_FORMAT, re-throw it\n if (error instanceof Error && error.message === RULE_ERRORS.INVALID_FORMAT) {\n throw error;\n }\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n // Format error message to match test expectations\n if (\n errorMessage.includes('unknown escape sequence') ||\n errorMessage.includes('YAML') ||\n errorMessage.includes('bad indentation')\n ) {\n throw new Error('Parse failed: Invalid YAML');\n }\n throw new Error('Parse failed: Invalid YAML');\n }\n }\n\n /**\n * Convert rules to JSON string\n */\n static toJSON(rules: DetectionRules, pretty = false): string {\n return JSON.stringify(rules, null, pretty ? 2 : 0);\n }\n\n /**\n * Convert rules to YAML string\n */\n static toYAML(rules: DetectionRules): string {\n return yaml.dump(rules, {\n indent: 2,\n lineWidth: -1,\n noRefs: true,\n sortKeys: false,\n });\n }\n\n /**\n * Validate basic rule structure\n */\n static validateStructure(rules: unknown): boolean {\n if (!rules || typeof rules !== 'object') return false;\n const candidate = rules as Record<string, unknown>;\n return !!(\n typeof candidate.version === 'string' &&\n typeof candidate.lastUpdated === 'string' &&\n candidate.rules &&\n typeof candidate.rules === 'object'\n );\n }\n}\n","/**\n * vendor-range-freshness.ts (checkpoint P35).\n *\n * Independent staleness gate for the AIVF-1 vendor IP-range catalogue\n * (`packages/checkpoint-rules/data/agent-types.yaml`). Deliberately\n * decoupled from `scripts/refresh-ai-vendor-ips.ts`'s own exit-code\n * contract: that script exits 1 only when EVERY enabled vendor's fetch\n * fails in a single run (a runner-side incident signal), so one vendor\n * that has been failing quietly for weeks — DNS drift, a moved feed URL,\n * a persistent 403 — never fails the job as long as the other rows keep\n * succeeding. This module checks the RESULT (how long since we last\n * successfully checked this vendor) rather than the process (did today's\n * fetch succeed), so it catches the failure mode the exit code can't see.\n *\n * This is the same shape of defect that let the Tier-1 OpenAI signing-key\n * pin (rust/crates/kya-os-engine/data/vendor-keys/openai.json) sit\n * expired for ~2 months: a refresh script existed, nothing ran it on a\n * schedule, and nothing alarmed when the pinned data went stale. See that\n * file's `_meta.comment` for the incident this module exists to prevent\n * from recurring here.\n *\n * Reads `ip_feed.last_checked`, NOT `ip_feed.last_refreshed`. Those two\n * fields answer different questions — `last_refreshed` is the VENDOR's\n * own `creationTime` for the data currently stored (can legitimately sit\n * unchanged for months on a vendor whose prefix list simply hasn't\n * moved), while `last_checked` is the RUNNER's wall clock, stamped on\n * every successful evaluation regardless of whether the data changed.\n * An earlier version of this module read `last_refreshed`, which made\n * every low-churn vendor read as permanently stale even on a perfectly\n * healthy refresh cadence (Cursor Bugbot finding on the PR that\n * introduced this gate — fixed before merge, kept here as the\n * cautionary note for why this distinction matters).\n */\n\nexport interface VendorFreshnessInput {\n id: string;\n /** Vendor rows with `enabled === false` are skipped — they aren't refreshed, so their age is expected and not an incident. */\n enabled?: boolean;\n /** The vendor's `ip_feed.last_checked` value (runner wall clock, stamped on every successful check — see file header for why this is NOT `last_refreshed`), in whatever ISO-ish shape agent-types.yaml stores (with or without a `Z`/offset). A missing/empty value is treated as unparseable, i.e. maximally stale — see `findStaleVendorRanges`. */\n lastCheckedIso: string;\n}\n\nexport interface StaleVendorDetail {\n id: string;\n lastCheckedIso: string;\n /** Milliseconds between `now` and the parsed `lastCheckedIso`. `Infinity` when the timestamp couldn't be parsed at all. */\n ageMs: number;\n}\n\n// Daily cron cadence (see .github/workflows/refresh-ai-vendor-ips.yml) plus\n// a 3-day grace window: one missed run shouldn't page anyone, but three in\n// a row — or one vendor silently failing for that long — should.\nexport const DEFAULT_MAX_VENDOR_RANGE_AGE_MS = 4 * 24 * 60 * 60 * 1000;\n\n/**\n * Returns every ENABLED vendor whose `lastCheckedIso` is older than\n * `maxAgeMs`. An unparseable (or missing/empty) timestamp is treated as\n * maximally stale (`ageMs: Infinity`) rather than skipped — a row this\n * module can't prove is fresh must never be reported as fresh; failing\n * closed toward alarming is the whole point of this module (see file\n * header).\n */\nexport function findStaleVendorRanges(\n vendors: VendorFreshnessInput[],\n now: Date,\n maxAgeMs: number = DEFAULT_MAX_VENDOR_RANGE_AGE_MS\n): StaleVendorDetail[] {\n const stale: StaleVendorDetail[] = [];\n for (const v of vendors) {\n if (v.enabled === false) continue;\n\n const parsedMs = Date.parse(v.lastCheckedIso);\n const ageMs = Number.isNaN(parsedMs) ? Infinity : now.getTime() - parsedMs;\n\n if (ageMs > maxAgeMs) {\n stale.push({ id: v.id, lastCheckedIso: v.lastCheckedIso, ageMs });\n }\n }\n return stale;\n}\n\nexport class StaleVendorRangesError extends Error {\n constructor(readonly stale: StaleVendorDetail[]) {\n const detail = stale\n .map((s) => {\n const age =\n s.ageMs === Infinity\n ? `unparseable/missing last_checked (${JSON.stringify(s.lastCheckedIso)})`\n : `${(s.ageMs / (24 * 60 * 60 * 1000)).toFixed(1)}d old`;\n return `${s.id} (${age})`;\n })\n .join(', ');\n super(\n `${stale.length} vendor range set(s) exceeded the staleness threshold and must not be ` +\n `served quietly: ${detail}. Refresh has stopped keeping up for these vendors — ` +\n `investigate scripts/refresh-ai-vendor-ips.ts's recent runs before treating the ` +\n `existing data as trustworthy.`\n );\n this.name = 'StaleVendorRangesError';\n }\n}\n\n/**\n * Throws `StaleVendorRangesError` when any enabled vendor's range set is\n * older than `maxAgeMs`. This is the \"raise rather than serve quietly\"\n * half of the contract — callers that need a hard stop (the CI freshness\n * gate in scripts/check-vendor-ranges-freshness.ts) call this directly;\n * a caller on a hot request path that must never throw (e.g. a future\n * runtime consumer) should use `findStaleVendorRanges` and log instead.\n */\nexport function assertVendorRangesFresh(\n vendors: VendorFreshnessInput[],\n now: Date,\n maxAgeMs: number = DEFAULT_MAX_VENDOR_RANGE_AGE_MS\n): void {\n const stale = findStaleVendorRanges(vendors, now, maxAgeMs);\n if (stale.length > 0) {\n throw new StaleVendorRangesError(stale);\n }\n}\n","import {\n PROBE_CLASSES,\n lacksBaselinePermit,\n statementId,\n unnarrowedDenyStatements,\n} from './cedar-principal-scope';\nimport { NO_EVIDENCE_CATEGORY, NO_EVIDENCE_EXCLUSION_TERM } from './legacy-carve-out';\n\nexport interface LintFinding {\n ruleId?: string;\n line: number;\n message: string;\n}\n\nconst NARROW_ADVICE =\n 'Add a `principal.category == \"ai_agent\"` (or `principal.name`) condition, or confirm you intend to affect them.';\nconst EVERYONE_MESSAGE = `This rule denies every visitor, including humans and ${NO_EVIDENCE_CATEGORY} visitors, because it does not narrow the principal. ${NARROW_ADVICE}`;\nconst HUMAN_MESSAGE = `This rule denies human visitors because it does not narrow the principal. ${NARROW_ADVICE}`;\nconst NO_EVIDENCE_MESSAGE =\n `This rule also applies to ${NO_EVIDENCE_CATEGORY} visitors, who are real people whose browser sent no evidence to classify. ` +\n `Add a \\`${NO_EVIDENCE_EXCLUSION_TERM}\\` condition, or confirm you intend to affect them.`;\n\nconst messageFor = (classes: readonly string[]): string =>\n classes.length === PROBE_CLASSES.length\n ? EVERYONE_MESSAGE\n : classes.includes(NO_EVIDENCE_CATEGORY)\n ? NO_EVIDENCE_MESSAGE\n : HUMAN_MESSAGE;\n\nexport function lintUnnarrowedDenyRules(cedar: string): LintFinding[] {\n return unnarrowedDenyStatements(cedar).map(({ statement, classes, line }) => ({\n ruleId: statementId(statement),\n line,\n message: messageFor(classes),\n }));\n}\n\nconst MISSING_BASELINE_MESSAGE =\n `This policy has no baseline permit, so every visitor that no permit rule covers is denied, humans and ${NO_EVIDENCE_CATEGORY} visitors included. ` +\n 'Add `permit(principal, action, resource);` if you want unmatched traffic allowed.';\n\nexport function lintMissingBaselinePermit(cedar: string): LintFinding[] {\n return lacksBaselinePermit(cedar) ? [{ line: 1, message: MISSING_BASELINE_MESSAGE }] : [];\n}\n","/**\n * Policy Module\n *\n * Shared policy types and schemas, the policy fetcher, and the helpers an\n * enforcement point uses around the engine's Cedar decision. The decision\n * itself comes from the engine (`@kya-os/checkpoint-wasm-runtime`).\n */\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nexport {\n // Enforcement actions (Vocab-1: PERMIT canonical, ALLOW + LOG deprecated aliases)\n ENFORCEMENT_ACTIONS,\n type EnforcementAction,\n // Enforcement modes (Vocab-1: orthogonal axis to Decision)\n ENFORCEMENT_MODES,\n type EnforcementMode,\n // Condition operators\n CONDITION_OPERATORS,\n type ConditionOperator,\n // Condition fields\n CONDITION_FIELDS,\n type ConditionField,\n // Defaults\n DEFAULT_THRESHOLDS,\n DEFAULT_POLICY,\n DEFAULT_RULE_PRIORITY,\n CACHE_TTL,\n CURRENT_POLICY_VERSION,\n} from './constants';\n\n// ============================================================================\n// Schemas (for runtime validation)\n// ============================================================================\n\nexport {\n // Action & match schemas (Vocab-1)\n EnforcementActionSchema,\n EnforcementModeSchema,\n // Decision schemas (Vocab-1: TS mirror of Rust Decision enum)\n BlockReasonSchema,\n AssuranceTierSchema,\n ChallengeParamsSchema,\n RedirectTargetSchema,\n SuggestedActionSchema,\n InstructPayloadSchema,\n DecisionSchema,\n // Threshold schemas\n ThresholdConfigSchema,\n // List entry schemas\n DenyListEntrySchema,\n AllowListEntrySchema,\n // Condition schemas\n ConditionOperatorSchema,\n ConditionFieldSchema,\n ConditionValueSchema,\n PolicyConditionSchema,\n // Rule schemas\n RuleMetadataSchema,\n PolicyRuleSchema,\n // Policy config schemas\n PolicyMetadataSchema,\n PolicyConfigSchema,\n // Validation helpers\n safeParsePolicyConfig,\n // Human step-up (gateway-enforcement-step-up, build item 5): normalize a\n // wire `challengeType` to the kind every renderer must treat it as.\n normalizeChallengeType,\n isEngineEnforcing,\n} from './schemas';\n\nexport { FAIL_CLOSED_BODY, FAIL_CLOSED_HEADERS, FAIL_CLOSED_STATUS } from './fail-closed-response';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type {\n ThresholdConfig,\n DenyListEntry,\n AllowListEntry,\n ConditionValue,\n PolicyCondition,\n RuleMetadata,\n PolicyRule,\n PolicyMetadata,\n PolicyConfig,\n // Vocab-1 Decision types (TS mirror of Rust Decision enum)\n BlockReason,\n AssuranceTier,\n ChallengeParams,\n RedirectTarget,\n SuggestedAction,\n InstructPayload,\n Decision,\n // Note: EnforcementMode is exported above from constants.ts (the\n // value-side const lives there; the schema lives here). Re-exporting\n // both keeps consumers from having to import from two paths.\n} from './schemas';\n\n// ============================================================================\n// Path patterns (skip and include path lists)\n// ============================================================================\n\nexport { matchPath } from './match-path';\n\n// ============================================================================\n// Composed-policy required scopes (the @scopes a CHALLENGE rule demands)\n// ============================================================================\n\nexport { requiredScopesForRequest } from './required-scopes';\nexport { ByteBoundedMemo } from './byte-bounded-memo';\n// #3236 / #3272 PR3: position-per-kind extraction of the determining policy's\n// authored @id from a Decision (the policies-index join key).\nexport { decisionPolicyId, type DecisionLike } from './decision-policy-id';\n// KYA-862 follow-up: synthetic `@id`s for the gateway's bespoke (non-Cedar)\n// policy mechanisms, so `/activity` attributes them (friendly non-linked label)\n// instead of an em-dash. (The `bespoke-` prefix const + id type stay internal to\n// the module — readers use exact membership via `isBespokePolicyId`, not the\n// prefix.)\nexport {\n BASELINE_ALLOW_POLICY_ID,\n BESPOKE_POLICY_IDS,\n bespokePolicyLabel,\n isBespokePolicyId,\n isNonNavigablePolicyId,\n nonNavigablePolicyLabel,\n} from './bespoke-policy';\nexport type { RequestFacts, PolicyHazardAnalysis } from './cedar-rule-match';\nexport {\n splitCedarBlocks,\n blockEqualityLiterals,\n pathLiteralsInBlock,\n pathHasUnnarrowedDenyRuleFor,\n analyzePolicySource,\n} from './cedar-rule-match';\nexport type { ProbeClass } from './cedar-principal-scope';\nexport { parseCedarStatements, statementApplies, statementId } from './cedar-principal-scope';\nexport {\n NO_EVIDENCE_CATEGORY,\n NO_EVIDENCE_EQUALITY_TERM,\n NO_EVIDENCE_EXCLUSION_TERM,\n withNoEvidenceExclusion,\n} from './legacy-carve-out';\n\n// ============================================================================\n// Author-time lint (Task 3)\n// ============================================================================\n\nexport type { LintFinding } from './policy-lint';\nexport { lintUnnarrowedDenyRules, lintMissingBaselinePermit } from './policy-lint';\n\n// ============================================================================\n// Cedar string grammar (escape codec + capture) — shared by the compose engine\n// emitter/parser and the enforcement-path readers so the grammar can't drift.\n// ============================================================================\n\nexport { escapeCedarString, unescapeCedarString, cedarQuotedValueRegExp } from './cedar-string';\n\n// ============================================================================\n// Composed-policy approval quorum (the @approvers / @quorum a CHALLENGE demands)\n// — the step-up case, distinct from the consent @scopes case (ADR D7).\n// ============================================================================\n\nexport { approvalQuorumForRequest, type ApprovalQuorum } from './approval-quorum';\n\n// ============================================================================\n// Step-up quorum validation (T3-edge) — the fail-closed guard the enforce path\n// runs before approval-signature verification. Shared so every edge runtime\n// applies the same gate as the central gateway PEP.\n// ============================================================================\n\nexport {\n validateStepUpQuorum,\n type InvalidStepUpReason,\n type StepUpQuorumCheck,\n type StepUpQuorumLike,\n} from './step-up';\n\n// ============================================================================\n// Fetcher\n// ============================================================================\n\nexport {\n // Types\n type PolicyCacheAdapter,\n type PolicyFetcherConfig,\n type CachedPolicy,\n // Class\n PolicyFetcher,\n PolicyUnavailableError,\n isPolicyUnavailableError,\n} from './fetcher';\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Check if an action is a \"blocking\" action — i.e. one where the host wrapper\n * does NOT pass the original request/response through unchanged. `instruct` is\n * blocking-class because the request is held pending guidance (matches the\n * dashboard's outcome bucket and the Decision-priority ordering in ADR-001).\n */\nexport function isBlockingAction(action: string): boolean {\n return (\n action === 'block' || action === 'redirect' || action === 'challenge' || action === 'instruct'\n );\n}\n","/**\n * Wire contract for the gateway ↔ vault bridge on Vercel (#1532,\n * #2025, #2029).\n *\n * Route: `POST /api/v1/gateway/vault/:projectId/resolve`\n *\n * The Fly gateway posts a signed Ed25519 assertion; the Vercel\n * route resolves per-user credentials and returns them. The two\n * sides used to keep independent TypeScript types for the envelope,\n * which let the success shape drift unnoticed when Vercel wrapped\n * the body in the standard `{ success, data }` envelope but Fly\n * kept reading `body.secrets` at the root. Both sides now import\n * and validate through these schemas, so shape drift becomes a\n * typecheck / runtime validation error instead of a silent bug.\n *\n * The schemas are exhaustive for their path — no `.passthrough()`,\n * no optional fields that aren't actually optional. If the live\n * wire format grows a field, land the schema change in the same\n * commit as the code that writes/reads it.\n */\n\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// Success body — 200 response from /api/v1/gateway/vault/:projectId/resolve\n// ---------------------------------------------------------------------------\n\n/**\n * Optional metadata attached to the 200 response when the vault side\n * has the org / upstream slug context. The gateway uses these to\n * build deep-link `actionUrl`s when the secrets map is empty\n * (CREDENTIALS_NOT_CONFIGURED path).\n */\nexport const vaultResolveMetaSchema = z\n .object({\n orgSlug: z.string().optional(),\n upstreamSlug: z.string().optional(),\n })\n .strict();\n\n/**\n * The inner `data` payload on a 200 response.\n *\n * `secrets` is always an object keyed by `envVarName`. Empty object\n * is valid and distinct from missing — an empty map signals \"user\n * hasn't connected this upstream yet\" while a missing field would\n * be a broken response. Values are always strings per §3.4 of the\n * #1532 wire contract; no nested secret types.\n */\nexport const vaultResolveDataSchema = z\n .object({\n secrets: z.record(z.string(), z.string()),\n _meta: vaultResolveMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Canonical envelope for every successful vault resolve. Every\n * 200 response on this path MUST match this schema exactly. The\n * `.strict()` on the outer object catches stray top-level fields\n * — if a new claim needs to land on the envelope, it gets a\n * schema update in the same PR.\n */\nexport const vaultResolveSuccessSchema = z\n .object({\n success: z.literal(true),\n data: vaultResolveDataSchema,\n })\n .strict();\n\nexport type VaultResolveSuccess = z.infer<typeof vaultResolveSuccessSchema>;\nexport type VaultResolveData = z.infer<typeof vaultResolveDataSchema>;\nexport type VaultResolveMeta = z.infer<typeof vaultResolveMetaSchema>;\n\n// ---------------------------------------------------------------------------\n// Error body — 4xx/5xx responses from the same route\n// ---------------------------------------------------------------------------\n\n/**\n * Every error response uses the nested `error: { code, message, data }`\n * envelope established in #1532 step 4 (commit 95994b751). The\n * `code` is a machine-readable string (`NOT_FOUND`, `INVALID_SIGNATURE`,\n * `GONE`, etc.) — see `vault-response-mapping.ts` on the gateway\n * side for the full list of recognized codes.\n */\nexport const vaultResolveErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n data: z\n .object({\n orgSlug: z.string().optional(),\n upstreamSlug: z.string().optional(),\n retryAfter: z.number().optional(),\n })\n .passthrough()\n .optional(),\n })\n .strict(),\n })\n .strict();\n\nexport type VaultResolveError = z.infer<typeof vaultResolveErrorSchema>;\n\n/**\n * Discriminated union over the two shapes. Callers that receive a\n * parsed body can branch on `success` without a separate status\n * check.\n */\nexport const vaultResolveResponseSchema = z.discriminatedUnion('success', [\n vaultResolveSuccessSchema,\n vaultResolveErrorSchema,\n]);\n\nexport type VaultResolveResponse = z.infer<typeof vaultResolveResponseSchema>;\n","/**\n * Canonical KYA-OS per-organization did:web derivation.\n *\n * The org slug becomes a single path segment in\n * `https://kya.vouched.id/orgs/<slug>/did.json`, so validation here is a\n * security boundary shared by issuers and verifiers.\n */\n\n/** did:web host for org issuer DIDs. */\nexport const MCPI_ORG_DID_HOST = 'kya.vouched.id';\n\nconst ORG_SLUG_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/**\n * True when `slug` is a valid `did:web` org path segment — i.e. it can be fed\n * to {@link deriveMcpiOrgDid} without throwing. Callers that accept a\n * user-supplied slug MUST gate on this before persisting it, since the org DID\n * is derived from the slug at every mint/publish/verify site; an invalid slug\n * bricks credential issuance for that org.\n */\nexport function isValidMcpiOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug);\n}\n\n/** Build the org's `did:web` issuer DID from its slug. Throws on invalid slugs. */\nexport function deriveMcpiOrgDid(slug: string): string {\n if (!ORG_SLUG_PATTERN.test(slug)) {\n throw new Error(`Invalid org slug for did:web derivation: ${JSON.stringify(slug)}`);\n }\n return `did:web:${MCPI_ORG_DID_HOST}:orgs:${slug}`;\n}\n\n/**\n * The verification-method fragment of an org's signing key number `sequence`\n * (`key-<sequence>`). An org's keys are numbered from 1 and a number is never\n * reused, so `<org did>#key-<sequence>` names one key forever; it is that\n * key's verification method in the org DID document and the JWT `kid` of\n * everything it signs. Which key is active is the issuer's business: a\n * verifier takes the key the kid names from the issuer's DID document.\n */\nexport function mcpiOrgKeyFragment(sequence: number): string {\n if (!Number.isSafeInteger(sequence) || sequence < 1) {\n throw new RangeError(`An org key sequence is a positive integer, got ${sequence}`);\n }\n return `key-${sequence}`;\n}\n\nconst ORG_KEY_FRAGMENT_PATTERN = /^key-[1-9]\\d{0,8}$/;\n\n/**\n * True when `kid` names one of the org's signing keys: `<orgDid>#key-<n>`,\n * n ≥ 1. Verifiers pin a credential's `kid` with this before resolving the\n * issuer's DID document, then take the key from the method with that id.\n */\nexport function isMcpiOrgKeyId(orgDid: string, kid: unknown): boolean {\n return (\n typeof kid === 'string' &&\n kid.startsWith(`${orgDid}#`) &&\n ORG_KEY_FRAGMENT_PATTERN.test(kid.slice(orgDid.length + 1))\n );\n}\n\n/**\n * The delegation root DIDs an org trusts — the value the policies route resolves\n * SERVER-SIDE and returns on the policy payload, which each surface forwards into\n * the engine's `ContextSpec.trustedDelegationRoots` allow-list.\n *\n * Option 1 (first-party): an org trusts ONLY delegations rooted at its own DID.\n * This is the single place trust-root composition lives — called server-side in\n * the policies route, never on a surface. Option 2 (configurable partner issuer\n * DIDs) and the #3020 `resolveOrgDid(org)` multi-host generalization extend ONLY\n * this function; the engine, wire format, orchestrator threading, and every\n * surface stay unchanged.\n *\n * Throws on an invalid slug (same boundary as {@link deriveMcpiOrgDid}) rather\n * than returning `[]`: an empty list makes the engine reject every delegation,\n * so an org with a broken slug is a configuration error to surface loudly\n * server-side, not a silent outage of every delegated agent.\n */\nexport function resolveTrustedDelegationRoots(org: { slug: string }): string[] {\n return [deriveMcpiOrgDid(org.slug)];\n}\n","/**\n * Canonical KYA-OS user DID derivation: a user's did:web under the org's DID\n * tree. Every sign-in method and every consent leg names its user here, so the\n * mapping from a user id to a DID is one function.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { deriveMcpiOrgDid } from './org-did';\n\n/**\n * Marks a hashed user id segment: `sha256-` plus the RFC 4648 base32\n * (lowercase, unpadded) of SHA-256 over the UTF-8 bytes of `<slug>:<userId>`.\n */\nexport const MCPI_HASHED_USER_ID_PREFIX = 'sha256-';\n\n/** A did:web path segment: letters, digits, `.`, `_`, `-`, alphanumeric at both ends, ≤ 255. */\nconst USER_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\nconst BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';\n\n/** RFC 4648 base32, lowercase, without padding. */\nfunction base32(bytes: Uint8Array): string {\n let out = '';\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = ((buffer << 8) | byte) & 0xfff;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += BASE32_ALPHABET[(buffer >> bits) & 31];\n }\n }\n if (bits > 0) out += BASE32_ALPHABET[(buffer << (5 - bits)) & 31];\n return out;\n}\n\n/**\n * The DID path segment that names `userId` in org `slug`.\n *\n * - A user id that is a valid path segment is used as it is, so those DIDs\n * never move.\n * - Any other id (an Auth0 `auth0|…` subject, an email, a URL, anything over\n * 255 characters) is hashed: `sha256-` + base32(SHA-256(\"<slug>:<userId>\")),\n * 59 characters. The DID then carries no personal data and keeps a fixed\n * length, and a merchant can recompute it from its own customer id. The hash\n * is over the id exactly as given, with no trimming or Unicode normalisation.\n * - An id that already starts with the prefix (in any case) is hashed too, so\n * no raw id can equal another id's hash.\n *\n * Throws on a blank user id: a blank principal is never a user.\n */\nexport function mcpiUserIdSegment(slug: string, userId: string): string {\n if (userId.trim() === '') {\n throw new Error(`Invalid user id for did:web derivation: ${JSON.stringify(userId)}`);\n }\n const reserved = userId.toLowerCase().startsWith(MCPI_HASHED_USER_ID_PREFIX);\n if (USER_ID_PATTERN.test(userId) && !reserved) return userId;\n const digest = sha256(new TextEncoder().encode(`${slug}:${userId}`));\n return `${MCPI_HASHED_USER_ID_PREFIX}${base32(digest)}`;\n}\n\n/**\n * Build a user's `did:web` DID under the org's DID tree. Resolves to\n * `https://kya.vouched.id/orgs/<slug>/users/<segment>/did.json`, where the\n * segment is {@link mcpiUserIdSegment}.\n *\n * Throws on an invalid slug or a blank user id.\n */\nexport function deriveMcpiUserDid(slug: string, userId: string): string {\n const orgDid = deriveMcpiOrgDid(slug);\n return `${orgDid}:users:${mcpiUserIdSegment(slug, userId)}`;\n}\n","/**\n * Canonical principals + MCP client DID derivation.\n *\n * Standard requires `did:web` or `did:key` for any DID we emit — no\n * ad-hoc methods. This module defines:\n *\n * - {@link ANONYMOUS_PRINCIPAL_DID}: a known anonymous-principal `did:web`\n * used as the sentinel when the gateway cannot determine the subject\n * (replaces the pre-#3022 `did:kya:anonymous` ad-hoc form).\n * - {@link deriveMcpClientDid}: derives an MCP client's canonical `did:web`\n * from its client id (replaces the pre-#3022 `did:client:<id>` shape).\n *\n * The anonymous principal resolves to a minimal stub DID document at\n * `https://kya.vouched.id/principals/anonymous/did.json` (no verification\n * methods — the principal can't sign anything, it's a sentinel).\n *\n * The client DID resolves to `https://knowthat.ai/clients/<id>/did.json`.\n * Known first-party clients (Cursor, Claude Desktop, etc.) have docs served\n * by the KTA registry; unknown clients use the same shape and may 404 on\n * resolution today.\n *\n * `deriveMcpClientDid` also accepts a CIMD `client_id` (an OAuth Client ID\n * Metadata Document URL, SEP-991 / draft-ietf-oauth-client-id-metadata-\n * document). This is NOT the ratified `did:web` <-> HTTPS bijection from\n * SPEC-ENTITY-CARD.md §7.1 (`didFromClientId` in `@kya-os/mcp`'s\n * `src/card/cimd.ts`) — applying that bijection to a third-party CIMD URL\n * (e.g. `https://claude.ai/...`) would mint a `did:web:claude.ai:...`, a\n * different host than `knowthat.ai`, which this module's callers require\n * and which would 404 (Anthropic doesn't serve a DID document there). So a\n * CIMD URL is instead mapped onto the SAME `knowthat.ai:clients:<slug>`\n * shape every other client id already produces — see `CIMD_CLIENT_SLUGS`.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\n\nexport { ANONYMOUS_PRINCIPAL_DID } from './anonymous-principal';\n\n/** did:web host for MCP client DIDs (KnowThatAi registry). */\nexport const MCP_CLIENT_DID_HOST = 'knowthat.ai';\n\nconst CLIENT_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/** Deterministic-fallback slug prefix for a CIMD URL with no known mapping below. */\nconst CIMD_FALLBACK_PREFIX = 'cimd-';\n\n/**\n * Known CIMD `client_id` URLs mapped onto the SAME slug `KNOWN_CLIENTS`\n * already uses in `apps/web/lib/gateway/mcp-client-did.ts` — resolving one\n * of these produces the EXACT DID string that id already resolves to today\n * (no migration). Keyed on the full, exact `client_id` string, never the\n * host: `claude.ai` alone serves distinct CIMD documents for Claude Code vs.\n * Claude Desktop/web/Cowork, and host-only keying would merge slugs\n * `KNOWN_CLIENTS` deliberately keeps separate.\n *\n * `https://claude.ai/oauth/mcp-oauth-client-metadata` (Claude Desktop, the\n * claude.ai web app, mobile, and Cowork) is deliberately left OUT: that one\n * client_id is shared by four distinct surfaces, and mapping it to a single\n * `claude-desktop` slug would over-claim a precision the id doesn't carry.\n * It falls through to the deterministic `cimd-<hash>` slug below instead.\n * Revisit if/when KTA adds a broader registry entry for it.\n */\nconst CIMD_CLIENT_SLUGS: Readonly<Record<string, string>> = {\n 'https://claude.ai/oauth/claude-code-client-metadata': 'claude-code',\n 'https://vscode.dev/oauth/client-metadata.json': 'vscode',\n};\n\n/**\n * The slugs `CIMD_CLIENT_SLUGS` maps CIMD URLs onto — reserved so an\n * OPAQUE (non-URL) client id can never collide with one. Without this, an\n * opaque `client_id: 'claude-code'` would mint the exact same\n * `did:web:knowthat.ai:clients:claude-code` a domain-verified CIMD\n * resolution produces, distinguishable only by the caller's separately-\n * tracked provenance (`oauth_client_derived` vs `oauth_client_cimd`) —\n * any downstream consumer that keys off `agentDid` alone can't tell them\n * apart. `isCimdClientId` already rejects non-URL strings before this\n * function's CIMD branch ever runs, so the only way to reach a reserved\n * slug through the opaque path is by supplying the bare slug text itself.\n */\nconst RESERVED_CIMD_SLUGS = new Set(Object.values(CIMD_CLIENT_SLUGS));\n\n/**\n * Build an MCP client's `did:web` from its client id. Throws on invalid ids.\n *\n * Accepts two client id shapes:\n * - An opaque, pattern-valid id (e.g. a DCR-issued UUID or a known slug)\n * — unchanged behavior, byte-identical output to before CIMD support.\n * - A CIMD `client_id` URL — must be `https:` with a non-empty path.\n * A known KYA-OS-issued URL (`CIMD_CLIENT_SLUGS`) resolves to its\n * existing slug; an unknown one gets a deterministic `cimd-<sha256\n * prefix>` slug, stable for the life of that client_id. Either way the\n * DID keeps the exact same `did:web:knowthat.ai:clients:<slug>` shape,\n * so no migration is required.\n *\n * The resulting DID resolves to `https://knowthat.ai/clients/<id>/did.json`.\n */\nexport function deriveMcpClientDid(clientId: string): string {\n const cimdUrl = tryParseUrl(clientId);\n const slug = cimdUrl ? slugForCimdUrl(cimdUrl, clientId) : clientId;\n\n if (!CLIENT_ID_PATTERN.test(slug)) {\n throw new Error(`Invalid client id for did:web derivation: ${JSON.stringify(clientId)}`);\n }\n // Reject an opaque client id that collides with a slug CIMD_CLIENT_SLUGS\n // reserves for domain-verified resolution — see RESERVED_CIMD_SLUGS.\n if (!cimdUrl && RESERVED_CIMD_SLUGS.has(slug)) {\n throw new Error(`Reserved CIMD client slug, cannot use as an opaque client id: ${slug}`);\n }\n return `did:web:${MCP_CLIENT_DID_HOST}:clients:${slug}`;\n}\n\n/** Parse `value` as a URL, or null if it isn't URL-shaped (an opaque client id). */\nfunction tryParseUrl(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a CIMD `client_id` URL to its did:web slug. CIMD requires `https`\n * and a path component; a non-https scheme or a bare origin throws rather\n * than silently falling back to the opaque-id path.\n */\nfunction slugForCimdUrl(url: URL, originalClientId: string): string {\n if (url.protocol !== 'https:' || url.pathname === '' || url.pathname === '/') {\n throw new Error(\n `Invalid client id for did:web derivation: ${JSON.stringify(originalClientId)}`\n );\n }\n const known = CIMD_CLIENT_SLUGS[originalClientId];\n if (known) return known;\n const digest = bytesToHex(sha256(new TextEncoder().encode(originalClientId)));\n return `${CIMD_FALLBACK_PREFIX}${digest.slice(0, 32)}`;\n}\n","/**\n * Reported identity — the wire block a KYA-OS-aware enforcement point (a\n * \"verifier\", e.g. the in-process `@kya-os/id/mcp` reporter the Hobbsidian\n * reference customer runs) sends to Checkpoint's `/api/v1/log-detection` to\n * describe WHO acted and on WHOSE behalf.\n *\n * This is the M1 hinge contract of `docs/architecture/agent-identity-taxonomy.md`\n * (§5.1) — the shape both Checkpoint ingest and every KYA-OS reporter converge\n * on, and the draft of the proposed \"Verifier Reporting Profile\" (§10). Field\n * names track KYA-OS / draft-kya-http vocabulary (issuer / audience / capability\n * / jti) so the block can graduate into a non-normative DIF companion without a\n * rename.\n *\n * THREE deliberate properties:\n *\n * 1. **Asserted vs verified is explicit.** `agent` and `principal` are\n * identities the reporter ASSERTS; only `delegation.result` carries a\n * verification OUTCOME, and `delegation.verifiedBy` says who did the\n * cryptography. Checkpoint derives an *assurance* tier\n * ({@link AssuranceTier}) from these server-side — the reporter does not\n * get to assert its own assurance.\n *\n * 2. **agent ≠ principal, structurally.** The bug that motivated this block\n * (a reporter sending a *user* DID under a generic `signals[{kind:\n * \"agent_did\"}]` entry, rendering \"on behalf of: unattributed\") is\n * impossible to express here: the principal's DID lives on `principal.did`,\n * the agent's on `agent.did`. They are separate objects.\n *\n * 3. **`clientInfoName` is a DECLARED hint, never identity.** MCP `initialize`\n * `clientInfo.name` and User-Agent are unauthenticated; a verifier MUST NOT\n * treat them as agent identity (this is the spec security-considerations\n * posture, §10.2). They are recorded as declared metadata at most — the\n * resolution ladder caps their assurance at `attested-bearer`.\n *\n * Additive-optional, mirroring every prior `log-detection` evolution\n * (enforcement #2446, engine Phase-0.1, sdk #3076, engineSteps #3164): the whole\n * block is optional, and objects are non-strict (unknown keys strip) so a newer\n * reporter field never 400s an older Checkpoint. The reporter may emit this\n * block immediately — pre-M1 ingest silently strips it (see §5.3 dual-emit pin).\n *\n * NOT carried here: the full delegation JWS/VC body. `delegations` /\n * `bouncer_proofs` remain the credential stores; this block carries the\n * *reference* (`jti`) and the *outcome*, not the proof.\n */\n\nimport { z } from 'zod';\nimport { REGISTERED_SID_MAX_LENGTH } from './registered-sid';\n\n/**\n * A W3C DID string. Required form per the KYA-OS standard: `did:web` or\n * `did:key` (no ad-hoc methods). We validate only the `did:` scheme prefix here\n * — method-specific structure is the resolver's concern — but the prefix alone\n * is enough to reject the junk that an untyped signals array used to admit (a\n * bare userId, an email, a UA string).\n */\nconst DidStringSchema = z\n .string()\n .trim()\n .min(1)\n .regex(/^did:/, 'must be a DID (did:web / did:key)');\n\n/** A non-empty, trimmed free string (rejects whitespace-only values). */\nconst NonEmptyTrimmed = z.string().trim().min(1);\n\n/**\n * The acting agent's asserted identity. Every field is optional — a reporter\n * fills in what it actually knows: an enterprise A2A agent has a `did`; a\n * generic OAuth MCP client has only an `oauthClientId` (Checkpoint derives its\n * `did:web` server-side via `deriveMcpClientDid`); an unauthenticated client\n * offers only the declared `clientInfoName`.\n */\nexport const ReportedAgentSchema = z\n .object({\n /** The agent's own DID, when it has one (enterprise A2A / provisioned). */\n did: DidStringSchema.optional(),\n /**\n * OAuth `client_id` of an authenticated MCP client. Checkpoint derives the\n * canonical `did:web` from this (DR-9 `deriveMcpClientDid`); the reporter\n * sends the raw id, not the derived DID.\n */\n oauthClientId: NonEmptyTrimmed.optional(),\n /**\n * MCP `initialize` `clientInfo.name` (e.g. `claude-ai`, `cursor`). DECLARED,\n * unauthenticated — recorded as a hint, never resolved as identity above\n * `attested-bearer` assurance.\n */\n clientInfoName: NonEmptyTrimmed.optional(),\n /** MCP `initialize` `clientInfo.version`. Declared. */\n clientInfoVersion: NonEmptyTrimmed.optional(),\n })\n .describe('Asserted identity of the acting agent');\nexport type ReportedAgent = z.infer<typeof ReportedAgentSchema>;\n\n/**\n * The human (or upstream) principal the agent acted on behalf of — the \"on\n * behalf of\" attribution. `did` is preferred (e.g.\n * `did:web:h0bb5.dev:u:<userId>`); `sub` is the issuer-local subject when no\n * DID is minted; `email` is an optional display identity only.\n */\nexport const ReportedPrincipalSchema = z\n .object({\n /** The principal's DID (the delegation issuer, typically). */\n did: DidStringSchema.optional(),\n /** Issuer-local subject identifier, when the principal has no DID. */\n sub: NonEmptyTrimmed.optional(),\n /** Optional display email. Never the identity key — `did`/`sub` are. */\n email: NonEmptyTrimmed.email().optional(),\n })\n .describe('Asserted identity of the principal the agent acted for');\nexport type ReportedPrincipal = z.infer<typeof ReportedPrincipalSchema>;\n\n/**\n * Outcome of presenting a delegation. `verified` = the signed delegation\n * checked out; `failed` = presented but rejected; `not_presented` = none on the\n * request. Required whenever a `delegation` block is sent — an outcome-less\n * delegation block is meaningless.\n */\nexport const DelegationResultSchema = z.enum(['verified', 'failed', 'not_presented']);\nexport type DelegationResult = z.infer<typeof DelegationResultSchema>;\n\n/**\n * Who performed the delegation cryptography — the trust provenance of\n * `result`. `reporter` = the customer's own in-process verifier checked it\n * (same trust class as all SDK self-reporting, bounded by the API key's project\n * scope); `gateway` = a Checkpoint gateway verified it in-path; `checkpoint` =\n * the ingest plane re-verified. Persisted so a future in-path mode can rank\n * above self-reported without a schema change.\n */\nexport const DelegationVerifiedBySchema = z.enum(['reporter', 'gateway', 'checkpoint']);\nexport type DelegationVerifiedBy = z.infer<typeof DelegationVerifiedBySchema>;\n\nexport { REGISTERED_SID_MAX_LENGTH, SID_ATTRIBUTABLE_RESULT } from './registered-sid';\n\n/**\n * The delegation the agent presented (a reference + outcome, not the proof).\n * `result` and `verifiedBy` are required; the JWT claims (`jti` / `iss` / `aud`\n * / `capabilities` / `exp`) are optional because `not_presented` carries none.\n */\nexport const ReportedDelegationSchema = z\n .object({\n /** Delegation credential id — the join key into `delegations`. */\n jti: NonEmptyTrimmed.optional(),\n /**\n * The registered session anchor: the draft-kya-http-02 `sid` claim of the\n * presented credential (the top-level VC-JWT `sid` minted in\n * `mint-vc-jwt.ts`), distinct from any gateway or MCP session id. Optional,\n * and attributed to a session timeline only when `result` is `verified`\n * ({@link SID_ATTRIBUTABLE_RESULT}); ingest nulls it for any other result.\n * No refine here: the identity block must never fail a request.\n */\n sid: NonEmptyTrimmed.max(REGISTERED_SID_MAX_LENGTH).optional(),\n /** Issuer DID (usually the principal). */\n iss: DidStringSchema.optional(),\n /** Audience DID (the intended verifier / resource). */\n aud: DidStringSchema.optional(),\n /** Granted capabilities, e.g. `['vault:read']`. */\n capabilities: z.array(NonEmptyTrimmed).optional(),\n /** Expiry, unix seconds. */\n exp: z.number().int().positive().optional(),\n /** Verification outcome — required. */\n result: DelegationResultSchema,\n /** Who verified — required. */\n verifiedBy: DelegationVerifiedBySchema,\n })\n .describe('Presented delegation: reference + verification outcome');\nexport type ReportedDelegation = z.infer<typeof ReportedDelegationSchema>;\n\n/**\n * The full reported-identity block. All three sub-blocks are optional so a\n * reporter sends only what it has; an empty `{}` is valid (a reporter that\n * carries no identity at all). Checkpoint resolves the agent against its\n * catalog, attributes the principal, and derives the assurance tier from this\n * block plus the engine verdict.\n */\nexport const ReportedIdentitySchema = z\n .object({\n agent: ReportedAgentSchema.optional(),\n principal: ReportedPrincipalSchema.optional(),\n delegation: ReportedDelegationSchema.optional(),\n })\n .describe('KYA-OS reported identity (verifier → observability plane)');\nexport type ReportedIdentity = z.infer<typeof ReportedIdentitySchema>;\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Tolerant + canonical multibase codec for Ed25519 public keys used across\n * checkpoint's mcp-i auth surfaces (org DID docs, approver keys, worker\n * signed-agent verification).\n *\n * Lifts two previously-divergent decoders into one shared implementation:\n * - apps/gateway/src/lib/multibase.ts's `decodeEd25519PublicKeyMultibase`\n * accepted ONLY `z` (base58btc) + exactly 34 bytes (multicodec), throwing\n * on anything else.\n * - apps/web/workers/gateway/src/detection/did-verifier.ts's local\n * `decodeMultibase` accepted `z` and `m` (read as base64url, which\n * deviates from the multibase spec where `m` = standard base64, but\n * matches what knowthat.ai's DID generator actually emits), plus 32-byte\n * raw or 34-byte multicodec bodies.\n *\n * Neither accepted `u`, the actual multibase-spec prefix for base64url.\n * `decodeEd25519PublicKeyMultibaseTolerant` accepts z/m/u and both body\n * shapes, and — unlike the strict gateway decoder — never throws; callers\n * treat `null` as \"not a decodable Ed25519 key\" and route it into their\n * existing fail-closed paths.\n *\n * Reuses the base58btc codec from `./did-key` rather than adding a third\n * copy (a THIRD near-identical implementation was the state before this\n * module existed).\n */\n\nimport { base58btcDecode, base58btcEncode } from './did-key';\n\nconst ED25519_PUB_MULTICODEC = [0xed, 0x01] as const;\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Length ceiling applied BEFORE decoding. The longest legitimate body is a\n * 34-byte multicodec key: 47 chars in base58btc, 48 in padded base64. Bodies\n * past this cap are rejected by the length check anyway — the point is to\n * reject them before `base58btcDecode`'s O(n^2) repeated division runs, since\n * `publicKeyMultibase` / `publicKeyBase58` arrive from DID documents fetched\n * over the network and a hostile document could otherwise burn seconds of\n * event-loop (gateway) or isolate (worker) CPU per key. Mirrors the same guard\n * on `decodeDidKeyEd25519` in ./did-key.\n */\nexport const MAX_ED25519_KEY_BODY_LENGTH = 64;\n\n/**\n * Decode a base64 body to bytes, accepting both the url-safe (`-`, `_`) and\n * standard (`+`, `/`) alphabets and tolerating the presence or absence of\n * `=` padding. Returns null on any malformed input — never throws.\n */\nfunction base64AnyToBytes(body: string): Uint8Array | null {\n if (body.length === 0) return null;\n let normalized = body.replace(/-/g, '+').replace(/_/g, '/');\n const remainder = normalized.length % 4;\n if (remainder === 1) return null; // no valid base64 encoding has this length\n if (remainder === 2) normalized += '==';\n else if (remainder === 3) normalized += '=';\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;\n\n try {\n const bin = atob(normalized);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\n/** Strip the ed25519-pub multicodec prefix if present; validate the length either way. */\nfunction toRawEd25519Key(decoded: Uint8Array): Uint8Array | null {\n if (decoded.length === ED25519_PUBKEY_LENGTH) return decoded;\n if (\n decoded.length === ED25519_MULTIKEY_LENGTH &&\n decoded[0] === ED25519_PUB_MULTICODEC[0] &&\n decoded[1] === ED25519_PUB_MULTICODEC[1]\n ) {\n return decoded.slice(ED25519_PUB_MULTICODEC.length);\n }\n return null;\n}\n\n/**\n * Decode a `publicKeyMultibase` value to a raw 32-byte Ed25519 public key.\n * Accepts multibase prefixes `z` (base58btc), `m` (base64url — the value\n * checkpoint's own DID documents emit, though not per the multibase spec),\n * and `u` (base64url per the multibase spec). The decoded body may be 32\n * raw key bytes or 34 bytes prefixed with the ed25519-pub multicodec\n * (`0xed 0x01`), which is stripped. Returns null for any other prefix,\n * length, or invalid encoding — never throws.\n */\nexport function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null {\n if (typeof mb !== 'string' || mb.length < 2) return null;\n\n const prefix = mb[0];\n const body = mb.slice(1);\n if (body.length > MAX_ED25519_KEY_BODY_LENGTH) return null;\n\n let decoded: Uint8Array | null;\n if (prefix === 'z') {\n decoded = base58btcDecode(body);\n } else if (prefix === 'm' || prefix === 'u') {\n decoded = base64AnyToBytes(body);\n } else {\n return null;\n }\n if (!decoded) return null;\n\n return toRawEd25519Key(decoded);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a canonical `z`-prefixed,\n * ed25519-pub-multicodec multibase string. Throws if the key is not\n * exactly 32 bytes — an emitter handing in the wrong length is a\n * programming error, not untrusted input (unlike the tolerant decoder).\n */\nexport function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string {\n if (rawPubKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `Ed25519 public key must be ${ED25519_PUBKEY_LENGTH} bytes, got ${rawPubKey.length}`\n );\n }\n const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n prefixed[0] = ED25519_PUB_MULTICODEC[0];\n prefixed[1] = ED25519_PUB_MULTICODEC[1];\n prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);\n return 'z' + base58btcEncode(prefixed);\n}\n\n// Re-exported so a single subpath import also covers: (1) the legacy\n// `Ed25519VerificationKey2018` `publicKeyBase58` form (raw base58btc, no\n// multibase prefix, no multicodec) the worker needs, and (2) constructing\n// non-canonical-but-valid multibase fixtures (e.g. raw-32-byte z bodies) in\n// tests — without pulling the full package index either way.\nexport { base58btcDecode, base58btcEncode };\n","/**\n * Common delegation-verdict shape (verifier/engine unification series).\n *\n * The `delegation` cross-runtime-parity track\n * (`tests/cross-runtime-parity/delegation/`) checks multiple independent\n * delegation-verify implementations — the Fly gateway (`apps/gateway/src/lib/\n * mcpi-auth-resolver.ts` + `dashboard-delegation-verifier.ts`, both engine-\n * backed as of PR6/PR7) and `rust/crates/kya-os-engine`'s `verify_delegation`\n * — against one canonical vector set. Every emitter normalizes its runtime's\n * result to this shape before writing `runtime-outputs/<name>.json`. Lives\n * under the package's main entrypoint (not `test-fixtures`) because the\n * parity-harness test imports it as production infrastructure;\n * `test-fixtures/delegation-verdict.ts` re-exports it for the existing\n * parity-harness imports.\n *\n * Deliberately verdict-only (`kind` + coarse `reason.kind`), not the full\n * delegation record: the gateway's audit extractions (`delegationId`,\n * `clientDid`, `orgId`, `accountableAdminDid`) are deterministic claim reads,\n * not verification decisions, so they don't belong in a cross-implementation\n * agreement check — their correctness is covered by the gateway's own unit\n * tests (`mcpi-auth-resolver.test.ts`, `dashboard-delegation-verifier.test.ts`),\n * which is their natural home. Keeping this shape to exactly what\n * `scripts/assert-cross-runtime-parity.ts` already matches on (`kind`,\n * `reason.kind`, `reason.kindStartsWith`, `oneOf`) means that script needs no\n * per-track special-casing.\n *\n * `reason.kind` is deliberately coarse — a structural reason CLASS, not a\n * fine-grained cause. Each runtime's native vocabulary is many-to-one mapped\n * onto this fixed set via `toCoarseReasonKind`:\n *\n * - `signature` — bad/absent cryptographic signature\n * - `claim` — any issuer / audience / subject / orgId / other claim or\n * authorization mismatch (including \"no identity material\n * presented at all\")\n * - `time` — expired OR not-yet-valid\n * - `revocation` — revoked, or status-unavailable (fail-closed)\n * - `scope` — delegation doesn't grant the requested scope\n * - `resolve` — DID / context could not be resolved\n *\n * This is the coarsest granularity both the gateway (whose own top-level\n * verifier already folds iss/aud/orgId/sub into one `claim_invalid` /\n * `claim_mismatch`) and the engine (whose `BlockReason` has no\n * audience/issuer/not-yet-valid-specific variants) can already express\n * without changing either side's production reason taxonomy. Fine-grained\n * reason parity is an observability nice-to-have, not a security property —\n * the gate's job is to catch security-relevant WHY-drift (a different\n * structural reason class, or accept-vs-reject), not whether both sides spell\n * a claim rejection the same way. If per-cause parity is ever wanted, extend\n * each runtime's own reason vocabulary deliberately on its own timeline —\n * never bundle it with this track's blocking gate.\n */\n\nexport type DelegationVerdictKind = 'Permit' | 'Block';\n\nexport type CoarseReasonKind = 'signature' | 'claim' | 'time' | 'revocation' | 'scope' | 'resolve';\n\nexport interface DelegationVerdictReason {\n kind: CoarseReasonKind;\n}\n\nexport interface DelegationVerdict {\n kind: DelegationVerdictKind;\n reason: DelegationVerdictReason | null;\n}\n\n/**\n * Every raw reason discriminator either runtime can natively emit for the\n * delegation path, mapped onto the coarse taxonomy above.\n *\n * Gateway (`McpiAuthErrorReason` in `mcpi-auth-resolver.ts`,\n * `DashboardVerifyFailure['reason']` in `dashboard-delegation-verifier.ts`):\n * snake_case. Engine (`BlockReason` in `rust/crates/kya-os-engine/src/types.rs`):\n * PascalCase variant names. Unrecognized input is a harness bug (an emitter\n * started producing a reason string neither side has ever emitted before) —\n * `toCoarseReasonKind` throws rather than silently defaulting, so a new raw\n * reason gets a deliberate classification instead of landing in the wrong\n * bucket unnoticed.\n */\nconst REASON_KIND_MAP: Record<string, CoarseReasonKind> = {\n // --- gateway: apps/gateway/src/lib/mcpi-auth-resolver.ts ---\n missing_bearer_token: 'claim',\n parse_error: 'claim',\n did_resolve_failed: 'resolve',\n signature_invalid: 'signature',\n audience_mismatch: 'claim',\n expired: 'time',\n not_yet_valid: 'time',\n revoked: 'revocation',\n delegation_inactive: 'revocation',\n missing_claim: 'claim',\n claim_invalid: 'claim',\n // --- gateway: apps/gateway/src/lib/dashboard-delegation-verifier.ts ---\n not_configured: 'claim',\n header_missing: 'claim',\n claim_mismatch: 'claim',\n malformed: 'claim',\n // --- engine-rust: rust/crates/kya-os-engine/src/types.rs BlockReason ---\n Revoked: 'revocation',\n InvalidSignature: 'signature',\n Unauthenticated: 'claim',\n Expired: 'time',\n OutOfScope: 'scope',\n};\n\n/** Map a runtime's native reason discriminator onto the coarse taxonomy. */\nexport function toCoarseReasonKind(rawReasonKind: string): CoarseReasonKind {\n const coarse = REASON_KIND_MAP[rawReasonKind];\n if (!coarse) {\n throw new Error(\n `toCoarseReasonKind: unrecognized raw reason kind ${JSON.stringify(rawReasonKind)} — ` +\n `add it to REASON_KIND_MAP in delegation-verdict.ts with a deliberate coarse classification`\n );\n }\n return coarse;\n}\n\n/** Build a `Permit` verdict. */\nexport function permitDelegationVerdict(): DelegationVerdict {\n return { kind: 'Permit', reason: null };\n}\n\n/** Build a `Block` verdict from a runtime-native reason discriminator. */\nexport function blockDelegationVerdict(rawReasonKind: string): DelegationVerdict {\n return { kind: 'Block', reason: { kind: toCoarseReasonKind(rawReasonKind) } };\n}\n","/**\n * JAFAR feed parser (TypeScript prep-side — AIVF-1).\n *\n * Single-shape parser for the IETF draft `draft-illyes-webbotauth-jafar`.\n * All 14 vendor endpoints catalogued in `AI-Vendor-IP-Feeds-1.md` §2\n * conform to the same JSON shape; differences are purely whitespace +\n * timestamp format. The Rust engine-side counterpart lands later when\n * Bench-Before-After-1 §3.8 unblocks.\n *\n * Out of scope here: CIDR membership semantics, IP arithmetic, vendor\n * cross-match. Engine consumes the parsed prefixes; this layer only\n * validates the wire shape.\n *\n * Empirical 2026-05-17 across all 14 fixtures:\n * - `creationTime`: 2 of 14 emit RFC 3339 with `Z` (Anthropic, CCBot);\n * the other 12 emit Python `datetime.isoformat()` output with\n * microsecond precision and no offset (e.g.\n * `2026-05-15T14:45:52.000000`). JavaScript's Date constructor\n * interprets ISO-like strings without offset as local time per\n * ES2019+; the parser explicitly appends `Z` when no offset is\n * present so naive Python output is treated as UTC.\n * - `prefixes`: every entry has exactly one of `ipv4Prefix` or\n * `ipv6Prefix`; never both, never neither.\n * - Top-level extension fields: CCBot's feed carries `synctoken`\n * and `notes` in addition to the two JAFAR-spec fields. The\n * top-level schema therefore uses `passthrough()` so vendor\n * extensions don't trip Postel's Law; the typed surface exposes\n * `synctoken` and `notes` since they're useful provenance for\n * the daily-refresh cron (synctoken can short-circuit no-op\n * refreshes; notes can land in the auto-PR body). Per-prefix\n * entries stay strict — no vendor adds extras there today.\n */\n\nimport { z } from 'zod';\n\nconst IPV4_CIDR_RE =\n /^(?:(?: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)$/;\n\n// Relaxed IPv6 address recogniser. Strict semantic validation (canonical\n// form, zero-compression rules) is engine-side.\nconst IPV6_CIDR_RE = /^[0-9a-fA-F:]+\\/(?:12[0-8]|1[01]\\d|\\d{1,2})$/;\n\nconst HAS_OFFSET_RE = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\nconst creationTimeSchema = z\n .string()\n .min(1)\n .transform((raw, ctx) => {\n const normalized = HAS_OFFSET_RE.test(raw) ? raw : `${raw}Z`;\n const ms = Date.parse(normalized);\n if (Number.isNaN(ms)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `creationTime is not a parseable ISO 8601 timestamp: ${raw}`,\n });\n return z.NEVER;\n }\n return new Date(ms);\n });\n\nconst prefixSchema = z\n .object({\n ipv4Prefix: z.string().regex(IPV4_CIDR_RE).optional(),\n ipv6Prefix: z.string().regex(IPV6_CIDR_RE).optional(),\n })\n .strict()\n .refine((p) => (p.ipv4Prefix != null) !== (p.ipv6Prefix != null), {\n message: 'prefix entry must have exactly one of ipv4Prefix or ipv6Prefix',\n });\n\nconst jafarFeedSchema = z\n .object({\n creationTime: creationTimeSchema,\n prefixes: z.array(prefixSchema),\n synctoken: z.string().optional(),\n notes: z.string().optional(),\n })\n .passthrough();\n\nexport type JafarPrefix = {\n ipv4Prefix?: string;\n ipv6Prefix?: string;\n};\n\nexport type JafarFeed = {\n creationTime: Date;\n prefixes: JafarPrefix[];\n synctoken?: string;\n notes?: string;\n};\n\nexport class JafarParseError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown\n ) {\n super(message);\n this.name = 'JafarParseError';\n }\n}\n\n/**\n * Parse a JAFAR-format feed payload.\n *\n * Throws `JafarParseError` on malformed JSON or schema violation. The\n * thrown error's `cause` carries the underlying `SyntaxError` (JSON\n * parse) or `ZodError` (schema mismatch) so callers can drill in when\n * needed without leaking framework types in the happy path.\n */\nexport function parseJafarFeed(json: string): JafarFeed {\n let raw: unknown;\n try {\n raw = JSON.parse(json);\n } catch (err) {\n throw new JafarParseError('JAFAR feed is not valid JSON', err);\n }\n\n const result = jafarFeedSchema.safeParse(raw);\n if (!result.success) {\n throw new JafarParseError(\n `JAFAR feed failed schema validation: ${result.error.message}`,\n result.error\n );\n }\n return result.data;\n}\n","import { z } from 'zod';\n\n/** I1 additive wire records. Parsing does not establish authority or reviewer trust. */\nconst Id = z\n .string()\n .min(1)\n .max(256)\n .regex(/^[\\x21-\\x7e]+$/);\nconst Count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst Revision = Count.positive();\nconst ContentDigest = z\n .string()\n .length(64)\n .regex(/^[a-f0-9]{64}$/);\nconst RecordDigest = z\n .string()\n .length(71)\n .regex(/^sha256:[a-f0-9]{64}$/);\nconst AcceptanceId = z\n .string()\n .length(68)\n .regex(/^acc:[a-f0-9]{64}$/);\nconst GitObjectId = z\n .string()\n .regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)\n .refine((v) => v.length === 40 || v.length === 64);\nconst Kind = z.enum([\n 'workspace_snapshot',\n 'commit',\n 'pull_request',\n 'test_report',\n 'package',\n 'document',\n]);\nexport const ImmutableArtifactLocatorSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('local_snapshot'), digest: ContentDigest }).strict(),\n z.object({ type: z.literal('git_commit'), objectId: GitObjectId }).strict(),\n z\n .object({\n type: z.literal('pull_request_head'),\n repositoryId: Id,\n number: Revision,\n headObjectId: GitObjectId,\n })\n .strict(),\n z.object({ type: z.literal('content_blob'), digest: ContentDigest }).strict(),\n]);\nexport const ArtifactIdentitySchema = z\n .object({\n kind: Kind,\n repositoryId: Id,\n baseCommit: GitObjectId,\n contentDigest: ContentDigest,\n locator: ImmutableArtifactLocatorSchema,\n })\n .strict()\n .superRefine((v, ctx) => {\n const expected = {\n workspace_snapshot: 'local_snapshot',\n commit: 'git_commit',\n pull_request: 'pull_request_head',\n test_report: 'content_blob',\n package: 'content_blob',\n document: 'content_blob',\n }[v.kind];\n if (v.locator.type !== expected)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Artifact kind and locator disagree' });\n if (\n (v.locator.type === 'local_snapshot' || v.locator.type === 'content_blob') &&\n v.locator.digest !== v.contentDigest\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Locator does not identify content' });\n if (v.locator.type === 'pull_request_head' && v.locator.repositoryId !== v.repositoryId)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Pull request repository mismatch' });\n });\nexport const AcceptedArtifactRevisionSchema = z\n .object({\n schemaVersion: z.literal(1),\n acceptanceId: AcceptanceId,\n taskId: Id,\n specRevision: Revision,\n manifestDigest: RecordDigest,\n trackGeneration: Revision.nullable(),\n artifact: ArtifactIdentitySchema,\n reviewDigest: RecordDigest,\n reviewer: Id,\n acceptedAtMs: Count,\n supersedes: AcceptanceId.nullable(),\n })\n .strict()\n .refine((v) => v.supersedes !== v.acceptanceId, 'Acceptance cannot supersede itself');\nexport const AcceptanceWithdrawalSchema = z\n .object({\n schemaVersion: z.literal(1),\n acceptanceId: AcceptanceId,\n reason: z.string().min(1).max(4096),\n triggerTaskId: Id,\n withdrawnBy: Id,\n withdrawnAtMs: Count,\n })\n .strict();\nexport const ConsumedArtifactSchema = z\n .object({\n prerequisiteTaskId: Id,\n prerequisiteSpecRevision: Revision,\n requirement: z.enum(['accepted_patch', 'merged']),\n acceptanceId: AcceptanceId,\n repositoryId: Id,\n kind: Kind,\n contentDigest: ContentDigest,\n mergedCommit: GitObjectId.nullable(),\n })\n .strict()\n .refine(\n (v) => (v.requirement === 'merged') === (v.mergedCommit !== null),\n 'Merge evidence is required exactly for merged prerequisites'\n );\nexport const DependencyBindingSchema = z\n .object({\n schemaVersion: z.literal(1),\n bindingId: z\n .string()\n .length(69)\n .regex(/^bind:[a-f0-9]{64}$/),\n dependentTaskId: Id,\n dependentSpecRevision: Revision,\n trackId: Id,\n trackGeneration: Revision,\n consumed: z.array(ConsumedArtifactSchema).min(1).max(2000),\n materializationPlanDigest: RecordDigest,\n })\n .strict()\n .superRefine((v, ctx) => {\n let previous: string[] | undefined;\n for (const row of v.consumed) {\n const slot = [row.prerequisiteTaskId, row.repositoryId, row.kind];\n const order = previous && compareSlot(previous, slot);\n if (order !== undefined && order >= 0)\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Consumed artifact slots must be unique and sorted',\n });\n if (row.prerequisiteTaskId === v.dependentTaskId)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Self dependency' });\n previous = slot;\n }\n });\nfunction compareSlot(a: string[], b: string[]): number {\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n return 0;\n}\n/**\n * Why a binding no longer matches the graph and acceptance ledger (D2). A stale\n * binding is reviewed and replaced, never silently rebound.\n */\nexport const StaleReasonSchema = z\n .discriminatedUnion('type', [\n z.object({ type: z.literal('track_mismatch'), bindingTrackId: Id, trackId: Id }).strict(),\n z.object({ type: z.literal('dependent_removed') }).strict(),\n z\n .object({ type: z.literal('dependent_revision_changed'), from: Revision, to: Revision })\n .strict(),\n z.object({ type: z.literal('edge_added'), prerequisiteTaskId: Id }).strict(),\n z.object({ type: z.literal('edge_removed'), prerequisiteTaskId: Id }).strict(),\n z\n .object({\n type: z.literal('prerequisite_revision_changed'),\n taskId: Id,\n from: Revision,\n to: Revision,\n })\n .strict(),\n z.object({ type: z.literal('requirement_changed'), prerequisiteTaskId: Id }).strict(),\n z.object({ type: z.literal('acceptance_withdrawn'), acceptanceId: AcceptanceId }).strict(),\n z\n .object({\n type: z.literal('acceptance_superseded'),\n acceptanceId: AcceptanceId,\n by: AcceptanceId,\n })\n .strict(),\n z.object({ type: z.literal('acceptance_unknown'), acceptanceId: AcceptanceId }).strict(),\n z.object({ type: z.literal('acceptance_mismatch'), acceptanceId: AcceptanceId }).strict(),\n ])\n .superRefine((v, ctx) => {\n const unchanged =\n (v.type === 'track_mismatch' && v.bindingTrackId === v.trackId) ||\n ((v.type === 'dependent_revision_changed' || v.type === 'prerequisite_revision_changed') &&\n v.from === v.to) ||\n (v.type === 'acceptance_superseded' && v.acceptanceId === v.by);\n if (unchanged)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'A stale reason must name a change' });\n });\n/** One to 2000 distinct reasons. */\nexport const StaleReasonsSchema = z\n .array(StaleReasonSchema)\n .min(1)\n .max(2000)\n .refine(\n (reasons) => new Set(reasons.map(canonical)).size === reasons.length,\n 'Duplicate stale reason'\n );\nexport const BindingStatusSchema = z.discriminatedUnion('state', [\n z.object({ state: z.literal('current') }).strict(),\n z.object({ state: z.literal('stale'), reasons: StaleReasonsSchema }).strict(),\n]);\nexport type StaleReason = z.infer<typeof StaleReasonSchema>;\nexport type BindingStatus = z.infer<typeof BindingStatusSchema>;\nexport type AcceptedArtifactRevision = z.infer<typeof AcceptedArtifactRevisionSchema>;\nexport type AcceptanceWithdrawal = z.infer<typeof AcceptanceWithdrawalSchema>;\nexport type DependencyBinding = z.infer<typeof DependencyBindingSchema>;\n\n// All admitted numbers are safe integers. UTF-16 key sorting and JSON.stringify\n// implement the applicable RFC8785 domain without a Node-only hashing dependency.\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';\n if (value !== null && typeof value === 'object') {\n const object = value as Record<string, unknown>;\n return (\n '{' +\n Object.keys(object)\n .sort()\n .map((k) => JSON.stringify(k) + ':' + canonical(object[k]))\n .join(',') +\n '}'\n );\n }\n const result = JSON.stringify(value);\n if (result === undefined) throw new Error('Unsupported canonical value');\n return result;\n}\n/** Lowercase SHA-256 hex of the value's canonical (RFC8785) form. */\nexport async function contractDigest(value: unknown): Promise<string> {\n const hash = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(canonical(value))\n );\n return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');\n}\nexport async function verifyContractRecordIdentity(\n record: Record<string, unknown>,\n field: string,\n prefix: string\n): Promise<void> {\n const body = { ...record };\n delete body[field];\n if (record[field] !== prefix + (await contractDigest(body)))\n throw new Error('Record identity does not match canonical content');\n}\n/** Use this boundary before storing/admitting a record; shape validation alone is insufficient. */\nexport async function parseAcceptedArtifactRevision(\n input: unknown\n): Promise<AcceptedArtifactRevision> {\n const value = AcceptedArtifactRevisionSchema.parse(input);\n await verifyContractRecordIdentity(value, 'acceptanceId', 'acc:');\n return value;\n}\nexport async function parseDependencyBinding(input: unknown): Promise<DependencyBinding> {\n const value = DependencyBindingSchema.parse(input);\n await verifyContractRecordIdentity(value, 'bindingId', 'bind:');\n return value;\n}\n","import { z } from 'zod';\nimport {\n contractDigest,\n ImmutableArtifactLocatorSchema,\n StaleReasonsSchema,\n verifyContractRecordIdentity,\n} from './artifact-bindings';\nconst Id = z\n .string()\n .min(1)\n .max(256)\n .regex(/^[\\x21-\\x7e]+$/);\nconst Count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst Revision = Count.positive();\nconst Digest = z\n .string()\n .length(64)\n .regex(/^[a-f0-9]{64}$/);\nconst RecordDigest = z\n .string()\n .length(71)\n .regex(/^sha256:[a-f0-9]{64}$/);\nconst AcceptanceId = z\n .string()\n .length(68)\n .regex(/^acc:[a-f0-9]{64}$/);\nconst GitObject = z\n .string()\n .regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)\n .refine((v) => v.length === 40 || v.length === 64);\nconst Text = z.string().min(1).max(4096);\n// Claims remain inert until a separately authorized resolver handles them.\nconst ClaimUri = Text.refine((uri) => {\n const unsafe = [...uri].some((character) => {\n const code = character.charCodeAt(0);\n return code <= 32 || code === 127 || character === '\\\\';\n });\n if (unsafe || uri.startsWith('//')) return false;\n try {\n const parsed = new URL(uri);\n return (\n ['https:', 'http:'].includes(parsed.protocol) &&\n !!parsed.hostname &&\n !parsed.username &&\n !parsed.password\n );\n } catch {\n return !uri.includes(':');\n }\n}, 'Evidence must be an HTTP(S) or inert relative reference');\nconst Path = z\n .string()\n .min(1)\n .max(4096)\n .refine(\n (v) =>\n !v.includes('\\\\') &&\n !v.includes(':') &&\n !v.split('/').some((p) => !p || p === '.' || p === '..' || p.toLowerCase() === '.git') &&\n [...v].every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127),\n 'Unsafe materialization path'\n );\nconst unique = <T>(items: T[]) => new Set(items).size === items.length;\n/** Unicode code point order, which is UTF-8 byte order and Rust `str` order. */\nfunction compareCodePoints(a: string, b: string): number {\n const left = Array.from(a, (c) => c.codePointAt(0) as number);\n const right = Array.from(b, (c) => c.codePointAt(0) as number);\n for (let i = 0; i < Math.min(left.length, right.length); i++)\n if (left[i] !== right[i]) return left[i] - right[i];\n return left.length - right.length;\n}\n/** Strictly ascending, so each path appears at most once. */\nconst canonicalPaths = (paths: string[]) =>\n paths.every((path, i) => i === 0 || compareCodePoints(paths[i - 1], path) < 0);\nconst Ids = z.array(Id).max(2000).refine(unique, 'Duplicate identity');\nexport const TrackDependencyV2Schema = z\n .object({\n prerequisiteTaskId: Id,\n dependentTaskId: Id,\n requirement: z.enum(['accepted_patch', 'merged']),\n origin: z.enum(['source', 'local_edit', 'decomposition', 'lead_proposal']),\n })\n .strict()\n .refine((v) => v.prerequisiteTaskId !== v.dependentTaskId, 'Self dependency');\nconst IssueId = z\n .string()\n .length(70)\n .regex(/^issue:[a-f0-9]{64}$/);\nexport const ImportIssueV2Schema = z\n .object({\n issueId: IssueId,\n taskId: Id.nullable(),\n code: Id,\n message: Text,\n origin: z.enum(['import_diagnostic', 'reviewer_question']),\n blocking: z.boolean(),\n })\n .strict();\nexport const MaterializationPlanSchema = z\n .object({\n schemaVersion: z.literal(1),\n repositoryId: Id,\n baseCommit: GitObject,\n order: z.array(AcceptanceId).min(1).max(2000).refine(unique, 'Duplicate acceptance'),\n entries: z\n .array(\n z\n .object({\n path: Path,\n sourceAcceptanceId: AcceptanceId,\n kind: z.enum(['file', 'executable', 'delete']),\n contentDigest: Digest.nullable(),\n })\n .strict()\n .refine(\n (v) => (v.kind === 'delete') === (v.contentDigest === null),\n 'Deletion must not name content'\n )\n )\n .max(10000),\n conflicts: z\n .array(\n z\n .object({\n path: Path,\n acceptanceIds: z.array(AcceptanceId).min(2).max(2000).refine(unique),\n reason: z.enum(['divergent_content', 'delete_modify', 'type_change']),\n })\n .strict()\n )\n .max(10000),\n planDigest: RecordDigest,\n })\n .strict()\n .superRefine((v, ctx) => {\n if (\n !canonicalPaths(v.entries.map((e) => e.path)) ||\n !canonicalPaths(v.conflicts.map((c) => c.path))\n )\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Planned entries and conflicts must be unique and in canonical path order',\n });\n const planned = new Set(v.entries.map((e) => e.path));\n if (v.conflicts.some((c) => planned.has(c.path)))\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'A path is either planned or in conflict, never both',\n });\n if (\n v.entries.some((e) => !v.order.includes(e.sourceAcceptanceId)) ||\n v.conflicts.some((c) => c.acceptanceIds.some((id) => !v.order.includes(id)))\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unknown source acceptance' });\n });\nexport const ReconciliationDecisionSetSchema = z\n .object({\n schemaVersion: z.literal(1),\n importId: Id,\n expectedGeneration: Revision,\n expectedDraftDigest: RecordDigest,\n conflicts: z\n .array(z.object({ conflictId: Id, choice: z.enum(['base', 'local', 'incoming']) }).strict())\n .max(2000),\n removals: z\n .array(\n z\n .object({ taskId: Id, decision: z.enum(['remove_from_track', 'retain_as_local']) })\n .strict()\n )\n .max(2000),\n issues: z\n .array(\n z\n .object({\n issueId: Id,\n action: z.discriminatedUnion('type', [\n z.object({ type: z.literal('keep') }).strict(),\n z.object({ type: z.literal('resolve'), note: Text }).strict(),\n ]),\n })\n .strict()\n )\n .max(2000),\n decidedBy: Id,\n decidedAtMs: Count,\n })\n .strict()\n .refine(\n (v) =>\n unique(v.conflicts.map((c) => c.conflictId)) &&\n unique(v.removals.map((r) => r.taskId)) &&\n unique(v.issues.map((i) => i.issueId)),\n 'Duplicate reconciliation decision'\n );\nexport const ClaimVerificationSchema = z\n .object({\n schemaVersion: z.literal(1),\n verificationId: z\n .string()\n .length(71)\n .regex(/^claimv:[a-f0-9]{64}$/),\n taskId: Id,\n specRevision: Revision,\n claim: z.object({ uri: ClaimUri, label: z.string().max(4096).nullable() }).strict(),\n subject: z\n .object({ repositoryId: Id, locator: ImmutableArtifactLocatorSchema })\n .strict()\n .nullable(),\n criteriaIds: Ids,\n checkReceiptIds: Ids,\n verdict: z.enum(['valid', 'invalid', 'indeterminate']),\n reasons: z.array(Text).max(2000),\n reviewer: Id.nullable(),\n reviewedAtMs: Count.nullable(),\n })\n .strict()\n .superRefine((v, ctx) => {\n if ((v.reviewer === null) !== (v.reviewedAtMs === null))\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Incomplete review attestation' });\n if (\n v.verdict === 'valid' &&\n (!v.subject || !v.criteriaIds.length || !v.checkReceiptIds.length || !v.reviewer)\n )\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Valid claims require pinned subject, criteria, checks and review',\n });\n if (\n v.subject?.locator.type === 'pull_request_head' &&\n v.subject.repositoryId !== v.subject.locator.repositoryId\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Claim repository mismatch' });\n });\nconst ChildState = z.discriminatedUnion('type', [\n z.object({ type: z.literal('accepted'), acceptanceId: AcceptanceId }).strict(),\n z.object({ type: z.literal('pending') }).strict(),\n z.object({ type: z.literal('blocked'), reasons: z.array(Text).min(1).max(2000) }).strict(),\n z.object({ type: z.literal('stale'), reasons: StaleReasonsSchema }).strict(),\n]);\nexport const ParentIntegrationStatusSchema = z\n .object({\n schemaVersion: z.literal(1),\n parentTaskId: Id,\n parentSpecRevision: Revision,\n children: z\n .array(z.object({ taskId: Id, repositoryId: Id, state: ChildState }).strict())\n .min(1)\n .max(2000),\n parentOnlyCriteria: z\n .array(z.object({ criterionId: Id, evidence: RecordDigest.nullable() }).strict())\n .max(2000),\n state: z.enum(['not_started', 'partial', 'awaiting_integration', 'satisfied', 'stale']),\n })\n .strict()\n .superRefine((v, ctx) => {\n if (\n !unique(v.children.map((c) => c.taskId)) ||\n !unique(v.parentOnlyCriteria.map((c) => c.criterionId)) ||\n v.children.some((c) => c.taskId === v.parentTaskId)\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid integration identities' });\n const accepted = v.children.filter((c) => c.state.type === 'accepted').length;\n const expected = v.children.some((c) => c.state.type === 'stale')\n ? 'stale'\n : accepted === v.children.length\n ? v.parentOnlyCriteria.every((c) => c.evidence !== null)\n ? 'satisfied'\n : 'awaiting_integration'\n : accepted\n ? 'partial'\n : 'not_started';\n if (v.state !== expected)\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Integration state contradicts evidence',\n });\n });\nexport type TrackDependencyV2 = z.infer<typeof TrackDependencyV2Schema>;\nexport type ImportIssueV2 = z.infer<typeof ImportIssueV2Schema>;\nexport type MaterializationPlan = z.infer<typeof MaterializationPlanSchema>;\nexport type ReconciliationDecisionSet = z.infer<typeof ReconciliationDecisionSetSchema>;\nexport type ClaimVerification = z.infer<typeof ClaimVerificationSchema>;\nexport type ParentIntegrationStatus = z.infer<typeof ParentIntegrationStatusSchema>;\nexport async function parseMaterializationPlan(input: unknown): Promise<MaterializationPlan> {\n const value = MaterializationPlanSchema.parse(input);\n await verifyContractRecordIdentity(value, 'planDigest', 'sha256:');\n return value;\n}\n/** D7: `issue:` + SHA-256 of the canonical `{origin, taskId, code, message}`. */\nexport async function deriveImportIssueId(\n issue: Pick<ImportIssueV2, 'origin' | 'taskId' | 'code' | 'message'>\n): Promise<string> {\n const { origin, taskId, code, message } = issue;\n return 'issue:' + (await contractDigest({ origin, taskId, code, message }));\n}\n/** D7: `conf:` + SHA-256 of the canonical `{taskId, field, base, local, incoming}`. */\nexport async function deriveConflictId(conflict: {\n taskId: string | null;\n field: string;\n base: unknown;\n local: unknown;\n incoming: unknown;\n}): Promise<string> {\n const { taskId, field, base, local, incoming } = conflict;\n return 'conf:' + (await contractDigest({ taskId, field, base, local, incoming }));\n}\n/** Shape plus content identity; use before trusting an issue ID. */\nexport async function parseImportIssueV2(input: unknown): Promise<ImportIssueV2> {\n const value = ImportIssueV2Schema.parse(input);\n if (value.issueId !== (await deriveImportIssueId(value)))\n throw new Error('Record identity does not match canonical content');\n return value;\n}\nexport async function parseClaimVerification(input: unknown): Promise<ClaimVerification> {\n const value = ClaimVerificationSchema.parse(input);\n await verifyContractRecordIdentity(value, 'verificationId', 'claimv:');\n return value;\n}\n\n/** Reviewed claim-resolution mapping; it confers no repository access. HTTPS is the v1 transport profile. */\nexport const RepositoryIdentitySchema = z\n .object({\n schemaVersion: z.literal(1),\n repositoryId: Id,\n remote: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => {\n try {\n const url = new URL(value);\n return (\n url.protocol === 'https:' &&\n !url.username &&\n !url.password &&\n !url.search &&\n !url.hash &&\n // An empty query or fragment leaves search and hash empty but is\n // still part of the remote; Rust refuses both.\n !/[?#]/.test(value) &&\n url.pathname.split('/').filter(Boolean).length >= 2 &&\n url.href === value\n );\n } catch {\n return false;\n }\n }, 'Expected a canonical credential-free HTTPS repository remote'),\n })\n .strict();\nexport type RepositoryIdentity = z.infer<typeof RepositoryIdentitySchema>;\n","import { z } from 'zod';\nimport { LinearInstallationWorkflowSchema } from './task-ingress';\n\nexport const LinearInstallationProviderStatusSchema = z.enum(['connected', 'expired', 'revoked']);\nexport const LinearInstallationStatusReasonSchema = z.enum([\n 'uninstalled',\n 'refresh_rejected',\n 'token_rejected',\n 'reinstall_required',\n]);\n/** Provider identity and credentials are obtained by the server-side OAuth callback. */\nexport const StartLinearInstallationSchema = z\n .object({\n projectId: z.string().uuid(),\n enabled: z.boolean().default(true),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict();\n/** Additive replacement. C2 switches the route and retires the legacy configure body atomically. */\nexport const ConfigureLinearInstallationV2Schema = StartLinearInstallationSchema.extend({\n installationId: z.string().uuid(),\n}).strict();\nexport const LinearInstallationAuthorizationSchema = z\n .object({\n authorizationUrl: z\n .string()\n .max(8192)\n .url()\n .refine((value) => {\n try {\n const url = new URL(value);\n const required = [\n 'client_id',\n 'redirect_uri',\n 'response_type',\n 'scope',\n 'state',\n 'actor',\n 'code_challenge',\n 'code_challenge_method',\n ];\n return (\n url.origin === 'https://linear.app' &&\n url.pathname === '/oauth/authorize' &&\n !url.username &&\n !url.password &&\n !url.hash &&\n required.every(\n (key) =>\n url.searchParams.getAll(key).length === 1 && Boolean(url.searchParams.get(key))\n ) &&\n url.searchParams.get('response_type') === 'code' &&\n url.searchParams.get('actor') === 'app' &&\n url.searchParams.get('code_challenge_method') === 'S256'\n );\n } catch {\n return false;\n }\n }, 'Expected the managed Linear app authorization with state and S256'),\n expiresAt: z.string().datetime(),\n })\n .strict();\n/** Token-free owner/admin projection. This record is not a workload credential. */\nexport const LinearInstallationStatusSchema = z\n .object({\n installationId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n provider: z.literal('linear'),\n workspaceId: z.string().min(1).max(255),\n appUserId: z.string().min(1).max(255),\n enabled: z.boolean(),\n providerStatus: LinearInstallationProviderStatusSchema,\n providerStatusReason: LinearInstallationStatusReasonSchema.nullable(),\n providerStatusChangedAt: z.string().datetime().nullable(),\n providerAuthenticatedAt: z.string().datetime().nullable(),\n accessTokenExpiresAt: z.string().datetime().nullable(),\n admissible: z.boolean(),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict()\n .refine(\n (v) => v.admissible === (v.enabled && v.providerStatus === 'connected'),\n 'Admissibility contradicts installation policy and lifecycle'\n );\nexport type StartLinearInstallation = z.infer<typeof StartLinearInstallationSchema>;\nexport type ConfigureLinearInstallationV2 = z.infer<typeof ConfigureLinearInstallationV2Schema>;\nexport type LinearInstallationAuthorization = z.infer<typeof LinearInstallationAuthorizationSchema>;\nexport type LinearInstallationStatus = z.infer<typeof LinearInstallationStatusSchema>;\n","import { z } from 'zod';\nimport { PostureOriginsSchema } from '../types/posture-origins-schema';\n\n/**\n * C3: a human management session for the KYA-OS CLI, distinct from project API keys, workload\n * proofs and the gateway's delegation tokens. Browser (loopback) and device pairing both bind\n * PKCE S256; access tokens are short-lived and refresh tokens rotate. Workloads never accept it.\n */\nexport const MANAGEMENT_CLIENT_ID = 'kya-os-cli';\nexport const MANAGEMENT_AUDIENCE = 'urn:kya-os:checkpoint:management';\nexport const MANAGEMENT_ACCESS_PREFIX = 'kyam_';\nexport const MANAGEMENT_REFRESH_PREFIX = 'kyamr_';\n/** Seconds between device polls; `slow_down` adds 5 (RFC 8628 §3.5). */\nexport const MANAGEMENT_DEVICE_INTERVAL = 5;\n/** User codes avoid vowels and look-alike characters (RFC 8628 §6.1). */\nexport const MANAGEMENT_USER_CODE_ALPHABET = 'BCDFGHJKLMNPQRSTVWXZ';\n\nexport const ManagementScopeSchema = z.enum(['workbench.read', 'workbench.manage']);\nexport type ManagementScope = z.infer<typeof ManagementScopeSchema>;\n\nconst Base64Url43 = z\n .string()\n .length(43)\n .regex(/^[A-Za-z0-9_-]{43}$/);\nconst Verifier = z\n .string()\n .min(43)\n .max(128)\n .regex(/^[A-Za-z0-9._~-]+$/);\nconst Opaque = (prefix: string) =>\n z\n .string()\n .length(prefix.length + 43)\n .regex(new RegExp(`^${prefix}[A-Za-z0-9_-]{43}$`));\nexport const ManagementAccessTokenSchema = Opaque(MANAGEMENT_ACCESS_PREFIX);\nexport const ManagementRefreshTokenSchema = Opaque(MANAGEMENT_REFRESH_PREFIX);\nconst Timestamp = z.string().datetime();\nconst UserCode = z.string().regex(/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/);\n/** Space-separated, as in OAuth requests; at least one known scope, each once. */\nexport const ManagementScopeRequestSchema = z\n .string()\n .max(128)\n .transform((value, ctx) => {\n const scopes = value.split(' ').filter(Boolean);\n const parsed = z.array(ManagementScopeSchema).min(1).safeParse(scopes);\n if (!parsed.success || new Set(scopes).size !== scopes.length) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'invalid scope' });\n return z.NEVER;\n }\n return parsed.data;\n });\n\n/** RFC 8252 loopback redirect: exact path, any port, never a hostname that could resolve. */\nexport const ManagementLoopbackRedirectSchema = z\n .string()\n .max(64)\n .regex(/^http:\\/\\/(127\\.0\\.0\\.1|\\[::1\\]):([1-9][0-9]{0,4})\\/callback$/)\n .refine((value) => {\n const port = Number(/:(\\d+)\\/callback$/.exec(value)?.[1]);\n return port >= 1024 && port <= 65535;\n }, 'Loopback port must be 1024-65535');\n\nexport const ManagementPrincipalSchema = z\n .object({\n userId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectIds: z.array(z.string().uuid()).min(1).max(50),\n })\n .strict()\n .refine((value) => new Set(value.projectIds).size === value.projectIds.length, {\n message: 'Each project appears once',\n });\n\n/**\n * A name the CLI proposes for a project the user creates at consent, usually the repository's.\n * Printable ASCII with no space at either end, so the CLI can check it the same way.\n */\nexport const ManagementProjectNameSchema = z\n .string()\n .min(1)\n .max(100)\n .regex(/^[\\x21-\\x7E]([\\x20-\\x7E]*[\\x21-\\x7E])?$/);\n\n/** Query of `GET /cli/management/authorize`, validated before the consent page renders. */\nexport const ManagementAuthorizeQuerySchema = z\n .object({\n response_type: z.literal('code'),\n client_id: z.literal(MANAGEMENT_CLIENT_ID),\n redirect_uri: ManagementLoopbackRedirectSchema,\n code_challenge: Base64Url43,\n code_challenge_method: z.literal('S256'),\n state: z.string().min(22).max(512),\n resource: z.string().url().max(256),\n scope: ManagementScopeRequestSchema,\n project_hint: z.string().uuid().optional(),\n /** Prefills the consent page's new-project name; the grant itself never depends on it. */\n project_name: ManagementProjectNameSchema.optional(),\n })\n .strict();\n\n/** `POST /api/cli/management/device`. */\nexport const ManagementDeviceRequestSchema = z\n .object({\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n codeChallenge: Base64Url43,\n codeChallengeMethod: z.literal('S256'),\n scope: ManagementScopeRequestSchema,\n resource: z.string().url().max(256),\n projectHint: z.string().uuid().optional(),\n /** Prefills the consent page's new-project name, as `project_name` does for the browser. */\n projectName: ManagementProjectNameSchema.optional(),\n })\n .strict();\nexport const ManagementDeviceResponseSchema = z\n .object({\n deviceCode: Base64Url43,\n userCode: UserCode,\n verificationUri: z.string().url(),\n verificationUriComplete: z.string().url(),\n expiresAt: Timestamp,\n interval: z.number().int().min(MANAGEMENT_DEVICE_INTERVAL).max(60),\n })\n .strict();\n\n/** `POST /api/cli/management/token`. */\nexport const ManagementTokenRequestSchema = z.discriminatedUnion('grantType', [\n z\n .object({\n grantType: z.literal('authorization_code'),\n code: Base64Url43,\n codeVerifier: Verifier,\n redirectUri: ManagementLoopbackRedirectSchema,\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n })\n .strict(),\n z\n .object({\n grantType: z.literal('device_code'),\n deviceCode: Base64Url43,\n codeVerifier: Verifier,\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n })\n .strict(),\n z\n .object({\n grantType: z.literal('refresh_token'),\n refreshToken: ManagementRefreshTokenSchema,\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n })\n .strict(),\n]);\nexport const ManagementTokenResponseSchema = z\n .object({\n accessToken: ManagementAccessTokenSchema,\n tokenType: z.literal('Bearer'),\n expiresAt: Timestamp,\n refreshToken: ManagementRefreshTokenSchema,\n refreshExpiresAt: Timestamp,\n scope: z.array(ManagementScopeSchema).min(1).max(2),\n audience: z.literal(MANAGEMENT_AUDIENCE),\n issuer: z.string().url(),\n principal: ManagementPrincipalSchema,\n sessionId: z.string().uuid(),\n })\n .strict();\n\n/** `POST /api/cli/management/revoke`: a Bearer access token, or this body once it expired. */\nexport const ManagementRevokeRequestSchema = z\n .object({ refreshToken: ManagementRefreshTokenSchema })\n .strict();\n\n/** `GET /api/cli/management/session`. */\nexport const ManagementSessionSchema = z\n .object({\n sessionId: z.string().uuid(),\n principal: ManagementPrincipalSchema,\n scope: z.array(ManagementScopeSchema).min(1).max(2),\n audience: z.literal(MANAGEMENT_AUDIENCE),\n issuer: z.string().url(),\n createdAt: Timestamp,\n expiresAt: Timestamp,\n refreshExpiresAt: Timestamp,\n })\n .strict();\n\n/** `GET /api/cli/management/projects`: only the session's projects. */\nexport const ManagementProjectsSchema = z\n .object({\n organizationId: z.string().uuid(),\n projects: z\n .array(z.object({ id: z.string().uuid(), name: z.string().min(1).max(255) }).strict())\n .max(50),\n })\n .strict();\n\n/**\n * `GET /api/cli/management/profile`: who the session belongs to, by name, so `kya-os whoami`\n * can show names next to the principal's IDs. The CLI ignores fields it does not know here\n * (unlike the session and projects responses), so this may grow without breaking it.\n */\nexport const ManagementProfileSchema = z\n .object({\n userId: z.string().uuid(),\n email: z.string().min(1).max(255).optional(),\n name: z.string().min(1).max(255).optional(),\n organizationId: z.string().uuid(),\n organizationName: z.string().min(1).max(255).optional(),\n })\n .strict();\n\n/**\n * What an app's runtime key is for, which fixes its permissions: `sdk` reads (detection,\n * enforcement, policy fetches); `mcp` also writes (server registration, proofs, sessions,\n * events).\n */\nexport const ManagementRuntimeKeyPurposeSchema = z.enum(['sdk', 'mcp', 'proxy']);\n\n/**\n * `POST /api/cli/management/projects/{projectId}/runtime-keys`. `label` names where the key\n * will live (a host and repository), so each machine's key can be told apart and revoked alone.\n */\nexport const ManagementRuntimeKeyRequestSchema = z\n .object({\n purpose: ManagementRuntimeKeyPurposeSchema,\n label: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[\\x20-\\x7E]+$/),\n })\n .strict();\n\n/** A minted project runtime key. `key` is returned once, here, and never again. */\nexport const ManagementRuntimeKeySchema = z\n .object({\n keyId: z.string().uuid(),\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n key: z.string().regex(/^sk_[0-9a-f]{64}$/),\n preview: z.string().min(1).max(20),\n permissions: z\n .array(z.enum(['read', 'write', 'forward']))\n .min(1)\n .max(2),\n createdAt: Timestamp,\n })\n .strict();\n\nexport const ManagementPostureJwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n x: z.string(),\n y: z.string(),\n kid: z.string().min(1),\n alg: z.literal('ES256'),\n use: z.literal('sig'),\n })\n .strict();\n\nexport const ManagementPostureSchema = z\n .object({\n enabled: z.literal(true),\n keyId: z.string().min(1),\n publicJwk: ManagementPostureJwkSchema,\n primaryOrigin: z.string().nullable(),\n origins: z.array(z.string()),\n keysUrl: z.string().url(),\n })\n .strict();\n\nexport const ManagementPostureOriginsRequestSchema = z\n .object({ origins: PostureOriginsSchema })\n .strict();\n\nexport const ManagementErrorCodeSchema = z.enum([\n 'invalid_request',\n 'invalid_client',\n 'invalid_grant',\n 'invalid_target',\n 'access_denied',\n 'expired_token',\n 'authorization_pending',\n 'slow_down',\n 'invalid_token',\n 'insufficient_scope',\n 'temporarily_unavailable',\n // 429 from the per-client limiter; honour Retry-After.\n 'rate_limit_exceeded',\n]);\nexport const ManagementErrorReasonSchema = z.enum(['management_issuer_unconfigured']);\nexport const ManagementErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: ManagementErrorCodeSchema,\n message: z.string().min(1).max(256),\n reason: ManagementErrorReasonSchema.optional(),\n })\n .strict(),\n })\n .strict();\n\n/**\n * A resource route's own refusal (grants, delegations, tasks), distinct from the session codes\n * above: an uppercase domain code at its real HTTP status, for example 409 GRANT_EXCEEDS_POLICY.\n */\nexport const ManagementDomainErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: z.string().regex(/^[A-Z][A-Z0-9_]{2,63}$/),\n message: z.string().min(1).max(256),\n })\n .strict(),\n })\n .strict();\n\n/**\n * Browser consent posts, same-origin behind the signed-in session. Approval names one\n * organization and its projects; denial needs no choice, so it carries only the request.\n */\nconst ConsentChoice = {\n decision: z.literal('approve'),\n organizationId: z.string().uuid(),\n projectIds: z.array(z.string().uuid()).min(1).max(50),\n};\nconst ConsentFlow = {\n authorization_code: {\n flow: z.literal('authorization_code'),\n query: ManagementAuthorizeQuerySchema,\n },\n device: { flow: z.literal('device'), userCode: z.string().min(8).max(16) },\n};\nexport const ManagementConsentSchema = z.union([\n z.object({ ...ConsentFlow.authorization_code, ...ConsentChoice }).strict(),\n z.object({ ...ConsentFlow.authorization_code, decision: z.literal('deny') }).strict(),\n z.object({ ...ConsentFlow.device, ...ConsentChoice }).strict(),\n z.object({ ...ConsentFlow.device, decision: z.literal('deny') }).strict(),\n]);\n\n/** The consent pickers list at most this many organizations, and projects per organization. */\nexport const MANAGEMENT_CONSENT_MAX_ORGANIZATIONS = 100;\nexport const MANAGEMENT_CONSENT_MAX_PROJECTS = 500;\n\n/** What the signed-in user may grant: live organizations, their role, and live projects. */\nexport const ManagementConsentContextSchema = z\n .object({\n organizations: z\n .array(\n z\n .object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255),\n role: z.enum(['owner', 'admin', 'member']),\n projects: z\n .array(z.object({ id: z.string().uuid(), name: z.string().min(1).max(255) }).strict())\n .max(MANAGEMENT_CONSENT_MAX_PROJECTS),\n /** More live projects exist than are listed; the hinted project is always listed. */\n projectsTruncated: z.boolean(),\n })\n .strict()\n )\n .max(MANAGEMENT_CONSENT_MAX_ORGANIZATIONS),\n organizationsTruncated: z.boolean(),\n })\n .strict();\n/** A pending device request, as shown to the user deciding it. */\nexport const ManagementDeviceDescriptionSchema = z\n .object({\n scope: z.array(ManagementScopeSchema).min(1).max(2),\n projectHint: z.string().uuid().nullable(),\n projectName: ManagementProjectNameSchema.nullable(),\n expiresAt: z.string().datetime(),\n })\n .strict();\n\nexport type ManagementPrincipal = z.infer<typeof ManagementPrincipalSchema>;\nexport type ManagementAuthorizeQuery = z.infer<typeof ManagementAuthorizeQuerySchema>;\nexport type ManagementDeviceRequest = z.infer<typeof ManagementDeviceRequestSchema>;\nexport type ManagementDeviceResponse = z.infer<typeof ManagementDeviceResponseSchema>;\nexport type ManagementTokenRequest = z.infer<typeof ManagementTokenRequestSchema>;\nexport type ManagementTokenResponse = z.infer<typeof ManagementTokenResponseSchema>;\nexport type ManagementSession = z.infer<typeof ManagementSessionSchema>;\nexport type ManagementProjects = z.infer<typeof ManagementProjectsSchema>;\nexport type ManagementProfile = z.infer<typeof ManagementProfileSchema>;\nexport type ManagementRuntimeKeyPurpose = z.infer<typeof ManagementRuntimeKeyPurposeSchema>;\nexport type ManagementRuntimeKeyRequest = z.infer<typeof ManagementRuntimeKeyRequestSchema>;\nexport type ManagementRuntimeKey = z.infer<typeof ManagementRuntimeKeySchema>;\nexport type ManagementPosture = z.infer<typeof ManagementPostureSchema>;\nexport type ManagementPostureOriginsRequest = z.infer<typeof ManagementPostureOriginsRequestSchema>;\nexport type ManagementErrorCode = z.infer<typeof ManagementErrorCodeSchema>;\nexport type ManagementErrorReason = z.infer<typeof ManagementErrorReasonSchema>;\nexport type ManagementDomainError = z.infer<typeof ManagementDomainErrorSchema>;\nexport type ManagementConsent = z.infer<typeof ManagementConsentSchema>;\n/** What the browser posts: the authorize query still carries its raw scope string. */\nexport type ManagementConsentInput = z.input<typeof ManagementConsentSchema>;\nexport type ManagementConsentContext = z.infer<typeof ManagementConsentContextSchema>;\nexport type ManagementDeviceDescription = z.infer<typeof ManagementDeviceDescriptionSchema>;\n","import { z } from 'zod';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport {\n TaskStandingAdmissionRequestBaseSchema,\n TaskStandingAdmissionReceiptBaseSchema,\n TaskStandingCapabilitySchema,\n validModelAdmission,\n} from './task-ingress';\n\n/**\n * C11: protocol grants for standing work. A grant binds one runner key (never a human) to exact\n * actions, one repository, one lead and optionally exact arguments, under one installation\n * policy revision. Grants form a revocable chain up to a root an owner or admin issued. Every\n * admission reserves against the whole chain in one PostgreSQL transaction, so siblings share\n * their ancestors' allowances. A grant is never edited: renewal or new limits issue a\n * replacement, and admitted operations keep the grant they were admitted under.\n */\n\n/** Operation-admission protocols this server speaks, oldest first. Negotiate before use. */\nexport const TASK_ADMISSION_PROTOCOLS = ['kya.task.admission.v1', 'kya.task.admission.v2'] as const;\nexport const TaskAdmissionProtocolSchema = z.enum(TASK_ADMISSION_PROTOCOLS);\nexport type TaskAdmissionProtocol = z.infer<typeof TaskAdmissionProtocolSchema>;\n\n/** `GET /api/v1/task-mailbox/protocol`: public, tenant-free. */\n/**\n * Advertised by a deployment that answers an identical admission resend (same project, source,\n * execution operation and body, from the lead it recorded) by the admission it created, before\n * any current-policy check. Against such a deployment a 4xx on an identical resend proves the\n * original never committed. Absent from older deployments, where it proves nothing.\n */\nexport const TASK_ADMISSION_RESEND = 'kya.task.admission-resend.v1' as const;\nexport const TaskMailboxProtocolSchema = z\n .object({\n admissionProtocols: z.array(TaskAdmissionProtocolSchema).min(1),\n grantStatus: z.literal('kya.task.grant-status.v1'),\n admissionResend: z.literal(TASK_ADMISSION_RESEND).optional(),\n })\n .strict();\nexport type TaskMailboxProtocol = z.infer<typeof TaskMailboxProtocolSchema>;\n\nconst KeyDid = z.string().startsWith('did:key:').max(512);\nconst Sha256Digest = z.string().regex(/^sha256:[a-f0-9]{64}$/);\n/** Lowercase so a binding compares exactly; admission lowercases the repository it reserves. */\nconst GrantRepository = z\n .string()\n .max(255)\n .regex(/^[a-z0-9_.-]+\\/[a-z0-9_.-]+$/);\nconst GrantActions = z\n .array(TaskStandingCapabilitySchema)\n .min(1)\n .max(4)\n .refine(\n (values) => values.every((value, index) => index === 0 || values[index - 1] < value),\n 'Actions are unique and sorted'\n );\n\n/** What an admission must match exactly. */\nexport const TaskGrantBindingSchema = z\n .object({\n holderDid: KeyDid,\n actions: GrantActions,\n repository: GrantRepository,\n leadDid: KeyDid,\n /** `null` binds any arguments within the repository; otherwise exactly one argument set. */\n argumentsDigest: Sha256Digest.nullable(),\n policyRevision: z.number().int().positive(),\n })\n .strict();\nexport type TaskGrantBinding = z.infer<typeof TaskGrantBindingSchema>;\n\n/** The arguments an admission's digest covers. */\nexport const TaskGrantArgumentsSchema = z\n .object({\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n specRevision: z.number().int().positive(),\n manifestDigest: Sha256Digest,\n repository: GrantRepository,\n baseSha: z.string().regex(/^[a-f0-9]{40}$/),\n })\n .strict();\nexport type TaskGrantArguments = z.infer<typeof TaskGrantArgumentsSchema>;\n\n/**\n * RFC 8785 (JCS) for a flat object of strings and safe integers: members sorted by UTF-16 code\n * units, each serialized as `JSON.stringify` does, which is what JCS specifies for them. Local\n * because `canonicalize` is ESM-only and this module ships in the CJS root barrel.\n */\nfunction canonicalFlat(value: Readonly<Record<string, string | number>>): string {\n const members = Object.keys(value)\n .sort()\n .map((key) => {\n const item = value[key];\n if (typeof item !== 'string' && !Number.isSafeInteger(item))\n throw new TypeError(`Cannot canonicalize ${key}: only strings and safe integers`);\n return `${JSON.stringify(key)}:${JSON.stringify(item)}`;\n });\n return `{${members.join(',')}}`;\n}\n\n/** `sha256:` over the RFC 8785 (JCS) form of the arguments. */\nexport function taskGrantArgumentsDigest(input: TaskGrantArguments): string {\n const args = TaskGrantArgumentsSchema.parse(input);\n return `sha256:${bytesToHex(sha256(new TextEncoder().encode(canonicalFlat(args))))}`;\n}\n\n/** Shared by the grant and every descendant: each admission reserves against all of them. */\nexport const TaskGrantAllowanceSchema = z\n .object({\n maxOperations: z.number().int().min(1).max(10000),\n maxCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n maxConcurrentOperations: z.number().int().min(1).max(100),\n })\n .strict();\nexport type TaskGrantAllowance = z.infer<typeof TaskGrantAllowanceSchema>;\n\n/** Nearest parent first, root last. A chain is at most eight grants deep. */\nexport const MAX_TASK_GRANT_DEPTH = 8;\n\nexport const TaskGrantSchema = z\n .object({\n schema: z.literal('kya.task.grant.v1'),\n grantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n installationId: z.string().uuid(),\n parentGrantId: z.string().uuid().nullable(),\n replacesGrantId: z.string().uuid().nullable(),\n ancestors: z.array(z.string().uuid()).max(MAX_TASK_GRANT_DEPTH - 1),\n binding: TaskGrantBindingSchema,\n allowance: TaskGrantAllowanceSchema,\n notBefore: z.string().datetime(),\n expiresAt: z.string().datetime(),\n issuedByUserId: z.string().uuid(),\n issuedAt: z.string().datetime(),\n })\n .strict()\n .refine((grant) => grant.ancestors[0] === (grant.parentGrantId ?? undefined), {\n message: 'The nearest ancestor is the parent',\n })\n .refine((grant) => grant.notBefore < grant.expiresAt, { message: 'Validity is not empty' });\nexport type TaskGrant = z.infer<typeof TaskGrantSchema>;\n\nexport const TaskGrantStatusValueSchema = z.enum(['active', 'revoked', 'expired', 'replaced']);\n/** Why a grant cannot admit now; `active` only when it and every ancestor can. */\nexport const TaskGrantEffectiveStatusSchema = z.enum([\n 'active',\n 'not_yet_valid',\n 'revoked',\n 'expired',\n 'replaced',\n 'ancestor_inactive',\n]);\n\n/**\n * Recorded revocation, the server's first enforcement of it and already-admitted effects are\n * reported separately. A revoked in-flight effect stays recorded and charged; nothing here says\n * it was undone, and no notification is the authority gate.\n */\nexport const TaskGrantStatusSchema = z\n .object({\n schema: z.literal('kya.task.grant-status.v1'),\n grantId: z.string().uuid(),\n status: TaskGrantStatusValueSchema,\n effectiveStatus: TaskGrantEffectiveStatusSchema,\n revokedAt: z.string().datetime().nullable(),\n revocationReason: z.string().max(500).nullable(),\n replacedByGrantId: z.string().uuid().nullable(),\n /** First time the server refused an admission or action because this grant is inactive. */\n enforcementObservedAt: z.string().datetime().nullable(),\n admitted: z\n .object({\n operations: z.number().int().nonnegative(),\n inFlight: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n reservedCostMicrousd: z.string().regex(/^\\d+$/),\n })\n .strict(),\n observedAt: z.string().datetime(),\n })\n .strict();\nexport type TaskGrantStatus = z.infer<typeof TaskGrantStatusSchema>;\n\n/** Mailbox `grant-status`: the holder, the lead, or an ancestor's holder may read it. */\nexport const TaskGrantStatusRequestSchema = z\n .object({ ownerEpoch: z.number().int().positive(), grantId: z.string().uuid() })\n .strict();\n\n/** Admission under a grant. v1 requests stay byte-identical and never carry a grant. */\nexport const TaskGrantAdmissionRequestSchema = TaskStandingAdmissionRequestBaseSchema.extend({\n protocolVersion: z.literal('kya.task.admission.v2'),\n grant: z.object({ grantId: z.string().uuid(), binding: TaskGrantBindingSchema }).strict(),\n})\n .strict()\n .refine(validModelAdmission, 'Model capability requires a bounded policy');\nexport type TaskGrantAdmissionRequest = z.infer<typeof TaskGrantAdmissionRequestSchema>;\n\n/** The v2 receipt: the v1 receipt plus the exact chain the admission reserved against. */\nexport const TaskGrantAdmissionSchema = TaskStandingAdmissionReceiptBaseSchema.extend({\n schema: z.literal('kya.task.admission.v2'),\n grant: z\n .object({\n grantId: z.string().uuid(),\n ancestors: z.array(z.string().uuid()).max(MAX_TASK_GRANT_DEPTH - 1),\n binding: TaskGrantBindingSchema,\n })\n .strict(),\n})\n .strict()\n .refine(validModelAdmission, 'Model capability requires a bounded policy');\nexport type TaskGrantAdmission = z.infer<typeof TaskGrantAdmissionSchema>;\n\n/** Management: issue a root or child grant. `operationId` makes a retried issue idempotent. */\nexport const IssueTaskGrantSchema = z\n .object({\n operationId: z.string().uuid(),\n installationId: z.string().uuid(),\n parentGrantId: z.string().uuid().nullable(),\n binding: TaskGrantBindingSchema,\n allowance: TaskGrantAllowanceSchema,\n notBefore: z.string().datetime().optional(),\n expiresAt: z.string().datetime(),\n })\n .strict();\nexport type IssueTaskGrant = z.infer<typeof IssueTaskGrantSchema>;\n\n/** Management: renew or change limits. The binding stays, at the current policy revision. */\nexport const ReplaceTaskGrantSchema = z\n .object({\n operationId: z.string().uuid(),\n allowance: TaskGrantAllowanceSchema,\n notBefore: z.string().datetime().optional(),\n expiresAt: z.string().datetime(),\n })\n .strict();\nexport type ReplaceTaskGrant = z.infer<typeof ReplaceTaskGrantSchema>;\n\nexport const RevokeTaskGrantSchema = z\n .object({ reason: z.string().trim().min(1).max(500) })\n .strict();\n\nexport const TaskGrantViewSchema = z\n .object({ grant: TaskGrantSchema, status: TaskGrantStatusSchema })\n .strict();\nexport const TaskGrantListSchema = z\n .object({ grants: z.array(TaskGrantViewSchema).max(200) })\n .strict();\nexport type TaskGrantView = z.infer<typeof TaskGrantViewSchema>;\n\n/** Issue and replace: a retried `operationId` with the same body returns the same grant. */\nexport const TaskGrantIssueResultSchema = z\n .object({ grant: TaskGrantSchema, status: TaskGrantStatusSchema, duplicate: z.boolean() })\n .strict();\nexport type TaskGrantIssueResult = z.infer<typeof TaskGrantIssueResultSchema>;\n\n/** Revocation is recorded at commit; it never reports admitted effects as undone. */\nexport const TaskGrantRevocationSchema = z\n .object({\n grant: TaskGrantSchema,\n status: TaskGrantStatusSchema,\n wasAlreadyRevoked: z.boolean(),\n })\n .strict();\nexport type TaskGrantRevocation = z.infer<typeof TaskGrantRevocationSchema>;\n\n/** A grant may not outlive this many days from `notBefore`; renewal issues a replacement. */\nexport const MAX_TASK_GRANT_DAYS = 90;\n\n/** Mailbox `grants`: the grants a runner may present, as their holder or their lead. */\nexport const TaskGrantHolderListRequestSchema = z\n .object({ ownerEpoch: z.number().int().positive() })\n .strict();\n","import { z } from 'zod';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\n/**\n * C10: reviewed identity provisioning and workload enrollment, behind the C3 management session.\n * A read never provisions, mints or probes. Each fact the project identity view reports keeps its\n * own evidence: configured (a stored record), observed (an explicit probe, when it ran),\n * authoritative (the registry's current record, when last read), history (verified by the CLI's\n * identity sidecar, never claimed by the server) and receiving authorization (an explicit link).\n */\n\nconst Timestamp = z.string().datetime();\nconst Uuid = z.string().uuid();\nconst KeyDid = z.string().startsWith('did:key:').max(512);\nconst PublicUrl = z\n .string()\n .url()\n .max(2048)\n .refine((value) => {\n const url = new URL(value);\n return (\n ['https:', 'http:'].includes(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.search &&\n !url.hash\n );\n }, 'A public URL has no credentials, query or fragment');\nconst Code = z.string().regex(/^[A-Z][A-Z0-9_]{2,63}$/);\n\n/** The last explicit observation of a subject; `not_observed` until someone ran one. */\nexport const IdentityObservationSchema = z\n .object({\n state: z.enum(['healthy', 'unhealthy', 'unavailable', 'not_observed']),\n observedAt: Timestamp.nullable(),\n })\n .strict();\n\nexport const RegistryAuthorityStateSchema = z.enum([\n // The registry's current record names the recorded DID, is active, and its current key is\n // the organization's signing key.\n 'matches',\n 'differs',\n 'deactivated',\n 'not_found',\n 'unavailable',\n 'not_observed',\n]);\n\nexport const ProjectIdentitySchema = z\n .object({\n schema: z.literal('kya.identity.project.v1'),\n organizationId: Uuid,\n projectId: Uuid,\n readAt: Timestamp,\n signingIdentity: z\n .object({\n /** A key exists in Checkpoint's encrypted custody. The key itself never leaves it. */\n configured: z.boolean(),\n didWeb: z.string().startsWith('did:web:').max(512).nullable(),\n })\n .strict(),\n registry: z\n .object({\n /** This deployment can register organizations. */\n configured: z.boolean(),\n recorded: z\n .object({\n did: z.string().startsWith('did:webvh:').max(512),\n entityId: z.string().min(1).max(64),\n multikey: z.string().min(1).max(128),\n })\n .strict()\n .nullable(),\n authoritative: z\n .object({\n state: RegistryAuthorityStateSchema,\n observedAt: Timestamp.nullable(),\n currentGeneration: z.number().int().positive().nullable(),\n })\n .strict(),\n /** Signed history is verified by the CLI identity sidecar; the server never claims it. */\n history: z\n .object({\n verifiedByServer: z.literal(false),\n logUrl: PublicUrl.nullable(),\n })\n .strict(),\n })\n .strict(),\n services: z\n .array(\n z\n .object({\n id: z.string().min(1).max(255),\n kind: z.enum(['authorization_host', 'mcp']),\n url: PublicUrl.nullable(),\n configured: z.boolean(),\n /** A probe Checkpoint ran; MCP deployments are never probed, only self-reported. */\n observed: IdentityObservationSchema,\n selfReportedAt: Timestamp.nullable(),\n receiving: z\n .object({\n state: z.enum(['authorized', 'not_linked', 'not_applicable']),\n linkedAt: Timestamp.nullable(),\n })\n .strict(),\n })\n .strict()\n )\n .max(102),\n })\n .strict();\nexport type ProjectIdentity = z.infer<typeof ProjectIdentitySchema>;\n\n/**\n * `create` a signing identity in encrypted custody; `register` the organization's did:webvh root\n * with that key; `repair` a registration whose response was lost (only from a verified registry\n * read whose current key is the organization's key; never a re-mint); `link` a recorded MCP\n * deployment as authorized to receive for this organization.\n */\nexport const IdentityIntentActionSchema = z.enum(['create', 'register', 'repair', 'link']);\nexport type IdentityIntentAction = z.infer<typeof IdentityIntentActionSchema>;\n\n/** `POST …/identity/intents`: a review; nothing changes until it is applied. */\nexport const IdentityIntentRequestSchema = z.discriminatedUnion('action', [\n z.object({ operationId: Uuid, action: z.literal('create') }).strict(),\n z.object({ operationId: Uuid, action: z.literal('register') }).strict(),\n z.object({ operationId: Uuid, action: z.literal('repair') }).strict(),\n z.object({ operationId: Uuid, action: z.literal('link'), deploymentId: Uuid }).strict(),\n]);\nexport type IdentityIntentRequest = z.infer<typeof IdentityIntentRequestSchema>;\n\n/** Review and outcome text is read back in terminals and the dashboard. */\nconst Readable = (max: number) => z.string().max(max).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\nconst PublicMetadata = z.record(Readable(64), Readable(512));\n\nexport const IdentityIntentStateSchema = z.enum([\n 'reviewed',\n 'applying',\n 'succeeded',\n 'failed',\n // The external effect may or may not have happened; `repair` or a re-read resolves it.\n 'unknown',\n 'expired',\n]);\n\nexport const IdentityIntentSchema = z\n .object({\n schema: z.literal('kya.identity.intent.v1'),\n operationId: Uuid,\n organizationId: Uuid,\n projectId: Uuid,\n action: IdentityIntentActionSchema,\n deploymentId: Uuid.nullable(),\n state: IdentityIntentStateSchema,\n review: z\n .object({\n /** Plain-language effects the reviewer approves, in order. */\n effects: z.array(Readable(300).min(1)).min(1).max(8),\n /** Public metadata only: DIDs, entity IDs, URLs. Never key material. */\n publicMetadata: PublicMetadata,\n digest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n expiresAt: Timestamp,\n })\n .strict(),\n outcome: z\n .object({\n code: Code,\n publicMetadata: PublicMetadata,\n /** True when a later `repair` or a retried apply can settle it. */\n recoverable: z.boolean(),\n })\n .strict()\n .nullable(),\n requestedByUserId: Uuid,\n requestedAt: Timestamp,\n appliedByUserId: Uuid.nullable(),\n completedAt: Timestamp.nullable(),\n })\n .strict()\n // Only a link names a deployment. A link whose deployment was deleted since names none;\n // its review and outcome still record which deployment it was.\n .refine((intent) => intent.action === 'link' || intent.deploymentId === null, {\n message: 'Only a link intent names a deployment',\n path: ['deploymentId'],\n });\nexport type IdentityIntent = z.infer<typeof IdentityIntentSchema>;\n\n/** `POST …/identity/intents/{operationId}/apply`: the reviewer's approval of exactly that review. */\nexport const ApplyIdentityIntentSchema = z\n .object({ reviewDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/) })\n .strict();\n\n// Workload enrollment (B05): a runner's own key, bound to one host and runner in one project.\n\n/** `POST …/enrollments/challenge`: a single-use nonce the holder key must sign. */\nexport const WorkloadEnrollmentChallengeSchema = z\n .object({\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n audience: z.string().url().max(512),\n expiresAt: Timestamp,\n })\n .strict();\n\nconst HostId = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/);\nconst Signature = z.string().regex(/^[A-Za-z0-9_-]{86}$/);\n\n/**\n * What an enrollment proof signs: the JCS form of this object, Ed25519 by the holder key, base64url.\n * Rotation signs `kya.workload.enrollment-rotation.v1` with both the old and the new key.\n */\nexport const WorkloadEnrollmentProofPayloadSchema = z\n .object({\n schema: z.literal('kya.workload.enrollment-proof.v1'),\n audience: z.string().url().max(512),\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n organizationId: Uuid,\n projectId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n holderDid: KeyDid,\n })\n .strict();\nexport const WorkloadRotationProofPayloadSchema = z\n .object({\n schema: z.literal('kya.workload.enrollment-rotation.v1'),\n audience: z.string().url().max(512),\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n enrollmentId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n oldHolderDid: KeyDid,\n newHolderDid: KeyDid,\n })\n .strict();\n\nexport const EnrollWorkloadSchema = z\n .object({\n operationId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n holderDid: KeyDid,\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n proof: Signature,\n /** When the owner's approval lapses; at most 180 days, default 90. */\n approvalExpiresAt: Timestamp.optional(),\n })\n .strict();\n\nexport const RotateWorkloadEnrollmentSchema = z\n .object({\n operationId: Uuid,\n newHolderDid: KeyDid,\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n oldProof: Signature,\n newProof: Signature,\n })\n .strict();\n\nexport const RevokeWorkloadEnrollmentSchema = z\n .object({ reason: z.string().trim().min(1).max(500) })\n .strict();\n\n/**\n * Approval, credential and renewal times are separate: the owner's approval can outlive many\n * credential periods, and renewal opens before the credential expires. A retiring enrollment\n * still identifies attempts admitted under it; it enrolls nothing new.\n */\nexport const WorkloadEnrollmentSchema = z\n .object({\n schema: z.literal('kya.workload.enrollment.v1'),\n enrollmentId: Uuid,\n operationId: Uuid,\n organizationId: Uuid,\n projectId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n holderDid: KeyDid,\n status: z.enum(['active', 'retiring', 'retired', 'revoked']),\n approvedByUserId: Uuid,\n approvedAt: Timestamp,\n approvalExpiresAt: Timestamp,\n credentialExpiresAt: Timestamp,\n renewalWindowStartsAt: Timestamp,\n replacesEnrollmentId: Uuid.nullable(),\n replacedByEnrollmentId: Uuid.nullable(),\n retiresAt: Timestamp.nullable(),\n revokedAt: Timestamp.nullable(),\n revokedByUserId: Uuid.nullable(),\n revocationReason: z.string().max(500).nullable(),\n })\n .strict();\nexport type WorkloadEnrollment = z.infer<typeof WorkloadEnrollmentSchema>;\n\n/** `POST …/enrollments/{id}/revoke`: a repeated revoke returns the recorded revocation. */\nexport const WorkloadEnrollmentRevocationSchema = z\n .object({ enrollment: WorkloadEnrollmentSchema, wasAlreadyRevoked: z.boolean() })\n .strict();\n\nexport const WorkloadEnrollmentResultSchema = z\n .object({ enrollment: WorkloadEnrollmentSchema, duplicate: z.boolean() })\n .strict();\nexport const WorkloadEnrollmentListSchema = z\n .object({ enrollments: z.array(WorkloadEnrollmentSchema).max(200) })\n .strict();\n","import { z } from 'zod';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\n/**\n * C11: human management of legacy delegations through a C3 management session. Reads need any\n * current role in the project; revocation needs a current owner or admin, rechecked when it\n * commits. Another organization's or project's delegation is indistinguishable from none.\n */\n\nconst Timestamp = z.string().datetime();\n\n/** A revocation reason is free text read back in terminals and the dashboard: readable text. */\nconst RevocationReason = z.string().max(500).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\n\n/** The stored lifecycle column. It is never flipped to `expired` by time alone. */\nexport const DelegationStoredStatusSchema = z.enum(['active', 'expired', 'revoked']);\nexport type DelegationStoredStatus = z.infer<typeof DelegationStoredStatusSchema>;\n\n/**\n * What verification would decide from the record alone at `evaluatedAt`: revocation first, then\n * expiry (`expiresAt` or the `notAfter` constraint), then the `notBefore` constraint.\n */\nexport const DelegationEffectiveStatusSchema = z.enum([\n 'active',\n 'not_yet_valid',\n 'expired',\n 'revoked',\n]);\nexport type DelegationEffectiveStatus = z.infer<typeof DelegationEffectiveStatusSchema>;\n\n/**\n * List filter over the effective status. `active` means neither revoked nor expired, so it also\n * lists delegations that are not yet valid.\n */\nexport const DelegationListStatusFilterSchema = z.enum(['active', 'revoked', 'expired', 'all']);\nexport type DelegationListStatusFilter = z.infer<typeof DelegationListStatusFilterSchema>;\n\n/** The bounds verification enforces. A stored bound of 0 means none, as in verification. */\nexport const DelegationConstraintSummarySchema = z\n .object({\n notBefore: Timestamp.nullable(),\n notAfter: Timestamp.nullable(),\n maxCalls: z.number().nullable(),\n })\n .strict();\nexport type DelegationConstraintSummary = z.infer<typeof DelegationConstraintSummarySchema>;\n\n/**\n * One delegation as its project's members see it. `usageCount` counts verifications accepted\n * against `maxCalls`; verification never counts uses of a delegation without a cap, so both\n * `usageCount` and `remainingCalls` are null there rather than a misleading 0.\n */\nexport const DelegationManagementItemSchema = z\n .object({\n delegationId: z.string().uuid(),\n agentDid: z.string().max(500),\n agentName: z.string().max(255).nullable(),\n userDid: z.string().max(500).nullable(),\n userIdentifier: z.string().max(500).nullable(),\n scopes: z.array(z.string().min(1)),\n constraints: DelegationConstraintSummarySchema,\n status: DelegationStoredStatusSchema,\n effectiveStatus: DelegationEffectiveStatusSchema,\n issuedAt: Timestamp,\n expiresAt: Timestamp.nullable(),\n revokedAt: Timestamp.nullable(),\n revocationReason: RevocationReason.nullable(),\n usageCount: z.number().int().nonnegative().nullable(),\n remainingCalls: z.number().int().nonnegative().nullable(),\n lastUsedAt: Timestamp.nullable(),\n })\n .strict();\nexport type DelegationManagementItem = z.infer<typeof DelegationManagementItemSchema>;\n\n/** `GET /api/cli/management/projects/{projectId}/delegations`: newest first. */\nexport const DelegationManagementListSchema = z\n .object({\n delegations: z.array(DelegationManagementItemSchema).max(200),\n /** Opaque; pass back as `?cursor=` for the next page. Null on the last page. */\n nextCursor: z.string().min(1).max(256).nullable(),\n /** The instant every `effectiveStatus` in this page was evaluated at. */\n evaluatedAt: Timestamp,\n })\n .strict();\nexport type DelegationManagementList = z.infer<typeof DelegationManagementListSchema>;\n\n/** Audit records that name this delegation, counted within its organization and project. */\nexport const DelegationAuditSourceSchema = z.enum([\n 'bouncer_proofs',\n 'gateway_tool_calls',\n 'usage_events',\n]);\nexport type DelegationAuditSource = z.infer<typeof DelegationAuditSourceSchema>;\nexport const DelegationAuditSummarySchema = z\n .object({\n source: DelegationAuditSourceSchema,\n count: z.number().int().nonnegative(),\n latestAt: Timestamp.nullable(),\n })\n .strict();\nexport type DelegationAuditSummary = z.infer<typeof DelegationAuditSummarySchema>;\n\n/**\n * Where Checkpoint handed the delegation's persisted bearer credential out: the verify response,\n * the dashboard list, gateway pickup polls, the JSON gateway consent approval, managed native\n * issuance and OpenClaw approvals. Freshly minted per-response tokens are separate credentials.\n */\nexport const DelegationExportChannelSchema = z.enum([\n 'verify_response',\n 'dashboard_list',\n 'gateway_pickup',\n 'gateway_consent',\n 'native_issuance',\n 'openclaw_approval',\n]);\nexport type DelegationExportChannel = z.infer<typeof DelegationExportChannelSchema>;\n\nexport const DelegationExportRecordSchema = z\n .object({\n channel: DelegationExportChannelSchema,\n firstExportedAt: Timestamp,\n lastExportedAt: Timestamp,\n /** Exports counted at most once a minute per credential, so a lower bound. */\n exportCount: z.number().int().positive(),\n })\n .strict();\nexport type DelegationExportRecord = z.infer<typeof DelegationExportRecordSchema>;\n\n/**\n * The compatibility export ledger's view of one delegation. It lists recorded exports only:\n * a ledger write that failed was logged, not retried, and credentials minted fresh for a\n * response (rather than read from the delegation record) are not exports of this credential.\n *\n * `historical` is `unknown` when the delegation was created before `ledgerStartedAt` (or this\n * environment has no ledger), because exports before then were never recorded; unknown is not\n * none. It is `none` only when the ledger covered the delegation's whole life, so `recorded` is\n * then every recorded channel. Revoking never retracts an export: `retractedByRevocation` is\n * always false, and whoever holds an exported credential still holds it.\n */\nexport const DelegationExposureSchema = z\n .object({\n ledgerStartedAt: Timestamp.nullable(),\n historical: z.enum(['unknown', 'none']),\n recorded: z\n .array(DelegationExportRecordSchema)\n .max(DelegationExportChannelSchema.options.length),\n retractedByRevocation: z.literal(false),\n })\n .strict();\nexport type DelegationExposure = z.infer<typeof DelegationExposureSchema>;\n\n/** `GET /api/cli/management/projects/{projectId}/delegations/{delegationId}`. */\nexport const DelegationManagementDetailSchema = DelegationManagementItemSchema.extend({\n audit: z.array(DelegationAuditSummarySchema).max(DelegationAuditSourceSchema.options.length),\n exposure: DelegationExposureSchema,\n}).strict();\nexport type DelegationManagementDetail = z.infer<typeof DelegationManagementDetailSchema>;\n\n/** `POST .../delegations/{delegationId}/revoke`. The reason is stored and shown to members. */\nexport const DelegationRevokeRequestSchema = z\n .object({ reason: z.string().trim().pipe(RevocationReason.min(1)) })\n .strict();\nexport type DelegationRevokeRequest = z.infer<typeof DelegationRevokeRequestSchema>;\n\n/**\n * The outcome of a human revocation. Revoking is idempotent: a delegation that was already\n * revoked answers `wasAlreadyRevoked: true` with its original `revokedAt`.\n *\n * `enforcement` names the only gate: Checkpoint verification. Every verification that consults\n * Checkpoint refuses the delegation once the revocation commits, whatever channel the credential\n * left through; `revokedAt` is when the revoking transaction began, at most moments earlier.\n * Exported bearer credentials are not retracted or deleted (see `exposure`), a verifier that\n * never consults Checkpoint is not stopped, and any status-list publication may lag. No\n * notification sent afterwards is part of the gate.\n *\n * `inFlight` is what the delegation had admitted when it was revoked: those uses may still be\n * completing downstream, and none is admitted after it. `admittedUses` is null for a delegation\n * without a call cap, whose uses verification never counts.\n */\nexport const DelegationRevokeResponseSchema = z\n .object({\n delegationId: z.string().uuid(),\n status: z.literal('revoked'),\n revokedAt: Timestamp,\n wasAlreadyRevoked: z.boolean(),\n inFlight: z\n .object({\n admittedUses: z.number().int().nonnegative().nullable(),\n lastUsedAt: Timestamp.nullable(),\n })\n .strict(),\n exposure: DelegationExposureSchema,\n enforcement: z.literal('checkpoint_verification'),\n })\n .strict();\nexport type DelegationRevokeResponse = z.infer<typeof DelegationRevokeResponseSchema>;\n","import { z } from 'zod';\n\n/** Why an item may not start. Frozen with Rust `ReadinessCode`: a new code is a contract change. */\nexport const TrackingReadinessReasonCodeSchema = z.enum([\n 'invalid_track',\n 'unknown_task',\n 'completion_claim_requires_verification',\n 'source_needs_reconciliation',\n 'not_queued',\n 'unapproved_revision',\n 'missing_acceptance_criteria',\n 'repositories_not_ready',\n 'authority_not_ready',\n 'external_blocker',\n 'blocking_issue_unresolved',\n 'dependency_artifact_invalid',\n 'dependency_artifact_ambiguous',\n 'dependency_artifact_missing',\n 'dependency_requires_merge',\n 'dependency_binding_missing',\n 'dependency_binding_stale',\n]);\nexport const TrackingReadinessSchema = z\n .object({\n startable: z.boolean(),\n reasons: z.array(\n z.object({ code: TrackingReadinessReasonCodeSchema, message: z.string() }).strict()\n ),\n })\n .strict();\n","import { z } from 'zod';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\nexport const CLI_PAIRING_PROTOCOL_VERSION = 2 as const;\nexport const CLI_PAIRING_UPGRADE_MESSAGE =\n 'Upgrade the KYA-OS CLI and run checkpoint init again. This pairing requires independent terminal proof.';\n\nexport const CliPairingProofSchema = z.string().regex(/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/);\nexport const CLI_PAIRING_FRAMEWORKS = ['nextjs', 'express', 'static', 'unknown'] as const;\nconst readable = z.string().max(255).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\nconst label = readable.min(1);\nconst hint = z.string().trim().min(1).max(255).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\nconst uuid = z.string().uuid();\n\nexport const CliPairingRegisterRequestSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n exchangeChallenge: CliPairingProofSchema,\n domainHint: hint.optional(),\n repoName: hint.optional(),\n framework: z.enum(CLI_PAIRING_FRAMEWORKS).optional(),\n })\n .strict();\n\nexport const CliPairingApprovedClaimSchema = z\n .object({\n userId: uuid,\n organizationId: uuid,\n projectId: uuid,\n })\n .strict();\nexport const CliPairingClaimSchema = z\n .object({\n userId: uuid,\n userEmail: label,\n userName: readable.nullable(),\n organizationId: uuid,\n organizationName: label,\n organizationSlug: readable.nullable(),\n projectId: uuid,\n projectName: label,\n projectDomain: readable.nullable(),\n })\n .strict();\nexport const CliPairingExchangeRequestSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n registrationId: uuid,\n exchangeVerifier: CliPairingProofSchema,\n approvedClaim: CliPairingApprovedClaimSchema,\n })\n .strict();\n\nexport const CliPairingRegisterDataSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n registrationId: uuid,\n claimToken: z.string().regex(/^cliclaim_[a-f0-9]{64}$/),\n claimUrl: z.string().url(),\n confirmationCode: z.string().regex(/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/),\n expiresAt: z.string().datetime(),\n })\n .strict();\nexport const CliPairingPrivateStatusDataSchema = z.discriminatedUnion('status', [\n z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n status: z.literal('pending'),\n claimed: z.null(),\n })\n .strict(),\n z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n status: z.literal('claimed'),\n claimed: CliPairingClaimSchema,\n })\n .strict(),\n]);\nexport const CliPairingExchangeDataSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n userId: uuid,\n projectId: uuid,\n organizationId: uuid,\n friendlyId: z.string().nullable(),\n apiKey: z.string().regex(/^sk_[a-f0-9]{64}$/),\n dashboardUrl: z.string().url(),\n })\n .strict();\n\nexport type CliPairingClaim = z.infer<typeof CliPairingClaimSchema>;\nexport type CliPairingApprovedClaim = z.infer<typeof CliPairingApprovedClaimSchema>;\nexport type CliPairingExchangeRequest = z.infer<typeof CliPairingExchangeRequestSchema>;\nexport type CliPairingPrivateStatusData = z.infer<typeof CliPairingPrivateStatusDataSchema>;\n","/**\n * @kya-os/checkpoint-shared\n *\n * Shared types, schemas, and constants for Checkpoint\n * This is the single source of truth for all TypeScript types\n */\n\n// Core types\nexport * from './core/detection';\nexport * from './core/ruleset-hash';\nexport * from './core/enforcement';\nexport * from './core/agent';\nexport * from './core/confidence';\nexport * from './core/risk-score';\nexport * from './core/verdict-evidence';\nexport * from './core/detection-reason-codes';\nexport * from './core/detection-reason-code-schema';\nexport * from './core/detection-reason-mapping';\n\n// Configuration types\n\n// Constants\nexport * from './constants/agents';\nexport * from './constants/bots';\nexport * from './constants/delegation';\nexport * from './constants/errors';\nexport * from './constants/limits';\nexport * from './constants/patterns';\nexport * from './constants/rules';\n\n// API types\nexport * from './api/request';\nexport * from './api/response';\nexport * from './api/event';\nexport * from './api/task-ingress';\nexport * from './api/task-a2a';\nexport * from './api/cli-identity';\nexport * from './api/bulk';\nexport * from './api/internal';\nexport * from './api/signal-exposure';\nexport type * from './api/delegation-lifecycle';\n// Fingerprint analysis types\nexport {\n FingerprintAnalysisSchema,\n FingerprintResponseSchema,\n TLSFingerprintSchema,\n NetworkTimingSchema,\n} from './api/fingerprint';\n\nexport type {\n FingerprintAnalysis,\n FingerprintResponse,\n TLSFingerprint,\n NetworkTiming,\n} from './api/fingerprint';\n\n// Re-export specific types that might be missed by wildcard exports\nexport type { SuccessResponse, PaginatedResponse, ApiKeyWithProject } from './api/internal';\n\n// Organization and multi-user types\nexport * from './types/organization';\n\n// Shopify integration types\nexport * from './types/shopify';\nexport * from './types/posture-origins-schema';\nexport * from './types/posture-report-paths-schema';\n\n// Event types\nexport * from './events/agent-shield';\nexport * from './events/behavioral';\nexport * from './events/realtime';\nexport * from './events/deploy-progress';\n\n// All type definitions\nexport * from './types';\n\n// API route types\nexport type {\n NextRouteContext,\n OptionalNextRouteContext,\n RouteParamValue,\n RouteParams,\n RouteParamsFromContext,\n} from './types/api';\n\n// All constants\nexport * from './constants';\n\n// Utility functions\nexport * from './utils/verification';\nexport * from './utils/detection-class';\nexport * from './utils/agent-runtime-label';\nexport * from './utils/client-ip';\nexport * from './utils/bot-signals';\nexport * from './utils/zod-helpers';\nexport * from './utils/allowed-domains';\nexport * from './utils/bot-signals';\n\n// Isomorphic request correlation-id derivation (traceparent → x-kya-correlation-id →\n// fallback → minted UUID). One helper every detection surface uses so a request keeps a\n// single canonical 32-hex id across surfaces. Edge/Node/browser safe (globalThis.crypto).\nexport * from './utils/correlation-id';\n\n// All schemas (for runtime validation)\nexport * from './schemas';\n\n// Analytics schemas\nexport type {\n AnalyticsQuery,\n AnalyticsSessionsQuery,\n AnalyticsAgentSourcesQuery,\n AnalyticsAgentTypesQuery,\n AnalyticsExportQuery,\n AnalyticsRealtimeQuery,\n AnalyticsTimeSeries,\n AnalyticsSummary as AnalyticsSessionsSummary,\n AnalyticsChartData,\n AnalyticsSessionsResponse,\n AgentTypeDistribution as SharedAgentTypeDistribution,\n AgentSourceDistribution,\n ConfidenceDistribution as SharedConfidenceDistribution,\n} from './schemas/analytics';\n\nexport {\n AnalyticsQuerySchema,\n AnalyticsSessionsQuerySchema,\n AnalyticsAgentSourcesQuerySchema,\n AnalyticsAgentTypesQuerySchema,\n AnalyticsExportQuerySchema,\n AnalyticsRealtimeQuerySchema,\n AnalyticsTimeSeriesSchema,\n AnalyticsSummarySchema as AnalyticsSessionsSummarySchema,\n AnalyticsChartDataSchema,\n AnalyticsSessionsResponseSchema,\n AgentTypeDistributionSchema as SharedAgentTypeDistributionSchema,\n AgentSourceDistributionSchema,\n ConfidenceDistributionSchema as SharedConfidenceDistributionSchema,\n} from './schemas/analytics';\n\n// Rule system exports - Types\nexport type {\n UserAgentRule,\n IpRangeRule,\n SignatureRule,\n BehavioralThreshold,\n BehavioralPattern,\n BehavioralRules,\n HeaderRule,\n HeaderRules,\n IpRangeCollection,\n DetectionRules,\n RuleLoadOptions,\n RuleValidationResult,\n} from './types/rules';\n\n// Rule system exports - Schemas (these export both schemas and types)\nexport {\n UserAgentRuleSchema,\n IpRangeRuleSchema,\n SignatureRuleSchema,\n BehavioralThresholdSchema,\n BehavioralPatternSchema,\n BehavioralRulesSchema,\n HeaderRuleSchema,\n HeaderRulesSchema,\n IpRangeCollectionSchema,\n DetectionRulesSchema,\n RuleLoadOptionsSchema,\n RuleValidationResultSchema,\n RuleUpdateEventSchema,\n RuleMatchResultSchema,\n validateRules,\n parseRules,\n validateRulesLoose,\n} from './schemas/rules';\n\n// Rule system exports - Constants\nexport * from './constants/rules';\n\n// Rule system exports - Classes and functions\nexport { RuleLoader, loadRulesAsync } from './rules/rule-loader';\nexport { RuleParser } from './rules/rule-parser';\nexport { RuleValidator } from './rules/rule-validator';\nexport {\n assertVendorRangesFresh,\n DEFAULT_MAX_VENDOR_RANGE_AGE_MS,\n findStaleVendorRanges,\n StaleVendorRangesError,\n type StaleVendorDetail,\n type VendorFreshnessInput,\n} from './rules/vendor-range-freshness';\n\n// Policy module (shared between middleware packages)\nexport * from './policy';\n\n// Host-adapter primitives (shared between framework wrappers — checkpoint-nextjs, checkpoint-express)\nexport * from './host-adapter';\n\n// Wire-contract Zod schemas for Vercel ↔ Fly boundaries (#2029).\n// Both the Fly gateway and the Vercel routes import + validate\n// through these schemas, so shape drift becomes a validation\n// error instead of a silent runtime bug.\nexport * from './wire';\n\n// Canonical KYA-OS signer (Sign-1 / #2500) -- value exports live ONLY at\n// the dedicated `@kya-os/checkpoint-shared/canonical-signer` subpath\n// (tsup.config.ts ships it as its own bundle entry precisely so barrel\n// consumers don't drag in `canonicalize`, an ESM-only package with no\n// `require` export condition -- pulling it into this CJS-built barrel\n// broke every tsx/CJS consumer, e.g. scripts/sync-agent-types.ts, with\n// ERR_PACKAGE_PATH_NOT_EXPORTED). `export *` here defeated that\n// isolation. Only `McpIPayload` (a type, erased at compile time) is\n// consumed through the bare barrel anywhere in the repo\n// (checkpoint-wasm-runtime/src/engine/types.ts); every value-level\n// consumer (bouncer-middleware) already imports the subpath directly.\nexport type { McpIPayload } from './canonical-signer';\n\n// KYA-OS org issuer DID derivation shared by credential issuers and verifiers.\nexport * from './mcpi/org-did';\n\n// KYA-OS user DID derivation under the org's DID tree, hashing ids that are not path segments.\nexport * from './mcpi/user-did';\n\n// KYA-OS delegation-proof request detection (P2 / DR-1) — the single header set\n// every verifier surface uses to gate org trusted-root resolution.\nexport * from './mcpi/delegation-headers';\n\n// Canonical principals + MCP client DID derivation (#3022).\nexport * from './mcpi/principal';\n\n// Reported-identity wire block — the M1 verifier→ingest contract for\n// KYA-OS-attested tool calls (agent identity taxonomy v2 §5.1). Reporter asserts\n// agent/principal/delegation; Checkpoint derives assurance.\nexport * from './mcpi/reported-identity';\n\n// Authorization Host resolution — draft-kya-http-02 §7 PEP config discovery (H1.1 #3244).\nexport * from './mcpi/authorization-host';\n\n// did:key (Ed25519 multikey) codec — pure-JS base58btc/0xed01 decode+encode for\n// RFC 9421 keyid pinning (draft-kya-http-02 / H1.2 #3245).\nexport * from './mcpi/did-key';\n\n// Tolerant + canonical publicKeyMultibase codec (z/m/u prefixes) for Ed25519\n// DID-document verification methods — the single decoder shared by\n// apps/gateway's mcp-i auth/approver resolvers and the gateway worker.\nexport * from './mcpi/multibase-ed25519';\n\n// KYA-HTTP error code registry (draft-kya-http-02 §9) — the kyaos/* wire\n// constants, parity-guarded against fixtures/kya-http/error-codes.json.\nexport * from './mcpi/kya-http-error-codes';\n\n// Common delegation-verdict shape (verifier/engine unification PR 1) — the\n// coarse kind+reason.kind both the delegation cross-runtime-parity track and\n// the gateway's engine shadow-verify (PR 5) normalize each runtime's result\n// onto.\nexport * from './mcpi/delegation-verdict';\n\n// JAFAR vendor-feed parser (AIVF-1 prep). TS-side counterpart to the\n// engine-side Rust parser that lands when Bench-Before-After-1 unblocks.\nexport * from './parsers/jafar';\n\n// Utility types\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type Nullable<T> = T | null;\n\nexport type Optional<T> = T | undefined;\n\nexport type AsyncResult<T, E = Error> = Promise<{ data: T } | { error: E }>;\n\n// Version info\nexport const VERSION = '0.1.0';\nexport const PACKAGE_NAME = '@kya-os/checkpoint-shared';\n\nexport * from './api/artifact-bindings';\nexport * from './api/graph-interfaces';\nexport * from './api/linear-installation';\nexport * from './api/task-status-projection';\nexport * from './api/management-session';\nexport * from './api/task-grant';\nexport * from './api/identity-provisioning';\nexport * from './api/model-credentials';\nexport * from './api/readable-text';\nexport * from './api/delegation-management';\nexport * from './api/tracking-readiness';\nexport * from './api/cli-registration';\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGA,MAAa,eAAe;CACxB,cAAc;CACd,SAAS;CACT,WAAW;CACX,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,eAAe;CACf,aAAa;CACb,iBAAiB;CACjB,eAAe;CACf,QAAQ;AACZ;;AAaA,IAAW;AAER,0BAA0B,wBAAwB,CAAC;;;;ACzBtD,SAAgB,OAAO,QAAQ;CAC3B,OAAOA,eAAoBC,WAAmB,MAAM;AACxD;AACA,SAAgB,QAAQ,QAAQ;CAC5B,OAAOC,gBAAqBC,YAAoB,MAAM;AAC1D;AAIA,SAAgB,KAAK,QAAQ;CACzB,OAAOC,aAAkBC,SAAiB,MAAM;AACpD;;;;ACdA,MAAa,6BAA6BC,MAAO;CAC/C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,eAAeC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,YAAY;AAC7D,MAAM,aAAaA,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;;A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umber","core._coercedBoolean","schemas.ZodBoolean","core._coercedDate","schemas.ZodDate","z.enum","z.number","z\n .object","z.string","z.literal","z\n .number","z\n .enum","z\n .enum","z.discriminatedUnion","z.object","z.literal","z.string","z.enum","z\n .enum","z.record","z.unknown","z.date","z\n .enum","z\n .number","z\n .string","z\n .record","z.number","z.array","z.boolean","z\n .object","z\n // Dual-accept (mcp-i → kya-os): accept the canonical engine value\n // `kyaos_handshake` alongside the legacy `mcp_i_handshake` so engine output\n // still validates once upstream flips its emitter.\n .enum","z.union","z.instanceof","z.enum","z.object","z.string","z.boolean","z.array","z.record","z.number","z\n .enum","z.enum","z.object","z.number","z.array","z.string","z.object","z.string","z.number","z.enum","z.object","z.string","z.array","z.number","z.object","z.number","z.enum","z.string","z\n .object","z.array","z.boolean","z.object","z.string","z.record","z\n .object","z.enum","z.boolean","z.number","z.array","z\n .array","z.object","z.boolean","z.any","z\n .object","z.string","z.number","z.array","z.enum","z\n .record","z.object","z.boolean","z.string","z.number","z\n .object","z.array","z.literal","z\n .object","z\n .record","z.unknown","z.record","z.enum","z.date","z.union","z.ipv4","z.ipv6","z.object","z.string","z.enum","z.record","z.number","z.unknown","z.boolean","z\n .object","z.array","z\n .object","Timestamp","z.string","Uuid","z.literal","z\n .string","z\n .object","z.number","z.enum","z.boolean","z.array","Id","z.string","z\n .object","z.literal","z.union","z.number","z.unknown","z\n .object","z\n .array","z\n .object","z.enum","z.object","z.discriminatedUnion","z\n .string","z\n .string","z.enum","z\n .object","z.string","z.literal","z.number","z.boolean","z.array","z\n .array","z.union","z.string","KeyDid","z\n .string","z.enum","z\n .object","z.literal","z\n .array","z.number","z\n .object","z\n .string","z\n .array","z.array","z.boolean","z.object","z.discriminatedUnion","z\n .object","Sha256Digest","z\n .object","z\n .array","z\n .object","Text","z\n .string","PublicUrl","z.object","z.string","z\n .object","z.enum","z.literal","z\n .object","z\n .array","z\n .array","z.string","z.enum","z.object","z.boolean","z.number","z.unknown","z\n .object","z.string","z.array","z.discriminatedUnion","z.literal","z.enum","z.object","z.string","z.date","z.boolean","z.number","z.array","z.record","z.unknown","z.string","z.enum","z\n .string","z.object","z.number","z.literal","z\n .object","z.array","z.boolean","z.record","z.union","z\n .object","z\n .string","z.discriminatedUnion","z\n .string","z\n .object","z\n .string","z\n .record","z.unknown","z\n .string","z.enum","z\n .object","z.boolean","z.string","z.array","z.object","z.number","z\n .object","z\n .string","z\n .array","z.string","z.NEVER","z\n .array","z.string","z.NEVER","z.string","z.object","z.coerce.number","z.coerce\n .number","z.enum","z.array","z\n .object","z.boolean","z.number","z\n .string","z.discriminatedUnion","z.literal","z.record","z.unknown","z\n .enum","z.coerce.boolean","z\n .array","z.object","z\n .array","z\n .boolean","z.object","z.boolean","z.array","z.string","z.number","z\n .object","z.record","z.unknown","z.object","z.string","z.literal","z.boolean","z.number","z.enum","z\n .string","z\n .number","z.array","z\n .object","z.object","z.string","z.number","z.enum","z.object","z.number","z.string","z.any","z.literal","DidStringSchema","z\n .string","z.enum","z\n .object","z.boolean","z.string","z.number","z.array","z\n .array","z\n .object","z.object","z.literal","z.discriminatedUnion","z\n .object","z.enum","z.object","z.string","z.number","z\n .object","z.literal","z.array","z.boolean","z\n .array","z.record","z.object","z.enum","z.string","z\n .object","z.boolean","z.array","z.number","z.object","z\n .object","z.string","z.enum","z.array","z.record","z.boolean","z.number","z.enum","z.object","z.string","z.date","z.record","z\n .object","z\n .object","z.boolean","z.number","z.array","z.any","z\n .array","z\n .object","z\n .partialRecord","z\n .array","z.enum","z.object","z.string","z.boolean","z.number","z.array","z.date","z.record","z.unknown","z.object","z.literal","z.boolean","z.string","z.enum","z.array","z.coerce.number","z.object","z.enum","z\n .string","z.coerce\n .number","z.string","z\n .string","z\n .object","z.string","z.object","z.enum","z.string","z\n .object","z.boolean","z.array","z.number","z.coerce.number","z.enum","z.strictObject","z.string","z.boolean","z.array","z.number","z\n .object","z.string","z.record","z.unknown","z.enum","z.number","z.array","z\n .string","z.object","z.string","z.enum","z.array","z.record","z.boolean","z.number","z\n .array","z\n .string","z\n .object","z\n .object","z\n .number","z\n .record","z.coerce.date","z.object","z.array","z.string","z.number","z.enum","z.record","z.any","z.boolean","z.union","z\n .object","z\n .array","z.ZodError","z.ZodError","z\n .object","z.string","z.record","z.literal","z\n .object","z\n .object","z.number","z.discriminatedUnion","z\n .string","z.string","z\n .object","z.enum","z.array","z.number","ED25519_PUBKEY_LENGTH","ED25519_MULTIKEY_LENGTH","z\n .string","z.NEVER","z\n .object","z.string","z.array","Id","z\n .string","Count","z.number","Revision","RecordDigest","AcceptanceId","z.enum","z.discriminatedUnion","z.object","z.literal","z\n .object","z\n .object","z.string","z\n .string","z.array","z\n .discriminatedUnion","z\n .object","z\n .array","z\n .string","z.number","z.string","z.array","z\n .object","z.enum","z.boolean","z.literal","z\n .array","z\n .object","z.object","z.discriminatedUnion","z\n .string","z\n .object","z.enum","z\n .object","z.string","z.boolean","z\n .string","z.literal","z.enum","z\n .string","z\n .string","Timestamp","z.string","z.array","z.NEVER","z\n .object","z.literal","z.number","z.discriminatedUnion","z\n .object","z\n .array","z.object","z\n .string","z\n .object","z.union","z\n .object","z\n .array","z.boolean","z.enum","z\n .object","z.array","z.literal","KeyDid","z.string","z\n .string","z\n .array","z.number","z\n .object","z.object","z\n .object","z.boolean","Timestamp","z.string","z\n .string","z\n .object","z.enum","z.literal","z\n .object","z.boolean","z\n .object","z.number","z\n .array","z\n .object","z.discriminatedUnion","z.object","z.record","z.array","z.string","z.enum","z\n .object","z.number","z.array","z\n .array","z.literal","z.boolean","z\n .object","z.enum","z\n .object","z.boolean","z.array","z.object","z.string","z.string","z\n .object","z.literal","z.enum","z.discriminatedUnion","z\n .object","z.null"],"sources":["../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/compat.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/coerce.js","../src/core/network-assertions.ts","../src/core/risk-score.ts","../src/core/detection-reason-code-schema.ts","../src/core/detection.ts","../src/core/agent.ts","../src/core/confidence.ts","../src/core/verdict-evidence.ts","../src/constants/agents.ts","../src/constants/bots.ts","../src/constants/delegation.ts","../src/constants/errors.ts","../src/constants/limits.ts","../src/constants/rules.ts","../src/events/behavioral.ts","../src/api/request.ts","../src/api/response.ts","../src/types/pixel.ts","../src/utils/zod-helpers.ts","../src/api/event.ts","../src/api/readable-text.ts","../src/api/model-credentials.ts","../src/api/task-a2a.ts","../src/api/task-status-projection.ts","../src/api/task-ingress.ts","../src/api/cli-identity.ts","../src/utils/allowed-domains.ts","../src/api/bulk.ts","../src/constants/ai-traffic-taxonomy.ts","../src/types/entities.ts","../src/schemas/provider-registry.ts","../src/schemas/bouncer.ts","../src/types/organization.ts","../src/mcpi/authorization-host.ts","../src/types/posture-origins-schema.ts","../src/types/posture-report-paths-schema.ts","../src/api/internal.ts","../src/api/signal-exposure.ts","../src/api/fingerprint.ts","../src/types/shopify.ts","../src/events/agent-shield.ts","../src/events/realtime.ts","../src/deploy/index.ts","../src/events/deploy-progress.ts","../src/types/analytics.ts","../src/types/detection-metadata.ts","../src/types/auth.ts","../src/types/fingerprint.ts","../src/types/signing-vendors.generated.ts","../src/types/agent-classification.ts","../src/types/admin.ts","../src/types/admin-overview.ts","../src/utils/agent-runtime-label.ts","../src/utils/correlation-id.ts","../src/schemas/auth.ts","../src/schemas/admin.ts","../src/schemas/consent-policy-endpoint.ts","../src/wire/gateway-internal-tools.ts","../src/schemas/gateway.ts","../src/schemas/index.ts","../src/schemas/rules.ts","../src/rules/rule-validator.ts","../src/data/compiled/merged-rules.json","../src/rules/rule-loader.ts","../src/rules/rule-parser.ts","../src/rules/vendor-range-freshness.ts","../src/policy/policy-lint.ts","../src/policy/index.ts","../src/wire/vault.ts","../src/mcpi/org-did.ts","../src/mcpi/user-did.ts","../src/mcpi/principal.ts","../src/mcpi/reported-identity.ts","../src/mcpi/did-key.ts","../src/mcpi/multibase-ed25519.ts","../src/mcpi/delegation-verdict.ts","../src/parsers/jafar.ts","../src/api/artifact-bindings.ts","../src/api/graph-interfaces.ts","../src/api/linear-installation.ts","../src/api/management-session.ts","../src/api/task-grant.ts","../src/api/identity-provisioning.ts","../src/api/delegation-management.ts","../src/api/tracking-readiness.ts","../src/api/cli-registration.ts","../src/index.ts"],"sourcesContent":["// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import { z } from 'zod';\n\nexport const ProxyCollectionStateSchema = z.enum([\n 'current',\n 'unavailable',\n 'stale',\n 'unsupported',\n 'conflicting',\n 'insufficient_support',\n]);\nexport type ProxyCollectionState = z.infer<typeof ProxyCollectionStateSchema>;\n\nconst epochSeconds = z.number().int().min(0).max(253402300799);\nconst percentage = z.number().int().min(0).max(100);\n\n/** Source assertions describe request egress membership, never a visitor identity or fraud verdict. */\nexport const ProxyAssertionSchema = z\n .object({\n // Preserve future kinds; compatibility mapping reports unsupported instead of guessing.\n kind: z.string().min(1),\n source: z.string().min(1),\n subjectScope: z.literal('request_egress'),\n membership: z.enum(['present', 'absent', 'unknown']),\n evidenceGrade: z.enum(['confirmed', 'vendor_reported']),\n collectionState: ProxyCollectionStateSchema,\n /** Unix seconds supplied by the source. Reader fetch time is not source observation time. */\n observedAt: epochSeconds.nullable(),\n expiresAt: epochSeconds.nullable(),\n membershipConfidence: percentage.nullable(),\n sourceReliability: percentage.nullable(),\n fraudProbability: z.number().min(0).max(1).nullable(),\n proxyClass: z.enum(['datacenter', 'unknown']).optional(),\n })\n .strict();\nexport type ProxyAssertion = z.infer<typeof ProxyAssertionSchema>;\n\nconst knownKinds = new Set([\n 'tor_exit',\n 'published_vpn_exit',\n 'observed_proxy',\n 'suspected_residential_proxy',\n 'privacy_relay',\n 'local_tunnel',\n 'hosting',\n]);\n\n/**\n * The default admits only confirmed, current assertions. maxmind_legacy preserves\n * existing vendor positives without claiming that its undated optional file is fresh.\n * Uncertain evidence never produces a confirmed-clean false Boolean.\n */\nexport function mapProxyAssertions(\n proxyAssertions: readonly ProxyAssertion[],\n nowSeconds: number,\n collectionState: ProxyCollectionState,\n compatibility: 'confirmed_current' | 'maxmind_legacy' = 'confirmed_current'\n) {\n const states: ProxyCollectionState[] = [collectionState];\n const eligible: ProxyAssertion[] = [];\n for (const assertion of proxyAssertions) {\n if (!knownKinds.has(assertion.kind)) {\n states.push('unsupported');\n continue;\n }\n states.push(assertion.collectionState);\n const explicitUnknown =\n assertion.collectionState !== 'current' &&\n assertion.collectionState !== 'insufficient_support';\n if (explicitUnknown) {\n states.push(assertion.collectionState);\n continue;\n }\n const dated = assertion.observedAt !== null && assertion.expiresAt !== null;\n const current =\n dated && assertion.observedAt! <= nowSeconds && assertion.expiresAt! > nowSeconds;\n if (dated && !current) {\n states.push('stale');\n continue;\n }\n const confirmed =\n assertion.evidenceGrade === 'confirmed' && assertion.collectionState === 'current' && current;\n const legacy =\n compatibility === 'maxmind_legacy' &&\n assertion.source === 'maxmind-anonymous-ip' &&\n assertion.evidenceGrade === 'vendor_reported' &&\n assertion.collectionState === 'insufficient_support' &&\n assertion.observedAt === null &&\n assertion.expiresAt === null;\n if (confirmed || legacy) eligible.push(assertion);\n else states.push('insufficient_support');\n }\n\n for (const assertion of eligible) {\n if (\n assertion.membership === 'present' &&\n eligible.some((other) => other.kind === assertion.kind && other.membership === 'absent')\n ) {\n states.push('conflicting');\n }\n }\n\n if (proxyAssertions.length === 0) states.push('insufficient_support');\n const proxyCollectionState = (\n [\n 'conflicting',\n 'unsupported',\n 'unavailable',\n 'stale',\n 'insufficient_support',\n 'current',\n ] as const\n ).find((state) => states.includes(state))!;\n const blocked =\n proxyCollectionState !== 'current' && proxyCollectionState !== 'insufficient_support';\n const positive = eligible.filter((assertion) => assertion.membership === 'present');\n const preferred = [\n positive.find((assertion) => assertion.kind === 'tor_exit'),\n positive.find((assertion) => assertion.kind === 'published_vpn_exit'),\n positive.find((assertion) => assertion.kind === 'suspected_residential_proxy'),\n positive.find(\n (assertion) => assertion.kind === 'observed_proxy' && assertion.proxyClass === 'datacenter'\n ),\n positive.find((assertion) => assertion.kind === 'observed_proxy'),\n ].find(Boolean);\n const types = {\n tor_exit: 'tor',\n published_vpn_exit: 'vpn',\n suspected_residential_proxy: 'residential_proxy',\n observed_proxy: preferred?.proxyClass === 'datacenter' ? 'datacenter' : 'unknown',\n } as const;\n const proxy =\n !blocked && preferred\n ? {\n isProxy: true,\n proxyType: types[preferred.kind as keyof typeof types],\n // Preserve the historical compatibility score without inventing source confidence.\n confidence:\n preferred.membershipConfidence ??\n (preferred.evidenceGrade === 'vendor_reported' ? 90 : 0),\n }\n : undefined;\n return { proxy, proxyAssertions, proxyCollectionState };\n}\n","/**\n * `riskScore` (P58/PR-A): the Noisy-Or probability that a request is\n * automated, on the wire, in the DB, and across every SDK.\n *\n * Defined once here so every consumer (pixel/enforce/detect responses, the\n * `detections.risk_score` column, the TS/.NET/Java SDK result projections,\n * the delta report) rescales the SAME source value the SAME way. Distinct\n * from `confidence`: `riskScore` is purely additive and NEVER derived from\n * or fed back into it.\n *\n * `shadow_noisy_or_confidence` is the engine's raw, UNCALIBRATED Noisy-Or\n * combiner score, on a 0-100 scale, stamped onto `detectionDetail.metadata`\n * only under `NoisyOrShadowMode.Shadow`/`Live`\n * (`rust/crates/kya-os-engine/src/api.rs::stamp_scoring_metadata`). Distinct\n * from `shadow_calibrated_confidence`, which the engine also stamps once a\n * curve is configured — `riskScoreFromMetadata` never reads that key\n * (bestbrian, PR #4999: earlier revisions of this comment called\n * `riskScore` \"calibrated\", which was wrong — see `riskScoreSourceFromMetadata`\n * below, which makes that choice an observable wire field instead of a\n * comment). Once a curve is published in production, `PR B` is where the\n * platform reconsiders which metadata key `riskScore` reads from for the\n * live-cutover semantics — this module does not change without a matching\n * decision recorded there.\n */\nimport { z } from 'zod';\n\n/** Wire shape: 0-1, two decimals, `null` when the combiner did not run. */\nexport const RiskScoreSchema = z\n .number()\n .min(0)\n .max(1)\n .nullable()\n .describe(\n 'The Noisy-Or probability that the request is automated (0-1, two decimals), uncalibrated (see riskScoreSource). Null when the combiner did not run (NoisyOrShadowMode.Off, an engine fault, or skipDetection).'\n );\nexport type RiskScore = z.infer<typeof RiskScoreSchema>;\n\n/**\n * Which metadata key `riskScore` was derived from. Always `'uncalibrated'`\n * today: `riskScoreFromMetadata` reads only `shadow_noisy_or_confidence`,\n * the combiner's raw score, never `shadow_calibrated_confidence` — even\n * when a calibration curve is configured and the engine has stamped a\n * calibrated preview alongside it. `riskScore` moving to read the\n * calibrated key is a decision this module's own doc comment says a later\n * PR makes explicitly (bestbrian, PR #4999); this field exists so that\n * switch is an observable wire change the day it happens, not a silent one.\n */\nexport const RiskScoreSourceSchema = z\n .enum(['uncalibrated', 'calibrated'])\n .nullable()\n .describe(\n \"Which metadata key riskScore was derived from: 'uncalibrated' (shadow_noisy_or_confidence, the combiner's raw score — always true today) or 'calibrated' (shadow_calibrated_confidence, not yet wired). Null exactly when riskScore is null.\"\n );\nexport type RiskScoreSource = z.infer<typeof RiskScoreSourceSchema>;\n\n/** The `detectionDetail.metadata` key `riskScore` derives from. */\nexport const SHADOW_NOISY_OR_CONFIDENCE_KEY = 'shadow_noisy_or_confidence';\n\n/**\n * Derives `riskScore` from a raw detection-metadata bag (the engine's\n * `detectionDetail.metadata`, or an ingest route's forwarded copy of the\n * `shadow_*`-filtered subset — both carry `shadow_noisy_or_confidence`\n * under the same key when the combiner ran). Returns `null` — never\n * `0` — when the key is absent, non-numeric, or the input isn't an object:\n * an actual `0` score is a real (if rare) combiner output and must stay\n * distinguishable from \"the combiner did not run\".\n *\n * Clamps to [0, 100] before rounding — a value outside that range (a bad\n * combiner input, a future engine bug) would otherwise overflow the wire\n * schema's [0, 1] domain and the DB column's `numeric(3, 2)` domain\n * (±9.99); Postgres raises 22003 on the latter, and since\n * `persistDetections` batches rows into one multi-row INSERT, a single\n * bad value fails every detection in that batch (bestbrian, PR #4999).\n *\n * Rounds the raw 0-100 value to the nearest whole number before dividing by\n * 100 — equivalent to rounding the final 0-1 value to two decimal places,\n * kept in this exact form so the same formula reads identically next to\n * the .NET (`Math.Round(raw) / 100.0`) and Java (`Math.round(raw) / 100.0`)\n * projections, which must stay in lockstep with this one (both clamp the\n * same way).\n */\nexport function riskScoreFromMetadata(metadata: unknown): number | null {\n if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)) {\n return null;\n }\n const raw = (metadata as Record<string, unknown>)[SHADOW_NOISY_OR_CONFIDENCE_KEY];\n if (typeof raw !== 'number' || !Number.isFinite(raw)) return null;\n const clamped = Math.min(100, Math.max(0, raw));\n return Math.round(clamped) / 100;\n}\n\n/**\n * Companion to `riskScoreFromMetadata`: `null` exactly when `riskScore`\n * is `null` (the combiner did not run), `'uncalibrated'` otherwise — see\n * `RiskScoreSourceSchema`'s doc comment for why this is the only value\n * this function can return today.\n */\nexport function riskScoreSourceFromMetadata(metadata: unknown): RiskScoreSource {\n return riskScoreFromMetadata(metadata) === null ? null : 'uncalibrated';\n}\n\n/**\n * `riskScoreFromMetadata`, stringified for a Drizzle `numeric(3, 2)` insert\n * column — Drizzle types Postgres `numeric` as `string` (never `number`) to\n * avoid float precision loss, so every `detections.riskScore` insert site\n * needs this rather than the bare wire/`number` value above.\n */\nexport function riskScoreColumnValue(metadata: unknown): string | null {\n const score = riskScoreFromMetadata(metadata);\n return score === null ? null : score.toFixed(2);\n}\n","/**\n * The Zod schema for one `detection/*` reason code. Kept apart from the\n * registry (`./detection-reason-codes.ts`), which loads no Zod, so the\n * registry and its mapping (`./detection-reason-mapping.ts`) can be loaded on\n * the request path from the `./reason-codes` lean entry.\n */\nimport { z } from 'zod';\n\nimport { DETECTION_REASON_CODES, type DetectionReasonCode } from './detection-reason-codes';\n\n/** The registry's value tuple, for z.enum. */\nconst REASON_CODE_VALUES = Object.values(DETECTION_REASON_CODES) as [\n DetectionReasonCode,\n ...DetectionReasonCode[],\n];\n\n/** A single `detection/*` code from the DETECTION_REASON_CODES registry. */\nexport const DetectionReasonCodeSchema = z\n .enum(REASON_CODE_VALUES)\n .describe(\n 'A machine-readable detection/* reason code from the DETECTION_REASON_CODES registry (see docs/architecture/detection-reason-codes.generated.md).'\n );\n","/**\n * Core detection types for Checkpoint\n *\n * BREAKING CHANGE v1.40.0: Confidence scores now use 0-100 scale\n * ─────────────────────────────────────────────────────────────\n * Previously: confidence values were 0-1 decimal (e.g., 0.85)\n * Now: confidence values are 0-100 percentage (e.g., 85)\n *\n * Migration guide:\n * - Test fixtures: expectedConfidence: 0.5 → expectedConfidence: 50\n * - API responses: { confidence: 0.85 } → { confidence: 85 }\n * - Threshold configs: confidenceThreshold: 0.7 → confidenceThreshold: 70\n * - Display: Math.round(confidence * 100) → Math.round(confidence)\n */\n\nimport { z } from 'zod';\nimport { ProxyAssertionSchema, ProxyCollectionStateSchema } from './network-assertions';\nexport * from './network-assertions';\n\nimport { RiskScoreSchema, RiskScoreSourceSchema } from './risk-score';\nimport { DetectionReasonCodeSchema } from './detection-reason-code-schema';\n\n/**\n * Detection class enum for clear hierarchy (updated in migration 0029)\n * - Human: Regular human user\n * - AiAgent: AI assistants (ChatGPT, Claude, etc.) - PRIMARY VALUE\n * - Bot: Bots, scrapers, crawlers (includes former 'automation' category)\n * - IncompleteData: Cannot determine due to insufficient data (replaces 'unknown')\n *\n * Legacy types (maintained for backwards compatibility):\n * - Automation: Deprecated - migrated to Bot in migration 0029\n * - Unknown: Deprecated - migrated to IncompleteData in migration 0029\n */\nexport const DetectionClassSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('Human'),\n }),\n z.object({\n type: z.literal('AiAgent'),\n agentType: z.string().optional(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n }),\n z.object({\n type: z.literal('Automation'),\n toolType: z.enum(['Puppeteer', 'Selenium', 'Playwright', 'Custom']).optional(),\n purpose: z.enum(['Testing', 'Scraping', 'Monitoring', 'Analytics', 'Other']).optional(),\n }),\n z.object({\n type: z.literal('Bot'),\n // The engine sets Scraper, SearchEngine, HeadlessBrowser, Tool and\n // HighVelocity; the others are kept for older data.\n // __tests__/core/engine-detection-detail.test.ts pins the engine's values.\n botType: z\n .enum([\n 'SearchEngine',\n 'SocialMedia',\n 'Monitoring',\n 'Scraper',\n 'Security',\n 'Analytics',\n 'HeadlessBrowser',\n 'Tool',\n 'HighVelocity',\n ])\n .optional(),\n legitimacy: z.enum(['Legitimate', 'Suspicious', 'Malicious']).optional(),\n }),\n z.object({\n type: z.literal('IncompleteData'),\n }),\n z.object({\n type: z.literal('Unknown'),\n }),\n]);\nexport type DetectionClass = z.infer<typeof DetectionClassSchema>;\n\n/**\n * Input data for agent detection\n */\nexport const DetectionInputSchema = z.object({\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n ipAddress: z.string().optional(), // Alias for ip\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n body: z.unknown().optional(),\n timestamp: z.date().default(() => new Date()),\n});\nexport type DetectionInput = z.infer<typeof DetectionInputSchema>;\n\n/**\n * Request context for analysis\n */\nexport const RequestContextSchema = z.object({\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n body: z.unknown().optional(),\n timestamp: z.date().default(() => new Date()),\n});\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n\n/**\n * Detection signal from various analysis methods\n * Note: All confidence scores use 0-100 scale for consistency\n *\n * The per-field `.describe()` strings below are the SSOT for the generated\n * signal-exposure reference (`scripts/generate-signal-exposure-docs.ts`,\n * KYA-1107): the generator throws on any undescribed field, and CI fails\n * on a stale generated page, so schema and docs cannot drift.\n */\nexport const DetectionSignalSchema = z.object({\n signalType: z\n .enum(['signature', 'pattern', 'behavioral', 'network', 'fingerprint'])\n .describe(\n 'Evidence plane this signal was observed on: cryptographic signature, User-Agent/header pattern, behavioral interaction, network/IP, or transport fingerprint.'\n ),\n confidence: z\n .number()\n .min(0)\n .max(100)\n .describe(\"This signal's own confidence contribution on the 0-100 scale.\"),\n weight: z\n .number()\n .min(0)\n .max(1)\n .describe(\"This signal's relative weight (0-1) in the combined verdict.\"),\n source: z\n .string()\n .describe(\n \"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.\"\n ),\n explanation: z\n .string()\n .describe('Human-readable explanation of what this signal observed. Prose, not a contract.'),\n metadata: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Optional source-specific structured details (e.g. the matched pattern, the vendor feed name).'\n ),\n});\nexport type DetectionSignal = z.infer<typeof DetectionSignalSchema>;\n\n/**\n * Reasoning step for transparent confidence calculation\n * Note: All confidence scores use 0-100 scale for consistency\n */\nexport const ReasoningStepSchema = z.object({\n signalType: z.string(),\n rawConfidence: z.number().min(0).max(100),\n weight: z.number().min(0).max(1),\n reliability: z.number().min(0).max(1),\n contribution: z.number(),\n explanation: z.string(),\n});\nexport type ReasoningStep = z.infer<typeof ReasoningStepSchema>;\n\n/**\n * Per-stage trace step emitted by the engine on every `verify()` call.\n * Wire keys are camelCase — mirrors `#[serde(rename_all = \"camelCase\")]`\n * on the Rust side (`rust/crates/kya-os-engine/src/types.rs`).\n */\nexport const TraceStepSchema = z.object({\n /**\n * Stable stage identifier. Canonical names: `\"detection\"` (PlainHttp) or\n * `\"identity\"` | `\"signature\"` | `\"revocation\"` | `\"expiration\"` |\n * `\"scope\"` | `\"reputation\"` | `\"policy\"` (MCP-I's 7-stage pipeline).\n * Not a union on the wire — new step names are non-breaking. Mirrors\n * `TraceStep::name` on the Rust side.\n */\n name: z.string(),\n /**\n * Per-step verdict. `\"pass\"` = step ran and succeeded, `\"fail\"` = step\n * ran and rejected, `\"skip\"` = step was skipped (e.g. no identity\n * material on PlainHttp). Mirrors `TraceVerdict` on the Rust side,\n * which serializes lowercase.\n */\n verdict: z.enum(['pass', 'fail', 'skip']),\n /**\n * Stage execution time in microseconds. Mirrors `latency_micros` on the\n * Rust side which carries the `#[serde(rename = \"latencyMicros\")]` wire\n * key.\n */\n latencyMicros: z.number(),\n /**\n * Optional human-readable reason. Always present when verdict is\n * `\"fail\"`.\n */\n reason: z.string().optional(),\n});\nexport type TraceStep = z.infer<typeof TraceStepSchema>;\n\n/**\n * Detailed reasoning for detection decisions\n * Note: All confidence scores use 0-100 scale for consistency\n */\nexport const DetectionReasoningSchema = z.object({\n primaryFactors: z.array(z.string()),\n supportingEvidence: z.array(z.string()),\n confidenceBreakdown: z.record(\n z.string(),\n z.object({\n confidence: z.number().min(0).max(100),\n weight: z.number().min(0).max(1),\n contribution: z.number(),\n })\n ),\n reasoningSteps: z.array(ReasoningStepSchema),\n explanation: z.string(),\n calculationMethod: z.string().default('weighted_aggregation'),\n});\nexport type DetectionReasoning = z.infer<typeof DetectionReasoningSchema>;\n\n/**\n * Engine self-identification — Phase 0.1 of the Checkpoint refactor.\n *\n * Stamped on every DetectionResult so the dashboard can attribute a\n * detection to the specific implementation + ruleset that produced\n * it. Distinguishes package drift (two surfaces on different SDK\n * versions) from implementation divergence (two engines disagreeing\n * on the same rules). Optional for backwards compatibility with\n * SDKs that predate Phase 0.1.\n *\n * Known engine `name` values (kept here so downstream code can rely\n * on string equality without a separate enum import — engine names\n * are forward-compatible additions, never breaking changes). All\n * names use the `checkpoint-` brand prefix; the npm packages still\n * carry the legacy `agentshield-*` names until they're migrated to\n * `checkpoint-*` shims in Phase 1, but the engine string is the\n * customer-visible attribution and must reflect the brand.\n *\n * - 'checkpoint-engine-wasm' post-refactor Rust→WASM (Phase 2)\n * - 'checkpoint-matcher-js' post-refactor pure JS matcher (Phase 2)\n * - 'checkpoint-remote' result came from a remote enforce call\n * - 'checkpoint-edge-pattern' Next.js edge regex tables (pre-Phase-1)\n * - 'checkpoint-edge-wasm' Next.js edge WASM loader (pre-Phase-1)\n * - 'checkpoint-worker-wasm' Cloudflare worker WASM (pre-Phase-1)\n * - 'checkpoint-core' core agent-detector default (pre-Phase-1)\n */\nexport const EngineInfoSchema = z.object({\n name: z.string(),\n version: z.string(),\n rulesetHash: z.string(),\n rulesetVersion: z.string(),\n buildSha: z.string().optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n});\nexport type EngineInfo = z.infer<typeof EngineInfoSchema>;\n\n/**\n * Coarse network-path classification for a request's `trueIp`. `'unknown'`\n * is the host's own \"no verdict\" value — distinct from the whole\n * {@link NetworkContextSchema} being absent (no lookup attempted at all).\n */\nexport const RoutingTypeSchema = z.enum([\n 'residential',\n 'mobile',\n 'datacenter',\n 'hosting',\n 'unknown',\n]);\nexport type RoutingType = z.infer<typeof RoutingTypeSchema>;\n\n/** Coarse proxy/anonymization category, when `ProxyInfo.isProxy` is true. */\nexport const ProxyTypeSchema = z.enum(['vpn', 'tor', 'datacenter', 'residential_proxy', 'unknown']);\nexport type ProxyType = z.infer<typeof ProxyTypeSchema>;\n\n/**\n * Host-supplied proxy/anonymization verdict for a request's `trueIp`.\n * Mirrors the Rust `ProxyInfo` (`rust/crates/kya-os-engine/src/types.rs`).\n */\nexport const ProxyInfoSchema = z.object({\n isProxy: z.boolean(),\n proxyIp: z.string().optional(),\n proxyType: ProxyTypeSchema,\n lastDetected: z.number().optional(),\n /** Provider confidence in the proxy verdict, 0-100. */\n confidence: z.number().int().min(0).max(100),\n});\nexport type ProxyInfo = z.infer<typeof ProxyInfoSchema>;\n\n/**\n * Host-supplied network / IP-intelligence context for a request's\n * `trueIp`. Legacy fields mirror the Rust `NetworkContext` and appear on\n * the engine's `VerifyResult.network` (a sibling of `DetectionDetail`, like\n * `EngineInfo` above — there is no wrapping `VerifyResultSchema`) when the\n * host supplied one, and exposed to Cedar as `context.ip_routing_type` /\n * `context.is_proxy`. Absent-safe: a request with no network context is\n * the normal case, not an error.\n */\nexport const NetworkContextSchema = z.object({\n trueIp: z.string().optional(),\n asn: z.number().int().nonnegative().optional(),\n isp: z.string().optional(),\n routingType: RoutingTypeSchema,\n proxy: ProxyInfoSchema.optional(),\n /**\n * TypeScript-host evidence, retained in detection rows and extended API read-back.\n * Older Rust readers do not echo these additive fields.\n */\n proxyAssertions: z.array(ProxyAssertionSchema).optional(),\n proxyCollectionState: ProxyCollectionStateSchema.optional(),\n});\nexport type NetworkContext = z.infer<typeof NetworkContextSchema>;\n\n/**\n * Descriptive detection detail from the engine.\n *\n * This is the signal layer: what was detected, why, and with what\n * attribution. Enforcement decisions live separately on `Decision`.\n * Enhanced with detailed reasoning, signals, and risk assessment\n */\nexport const DetectionDetailSchema = z.object({\n // Core fields\n /**\n * @deprecated Use detectionClass instead. Will be removed in v2.0.0\n * Migration guide:\n * - isAgent: false → detectionClass: { type: 'Human' }\n * - isAgent: true → check detectionClass for specific type\n */\n isAgent: z.boolean().describe('DEPRECATED: Use detectionClass instead'),\n isBot: z.boolean().optional(), // Backwards compatibility\n /** True when detected bot is an AI crawler (GPTBot, ClaudeBot, etc.) */\n isAiCrawler: z.boolean().optional(),\n\n /**\n * Confidence score (0-100 scale)\n * - 0-30: Low confidence\n * - 31-70: Medium confidence\n * - 71-90: High confidence\n * - 91-100: Very high confidence\n */\n confidence: z.number().min(0).max(100),\n\n /**\n * P58/PR-A: the Noisy-Or probability that the request is automated\n * (0-1, two decimals), uncalibrated (see `riskScoreSource` below).\n * `null` when the combiner did not run. See `RiskScoreSchema` /\n * `riskScoreFromMetadata` — always additive, never derived from or fed\n * back into `confidence` above.\n */\n riskScore: RiskScoreSchema.optional(),\n /** Which metadata key `riskScore` was derived from. See `RiskScoreSourceSchema`. */\n riskScoreSource: RiskScoreSourceSchema.optional(),\n\n // NEW: Clear classification hierarchy\n detectionClass: DetectionClassSchema,\n\n // Detection details with enhanced reasoning\n confidenceLevel: z.enum(['low', 'medium', 'high', 'very_high']).optional(),\n reasons: z.array(z.string()),\n detectedPatterns: z.array(z.string()).optional(),\n\n // NEW: Detection signals and reasoning\n signals: z.array(DetectionSignalSchema).default([]),\n reasoning: DetectionReasoningSchema.optional(),\n\n // Agent information\n detectedAgent: z\n .object({\n type: z.string(),\n name: z.string(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n version: z.string().optional(),\n })\n .optional(),\n botType: z.string().optional(), // Backwards compatibility\n agentType: z.string().optional(),\n\n // Verification and enhanced risk assessment\n verificationMethod: z\n // Dual-accept (mcp-i → kya-os): accept the canonical engine value\n // `kyaos_handshake` alongside the legacy `mcp_i_handshake` so engine output\n // still validates once upstream flips its emitter.\n .enum([\n 'signature',\n 'pattern',\n 'behavioral',\n 'network',\n 'mcp_i_handshake',\n 'kyaos_handshake',\n 'kya-http',\n 'kya-http-delegated',\n // Tier-1 RFC 9421 (Web Bot Auth) verification. The engine emits this\n // on a verified HTTP Message Signature (api.rs Tier-1 path); without\n // it here, Zod-validating a Tier-1 verdict rejects a legitimately\n // signature-verified agent.\n 'tier1_rfc9421',\n // A2A Agent Card security scheme (RFC 9421 keyid, or a JWT bearer\n // against resolved JWKS) cryptographically verified — see\n // docs/architecture/a2a-verification.md.\n 'a2a',\n 'none',\n 'error',\n ])\n .optional(),\n riskLevel: z.string().optional(),\n forgeabilityRisk: z.enum(['low', 'medium', 'high']).optional(),\n // draft-kya-http-02 §1 assurance tier the engine established for this\n // verdict (`anonymous` | `attested-bearer` | `key-bound` | `registered` |\n // `delegated`). Stamped by the engine on every verdict; the canonical\n // ladder is `AssuranceTierSchema` in `../policy/schemas`. Kept a loose\n // string here (like `riskLevel`) to avoid a core→policy module dependency.\n assurance: z.string().optional(),\n\n // NEW: Enhanced risk assessment\n riskAssessment: z\n .object({\n level: z.enum(['low', 'medium', 'high', 'critical']),\n score: z.number().min(0).max(100),\n factors: z.array(z.string()),\n forgeabilityRisk: z.enum(['low', 'medium', 'high']),\n recommendations: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n timestamp: z.union([z.date(), z.number()]).default(() => new Date()),\n requestId: z.string().optional(),\n\n /** Engine self-identification — see EngineInfoSchema. Optional for\n * pre-Phase-0.1 SDKs; dashboard treats absence as \"legacy SDK.\" */\n engine: EngineInfoSchema.optional(),\n\n /** Scopes granted by a verified single-hop delegation (the mcp-i path).\n * Surfaced by the engine so a host can FORWARD them into\n * `context.granted_scopes` (authorize()) without re-decoding the delegation\n * credential — the engine already verified them. Omitted/empty for L1\n * envelopes or any unverified/forged path. Mirrors the Rust\n * `DetectionDetail.granted_scopes` (additive, omitted when empty). */\n grantedScopes: z.array(z.string()).optional(),\n\n /**\n * Detection reason codes (#4874): namespaced detection/* codes, most-\n * significant-evidence first, derived via mapDetectionToReasonCodes.\n * Optional: only producers that opt into signal exposure (currently\n * /api/v1/detect via buildDetectionSignalExposure) populate this.\n */\n reasonCodes: z.array(DetectionReasonCodeSchema).optional(),\n});\nexport type DetectionDetail = z.infer<typeof DetectionDetailSchema>;\n\n/**\n * @deprecated Use DetectionDetailSchema. Kept for one minor release so\n * older host packages can migrate without a coordinated breaking cut.\n */\nexport const DetectionResultSchema = DetectionDetailSchema;\n\n/**\n * @deprecated Use DetectionDetail. Kept for one minor release so older\n * host packages can migrate without a coordinated breaking cut.\n */\nexport type DetectionResult = DetectionDetail;\n\n/**\n * Detection mode configuration\n */\nexport const DetectionModeSchema = z.enum(['strict', 'balanced', 'lenient']);\nexport type DetectionMode = z.infer<typeof DetectionModeSchema>;\n\n/**\n * Custom detection rule\n */\nexport const CustomRuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n pattern: z.union([z.string(), z.instanceof(RegExp)]),\n weight: z.number().min(0).max(1),\n type: z.enum(['userAgent', 'header', 'behavior', 'ip']),\n enabled: z.boolean().default(true),\n});\nexport type CustomRule = z.infer<typeof CustomRuleSchema>;\n\n/**\n * Detection options\n */\nexport const DetectionOptionsSchema = z.object({\n mode: DetectionModeSchema.optional(),\n customRules: z.array(CustomRuleSchema).optional(),\n enablePatternMatching: z.boolean().default(true),\n enableBehaviorAnalysis: z.boolean().default(true),\n enableNetworkAnalysis: z.boolean().default(true),\n confidenceThreshold: z.number().min(0).max(100).default(70),\n});\nexport type DetectionOptions = z.infer<typeof DetectionOptionsSchema>;\n\n/**\n * Utility functions for confidence score conversion\n * All internal processing should use 0-100 scale\n */\nexport const ConfidenceUtils = {\n /**\n * Convert 0-1 scale to 0-100 scale\n */\n fromDecimal(score: number): number {\n return Math.round(Math.max(0, Math.min(1, score)) * 100);\n },\n\n /**\n * Convert 0-1000 scale to 0-100 scale\n */\n fromThousand(score: number): number {\n return Math.round(Math.max(0, Math.min(1000, score)) / 10);\n },\n\n /**\n * Convert 0-100 scale to 0-1 scale (for legacy compatibility)\n */\n toDecimal(score: number): number {\n return Math.max(0, Math.min(100, score)) / 100;\n },\n\n /**\n * Convert 0-100 scale to 0-1000 scale (for WASM compatibility)\n */\n toThousand(score: number): number {\n return Math.round(Math.max(0, Math.min(100, score)) * 10);\n },\n\n /**\n * Normalize any confidence score to 0-100 scale\n */\n normalize(score: number): number {\n if (score <= 1) {\n // Assume 0-1 scale\n return this.fromDecimal(score);\n } else if (score <= 100) {\n // Already 0-100 scale\n return Math.round(Math.max(0, Math.min(100, score)));\n } else {\n // Assume 0-1000 scale\n return this.fromThousand(score);\n }\n },\n\n /**\n * Get confidence level from score\n */\n getLevel(score: number): 'low' | 'medium' | 'high' | 'very_high' {\n const normalizedScore = this.normalize(score);\n if (normalizedScore >= 91) return 'very_high';\n if (normalizedScore >= 71) return 'high';\n if (normalizedScore >= 31) return 'medium';\n return 'low';\n },\n\n /**\n * Format score for display as percentage\n */\n toPercentage(score: number): string {\n return `${this.normalize(score)}%`;\n },\n};\n\n/**\n * Known AI crawler name patterns. Used as a fallback when isAiCrawler is not\n * explicitly set (e.g., pattern-detection paths that don't go through WASM).\n */\nconst AI_CRAWLER_NAMES = [\n 'gptbot',\n 'claudebot',\n 'perplexitybot',\n 'deepseekbot',\n 'bytespider',\n 'ccbot',\n 'google-extended',\n 'cohere',\n 'huggingface',\n 'amazon bedrock',\n 'vertex',\n];\n\n/**\n * Check if an agent name matches a known AI crawler.\n * Use this to set isAiCrawler on detection results from pattern-based paths.\n */\nexport function isKnownAiCrawler(agentName: string | undefined | null): boolean {\n if (!agentName) return false;\n const lower = agentName.toLowerCase();\n return AI_CRAWLER_NAMES.some((crawler) => lower.includes(crawler));\n}\n","/**\n * Agent-specific types and schemas\n */\n\nimport { z } from 'zod';\n\n/**\n * Known AI agent types (AI companies only, not traditional bots)\n */\nexport const AgentTypeSchema = z.enum([\n // OpenAI\n 'openai',\n 'chatgpt',\n // Anthropic\n 'claude',\n 'anthropic',\n // Search AI\n 'perplexity',\n 'phind',\n 'you',\n 'neeva',\n // Big Tech AI\n 'google',\n 'microsoft',\n 'meta',\n 'alibaba',\n // AI Model Providers\n 'mistral',\n 'cohere',\n 'huggingface',\n 'inflection',\n 'stability',\n 'replicate',\n 'together',\n '01ai',\n // Content/Writing AI\n 'writer',\n 'jasper',\n // Additional AI vendors — Engine-Pattern-Codegen-Retirement-1 backfilled\n // these after the SSOT migration surfaced legacy patterns_generated.rs\n // entries (xAI Grok, DeepSeek-User/DeepSeekBot, Amazon Q + NovaAct,\n // KYA Agent) that were never represented in TS. Their patterns lived\n // only in the retired YAML→Rust pipeline; without these types the\n // backfilled `KNOWN_AGENT_PATTERNS` entries would have to coerce to\n // `'unknown'` and lose per-vendor classification downstream.\n 'xai',\n 'deepseek',\n 'amazon',\n 'kya',\n // Unknown AI agent\n 'unknown',\n]);\nexport type AgentType = z.infer<typeof AgentTypeSchema>;\n\n/**\n * Agent information\n */\nexport const AgentInfoSchema = z.object({\n type: AgentTypeSchema,\n name: z.string(),\n version: z.string().optional(),\n provider: z.string().optional(),\n verified: z.boolean().default(false),\n});\nexport type AgentInfo = z.infer<typeof AgentInfoSchema>;\n\n/**\n * Agent pattern for matching\n *\n * F-08 PR-C: each pattern entry now carries its own `category` value.\n * Replaces the previous arrangement where agent-types-sync.service.ts\n * hardcoded `'ai_assistant'` for every KNOWN_AGENT_PATTERNS entry,\n * which conflated training crawlers with interactive AI assistants.\n * Targets the 9-value canonical taxonomy locked by F-03 (#2160) — see\n * AgentCategorySchema in `../types/agent-classification`.\n *\n * Optional for backward compatibility with any external callers; the\n * sync service falls back to `'ai_assistant'` if absent (pre-PR-C\n * behaviour). New entries should always declare a category explicitly.\n */\nexport const AgentPatternSchema = z.object({\n id: z.string(),\n type: AgentTypeSchema,\n name: z.string(),\n patterns: z.array(z.string()),\n headers: z.record(z.string(), z.string()).optional(),\n ipRanges: z.array(z.string()).optional(),\n confidence: z.number().min(0).max(1).default(0.8),\n category: z\n .enum([\n 'ai_assistant',\n 'search_engine',\n 'social_media',\n 'monitoring',\n 'scraper',\n 'automation',\n 'security',\n 'analytics',\n 'unknown',\n ])\n .optional(),\n /**\n * Whether this pattern represents a known, declared, well-behaved\n * crawler / agent. Optional — defaults to `true` for known AI\n * providers in KNOWN_AGENT_PATTERNS (Anthropic's ClaudeBot, OpenAI's\n * GPTBot, etc. all respect robots.txt and declare themselves).\n *\n * F-08 PR-C followup (cursor bot review): without this field,\n * `agent-types-sync.service.ts` derives isLegitimate from category\n * via a hardcoded `ai_assistant | search_engine | social_media` set.\n * That set excludes `scraper`, so well-behaved AI training crawlers\n * (which legitimately live in the `scraper` bucket per F-03's\n * locked taxonomy) would silently flip from isLegitimate=true to\n * false on the next sync. Per-entry isLegitimate prevents that.\n */\n isLegitimate: z.boolean().optional(),\n});\nexport type AgentPattern = z.infer<typeof AgentPatternSchema>;\n\n/**\n * Agent classification result\n */\nexport const AgentClassificationSchema = z.object({\n primary: AgentTypeSchema,\n secondary: z.array(AgentTypeSchema).optional(),\n confidence: z.number().min(0).max(1),\n matchedPatterns: z.array(z.string()),\n});\nexport type AgentClassification = z.infer<typeof AgentClassificationSchema>;\n","/**\n * Confidence and risk assessment types\n */\n\nimport { z } from 'zod';\nimport type { SignalMode, SignalPlane, StabilityTier } from '../signals/types';\n\n/**\n * Confidence levels for detection\n */\nexport const ConfidenceLevelSchema = z.enum(['low', 'medium', 'high', 'very_high']);\nexport type ConfidenceLevel = z.infer<typeof ConfidenceLevelSchema>;\n\n/**\n * Forgeability risk levels\n */\nexport const ForgeabilityRiskSchema = z.enum(['low', 'medium', 'high']);\nexport type ForgeabilityRisk = z.infer<typeof ForgeabilityRiskSchema>;\n\n/**\n * Risk assessment result\n */\nexport const RiskAssessmentSchema = z.object({\n level: z.enum(['low', 'medium', 'high', 'critical']),\n score: z.number().min(0).max(1),\n factors: z.array(z.string()),\n forgeabilityRisk: ForgeabilityRiskSchema,\n recommendations: z.array(z.string()).optional(),\n});\nexport type RiskAssessment = z.infer<typeof RiskAssessmentSchema>;\n\n/**\n * Confidence breakdown by detection method\n */\nexport const ConfidenceBreakdownSchema = z.object({\n patternMatching: z.number().min(0).max(1).optional(),\n behaviorAnalysis: z.number().min(0).max(1).optional(),\n networkAnalysis: z.number().min(0).max(1).optional(),\n signatureVerification: z.number().min(0).max(1).optional(),\n overall: z.number().min(0).max(1),\n});\nexport type ConfidenceBreakdown = z.infer<typeof ConfidenceBreakdownSchema>;\n\n/**\n * Confidence threshold configuration\n * Using 0-1 scale for internal consistency\n */\nexport const ConfidenceThresholdSchema = z.object({\n low: z.number().min(0).max(1).default(0.3),\n medium: z.number().min(0).max(1).default(0.6),\n high: z.number().min(0).max(1).default(0.8),\n veryHigh: z.number().min(0).max(1).default(0.95),\n});\nexport type ConfidenceThreshold = z.infer<typeof ConfidenceThresholdSchema>;\n\n/**\n * Helper function to get confidence level from score\n */\nexport function getConfidenceLevel(\n score: number,\n thresholds?: ConfidenceThreshold\n): ConfidenceLevel {\n const t = thresholds || {\n low: 0.3,\n medium: 0.6,\n high: 0.8,\n veryHigh: 0.95,\n };\n\n if (score >= t.veryHigh) return 'very_high';\n if (score >= t.high) return 'high';\n if (score >= t.medium) return 'medium';\n return 'low';\n}\n\n// ============================================================================\n// CONFIDENCE SCALE UTILITIES\n// ============================================================================\n//\n// IMPORTANT: All Checkpoint confidence scores use a 0.0-1.0 scale internally.\n// - WASM detect_agent() returns: 0.95 (not 95)\n// - Pattern definitions use: 0.70, 0.85, 0.95 (not 70, 85, 95)\n// - Thresholds should be: 0.3, 0.7, 0.9 (not 30, 70, 90)\n//\n// Use these utilities to convert for display or validate incoming values.\n// ============================================================================\n\n/**\n * Convert confidence (0.0-1.0) to percentage (0-100) for display\n *\n * @example\n * const result = detect_agent(metadata); // returns 0.95\n * toPercent(result.confidence) // returns 95\n */\nexport function toPercent(confidence: number): number {\n return Math.round(confidence * 100);\n}\n\n/**\n * Format confidence as percentage string\n *\n * @example\n * formatConfidence(0.95) // \"95%\"\n */\nexport function formatConfidence(confidence: number): string {\n return `${toPercent(confidence)}%`;\n}\n\n/**\n * Validate and normalize confidence to 0.0-1.0 scale.\n * If value > 1, assumes it's in 0-100 scale and converts.\n * Logs warning in development when conversion happens.\n *\n * @example\n * normalizeConfidence(0.95) // 0.95 (unchanged)\n * normalizeConfidence(95) // 0.95 (converted, logs warning)\n */\nexport function normalizeConfidence(value: number, context?: string): number {\n if (value > 1.0) {\n if (process.env.NODE_ENV !== 'production') {\n const location = context ? ` in ${context}` : '';\n console.warn(\n `[AgentShield] Confidence value ${value}${location} appears to be 0-100 scale. ` +\n `Expected 0.0-1.0. Auto-converting to ${value / 100}.`\n );\n }\n return Math.min(value / 100, 1.0);\n }\n return Math.max(0, Math.min(value, 1.0));\n}\n\n// ============================================================================\n// ENTROPY-DERIVED CONFIDENCE (P19)\n// ============================================================================\n//\n// This is a different axis from classification PROBABILITY (P17/P18's\n// calibrated \"how likely is this traffic automated\"). Confidence measures\n// how much evidence we collected, not what we concluded from it. A\n// high-confidence human and a high-confidence bot are both possible; a\n// low-confidence read of either can happen too. Never combine the two\n// into one number, and name them distinctly wherever both appear (see\n// P51 for the UI-facing convention, which this ticket does not set).\n//\n// THE FORMULA, RATIFIED\n// ----------------------\n// Every observed signal contributes information in bits: `-log2(u)` once\n// the P21 frequency table populates `u` (the coincidence probability —\n// how often two unrelated visitors would agree on this read), falling\n// back to a tier-based proxy (TIER_INFO_BITS) until then. A signal whose\n// `mode` is 'never' contributes nothing, matching the registry's own\n// contract that such signals never feed identity.\n//\n// Raw evidence bits are not simply summed, because signals sharing a\n// Merkle `group` (near-duplicate reads of the same underlying source,\n// e.g. a canvas signal and its v2 fork) or the same `plane` (broader\n// subsystem, e.g. two different rendering reads sharing GPU/driver\n// characteristics) co-vary — they are not independent evidence, so\n// summing them at face value would overstate what six correlated reads\n// from one plane tell you versus three genuinely independent ones.\n//\n// Instead, contributions are combined with a two-tier discount, geometric\n// by rank within each tier:\n//\n// groupBits(group) = Σ_i bits_i * GROUP_DISCOUNT^i (i-th largest bits in the group, 0-indexed)\n// planeBits(plane) = Σ_j groupBits_j * PLANE_DISCOUNT^j (j-th largest groupBits in the plane)\n// totalBits = Σ_planes planeBits(plane) (full weight — planes are independent by definition)\n//\n// This is deliberately the maximum weighted sum achievable by any\n// pairing of (sorted) values against (sorted) discount weights — by the\n// rearrangement inequality, sorting descending against descending\n// weights is that maximum. That characterization is what makes the\n// result PROVABLY monotonic: `Σ v_(i) w_i` equals `max over permutations\n// π of Σ v_i w_π(i)`, a pointwise max of functions each linear (hence\n// non-decreasing, since every w_i >= 0) in every v_i. A max of\n// non-decreasing functions is non-decreasing, so totalBits can only\n// rise or hold steady as evidence is added at any level — removing or\n// zeroing out a signal (mode 'never' is exactly a zero-bit signal) can\n// only lower it. That is \"falls when a high-entropy signal is absent\"\n// and \"rises with independent planes\" as a mathematical guarantee, not\n// a property that happens to hold on the test fixtures.\n//\n// Bits are then mapped onto a bounded, asymptotic confidence:\n//\n// confidence = FLOOR + (CEILING - FLOOR) * (1 - e^(-totalBits / SCALE_BITS))\n//\n// This is strictly increasing in totalBits, equals FLOOR exactly at\n// zero bits (no evidence still yields a floor, never a bare zero — a\n// bare zero would read as \"we know literally nothing,\" which is never\n// true; even a non-response carries some information), and approaches\n// but never reaches CEILING (< 1.0) for any finite evidence — certainty\n// is not on offer.\n//\n// GROUP_DISCOUNT (0.5) is steeper than PLANE_DISCOUNT (0.75): a fork of\n// the same read (same group) co-varies more tightly than two different\n// subsystems that merely share a broad plane, so it is discounted harder.\n// TIER_INFO_BITS is an illustrative proxy — every registry entry's\n// `measurement` is still provisional (no shipped agreement-rate data),\n// so these are placeholder bit-counts (a \"high\" tier signal is modeled\n// as roughly as informative as picking 1-of-64; \"medium\" 1-of-8; \"low\"\n// 1-of-2) that P21's real `u` values supersede per-signal the moment\n// they land — no code change required, since `u` is checked first.\n// ============================================================================\n\n/** One observed signal's evidence-relevant metadata, as needed to compute\n * entropy-derived confidence. A structural subset of the P8 signal\n * registry's `SignalDefinition` — any `SignalDefinition` already satisfies\n * this shape — kept narrow so confidence computation doesn't couple to\n * registry bookkeeping (versioning, description, review) it doesn't need.\n */\nexport interface EvidenceSignal {\n /** Where this signal's read sits for grouping correlated evidence. */\n plane: SignalPlane;\n /** Finer-grained grouping within a plane; near-duplicate/forked reads share a group. */\n group: string;\n /** Stability tier, used as the information-content proxy until `u` is populated (P21). */\n tier: StabilityTier;\n /** Governs identity contribution: 'never' signals carry zero evidence weight. */\n mode: SignalMode;\n /** Coincidence probability from the frequency table (P21). Null until populated. */\n u: number | null;\n}\n\n/** Confidence returned for zero observed evidence. Strictly positive: even total\n * silence isn't \"we know literally nothing,\" so it never reads as a bare zero. */\nexport const ENTROPY_CONFIDENCE_FLOOR = 0.02;\n\n/** Asymptotic upper bound. Never reached for any finite evidence — certainty\n * is not on offer, per the ticket's \"bounded, and never exactly 1.0\" requirement. */\nexport const ENTROPY_CONFIDENCE_CEILING = 0.98;\n\n/** Bits of accumulated evidence at which confidence has closed roughly\n * two-thirds of the gap between FLOOR and CEILING (1 - e^-1 ≈ 0.63). */\nconst CONFIDENCE_SCALE_BITS = 8;\n\n/** Decay applied to the 2nd, 3rd, ... signal within the SAME group (rank\n * 0-indexed): near-duplicate reads of one underlying source co-vary tightly. */\nconst GROUP_DISCOUNT = 0.5;\n\n/** Decay applied to the 2nd, 3rd, ... group's contribution within the SAME\n * plane: different subsystems in one broad plane co-vary more loosely than\n * same-group reads do, so the penalty is milder than GROUP_DISCOUNT. */\nconst PLANE_DISCOUNT = 0.75;\n\n/** Illustrative information-content proxy (bits) per stability tier, used\n * only until a signal's real coincidence probability `u` is populated. */\nconst TIER_INFO_BITS: Record<StabilityTier, number> = {\n high: 6,\n medium: 3,\n low: 1,\n};\n\n/** Floor on `u` before taking -log2, so a frequency-table entry of exactly\n * (or effectively) zero can't blow the formula up to +Infinity bits. */\nconst MIN_COINCIDENCE_PROBABILITY = 1e-6;\n\nfunction signalInfoBits(signal: EvidenceSignal): number {\n if (signal.mode === 'never') return 0;\n if (signal.u !== null && Number.isFinite(signal.u)) {\n const u = Math.min(Math.max(signal.u, MIN_COINCIDENCE_PROBABILITY), 1);\n return -Math.log2(u);\n }\n // Unknown tier (or a non-finite `u` with no valid tier to fall back to) —\n // e.g. a future registry tier this build doesn't know about yet, or a\n // malformed evidence object from a caller that bypassed the type system\n // — contributes no evidence rather than poisoning the whole sum to NaN.\n return TIER_INFO_BITS[signal.tier] ?? 0;\n}\n\n/** The rearrangement-inequality-maximal weighted sum: descending values\n * paired against descending powers of `discount`. See the module doc for\n * why this specific combination rule is what makes the formula monotonic. */\nfunction sortedGeometricSum(values: number[], discount: number): number {\n return [...values]\n .sort((a, b) => b - a)\n .reduce((sum, value, rank) => sum + value * discount ** rank, 0);\n}\n\n/**\n * Computes confidence (how much evidence we have) from the signals actually\n * observed for a detection event — never from a platform/OS lookup table.\n * See the module doc above for the ratified formula and its properties.\n *\n * This is NOT a probability that traffic is automated; see P17/P18 for\n * that calibrated, separately-computed number.\n */\nexport function computeEntropyConfidence(observed: readonly EvidenceSignal[]): number {\n const bitsByPlaneAndGroup = new Map<SignalPlane, Map<string, number[]>>();\n\n for (const signal of observed) {\n const bits = signalInfoBits(signal);\n if (bits <= 0) continue;\n\n let groups = bitsByPlaneAndGroup.get(signal.plane);\n if (!groups) {\n groups = new Map();\n bitsByPlaneAndGroup.set(signal.plane, groups);\n }\n const bitsInGroup = groups.get(signal.group);\n if (bitsInGroup) {\n bitsInGroup.push(bits);\n } else {\n groups.set(signal.group, [bits]);\n }\n }\n\n let totalBits = 0;\n for (const groups of bitsByPlaneAndGroup.values()) {\n const groupContributions = Array.from(groups.values(), (bitsInGroup) =>\n sortedGeometricSum(bitsInGroup, GROUP_DISCOUNT)\n );\n // Full weight across planes: planes are independent by definition.\n totalBits += sortedGeometricSum(groupContributions, PLANE_DISCOUNT);\n }\n\n return (\n ENTROPY_CONFIDENCE_FLOOR +\n (ENTROPY_CONFIDENCE_CEILING - ENTROPY_CONFIDENCE_FLOOR) *\n (1 - Math.exp(-totalBits / CONFIDENCE_SCALE_BITS))\n );\n}\n","/**\n * Verdict evidence (P20) — the contributing-signal list behind a detection\n * verdict, as structured output rather than a debug log.\n *\n * P16/P18 combine independent `DetectionSignal`s into one confidence number\n * via a Noisy-Or combiner (`rust/crates/kya-os-engine/src/stages/scoring.rs`):\n * each signal contributes `weight * probability` (`probability` being\n * `confidence / 100`), and the combiner folds those contributions together.\n * That per-signal contribution is exactly the number a reviewer needs to\n * answer \"why did this verdict land where it did\" — and today it is\n * recomputed and discarded inside the combiner, never persisted.\n *\n * `buildVerdictEvidence` re-derives the SAME `weight * probability` term for\n * each signal and returns it as a flat, typed, sorted list: the signal's\n * name, its weight, its probability contribution, and which detection\n * `plane` (`DetectionSignal.signalType`) it came from. This is deliberately\n * NOT the raw `DetectionSignal[]` passed straight through — that already\n * exists (`metadata.enforcement.signals`) as an opaque, unstructured\n * passthrough. Evidence is the derived, reviewable projection of it.\n *\n * SCOPE at the time this module was written: emit + persist only, with\n * dashboard rendering deferred to P51. P51 has since wired this into the\n * `/activity` Inspector and the agent detail sheet's recent-activity rows\n * (`EvidenceList` in `components/features/activity/verdict-evidence-list.tsx`).\n * Unifying this with the identity/fraud-signal \"explainable verdict\" object\n * `novelty.service.ts` (P25) forward-declares is still P38 — out of scope\n * here.\n */\nimport { z } from 'zod';\nimport { DetectionSignalSchema, type DetectionSignal } from './detection';\n\n/**\n * One contributing signal behind a verdict's confidence, as persisted\n * structured output.\n *\n * - `signal` — the signal's machine-readable source identifier\n * (`DetectionSignal.source`), e.g. `\"tier3_ua_pattern\"`.\n * - `plane` — which detection plane produced it (`DetectionSignal.signalType`\n * — signature / pattern / behavioral / network / fingerprint).\n * - `weight` — the signal family's relative trust weight, 0-1.\n * - `probabilityContribution` — `weight * (confidence / 100)`, the exact\n * term the Noisy-Or combiner multiplies together\n * (`1 - Π(1 - probabilityContribution_i)`). Storing this term (rather\n * than raw `weight` + `confidence` separately) is sufficient on its own to\n * reconstruct the combiner's confidence from stored evidence alone,\n * without replaying the original request.\n */\nexport const VerdictEvidenceSchema = z.object({\n signal: z.string(),\n plane: DetectionSignalSchema.shape.signalType,\n weight: z.number().min(0).max(1),\n probabilityContribution: z.number().min(0).max(1),\n});\nexport type VerdictEvidence = z.infer<typeof VerdictEvidenceSchema>;\n\n/** `weight_i * probability_i` — mirrors the Noisy-Or combiner's own inline\n * `contribution` term (`stages::scoring::noisy_or_combine`) so the two can\n * never silently diverge. `probability` is `confidence / 100`, already\n * validated into `[0, 100]` by `DetectionSignalSchema`, so the product is\n * guaranteed to land in `[0, 1]` with no extra clamping needed. */\nfunction signalContribution(signal: DetectionSignal): number {\n return signal.weight * (signal.confidence / 100);\n}\n\n/**\n * Builds the verdict's evidence list from the engine's raw detection\n * signals — allow or block, live or shadow, persisted or not: this is a\n * pure function of `signals` with no I/O of its own, so it emits the exact\n * same evidence regardless of what a caller does with the result\n * afterward (including a caller that never persists it at all).\n *\n * Entries that don't parse as a well-formed `DetectionSignal` (a malformed\n * wire payload, or a future signal-shaped-but-not-quite record) are\n * dropped rather than allowed to poison the list with `NaN`/garbage\n * contributions — mirrors `extractShadowMetadata`'s \"never throws, always\n * returns a safe-to-use value\" contract.\n *\n * Ordering is deterministic — sorted by `(plane, signal)` and never by\n * input/iteration order, since the upstream signal list is assembled\n * differently by different detection paths (PlainHttp classification vs.\n * SDK/gateway self-reports) and must still diff/hash identically for the\n * same logical evidence. `probabilityContribution` descending is the final\n * tiebreak for the (rare) case of two entries sharing both plane and name.\n */\nexport function buildVerdictEvidence(\n signals: readonly unknown[] | null | undefined\n): VerdictEvidence[] {\n if (!signals || signals.length === 0) return [];\n\n const entries: VerdictEvidence[] = [];\n for (const raw of signals) {\n const parsed = DetectionSignalSchema.safeParse(raw);\n if (!parsed.success) continue;\n const signal = parsed.data;\n entries.push({\n signal: signal.source,\n plane: signal.signalType,\n weight: signal.weight,\n probabilityContribution: signalContribution(signal),\n });\n }\n\n entries.sort((a, b) => {\n if (a.plane !== b.plane) return a.plane < b.plane ? -1 : 1;\n if (a.signal !== b.signal) return a.signal < b.signal ? -1 : 1;\n return b.probabilityContribution - a.probabilityContribution;\n });\n\n return entries;\n}\n\n/**\n * Mirrors `UNCALIBRATED_NOISY_OR_PRIOR` in\n * `rust/crates/kya-os-engine/src/stages/scoring.rs` — the Noisy-Or\n * combiner's \"leak\" node, the baseline probability of the outcome even with\n * zero observed evidence. The Rust engine folds this into every live\n * confidence it computes (`noisy_or_confidence_percent` calls\n * `noisy_or_combine(UNCALIBRATED_NOISY_OR_PRIOR, &inputs)`); reconstructing\n * confidence from stored evidence without it silently drops a fixed,\n * predictable amount from every verdict (bestbrian, PR #4747 review:\n * verified by hand against `TWO_SIGNAL_EVIDENCE_FIXTURE` — the un-primed\n * formula returns 94.2, the real engine returns 94.78).\n *\n */\nexport const UNCALIBRATED_NOISY_OR_PRIOR = 0.1;\n\n/**\n * Reconstructs the Noisy-Or confidence (0-100 scale) from a persisted\n * evidence list alone — no access to the original request or the raw\n * signals it was built from. `1 - (1 - prior) * Π(1 - probabilityContribution_i)`,\n * the SAME formula (with the SAME prior) `stages::scoring::noisy_or_combine`\n * computes for the live verdict — this must never diverge from the number\n * the engine actually returned, or \"explainable from stored data\" is a lie\n * by a fixed, predictable margin.\n *\n * Zero evidence reconstructs to the bare prior (10.0 on the 0-100 scale),\n * never a bare 0 — a claim of certainty (\"definitely not automated\") that\n * zero observed evidence never actually supports, exactly as\n * `noisy_or_combine`'s own doc comment argues.\n *\n * This is the acceptance test made concrete: an adverse decision must be\n * explainable from what was stored, without replaying the request.\n */\nexport function reconstructConfidenceFromEvidence(evidence: readonly VerdictEvidence[]): number {\n const probabilityAbsent = evidence.reduce(\n (acc, entry) => acc * (1 - entry.probabilityContribution),\n 1 - UNCALIBRATED_NOISY_OR_PRIOR\n );\n return (1 - probabilityAbsent) * 100;\n}\n","/**\n * Known AI agent patterns and constants\n *\n * F-08 PR-C: each entry now declares its own `category` (per the 9-value\n * canonical taxonomy locked by F-03 #2160). Previously\n * agent-types-sync.service.ts hardcoded `'ai_assistant'` for every entry\n * here, which is what stamped GPTBot / ClaudeBot / etc. as ai_assistant\n * in the agent_types table and ultimately as `detection_class='ai_agent'`\n * in detections (the F-08 bug). With per-entry categories, the sync\n * service routes each entry to the correct bucket directly.\n *\n * Two bundled entries from the prior shape have been split here so a\n * single agent_types row no longer represents both an interactive AI\n * session and a training crawler:\n * - `openai-gptbot` (was: GPTBot + ChatGPT-User + gpt-* models)\n * → `openai-gptbot` (scraper, just GPTBot)\n * + `openai-chatgpt` (ai_assistant, ChatGPT-User + gpt-* models)\n * - `google-bard` (was: Google-Extended + Bard + Google-InspectionTool + gemini + palm)\n * → `google-bard` (ai_assistant), later renamed to `gemini`\n * (migration 0201, id only). Google-Extended is a robots.txt token,\n * not a User-Agent, so it has no row.\n *\n * Mirrors the equivalent split in apps/web/scripts/seed-agent-types-data.ts\n * (claude / claudebot, perplexity / perplexity-bot).\n */\n\nimport { AgentPattern } from '../core/agent';\n\n/**\n * Known AI agent patterns\n */\nexport const KNOWN_AGENT_PATTERNS: AgentPattern[] = [\n // OpenAI — split into crawler vs interactive (PR-C)\n {\n id: 'openai-gptbot',\n type: 'openai',\n name: 'GPTBot',\n patterns: ['GPTBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'openai-chatgpt',\n type: 'openai',\n name: 'ChatGPT',\n // `OAI-SearchBot` backfilled by Engine-Pattern-Codegen-Retirement-1\n // after the legacy YAML→Rust path was retired. Previously detected\n // only via the legacy generator; the new TS SSOT migration would\n // have silently lost it.\n patterns: ['ChatGPT-User', 'OAI-SearchBot'],\n headers: {\n 'X-OpenAI-Assistant': '*',\n },\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n // GPT-Crawler — distinct from GPTBot (OpenAI's official training crawler);\n // tracked separately so the classifier can attribute hits to the\n // right entity. PDM-2 promoted from the INTERACTIVE_AGENT_PATTERNS\n // supplement.\n {\n id: 'openai-gpt-crawler',\n type: 'openai',\n name: 'GPT Crawler',\n patterns: ['GPT-Crawler'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // OpenAI generic vendor fallback — catches UAs that mention OpenAI\n // but use an undocumented sub-token (e.g. `OpenAI-Foo/1.0`,\n // `OpenAI-Web/2.0`). Word-boundary anchored (post-#2599). Lower\n // confidence than the strict per-token entries above. PDM-2.\n {\n id: 'openai-generic',\n type: 'openai',\n name: 'OpenAI',\n patterns: ['OpenAI'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Anthropic — split into interactive assistant vs training crawler.\n // The 'anthropic-ai' UA token used to live in this entry's patterns\n // alongside 'Claude-Web', which made every anthropic-ai crawler hit\n // resolve as ai_assistant. Moved out into the dedicated\n // `anthropic-ai-crawler` entry below so the classifier produces\n // (scraper, bot) for those rows. Same shape as the openai-gptbot /\n // openai-chatgpt split.\n {\n id: 'anthropic-claude',\n type: 'anthropic',\n name: 'Claude',\n patterns: [\n 'Claude-Web',\n 'claude-web',\n // Claude-User is Anthropic's user-initiated fetcher (the assistant\n // pulls a URL on the user's behalf — equivalent to ChatGPT-User).\n // Distinct from ClaudeBot (training crawler, captured separately\n // by `anthropic-claudebot`). anthropic.yaml already lists\n // 'Claude-User' on `anthropic_claude`, so the Rust WASM engine\n // recognizes it; this entry was the only layer where the pattern\n // was missing, which left ~14 real Claude-User sessions on\n // production stamped (bot, …) instead of (ai_agent, ai_assistant).\n 'Claude-User',\n // `Claude-SearchBot` and `claude-code` backfilled by\n // Engine-Pattern-Codegen-Retirement-1 — both were in the retired\n // YAML→Rust pipeline but never represented in TS. Claude-Code is\n // Anthropic's CLI agent (this very tool); Claude-SearchBot is\n // their search-augmented fetcher (parallel to OAI-SearchBot).\n 'Claude-SearchBot',\n 'claude-code',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #e111d65f):\n // the retired YAML→Rust pipeline matched both `claude-code` AND\n // `claude code` (space-separated). Some host wrappers stamp the\n // tool name with a space; the hyphenated form alone misses them.\n 'claude code',\n ],\n headers: {\n 'X-Anthropic-Client': '*',\n },\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'anthropic-claudebot',\n type: 'anthropic',\n name: 'ClaudeBot',\n patterns: ['ClaudeBot', 'claudebot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'anthropic-ai-crawler',\n type: 'anthropic',\n name: 'Anthropic-AI Crawler',\n patterns: ['anthropic-ai'],\n // 0.95, matching every other single-exact-token vendor crawler\n // (openai-gptbot, anthropic-claudebot, meta-externalagent,\n // gemini-deep-research, deepseek-bot). Previously 0.9, tied with\n // anthropic-generic below — classifyByUserAgent picks the first\n // match on a confidence tie (strict `>`, no stable order), so an\n // 'anthropic-ai' UA could resolve to either row depending on DB\n // iteration order, reopening the exact misclassification this\n // taxonomy split retires the token to fix. Caught by Bugbot on\n // #4172 once the migration landing this row made the tie live.\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // Anthropic generic vendor fallback — catches UAs that mention\n // Anthropic but use an undocumented sub-token (e.g. `Anthropic-Web`,\n // future variants). Word-boundary anchored (post-#2599) — only\n // matches when `Anthropic` is a standalone token, not embedded in\n // e.g. `AnthropicAssistant`. Lower confidence than the per-token\n // entries above. PDM-2 promoted from the INTERACTIVE_AGENT_PATTERNS\n // supplement.\n {\n id: 'anthropic-generic',\n type: 'anthropic',\n name: 'Anthropic',\n patterns: ['Anthropic'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Perplexity (training crawler, distinct from the interactive Perplexity-User\n // session captured by perplexity-user below)\n {\n id: 'perplexity-bot',\n type: 'perplexity',\n name: 'PerplexityBot',\n patterns: ['PerplexityBot', 'Perplexica'],\n confidence: 0.9,\n category: 'scraper',\n isLegitimate: true,\n },\n // Interactive Perplexity fetcher — parallel to ChatGPT-User shape;\n // the assistant pulls a URL on a human's behalf. Distinct from\n // PerplexityBot (training crawler). PDM-2 promoted this from the\n // INTERACTIVE_AGENT_PATTERNS supplement that #2599 carved out.\n {\n id: 'perplexity-user',\n type: 'perplexity',\n name: 'Perplexity',\n // `Comet` is Perplexity's AI-powered browser; backfilled into the\n // TS canonical via Engine-Pattern-Codegen-Retirement-1 after the\n // SSOT consolidation surfaced the gap. Previously detected only by\n // the legacy YAML→Rust codegen path; `apps/web/scripts/seed-agent-\n // types-data.ts` listed it as a Perplexity AI detection while\n // `KNOWN_AGENT_PATTERNS` did not. Now structurally enforced.\n patterns: ['Perplexity-User', 'Perplexity-AI'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n // Perplexity generic vendor fallback — catches UAs that mention\n // Perplexity but use an undocumented sub-token (future variants).\n // Lower confidence than the strict per-token entries above, and\n // declared after them: the engine takes the first match in source\n // order, so this only wins on truly unknown shapes. (The DB-side\n // `classifyByUserAgent` path instead picks the highest-confidence\n // match; both agree here.) Word-boundary anchored (post-#2599) so\n // `perplexity` only matches as a standalone token, not embedded.\n {\n id: 'perplexity-generic',\n type: 'perplexity',\n name: 'Perplexity',\n patterns: ['Perplexity'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Google — interactive assistants. `Google-Extended` is a robots.txt\n // product token (Google documents that it has no separate user-agent\n // string; the crawling itself uses Google's regular crawler UAs), so it\n // has no row here.\n {\n // ORDERING NOTE: `gemini-deep-research` MUST appear BEFORE\n // `gemini` (renamed from `google-bard`, migration 0201) so the\n // more-specific 'Gemini-Deep-Research'\n // pattern wins under the engine's first-match-wins iteration over\n // AI_AGENT_PATTERNS. The legacy YAML→Rust output collapsed all\n // Google patterns under a single \"Google AI\" name with identical\n // confidence (0.90), so shadowing was benign; the SSOT migration\n // surfaced different names + confidences (0.95 scraper vs 0.90\n // ai_assistant), making the order load-bearing.\n //\n // Google's user-directed deep-research agent — distinct UA from\n // Bard/Gemini interactive sessions. CT85 (pattern-gaps-and-taxonomy,\n // 2026-09-03): was category 'scraper', which the DB agent_types\n // catalog row (apps/web/scripts/seed-agent-types-data.ts, migration\n // 0231) copied — that mismatched the engine's own ai_agent/95 wire\n // verdict and Google's own docs (a user-directed agent, not a\n // training crawler). Realigned here too so this SSOT, the DB\n // catalog, and the wire all agree — this is the file\n // agent-types-sync.service.ts reads as canonical, so leaving it at\n // 'scraper' would let a future sync silently revert the DB fix.\n id: 'gemini-deep-research',\n type: 'google',\n name: 'Gemini-Deep-Research',\n patterns: ['Gemini-Deep-Research', 'gemini-deep-research'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n // Renamed from 'google-bard' (migration 0201, P4 follow-up). The prior\n // fix (Fix-Gemini-Mislabeled-As-Google-Bard-1) deliberately left the id\n // as `google-bard` and only renamed the human-facing `name` below,\n // because the id is the stable codegen/stored key (Rust pattern ids via\n // build.rs -> known-agent-patterns.json, the agent_types.name DB row,\n // `agent-classification.service.ts`'s directMappings). This PR does the\n // full id rename instead: verified zero live project/org policies\n // (cedar_policy_text, allowed/denied agent-type lists) reference the\n // 'google-bard' slug (checked against a Neon branch off prod main,\n // 2026-08-14), so the earlier narrower fix's risk no longer applies.\n // `agent_types.agent_did` already reads\n // `did:web:knowthat.ai:agents:gemini` — this id rename just catches the\n // codegen/DB slug up to what the DID already assumed.\n id: 'gemini',\n type: 'google',\n name: 'Google Gemini',\n // Engine-Pattern-Codegen-Retirement-1 corrections:\n // - REMOVED `Google-InspectionTool` from this entry. The legacy\n // YAML→Rust pipeline classified Google-InspectionTool as a\n // Googlebot-family search inspection tool (Search Console\n // verification, structured-data testing), not a Bard/Gemini AI\n // session. Moved to `NON_AI_PATTERNS` in\n // `rust/crates/kya-os-engine/src/stages/patterns.rs` under the\n // `Googlebot` family so classification stays SearchCrawler.\n // - ADDED `GoogleAgent-Mariner` (Google's browser-controlling agent\n // product), which was in the retired pipeline, never in TS.\n //\n // Engine-Pattern-Codegen-Retirement-2 (this PR, Bugbot #ae22713a and\n // #6984df6d): bare 'gemini' matched `GeminiiOS` (Google's own\n // Gemini app rendering a page in its in-app webview — a HUMAN, not an\n // agent) as a plain unanchored substring — `build.rs` emits every\n // pattern here into `format!(\"(?i){pattern}\")` with no escaping and no\n // boundary, so a literal `'gemini'` compiles to `Regex::new(\"(?i)gemini\")`,\n // which `.is_match()`-style scanning matches anywhere. That reopened,\n // one layer down, the exact hole migration 0208 closed on the\n // DB-side `classifyByUserAgent` path: this PR's own `lookupAgentDid`\n // fix matches the WASM engine's emitted `name` ('Google Gemini')\n // against `agent_types.displayName` for the enforce/pixel-track\n // routes, which run no TS classifier and never touch\n // `classifyByUserAgent` at all — so `GeminiiOS` could still reach the\n // live `gemini` DID via this second, engine-only path.\n //\n // First attempt was an outright removal, which closed the hole but\n // also dropped genuine coverage: a bare `Gemini/1.0` or\n // `Google-Gemini/1.0` UA carrying no specific model suffix no longer\n // matched anything (caught by Bugbot #6984df6d's follow-up review,\n // and independently by 4 apps/web unit tests asserting exactly that\n // coverage — see git history). Word-boundary anchors close the false\n // positive AND keep the coverage: `\\bgemini\\b` matches `Gemini/1.0`\n // and `Google-Gemini/1.0` (boundary before the leading `G`/after `-`,\n // and before the trailing `/`) but NOT `GeminiiOS` (no boundary\n // between the two `i`s — both are word characters). Model-version\n // names (`gemini-pro`, `palm2`, `LaMDA`) are not UA tokens and are\n // not listed; `\\bgemini\\b` already covers `gemini-pro/1.0`. TS\n // string literals need `\\\\b` (double backslash) to produce a literal\n // `\\b` in the resulting string — `\\b` alone is the JS backspace\n // escape, not a regex boundary.\n patterns: ['Bard', '\\\\bgemini\\\\b', 'GoogleAgent-Mariner'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // NotebookLM's user-triggered fetcher (developers.google.com/search/docs/\n // crawling-indexing/google-user-triggered-fetchers). `\\bgemini\\b` above\n // does not match `Google-GeminiNotebook` (no boundary after `Gemini`), so\n // this row is the only one that claims it.\n {\n id: 'google-notebooklm',\n type: 'google',\n name: 'Google NotebookLM',\n patterns: ['Google-GeminiNotebook'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Microsoft Copilot\n {\n id: 'microsoft-copilot',\n type: 'microsoft',\n name: 'Microsoft Copilot',\n patterns: [\n 'github-copilot',\n 'microsoft-copilot',\n // Word-bounded: a bare substring also matched app and framework\n // tokens that merely contain the word.\n '\\\\bcopilot\\\\b',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #89cfb23d):\n // the retired YAML→Rust pipeline carried `BingPreview/.*ChatGPT`\n // for Bing Copilot UAs. Without this, BingPreview+ChatGPT UAs hit\n // the non-AI `BingPreview` Bingbot rule and resolve as SearchBot.\n // Note: this entry must order BEFORE the Bingbot regex in the\n // composed table — AI patterns lead, so the dispatch order in\n // patterns.rs::AI_AGENT_PATTERNS (AI_PATTERNS_FROM_TS then\n // NON_AI_PATTERNS) preserves the precedence the legacy table\n // gave Microsoft AI at confidence 0.9.\n 'BingPreview/.*ChatGPT',\n ],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Meta AI (LLaMA) — interactive assistant only.\n // Disambiguated from Meta's web crawler (Meta-ExternalAgent) in the\n // dedicated entry below. Pre-split, prod's `meta-ai` agent_types row\n // had 'Meta-ExternalAgent' in its patterns AND category='ai_assistant',\n // which silently classified ~10K Meta-ExternalAgent crawler hits as\n // AI-assistant traffic on Hardware-World alone. Same pattern as the\n // openai-gptbot / openai-chatgpt split.\n {\n id: 'meta-ai',\n type: 'meta',\n name: 'Meta AI',\n patterns: ['Meta-AI'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-muse',\n type: 'meta',\n name: 'Meta Muse',\n patterns: ['Meta-Muse'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-externalagent',\n type: 'meta',\n name: 'Meta-ExternalAgent',\n patterns: ['Meta-ExternalAgent', 'meta-externalagent'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // Meta's user-triggered fetcher (developers.facebook.com/docs/sharing/\n // webmasters/web-crawlers): retrieves individual links at a user's\n // request and may ignore robots.txt. Interactive, so ai_assistant like\n // the other user-initiated fetchers (ChatGPT-User, Claude-User), not\n // the meta-externalagent crawler above.\n {\n id: 'meta-externalfetcher',\n type: 'meta',\n name: 'Meta-ExternalFetcher',\n patterns: ['Meta-ExternalFetcher'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-webindexer',\n type: 'meta',\n name: 'Meta-WebIndexer',\n patterns: ['meta-webindexer'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Cohere — bot variant (training/research crawler)\n {\n id: 'cohere-bot',\n type: 'cohere',\n name: 'CohereBot',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #8007b7a3):\n // the retired YAML→Rust pipeline matched the literal `CohereBot`\n // token; without it the UA falls through to the generic-bot\n // fallback (`bot` substring) and resolves as `Generic Bot` /\n // OtherBot, losing vendor attribution.\n patterns: ['cohere-ai', 'CohereBot'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // HuggingFace — bot variant\n {\n id: 'huggingface-bot',\n type: 'huggingface',\n name: 'HuggingFaceBot',\n patterns: ['HuggingFace', 'transformers'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Mistral AI\n {\n id: 'mistral-ai',\n type: 'mistral',\n name: 'MistralBot',\n patterns: ['mistral'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Inflection AI\n {\n id: 'inflection-pi',\n type: 'inflection',\n name: 'PiBot',\n patterns: ['inflection', 'pi-bot', 'pi.ai'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Stability AI\n {\n id: 'stability-ai',\n type: 'stability',\n name: 'StabilityBot',\n patterns: ['stability-ai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Writer AI\n {\n id: 'writer-ai',\n type: 'writer',\n name: 'WriterBot',\n patterns: ['writerai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Phind — bot variant\n {\n id: 'phind-bot',\n type: 'phind',\n name: 'PhindBot',\n patterns: ['phind', 'phind-codellama'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // You.com — bot variant (you.com / youbot are crawler patterns;\n // the interactive You.com session would be a separate entry if it\n // had a distinct UA, but currently doesn't)\n {\n id: 'you-bot',\n type: 'you',\n name: 'YouBot',\n patterns: ['you.com', 'youbot'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Neeva — bot variant\n {\n id: 'neeva-bot',\n type: 'neeva',\n name: 'NeevaBot',\n patterns: ['neeva', 'neevabot'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Jasper AI\n {\n id: 'jasper-ai',\n type: 'jasper',\n name: 'JasperBot',\n patterns: ['jasper', 'jasperai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Replicate — bot variant\n {\n id: 'replicate-bot',\n type: 'replicate',\n name: 'ReplicateBot',\n patterns: ['replicate'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Together AI\n {\n id: 'together-ai',\n type: 'together',\n name: 'TogetherBot',\n patterns: ['together-ai', 'togetherai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // ─────────────────────────────────────────────────────────────────────\n // Engine-Pattern-Codegen-Retirement-1 backfills.\n //\n // Each entry below was detected by the retired YAML→Rust codegen path\n // (`patterns_generated.rs`) but never represented in TS. The SSOT\n // migration would have silently dropped detection for these vendors.\n // Names + confidences mirror the legacy pipeline so classify_agent /\n // classify_vendor downstream consumers don't see a behavioral shift.\n // ─────────────────────────────────────────────────────────────────────\n\n // xAI Grok — Elon's AI; user-facing assistant + crawler share the\n // same vendor brand, all routed through this single entry. The\n // legacy pipeline emitted them under one \"xAI Grok\" name, so a split\n // would change downstream classification.\n {\n id: 'xai-grok',\n type: 'xai',\n name: 'xAI Grok',\n patterns: ['xAI-Grok', 'GrokBot', 'Grok-DeepSearch'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // DeepSeek — split into interactive (DeepSeek-User) and crawler\n // (DeepSeekBot), parallel to the openai-chatgpt / openai-gptbot\n // and anthropic-claude / anthropic-claudebot splits.\n {\n id: 'deepseek-user',\n type: 'deepseek',\n name: 'DeepSeek AI',\n patterns: ['DeepSeek-User'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'deepseek-bot',\n type: 'deepseek',\n name: 'DeepSeekBot',\n patterns: ['DeepSeekBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Crawlers whose operators publish a User-Agent token: Exa\n // (crawler.exa.ai), AI2 (allenai.org/crawler), Diffbot (diffbot.com/docs/\n // crawl/faq/robots-txt), Kimi (kimi.com/policies/kimi-crawlers). Their\n // vendors are not members of `AgentTypeSchema`, so `type` is 'unknown'.\n // Kimi splits like OpenAI and DeepSeek: `Kimi-User` fetches a page for a\n // person, `KimiBot`/`Kimi-SearchBot` are crawlers.\n {\n id: 'exa-search-bot',\n type: 'unknown',\n name: 'ExaSearchBot',\n patterns: ['ExaSearchBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'ai2-bot',\n type: 'unknown',\n name: 'AI2Bot',\n patterns: ['AI2Bot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'diffbot',\n type: 'unknown',\n name: 'Diffbot',\n patterns: ['Diffbot'],\n confidence: 0.9,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'kimi-user',\n type: 'unknown',\n name: 'Kimi',\n patterns: ['Kimi-User'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'kimi-bot',\n type: 'unknown',\n name: 'KimiBot',\n patterns: ['KimiBot', 'Kimi-SearchBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Amazon Quick — AWS's rendering web crawler (formerly launched as part\n // of the \"Amazon Q\" family, since renamed; docs.aws.amazon.com/quick).\n // UA convention is `amazon-Quick-on-behalf-of-<id>` / AWS's own\n // documented `aws-quick-on-behalf-of-<UUID>`. Declared BEFORE\n // `amazon-q` below: the Rust engine's AI_AGENT_PATTERNS match is\n // first-match-wins in TS source order (see patterns.rs\n // `analyze_user_agent`), and 'Amazon-Quick' is a superstring of\n // 'Amazon-Q' below, so the more specific pattern must be tried first\n // there. `classifyByUserAgent` (TS/DB path) doesn't use source order —\n // it tie-breaks on confidence — so this row's confidence must also\n // stay strictly above `amazon-q`'s (mirrors the anthropic-ai-crawler /\n // anthropic-generic split: specific crawler token > broad label).\n // is_legitimate: AWS's docs describe it as a JS-rendering, non-\n // interactive crawler (no simulated user interaction) — the taxonomy's\n // `scraper` bucket, not `ai_assistant` (real-time human-driven use).\n {\n id: 'amazon-quick',\n type: 'amazon',\n name: 'Amazon Quick',\n patterns: ['Amazon-Quick', 'aws-quick'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Amazon Q + NovaAct — Amazon's AI assistant product family.\n // NovaAct is the AWS-branded browser-controlling agent (parallel to\n // Anthropic's Claude-Code, Google's GoogleAgent-Mariner).\n //\n // Confidence intentionally below `amazon-quick` above, by MORE than the\n // TS/DB path's max multi-pattern bonus (+5 for 2+ pattern matches — see\n // calculateConfidence in agent-classification.service.ts): 0.85 not 0.90.\n // A UA containing both of amazon-q's patterns ('Amazon-Q' — substring-\n // matched by 'Amazon-Quick' — and 'NovaAct', plausible on the same\n // product family's browser-driving traffic) would score 90 + 5 = 95,\n // tying amazon-quick's flat 95 and recreating the exact order-dependent\n // tie this split exists to eliminate (own regression test:\n // agent-classification-amazon-quick-crawler-tie.test.ts). At 0.85 the\n // bonus tops out at 85 + 5 = 90, still short of amazon-quick's 95.\n {\n id: 'amazon-q',\n type: 'amazon',\n name: 'Amazon Q',\n patterns: ['Amazon-Q', 'NovaAct'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // KYA Agent — our own product family. KYA-Agent/<version> is the\n // canonical UA; KYA-OS is the umbrella protocol token; KYA-Compute/\n // is the signed-compute variant. All ai_assistant — none of these\n // are training crawlers.\n //\n // Display name is `'Kya Agent'` (sentence case), NOT `'KYA Agent'`\n // (brand all-caps). Matches every other consumer's expectation: the\n // gateway router docstring refers to the \"Kya Agent\" pattern, and the\n // signed-agent e2e test asserts on `'Kya Agent'` for the unsigned\n // Tier-3 UA path. One source of truth, sentence case.\n {\n id: 'kya-agent',\n type: 'kya',\n name: 'Kya Agent',\n patterns: ['KYA-Agent/', 'KYA-OS', 'KYA-Compute/'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n];\n\n/**\n * Known cloud provider IP ranges (partial list)\n */\nexport const CLOUD_PROVIDER_RANGES = {\n aws: ['52.0.0.0/8', '54.0.0.0/8', '18.0.0.0/8', '35.0.0.0/8'],\n gcp: ['35.190.0.0/16', '35.240.0.0/16', '34.0.0.0/8'],\n azure: ['40.0.0.0/8', '20.0.0.0/8', '13.0.0.0/8'],\n};\n\n/**\n * Common bot user agent patterns. Model-version names (gpt-4, claude-3,\n * llama-3, ...) are not UA tokens and are not listed.\n */\nexport const BOT_USER_AGENT_PATTERNS = [\n /bot/i,\n /crawler/i,\n /spider/i,\n /scraper/i,\n /agent/i,\n /ai\\//i,\n // OpenAI\n /chatgpt/i,\n /openai/i,\n // Anthropic\n /claude/i,\n /anthropic/i,\n // Google\n /gemini/i,\n /bard/i,\n // Mistral\n /mistral/i,\n // Microsoft\n /copilot/i,\n // Other vendors\n /perplexity/i,\n /\\bphind\\b/i,\n // `you.com` is detected as a UA SUBSTRING — the pattern is consumed\n // only by `BOT_USER_AGENT_PATTERNS.some(p => p.test(userAgent))`\n // (UA context, not URL). CodeQL js/regex/missing-regexp-anchor\n // speculated about URL misuse on PR #2576; PR #2591's tightened\n // consuming-class form (`[\\s;()]`) introduced a real false-negative\n // for legit UA shapes containing `/`:\n // - `you.com/1.0` (You.com bot, version-suffixed)\n // - `Mozilla/5.0 you.com/bot` (token-with-version)\n // - `+https://you.com)` (token after URL inside parens)\n // Cursor caught the regression on PR #2591. Reverting to `\\b` —\n // word-boundary is the correct anchor for UA-substring matching;\n // the original CodeQL flag is a context-blind false positive (the\n // codebase does not apply BOT_USER_AGENT_PATTERNS to URL strings).\n // If CodeQL re-flags, dismiss in the UI as \"false positive\" with\n // pointer to this comment.\n /\\byou\\.com\\b/i,\n /\\bneeva\\b/i,\n /jasper/i,\n /replicate/i,\n /together(-?ai)?/i,\n /cohere/i,\n /huggingface/i,\n /transformers/i,\n];\n\n/**\n * Headers commonly used by AI agents\n */\nexport const AI_AGENT_HEADERS = [\n 'X-OpenAI-Assistant',\n 'X-Anthropic-Client',\n 'X-AI-Agent',\n 'X-Bot-Token',\n 'X-Agent-ID',\n 'X-LLM-Request',\n];\n\n/**\n * Suspicious header patterns\n */\nexport const SUSPICIOUS_HEADERS = {\n // Missing standard headers\n missingUserAgent: 'User-Agent header is missing',\n missingAccept: 'Accept header is missing',\n\n // Unusual values\n genericUserAgent: 'User-Agent appears to be generic or spoofed',\n mismatchedHeaders: 'Headers contain conflicting information',\n\n // Known spoofing attempts\n fakeChrome: 'Chrome user agent without expected Chrome headers',\n fakeSafari: 'Safari user agent without expected Safari headers',\n};\n","/**\n * Traditional Bot Constants and Types\n *\n * These are NON-AI bots like search engines, crawlers, and SEO tools.\n * AI agents (Claude, GPT, etc.) should be in agents.ts\n */\n\nimport { z } from 'zod';\n\n/**\n * Traditional bot types (not AI agents)\n */\nexport const BotTypeSchema = z.enum([\n 'search_engine', // googlebot, bingbot, yandexbot\n 'social_media', // facebookbot, twitterbot, linkedinbot\n 'seo_tool', // semrushbot, ahrefsbot, mj12bot\n 'crawler', // generic web crawlers\n 'scraper', // data scrapers\n 'monitoring', // uptime monitors, health checkers\n 'security_scanner', // security scanning tools\n 'unknown_bot',\n]);\n\nexport type BotType = z.infer<typeof BotTypeSchema>;\n\n/**\n * Trusted traditional bots that can be cached\n * These are well-known, legitimate bots with stable patterns\n * NOT for AI agents - those should never be cached\n */\nexport const TRUSTED_BOTS = [\n // Search engines\n 'googlebot', // Google Search\n 'bingbot', // Bing Search\n 'slurp', // Yahoo\n 'duckduckbot', // DuckDuckGo\n 'baiduspider', // Baidu\n 'yandexbot', // Yandex\n 'applebot', // Apple Search\n\n // Social media\n 'facebookexternalhit', // Facebook\n 'twitterbot', // Twitter/X\n 'linkedinbot', // LinkedIn\n 'whatsapp', // WhatsApp\n\n // SEO tools\n 'semrushbot', // SEMrush SEO\n 'ahrefsbot', // Ahrefs SEO\n 'mj12bot', // Majestic SEO\n 'dotbot', // Moz SEO\n];\n\n/**\n * Bot pattern for traditional bot matching\n */\nexport const BotPatternSchema = z.object({\n id: z.string(),\n type: BotTypeSchema,\n name: z.string(),\n patterns: z.array(z.string()),\n confidence: z.number().min(0).max(1).default(0.8),\n});\n\nexport type BotPattern = z.infer<typeof BotPatternSchema>;\n\n/**\n * Traditional bot patterns.\n *\n * NAME VOCABULARY: `name` MUST be the detection engine's pattern name — the\n * string `kya-os-engine` stamps as `agent_name` (see the `NON_AI_PATTERNS`\n * table in `rust/crates/kya-os-engine/src/stages/patterns.rs`). That string\n * becomes `agent_types.display_name` via the sync service, the Cedar\n * principal the policy picker emits, and the `principal.name` every\n * evaluator byte-compares. A name the engine never emits can't be policy-\n * matched. Drift is pinned by `bot-name-vocabulary.spec.ts`, which parses\n * the Rust table at test time; entries the engine has NO name for are\n * allow-listed there and tracked by the codegen-consolidation issue.\n */\nexport const TRADITIONAL_BOT_PATTERNS: BotPattern[] = [\n // Search engines\n {\n id: 'googlebot',\n type: 'search_engine',\n name: 'Googlebot',\n patterns: ['googlebot', 'google-structured-data-testing-tool'],\n confidence: 0.95,\n },\n {\n id: 'bingbot',\n type: 'search_engine',\n name: 'Bingbot',\n patterns: ['bingbot', 'bingpreview', 'msnbot'],\n confidence: 0.95,\n },\n {\n id: 'yandexbot',\n type: 'search_engine',\n name: 'Yandexbot',\n patterns: ['yandexbot', 'yandex'],\n confidence: 0.9,\n },\n\n // Social media\n {\n id: 'facebook',\n type: 'social_media',\n name: 'Meta Crawler',\n patterns: ['facebookexternalhit', 'facebookcatalog', 'Meta-ExternalAgent'],\n confidence: 0.9,\n },\n {\n id: 'twitter',\n type: 'social_media',\n name: 'Twitterbot',\n patterns: ['twitterbot'],\n confidence: 0.9,\n },\n\n // SEO tools\n {\n id: 'semrush',\n type: 'seo_tool',\n name: 'SEMrush',\n patterns: ['semrushbot'],\n confidence: 0.85,\n },\n {\n id: 'ahrefs',\n type: 'seo_tool',\n name: 'Ahrefsbot',\n patterns: ['ahrefsbot'],\n confidence: 0.85,\n },\n\n // Generic crawlers\n {\n id: 'generic-crawler',\n type: 'crawler',\n name: 'Generic Bot',\n patterns: ['crawler', 'spider', 'bot/'],\n confidence: 0.6,\n },\n {\n id: 'generic-scraper',\n type: 'scraper',\n name: 'Generic Scraper',\n patterns: ['scraper', 'python-requests', 'curl/', 'wget/'],\n confidence: 0.7,\n },\n];\n\n/**\n * Check if a user agent is a traditional bot (not AI agent)\n */\nexport function isTraditionalBot(userAgent: string): boolean {\n const lowerUA = userAgent.toLowerCase();\n return TRUSTED_BOTS.some((bot) => lowerUA.includes(bot));\n}\n\n/**\n * Get bot type from user agent\n */\nexport function getBotType(userAgent: string): BotType | null {\n const lowerUA = userAgent.toLowerCase();\n\n for (const pattern of TRADITIONAL_BOT_PATTERNS) {\n if (pattern.patterns.some((p) => lowerUA.includes(p.toLowerCase()))) {\n return pattern.type;\n }\n }\n\n return null;\n}\n","/**\n * Delegation credential lifetime bounds.\n *\n * Shared because the mint and the dashboard MUST agree: the policy page once\n * advertised a project's configured `delegationExpirationDays` (\"good for 7\n * days\") while the credential that flow actually minted was 900 seconds.\n */\n\n/**\n * Maximum lifetime of an `attested-bearer` DelegationCredential, in seconds.\n *\n * A credential with no `cnf` (holder-key) claim is a bearer credential:\n * whoever holds the bytes can use them. The HTTP binding therefore bounds it\n * at 900s, and key-bound remains the default and conformance floor. Raising\n * this hands out longer-lived ambient authority — the exact failure the\n * key-bound design removes — so it is a spec change, not a config knob.\n */\nexport const ATTESTED_BEARER_MAX_TTL_SECONDS = 900;\n","/**\n * Error Codes and Messages\n *\n * Standardized error codes and messages used across all packages\n */\n\n/**\n * Error Code Categories\n */\nexport const ERROR_CATEGORIES = {\n AUTH: 'AUTH',\n VALIDATION: 'VALIDATION',\n DETECTION: 'DETECTION',\n RATE_LIMIT: 'RATE_LIMIT',\n PERMISSION: 'PERMISSION',\n NETWORK: 'NETWORK',\n INTERNAL: 'INTERNAL',\n CONFIGURATION: 'CONFIGURATION',\n WASM: 'WASM',\n SESSION: 'SESSION',\n PIXEL: 'PIXEL',\n API: 'API',\n} as const;\n\n/**\n * Authentication Error Codes\n */\nexport const AUTH_ERRORS = {\n INVALID_API_KEY: 'AUTH_INVALID_API_KEY',\n EXPIRED_API_KEY: 'AUTH_EXPIRED_API_KEY',\n INVALID_TOKEN: 'AUTH_INVALID_TOKEN',\n EXPIRED_TOKEN: 'AUTH_EXPIRED_TOKEN',\n MISSING_CREDENTIALS: 'AUTH_MISSING_CREDENTIALS',\n UNAUTHORIZED: 'AUTH_UNAUTHORIZED',\n // A C3 human management session presented where an API key is required.\n MANAGEMENT_TOKEN_NOT_ACCEPTED: 'AUTH_MANAGEMENT_TOKEN_NOT_ACCEPTED',\n INVALID_PIXEL_ID: 'AUTH_INVALID_PIXEL_ID',\n INVALID_SECRET_KEY: 'AUTH_INVALID_SECRET_KEY',\n} as const;\n\n/**\n * Validation Error Codes\n */\nexport const VALIDATION_ERRORS = {\n INVALID_REQUEST: 'VALIDATION_INVALID_REQUEST',\n MISSING_REQUIRED_FIELD: 'VALIDATION_MISSING_REQUIRED_FIELD',\n INVALID_FIELD_TYPE: 'VALIDATION_INVALID_FIELD_TYPE',\n INVALID_FIELD_VALUE: 'VALIDATION_INVALID_FIELD_VALUE',\n FIELD_TOO_LONG: 'VALIDATION_FIELD_TOO_LONG',\n FIELD_TOO_SHORT: 'VALIDATION_FIELD_TOO_SHORT',\n INVALID_EMAIL: 'VALIDATION_INVALID_EMAIL',\n INVALID_URL: 'VALIDATION_INVALID_URL',\n INVALID_UUID: 'VALIDATION_INVALID_UUID',\n INVALID_IP_ADDRESS: 'VALIDATION_INVALID_IP_ADDRESS',\n INVALID_USER_AGENT: 'VALIDATION_INVALID_USER_AGENT',\n BAD_REQUEST: 'VALIDATION_BAD_REQUEST',\n INVALID_START_DATE: 'VALIDATION_INVALID_START_DATE',\n INVALID_END_DATE: 'VALIDATION_INVALID_END_DATE',\n INVALID_DATE_RANGE: 'VALIDATION_INVALID_DATE_RANGE',\n} as const;\n\n/**\n * Detection Error Codes\n */\nexport const DETECTION_ERRORS = {\n DETECTION_FAILED: 'DETECTION_FAILED',\n INSUFFICIENT_DATA: 'DETECTION_INSUFFICIENT_DATA',\n PATTERN_MATCH_FAILED: 'DETECTION_PATTERN_MATCH_FAILED',\n WASM_NOT_LOADED: 'DETECTION_WASM_NOT_LOADED',\n WASM_EXECUTION_FAILED: 'DETECTION_WASM_EXECUTION_FAILED',\n CONFIDENCE_BELOW_THRESHOLD: 'DETECTION_CONFIDENCE_BELOW_THRESHOLD',\n SIGNATURE_VERIFICATION_FAILED: 'DETECTION_SIGNATURE_VERIFICATION_FAILED',\n} as const;\n\n/**\n * Rate Limit Error Codes\n */\nexport const RATE_LIMIT_ERRORS = {\n RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',\n BURST_LIMIT_EXCEEDED: 'RATE_LIMIT_BURST_EXCEEDED',\n DAILY_LIMIT_EXCEEDED: 'RATE_LIMIT_DAILY_EXCEEDED',\n MONTHLY_LIMIT_EXCEEDED: 'RATE_LIMIT_MONTHLY_EXCEEDED',\n CONCURRENT_LIMIT_EXCEEDED: 'RATE_LIMIT_CONCURRENT_EXCEEDED',\n QUOTA_EXCEEDED: 'RATE_LIMIT_QUOTA_EXCEEDED',\n RATE_LIMITED: 'RATE_LIMITED',\n} as const;\n\n/**\n * Permission Error Codes\n */\nexport const PERMISSION_ERRORS = {\n INSUFFICIENT_PERMISSIONS: 'PERMISSION_INSUFFICIENT',\n RESOURCE_NOT_FOUND: 'PERMISSION_RESOURCE_NOT_FOUND',\n RESOURCE_ACCESS_DENIED: 'PERMISSION_ACCESS_DENIED',\n OPERATION_NOT_ALLOWED: 'PERMISSION_OPERATION_NOT_ALLOWED',\n PROJECT_ACCESS_DENIED: 'PERMISSION_PROJECT_ACCESS_DENIED',\n PIXEL_ACCESS_DENIED: 'PERMISSION_PIXEL_ACCESS_DENIED',\n FORBIDDEN: 'PERMISSION_FORBIDDEN',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n} as const;\n\n/**\n * Network Error Codes\n */\nexport const NETWORK_ERRORS = {\n CONNECTION_FAILED: 'NETWORK_CONNECTION_FAILED',\n TIMEOUT: 'NETWORK_TIMEOUT',\n DNS_RESOLUTION_FAILED: 'NETWORK_DNS_FAILED',\n SSL_ERROR: 'NETWORK_SSL_ERROR',\n PROXY_ERROR: 'NETWORK_PROXY_ERROR',\n UPSTREAM_ERROR: 'NETWORK_UPSTREAM_ERROR',\n} as const;\n\n/**\n * Internal Error Codes\n */\nexport const INTERNAL_ERRORS = {\n INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',\n DATABASE_ERROR: 'INTERNAL_DATABASE_ERROR',\n CACHE_ERROR: 'INTERNAL_CACHE_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_CONFIGURATION_ERROR',\n INITIALIZATION_ERROR: 'INTERNAL_INITIALIZATION_ERROR',\n PROCESSING_ERROR: 'INTERNAL_PROCESSING_ERROR',\n UNKNOWN_ERROR: 'INTERNAL_UNKNOWN_ERROR',\n SERVICE_UNAVAILABLE_TRANSIENT: 'SERVICE_UNAVAILABLE_TRANSIENT',\n TRANSACTION_FAILED: 'TRANSACTION_FAILED',\n DELETE_FAILED: 'DELETE_FAILED',\n PARTITION_RETIREMENT_IN_PROGRESS: 'PARTITION_RETIREMENT_IN_PROGRESS',\n FLY_CLEANUP_FAILED: 'FLY_CLEANUP_FAILED',\n} as const;\n\n/**\n * Session Error Codes\n */\nexport const SESSION_ERRORS = {\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_EXPIRED: 'SESSION_EXPIRED',\n SESSION_INVALID: 'SESSION_INVALID',\n SESSION_CREATION_FAILED: 'SESSION_CREATION_FAILED',\n SESSION_UPDATE_FAILED: 'SESSION_UPDATE_FAILED',\n SESSION_STORAGE_ERROR: 'SESSION_STORAGE_ERROR',\n MAX_SESSIONS_EXCEEDED: 'SESSION_MAX_EXCEEDED',\n} as const;\n\n/**\n * Pixel Error Codes\n */\nexport const PIXEL_ERRORS = {\n PIXEL_NOT_FOUND: 'PIXEL_NOT_FOUND',\n PIXEL_DISABLED: 'PIXEL_DISABLED',\n PIXEL_CONFIGURATION_ERROR: 'PIXEL_CONFIGURATION_ERROR',\n PIXEL_DOMAIN_NOT_ALLOWED: 'PIXEL_DOMAIN_NOT_ALLOWED',\n PIXEL_PATH_SKIPPED: 'PIXEL_PATH_SKIPPED',\n PIXEL_EVENT_INVALID: 'PIXEL_EVENT_INVALID',\n PIXEL_BATCH_TOO_LARGE: 'PIXEL_BATCH_TOO_LARGE',\n MISSING_PIXEL_ID: 'MISSING_PIXEL_ID',\n DETECTION_STORAGE_FAILED: 'DETECTION_STORAGE_FAILED',\n PIXEL_CREATION_FAILED: 'PIXEL_CREATION_FAILED',\n} as const;\n\n/**\n * API Error Codes\n */\nexport const API_ERRORS = {\n ENDPOINT_NOT_FOUND: 'API_ENDPOINT_NOT_FOUND',\n METHOD_NOT_ALLOWED: 'API_METHOD_NOT_ALLOWED',\n VERSION_NOT_SUPPORTED: 'API_VERSION_NOT_SUPPORTED',\n CONTENT_TYPE_NOT_SUPPORTED: 'API_CONTENT_TYPE_NOT_SUPPORTED',\n RESPONSE_TOO_LARGE: 'API_RESPONSE_TOO_LARGE',\n REQUEST_TOO_LARGE: 'API_REQUEST_TOO_LARGE',\n // A route that no longer serves requests and answers 410 Gone, naming\n // its replacement, until it is removed.\n ENDPOINT_RETIRED: 'API_ENDPOINT_RETIRED',\n} as const;\n\n/**\n * Billing Error Codes\n */\nexport const BILLING_ERRORS = {\n LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',\n BILLING_SUSPENDED: 'BILLING_SUSPENDED',\n BILLING_GRACE_PERIOD: 'BILLING_GRACE_PERIOD',\n} as const;\n\n/**\n * Resource Error Codes\n */\nexport const RESOURCE_ERRORS = {\n CONFLICT: 'CONFLICT',\n PROJECT_NOT_FOUND: 'PROJECT_NOT_FOUND',\n REVIEW_REQUIRED: 'REVIEW_REQUIRED',\n} as const;\n\n/**\n * Policy Error Codes\n */\nexport const POLICY_ERRORS = {\n POLICY_FETCH_FAILED: 'POLICY_FETCH_FAILED',\n} as const;\n\n/**\n * Analytics Error Codes\n *\n * Emitted by the project analytics and shopify stats read routes.\n */\nexport const ANALYTICS_ERRORS = {\n INVALID_PERIOD: 'INVALID_PERIOD',\n ANALYTICS_FETCH_ERROR: 'ANALYTICS_FETCH_ERROR',\n STATS_FETCH_ERROR: 'STATS_FETCH_ERROR',\n} as const;\n\n/**\n * Deploy Error Codes\n *\n * Emitted by the managed deploy route and the managed deploy service it\n * wraps. The service-computed codes have no fixed status here (see the\n * NOTE in ERROR_STATUS_CODES).\n */\nexport const DEPLOY_ERRORS = {\n MISSING_USER_IDENTIFIER: 'MISSING_USER_IDENTIFIER',\n USER_NOT_FOUND: 'USER_NOT_FOUND',\n NO_ORGANIZATION: 'NO_ORGANIZATION',\n DEPLOY_FAILED: 'DEPLOY_FAILED',\n WFP_NOT_CONFIGURED: 'WFP_NOT_CONFIGURED',\n NATIVE_ISSUER_PROVISIONING_BUSY: 'NATIVE_ISSUER_PROVISIONING_BUSY',\n NATIVE_ISSUER_PROVISIONING_FAILED: 'NATIVE_ISSUER_PROVISIONING_FAILED',\n} as const;\n\n/**\n * Bare Error Codes\n *\n * Un-prefixed upper-case wire strings shared by several surfaces (pixel,\n * pixel/track, openclaw, deploy, shopify, bouncer, project analytics).\n * Keyed by value with a BARE_ prefix so the key cannot collide with the\n * prefixed groups.\n */\nexport const BARE_ERRORS = {\n BARE_VALIDATION_ERROR: 'VALIDATION_ERROR',\n BARE_INTERNAL_ERROR: 'INTERNAL_ERROR',\n BARE_INVALID_REQUEST: 'INVALID_REQUEST',\n BARE_INVALID_JSON: 'INVALID_JSON',\n BARE_INVALID_START_DATE: 'INVALID_START_DATE',\n BARE_INVALID_END_DATE: 'INVALID_END_DATE',\n BARE_INVALID_DATE_RANGE: 'INVALID_DATE_RANGE',\n BARE_INVALID_DATE: 'INVALID_DATE',\n BARE_UNKNOWN_ERROR: 'UNKNOWN_ERROR',\n BARE_NOT_FOUND: 'NOT_FOUND',\n BARE_FORBIDDEN: 'FORBIDDEN',\n} as const;\n\n/**\n * Lowercase Error Codes\n *\n * Lowercase wire strings are the SPEC-EVENTS wire format used by\n * /api/v1/kya-os/events and /api/v1/kya-os/revocations, and reused by the\n * bouncer family. Keyed by value with a LOWERCASE_ prefix.\n *\n * `invalid_cursor` is the revocation feed's answer to a `since` it did not\n * issue for the key's project; consumers drop their cursor and read the feed\n * from the start on exactly this code.\n */\nexport const LOWERCASE_ERRORS = {\n LOWERCASE_INVALID_JSON: 'invalid_json',\n LOWERCASE_VALIDATION_ERROR: 'validation_error',\n LOWERCASE_INVALID_CURSOR: 'invalid_cursor',\n} as const;\n\n/**\n * Bouncer Error Codes (lower-case wire format)\n *\n * Emitted by the /api/v1/bouncer routes, either inline by the route or via\n * a `BouncerError` subclass thrown from a bouncer service. Only subclass\n * codes that a bouncer route can actually put on the wire are registered\n * here; classes that exist but are never thrown are deliberately absent.\n * Keyed by value with a LOWERCASE_ prefix.\n */\nexport const BOUNCER_LOWERCASE_ERRORS = {\n LOWERCASE_NO_PROJECT: 'no_project',\n LOWERCASE_MISSING_AGENT_DID: 'missing_agent_did',\n LOWERCASE_NOT_CONFIGURED: 'not_configured',\n LOWERCASE_INVALID_CREDENTIAL_CONFIG: 'invalid_credential_config',\n LOWERCASE_PROJECT_NOT_FOUND: 'project_not_found',\n LOWERCASE_PROJECT_MISMATCH: 'project_mismatch',\n LOWERCASE_MISSING_DELEGATION_ID: 'missing_delegation_id',\n LOWERCASE_INVALID_TOKEN: 'invalid_token',\n LOWERCASE_DELEGATION_MISMATCH: 'delegation_mismatch',\n LOWERCASE_TOKENS_NOT_FOUND: 'tokens_not_found',\n LOWERCASE_DECRYPTION_ERROR: 'decryption_error',\n LOWERCASE_NO_PROOFS: 'no_proofs',\n LOWERCASE_BATCH_TOO_LARGE: 'batch_too_large',\n LOWERCASE_NO_PROOFS_PROCESSED: 'no_proofs_processed',\n LOWERCASE_ALL_PROOFS_REJECTED: 'all_proofs_rejected',\n LOWERCASE_UNAUTHORIZED: 'unauthorized',\n LOWERCASE_FORBIDDEN: 'forbidden',\n LOWERCASE_NOT_FOUND: 'not_found',\n // BouncerError subclass codes (apps/web/lib/bouncer/types/index.ts)\n LOWERCASE_CONFIG_NOT_FOUND: 'config_not_found',\n LOWERCASE_AGENT_DENIED: 'agent_denied',\n LOWERCASE_DELEGATION_NOT_FOUND: 'delegation_not_found',\n LOWERCASE_SESSION_NOT_FOUND: 'session_not_found',\n LOWERCASE_PROOF_VALIDATION_ERROR: 'proof_validation_error',\n LOWERCASE_INSUFFICIENT_SCOPES: 'insufficient_scopes',\n LOWERCASE_DELEGATION_VALIDATION_ERROR: 'delegation_validation_error',\n // A grant from before the issuance core: no org status list, so it cannot be re-minted.\n GRANT_PREDATES_ISSUANCE_CORE: 'grant_predates_issuance_core',\n LOWERCASE_INVALID_HTTP_REGISTRATION: 'invalid_http_registration',\n LOWERCASE_POLICY_REVISION_MISMATCH: 'policy_revision_mismatch',\n LOWERCASE_POLICY_REVISION_GRACE_UNAVAILABLE: 'policy_revision_grace_unavailable',\n LOWERCASE_AUTHORIZATION_HOST_UNAVAILABLE: 'authorization_host_unavailable',\n} as const;\n\n/**\n * Delegation OAuth Error Codes (lower-case wire format)\n *\n * Emitted by the bouncer authorize, oauth/start, oauth/callback and\n * oauth/token routes and the shared OAuth rate limiter. Several reuse RFC\n * 6749 vocabulary (`invalid_request`, `invalid_grant`,\n * `unsupported_grant_type`) but travel in the bouncer `{success, error}`\n * envelope, not an RFC 6749 body. Keyed by value with a LOWERCASE_ prefix.\n */\nexport const OAUTH_LOWERCASE_ERRORS = {\n LOWERCASE_INVALID_REQUEST: 'invalid_request',\n LOWERCASE_UNSUPPORTED_GRANT_TYPE: 'unsupported_grant_type',\n LOWERCASE_INVALID_GRANT: 'invalid_grant',\n LOWERCASE_INVALID_DELEGATION: 'invalid_delegation',\n LOWERCASE_INTERNAL_ERROR: 'internal_error',\n LOWERCASE_INVALID_STATE: 'invalid_state',\n LOWERCASE_INVALID_TRANSACTION: 'invalid_transaction',\n LOWERCASE_OAUTH_UNAVAILABLE: 'oauth_unavailable',\n LOWERCASE_OAUTH_NOT_CONFIGURED: 'oauth_not_configured',\n LOWERCASE_OAUTH_CONFIGURATION_UNSUPPORTED: 'oauth_configuration_unsupported',\n LOWERCASE_INVALID_PROVIDER_CONFIG: 'invalid_provider_config',\n LOWERCASE_RATE_LIMIT_EXCEEDED: 'rate_limit_exceeded',\n} as const;\n\n/**\n * Bouncer Error Codes (upper-case wire format)\n *\n * Emitted by the /api/v1/bouncer/projects/{projectId}/* routes and the\n * delegation request status route through `ApiError` / `v1ErrorResponse`.\n */\nexport const BOUNCER_UPPERCASE_ERRORS = {\n INVALID_REQUEST_BODY: 'INVALID_REQUEST_BODY',\n MCPI_CONFIG_NOT_FOUND: 'MCPI_CONFIG_NOT_FOUND',\n CONSENT_CONFIG_NOT_FOUND: 'CONSENT_CONFIG_NOT_FOUND',\n PROJECT_LOOKUP_FAILED: 'PROJECT_LOOKUP_FAILED',\n CONFIG_VALIDATION_ERROR: 'CONFIG_VALIDATION_ERROR',\n CONFIG_FETCH_FAILED: 'CONFIG_FETCH_FAILED',\n CONFIG_UPDATE_FAILED: 'CONFIG_UPDATE_FAILED',\n DEPLOYMENT_NOT_FOUND: 'DEPLOYMENT_NOT_FOUND',\n INVALID_REQUEST_ID: 'INVALID_REQUEST_ID',\n DELEGATION_REQUEST_NOT_FOUND: 'DELEGATION_REQUEST_NOT_FOUND',\n} as const;\n\n/**\n * Audit Ingest Error Codes\n *\n * Route-owned codes of POST /api/v1/audit/entries: credential, size, JSON,\n * rate-limit and submission-envelope failures raised before or around the\n * audit protocol itself.\n */\nexport const AUDIT_ERRORS = {\n AUDIT_CREDENTIAL_REQUIRED: 'AUDIT_CREDENTIAL_REQUIRED',\n AUDIT_REQUEST_TOO_LARGE: 'AUDIT_REQUEST_TOO_LARGE',\n AUDIT_INVALID_JSON: 'AUDIT_INVALID_JSON',\n AUDIT_INVALID_CREDENTIAL: 'AUDIT_INVALID_CREDENTIAL',\n AUDIT_RATE_LIMITED: 'AUDIT_RATE_LIMITED',\n AUDIT_INVALID_SUBMISSION: 'AUDIT_INVALID_SUBMISSION',\n AUDIT_INTERNAL_ERROR: 'AUDIT_INTERNAL_ERROR',\n} as const;\n\n/**\n * Audit Protocol Error Codes\n *\n * The `AUDIT_ERROR_CODES` vocabulary of `@kya-os/mcp`, relayed verbatim as\n * `error.code` by POST /api/v1/audit/entries when the recorder throws an\n * `AuditProtocolError`. This package does not depend on `@kya-os/mcp`, so\n * the strings are copied by hand; a lock test in apps/web asserts the two\n * sets stay equal. The route maps each code to one fixed status. For codes\n * at 500 and above the route replaces the protocol message with a generic\n * one, so ERROR_MESSAGES carries that generic text; below 500 the wire\n * message is protocol-owned and ERROR_MESSAGES is descriptive only.\n */\nexport const AUDIT_PROTOCOL_ERRORS = {\n AUDIT_UNAUTHORIZED_SUBMISSION: 'AUDIT_UNAUTHORIZED_SUBMISSION',\n AUDIT_LEDGER_MISMATCH: 'AUDIT_LEDGER_MISMATCH',\n AUDIT_EPOCH_MISMATCH: 'AUDIT_EPOCH_MISMATCH',\n AUDIT_EVENT_ID_CONFLICT: 'AUDIT_EVENT_ID_CONFLICT',\n AUDIT_INVALID_EVENT: 'AUDIT_INVALID_EVENT',\n AUDIT_EVIDENCE_FAILURE: 'AUDIT_EVIDENCE_FAILURE',\n AUDIT_EVIDENCE_INTEGRITY: 'AUDIT_EVIDENCE_INTEGRITY',\n AUDIT_INVALID_CONFIGURATION: 'AUDIT_INVALID_CONFIGURATION',\n AUDIT_JOURNAL_FAILURE: 'AUDIT_JOURNAL_FAILURE',\n AUDIT_APPEND_CONFLICT_EXHAUSTED: 'AUDIT_APPEND_CONFLICT_EXHAUSTED',\n AUDIT_EVIDENCE_LEGAL_HOLD: 'AUDIT_EVIDENCE_LEGAL_HOLD',\n AUDIT_EVIDENCE_ACCESS_DENIED: 'AUDIT_EVIDENCE_ACCESS_DENIED',\n AUDIT_CHECKPOINT_INVALID: 'AUDIT_CHECKPOINT_INVALID',\n AUDIT_CHECKPOINT_ROLLBACK: 'AUDIT_CHECKPOINT_ROLLBACK',\n AUDIT_CHECKPOINT_CONFLICT: 'AUDIT_CHECKPOINT_CONFLICT',\n AUDIT_CHECKPOINT_PUBLICATION_FAILED: 'AUDIT_CHECKPOINT_PUBLICATION_FAILED',\n AUDIT_PROJECTION_CONFLICT: 'AUDIT_PROJECTION_CONFLICT',\n AUDIT_MIRROR_VERIFICATION_FAILED: 'AUDIT_MIRROR_VERIFICATION_FAILED',\n AUDIT_MIRROR_CONTINUITY_FAILED: 'AUDIT_MIRROR_CONTINUITY_FAILED',\n AUDIT_MIRROR_OUT_OF_ORDER: 'AUDIT_MIRROR_OUT_OF_ORDER',\n} as const;\n\n/**\n * KYA-OS Native HTTP Protocol Error Codes (`kyaos/*`)\n *\n * Emitted by the /api/v1/bouncer/native-http/* handlers and the managed\n * native issuer and propagation-proof services. The wire body is\n * `{ error: \"<code>\" }` with no message, so ERROR_MESSAGES text for these\n * codes is documentation only. Keyed by value with a KYAOS_SLASH_ prefix\n * because the wire strings carry a `/`.\n */\nexport const KYAOS_PROTOCOL_ERRORS = {\n KYAOS_SLASH_ISSUER_FORBIDDEN: 'kyaos/issuer-forbidden',\n KYAOS_SLASH_PROFILE_VIOLATION: 'kyaos/profile-violation',\n KYAOS_SLASH_INVALID_SESSION: 'kyaos/invalid-session',\n KYAOS_SLASH_SESSION_CONFLICT: 'kyaos/session-conflict',\n KYAOS_SLASH_PICKUP_EXPIRED: 'kyaos/pickup-expired',\n KYAOS_SLASH_SCOPE_INSUFFICIENT: 'kyaos/scope-insufficient',\n KYAOS_SLASH_CONSENT_REQUIRED: 'kyaos/consent-required',\n KYAOS_SLASH_PICKUP_PINNED: 'kyaos/pickup-pinned',\n KYAOS_SLASH_AUTHORIZATION_HOST_UNAVAILABLE: 'kyaos/authorization-host-unavailable',\n KYAOS_SLASH_CHAIN_BROKEN: 'kyaos/chain-broken',\n KYAOS_SLASH_DELEGATION_REVOKED: 'kyaos/delegation-revoked',\n KYAOS_SLASH_EXPIRED: 'kyaos/expired',\n KYAOS_SLASH_HOLDER_MISMATCH: 'kyaos/holder-mismatch',\n KYAOS_SLASH_INVALID_SIGNATURE: 'kyaos/invalid-signature',\n KYAOS_SLASH_SESSION_MISMATCH: 'kyaos/session-mismatch',\n KYAOS_SLASH_POLICY_UNAVAILABLE: 'kyaos/policy-unavailable',\n} as const;\n\n/**\n * Gateway Vault Resolve Error Codes\n *\n * Emitted by POST /api/v1/gateway/vault/{projectId}/resolve, and five of them\n * (INVALID_ASSERTION, INVALID_SIGNATURE, ASSERTION_EXPIRED, ASSERTION_REPLAYED,\n * PROJECT_MISMATCH) also by POST /api/v1/vault/{projectId}/resolve, which\n * verifies through the same shared verifier and nonce store\n * (apps/web/lib/vault/). Every emission site passes an explicit message and\n * status, so registering them changes no wire behaviour.\n */\nexport const GATEWAY_VAULT_ERRORS = {\n MALFORMED_REQUEST_BODY: 'MALFORMED_REQUEST_BODY',\n GATEWAY_NOT_CONFIGURED: 'GATEWAY_NOT_CONFIGURED',\n INVALID_ASSERTION: 'INVALID_ASSERTION',\n INVALID_SIGNATURE: 'INVALID_SIGNATURE',\n ASSERTION_EXPIRED: 'ASSERTION_EXPIRED',\n ASSERTION_REPLAYED: 'ASSERTION_REPLAYED',\n PROJECT_MISMATCH: 'PROJECT_MISMATCH',\n ISSUER_MISMATCH: 'ISSUER_MISMATCH',\n USER_DID_MISMATCH: 'USER_DID_MISMATCH',\n TOOL_NAME_MISMATCH: 'TOOL_NAME_MISMATCH',\n SESSION_ID_MISMATCH: 'SESSION_ID_MISMATCH',\n NOT_AUTHORIZED: 'NOT_AUTHORIZED',\n CREDENTIALS_NOT_CONFIGURED: 'CREDENTIALS_NOT_CONFIGURED',\n OAUTH_EXPIRED: 'OAUTH_EXPIRED',\n} as const;\n\n/**\n * Vault Resolve Error Codes\n *\n * The one code unique to POST /api/v1/vault/{projectId}/resolve. The rest of\n * its surface reuses GATEWAY_VAULT_ERRORS, BARE_ERRORS and INTERNAL_ERRORS by\n * key.\n */\nexport const VAULT_ERRORS = {\n NO_AGENT_KEY: 'NO_AGENT_KEY',\n} as const;\n\n/**\n * All Error Codes\n */\nexport const ERROR_CODES = {\n ...AUTH_ERRORS,\n ...VALIDATION_ERRORS,\n ...DETECTION_ERRORS,\n ...RATE_LIMIT_ERRORS,\n ...PERMISSION_ERRORS,\n ...NETWORK_ERRORS,\n ...INTERNAL_ERRORS,\n ...SESSION_ERRORS,\n ...PIXEL_ERRORS,\n ...API_ERRORS,\n ...BILLING_ERRORS,\n ...RESOURCE_ERRORS,\n ...POLICY_ERRORS,\n ...ANALYTICS_ERRORS,\n ...DEPLOY_ERRORS,\n ...BARE_ERRORS,\n ...LOWERCASE_ERRORS,\n ...BOUNCER_LOWERCASE_ERRORS,\n ...OAUTH_LOWERCASE_ERRORS,\n ...BOUNCER_UPPERCASE_ERRORS,\n ...AUDIT_ERRORS,\n ...AUDIT_PROTOCOL_ERRORS,\n ...KYAOS_PROTOCOL_ERRORS,\n ...GATEWAY_VAULT_ERRORS,\n ...VAULT_ERRORS,\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * Error Messages\n */\nexport const ERROR_MESSAGES: Record<ErrorCode, string> = {\n // Authentication\n [AUTH_ERRORS.INVALID_API_KEY]: 'The provided API key is invalid',\n [AUTH_ERRORS.EXPIRED_API_KEY]: 'The API key has expired',\n [AUTH_ERRORS.INVALID_TOKEN]: 'The provided token is invalid',\n [AUTH_ERRORS.EXPIRED_TOKEN]: 'The token has expired',\n [AUTH_ERRORS.MISSING_CREDENTIALS]: 'Authentication credentials are required',\n [AUTH_ERRORS.MANAGEMENT_TOKEN_NOT_ACCEPTED]:\n 'Management session tokens are accepted only by /api/cli/management routes',\n [AUTH_ERRORS.UNAUTHORIZED]: 'You are not authorized to perform this action',\n [AUTH_ERRORS.INVALID_PIXEL_ID]: 'The provided pixel ID is invalid',\n [AUTH_ERRORS.INVALID_SECRET_KEY]: 'The provided secret key is invalid',\n\n // Validation\n [VALIDATION_ERRORS.INVALID_REQUEST]: 'The request is invalid',\n [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 'A required field is missing',\n [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 'Field type is invalid',\n [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 'Field value is invalid',\n [VALIDATION_ERRORS.FIELD_TOO_LONG]: 'Field value exceeds maximum length',\n [VALIDATION_ERRORS.FIELD_TOO_SHORT]: 'Field value is below minimum length',\n [VALIDATION_ERRORS.INVALID_EMAIL]: 'Invalid email address format',\n [VALIDATION_ERRORS.INVALID_URL]: 'Invalid URL format',\n [VALIDATION_ERRORS.INVALID_UUID]: 'Invalid UUID format',\n [VALIDATION_ERRORS.INVALID_IP_ADDRESS]: 'Invalid IP address format',\n [VALIDATION_ERRORS.INVALID_USER_AGENT]: 'Invalid or missing user agent',\n [VALIDATION_ERRORS.BAD_REQUEST]: 'Bad request',\n [VALIDATION_ERRORS.INVALID_START_DATE]: 'Invalid request data',\n [VALIDATION_ERRORS.INVALID_END_DATE]: 'Invalid request data',\n [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 'Invalid request data',\n\n // Detection\n [DETECTION_ERRORS.DETECTION_FAILED]: 'Agent detection failed',\n [DETECTION_ERRORS.INSUFFICIENT_DATA]: 'Insufficient data for detection',\n [DETECTION_ERRORS.PATTERN_MATCH_FAILED]: 'Pattern matching failed',\n [DETECTION_ERRORS.WASM_NOT_LOADED]: 'WASM module is not loaded',\n [DETECTION_ERRORS.WASM_EXECUTION_FAILED]: 'WASM execution failed',\n [DETECTION_ERRORS.CONFIDENCE_BELOW_THRESHOLD]: 'Detection confidence below threshold',\n [DETECTION_ERRORS.SIGNATURE_VERIFICATION_FAILED]: 'Signature verification failed',\n\n // Rate Limiting\n [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 'Rate limit exceeded',\n [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 'Burst limit exceeded',\n [RATE_LIMIT_ERRORS.DAILY_LIMIT_EXCEEDED]: 'Daily request limit exceeded',\n [RATE_LIMIT_ERRORS.MONTHLY_LIMIT_EXCEEDED]: 'Monthly request limit exceeded',\n [RATE_LIMIT_ERRORS.CONCURRENT_LIMIT_EXCEEDED]: 'Concurrent request limit exceeded',\n [RATE_LIMIT_ERRORS.QUOTA_EXCEEDED]: 'Account quota exceeded',\n [RATE_LIMIT_ERRORS.RATE_LIMITED]: 'Too many requests',\n\n // Permissions\n [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 'Insufficient permissions',\n [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 'Resource not found',\n [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 'Access to resource denied',\n [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 'Operation not allowed',\n [PERMISSION_ERRORS.PROJECT_ACCESS_DENIED]: 'Project access denied',\n [PERMISSION_ERRORS.PIXEL_ACCESS_DENIED]: 'Pixel access denied',\n [PERMISSION_ERRORS.FORBIDDEN]: 'Access denied',\n [PERMISSION_ERRORS.PERMISSION_DENIED]: 'Permission denied',\n\n // Network\n [NETWORK_ERRORS.CONNECTION_FAILED]: 'Connection failed',\n [NETWORK_ERRORS.TIMEOUT]: 'Request timeout',\n [NETWORK_ERRORS.DNS_RESOLUTION_FAILED]: 'DNS resolution failed',\n [NETWORK_ERRORS.SSL_ERROR]: 'SSL/TLS error',\n [NETWORK_ERRORS.PROXY_ERROR]: 'Proxy error',\n [NETWORK_ERRORS.UPSTREAM_ERROR]: 'Upstream service error',\n\n // Internal\n [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 'Internal server error',\n [INTERNAL_ERRORS.DATABASE_ERROR]: 'Database error',\n [INTERNAL_ERRORS.CACHE_ERROR]: 'Cache error',\n [INTERNAL_ERRORS.CONFIGURATION_ERROR]: 'Configuration error',\n [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 'Initialization error',\n [INTERNAL_ERRORS.PROCESSING_ERROR]: 'Processing error',\n [INTERNAL_ERRORS.UNKNOWN_ERROR]: 'An unknown error occurred',\n [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]:\n 'A dependency is temporarily unavailable. Retry shortly.',\n [INTERNAL_ERRORS.TRANSACTION_FAILED]:\n 'The deletion failed because of a database error. The project was not deleted.',\n [INTERNAL_ERRORS.DELETE_FAILED]: 'Failed to delete project',\n [INTERNAL_ERRORS.PARTITION_RETIREMENT_IN_PROGRESS]:\n 'The project data is being archived. Retry shortly.',\n [INTERNAL_ERRORS.FLY_CLEANUP_FAILED]:\n \"Couldn't stop a managed agent's machine, so the delete was refused. Retry the delete.\",\n\n // Session\n [SESSION_ERRORS.SESSION_NOT_FOUND]: 'Session not found',\n [SESSION_ERRORS.SESSION_EXPIRED]: 'Session has expired',\n [SESSION_ERRORS.SESSION_INVALID]: 'Session is invalid',\n [SESSION_ERRORS.SESSION_CREATION_FAILED]: 'Failed to create session',\n [SESSION_ERRORS.SESSION_UPDATE_FAILED]: 'Failed to update session',\n [SESSION_ERRORS.SESSION_STORAGE_ERROR]: 'Session storage error',\n [SESSION_ERRORS.MAX_SESSIONS_EXCEEDED]: 'Maximum sessions exceeded',\n\n // Pixel\n [PIXEL_ERRORS.PIXEL_NOT_FOUND]: 'Pixel not found',\n [PIXEL_ERRORS.PIXEL_DISABLED]: 'Pixel is disabled',\n [PIXEL_ERRORS.PIXEL_CONFIGURATION_ERROR]: 'Pixel configuration error',\n [PIXEL_ERRORS.PIXEL_DOMAIN_NOT_ALLOWED]: 'Domain not allowed for this pixel',\n [PIXEL_ERRORS.PIXEL_PATH_SKIPPED]: 'Path is configured to be skipped',\n [PIXEL_ERRORS.PIXEL_EVENT_INVALID]: 'Invalid pixel event',\n [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 'Event batch exceeds maximum size',\n [PIXEL_ERRORS.MISSING_PIXEL_ID]: 'Project ID is required',\n [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 'Failed to store detection data',\n [PIXEL_ERRORS.PIXEL_CREATION_FAILED]: 'Failed to create pixel for project',\n\n // API\n [API_ERRORS.ENDPOINT_NOT_FOUND]: 'API endpoint not found',\n [API_ERRORS.METHOD_NOT_ALLOWED]: 'HTTP method not allowed',\n [API_ERRORS.VERSION_NOT_SUPPORTED]: 'API version not supported',\n [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 'Content type not supported',\n [API_ERRORS.RESPONSE_TOO_LARGE]: 'Response exceeds maximum size',\n [API_ERRORS.REQUEST_TOO_LARGE]: 'Request exceeds maximum size',\n [API_ERRORS.ENDPOINT_RETIRED]: 'This endpoint has been retired',\n\n // Billing\n [BILLING_ERRORS.LIMIT_EXCEEDED]: 'Billing limit exceeded',\n [BILLING_ERRORS.BILLING_SUSPENDED]: 'Account billing suspended',\n [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 'Account in billing grace period',\n\n // Resources\n [RESOURCE_ERRORS.CONFLICT]: 'Resource conflict',\n [RESOURCE_ERRORS.PROJECT_NOT_FOUND]: 'Project not found',\n [RESOURCE_ERRORS.REVIEW_REQUIRED]:\n 'Deploy requires explicit confirmation of the consequential writes it will perform.',\n\n // Policy\n [POLICY_ERRORS.POLICY_FETCH_FAILED]: 'Failed to fetch policy',\n\n // Analytics\n [ANALYTICS_ERRORS.INVALID_PERIOD]: 'Period must be one of: hour, day, week, month',\n [ANALYTICS_ERRORS.ANALYTICS_FETCH_ERROR]: 'Failed to retrieve analytics data',\n [ANALYTICS_ERRORS.STATS_FETCH_ERROR]: 'Failed to retrieve stats',\n\n // Deploy\n [DEPLOY_ERRORS.MISSING_USER_IDENTIFIER]:\n 'Either userEmail or userGithubId is required to identify the user',\n [DEPLOY_ERRORS.USER_NOT_FOUND]:\n 'User not found in Checkpoint. The user must have an existing Checkpoint account to deploy.',\n [DEPLOY_ERRORS.NO_ORGANIZATION]:\n 'User has no organization in Checkpoint. Please complete onboarding first at https://kya.vouched.id',\n [DEPLOY_ERRORS.DEPLOY_FAILED]: 'Deployment failed',\n [DEPLOY_ERRORS.WFP_NOT_CONFIGURED]: 'Managed hosting is not configured',\n [DEPLOY_ERRORS.NATIVE_ISSUER_PROVISIONING_BUSY]:\n 'Native issuer provisioning is busy or temporarily unavailable; retry deployment',\n [DEPLOY_ERRORS.NATIVE_ISSUER_PROVISIONING_FAILED]:\n 'Native issuer provisioning failed; deployment retained for retry',\n\n // Bare (un-prefixed, shared across pixel/openclaw/deploy/shopify/bouncer/analytics)\n [BARE_ERRORS.BARE_VALIDATION_ERROR]: 'Invalid request data',\n [BARE_ERRORS.BARE_INTERNAL_ERROR]: 'Internal server error',\n [BARE_ERRORS.BARE_INVALID_REQUEST]: 'Invalid JSON body',\n [BARE_ERRORS.BARE_INVALID_JSON]: 'Request body must be valid JSON',\n [BARE_ERRORS.BARE_INVALID_START_DATE]:\n 'Invalid startDate format. Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)',\n [BARE_ERRORS.BARE_INVALID_END_DATE]:\n 'Invalid endDate format. Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)',\n [BARE_ERRORS.BARE_INVALID_DATE_RANGE]: 'startDate must be before endDate',\n [BARE_ERRORS.BARE_INVALID_DATE]:\n 'Invalid date format. Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)',\n [BARE_ERRORS.BARE_UNKNOWN_ERROR]: 'Failed to delete project',\n [BARE_ERRORS.BARE_NOT_FOUND]: 'Not found',\n [BARE_ERRORS.BARE_FORBIDDEN]: 'Forbidden',\n\n // Lowercase (kya-os events wire format)\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 'Request body must be valid JSON',\n [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 'Invalid request body',\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_CURSOR]:\n 'The cursor was not issued by this feed for this project; read from the start',\n\n // Bouncer (lower-case wire format)\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROJECT]: 'API key is not associated with a project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_AGENT_DID]: 'agent_did query parameter is required',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_CONFIGURED]: 'Bouncer is not configured for this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_CREDENTIAL_CONFIG]:\n 'Credential provider missing required fields: authEndpoint and responseFields',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_NOT_FOUND]: 'Project not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_MISMATCH]:\n 'API key does not have access to this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_DELEGATION_ID]: 'Delegation ID is required',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_TOKEN]: 'Invalid or expired delegation token',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_MISMATCH]: 'Delegation ID does not match token',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_TOKENS_NOT_FOUND]:\n 'OAuth tokens not available for this delegation',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DECRYPTION_ERROR]: 'Failed to decrypt OAuth tokens',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS]: 'At least one proof is required',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_BATCH_TOO_LARGE]: 'Maximum batch size is 100 proofs',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS_PROCESSED]:\n 'No proofs were processed. This indicates a server error.',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_ALL_PROOFS_REJECTED]:\n 'All proofs were rejected due to validation failures',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_UNAUTHORIZED]: 'API key is not associated with a project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_FORBIDDEN]: 'API key does not have access to this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_FOUND]: 'Session not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_CONFIG_NOT_FOUND]: 'Bouncer config not found for project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AGENT_DENIED]: 'Agent is on the deny list',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_NOT_FOUND]: 'Delegation not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_SESSION_NOT_FOUND]: 'Session not found',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROOF_VALIDATION_ERROR]: 'Proof validation failed',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INSUFFICIENT_SCOPES]: 'Missing required scopes',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_VALIDATION_ERROR]: 'Delegation validation failed',\n [BOUNCER_LOWERCASE_ERRORS.GRANT_PREDATES_ISSUANCE_CORE]:\n 'The grant predates the issuance core; authorize again',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_HTTP_REGISTRATION]:\n 'Invalid or unsupported native HTTP registration',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_MISMATCH]:\n 'The registered tool protection revision is not the one served to this project',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_GRACE_UNAVAILABLE]:\n 'The audit record for a registration on the previous tool protection revision could not be written; retry the registration',\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AUTHORIZATION_HOST_UNAVAILABLE]:\n 'Authorization host is a project deployment that cannot currently serve consent',\n\n // Delegation OAuth (lower-case wire format)\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_REQUEST]: 'Invalid request body',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_UNSUPPORTED_GRANT_TYPE]:\n 'Only authorization_code grant type is supported',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_GRANT]: 'Invalid or expired authorization code',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_DELEGATION]: 'Delegation not found or inactive',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INTERNAL_ERROR]:\n 'An internal error occurred during token exchange',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_STATE]:\n 'Restart authorization from the requesting agent.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_TRANSACTION]:\n 'Restart authorization from the requesting agent.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_UNAVAILABLE]:\n 'OAuth is temporarily unavailable. Please request a new authorization link.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_NOT_CONFIGURED]:\n 'OAuth provider is not configured. Please configure OAuth in the dashboard.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_CONFIGURATION_UNSUPPORTED]:\n 'The selected provider is not configured for the platform delegation callback.',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_PROVIDER_CONFIG]:\n 'OAuth provider is missing authorization endpoint',\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_RATE_LIMIT_EXCEEDED]:\n 'Too many requests. Please try again later.',\n\n // Bouncer (upper-case wire format)\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_BODY]: 'Invalid JSON in request body',\n [BOUNCER_UPPERCASE_ERRORS.MCPI_CONFIG_NOT_FOUND]: 'KYA-OS configuration not found',\n [BOUNCER_UPPERCASE_ERRORS.CONSENT_CONFIG_NOT_FOUND]:\n 'Consent configuration not found for this project',\n [BOUNCER_UPPERCASE_ERRORS.PROJECT_LOOKUP_FAILED]: 'Failed to lookup project',\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_VALIDATION_ERROR]: 'Configuration validation failed',\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_FETCH_FAILED]: 'Failed to fetch configuration',\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_UPDATE_FAILED]: 'Failed to update configuration',\n [BOUNCER_UPPERCASE_ERRORS.DEPLOYMENT_NOT_FOUND]: 'No active deployment for this project',\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_ID]: 'Invalid delegation request ID format',\n [BOUNCER_UPPERCASE_ERRORS.DELEGATION_REQUEST_NOT_FOUND]:\n 'No delegation request exists for this ID. It may have expired, or it was never issued.',\n\n // Audit ingest\n [AUDIT_ERRORS.AUDIT_CREDENTIAL_REQUIRED]: 'A source-bound audit ingest credential is required',\n [AUDIT_ERRORS.AUDIT_REQUEST_TOO_LARGE]: 'Audit submission exceeds 6291456 bytes',\n [AUDIT_ERRORS.AUDIT_INVALID_JSON]: 'Request body must be valid JSON',\n [AUDIT_ERRORS.AUDIT_INVALID_CREDENTIAL]: 'Invalid audit ingest credential',\n [AUDIT_ERRORS.AUDIT_RATE_LIMITED]: 'Audit ingest rate limit exceeded',\n [AUDIT_ERRORS.AUDIT_INVALID_SUBMISSION]: 'Invalid audit recorder submission envelope',\n [AUDIT_ERRORS.AUDIT_INTERNAL_ERROR]: 'Audit recorder is temporarily unavailable',\n\n // Audit protocol (relayed from @kya-os/mcp). Below 500 the wire message is\n // protocol-owned; these texts describe the failure class.\n [AUDIT_PROTOCOL_ERRORS.AUDIT_UNAUTHORIZED_SUBMISSION]:\n 'Audit producer is not authorized for this ledger',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_LEDGER_MISMATCH]:\n 'Submission belongs to a different audit ledger than the credential binding',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EPOCH_MISMATCH]: 'Submission belongs to a different ledger epoch',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVENT_ID_CONFLICT]:\n 'Producer event identity was reused with different content',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_EVENT]: 'Audit event failed protocol validation',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_FAILURE]:\n 'Submitted evidence could not be matched or persisted',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_INTEGRITY]:\n 'Evidence ciphertext or metadata digest does not verify',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_CONFIGURATION]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_JOURNAL_FAILURE]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_APPEND_CONFLICT_EXHAUSTED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_LEGAL_HOLD]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_ACCESS_DENIED]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_INVALID]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_ROLLBACK]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_CONFLICT]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_PUBLICATION_FAILED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_PROJECTION_CONFLICT]: 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_VERIFICATION_FAILED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_CONTINUITY_FAILED]:\n 'Audit recorder is temporarily unavailable',\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_OUT_OF_ORDER]: 'Audit recorder is temporarily unavailable',\n\n // KYA-OS native HTTP protocol (kyaos/*). The wire carries no message;\n // these texts are documentation only.\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_ISSUER_FORBIDDEN]:\n 'The caller is not an authorized native issuer for this project',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PROFILE_VIOLATION]:\n 'The request does not conform to the KYA-OS native HTTP profile',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SESSION]:\n 'The session is unknown, expired, or not owned by this project',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_CONFLICT]:\n 'The session is already bound to a different registration or grant',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_EXPIRED]: 'The pickup anchor has expired',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SCOPE_INSUFFICIENT]:\n 'The requested scopes exceed what the session allows',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CONSENT_REQUIRED]:\n 'Consent terms must be accepted before a delegation can be issued',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_PINNED]:\n 'The pickup anchor is pinned to a different holder key',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_AUTHORIZATION_HOST_UNAVAILABLE]:\n 'The authorization host cannot currently serve this request',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CHAIN_BROKEN]: 'The propagation chain could not be verified',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_DELEGATION_REVOKED]: 'The delegation has been revoked',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_EXPIRED]: 'The credential or proof has expired',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_HOLDER_MISMATCH]:\n 'The holder does not match the delegation or grant',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SIGNATURE]: 'The signature could not be verified',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_MISMATCH]:\n 'The session does not match the delegation or proof',\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_POLICY_UNAVAILABLE]:\n 'The policy revision is currently unavailable',\n\n // Gateway vault resolve (five codes shared with the API-key vault resolve route)\n [GATEWAY_VAULT_ERRORS.MALFORMED_REQUEST_BODY]: 'Malformed JSON body',\n [GATEWAY_VAULT_ERRORS.GATEWAY_NOT_CONFIGURED]:\n 'Gateway public key or trusted DID not configured for this project',\n [GATEWAY_VAULT_ERRORS.INVALID_ASSERTION]: 'Assertion JWT must have 3 parts',\n [GATEWAY_VAULT_ERRORS.INVALID_SIGNATURE]: 'Assertion signature verification failed',\n [GATEWAY_VAULT_ERRORS.ASSERTION_EXPIRED]: 'Assertion is expired or outside the allowed window',\n [GATEWAY_VAULT_ERRORS.ASSERTION_REPLAYED]: 'Assertion nonce has already been used',\n [GATEWAY_VAULT_ERRORS.PROJECT_MISMATCH]: 'Assertion projectId does not match route',\n [GATEWAY_VAULT_ERRORS.ISSUER_MISMATCH]: 'Assertion issuer does not match trusted gateway DID',\n [GATEWAY_VAULT_ERRORS.USER_DID_MISMATCH]: 'Assertion userDid does not match request body userDid',\n [GATEWAY_VAULT_ERRORS.TOOL_NAME_MISMATCH]:\n 'Assertion toolName does not match request body toolName',\n [GATEWAY_VAULT_ERRORS.SESSION_ID_MISMATCH]:\n 'Assertion sessionId does not match request body sessionId',\n [GATEWAY_VAULT_ERRORS.NOT_AUTHORIZED]: 'User is not a member of this organization',\n [GATEWAY_VAULT_ERRORS.CREDENTIALS_NOT_CONFIGURED]: 'Connect your credentials in Checkpoint',\n [GATEWAY_VAULT_ERRORS.OAUTH_EXPIRED]: 'Provider token expired; user must reconnect',\n\n // Vault resolve\n [VAULT_ERRORS.NO_AGENT_KEY]: 'No agent deployment found for this project',\n};\n\n/**\n * HTTP Status Codes for Errors\n */\nexport const ERROR_STATUS_CODES: Partial<Record<ErrorCode, number>> = {\n // 200 OK (billing grace period is a soft warning, not a failure)\n [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 200,\n\n // 400 Bad Request\n [VALIDATION_ERRORS.INVALID_REQUEST]: 400,\n [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 400,\n [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 400,\n [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 400,\n [VALIDATION_ERRORS.BAD_REQUEST]: 400,\n [VALIDATION_ERRORS.INVALID_START_DATE]: 400,\n [VALIDATION_ERRORS.INVALID_END_DATE]: 400,\n [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 400,\n [PIXEL_ERRORS.MISSING_PIXEL_ID]: 400,\n [ANALYTICS_ERRORS.INVALID_PERIOD]: 400,\n [DEPLOY_ERRORS.MISSING_USER_IDENTIFIER]: 400,\n [DEPLOY_ERRORS.NO_ORGANIZATION]: 400,\n [BARE_ERRORS.BARE_VALIDATION_ERROR]: 400,\n [BARE_ERRORS.BARE_INVALID_REQUEST]: 400,\n [BARE_ERRORS.BARE_INVALID_JSON]: 400,\n [BARE_ERRORS.BARE_INVALID_START_DATE]: 400,\n [BARE_ERRORS.BARE_INVALID_END_DATE]: 400,\n [BARE_ERRORS.BARE_INVALID_DATE_RANGE]: 400,\n [BARE_ERRORS.BARE_INVALID_DATE]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_CURSOR]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROJECT]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_AGENT_DID]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_CONFIGURED]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_CREDENTIAL_CONFIG]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_MISSING_DELEGATION_ID]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_BATCH_TOO_LARGE]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NO_PROOFS_PROCESSED]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_ALL_PROOFS_REJECTED]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROOF_VALIDATION_ERROR]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_VALIDATION_ERROR]: 400,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_HTTP_REGISTRATION]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_REQUEST]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_UNSUPPORTED_GRANT_TYPE]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_STATE]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_TRANSACTION]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_NOT_CONFIGURED]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_CONFIGURATION_UNSUPPORTED]: 400,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_PROVIDER_CONFIG]: 400,\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_BODY]: 400,\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_VALIDATION_ERROR]: 400,\n [BOUNCER_UPPERCASE_ERRORS.INVALID_REQUEST_ID]: 400,\n [AUDIT_ERRORS.AUDIT_INVALID_JSON]: 400,\n [AUDIT_ERRORS.AUDIT_INVALID_SUBMISSION]: 400,\n [GATEWAY_VAULT_ERRORS.MALFORMED_REQUEST_BODY]: 400,\n [GATEWAY_VAULT_ERRORS.INVALID_ASSERTION]: 400,\n\n // 401 Unauthorized\n [AUTH_ERRORS.INVALID_API_KEY]: 401,\n [AUTH_ERRORS.EXPIRED_API_KEY]: 401,\n [AUTH_ERRORS.INVALID_TOKEN]: 401,\n [AUTH_ERRORS.EXPIRED_TOKEN]: 401,\n [AUTH_ERRORS.MISSING_CREDENTIALS]: 401,\n [AUTH_ERRORS.MANAGEMENT_TOKEN_NOT_ACCEPTED]: 401,\n [AUTH_ERRORS.UNAUTHORIZED]: 401,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INVALID_TOKEN]: 401,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_UNAUTHORIZED]: 401,\n [AUDIT_ERRORS.AUDIT_CREDENTIAL_REQUIRED]: 401,\n [AUDIT_ERRORS.AUDIT_INVALID_CREDENTIAL]: 401,\n // Both vault resolve routes verify through one shared verifier, so a failed\n // signature is a 401 on each.\n [GATEWAY_VAULT_ERRORS.INVALID_SIGNATURE]: 401,\n\n // 402 Payment Required\n [BILLING_ERRORS.LIMIT_EXCEEDED]: 402,\n [BILLING_ERRORS.BILLING_SUSPENDED]: 402,\n\n // 403 Forbidden\n [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 403,\n [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 403,\n [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 403,\n [PERMISSION_ERRORS.FORBIDDEN]: 403,\n [PERMISSION_ERRORS.PERMISSION_DENIED]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_MISMATCH]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_MISMATCH]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_FORBIDDEN]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AGENT_DENIED]: 403,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_INSUFFICIENT_SCOPES]: 403,\n [BOUNCER_LOWERCASE_ERRORS.GRANT_PREDATES_ISSUANCE_CORE]: 409,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_MISMATCH]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_UNAUTHORIZED_SUBMISSION]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_ISSUER_FORBIDDEN]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SCOPE_INSUFFICIENT]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CONSENT_REQUIRED]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_PINNED]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_CHAIN_BROKEN]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_DELEGATION_REVOKED]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_HOLDER_MISMATCH]: 403,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SIGNATURE]: 403,\n [BARE_ERRORS.BARE_FORBIDDEN]: 403,\n [GATEWAY_VAULT_ERRORS.ASSERTION_EXPIRED]: 403,\n [GATEWAY_VAULT_ERRORS.ASSERTION_REPLAYED]: 403,\n [GATEWAY_VAULT_ERRORS.PROJECT_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.ISSUER_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.USER_DID_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.TOOL_NAME_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.SESSION_ID_MISMATCH]: 403,\n [GATEWAY_VAULT_ERRORS.NOT_AUTHORIZED]: 403,\n [GATEWAY_VAULT_ERRORS.OAUTH_EXPIRED]: 403,\n\n // 404 Not Found\n [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 404,\n [API_ERRORS.ENDPOINT_NOT_FOUND]: 404,\n [API_ERRORS.ENDPOINT_RETIRED]: 410,\n [PIXEL_ERRORS.PIXEL_NOT_FOUND]: 404,\n [SESSION_ERRORS.SESSION_NOT_FOUND]: 404,\n [DEPLOY_ERRORS.USER_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_PROJECT_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_TOKENS_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_CONFIG_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DELEGATION_NOT_FOUND]: 404,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_SESSION_NOT_FOUND]: 404,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_DELEGATION]: 404,\n [BOUNCER_UPPERCASE_ERRORS.MCPI_CONFIG_NOT_FOUND]: 404,\n [BOUNCER_UPPERCASE_ERRORS.CONSENT_CONFIG_NOT_FOUND]: 404,\n [BOUNCER_UPPERCASE_ERRORS.DEPLOYMENT_NOT_FOUND]: 404,\n [BOUNCER_UPPERCASE_ERRORS.DELEGATION_REQUEST_NOT_FOUND]: 404,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_INVALID_SESSION]: 404,\n [BARE_ERRORS.BARE_NOT_FOUND]: 404,\n [GATEWAY_VAULT_ERRORS.CREDENTIALS_NOT_CONFIGURED]: 404,\n [VAULT_ERRORS.NO_AGENT_KEY]: 404,\n\n // 405 Method Not Allowed\n [API_ERRORS.METHOD_NOT_ALLOWED]: 405,\n\n // 409 Conflict\n [RESOURCE_ERRORS.CONFLICT]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_LEDGER_MISMATCH]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EPOCH_MISMATCH]: 409,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVENT_ID_CONFLICT]: 409,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_CONFLICT]: 409,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_SESSION_MISMATCH]: 409,\n\n // 410 Gone\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PICKUP_EXPIRED]: 410,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_EXPIRED]: 410,\n\n // NOTE: RESOURCE_ERRORS.PROJECT_NOT_FOUND deliberately has no entry here.\n // The pixel API emits it with 400, while enforce and the policy\n // middleware emit it with 404. There is no single correct status, so it\n // stays unpinned and callers set their own status per surface. Locked by\n // a test in __tests__/errors.test.ts.\n\n // NOTE: DEPLOY_ERRORS.DEPLOY_FAILED, WFP_NOT_CONFIGURED,\n // NATIVE_ISSUER_PROVISIONING_BUSY and NATIVE_ISSUER_PROVISIONING_FAILED\n // deliberately have no entry here. They are computed by the managed\n // deploy service, and the deploy route ships every service code at 400\n // today even though WFP_NOT_CONFIGURED is a server misconfiguration and\n // DEPLOY_FAILED an infrastructure failure. No single status is correct,\n // so they stay unpinned and the route owns the status per surface.\n // Locked by a test in __tests__/errors.test.ts.\n\n // NOTE: OAUTH_LOWERCASE_ERRORS.LOWERCASE_INVALID_GRANT deliberately has no\n // entry here. The OAuth token exchange route emits it at 400 for an\n // invalid or expired authorization code and at 403 when the code does\n // not match the agent or project. No single status is correct, so it\n // stays unpinned and the route owns the status per branch. Locked by a\n // test in __tests__/errors.test.ts.\n\n // NOTE: KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_PROFILE_VIOLATION deliberately\n // has no entry here. The native HTTP handler emits it at 415 (wrong\n // content type), 413 (body over 64 KiB) and 400 (unparseable or\n // schema-invalid input), and the issuer and propagation services emit it\n // at 403 for pickup, policy and holder-binding violations. No single\n // status is correct, so it stays unpinned and each emitter owns the\n // status. Locked by a test in __tests__/errors.test.ts.\n\n // 413 Payload Too Large\n [API_ERRORS.REQUEST_TOO_LARGE]: 413,\n [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 413,\n [AUDIT_ERRORS.AUDIT_REQUEST_TOO_LARGE]: 413,\n\n // 415 Unsupported Media Type\n [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 415,\n\n // 422 Unprocessable Entity\n [RESOURCE_ERRORS.REVIEW_REQUIRED]: 422,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_EVENT]: 422,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_FAILURE]: 422,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_INTEGRITY]: 422,\n\n // 429 Too Many Requests\n [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.DAILY_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.RATE_LIMITED]: 429,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_RATE_LIMIT_EXCEEDED]: 429,\n [AUDIT_ERRORS.AUDIT_RATE_LIMITED]: 429,\n\n // 500 Internal Server Error\n [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 500,\n [INTERNAL_ERRORS.DATABASE_ERROR]: 500,\n [INTERNAL_ERRORS.PROCESSING_ERROR]: 500,\n [INTERNAL_ERRORS.TRANSACTION_FAILED]: 500,\n [INTERNAL_ERRORS.DELETE_FAILED]: 500,\n [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 500,\n [PIXEL_ERRORS.PIXEL_CREATION_FAILED]: 500,\n [POLICY_ERRORS.POLICY_FETCH_FAILED]: 500,\n [ANALYTICS_ERRORS.ANALYTICS_FETCH_ERROR]: 500,\n [ANALYTICS_ERRORS.STATS_FETCH_ERROR]: 500,\n [BARE_ERRORS.BARE_INTERNAL_ERROR]: 500,\n [BARE_ERRORS.BARE_UNKNOWN_ERROR]: 500,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_DECRYPTION_ERROR]: 500,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_INTERNAL_ERROR]: 500,\n [BOUNCER_UPPERCASE_ERRORS.PROJECT_LOOKUP_FAILED]: 500,\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_FETCH_FAILED]: 500,\n [BOUNCER_UPPERCASE_ERRORS.CONFIG_UPDATE_FAILED]: 500,\n [AUDIT_ERRORS.AUDIT_INTERNAL_ERROR]: 500,\n // The audit ingest route's protocolStatus switch falls through to 500 for\n // these ten; pinned explicitly because that is the status it ships.\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_LEGAL_HOLD]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_EVIDENCE_ACCESS_DENIED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_INVALID]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_ROLLBACK]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_CONFLICT]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_CHECKPOINT_PUBLICATION_FAILED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_PROJECTION_CONFLICT]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_VERIFICATION_FAILED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_CONTINUITY_FAILED]: 500,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_MIRROR_OUT_OF_ORDER]: 500,\n [GATEWAY_VAULT_ERRORS.GATEWAY_NOT_CONFIGURED]: 500,\n\n // 502 Bad Gateway\n [NETWORK_ERRORS.UPSTREAM_ERROR]: 502,\n [INTERNAL_ERRORS.FLY_CLEANUP_FAILED]: 502,\n\n // 503 Service Unavailable\n [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 503,\n [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]: 503,\n [INTERNAL_ERRORS.PARTITION_RETIREMENT_IN_PROGRESS]: 503,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_AUTHORIZATION_HOST_UNAVAILABLE]: 503,\n [BOUNCER_LOWERCASE_ERRORS.LOWERCASE_POLICY_REVISION_GRACE_UNAVAILABLE]: 503,\n [OAUTH_LOWERCASE_ERRORS.LOWERCASE_OAUTH_UNAVAILABLE]: 503,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_INVALID_CONFIGURATION]: 503,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_JOURNAL_FAILURE]: 503,\n [AUDIT_PROTOCOL_ERRORS.AUDIT_APPEND_CONFLICT_EXHAUSTED]: 503,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_AUTHORIZATION_HOST_UNAVAILABLE]: 503,\n [KYAOS_PROTOCOL_ERRORS.KYAOS_SLASH_POLICY_UNAVAILABLE]: 503,\n\n // 504 Gateway Timeout\n [NETWORK_ERRORS.TIMEOUT]: 504,\n};\n\n/**\n * Create a standardized error object\n */\nexport function createError(\n code: ErrorCode,\n details?: Record<string, unknown>,\n customMessage?: string\n) {\n return {\n code,\n message: customMessage || ERROR_MESSAGES[code] || 'An error occurred',\n statusCode: ERROR_STATUS_CODES[code] || 500,\n details,\n timestamp: new Date().toISOString(),\n };\n}\n","/**\n * Rate Limits and Plan Limits\n *\n * Defines limits for different subscription plans and API usage\n */\n\nimport { UserPlan } from '../types/entities';\n\n/**\n * Plan-based Rate Limits\n */\nexport const PLAN_RATE_LIMITS: Record<\n UserPlan,\n {\n requestsPerSecond: number;\n requestsPerMinute: number;\n requestsPerHour: number;\n requestsPerDay: number;\n requestsPerMonth: number;\n burstLimit: number;\n concurrentRequests: number;\n }\n> = {\n free: {\n requestsPerSecond: 1,\n requestsPerMinute: 20,\n requestsPerHour: 500,\n requestsPerDay: 1_000,\n requestsPerMonth: 10_000,\n burstLimit: 5,\n concurrentRequests: 2,\n },\n pro: {\n requestsPerSecond: 10,\n requestsPerMinute: 200,\n requestsPerHour: 5_000,\n requestsPerDay: 50_000,\n requestsPerMonth: 1_000_000,\n burstLimit: 20,\n concurrentRequests: 10,\n },\n enterprise: {\n requestsPerSecond: 100,\n requestsPerMinute: 2_000,\n requestsPerHour: 50_000,\n requestsPerDay: -1, // Unlimited\n requestsPerMonth: -1, // Unlimited\n burstLimit: 200,\n concurrentRequests: 100,\n },\n};\n\n/**\n * Plan-based Feature Limits\n */\nexport const PLAN_FEATURE_LIMITS: Record<\n UserPlan,\n {\n projects: number;\n pixelsPerProject: number;\n apiKeys: number;\n teamMembers: number;\n dataRetentionDays: number;\n customDomains: number;\n webhooks: number;\n alertRules: number;\n sessionsTracked: number;\n exportSizeLimit: number; // In MB\n organizations: number;\n }\n> = {\n free: {\n projects: 2,\n pixelsPerProject: 3,\n apiKeys: 2,\n teamMembers: 1,\n dataRetentionDays: 7,\n customDomains: 0,\n webhooks: 0,\n alertRules: 1,\n sessionsTracked: 1_000,\n exportSizeLimit: 10,\n organizations: 1,\n },\n pro: {\n projects: 10,\n pixelsPerProject: 20,\n apiKeys: 20,\n teamMembers: 5,\n dataRetentionDays: 90,\n customDomains: 3,\n webhooks: 5,\n alertRules: 10,\n sessionsTracked: 100_000,\n exportSizeLimit: 100,\n organizations: 5,\n },\n enterprise: {\n projects: -1, // Unlimited\n pixelsPerProject: -1, // Unlimited\n apiKeys: -1, // Unlimited\n teamMembers: -1, // Unlimited\n dataRetentionDays: 365,\n customDomains: -1, // Unlimited\n webhooks: -1, // Unlimited\n alertRules: -1, // Unlimited\n sessionsTracked: -1, // Unlimited\n exportSizeLimit: -1, // Unlimited\n organizations: -1, // Unlimited\n },\n};\n\n/**\n * API Request Limits\n */\nexport const API_REQUEST_LIMITS = {\n maxRequestBodySize: 10 * 1024 * 1024, // 10 MB\n maxResponseBodySize: 50 * 1024 * 1024, // 50 MB\n maxHeadersSize: 8 * 1024, // 8 KB\n maxUrlLength: 2048,\n maxQueryParams: 50,\n maxBatchSize: 100,\n maxFileUploadSize: 100 * 1024 * 1024, // 100 MB\n} as const;\n\n/**\n * Pixel Event Limits\n */\nexport const PIXEL_EVENT_LIMITS = {\n maxEventsPerBatch: 100,\n maxEventSize: 64 * 1024, // 64 KB per event\n maxMetadataSize: 16 * 1024, // 16 KB for metadata\n maxCustomDataFields: 50,\n maxSessionDuration: 24 * 60 * 60 * 1000, // 24 hours in ms\n maxPageViewsPerSession: 1000,\n maxInteractionsPerSession: 10000,\n eventQueueSize: 500,\n flushIntervalMin: 1000, // 1 second\n flushIntervalMax: 60000, // 60 seconds\n} as const;\n\n/**\n * Session Limits\n */\nexport const SESSION_LIMITS = {\n maxSessionsPerUser: 10,\n maxSessionsPerIp: 100,\n sessionTimeoutMin: 60, // 1 minute\n sessionTimeoutMax: 86400, // 24 hours\n idleTimeoutMin: 60, // 1 minute\n idleTimeoutMax: 7200, // 2 hours\n maxSessionDataSize: 64 * 1024, // 64 KB\n maxMetadataFields: 20,\n} as const;\n\n/**\n * Detection Limits\n */\nexport const DETECTION_LIMITS = {\n maxUserAgentLength: 1024,\n maxHeadersCount: 100,\n maxHeaderValueLength: 4096,\n maxIpAddressesPerRequest: 10,\n maxCustomRules: 100,\n maxPatternLength: 500,\n cacheSize: 10000,\n cacheTTL: 3600, // 1 hour in seconds\n maxConcurrentDetections: 1000,\n} as const;\n\n/**\n * Database Limits\n */\nexport const DATABASE_LIMITS = {\n maxQueryResults: 10000,\n maxBulkInsertSize: 1000,\n maxBulkUpdateSize: 500,\n maxBulkDeleteSize: 500,\n maxTransactionDuration: 30000, // 30 seconds\n maxConnectionPoolSize: 20,\n queryTimeout: 10000, // 10 seconds\n} as const;\n\n/**\n * Cache Limits\n */\nexport const CACHE_LIMITS = {\n maxCacheSize: 100 * 1024 * 1024, // 100 MB\n maxCacheEntries: 50000,\n maxKeyLength: 250,\n maxValueSize: 1 * 1024 * 1024, // 1 MB\n defaultTTL: 3600, // 1 hour\n maxTTL: 86400, // 24 hours\n} as const;\n\n/**\n * Webhook Limits\n */\nexport const WEBHOOK_LIMITS = {\n maxRetries: 3,\n retryDelayMs: [1000, 5000, 15000], // Exponential backoff\n requestTimeout: 10000, // 10 seconds\n maxPayloadSize: 256 * 1024, // 256 KB\n maxHeadersCount: 20,\n maxUrlLength: 2048,\n} as const;\n\n/**\n * Export Limits\n */\nexport const EXPORT_LIMITS = {\n maxCsvRows: 1000000,\n maxJsonSize: 100 * 1024 * 1024, // 100 MB\n maxExportDuration: 300000, // 5 minutes\n maxConcurrentExports: 3,\n exportRetentionDays: 7,\n} as const;\n\n/**\n * Security Limits\n */\nexport const SECURITY_LIMITS = {\n maxLoginAttempts: 5,\n lockoutDuration: 900, // 15 minutes in seconds\n passwordMinLength: 8,\n passwordMaxLength: 128,\n tokenLength: 32,\n apiKeyLength: 32,\n secretKeyLength: 64,\n otpLength: 6,\n otpValiditySeconds: 300, // 5 minutes\n maxActiveTokens: 10,\n} as const;\n\n/**\n * Performance Thresholds\n */\nexport const PERFORMANCE_THRESHOLDS = {\n slowQueryMs: 1000,\n slowApiCallMs: 3000,\n slowDetectionMs: 100,\n highMemoryUsageMB: 512,\n highCpuUsagePercent: 80,\n highDiskUsagePercent: 90,\n} as const;\n\n/**\n * Default Pagination\n */\nexport const PAGINATION_DEFAULTS = {\n defaultPageSize: 20,\n maxPageSize: 100,\n defaultOffset: 0,\n maxOffset: 100000,\n} as const;\n\n/**\n * Time Windows\n */\nexport const TIME_WINDOWS = {\n realtime: 60, // 1 minute\n hourly: 3600, // 1 hour\n daily: 86400, // 24 hours\n weekly: 604800, // 7 days\n monthly: 2592000, // 30 days\n yearly: 31536000, // 365 days\n} as const;\n\n/**\n * Helper function to check if a limit is exceeded\n */\nexport function isLimitExceeded(current: number, limit: number): boolean {\n if (limit === -1) return false; // Unlimited\n return current >= limit;\n}\n\n/**\n * Helper function to get remaining quota\n */\nexport function getRemainingQuota(used: number, limit: number): number {\n if (limit === -1) return Number.MAX_SAFE_INTEGER; // Unlimited\n return Math.max(0, limit - used);\n}\n\n/**\n * Helper function to calculate rate limit window\n */\nexport function getRateLimitWindow(windowType: keyof typeof TIME_WINDOWS): {\n start: Date;\n end: Date;\n duration: number;\n} {\n const now = new Date();\n const duration = TIME_WINDOWS[windowType] * 1000; // Convert to milliseconds\n const start = new Date(now.getTime() - duration);\n\n return {\n start,\n end: now,\n duration,\n };\n}\n","/**\n * Rule System Constants\n *\n * Configuration constants for the unified rule system\n */\n\n/**\n * Rule system version\n */\nexport const RULE_VERSION = '1.0.0';\n\n/**\n * Rule validation modes\n */\nexport const VALIDATION_MODES = {\n /** Strict validation - all fields required */\n STRICT: 'strict',\n /** Loose validation - allow extra fields */\n LOOSE: 'loose',\n /** No validation - use with caution */\n NONE: 'none',\n} as const;\n\n/**\n * Rule categories\n */\nexport const RULE_CATEGORIES = {\n USER_AGENT: 'userAgent',\n IP_RANGE: 'ipRange',\n SIGNATURE: 'signature',\n BEHAVIORAL: 'behavioral',\n HEADER: 'header',\n} as const;\n\n/**\n * Confidence thresholds\n */\nexport const CONFIDENCE_THRESHOLDS = {\n /** Very high confidence */\n VERY_HIGH: 0.95,\n /** High confidence */\n HIGH: 0.8,\n /** Medium confidence */\n MEDIUM: 0.6,\n /** Low confidence */\n LOW: 0.4,\n /** Very low confidence */\n VERY_LOW: 0.2,\n} as const;\n\n/**\n * Rule update frequencies\n */\nexport const UPDATE_FREQUENCIES = {\n HOURLY: 'hourly',\n DAILY: 'daily',\n WEEKLY: 'weekly',\n MONTHLY: 'monthly',\n} as const;\n\n/**\n * Rule match actions\n *\n * @deprecated Dead internally as of the gateway-enforcement-step-up branch\n * (zero remaining callers repo-wide) — the doc comment claiming\n * `MATCH_ACTIONS.CHALLENGE` backs the worker's CAPTCHA/challenge action was\n * already stale (see `detection/types.ts`'s own \"Future - CAPTCHA or\n * proof-of-work\" note; the real challenge mechanism is\n * `@challenge_type`/`human_step_up`, unrelated to this enum). Kept\n * `@deprecated` rather than removed (bestbrian P2, 2026-09-09): this is a\n * wildcard-re-exported member of `@kya-os/checkpoint-shared`'s public\n * surface at 1.4.0, so deleting it outright is a breaking change for any\n * external consumer without a major version bump. Remove in the next\n * major.\n */\nexport const MATCH_ACTIONS = {\n /** Block the request */\n BLOCK: 'block',\n /** Allow but log */\n LOG: 'log',\n /** Challenge with CAPTCHA */\n CHALLENGE: 'challenge',\n /** Rate limit the client */\n RATE_LIMIT: 'rate_limit',\n /** Allow the request */\n ALLOW: 'allow',\n} as const;\n\n/**\n * Error messages\n */\nexport const RULE_ERRORS = {\n INVALID_FORMAT: 'Invalid rule format',\n VALIDATION_FAILED: 'Rule validation failed',\n LOAD_FAILED: 'Failed to load rules',\n PARSE_FAILED: 'Failed to parse rules',\n VERSION_MISMATCH: 'Rule version mismatch',\n MISSING_REQUIRED: 'Missing required rule fields',\n} as const;\n\n/**\n * Rule file paths\n */\nexport const RULE_PATHS = {\n /** Source YAML file */\n YAML_SOURCE: 'src/data/default-rules.yaml',\n /** Generated JSON file */\n JSON_OUTPUT: 'dist/rules.json',\n /** Bundled rules path */\n BUNDLED: '@kya-os/checkpoint-shared/dist/rules.json',\n} as const;\n","/**\n * Behavioral event types for detection\n */\n\nimport { z } from 'zod';\n\n/**\n * Mouse movement event\n */\nexport const MouseEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n type: z.enum(['move', 'click', 'down', 'up']).optional(),\n});\nexport type MouseEvent = z.infer<typeof MouseEventSchema>;\n\n/**\n * Keyboard event\n */\nexport const KeyboardEventSchema = z.object({\n keyCode: z.number(),\n key: z.string().optional(),\n timestamp: z.number(),\n type: z.enum(['keydown', 'keyup', 'keypress']).optional(),\n});\nexport type KeyboardEvent = z.infer<typeof KeyboardEventSchema>;\n\n/**\n * Scroll event\n */\nexport const ScrollEventSchema = z.object({\n deltaX: z.number().optional(),\n deltaY: z.number(),\n timestamp: z.number(),\n position: z\n .object({\n x: z.number(),\n y: z.number(),\n })\n .optional(),\n});\nexport type ScrollEvent = z.infer<typeof ScrollEventSchema>;\n\n/**\n * Click event with position\n */\nexport const ClickEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n button: z.enum(['left', 'right', 'middle']).optional(),\n target: z.string().optional(),\n});\nexport type ClickEvent = z.infer<typeof ClickEventSchema>;\n\n/**\n * Touch event for mobile devices\n */\nexport const TouchEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n type: z.enum(['start', 'move', 'end', 'cancel']),\n identifier: z.number().optional(),\n});\nexport type TouchEvent = z.infer<typeof TouchEventSchema>;\n\n/**\n * Aggregated behavioral data\n */\nexport const BehavioralDataSchema = z.object({\n mouseMovements: z.array(MouseEventSchema).default([]),\n keyboardEvents: z.array(KeyboardEventSchema).default([]),\n scrollEvents: z.array(ScrollEventSchema).default([]),\n clickEvents: z.array(ClickEventSchema).default([]),\n touchEvents: z.array(TouchEventSchema).default([]),\n sessionDuration: z.number().optional(),\n pageViews: z.number().optional(),\n interactionRate: z.number().optional(),\n});\nexport type BehavioralData = z.infer<typeof BehavioralDataSchema>;\n\n/**\n * Behavioral analysis result\n */\nexport const BehavioralAnalysisSchema = z.object({\n isHumanLike: z.boolean(),\n confidence: z.number().min(0).max(1),\n patterns: z.array(z.string()),\n anomalies: z.array(z.string()).optional(),\n metrics: z\n .object({\n mouseEntropy: z.number().optional(),\n typingSpeed: z.number().optional(),\n scrollPattern: z.string().optional(),\n interactionComplexity: z.number().optional(),\n })\n .optional(),\n});\nexport type BehavioralAnalysis = z.infer<typeof BehavioralAnalysisSchema>;\n","/**\n * API request schemas\n */\n\nimport { z } from 'zod';\nimport { BehavioralDataSchema } from '../events/behavioral';\n\n/**\n * Detection API request\n */\nexport const DetectionRequestSchema = z.object({\n // Required fields\n userAgent: z.string(),\n\n // Optional fields\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n\n // Behavioral data\n behavioralData: BehavioralDataSchema.optional(),\n\n // Options\n options: z\n .object({\n mode: z.enum(['strict', 'balanced', 'lenient']).optional(),\n includeMetadata: z.boolean().optional(),\n includeBreakdown: z.boolean().optional(),\n })\n .optional(),\n\n // Request metadata\n requestId: z.string().optional(),\n timestamp: z.number().optional(),\n});\nexport type DetectionRequest = z.infer<typeof DetectionRequestSchema>;\n\n/**\n * Batch detection request\n */\nexport const BatchDetectionRequestSchema = z.object({\n requests: z.array(DetectionRequestSchema).min(1),\n options: z\n .object({\n parallel: z.boolean().default(true),\n continueOnError: z.boolean().default(true),\n })\n .default({\n parallel: true,\n continueOnError: true,\n }),\n});\nexport type BatchDetectionRequest = z.infer<typeof BatchDetectionRequestSchema>;\n\n/**\n * Verification request\n */\nexport const VerificationRequestSchema = z.object({\n signature: z.string(),\n payload: z.string(),\n timestamp: z.number(),\n publicKey: z.string().optional(),\n});\nexport type VerificationRequest = z.infer<typeof VerificationRequestSchema>;\n\n/**\n * Pattern update request\n */\nexport const PatternUpdateRequestSchema = z.object({\n patterns: z\n .array(\n z.object({\n id: z.string(),\n name: z.string(),\n pattern: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n })\n )\n .min(1),\n action: z.enum(['add', 'update', 'remove', 'replace']),\n});\nexport type PatternUpdateRequest = z.infer<typeof PatternUpdateRequestSchema>;\n","/**\n * API response schemas\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { ConfidenceBreakdownSchema } from '../core/confidence';\nimport { BehavioralAnalysisSchema } from '../events/behavioral';\n\n/**\n * Standard API response wrapper\n */\nexport const ApiResponseSchema = z.object({\n success: z.boolean(),\n data: z.any().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.any().optional(),\n })\n .optional(),\n metadata: z\n .object({\n timestamp: z.number(),\n requestId: z.string().optional(),\n /**\n * Canonical 32-hex correlation id (`deriveCorrelationId`), for\n * cross-surface correlation independent of the per-call `requestId`\n * above. Also echoed as the `X-KYA-Correlation-Id` response header on\n * routes that derive one.\n */\n correlationId: z.string().optional(),\n version: z.string().optional(),\n })\n .optional(),\n});\nexport type ApiResponse<T = unknown> = Omit<z.infer<typeof ApiResponseSchema>, 'data'> & {\n data?: T;\n};\n\n/**\n * Detection API response\n */\nexport const DetectionResponseSchema = z.object({\n result: DetectionResultSchema,\n breakdown: ConfidenceBreakdownSchema.optional(),\n behavioralAnalysis: BehavioralAnalysisSchema.optional(),\n metadata: z\n .object({\n processingTime: z.number(),\n wasmUsed: z.boolean().optional(),\n cacheHit: z.boolean().optional(),\n })\n .optional(),\n});\nexport type DetectionResponse = z.infer<typeof DetectionResponseSchema>;\n\n/**\n * Batch detection response\n */\nexport const BatchDetectionResponseSchema = z.object({\n results: z.array(\n z.object({\n index: z.number(),\n success: z.boolean(),\n result: DetectionResultSchema.optional(),\n error: z.string().optional(),\n })\n ),\n summary: z.object({\n total: z.number(),\n successful: z.number(),\n failed: z.number(),\n agentsDetected: z.number(),\n }),\n});\nexport type BatchDetectionResponse = z.infer<typeof BatchDetectionResponseSchema>;\n\n/**\n * Verification response\n */\nexport const VerificationResponseSchema = z.object({\n valid: z.boolean(),\n algorithm: z.string().optional(),\n timestamp: z.number(),\n message: z.string().optional(),\n});\nexport type VerificationResponse = z.infer<typeof VerificationResponseSchema>;\n\n/**\n * Health check response\n */\nexport const HealthResponseSchema = z.object({\n status: z.enum(['healthy', 'degraded', 'unhealthy']),\n version: z.string(),\n uptime: z.number().min(0),\n checks: z\n .record(\n z.string(),\n z.object({\n status: z.enum(['pass', 'fail']),\n message: z.string().optional(),\n })\n )\n .optional(),\n});\nexport type HealthResponse = z.infer<typeof HealthResponseSchema>;\n\n/**\n * Statistics response\n */\nexport const StatsResponseSchema = z.object({\n totalRequests: z.number().min(0),\n agentsDetected: z.number().min(0),\n detectionRate: z.number().min(0).max(1),\n averageConfidence: z.number().min(0).max(1),\n topAgents: z.array(\n z.object({\n type: z.string(),\n count: z.number().min(0),\n percentage: z.number().min(0).max(100),\n })\n ),\n timeRange: z.object({\n start: z.number(),\n end: z.number(),\n }),\n});\nexport type StatsResponse = z.infer<typeof StatsResponseSchema>;\n","/**\n * Pixel Tracking Types\n *\n * Types for pixel-based agent detection and event tracking\n * Used by the pixel script, API endpoints, and dashboard\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\n\n/**\n * Client Detection Data Schema\n * Data collected by the checkpoint-detector.js module\n */\nexport const ClientDetectionSchema = z.object({\n // Critical Perplexity detection signals\n headless: z.boolean().optional(),\n canvas: z.string().optional(),\n webrtc: z.string().optional(),\n plugins: z.number().optional(),\n automation: z.string().nullable().optional(),\n webdriver: z.boolean().optional(),\n userAgentData: z\n .object({\n brands: z.array(z.string().max(64)).max(16),\n mobile: z.boolean(),\n platform: z.string().max(64),\n architecture: z.string().max(64).optional(),\n bitness: z.string().max(64).optional(),\n model: z.string().max(64).optional(),\n platformVersion: z.string().max(64).optional(),\n highEntropyStatus: z.literal('not_allowed').optional(),\n })\n .optional(),\n\n // Browser characteristics\n chrome: z.boolean().optional(),\n languages: z.array(z.string()).optional(),\n hardwareConcurrency: z.number().nullable().optional(),\n deviceMemory: z.number().nullable().optional(),\n maxTouchPoints: z.number().optional(),\n platform: z.string().optional(),\n vendor: z.string().optional(),\n screenResolution: z.string().optional(),\n colorDepth: z.number().optional(),\n pixelRatio: z.number().optional(),\n timezone: z.string().optional(),\n timezoneOffset: z.number().optional(),\n cookieEnabled: z.boolean().optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n hasTouch: z.boolean().optional(),\n\n // Interaction metrics\n mouseMovements: z.number().optional(),\n keyboardEvents: z.number().optional(),\n scrollEvents: z.number().optional(),\n clickEvents: z.number().optional(),\n touchEvents: z.number().optional(),\n // Input events dispatched with isTrusted:false (synthetic script/extension\n // input, never real hardware). Provenance signal for content-script agent\n // drivers — see human-promotion-audit.untrustedInputShare.\n untrustedEvents: z.number().optional(),\n // Timing physics, counters only (checkpoint-detector.js). Bucket edges sit\n // below the floor a hand showed on the lab gauntlet; the server derives\n // shares and means (lib/detection/timing-physics.ts). No timestamps,\n // coordinates, or key identity ever ride here. `timingVersion` names the\n // detector's guard set (IME, modifier, multi-touch skips) so rows from\n // different sets can be told apart at calibration.\n timingVersion: z.number().optional(),\n keyDwellCount: z.number().optional(),\n keyDwellUnder5: z.number().optional(),\n keyDwellSumMs: z.number().optional(),\n keyGapCount: z.number().optional(),\n keyGapUnder5: z.number().optional(),\n pressCount: z.number().optional(),\n pressAdjacencyCount: z.number().int().nonnegative().optional(),\n pressAdjacentUnder5: z.number().int().nonnegative().optional(),\n pressUnder10: z.number().optional(),\n pressSumMs: z.number().optional(),\n mouseClicks: z.number().optional(),\n zeroTrailClicks: z.number().optional(),\n // Path kinematics, counters only (checkpoint-detector.js), for the driver\n // that manufactures a hand's timing: coalesced samples per pointermove,\n // and whether consecutive steps repeat their length or their heading.\n // Mouse pointer only; no coordinate rides here. `kinematicsVersion` names\n // the rule set (tolerances, pointer filter) the way `timingVersion` does.\n kinematicsVersion: z.number().optional(),\n pointerMoves: z.number().optional(),\n coalescedMoves: z.number().optional(),\n stepPairs: z.number().optional(),\n equalSteps: z.number().optional(),\n straightSteps: z.number().optional(),\n hasInteraction: z.boolean().optional(),\n\n // Connection info\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .nullable()\n .optional(),\n\n // Performance metrics\n performance: z\n .object({\n navigation: z.number().nullable().optional(),\n memory: z\n .object({\n usedJSHeapSize: z.number().optional(),\n totalJSHeapSize: z.number().optional(),\n jsHeapSizeLimit: z.number().optional(),\n })\n .optional(),\n })\n .nullable()\n .optional(),\n\n // Collection metadata\n collectionTime: z.number().optional(),\n timestamp: z.string().optional(),\n error: z.string().optional(),\n});\nexport type ClientDetection = z.infer<typeof ClientDetectionSchema>;\n\n/**\n * Pixel Tracking Request - Simplified request from pixel beacon\n * Used by the POST /api/v1/pixel endpoint\n */\nexport const PixelTrackingRequestSchema = z.object({\n // Pixel identification\n pixelId: z.string(), // UUID of the pixel\n sessionId: z.string(), // Session identifier\n\n // User identification\n userId: z.string().nullable().optional(), // Identified user ID\n // Prior (typically anonymous) user id for an `identify` alias. When present\n // and different from `userId`, the server COPIES older properties from this\n // profile onto the newly-identified one (properties are never merged across\n // profiles automatically). Mirrors the analytics-SDK `identify(previousId)` arg.\n previousId: z.string().optional(),\n userTraits: z\n .record(z.string(), z.unknown())\n .optional() // User properties/traits\n .refine((traits) => !traits || JSON.stringify(traits).length < 10000, {\n message: 'User traits too large (max 10KB)',\n })\n .refine((traits) => !traits || Object.keys(traits).length < 50, {\n message: 'Too many user trait properties (max 50)',\n })\n .refine(\n (traits) => {\n // Validate trait value types - prevent nested objects that are too deep\n if (!traits) return true;\n const validateDepth = (obj: unknown, depth = 0): boolean => {\n if (depth > 3) return false; // Max nesting depth of 3\n if (typeof obj !== 'object' || obj === null) return true;\n return Object.values(obj as Record<string, unknown>).every((val) =>\n validateDepth(val, depth + 1)\n );\n };\n return validateDepth(traits);\n },\n {\n message: 'User traits contain overly nested objects (max depth 3)',\n }\n ),\n\n // Page context\n url: z.string().url(), // Current page URL\n referrer: z.string().optional(), // Referrer URL\n title: z.string().optional(), // Page title\n\n // Detection data\n userAgent: z.string(), // Browser user agent\n headers: z.record(z.string(), z.string()).optional(), // Any additional headers\n\n // Client info\n screenResolution: z.string().optional(), // \"1920x1080\"\n viewport: z.string().optional(), // \"1200x800\"\n timezone: z.string().optional(), // \"America/New_York\"\n language: z.string().optional(), // \"en-US\"\n platform: z.string().optional(), // navigator.platform\n cookiesEnabled: z.boolean().optional(), // navigator.cookieEnabled\n onLine: z.boolean().optional(), // navigator.onLine\n timezoneOffset: z.number().optional(), // Date.getTimezoneOffset()\n connectionType: z.string().optional(), // navigator.connection.effectiveType\n connectionSpeed: z.number().optional(), // navigator.connection.downlink\n\n // Device identity — cross-subdomain cookie set by pixel.js\n deviceId: z.string().optional(),\n\n // Behavioral (if available)\n timeOnPage: z.number().optional(), // Milliseconds\n mouseMovements: z.number().optional(), // Count of mouse events\n clickCount: z.number().optional(), // Number of clicks\n scrollDepth: z.number().optional(), // Percentage 0-100\n pageLoadTime: z.number().optional(), // performance.timing load duration, ms\n domContentLoadedTime: z.number().optional(), // performance.timing DCL duration, ms\n\n // Client-side detection data (NEW)\n clientDetection: ClientDetectionSchema.optional(),\n\n // Request tracking (client-provided, will be validated server-side)\n requestId: z.string().optional(), // Unique request ID for deduplication\n correlationId: z.string().optional(), // Cross-surface correlation id (validated/normalized server-side)\n\n // Event type for special events\n eventType: z.string().optional(), // 'pageview', 'identify', 'logout', etc.\n\n // Metadata\n timestamp: z.string(), // ISO 8601\n version: z.string().optional(), // Pixel version\n\n // Nonce-bound ingest: the value from the PRIOR 202 response's `nonce`\n // field (see `lib/services/nonce.service.ts` in apps/web). Absent on the\n // first pixel hit of a session; absent, stale, or mismatched on any\n // later hit is a forgery signal, never a 400 — a forged hit is accepted\n // for storage but tagged, not rejected.\n nonce: z.string().max(64).optional(),\n // Declares this client stores and echoes the nonce it's handed (the\n // pixel script always sends `true`; absent means a cached pre-upgrade\n // copy of pixel.js, never something a client turns off) — see\n // `nonce.service.ts`'s missing-nonce rule for why the distinction matters.\n nonceEcho: z.boolean().optional(),\n handoffToken: z.string().max(2048).optional().catch(undefined),\n binding: z.string().max(128).optional(),\n\n // IP anonymization (build item 6). Default false, unlike beacon: Tier 2\n // vendor-IP corroboration needs the full address for pixel traffic — see\n // the pixel route's own doc comment.\n anonymizeIp: z.boolean().optional(),\n});\nexport type PixelTrackingRequest = z.infer<typeof PixelTrackingRequestSchema>;\n\n/**\n * Pixel Tracking Response\n */\nexport const PixelTrackingResponseSchema = z.object({\n success: z.boolean(),\n eventId: z.string().uuid().optional(),\n sessionId: z.string().optional(),\n detection: DetectionResultSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n // Nonce-bound ingest: echo this back as `nonce` on the NEXT pixel hit —\n // see `PixelTrackingRequestSchema`'s `nonce` field doc comment.\n nonce: z.string().max(64).optional(),\n handoff: z.object({ status: z.enum(['adopted', 'rejected', 'unavailable']) }).optional(),\n});\nexport type PixelTrackingResponse = z.infer<typeof PixelTrackingResponseSchema>;\n\n/**\n * Pixel Verification Status\n */\nexport const PixelVerificationStatusSchema = z.object({\n status: z.enum(['verified', 'partial', 'pending', 'failed']),\n message: z.string(),\n verified: z.boolean(),\n lastDetection: z.date().nullable(),\n detectionCount: z.number().int().min(0),\n metadata: z\n .object({\n recentDetections: z.number().int().min(0),\n failedDetections: z.number().int().min(0),\n timeWindow: z.string(),\n })\n .optional(),\n});\nexport type PixelVerificationStatus = z.infer<typeof PixelVerificationStatusSchema>;\n","/**\n * Version-agnostic Zod helper schemas.\n *\n * Zod 4 removes `z.string().ip()`. Every site that needs \"an IP address\"\n * goes through this helper so the Zod 4 flip changed one body, not a dozen\n * call sites. The body below is the Zod 4 form.\n */\n\nimport { z } from 'zod';\n\n/** Accepts a bare IPv4 or IPv6 address. Rejects ports, brackets, and whitespace. */\nexport const ipAddressSchema = z.union([z.ipv4(), z.ipv6()], { error: 'Invalid IP address' });\n","/**\n * Event API schemas for tracking and batch processing\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { BehavioralDataSchema } from '../events/behavioral';\nimport { ClientDetectionSchema } from '../types/pixel';\nimport { ipAddressSchema } from '../utils/zod-helpers';\n\n/**\n * Single Event Tracking Request\n */\nexport const EventTrackingRequestSchema = z.object({\n // Required fields\n pixelId: z.string().uuid(),\n sessionId: z.string().min(1).max(255),\n url: z.string().url(),\n userAgent: z.string().min(1).max(1024),\n\n // Optional fields\n ip: ipAddressSchema.optional(),\n timestamp: z.string().datetime().optional(),\n referrer: z.string().url().optional(),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).optional(),\n\n // Headers for additional context\n headers: z.record(z.string(), z.string()).optional(),\n\n // Behavioral tracking data\n behavioralData: BehavioralDataSchema.optional(),\n\n // Client-side browser fingerprint (headless/automation tells, interaction).\n // Optional + additive: legacy clients that omit it are unaffected.\n clientDetection: ClientDetectionSchema.optional(),\n\n // Page metrics\n timeOnPage: z.number().min(0).optional(),\n scrollDepth: z.number().min(0).max(100).optional(),\n clickCount: z.number().min(0).optional(),\n mouseMovements: z.number().min(0).optional(),\n keystrokes: z.number().min(0).optional(),\n\n // Device/viewport info\n screenResolution: z.string().optional(),\n viewport: z.string().optional(),\n\n // Custom metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type EventTrackingRequest = z.infer<typeof EventTrackingRequestSchema>;\n\n/**\n * Single Event Tracking Response\n */\nexport const EventTrackingResponseSchema = z.object({\n success: z.boolean(),\n eventId: z.string().uuid(),\n sessionId: z.string(),\n detection: DetectionResultSchema,\n\n // Rate limit info\n rateLimit: z\n .object({\n limit: z.number(),\n remaining: z.number(),\n reset: z.number(),\n })\n .optional(),\n\n // Debug info (only in development)\n debug: z\n .object({\n processingTime: z.number(),\n rulesVersion: z.string(),\n serverRegion: z.string().optional(),\n cacheHit: z.boolean().optional(),\n })\n .optional(),\n});\nexport type EventTrackingResponse = z.infer<typeof EventTrackingResponseSchema>;\n\n/**\n * Batch Event Request\n */\nexport const BatchEventRequestSchema = z.object({\n // API key for authentication (required for batch)\n apiKey: z.string().min(32).optional(), // Can be in header instead\n\n // Array of events (max 100)\n events: z.array(EventTrackingRequestSchema).min(1).max(100),\n\n // Processing options\n options: z\n .object({\n parallel: z.boolean().default(true),\n continueOnError: z.boolean().default(true),\n includeDetailed: z.boolean().default(false),\n })\n .optional(),\n});\nexport type BatchEventRequest = z.infer<typeof BatchEventRequestSchema>;\n\n/**\n * Batch Event Response\n */\nexport const BatchEventResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().uuid(),\n\n // Processing results\n results: z.array(\n z.object({\n index: z.number(),\n eventId: z.string().uuid().optional(),\n success: z.boolean(),\n detection: DetectionResultSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n })\n ),\n\n // Summary statistics\n summary: z.object({\n total: z.number(),\n successful: z.number(),\n failed: z.number(),\n agentsDetected: z.number(),\n averageConfidence: z.number().min(0).max(1),\n processingTime: z.number(),\n }),\n\n // Rate limit info\n rateLimit: z\n .object({\n limit: z.number(),\n remaining: z.number(),\n reset: z.number(),\n })\n .optional(),\n});\nexport type BatchEventResponse = z.infer<typeof BatchEventResponseSchema>;\n","/**\n * Text read back in terminals and the dashboard. It may be in any language, but it holds no\n * control characters (terminal escapes and line breaks among them) and no bidirectional\n * formatting characters, which could make it display as other text. The CLI refuses text that\n * breaks this rule, so Checkpoint never produces any.\n */\nexport const READABLE_TEXT = /^[^\\p{Cc}\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]*$/u;\nexport const READABLE_TEXT_MESSAGE = 'No control or bidirectional formatting characters';\n\nconst UNREADABLE = /[\\p{Cc}\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/gu;\n\n/** The same text with each character `READABLE_TEXT` refuses shown as U+FFFD. */\nexport function readableText(value: string): string {\n return value.replace(UNREADABLE, '\\uFFFD');\n}\n","import { z } from 'zod';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\n/**\n * C12: model provider keys an organization owns. An owner or admin stores the organization's own\n * key through the C3 management session; Checkpoint validates it with a free provider call,\n * encrypts it, and never returns it. An installation's model policy names the credential it\n * uses, so a model call is paid by the tenant whose key it names. There is no platform key,\n * switch or project allowlist.\n *\n * Adding and rotating are idempotent by `operationId`: the same operation with the same key\n * returns the recorded result (`duplicate: true`), and with another key it is refused\n * (`OPERATION_CONFLICT`). A client journals the operation with the key's fingerprint, never the\n * key.\n */\nconst Timestamp = z.string().datetime();\nconst Uuid = z.string().uuid();\n\n/** The providers a model credential can be for. */\nexport const ModelCredentialProviderSchema = z.literal('anthropic');\n\n/**\n * `sha256:` and the first 16 lowercase hex characters of SHA-256 over the key's UTF-8 bytes.\n * It identifies a key in receipts and listings without revealing it; a client computes the same\n * value locally with `modelCredentialFingerprint`.\n */\nexport const ModelCredentialFingerprintSchema = z.string().regex(/^sha256:[a-f0-9]{16}$/);\n\nexport function modelCredentialFingerprint(key: string): string {\n return `sha256:${bytesToHex(sha256(new TextEncoder().encode(key))).slice(0, 16)}`;\n}\n\n/** A person's name for a credential: printable ASCII, no space at either end. */\nexport const ModelCredentialLabelSchema = z\n .string()\n .min(1)\n .max(100)\n .regex(/^[\\x21-\\x7E]([\\x20-\\x7E]*[\\x21-\\x7E])?$/);\n\n/** A revocation reason is free text read back in terminals and the dashboard: readable text. */\nconst RevocationReasonSchema = z\n .string()\n .min(1)\n .max(500)\n .regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\n\n/** The secret itself, only ever in an add or rotate request body. Its shape is the provider's. */\nconst ModelApiKey = z\n .string()\n .min(20)\n .max(512)\n .regex(/^[\\x21-\\x7E]+$/);\n\n/** `kya.model-credential.v1`: metadata only. The key never appears in any response. */\nexport const ModelCredentialSchema = z\n .object({\n schema: z.literal('kya.model-credential.v1'),\n credentialId: Uuid,\n organizationId: Uuid,\n provider: ModelCredentialProviderSchema,\n label: ModelCredentialLabelSchema,\n /** The current key's fingerprint; a rotation replaces it and increments `version`. */\n fingerprint: ModelCredentialFingerprintSchema,\n version: z.number().int().positive().max(2147483647),\n status: z.enum(['active', 'revoked']),\n /** When the provider last accepted this key. */\n validatedAt: Timestamp,\n createdByUserId: Uuid,\n createdAt: Timestamp,\n rotatedAt: Timestamp.nullable(),\n /** Who made the latest rotation; set exactly when `rotatedAt` is. */\n rotatedByUserId: Uuid.nullable(),\n revokedAt: Timestamp.nullable(),\n revokedByUserId: Uuid.nullable(),\n revocationReason: RevocationReasonSchema.nullable(),\n })\n .strict()\n .refine((value) => {\n const recorded = [value.revokedAt, value.revokedByUserId, value.revocationReason].map(\n (field) => field !== null\n );\n return value.status === 'revoked' ? recorded.every(Boolean) : recorded.every((isSet) => !isSet);\n }, 'A revoked credential records when, by whom and why; an active one records none of them')\n .refine(\n (value) => (value.rotatedAt === null) === (value.rotatedByUserId === null),\n 'A rotation records when and by whom; an unrotated credential records neither'\n );\nexport type ModelCredential = z.infer<typeof ModelCredentialSchema>;\n\n/** `POST /api/cli/management/projects/{id}/model-credentials`, stored on the project's organization. */\nexport const AddModelCredentialSchema = z\n .object({\n operationId: Uuid,\n provider: ModelCredentialProviderSchema,\n label: ModelCredentialLabelSchema,\n key: ModelApiKey,\n })\n .strict();\n/** `POST …/model-credentials/{credentialId}/rotate`: a new key for the same credential. */\nexport const RotateModelCredentialSchema = z\n .object({ operationId: Uuid, key: ModelApiKey })\n .strict();\n/** `POST …/model-credentials/{credentialId}/revoke`. Revoking again returns the first revocation. */\nexport const RevokeModelCredentialSchema = z\n .object({ reason: z.string().trim().pipe(RevocationReasonSchema) })\n .strict();\nexport type AddModelCredential = z.infer<typeof AddModelCredentialSchema>;\nexport type RotateModelCredential = z.infer<typeof RotateModelCredentialSchema>;\nexport type RevokeModelCredential = z.infer<typeof RevokeModelCredentialSchema>;\n\n/** An add or rotate: the credential after it, and whether this operation had already run. */\nexport const ModelCredentialResultSchema = z\n .object({\n operationId: Uuid,\n credential: ModelCredentialSchema,\n duplicate: z.boolean(),\n })\n .strict();\nexport const ModelCredentialRevocationSchema = z\n .object({\n credential: ModelCredentialSchema,\n wasAlreadyRevoked: z.boolean(),\n })\n .strict()\n .refine(\n (value) => value.credential.status === 'revoked',\n 'A revocation returns a revoked credential'\n );\n/** `GET …/model-credentials`: the organization's credentials, newest first. */\nexport const ModelCredentialListSchema = z\n .object({\n organizationId: Uuid,\n credentials: z.array(ModelCredentialSchema).max(100),\n })\n .strict();\nexport type ModelCredentialResult = z.infer<typeof ModelCredentialResultSchema>;\nexport type ModelCredentialRevocation = z.infer<typeof ModelCredentialRevocationSchema>;\nexport type ModelCredentialList = z.infer<typeof ModelCredentialListSchema>;\n\n/**\n * Definite refusals of these routes and of a model call, all 4xx: nothing was stored, and a model\n * call refused for its credential never reached the provider.\n */\nexport const ModelCredentialRefusalCodeSchema = z.enum([\n /** The same operation was already used with another key. 409. */\n 'OPERATION_CONFLICT',\n /** No such credential in this organization. 404. */\n 'CREDENTIAL_NOT_FOUND',\n /** Rotating a revoked credential. 409. */\n 'CREDENTIAL_REVOKED',\n /** The provider refused the key. 422. */\n 'MODEL_KEY_REJECTED',\n /** The provider could not be asked; nothing was stored, try again. 424. */\n 'MODEL_KEY_UNVERIFIED',\n /** A model call's policy names a credential that is missing, revoked or another tenant's. 409. */\n 'MODEL_CREDENTIAL_UNAVAILABLE',\n]);\n","import { z } from 'zod';\n\n/** Application admission profile for the A2A 1.0 JSON-RPC binding. This is not a\n * replacement for the normative upstream proto or a complete A2A SDK schema. */\nexport const KYA_A2A_EXTENSION = 'https://kya-os.ai/a2a/task-source/v1';\nconst Id = z.string().min(1).max(255);\nconst Tenant = z.string().regex(/^[0-9a-f-]{36}:[1-9][0-9]{0,9}$/);\nexport const A2ARpcEnvelopeSchema = z\n .object({\n jsonrpc: z.literal('2.0'),\n id: z.union([Id, z.number().int().safe()]),\n method: Id,\n params: z.unknown(),\n })\n .strict();\nconst Send = z\n .object({\n tenant: Tenant,\n message: z\n .object({\n messageId: Id,\n role: z.literal('ROLE_USER'),\n parts: z\n .array(\n z\n .object({\n text: z.string().min(1).max(7000),\n mediaType: z.literal('text/plain').optional(),\n })\n .strict()\n )\n .min(1)\n .max(32),\n taskId: z.string().uuid().optional(),\n contextId: z.string().uuid().optional(),\n })\n .strict(),\n configuration: z\n .object({\n returnImmediately: z.literal(true),\n historyLength: z.number().int().min(0).max(1000).optional(),\n acceptedOutputModes: z\n .array(z.enum(['application/json', 'text/plain']))\n .min(1)\n .max(2)\n .optional(),\n })\n .strict(),\n })\n .strict();\nconst Get = z\n .object({\n tenant: Tenant,\n id: z.string().uuid(),\n historyLength: z.number().int().min(0).max(1000).optional(),\n })\n .strict();\nconst Cancel = z.object({ tenant: Tenant, id: z.string().uuid() }).strict();\nexport const A2ATaskRequestSchema = z.discriminatedUnion('method', [\n z.object({ method: z.literal('SendMessage'), params: Send }).strict(),\n z.object({ method: z.literal('GetTask'), params: Get }).strict(),\n z.object({ method: z.literal('CancelTask'), params: Cancel }).strict(),\n]);\nexport type A2ATaskRequest = z.infer<typeof A2ATaskRequestSchema>;\n\n/** Canonical standard base64 with padding: the unused bits of the last symbol are zero, so a\n * value decodes to exactly one byte string and re-encodes to itself. */\nconst StandardBase64 =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/;\nconst base64ByteLength = (value: string) =>\n (value.length / 4) * 3 - (value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0);\nconst HttpsUrl = z\n .string()\n .max(2048)\n .refine((value) => {\n try {\n return new URL(value).protocol === 'https:';\n } catch {\n return false;\n }\n }, 'targetUri must be an https URL');\n\n/**\n * B09-P3 `kya.a2a.signed-request.v1`: the exact RFC 9421 request Checkpoint verified for one A2A\n * delivery, so a receiving workbench can verify the sender's signature without trusting Checkpoint.\n * Every header member is the exact string received; `targetUri` is the exact target verified;\n * `body` is the standard base64 of the exact request body bytes (at most the 8 KiB A2A limit).\n * The kya-http/2 signature covers, joined by \"\\n\" with no trailing newline:\n * `\"@method\": POST`, `\"@authority\": <host[:port] of targetUri>`, `\"@target-uri\": <targetUri>`,\n * `\"content-digest\": <contentDigest>`, `\"content-type\": <contentType>` and\n * `\"@signature-params\": <signatureInput without its leading \"kya=\">`.\n */\nexport const A2ASignedRequestSchema = z\n .object({\n schema: z.literal('kya.a2a.signed-request.v1'),\n method: z.literal('POST'),\n targetUri: HttpsUrl,\n contentType: z.string().max(255),\n contentDigest: z.string().regex(/^sha-256=:[A-Za-z0-9+/]{43}=:$/),\n signatureInput: z.string().max(1024),\n signature: z.string().regex(/^kya=:[A-Za-z0-9+/]{86}==:$/),\n body: z\n .string()\n .max(10924)\n .regex(StandardBase64, 'body must be standard base64 with padding')\n .refine((value) => {\n const bytes = base64ByteLength(value);\n return bytes >= 1 && bytes <= 8192;\n }, 'body must decode to 1..8192 bytes'),\n })\n .strict();\nexport type A2ASignedRequest = z.infer<typeof A2ASignedRequestSchema>;\n\nexport const A2ATaskStateSchema = z.enum([\n 'TASK_STATE_UNSPECIFIED',\n 'TASK_STATE_SUBMITTED',\n 'TASK_STATE_WORKING',\n 'TASK_STATE_COMPLETED',\n 'TASK_STATE_FAILED',\n 'TASK_STATE_CANCELED',\n 'TASK_STATE_INPUT_REQUIRED',\n 'TASK_STATE_REJECTED',\n]);\nexport type A2ATaskState = z.infer<typeof A2ATaskStateSchema>;\nexport interface A2ATaskProjection {\n id: string;\n contextId: string;\n status: { state: A2ATaskState };\n metadata: {\n kyaTaskSource: {\n operationId: string;\n sourceRevision: number;\n ownerEpoch: number;\n deliveryState: string;\n cancellationRequested: boolean;\n authorization: 'requires_task_approval';\n completionBasis: 'none' | 'recorded_host_receipt';\n resultDigest?: string;\n evidenceRefs?: string[];\n executionState?: string;\n };\n };\n}\n\n/** Out-of-band discovery profile returned to the installation administrator.\n * RFC 9421 holder signatures require the extension; they are not bearer auth. */\nexport function createKyaA2AAgentCard(endpoint: string, tenant: string) {\n const url = new URL(endpoint);\n if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)\n throw new Error('A2A endpoint must be an exact HTTPS target');\n Tenant.parse(tenant);\n return {\n name: 'KYA accountable task intake',\n description:\n 'Queue bounded work, send steering and request cancellation. Execution requires separately admitted authority. This text-only asynchronous profile requires the KYA extension.',\n version: '1.0.0',\n supportedInterfaces: [\n { url: endpoint, protocolBinding: 'JSONRPC', protocolVersion: '1.0', tenant },\n ],\n capabilities: {\n streaming: false,\n pushNotifications: false,\n extendedAgentCard: false,\n extensions: [\n {\n uri: KYA_A2A_EXTENSION,\n required: true,\n description:\n 'KYA HTTP/2 Ed25519 holder proof over the exact JSON body and target; registered actors only. Source text never grants authority.',\n params: {\n methods: ['SendMessage', 'GetTask', 'CancelTask'],\n maxRequestBytes: 8192,\n returnImmediatelyRequired: true,\n historyReturned: false,\n authentication: {\n profile: 'kya-http/2',\n headers: ['Signature-Input', 'Signature', 'Content-Digest', 'Content-Type'],\n bearerSupported: false,\n },\n retry:\n 'Reuse the same messageId and unchanged parameters with a fresh HTTP proof after an uncertain acknowledgement.',\n },\n },\n ],\n },\n defaultInputModes: ['text/plain'],\n defaultOutputModes: ['application/json'],\n skills: [\n {\n id: 'accountable-work',\n name: 'Accountable work',\n description:\n 'Submit and inspect durable tasks; completion identifies a recorded host receipt, with separate artifact and acceptance verification.',\n tags: ['tasks', 'governance', 'evidence'],\n },\n ],\n };\n}\n","import { z } from 'zod';\n\nexport const TaskProjectionStateSchema = z.enum([\n 'queued',\n 'delivered',\n 'approved',\n 'running',\n 'unknown',\n 'awaiting_acceptance',\n 'accepted',\n 'published',\n]);\nexport const TaskProjectionEvidenceSchema = z\n .object({\n record: z.enum([\n 'source_intent',\n 'delivery_attempt',\n 'publication_binding',\n 'admission',\n 'action',\n 'result_receipt',\n 'activity',\n ]),\n id: z.string().min(1).max(255),\n state: z.string().min(1).max(64),\n // Null means the legacy record has no trustworthy transition timestamp.\n observedAt: z.string().datetime().nullable(),\n basis: z.enum([\n 'checkpoint_commit',\n 'host_receipt',\n 'lead_acknowledgment',\n 'provider_ack',\n 'provider_lookup',\n ]),\n })\n .strict();\n/** Metadata projection. Accepted means receipt acceptance, not human quality approval. */\nexport const TaskStatusProjectionSchema = z\n .object({\n schema: z.literal('kya.task.status-projection.v1'),\n taskId: z.string().uuid(),\n installationId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n provider: z.enum(['linear', 'github', 'discord', 'didcomm', 'a2a']),\n sessionId: z.string().min(1).max(255),\n sourceRevision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n ownerEpoch: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n state: TaskProjectionStateSchema,\n since: z.string().datetime().nullable(),\n cancellationRequested: z.boolean(),\n uncertain: z.array(TaskProjectionEvidenceSchema).max(64),\n evidence: z.array(TaskProjectionEvidenceSchema).min(1).max(64),\n projectedAt: z.string().datetime(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if ((value.state === 'unknown') !== value.uncertain.length > 0)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Uncertainty must take precedence' });\n if (value.since !== null && Date.parse(value.since) > Date.parse(value.projectedAt))\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Transition cannot follow observation',\n });\n if (![...value.evidence, ...value.uncertain].some((e) => e.observedAt === value.since))\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Transition needs record provenance' });\n for (const item of value.uncertain) {\n if (\n !value.evidence.some(\n (e) =>\n e.record === item.record &&\n e.id === item.id &&\n e.state === item.state &&\n e.observedAt === item.observedAt &&\n e.basis === item.basis\n )\n )\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Uncertainty must identify projection evidence',\n });\n }\n for (const items of [value.evidence, value.uncertain]) {\n if (new Set(items.map((e) => JSON.stringify([e.record, e.id]))).size !== items.length)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate record evidence' });\n }\n });\nexport type TaskProjectionState = z.infer<typeof TaskProjectionStateSchema>;\nexport type TaskProjectionEvidence = z.infer<typeof TaskProjectionEvidenceSchema>;\nexport type TaskStatusProjection = z.infer<typeof TaskStatusProjectionSchema>;\n\n/** A tenant-scoped page of projections, most recently created task first. */\nexport const TaskStatusProjectionListSchema = z\n .object({\n tasks: z.array(TaskStatusProjectionSchema).max(100),\n projectedAt: z.string().datetime(),\n })\n .strict();\n\n/** The conditions the activity drain needs to send; each names the reason it can fail. */\nexport const LinearActivityGateSchema = z.enum([\n 'installation_disabled',\n 'installation_disconnected',\n 'owner_epoch_changed',\n 'destination_changed',\n 'publication_binding_invalid',\n 'publication_binding_expired',\n 'approver_not_admin',\n 'github_custody_lost',\n]);\nexport const LinearActivityObservationSummarySchema = z\n .object({\n method: z.enum(['send', 'provider_lookup']),\n result: z.enum(['delivered', 'rejected', 'uncertain', 'absent', 'mismatch', 'unavailable']),\n observedAt: z.string().datetime(),\n httpStatus: z.number().int().min(100).max(599).nullable(),\n })\n .strict();\n/**\n * An outbox entry the drain will not send as things stand: a failing gate, or an unproven\n * delivery that only a provider lookup can resolve. Metadata only, never activity content.\n */\nexport const LinearObsoleteActivitySchema = z\n .object({\n schema: z.literal('kya.linear.obsolete-activity.v1'),\n activityId: z.string().uuid(),\n installationId: z.string().uuid(),\n operationId: z.string().uuid(),\n sessionId: z.string().min(1).max(255),\n kind: z.enum(['result', 'progress']),\n deliveryState: z.enum(['pending', 'claimed', 'unknown']),\n attemptCount: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),\n createdAt: z.string().datetime(),\n stateChangedAt: z.string().datetime().nullable(),\n reasons: z\n .array(z.union([LinearActivityGateSchema, z.literal('delivery_unproven')]))\n .min(1)\n .max(9),\n lastObservation: LinearActivityObservationSummarySchema.nullable(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (new Set(value.reasons).size !== value.reasons.length)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate reason' });\n // Only an unproven delivery is uncertain; a pending entry that never left is not.\n if (value.reasons.includes('delivery_unproven') === (value.deliveryState === 'pending'))\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unproven means unknown delivery' });\n });\nexport const LinearObsoleteActivityListSchema = z\n .object({\n activities: z.array(LinearObsoleteActivitySchema).max(200),\n projectedAt: z.string().datetime(),\n })\n .strict();\nexport type TaskStatusProjectionList = z.infer<typeof TaskStatusProjectionListSchema>;\nexport type LinearActivityGate = z.infer<typeof LinearActivityGateSchema>;\nexport type LinearObsoleteActivity = z.infer<typeof LinearObsoleteActivitySchema>;\nexport type LinearObsoleteActivityList = z.infer<typeof LinearObsoleteActivityListSchema>;\n","import { z } from 'zod';\nimport { ModelCredentialFingerprintSchema } from './model-credentials';\nimport { A2ASignedRequestSchema } from './task-a2a';\n\nconst BoundedId = z.string().min(1).max(255);\n// Receipts carry the same bounded identities and token shape as their requests.\nconst DestinationDid = z.string().startsWith('did:').max(512);\nconst KeyDid = z.string().startsWith('did:key:').max(512);\nconst ClaimToken = z\n .string()\n .length(64)\n .regex(/^[a-f0-9]{64}$/);\n// The publication service mints this branch from the immutable task binding digest.\nconst PublicationBranch = z\n .string()\n .length(35)\n .regex(/^kya\\/linear-[a-f0-9]{24}$/);\nconst Repository = z\n .string()\n .max(255)\n .regex(/^[a-zA-Z0-9_.-]+\\/[a-zA-Z0-9_.-]+$/);\nexport const TaskSourceProviderSchema = z.enum(['linear', 'github', 'discord', 'didcomm', 'a2a']);\nexport const TaskStandingCapabilitySchema = z.enum([\n 'task.execute',\n 'model.invoke',\n 'github.branch.write',\n 'github.pull_request.draft',\n]);\nconst TaskModelIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/);\n/** Fixed allocation per call, not a provider price estimate or a guaranteed billing ceiling. */\nexport const TaskModelPolicySchema = z\n .object({\n provider: z.literal('anthropic'),\n /** The organization's own model credential that pays for these calls (`model-credentials`). */\n credentialId: z.string().uuid(),\n models: z\n .array(TaskModelIdSchema)\n .min(1)\n .max(20)\n .refine((values) => new Set(values).size === values.length, 'Duplicate models'),\n maxOutputTokens: z.number().int().min(1).max(64000),\n maxRequestBytes: z.number().int().min(1).max(262144),\n reservedCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n })\n .strict();\nexport type TaskModelPolicy = z.infer<typeof TaskModelPolicySchema>;\n/** Initial text-only Messages profile. No caller endpoints, keys, hosted tools or streaming. */\nexport const TaskModelMessagesSchema = z\n .object({\n model: TaskModelIdSchema,\n max_tokens: z.number().int().min(1).max(64000),\n messages: z\n .array(\n z\n .object({ role: z.enum(['user', 'assistant']), content: z.string().min(1).max(262144) })\n .strict()\n )\n .min(1)\n .max(1000),\n system: z.string().max(262144).optional(),\n temperature: z.number().min(0).max(1).optional(),\n stream: z.literal(false).optional(),\n })\n .strict();\nexport type TaskModelMessages = z.infer<typeof TaskModelMessagesSchema>;\nexport const TaskModelStatusSchema = z\n .object({\n admissionId: z.string().uuid(),\n operationId: z.string().uuid(),\n ownerEpoch: z.number().int().positive(),\n })\n .strict();\nexport const TaskModelInvokeSchema = TaskModelStatusSchema.extend({\n request: TaskModelMessagesSchema,\n}).strict();\nexport type TaskModelInvoke = z.infer<typeof TaskModelInvokeSchema>;\nexport type TaskModelStatus = z.infer<typeof TaskModelStatusSchema>;\nconst ModelTokenCount = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();\nexport const TaskModelUsageSchema = z\n .object({\n newInputTokens: ModelTokenCount,\n cacheReadInputTokens: ModelTokenCount,\n cacheWriteInputTokens: ModelTokenCount,\n cacheWrite5mInputTokens: ModelTokenCount,\n cacheWrite1hInputTokens: ModelTokenCount,\n totalInputTokens: ModelTokenCount,\n outputTokens: ModelTokenCount,\n coverage: z.enum(['complete', 'partial', 'unknown']),\n })\n .strict();\nexport const TaskModelReceiptSchema = z\n .object({\n schema: z.literal('kya.task.model-receipt.v1'),\n admissionId: z.string().uuid(),\n admissionDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n operationId: z.string().uuid(),\n requestDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n provider: z.literal('anthropic'),\n model: TaskModelIdSchema,\n /** The admitted policy's credential, and the fingerprint of its key at call time. */\n credentialId: z.string().uuid(),\n credentialFingerprint: ModelCredentialFingerprintSchema,\n reservedCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n usage: TaskModelUsageSchema.nullable(),\n outputDigest: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/)\n .optional(),\n // MODEL_REFUSED: the request provably did not run (never sent, or a definite provider\n // refusal). Its allocation stays spent, but it does not make the admission uncertain.\n code: z.enum(['MODEL_STARTED', 'MODEL_COMPLETED', 'MODEL_REFUSED', 'MODEL_OUTCOME_UNKNOWN']),\n durationMs: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),\n requestStartedAtMs: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),\n costBasis: z.literal('unknown'),\n billingVerified: z.literal(false),\n })\n .strict();\nexport type TaskModelReceipt = z.infer<typeof TaskModelReceiptSchema>;\n// Rust refuses a repeated capability too (task_control.rs `capabilities`).\nconst StandingCapabilities = z\n .array(TaskStandingCapabilitySchema)\n .min(1)\n .max(4)\n .refine((values) => new Set(values).size === values.length, 'Duplicate capability');\nexport const TaskStandingPolicySchema = z\n .object({\n maxConcurrentOperations: z.number().int().min(1).max(100),\n maxAttemptsPerTask: z.number().int().min(1).max(10),\n workers: z\n .array(\n z\n .object({\n did: KeyDid,\n capabilities: StandingCapabilities,\n })\n .strict()\n )\n .min(1)\n .max(100),\n })\n .strict();\n/**\n * An owner-approved set of leads for pooled routing. One eligible lead is selected per task, at\n * the lead's own claim, and persisted before delivery; `maxConcurrentTasks` bounds how many\n * unfinished tasks a lead may hold. Leads receive tasks; workers remain `standingApproval`.\n */\nexport const TaskLeadPoolSchema = z\n .object({\n leads: z\n .array(\n z\n .object({\n did: KeyDid,\n maxConcurrentTasks: z.number().int().min(1).max(100),\n })\n .strict()\n )\n .min(2)\n .max(32),\n })\n .strict()\n .refine(\n (pool) => new Set(pool.leads.map((lead) => lead.did)).size === pool.leads.length,\n 'Each pool lead appears once'\n );\nexport type TaskLeadPool = z.infer<typeof TaskLeadPoolSchema>;\n\nexport const LinearInstallationWorkflowSchema = z\n .object({\n destinationDid: DestinationDid,\n ownerEpoch: z.number().int().positive().max(2147483647),\n allowedActorIds: z.array(BoundedId).min(1).max(100),\n allowedRepositories: z.array(Repository).min(1).max(50),\n maxRuntimeSeconds: z.number().int().positive().max(86400),\n maxOperations: z.number().int().positive().max(10000),\n maxCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n allowDraftPullRequest: z.boolean().default(false),\n executionMode: z.enum(['review_required', 'work_to_draft_pr']).default('review_required'),\n standingApproval: TaskStandingPolicySchema.optional(),\n modelPolicy: TaskModelPolicySchema.optional(),\n // Absent means direct routing to destinationDid, which then never falls back to anyone else.\n leadPool: TaskLeadPoolSchema.optional(),\n })\n .strict()\n .refine(\n (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 60000,\n 'Workflow exceeds delivery envelope bound'\n )\n // The addressable destination (DIDComm and A2A recipient) must itself be a qualified lead.\n .refine(\n (value) =>\n !value.leadPool || value.leadPool.leads.some((lead) => lead.did === value.destinationDid),\n 'A pooled destination must be one of its leads'\n );\nexport type LinearInstallationWorkflow = z.infer<typeof LinearInstallationWorkflowSchema>;\n\n/**\n * Whether the policy lets `did` lead this installation's tasks: the pool's leads, or the direct\n * destination. Checkpoint also requires a pooled lead to hold a live C10 workload enrollment.\n */\nexport function isAuthorizedLead(\n workflow: Pick<LinearInstallationWorkflow, 'destinationDid' | 'leadPool'>,\n did: string\n): boolean {\n return workflow.leadPool\n ? workflow.leadPool.leads.some((lead) => lead.did === did)\n : workflow.destinationDid === did;\n}\n\n/**\n * An owner/admin reassignment of one pooled task. `expectedLeadEpoch` fences a concurrent\n * reassignment; a null `leadDid` returns the task to the pool for the next eligible claim.\n */\nexport const ReassignTaskLeadSchema = z\n .object({\n expectedLeadEpoch: z.number().int().nonnegative().max(2147483647),\n leadDid: KeyDid.nullable(),\n })\n .strict();\nexport const TaskLeadAssignmentSchema = z\n .object({\n installationId: z.string().uuid(),\n taskId: z.string().uuid(),\n leadDid: KeyDid.nullable(),\n leadEpoch: z.number().int().positive().max(2147483647),\n })\n .strict();\nexport type ReassignTaskLead = z.infer<typeof ReassignTaskLeadSchema>;\nexport type TaskLeadAssignment = z.infer<typeof TaskLeadAssignmentSchema>;\n\nexport const ConfigureLinearInstallationSchema = z\n .object({\n projectId: z.string().uuid(),\n workspaceId: BoundedId,\n oauthClientId: BoundedId,\n appUserId: BoundedId,\n webhookId: BoundedId,\n webhookSecret: z.string().min(16).max(4096),\n accessToken: z.string().min(1).max(8192),\n enabled: z.boolean().default(true),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict();\n\nexport const GitHubTaskSourceConfigSchema = z\n .object({\n provider: z.literal('github'),\n githubInstallationId: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n repository: Repository.transform((value) => value.toLowerCase()),\n agentUserId: z.string().regex(/^[1-9][0-9]{0,19}$/),\n webhookSecret: z.string().min(16).max(4096),\n })\n .strict();\nexport const DiscordTaskSourceConfigSchema = z\n .object({\n provider: z.literal('discord'),\n applicationId: z.string().regex(/^[1-9][0-9]{16,19}$/),\n publicKeyHex: z.string().regex(/^[a-fA-F0-9]{64}$/),\n guildId: z.string().regex(/^[1-9][0-9]{16,19}$/),\n channelIds: z\n .array(z.string().regex(/^[1-9][0-9]{16,19}$/))\n .min(1)\n .max(100),\n commandName: z.string().regex(/^[a-z0-9_-]{1,32}$/),\n })\n .strict();\nexport const DidCommTaskSourceConfigSchema = z\n .object({\n provider: z.literal('didcomm'),\n recipientDid: z.string().startsWith('did:key:').max(255),\n })\n .strict();\nexport const A2ATaskSourceConfigSchema = z\n .object({ provider: z.literal('a2a'), recipientDid: z.string().startsWith('did:key:').max(255) })\n .strict();\nexport const DidCommTaskSourceBindingSchema = z\n .object({\n schema: z.literal('kya.task.source-binding.v1'),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n installationId: z.string().uuid(),\n ownerEpoch: z.number().int().positive().max(2147483647),\n })\n .strict();\n/** A native message's context is strict: its source binding and, optionally, the repository. */\nconst DidCommSourceContext = z\n .object({\n kyaTaskSource: DidCommTaskSourceBindingSchema,\n repo: Repository.optional(),\n })\n .strict();\nconst DidCommSourceEnvelope = z.object({\n id: z.string().uuid(),\n from: z.string().startsWith('did:key:').max(255),\n to: z.array(z.string().startsWith('did:key:').max(255)).length(1),\n created_time: z.number().int().positive(),\n expires_time: z.number().int().positive(),\n thid: BoundedId,\n pthid: BoundedId.optional(),\n});\nconst DidCommTaskBody = { taskId: BoundedId, context: DidCommSourceContext };\nexport const DidCommTaskSourceMessageSchema = z.discriminatedUnion('type', [\n DidCommSourceEnvelope.extend({\n type: z.literal('https://kya-os.ai/didcomm/task/assign'),\n body: z\n .object({\n ...DidCommTaskBody,\n description: z.string().min(1).max(190000),\n priority: z.enum(['low', 'normal', 'urgent']).optional(),\n relayTimeoutMs: z.number().int().positive().max(86400000).optional(),\n })\n .strict(),\n }).strict(),\n DidCommSourceEnvelope.extend({\n type: z.literal('https://kya-os.ai/didcomm/task/steer'),\n body: z\n .object({\n ...DidCommTaskBody,\n instruction: z.string().min(1).max(190000),\n priority: z.enum(['low', 'normal', 'urgent']).optional(),\n })\n .strict(),\n }).strict(),\n DidCommSourceEnvelope.extend({\n type: z.literal('https://kya-os.ai/didcomm/task/cancel'),\n body: z.object(DidCommTaskBody).strict(),\n }).strict(),\n]);\nexport const TaskSourceProviderConfigSchema = z.discriminatedUnion('provider', [\n GitHubTaskSourceConfigSchema,\n DiscordTaskSourceConfigSchema,\n DidCommTaskSourceConfigSchema,\n A2ATaskSourceConfigSchema,\n]);\nexport const ConfigureTaskSourceInstallationSchema = z\n .object({\n projectId: z.string().uuid(),\n source: TaskSourceProviderConfigSchema,\n /** Setup only: encrypted server custody, never included in source or workload responses. */\n discordBotToken: z.string().min(1).max(8192).optional(),\n enabled: z.boolean().default(true),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict();\n\n/** Authenticated source material, never an executable authorization. */\nexport const TaskSourceIntentSchema = z\n .object({\n schema: z.literal('kya.task.source-intent.v1'),\n taskId: z.string().uuid(),\n operationId: z.string().uuid(),\n installationId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n sessionId: BoundedId,\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n destinationDid: DestinationDid,\n kind: z.enum(['created', 'prompted', 'stop']),\n source: z\n .object({\n provider: TaskSourceProviderSchema,\n workspaceId: BoundedId,\n actorId: BoundedId,\n issueId: BoundedId.optional(),\n })\n .strict(),\n untrustedInput: z\n .string()\n .max(200000)\n .refine(\n (value) =>\n new TextEncoder().encode(value).byteLength <= 200000 &&\n new TextEncoder().encode(JSON.stringify(value)).byteLength <= 400000,\n 'Source input exceeds the UTF-8 or encoded response bound'\n ),\n inputDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n workflow: LinearInstallationWorkflowSchema,\n authorization: z.literal('requires_task_approval'),\n /** B09-P3: the exact signed A2A request Checkpoint verified for this delivery. Only an A2A\n * source carries it; an A2A revision recorded before retention began has none. */\n delivery: A2ASignedRequestSchema.optional(),\n })\n .strict()\n .refine((intent) => intent.delivery === undefined || intent.source.provider === 'a2a', {\n message: 'Only an A2A source carries its signed request',\n path: ['delivery'],\n });\nexport type TaskSourceIntent = z.infer<typeof TaskSourceIntentSchema>;\n\n/** Scope is derived from authenticated workload authority, never request-body tenancy. */\nexport const TaskMailboxScopeSchema = z\n .object({\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n destinationDid: DestinationDid,\n ownerEpoch: z.number().int().positive(),\n })\n .strict();\nexport type TaskMailboxScope = z.infer<typeof TaskMailboxScopeSchema>;\nexport const TaskMailboxClaimRequestSchema = z\n .object({\n ownerEpoch: z.number().int().positive().max(2147483647),\n acceptedProviders: z.array(TaskSourceProviderSchema).min(1).max(5).default(['linear']),\n claimId: z.string().uuid().optional(),\n claimToken: ClaimToken.optional(),\n })\n .strict()\n .refine(\n (value) => Boolean(value.claimId) === Boolean(value.claimToken),\n 'claimId and claimToken must be supplied together'\n );\nexport const TaskMailboxStatusRequestSchema = z\n .object({\n ownerEpoch: z.number().int().positive().max(2147483647),\n claimId: z.string().uuid(),\n })\n .strict();\nexport const TaskMailboxClaimSchema = z\n .object({\n claimId: z.string().uuid(),\n claimToken: ClaimToken,\n claimExpiresAt: z.string().datetime(),\n deliveryState: z.enum(['claimed', 'accepted', 'unknown', 'cancelled']),\n intent: TaskSourceIntentSchema,\n })\n .strict();\nexport type TaskMailboxClaim = z.infer<typeof TaskMailboxClaimSchema>;\nexport const TaskMailboxStatusSchema = z\n .object({\n claimId: z.string().uuid(),\n operationId: z.string().uuid(),\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n deliveryState: z.enum(['pending', 'claimed', 'accepted', 'unknown', 'cancelled']),\n outcome: z.enum(['claimed', 'accepted', 'not_delivered', 'unknown']),\n claimExpiresAt: z.string().datetime(),\n })\n .strict();\nexport type TaskMailboxStatus = z.infer<typeof TaskMailboxStatusSchema>;\nexport const TaskMailboxSettlementSchema = z\n .object({\n claimId: z.string().uuid(),\n operationId: z.string().uuid(),\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n claimToken: ClaimToken,\n outcome: z.enum(['accepted', 'not_delivered', 'unknown']),\n })\n .strict();\nexport type TaskMailboxSettlement = z.infer<typeof TaskMailboxSettlementSchema>;\n\nconst Sha256Digest = z.string().regex(/^sha256:[a-f0-9]{64}$/);\nconst PublicationBindingFields = {\n sourceOperationId: z.string().uuid(),\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n ownerEpoch: z.number().int().positive(),\n specRevision: z.number().int().positive(),\n manifestDigest: Sha256Digest,\n executionOperationId: z.string().min(1).max(255),\n};\nexport const ApproveTaskPublicationSchema = z\n .object({\n ...PublicationBindingFields,\n reporterDid: KeyDid,\n repository: Repository,\n baseSha: z.string().regex(/^[a-f0-9]{40}$/),\n expiresAt: z.string().datetime(),\n publishDraftPullRequest: z.boolean().default(false),\n })\n .strict();\nexport const FleetPullRequestReceiptSchema = z\n .object({\n schema: z.literal('kya.fleet.pull-request.v1'),\n taskId: z.string().uuid(),\n number: z.number().int().positive(),\n headSha: z.string().regex(/^[a-f0-9]{40}$/),\n })\n .strict();\nexport const TaskMailboxResultSchema = z\n .object({\n ...PublicationBindingFields,\n outcome: z.enum(['completed', 'failed', 'cancelled']),\n artifact: FleetPullRequestReceiptSchema.optional(),\n })\n .strict();\nexport type TaskMailboxResult = z.infer<typeof TaskMailboxResultSchema>;\nexport const ApprovedTaskPublicationSchema = ApproveTaskPublicationSchema.extend({\n schema: z.literal('kya.task.publication-binding.v1'),\n branch: PublicationBranch,\n approvedByUserId: z.string().uuid(),\n approvedAt: z.string().datetime(),\n githubInstallationId: z.number().int().positive().optional(),\n}).strict();\nexport type ApprovedTaskPublication = z.infer<typeof ApprovedTaskPublicationSchema>;\n\nexport const TaskStandingLimitsSchema = z\n .object({\n maxRuntimeSeconds: z.number().int().min(1).max(86400),\n maxCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n maxOperations: z.number().int().min(1).max(10000),\n })\n .strict();\nexport const TaskStandingAdmissionRequestBaseSchema = z\n .object({\n ...PublicationBindingFields,\n workerDid: KeyDid,\n repository: Repository,\n baseSha: z.string().regex(/^[a-f0-9]{40}$/),\n attemptNumber: z.number().int().min(1).max(10),\n capabilities: StandingCapabilities,\n limits: TaskStandingLimitsSchema,\n modelPolicy: TaskModelPolicySchema.optional(),\n })\n .strict();\nexport const validModelAdmission = (value: {\n capabilities: string[];\n modelPolicy?: TaskModelPolicy;\n limits: { maxCostMicrousd: number };\n}) =>\n value.capabilities.includes('model.invoke') === Boolean(value.modelPolicy) &&\n (!value.modelPolicy || value.modelPolicy.reservedCostMicrousd <= value.limits.maxCostMicrousd);\nexport const TaskStandingAdmissionRequestSchema = TaskStandingAdmissionRequestBaseSchema.refine(\n validModelAdmission,\n 'Model capability requires a bounded policy'\n);\nexport type TaskStandingAdmissionRequest = z.infer<typeof TaskStandingAdmissionRequestSchema>;\n/** The v1 receipt before its model refinement, so a later protocol can extend it. */\nexport const TaskStandingAdmissionReceiptBaseSchema = TaskStandingAdmissionRequestBaseSchema.omit({\n workerDid: true,\n})\n .extend({\n schema: z.literal('kya.task.admission.v1'),\n admissionId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n installationId: z.string().uuid(),\n leadDid: DestinationDid,\n holderDid: KeyDid,\n branch: PublicationBranch,\n notBefore: z.string().datetime(),\n expiresAt: z.string().datetime(),\n policyProvenance: z.literal('administrator_registered'),\n requiresOnlineActionGate: z.literal(true),\n credentialExport: z.literal(false),\n })\n .strict();\nexport const TaskStandingAdmissionSchema = TaskStandingAdmissionReceiptBaseSchema.refine(\n validModelAdmission,\n 'Model capability requires a bounded policy'\n);\nexport type TaskStandingAdmission = z.infer<typeof TaskStandingAdmissionSchema>;\nexport const TaskStandingActionSchema = z\n .object({\n admissionId: z.string().uuid(),\n operationId: z.string().uuid(),\n ownerEpoch: z.number().int().positive(),\n action: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('task.start') }).strict(),\n z\n .object({\n kind: z.literal('model.invoke'),\n provider: z.literal('anthropic'),\n model: TaskModelIdSchema,\n requestDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n maxOutputTokens: z.number().int().min(1).max(64000),\n })\n .strict(),\n z\n .object({\n kind: z.literal('task.finish'),\n outcome: z.enum(['completed', 'failed', 'cancelled', 'unknown']),\n })\n .strict(),\n z\n .object({\n kind: z.literal('github.commit'),\n expectedHeadSha: z.string().regex(/^[a-f0-9]{40}$/),\n message: z.string().min(1).max(2000),\n files: z\n .array(\n z\n .object({\n path: z.string().min(1).max(1000),\n content: z.string().max(200000).nullable(),\n })\n .strict()\n )\n .min(1)\n .max(100),\n })\n .strict(),\n z\n .object({\n kind: z.literal('github.pull_request.draft'),\n headSha: z.string().regex(/^[a-f0-9]{40}$/),\n })\n .strict(),\n ]),\n })\n .strict();\nexport type TaskStandingAction = z.infer<typeof TaskStandingActionSchema>;\nexport const TaskStandingReconcileSchema = TaskStandingActionSchema.extend({\n originalOwnerEpoch: z.number().int().positive(),\n}).strict();\nexport type TaskStandingReconcile = z.infer<typeof TaskStandingReconcileSchema>;\n\nexport * from './task-status-projection';\n","import { z } from 'zod';\n\n// A read projection of existing identity/deployment records. This contract does\n// not confer authority and never treats stored deployment status as a live probe.\nconst Text = z\n .string()\n .min(1)\n .max(500)\n .refine((s) =>\n [...s].every((character) => {\n const code = character.charCodeAt(0);\n return code >= 32 && code !== 127;\n })\n );\nconst PublicUrl = z\n .string()\n .url()\n .refine((value) => {\n const url = new URL(value);\n return (\n ['http:', 'https:'].includes(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.search &&\n !url.hash\n );\n });\nexport const CliIdentityQuerySchema = z.object({ projectId: z.string().min(1).max(255) }).strict();\nexport const CliIdentityServiceSchema = z\n .object({\n id: Text,\n kind: z.enum(['registry', 'authorization_host', 'mcp']),\n url: PublicUrl.nullable(),\n status: z.enum(['configured', 'active_recorded', 'inactive_recorded', 'not_configured']),\n observed_at: z.string().datetime().nullable(),\n })\n .strict();\nexport const CliIdentitySummarySchema = z\n .object({\n version: z.literal(1),\n observed_at: z.string().datetime(),\n project: z.object({ id: Text, name: Text }).strict(),\n organization: z\n .object({\n id: Text,\n name: Text,\n slug: Text,\n did_web: Text.refine((value) => value.startsWith('did:web:')).nullable(),\n did_webvh: Text.refine((value) => value.startsWith('did:webvh:')).nullable(),\n registry_state: z.enum(['registered', 'not_registered']),\n })\n .strict()\n .nullable(),\n services: z\n .array(CliIdentityServiceSchema)\n .max(102)\n .refine(\n (services) => new Set(services.map((service) => service.id)).size === services.length\n ),\n })\n .strict()\n .refine(\n (summary) =>\n !summary.organization ||\n (summary.organization.registry_state === 'registered') ===\n Boolean(summary.organization.did_webvh),\n 'Registration state must match the stored registry DID'\n );\nexport type CliIdentitySummary = z.infer<typeof CliIdentitySummarySchema>;\nexport type CliIdentityService = z.infer<typeof CliIdentityServiceSchema>;\n","import { z } from 'zod';\nimport { isPublicSuffixLike } from '../posture-origins';\n\n/**\n * A pixel's `configuration.allowedDomains`: the page hosts a pixel accepts\n * events from (`/api/v1/event` compares them to the event URL's hostname).\n *\n * Stored form is a bare, lowercase, punycoded host (`shop.example.com`) or a\n * leftmost wildcard (`*.example.com`, which covers `example.com` itself and\n * every subdomain, never a look-alike such as `evilexample.com`).\n *\n * The comparison side, `URL.hostname`, is always lowercase with no scheme,\n * port or path, so an entry stored as `*.Example.com`, `https://example.com`\n * or `example.com:443` never matched and 403'd every event. Entries are now\n * normalized on write, and legacy rows are normalized again on read so they\n * stop failing without a backfill.\n */\n\nconst WILDCARD_PROBE_LABEL = 'allowed-domain-wildcard-probe';\nexport const MAX_ALLOWED_DOMAIN_LENGTH = 300;\n/**\n * Most entries one pixel may list. Generous on purpose: each event checks\n * its host against every entry, and the list was uncapped before, so a\n * smaller cap could refuse an existing pixel's next save.\n */\nexport const MAX_ALLOWED_DOMAINS = 1000;\n/** One DNS label after URL's lowercasing and punycoding. `_` occurs in real subdomains. */\nconst HOST_LABEL = /^[a-z0-9_-]{1,63}$/;\nconst DEFAULT_PORTS = new Set(['80', '443']);\n\ninterface ParsedAllowedDomain {\n host: string;\n wildcard: boolean;\n /** A non-default port the entry carried, or ''. */\n port: string;\n}\n\n/** URL accepts empty labels and characters such as `;` or `,`, which no page host has. */\nfunction isHostName(host: string): boolean {\n // URL has already validated a bracketed IPv6 literal.\n if (host.startsWith('[') && host.endsWith(']')) return true;\n return host.split('.').every((label) => HOST_LABEL.test(label));\n}\n\nfunction parseAllowedDomain(entry: string): ParsedAllowedDomain | { error: string } {\n const trimmed = typeof entry === 'string' ? entry.trim() : '';\n if (!trimmed) return { error: 'Enter a domain such as shop.example.com' };\n if (trimmed.length > MAX_ALLOWED_DOMAIN_LENGTH) {\n return { error: `Must be at most ${MAX_ALLOWED_DOMAIN_LENGTH} characters` };\n }\n const schemeMatch = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(trimmed);\n const scheme = schemeMatch ? schemeMatch[1].toLowerCase() : 'https';\n if (scheme !== 'https' && scheme !== 'http') {\n return { error: 'Use a domain name, e.g. shop.example.com' };\n }\n const rest = schemeMatch ? trimmed.slice(schemeMatch[0].length) : trimmed;\n const wildcard = rest.startsWith('*.');\n const withoutWildcard = wildcard ? rest.slice(2) : rest;\n if (!withoutWildcard || withoutWildcard.includes('*')) {\n return { error: 'A wildcard is only allowed as the first label, e.g. *.example.com' };\n }\n let url: URL;\n try {\n // Parsed with the entry's own scheme so its default port (80 or 443)\n // drops out, and with a probe label standing in for `*` so URL still\n // lowercases and punycodes the rest of the host.\n url = new URL(`${scheme}://${wildcard ? `${WILDCARD_PROBE_LABEL}.` : ''}${withoutWildcard}`);\n } catch {\n return { error: 'Not a valid domain' };\n }\n if (url.username || url.password) return { error: 'Domains cannot contain a username' };\n let host = url.hostname.replace(/\\.$/, '');\n if (wildcard) {\n if (!host.startsWith(`${WILDCARD_PROBE_LABEL}.`)) return { error: 'Not a valid domain' };\n host = host.slice(WILDCARD_PROBE_LABEL.length + 1);\n }\n if (!isHostName(host)) return { error: 'Not a valid domain' };\n // 80 and 443 count as default whatever the scheme: an entry with no scheme\n // is parsed as https, where URL would keep `:80`.\n return { host, wildcard, port: DEFAULT_PORTS.has(url.port) ? '' : url.port };\n}\n\nfunction format(parsed: ParsedAllowedDomain): string {\n return `${parsed.wildcard ? '*.' : ''}${parsed.host}`;\n}\n\n/**\n * `*.com`, `*.co.uk`, `*.myshopify.com`: a wildcard that admits sites the\n * customer does not control. Same rule as posture origins, so the two\n * allowlists refuse the same entries.\n */\nfunction isPublicSuffixWildcard(parsed: ParsedAllowedDomain): boolean {\n return parsed.wildcard && isPublicSuffixLike(parsed.host);\n}\n\n/**\n * Strict write-time normalization. Returns the stored form, or an error for\n * junk: another scheme, userinfo, a misplaced wildcard, a host with an empty\n * label or a character no host has, a non-default port (the check compares\n * host names only, so a port would suggest a restriction that is never\n * enforced), or a wildcard over a public suffix.\n *\n * @example\n * normalizeAllowedDomainForWrite('HTTPS://Shop.Example.com:443/cart') // { ok: true, value: 'shop.example.com' }\n * normalizeAllowedDomainForWrite('*.Example.com.') // { ok: true, value: '*.example.com' }\n */\nexport function normalizeAllowedDomainForWrite(\n entry: string\n): { ok: true; value: string } | { ok: false; error: string } {\n const parsed = parseAllowedDomain(entry);\n if ('error' in parsed) return { ok: false, error: parsed.error };\n if (parsed.port) {\n return {\n ok: false,\n error: 'Ports are not supported; the check matches the host name only',\n };\n }\n if (isPublicSuffixWildcard(parsed)) {\n return {\n ok: false,\n error: `*.${parsed.host} would include sites you do not control; list your own hosts instead`,\n };\n }\n return { ok: true, value: format(parsed) };\n}\n\n/**\n * Lenient read-time normalization for entries already stored: strips a\n * scheme, path, port and trailing dot and lowercases, so a legacy entry\n * such as `https://Example.com:443/` still matches. Undefined for entries\n * that cannot be a host at all (they then match nothing, as before).\n *\n * It never widens what a pixel accepts to a public suffix. A malformed\n * wildcard over one (`*.COM`, `https://*.co.uk`) matched nothing before, and\n * cleaning it up would admit every site under it, which writes now refuse.\n * So it stays undefined. One already stored in exact form (`*.com`) matched\n * before this normalization existed and is returned unchanged.\n */\nexport function normalizeStoredAllowedDomain(entry: unknown): string | undefined {\n if (typeof entry !== 'string') return undefined;\n const parsed = parseAllowedDomain(entry);\n if ('error' in parsed) return undefined;\n const normalized = format(parsed);\n if (isPublicSuffixWildcard(parsed) && entry !== normalized) return undefined;\n return normalized;\n}\n\n/**\n * Whether a page host is admitted by a pixel's allowed domains. Exact\n * entries match the host exactly; `*.example.com` matches `example.com`\n * and any subdomain, on a label boundary.\n *\n * @example\n * hostMatchesAllowedDomains('shop.example.com', ['*.Example.com']) // true\n * hostMatchesAllowedDomains('evilexample.com', ['*.example.com']) // false\n */\nexport function hostMatchesAllowedDomains(hostname: string, allowedDomains: unknown[]): boolean {\n const host = hostname.toLowerCase().replace(/\\.$/, '');\n if (!host) return false;\n return allowedDomains.some((raw) => {\n const entry = normalizeStoredAllowedDomain(raw);\n if (!entry) return false;\n if (!entry.startsWith('*.')) return host === entry;\n const base = entry.slice(2);\n return host === base || host.endsWith(`.${base}`);\n });\n}\n\n/**\n * Normalizes a whole list for a write: stored forms in first-seen order with\n * duplicates removed, plus each junk entry's index and reason. Linear in the\n * list's length.\n *\n * @example\n * normalizeAllowedDomainList(['Example.com', 'a..b', 'example.com'])\n * // { values: ['example.com'], errors: [{ index: 1, message: 'Not a valid domain' }] }\n */\nexport function normalizeAllowedDomainList(entries: readonly string[]): {\n values: string[];\n errors: Array<{ index: number; message: string }>;\n} {\n const values = new Set<string>();\n const errors: Array<{ index: number; message: string }> = [];\n entries.forEach((entry, index) => {\n const result = normalizeAllowedDomainForWrite(entry);\n if (result.ok) values.add(result.value);\n else errors.push({ index, message: result.error });\n });\n return { values: [...values], errors };\n}\n\n/**\n * `allowedDomains` on a pixel write: at most {@link MAX_ALLOWED_DOMAINS}\n * entries, each normalized to its stored form (duplicates removed), and each\n * junk entry reported at its index so the route's 400 says which one and\n * why. The cap is checked first, so an oversized list is refused without\n * normalizing any entry.\n */\nexport const AllowedDomainsSchema = z\n .array(z.string())\n .max(MAX_ALLOWED_DOMAINS, `At most ${MAX_ALLOWED_DOMAINS} allowed domains`)\n .transform((entries, ctx) => {\n const { values, errors } = normalizeAllowedDomainList(entries);\n errors.forEach(({ index, message }) =>\n ctx.addIssue({ code: 'custom', message, path: [index] })\n );\n return values;\n });\n","/**\n * Bulk Operations API schemas\n *\n * Standard schemas for bulk CRUD operations across all resources\n */\n\nimport { z } from 'zod';\nimport { AllowedDomainsSchema } from '../utils/allowed-domains';\n\nexport const MAX_BULK_BATCH_SIZE = 100;\n\n/**\n * Bulk operation types\n */\nexport const BulkOperationTypeSchema = z.enum(['create', 'update', 'delete']);\n\n/**\n * Bulk operation options\n */\nexport const BulkOperationOptionsSchema = z.object({\n /** Continue processing remaining items on failure */\n continueOnError: z.boolean().default(true).optional(),\n /** Execute all operations in a single transaction (all-or-nothing) */\n transactional: z.boolean().default(false).optional(),\n /** Validate only without executing (dry run) */\n validateOnly: z.boolean().default(false).optional(),\n /** Preview what would be deleted without executing (alias for validateOnly on delete) */\n dryRun: z.boolean().default(false).optional(),\n});\n\n/**\n * Base bulk request schema\n */\nexport const BaseBulkRequestSchema = z.object({\n operation: BulkOperationTypeSchema,\n options: BulkOperationOptionsSchema.optional(),\n});\n\n/**\n * Bulk result item\n */\nexport const BulkResultItemSchema = z.object({\n index: z.number(),\n success: z.boolean(),\n data: z.unknown().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n })\n .optional(),\n});\nexport type BulkResultItem = z.infer<typeof BulkResultItemSchema>;\n\n/**\n * Bulk response\n */\nexport const BulkResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().uuid(),\n summary: z.object({\n total: z.number(),\n succeeded: z.number(),\n failed: z.number(),\n skipped: z.number(),\n }),\n results: z.array(BulkResultItemSchema),\n metadata: z\n .object({\n processingTime: z.number(),\n transactional: z.boolean(),\n dryRun: z.boolean().optional(),\n })\n .optional(),\n});\nexport type BulkResponse = z.infer<typeof BulkResponseSchema>;\n\n/**\n * Bulk delete preview stats for a single project\n */\nexport const BulkDeletePreviewStatsSchema = z.object({\n projectId: z.string().uuid(),\n friendlyId: z.string().nullable(),\n name: z.string(),\n counts: z.object({\n detections: z.number(),\n pixels: z.number(),\n apiKeys: z.number(),\n members: z.number(),\n bouncerConfigs: z.number(),\n delegations: z.number(),\n bouncerProofs: z.number(),\n bouncerSessions: z.number(),\n userAccounts: z.number(),\n userProfiles: z.number(),\n }),\n totalRecords: z.number(),\n});\nexport type BulkDeletePreviewStats = z.infer<typeof BulkDeletePreviewStatsSchema>;\n\n/**\n * Bulk delete response with optional preview\n */\nexport const BulkDeleteResponseSchema = BulkResponseSchema.extend({\n preview: z.array(BulkDeletePreviewStatsSchema).optional(),\n});\nexport type BulkDeleteResponse = z.infer<typeof BulkDeleteResponseSchema>;\n\n/**\n * Projects Bulk Request\n */\nexport const ProjectsBulkCreateItemSchema = z.object({\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\n\nexport const ProjectsBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n webhookUrl: z.string().url().nullable().optional(),\n webhookSecret: z.string().nullable().optional(),\n })\n .optional(),\n});\n\nexport const ProjectsBulkDeleteItemSchema = z.object({\n /** Project UUID to delete */\n id: z.string().uuid(),\n /** Skip confirmation for automated cleanup (admin only) */\n force: z.boolean().optional(),\n});\n\nexport const ProjectsBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(ProjectsBulkCreateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(ProjectsBulkUpdateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(ProjectsBulkDeleteItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n ])\n);\nexport type ProjectsBulkRequest = z.infer<typeof ProjectsBulkRequestSchema>;\n\n/**\n * Pixels Bulk Request\n */\nexport const PixelsBulkCreateItemSchema = z.object({\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n isActive: z.boolean().default(true),\n configuration: z\n .object({\n allowedDomains: AllowedDomainsSchema.default([]),\n collectBehavioral: z.boolean().default(true),\n enableFingerprinting: z.boolean().default(true),\n enableSessionTracking: z.boolean().default(true),\n sampleRate: z.number().min(0).max(1).default(1),\n })\n .optional(),\n});\n\nexport const PixelsBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n isActive: z.boolean().optional(),\n configuration: z\n .object({\n allowedDomains: AllowedDomainsSchema.optional(),\n collectBehavioral: z.boolean().optional(),\n enableFingerprinting: z.boolean().optional(),\n enableSessionTracking: z.boolean().optional(),\n sampleRate: z.number().min(0).max(1).optional(),\n })\n .optional(),\n});\n\nexport const PixelsBulkDeleteItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const PixelsBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(PixelsBulkCreateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(PixelsBulkUpdateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(PixelsBulkDeleteItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n ])\n);\nexport type PixelsBulkRequest = z.infer<typeof PixelsBulkRequestSchema>;\n\n/**\n * API Keys Bulk Request\n */\nexport const ApiKeysBulkCreateItemSchema = z.object({\n name: z.string().min(1).max(255),\n projectId: z.string().uuid().optional(),\n permissions: z.array(z.enum(['read', 'write', 'admin'])).default(['read']),\n rateLimits: z\n .object({\n requestsPerSecond: z.number().min(1).optional(),\n requestsPerMinute: z.number().min(1).optional(),\n requestsPerHour: z.number().min(1).optional(),\n requestsPerDay: z.number().min(1).optional(),\n })\n .optional(),\n expiresAt: z.string().datetime().optional(),\n});\n\nexport const ApiKeysBulkRevokeItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const ApiKeysBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n permissions: z.array(z.enum(['read', 'write', 'admin'])).optional(),\n rateLimits: z\n .object({\n requestsPerSecond: z.number().min(1).optional(),\n requestsPerMinute: z.number().min(1).optional(),\n requestsPerHour: z.number().min(1).optional(),\n requestsPerDay: z.number().min(1).optional(),\n })\n .optional(),\n expiresAt: z.string().datetime().optional().nullable(),\n});\n\nexport const ApiKeysBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(ApiKeysBulkCreateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(ApiKeysBulkUpdateItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(ApiKeysBulkRevokeItemSchema).min(1).max(MAX_BULK_BATCH_SIZE),\n }),\n ])\n);\nexport type ApiKeysBulkRequest = z.infer<typeof ApiKeysBulkRequestSchema>;\n\n/**\n * Bulk operation error codes\n */\nexport const BULK_ERROR_CODES = {\n BATCH_TOO_LARGE: 'BATCH_TOO_LARGE',\n INVALID_OPERATION: 'INVALID_OPERATION',\n TRANSACTION_FAILED: 'TRANSACTION_FAILED',\n TRANSACTION_ABORTED: 'TRANSACTION_ABORTED',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n PARTIAL_FAILURE: 'PARTIAL_FAILURE',\n LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',\n OWNERSHIP_ERROR: 'OWNERSHIP_ERROR',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n DELETE_FAILED: 'DELETE_FAILED',\n SKIPPED: 'SKIPPED',\n NOT_FOUND: 'NOT_FOUND',\n} as const;\n","/**\n * Buckets an `agent_daily_rollup` row `(agent_type, detection_class)` into\n * the admin overview's four-bucket AI traffic taxonomy, reproducing the\n * internal \"Customers & Installations\" report's overlay.\n *\n * Name wins over class: historical rows stamped training crawlers\n * (ClaudeBot, GPTBot) as `ai_agent`, so the overlay name lists below take\n * precedence over the stored `detection_class` before either falls back to\n * `KNOWN_AGENT_PATTERNS` and then to the class itself.\n */\n\nimport { KNOWN_AGENT_PATTERNS } from './agents';\nimport type { AgentPattern } from '../core/agent';\nimport type { TrafficTaxonomyBucket } from '../types/admin-overview';\nimport type { DetectionClassEnum } from '../utils/detection-class';\n\n/**\n * Training / indexing crawlers run by AI vendors. Values are the exact names\n * stored in detections.agent_type: KNOWN_AGENT_PATTERNS `name`s for the TS\n * classifier path and the engine's emitted names (which keep their spaces,\n * e.g. 'Bytedance Crawler') for the WASM path.\n *\n */\nexport const REPORT_AI_CRAWLER_NAMES: readonly string[] = [\n 'GPTBot',\n 'ClaudeBot',\n 'Anthropic-AI Crawler',\n 'PerplexityBot',\n 'Google-Extended',\n 'Gemini-Deep-Research',\n 'Meta-ExternalAgent',\n 'Meta AI',\n 'CohereBot',\n 'DeepSeekBot',\n 'MistralBot',\n 'Amazonbot',\n 'Amazon Bedrock',\n 'Common Crawl',\n 'Bytedance Crawler',\n];\n/** Interactive assistants / agents acting for a person. */\nexport const REPORT_AI_AGENT_NAMES: readonly string[] = [\n 'ChatGPT',\n 'ChatGPT-User',\n 'OpenAI',\n 'Claude',\n 'Claude-User',\n 'Anthropic',\n 'Perplexity',\n 'Perplexity-User',\n 'Google Gemini',\n 'Microsoft Copilot',\n 'DeepSeek AI',\n 'xAI Grok',\n 'Amazon Q',\n 'Kya Agent',\n];\n\n// Built once at module scope: lowercase membership sets for the overlay\n// lists, and a lowercase name-or-id lookup into KNOWN_AGENT_PATTERNS.\nconst CRAWLER_NAME_SET = new Set(REPORT_AI_CRAWLER_NAMES.map((name) => name.toLowerCase()));\nconst AGENT_NAME_SET = new Set(REPORT_AI_AGENT_NAMES.map((name) => name.toLowerCase()));\n\n/**\n * Build a lowercase name-or-id lookup over `patterns`, first-wins: the first\n * match in source order wins so a later entry that reuses a name cannot\n * silently change a bucket. Exported so the rule is testable on synthetic\n * input.\n */\nexport function buildKnownPatternLookup(\n patterns: readonly AgentPattern[]\n): ReadonlyMap<string, AgentPattern> {\n const map = new Map<string, AgentPattern>();\n for (const entry of patterns) {\n const nameKey = entry.name.toLowerCase();\n const idKey = entry.id.toLowerCase();\n if (!map.has(nameKey)) map.set(nameKey, entry);\n if (!map.has(idKey)) map.set(idKey, entry);\n }\n return map;\n}\n\nconst KNOWN_PATTERN_BY_NAME_OR_ID = buildKnownPatternLookup(KNOWN_AGENT_PATTERNS);\n\n/**\n * Classify a rollup row's `(agent_type, detection_class)` pair into a\n * {@link TrafficTaxonomyBucket}. An unidentified agent (`agent_type` null,\n * stored as 'Unknown' by the rollup) falls to the class fallback, so an\n * `ai_agent`-classed unidentified row counts as an AI agent and a\n * `bot`-classed one as other automation.\n */\nexport function classifyAgentTaxonomy(\n agentType: string | null | undefined,\n detectionClass: DetectionClassEnum | string | null | undefined\n): TrafficTaxonomyBucket {\n if (detectionClass === 'human') return 'human';\n\n const normalized = agentType?.trim().toLowerCase();\n if (normalized) {\n if (CRAWLER_NAME_SET.has(normalized)) return 'ai_crawler';\n if (AGENT_NAME_SET.has(normalized)) return 'ai_agent';\n\n const known = KNOWN_PATTERN_BY_NAME_OR_ID.get(normalized);\n if (known) {\n return (known.category ?? 'ai_assistant') === 'ai_assistant' ? 'ai_agent' : 'ai_crawler';\n }\n }\n\n return detectionClass === 'ai_agent' ? 'ai_agent' : 'other_automation';\n}\n","/**\n * Database Entity Types\n *\n * Shared types for database entities used across the dashboard,\n * API, and other packages in the monorepo.\n */\n\nimport { z } from 'zod';\nimport { ipAddressSchema } from '../utils/zod-helpers';\nimport { AllowedDomainsSchema } from '../utils/allowed-domains';\n\n/**\n * User Plan Levels\n */\nexport const UserPlanSchema = z.enum(['free', 'pro', 'enterprise']);\nexport type UserPlan = z.infer<typeof UserPlanSchema>;\n\n/**\n * API Key Permissions\n */\nexport const ApiKeyPermissionSchema = z.enum(['read', 'write', 'admin', 'forward']);\nexport type ApiKeyPermission = z.infer<typeof ApiKeyPermissionSchema>;\n\n/**\n * User Entity\n */\nexport const UserSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email(),\n name: z.string().nullish(),\n image: z.string().url().nullish(),\n emailVerified: z.date().nullish(),\n plan: UserPlanSchema.default('free'),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type User = z.infer<typeof UserSchema>;\n\n/**\n * Project Settings\n */\nexport const ProjectSettingsSchema = z.object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n // A caller-controlled configuration value, not a feature flag: raises a\n // project's beacon-ingest rate-limit ceiling above its plan's fixed\n // per-minute default (`PLAN_RATE_LIMITS[plan].requestsPerMinute`), for a\n // high-traffic tenant whose real visitor volume concentrates behind one\n // shared IP (e.g. a corporate NAT).\n beaconRateLimitPerMinute: z.number().int().positive().optional(),\n // Additional page origins browser posture may be issued for, beyond the\n // primary derived from `domain` (see `../posture-origins`). Lenient on\n // read: readers re-validate through `readPostureOriginsSetting`.\n postureOrigins: z.array(z.string()).optional(),\n postureReportPaths: z.array(z.string()).optional(),\n beaconIngestMode: z.enum(['origin', 'worker']).optional(),\n});\nexport type ProjectSettings = z.infer<typeof ProjectSettingsSchema>;\n\n/**\n * Project Entity\n */\nexport const ProjectSchema = z.object({\n id: z.string().uuid(),\n friendlyId: z.string().nullable().optional(), // Human-readable project ID for URLs\n userId: z.string().uuid(),\n name: z.string().min(1).max(255),\n domain: z.string().optional(),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ProjectSettingsSchema. prefault parses it, as Zod 3 did.\n settings: ProjectSettingsSchema.prefault({}),\n // Setup Flow v2 step 1 (\"What brings you here?\") selections, if this\n // project was created via that flow — see CreateProjectSchema's own\n // doc comment. Null/absent for every other creation path.\n setupGoals: z.array(z.string()).nullable().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Project = z.infer<typeof ProjectSchema>;\n\n/**\n * Pixel Configuration\n */\nexport const PixelConfigurationSchema = z.object({\n enabled: z.boolean().default(true),\n skipPaths: z.array(z.string()).default([]),\n // Normalized on write (lowercase host or `*.host`, no scheme/port/path);\n // junk is a 400 naming the entry. See utils/allowed-domains.ts.\n allowedDomains: AllowedDomainsSchema.default([]),\n blockedAgents: z.array(z.string()).default([]),\n batchSize: z.number().min(1).max(100).default(10),\n flushInterval: z.number().min(100).max(60000).default(5000),\n enableBehavioralTracking: z.boolean().default(true),\n enableSessionReplay: z.boolean().default(false),\n customHeaders: z.record(z.string(), z.string()).default({}),\n});\nexport type PixelConfiguration = z.infer<typeof PixelConfigurationSchema>;\n\n/**\n * Pixel Entity\n */\nexport const PixelSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n secretKey: z.string().min(32),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside PixelConfigurationSchema. prefault parses it, as Zod 3 did.\n configuration: PixelConfigurationSchema.prefault({}),\n isActive: z.boolean().default(true),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Pixel = z.infer<typeof PixelSchema>;\n\n/**\n * Pixel Statistics\n */\nexport const PixelStatsSchema = z.object({\n totalEvents: z.number().int().min(0),\n agentsDetected: z.number().int().min(0),\n uniqueSessions: z.number().int().min(0),\n averageConfidence: z.number().min(0).max(1),\n lastEventAt: z.date().optional(),\n periodStart: z.date(),\n periodEnd: z.date(),\n});\nexport type PixelStats = z.infer<typeof PixelStatsSchema>;\n\n/**\n * API Key Rate Limits\n */\nexport const ApiKeyRateLimitsSchema = z.object({\n requestsPerSecond: z.number().min(1).default(10),\n requestsPerMinute: z.number().min(1).default(100),\n requestsPerHour: z.number().min(1).default(1000),\n requestsPerDay: z.number().min(1).default(10000),\n burstLimit: z.number().min(1).default(20),\n});\nexport type ApiKeyRateLimits = z.infer<typeof ApiKeyRateLimitsSchema>;\n\n/**\n * API Key Entity\n */\nexport const ApiKeySchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n projectId: z.string().uuid().optional(),\n name: z.string().min(1).max(255),\n key: z.string().min(32),\n permissions: z.array(ApiKeyPermissionSchema).default(['read']),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ApiKeyRateLimitsSchema. prefault parses it, as Zod 3 did.\n rateLimits: ApiKeyRateLimitsSchema.prefault({}),\n lastUsedAt: z.date().optional(),\n expiresAt: z.date().optional(),\n createdAt: z.date(),\n revokedAt: z.date().optional(),\n});\nexport type ApiKey = z.infer<typeof ApiKeySchema>;\n\n/**\n * Detection Log Entity\n */\nexport const DetectionLogSchema = z.object({\n id: z.string().uuid(),\n pixelId: z.string().uuid(),\n projectId: z.string().uuid(),\n isAgent: z.boolean(),\n confidence: z.number().min(0).max(100), // Stored as 0-100 in DB\n agentType: z.string().optional(),\n userAgent: z.string().optional(),\n ipAddress: ipAddressSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n sessionId: z.string().optional(),\n createdAt: z.date(),\n});\nexport type DetectionLog = z.infer<typeof DetectionLogSchema>;\n\n/**\n * Session Entity (for NextAuth)\n */\nexport const SessionSchema = z.object({\n sessionToken: z.string(),\n userId: z.string().uuid(),\n expires: z.date(),\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\n/**\n * Account Entity (for OAuth providers)\n */\nexport const AccountSchema = z.object({\n userId: z.string().uuid(),\n type: z.string(),\n provider: z.string(),\n providerAccountId: z.string(),\n refresh_token: z.string().optional(),\n access_token: z.string().optional(),\n expires_at: z.number().optional(),\n token_type: z.string().optional(),\n scope: z.string().optional(),\n id_token: z.string().optional(),\n session_state: z.string().optional(),\n});\nexport type Account = z.infer<typeof AccountSchema>;\n\n/**\n * Verification Token Entity\n */\nexport const VerificationTokenSchema = z.object({\n identifier: z.string(),\n token: z.string(),\n expires: z.date(),\n});\nexport type VerificationToken = z.infer<typeof VerificationTokenSchema>;\n","/**\n * Provider Registry Re-exports\n *\n * This file re-exports types and schemas from @kya-os/provider-registry,\n * providing Checkpoint with a single source of truth for provider definitions\n * and eliminating type fragmentation bugs.\n *\n * ## Why This File Exists\n *\n * Prior to this integration, Checkpoint defined its own provider types that\n * diverged from the canonical types in provider-registry:\n * - Checkpoint used 'credential' while provider-registry uses 'password'\n * - Field names differed: 'authorizationUrl' vs 'authorizationEndpoint'\n * - Schemas were duplicated rather than shared\n *\n * ## Migration Notes\n *\n * For backward compatibility, we provide aliases:\n * - `AuthProviderType` = `ProviderAuthType` (with 'credential' mapped to 'password')\n *\n * @module provider-registry\n */\n\n// ==============================================================================\n// RE-EXPORT FROM @kya-os/provider-registry\n// ==============================================================================\n\n// Types only. The registry's runtime values (AUTH_MODES, PROVIDER_AUTH_TYPES,\n// the provider schemas and validators) are on the\n// `@kya-os/checkpoint-shared/provider-registry` entry instead: importing the\n// registry loads @kya-os/contracts, @kya-os/consent and a second Zod, which\n// the root entry should not make every consumer pay for.\nexport type {\n ProviderAuthType,\n ConsentProviderType,\n ProviderDefinition as ProviderRegistryDefinition,\n ProviderConfig,\n OAuthProviderConfig,\n CredentialProviderConfig,\n AuthMode,\n IProviderRegistry,\n RegistryLogger,\n} from '@kya-os/provider-registry';\n\n// ==============================================================================\n// BACKWARD COMPATIBILITY ALIASES\n// ==============================================================================\n\n/**\n * Backward compatibility alias for AuthProviderType.\n *\n * Checkpoint previously used 'credential' instead of 'password'.\n * This type alias allows existing code to continue working.\n *\n * @deprecated Use `ProviderAuthType` from provider-registry directly.\n * This alias maps:\n * - 'credential' → 'password' (canonical name)\n * - 'oauth2' → 'oauth2' (unchanged)\n */\nexport type LegacyAuthProviderType = 'oauth2' | 'credential';\n\n/**\n * Maps legacy auth type values to canonical provider-registry values.\n *\n * @example\n * ```typescript\n * import { mapLegacyAuthType } from '@kya-os/checkpoint-shared';\n *\n * const canonicalType = mapLegacyAuthType('credential'); // 'password'\n * ```\n */\nexport function mapLegacyAuthType(\n legacyType: LegacyAuthProviderType | string\n): 'oauth2' | 'password' | string {\n switch (legacyType) {\n case 'credential':\n case 'credentials':\n return 'password';\n case 'oauth2':\n return 'oauth2';\n default:\n return legacyType;\n }\n}\n\n/**\n * Maps canonical provider-registry auth types to legacy Checkpoint types.\n *\n * Useful when maintaining backward compatibility with existing API responses.\n *\n * @example\n * ```typescript\n * import { mapToLegacyAuthType } from '@kya-os/checkpoint-shared';\n *\n * const legacyType = mapToLegacyAuthType('password'); // 'credential'\n * ```\n */\nexport function mapToLegacyAuthType(canonicalType: string): 'oauth2' | 'credential' | string {\n switch (canonicalType) {\n case 'password':\n return 'credential';\n case 'oauth2':\n return 'oauth2';\n default:\n return canonicalType;\n }\n}\n\n// ==============================================================================\n// AUTHORIZATION MODE CONSTANTS (from provider-registry)\n// ==============================================================================\n\n/**\n * Authorization modes supported by Checkpoint Bouncer.\n *\n * These are aligned with consent UI auth modes and provider capabilities.\n *\n * Note: This is re-exported from @kya-os/provider-registry for consistency.\n * The canonical source is AUTH_MODES from provider-registry.\n */\nexport const AUTHORIZATION_MODES = {\n /** OAuth2 authentication flow */\n OAUTH: 'oauth',\n /** Username/password credential authentication */\n CREDENTIAL: 'credential',\n /** Consent-only - no authentication required */\n CONSENT_ONLY: 'consent-only',\n // Future modes (aligned with provider-registry):\n // PASSKEY: 'passkey',\n // MAGIC_LINK: 'magic-link',\n // OTP: 'otp',\n // IDV: 'idv',\n} as const;\n\nexport type AuthorizationMode = (typeof AUTHORIZATION_MODES)[keyof typeof AUTHORIZATION_MODES];\n","/**\n * Bouncer Schemas\n *\n * Zod schemas for Agent Bouncer KYA-OS protocol validation.\n *\n * ## Provider Registry Integration\n *\n * As of v0.3.0, this module imports core provider types from @kya-os/provider-registry\n * to eliminate type fragmentation between Checkpoint and KYA-OS.\n *\n * Key types imported:\n * - `ProviderAuthType` (canonical: 'oauth2' | 'password' | 'passkey' | etc.)\n * - `ProviderDefinition` (canonical provider metadata structure)\n * - `OAuthProviderConfig`, `CredentialProviderConfig` (canonical configs)\n *\n * For backward compatibility, we alias:\n * - `AuthProviderType` → maps 'credential' to 'password' internally\n */\n\nimport { z } from 'zod';\n\n// Import canonical types from provider-registry\nimport {\n type ProviderAuthType,\n type ConsentProviderType,\n mapLegacyAuthType,\n mapToLegacyAuthType,\n} from './provider-registry';\n\n// Re-export for consumers\nexport { mapLegacyAuthType, mapToLegacyAuthType };\n\n/**\n * Hex color validation regex - accepts #RRGGBB format only (6 hex digits)\n * Used for consent branding colors where we append alpha values like \"20\" or \"40\"\n * Note: 3-char hex (#RGB) is NOT allowed because appending alpha creates invalid 5-char CSS (#RGB20)\n * Note: 8-char hex (#RRGGBBAA) is NOT allowed because appending alpha would create invalid 10-char CSS\n */\nconst hexColorRegex = /^#[0-9A-Fa-f]{6}$/;\n\n/**\n * HTTP(S)-only URL validator.\n *\n * `z.string().url()` alone accepts dangerous pseudo-protocols like\n * `javascript:`, `data:`, `vbscript:`, and `file:` because the underlying\n * URL constructor parses them as valid URLs. When these values are later\n * rendered into `<a href>` or `<img src>` on a public page, they become\n * stored-XSS vectors.\n *\n * This validator parses the URL and explicitly requires the protocol to\n * be `http:` or `https:`. Used for every customer-editable URL field that\n * eventually gets rendered to a browser (logoUrl, termsUrl, mcpServerUrl,\n * etc.).\n *\n * Defense in depth — the render layer (`sanitizeDisplayUrl` in\n * apps/web/lib/utils/url-security.ts) also sanitizes at render time, so\n * legacy/direct-DB values don't bypass this.\n *\n * IMPORTANT: `maxLength` is opt-in with NO DEFAULT on purpose. Earlier\n * versions of this helper defaulted to 500 characters, which silently\n * capped fields that previously had no length cap — notably `authUrl` in\n * `DelegationPollingStatusSchema` and `mcpServerUrl` / `mcpWorkerUrl` in\n * `BouncerConfigSchema`. OAuth authorization URLs with scopes + PKCE +\n * state + redirect_uri routinely exceed 500 characters, so those fields\n * must NOT be capped. Always pass `maxLength` explicitly at the call site\n * and match the field's original constraint.\n *\n * @param maxLength - Optional maximum URL length. Pass only if the field\n * had a length cap before; pass nothing to preserve \"no length limit\".\n * @returns A zod schema that accepts only http(s) URLs\n */\nexport function httpUrlSchema(maxLength?: number) {\n const base = maxLength !== undefined ? z.string().url().max(maxLength) : z.string().url();\n return base.refine(\n (value) => {\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n },\n { message: 'URL must use http:// or https:// protocol' }\n );\n}\n\n/**\n * OAuth Provider Types\n */\nexport const OAuthProviderTypeSchema = z.enum(['oauth2', 'oidc', 'custom']);\nexport type OAuthProviderType = z.infer<typeof OAuthProviderTypeSchema>;\n\n/**\n * OAuth Connection Status\n */\nexport const OAuthConnectionStatusSchema = z.enum(['connected', 'disconnected', 'error']);\n\n// ==============================================================================\n// MULTI-PROVIDER OAUTH TYPES (CRED-001)\n// Provider Registry Integration: Types aligned with @kya-os/provider-registry\n// ==============================================================================\n\n/**\n * Auth Provider Type - determines the authentication method.\n *\n * **Provider Registry Integration:**\n * - Canonical types: 'oauth2' | 'password' (from provider-registry)\n * - Legacy alias: 'credential' maps to 'password' internally\n *\n * For new code, prefer using 'password' for credential-based auth.\n * The 'credential' value is accepted for backward compatibility.\n *\n * @see PROVIDER_AUTH_TYPES from @kya-os/provider-registry for canonical values\n */\nconst AuthProviderTypeSchema = z.enum(['oauth2', 'credential', 'password']).transform((val) => {\n // Map legacy 'credential' to canonical 'password'\n if (val === 'credential') return 'password';\n return val;\n});\n\n// Re-export the canonical type from provider-registry\nexport type { ProviderAuthType, ConsentProviderType };\n\n// ==============================================================================\n// PROVIDER SECRET METADATA (Provider Registry Alignment)\n// ==============================================================================\n\n/**\n * Secret name constraints: alphanumeric, underscores, max 128 chars\n * Pattern: KYA_{env}_{projectSlug}_{providerId}_{secretType}\n */\nexport const SecretNameSchema = z\n .string()\n .regex(/^[A-Z][A-Z0-9_]{2,127}$/, 'Secret name must be uppercase alphanumeric with underscores')\n .max(128);\nexport type SecretName = z.infer<typeof SecretNameSchema>;\n\n/**\n * Provider Secret Metadata - references to secrets stored in secure storage\n *\n * SECURITY: This schema stores ONLY metadata and secret names, NEVER actual secret values.\n * Secret values are resolved at runtime from Cloudflare Worker Secrets.\n */\nexport const ProviderSecretMetadataSchema = z.object({\n // Secret references (use consistent naming: *SecretName)\n clientIdSecretName: SecretNameSchema.optional(),\n clientSecretName: SecretNameSchema.optional(),\n apiKeySecretName: SecretNameSchema.optional(),\n // Rotation tracking\n clientSecretVersion: z.number().int().positive().optional(),\n lastRotatedAt: z.string().datetime().optional(),\n});\nexport type ProviderSecretMetadata = z.infer<typeof ProviderSecretMetadataSchema>;\n\n/**\n * Base Auth Provider - common fields for all provider types\n */\nexport const BaseAuthProviderSchema = z.object({\n displayName: z.string().max(100).optional(),\n status: OAuthConnectionStatusSchema.default('disconnected'),\n});\n\n/**\n * OAuth2 Provider Configuration\n * Stores all configuration for an OAuth2 provider\n */\nexport const OAuth2ProviderSchema = BaseAuthProviderSchema.extend({\n type: z.literal('oauth2'),\n clientId: z.string().max(255),\n clientSecret: z.string().optional(), // Encrypted, never returned in GET - TO BE DEPRECATED\n authEndpoint: z.string().max(500),\n tokenEndpoint: z.string().max(500),\n userInfoUrl: httpUrlSchema(500).optional(), // User info endpoint for identity resolution\n /**\n * Optional dot-path field mapping into the `userInfoUrl` response for\n * merchant identity extraction (native consent merchant-oauth leg).\n * When absent, extraction defaults to: userId ← first present of\n * `sub`/`id`/`customerId`; userEmail ← `email`.\n */\n userInfoFields: z\n .object({\n userId: z.string().max(255).optional(), // JSON dot-path to the customer id\n userEmail: z.string().max(255).optional(), // JSON dot-path to the customer email\n })\n .optional(),\n redirectUri: z.string().max(500),\n scopes: z.array(z.string()).optional(),\n supportsPKCE: z.boolean().optional(),\n // Phase 3 fields\n customParams: z.record(z.string(), z.string()).optional(),\n tokenEndpointAuthMethod: z.enum(['client_secret_post', 'client_secret_basic']).optional(),\n responseType: z.string().optional(),\n grantType: z.string().optional(),\n // Provider Registry Alignment: Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type OAuth2Provider = z.infer<typeof OAuth2ProviderSchema>;\n\n/**\n * Credential Provider Configuration\n * Stores configuration for username/password, email/password, or cookie-based authentication\n *\n * Supports:\n * - JSON token responses (JWT, Bearer tokens)\n * - Cookie-based sessions (like HardwareWorld)\n * - Custom response validation\n */\nexport const CredentialProviderSchema = BaseAuthProviderSchema.extend({\n type: z.literal('credential'),\n authEndpoint: z.string().max(500),\n\n // Request configuration\n requestBodyTemplate: z.record(z.string(), z.string()).optional(), // Field mapping for request body\n // How the templated fields are sent: a JSON object (the default) or an\n // application/x-www-form-urlencoded form. The response is read as JSON either way.\n requestEncoding: z.enum(['json', 'form']).optional(),\n\n // Response field mapping\n responseFields: z.object({\n // Session/auth token - can be JWT, session cookie, or any auth identifier\n sessionToken: z.string(), // JSON path to auth token (renamed from accessToken for clarity)\n userId: z.string().optional(), // JSON path to user ID\n userEmail: z.string().optional(), // JSON path to user email (for delegation records)\n userDisplayName: z.string().optional(), // JSON path to display name (for consent screens)\n expiresIn: z.string().optional(), // JSON path to token expiry (optional for cookie-based)\n }),\n\n // Success validation - verify the login actually succeeded\n successCheck: z\n .object({\n path: z.string(), // JSON path to check (e.g., \"success\", \"status\")\n expectedValue: z.union([z.string(), z.boolean(), z.number()]), // Expected value (e.g., true, \"ok\", 200)\n })\n .optional(),\n\n // Custom headers for API requests\n headers: z.record(z.string(), z.string()).optional(),\n\n // Token usage configuration (CRED-002)\n // Tells xmcp-i how to use the session token for subsequent API calls\n tokenUsage: z.enum(['cookie', 'bearer', 'header']).optional().default('cookie'),\n tokenHeader: z.string().max(100).optional(), // Custom header name if tokenUsage === 'header'\n cookieFormat: z.string().max(500).optional(), // Cookie format template, e.g., \"CIX={{token}}; customerCookie={{token}}\"\n apiHeaders: z.record(z.string(), z.string()).optional(), // Additional headers for API calls\n\n // Consent overrides for credential forms (CRED-002)\n consentOverrides: z\n .object({\n branding: z\n .object({\n primaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #2563EB)')\n .optional(),\n secondaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #DBEAFE)')\n .optional(),\n logoUrl: httpUrlSchema(500).optional(),\n companyName: z.string().max(255).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n })\n .partial()\n .optional(),\n terms: z\n .object({\n url: httpUrlSchema(500).optional(),\n text: z.string().max(500).optional(),\n required: z.boolean().optional(),\n version: z.string().max(50).optional(),\n })\n .partial()\n .optional(),\n formTitle: z.string().max(255).optional(),\n formDescription: z.string().max(1000).optional(),\n identityFieldLabel: z.string().max(255).optional(),\n passwordFieldLabel: z.string().max(255).optional(),\n submitButtonText: z.string().max(100).optional(),\n })\n .optional(),\n // Provider Registry Alignment: Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type CredentialProvider = z.infer<typeof CredentialProviderSchema>;\n\n/**\n * Configured Provider Union - can be OAuth2 or Credential\n * Named to avoid conflict with AuthProvider in types/auth.ts\n */\nexport const ConfiguredProviderSchema = z.discriminatedUnion('type', [\n OAuth2ProviderSchema,\n CredentialProviderSchema,\n]);\nexport type ConfiguredProvider = z.infer<typeof ConfiguredProviderSchema>;\n\n/**\n * OAuth Providers Map - keyed by provider ID (github, google, custom, etc.)\n */\nexport const OAuthProvidersMapSchema = z.record(z.string(), ConfiguredProviderSchema);\n\n/**\n * Add/Update Provider Request Schema\n * Used for PUT /api/internal/bouncer/config/[projectId]/providers/[providerId]\n */\nexport const AddUpdateProviderRequestSchema = ConfiguredProviderSchema;\n\n/**\n * Scope Definition\n */\nexport const ScopeSchema = z.object({\n name: z.string().min(1).max(100),\n description: z.string().max(500).optional(),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n category: z.string().max(50).optional(),\n});\nexport type Scope = z.infer<typeof ScopeSchema>;\n\n/**\n * CRISP Budget Configuration\n */\nexport const CRISPBudgetSchema = z.object({\n requestsPerHour: z.number().int().positive().optional(),\n requestsPerDay: z.number().int().positive().optional(),\n tokensPerHour: z.number().int().positive().optional(),\n tokensPerDay: z.number().int().positive().optional(),\n computeUnitsPerHour: z.number().int().positive().optional(),\n computeUnitsPerDay: z.number().int().positive().optional(),\n});\n\n/**\n * Consent Branding Configuration\n */\nexport const ConsentBrandingSchema = z.object({\n primaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #2563EB)')\n .optional(),\n secondaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #DBEAFE)')\n .optional(),\n logoUrl: httpUrlSchema(500).optional(),\n companyName: z.string().max(255).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n});\nexport type ConsentBranding = z.infer<typeof ConsentBrandingSchema>;\n\n/**\n * Consent Terms Configuration\n */\nexport const ConsentTermsSchema = z.object({\n url: httpUrlSchema(500).optional(),\n text: z.string().max(500).optional(),\n required: z.boolean().optional(),\n version: z.string().max(50).optional(),\n privacyUrl: httpUrlSchema(500).optional(),\n});\nexport type ConsentTerms = z.infer<typeof ConsentTermsSchema>;\n\n/**\n * Consent UI Configuration\n */\nexport const ConsentUISchema = z.object({\n title: z.string().max(255).optional(),\n description: z.string().max(1000).optional(),\n expirationText: z.string().max(500).optional(),\n cancelButtonText: z.string().max(100).optional(),\n submitButtonText: z.string().max(100).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n popupEnabled: z.boolean().optional(),\n autoClose: z.boolean().optional(),\n});\nexport type ConsentUI = z.infer<typeof ConsentUISchema>;\n\n/**\n * Consent Custom Field Configuration\n */\nexport const ConsentCustomFieldSchema = z.object({\n name: z.string().max(100),\n label: z.string().max(255),\n type: z.enum(['text', 'textarea', 'checkbox']),\n required: z.boolean(),\n});\nexport type ConsentCustomField = z.infer<typeof ConsentCustomFieldSchema>;\n\n/**\n * Consent metadata used for cache busting + UX hints\n */\nexport const ConsentConfigMetadataSchema = z.object({\n version: z.number().int().min(1).default(1),\n updatedAt: z.string().datetime().nullable().optional(),\n bumpedAt: z.string().datetime().nullable().optional(),\n});\nexport type ConsentConfigMetadata = z.infer<typeof ConsentConfigMetadataSchema>;\n\n/**\n * First-Contact Scope Cap section 3: the two risk tiers that require a\n * minimum Sensitive/Critical trust tier before a capability can be offered.\n * Shared by the Rule 1 refine below (`ConsentCapabilitySchema`) and the\n * Rule 2/3 refine on `ConsentConfigSchema`, so the tier boundary is defined\n * once instead of repeated as an inline check at each site.\n */\nfunction requiresSensitiveTier(riskLevel: 'low' | 'medium' | 'high' | 'critical'): boolean {\n return riskLevel === 'high' || riskLevel === 'critical';\n}\n\n/**\n * Capability — operator-authored capability row shown to the user during\n * consent. The `cedar` field holds the policy fragment (with `{{agent_did}}`,\n * `{{user_did}}`, `{{org}}`, `{{deployment}}` placeholders) that the runtime\n * binds and attaches to the issued delegation VC.\n */\nexport const ConsentCapabilitySchema = z\n .object({\n id: z\n .string()\n .min(1)\n .max(64)\n .regex(\n /^[a-z][a-z0-9._-]*$/,\n 'Capability id must be lowercase alphanumeric with `.`, `_`, or `-`'\n ),\n label: z.string().min(1).max(80),\n description: z.string().min(1).max(280),\n icon: z.enum([\n 'search',\n 'cart',\n 'card',\n 'pin',\n 'pin-new',\n 'shield',\n 'key',\n 'tools',\n 'user',\n 'calendar',\n 'lock',\n 'eye',\n 'send',\n 'package',\n 'neutral',\n ]),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']),\n defaultOn: z.boolean(),\n cedar: z\n .string()\n .min(1)\n .max(8000)\n .refine(\n (value) => /^\\s*(permit|forbid)\\s*\\(/.test(value),\n 'Cedar fragment must begin with `permit (` or `forbid (`'\n ),\n scopes: z.array(z.string().min(1).max(120)).min(1).max(20),\n category: z.string().max(80).optional(),\n })\n // First-Contact Scope Cap section 3, Rule 1: a high/critical capability can\n // never default on. Operators may still author one (probe-only, opt-in),\n // they just cannot pre-check the box for a grant that requires a\n // Sensitive/Critical tier. Reject at parse so this can never reach storage.\n //\n // Blast radius beyond direct capability edits: the write path\n // (UpdateBouncerConfigSchema) validates the WHOLE consentConfig on every\n // PUT/PATCH, so a stored row that already violates this rule (one exists\n // in prod today, pre-dating this floor) rejects ANY save that round-trips\n // it unchanged too -- including the dashboard editor's Cache Refresh\n // (ConsentScreenEditor.tsx's handleCacheRefresh, which merges + resubmits\n // the full stored config just to bump a cache-busting timestamp). That is\n // the intended fail-closed behavior, not a bug, but it is a wider surface\n // than \"editing capabilities\" -- an operator on an already-violating\n // project cannot even refresh the cache until the violating row is fixed.\n .superRefine((capability, ctx) => {\n if (requiresSensitiveTier(capability.riskLevel) && capability.defaultOn) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['defaultOn'],\n 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).`,\n });\n }\n });\n\n/**\n * Group of capabilities. Renders as a section in the consent screen.\n */\nexport const ConsentCapabilityGroupSchema = z.object({\n id: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z][a-z0-9._-]*$/),\n label: z.string().min(1).max(80),\n capabilities: z.array(ConsentCapabilitySchema).min(1).max(20),\n});\nexport type ConsentCapabilityGroup = z.infer<typeof ConsentCapabilityGroupSchema>;\n\n/**\n * Agent identity tile data shared between consent + gateway screens.\n */\nexport const ConsentAgentMetadataSchema = z.object({\n name: z.string().min(1).max(80),\n did: z.string().min(1).max(500),\n vendor: z.string().max(80).optional(),\n surfaceLabel: z.string().max(40).optional(),\n // Display-only. NOT authoritative for grant decisions: First-Contact\n // Scope Cap Rules 2 and 3 read first contact and verification from\n // server state (see FirstContactScopeCap resolver in\n // apps/web/lib/bouncer/services), never from this field, because it\n // sits inside the same config object an operator writes. Kept here only\n // so already-stored configs (and any future display use) keep parsing.\n verified: z.boolean(),\n logoUrl: httpUrlSchema(500).optional(),\n // Display-only, same as `verified` above: not consulted for grant\n // decisions.\n connectedAt: z.string().datetime().optional(),\n});\n\n/**\n * Brand copy for one input the consent page asks a person to fill in. Copy\n * only: which inputs appear is the project's consent policy's call (its\n * sign-in methods and assurance providers), never this config's.\n */\nexport const ConsentInputCopySchema = z.object({\n label: z.string().max(80).optional(),\n /** A typed field's placeholder, or the hint line under it where the step has one. */\n hint: z.string().max(200).optional(),\n});\n\nexport const ConsentSignInCopySchema = z.object({\n /** The address field of the email-code and email-and-password sign-ins. */\n email: ConsentInputCopySchema.optional(),\n password: ConsentInputCopySchema.optional(),\n /** The RPPS number step (`registry:fr-rpps`); `prompt` is its heading. */\n rpps: ConsentInputCopySchema.extend({ prompt: z.string().max(120).optional() }).optional(),\n});\n\n/** A consent policy names a handful of scopes; this only bounds the stored map. */\nconst MAX_SCOPE_LABELS = 50;\n\n/**\n * The brand's name for a scope no authored capability covers, keyed by the\n * literal scope. Copy only: unlike a capability, a label here never makes a\n * scope grantable (`allowedScopesFor` does not read it) and carries no Cedar.\n */\nexport const ConsentScopeLabelsSchema = z\n .record(z.string().min(1).max(120), z.string().min(1).max(80))\n .refine(\n (labels) => Object.keys(labels).length <= MAX_SCOPE_LABELS,\n `At most ${MAX_SCOPE_LABELS} scope labels`\n );\n\n/**\n * Full Consent Configuration\n */\nexport const ConsentConfigSchema = z.object({\n branding: ConsentBrandingSchema.optional(),\n terms: ConsentTermsSchema.optional(),\n ui: ConsentUISchema.optional(),\n customFields: z.array(ConsentCustomFieldSchema).optional(),\n metadata: ConsentConfigMetadataSchema.optional(),\n expirationDays: z.number().int().min(1).max(365).optional(),\n // Humanized capability layout (Peter's mockup). When present the deployed\n // server renders the new design-language consent screen; when absent the\n // legacy raw-scope checkboxes are shown.\n capabilities: z.array(ConsentCapabilityGroupSchema).max(20).optional(),\n // Populated server-side only: `UpdateBouncerConfigSchema` (the one\n // write path) unconditionally rejects a write that sets this, so an\n // operator can never self-attest an agent's identity or verification\n // status. Display-only; see `ConsentAgentMetadataSchema` above. NOT\n // consulted by First-Contact Scope Cap Rules 2/3, which read server\n // state instead (apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts).\n agentMetadata: ConsentAgentMetadataSchema.optional(),\n // First-Contact Scope Cap section 3, Rules 2 and 3 opt-in. Per-project,\n // defaults to off/absent so every existing config, and every config that\n // hasn't explicitly opted in, renders byte-identically to before this\n // field existed. Flip to `true` on one project's consentConfig (a\n // normal PUT/PATCH) to turn the probe gate on for that project.\n //\n // This flag is read at RENDER time, not enforced by this schema: Rules 2\n // and 3 are not write-time properties of a config, they depend on who is\n // in front of the screen right now, which this schema has no way to\n // know. See `applyFirstContactScopeCap` in\n // apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts for\n // the actual enforcement, which resolves first contact and verification\n // from server state (delegations, and a verification seam that returns\n // `indeterminate` until a real agent-verification source exists).\n firstContactScopeCapEnabled: z.boolean().optional(),\n consentTheme: z.enum(['light', 'dark']).optional(),\n headlineVerb: z.string().min(1).max(40).optional(),\n revocationPath: z.string().min(1).max(120).optional(),\n inactivityDays: z.number().int().min(1).max(3650).optional(),\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The RESOLVED bare\n // host where this project's consent screen + delegation pickup live (null\n // column → platform default). Surfaced so the consent PEP and the gateway\n // challenge emitter build consent_uri / pickup_uri from config, never a\n // hardcoded host. Populated server-side by `loadConsentConfig`.\n authorizationHost: z.string().min(1).max(255).optional(),\n signInCopy: ConsentSignInCopySchema.optional(),\n scopeLabels: ConsentScopeLabelsSchema.optional(),\n});\nexport type ConsentConfig = z.infer<typeof ConsentConfigSchema>;\n\n/**\n * Bouncer Config (for GET response)\n */\nexport const BouncerConfigSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n\n // Authorization settings\n reputationThreshold: z.number().int().min(0).max(100).default(76),\n allowedScopes: z.array(z.string()).default([]),\n deniedAgents: z.array(z.string()).default([]),\n\n // CRISP budget settings\n crispEnabled: z.boolean().default(false),\n crispBudget: CRISPBudgetSchema.nullable().optional(),\n\n // Multi-provider OAuth configuration (CRED-001)\n oauthProviders: OAuthProvidersMapSchema.default({}),\n defaultProvider: z.string().max(50).nullable().optional(),\n\n // Legacy OAuth configuration (deprecated - use oauthProviders)\n oauthClientId: z.string().max(255).nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(), // Encrypted\n oauthRedirectUri: httpUrlSchema(500).nullable().optional(),\n oauthAuthEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthTokenEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthProviderType: OAuthProviderTypeSchema.default('oauth2'),\n oauthScopes: z.array(ScopeSchema).default([]),\n oauthConnectionStatus: OAuthConnectionStatusSchema.default('disconnected'),\n lastScopesSync: z.string().datetime().nullable().optional(),\n\n // Delegation configuration\n delegationExpirationDays: z.number().int().positive().default(7),\n\n // Consent page configuration\n consentConfig: ConsentConfigSchema.optional(),\n\n // Tool discovery\n discoveredTools: z.record(z.string(), z.unknown()).default({}),\n mcpServerUrl: httpUrlSchema().nullable().optional(),\n mcpWorkerUrl: httpUrlSchema().nullable().optional(),\n\n // Organization settings\n isEnabled: z.boolean().default(false),\n updatedAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n});\nexport type BouncerConfig = z.infer<typeof BouncerConfigSchema>;\n\n/**\n * Update Bouncer Config (for PUT request body)\n */\nexport const UpdateBouncerConfigSchema = z\n .object({\n // Authorization settings\n reputationThreshold: z.number().int().min(0).max(100).optional(),\n allowedScopes: z.array(z.string()).optional(),\n deniedAgents: z.array(z.string()).optional(),\n\n // CRISP budget settings\n crispEnabled: z.boolean().optional(),\n crispBudget: CRISPBudgetSchema.nullable().optional(),\n\n // Multi-provider OAuth configuration (CRED-001)\n defaultProvider: z.string().max(50).nullable().optional(),\n\n // Legacy OAuth configuration (deprecated - use providers endpoint)\n oauthClientId: z.string().max(255).nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(), // Will be encrypted by API\n oauthRedirectUri: httpUrlSchema(500).nullable().optional(),\n oauthAuthEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthTokenEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthProviderType: OAuthProviderTypeSchema.optional(),\n oauthConnectionStatus: OAuthConnectionStatusSchema.optional(),\n\n // Delegation configuration\n delegationExpirationDays: z.number().int().positive().optional(),\n\n // Consent page configuration\n consentConfig: ConsentConfigSchema.optional(),\n\n // MCP Server URL (for manual configuration)\n mcpServerUrl: httpUrlSchema().nullable().optional(),\n\n // Organization settings\n isEnabled: z.boolean().optional(),\n })\n .strict()\n // First-Contact Scope Cap section 3: `agentMetadata` represents facts\n // about a specific requesting agent (identity, verification, connection\n // age), not an operator preference. It has no legitimate writer today (no\n // admin UI, no other backend job sets it), so this is the only place it\n // could ever reach storage. If an operator could submit it here, they\n // could self-attest `verified: true` and any `connectedAt` in the same\n // write that defines their capabilities, defeating Rules 2/3 entirely\n // since nothing else re-checks that claim against a real agent. Reject it\n // unconditionally so a stored `agentMetadata`, if one ever exists, can\n // only have come from a future render-assembly step, never the operator.\n .superRefine((data, ctx) => {\n if (data.consentConfig?.agentMetadata !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['consentConfig', 'agentMetadata'],\n message:\n '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.',\n });\n }\n });\nexport type UpdateBouncerConfig = z.infer<typeof UpdateBouncerConfigSchema>;\n\n/**\n * Refresh Scopes Request\n */\nexport const RefreshScopesRequestSchema = z\n .object({\n mcpServerUrl: httpUrlSchema().optional(),\n })\n .strict();\nexport type RefreshScopesRequest = z.infer<typeof RefreshScopesRequestSchema>;\n\n/**\n * Bouncer Proof Outcome\n */\nconst BouncerOutcomeSchema = z.enum(['success', 'failed', 'blocked', 'error']);\nexport type BouncerOutcome = z.infer<typeof BouncerOutcomeSchema>;\n\n/**\n * Custom URL validator that allows:\n * - Valid URLs (standard URL format)\n * - Empty strings (for optional endpoints)\n * - Placeholder URLs (URLs with {placeholder} patterns like {shop}, {domain})\n */\nconst urlOrPlaceholderSchema = z.string().refine(\n (val) => {\n if (val === '') return true; // Empty string is allowed\n // Check if it's a valid URL\n try {\n new URL(val);\n return true;\n } catch {\n // If not a valid URL, check if it's a placeholder URL (contains {placeholder})\n // Placeholder URLs follow URL structure but have {placeholder} segments\n // Example: https://{shop}.myshopify.com/admin/oauth/authorize\n const placeholderUrlPattern = /^https?:\\/\\/[^\\s]+$/;\n return placeholderUrlPattern.test(val) && val.includes('{') && val.includes('}');\n }\n },\n {\n message:\n 'Must be a valid URL, empty string, or placeholder URL (e.g., https://{shop}.example.com)',\n }\n);\n\n/**\n * OAuth Mode - determines how the OAuth flow is handled\n * - 'direct': KYA-OS handles OAuth directly with IDP (PKCE support, no secret needed)\n * - 'proxy': KYA-OS routes through Checkpoint (keeps client_secret secure server-side)\n */\nexport const OAuthModeSchema = z.enum(['direct', 'proxy']);\n\n/**\n * OAuth Provider Metadata Schema\n * Used for /api/v1/bouncer/projects/{projectId}/providers endpoint\n */\nexport const OAuthProviderMetadataSchema = z.object({\n clientId: z.string().nullable(),\n // SECURITY: clientSecret is intentionally NOT returned in API responses\n // Agents receive only hasClientSecret flag and metadata.clientSecretName for runtime resolution\n hasClientSecret: z.boolean(), // Boolean for quick detection\n authorizationUrl: urlOrPlaceholderSchema, // Allow valid URLs, empty strings, or placeholder URLs\n tokenUrl: urlOrPlaceholderSchema, // Allow valid URLs, empty strings, or placeholder URLs\n userInfoUrl: urlOrPlaceholderSchema.optional(), // Optional per contracts interface\n supportsPKCE: z.boolean(),\n requiresClientSecret: z.boolean(),\n proxyMode: z.boolean().optional(), // Optional per contracts interface (deprecated - use mode)\n scopes: z.array(z.string()).optional(), // Optional per contracts interface\n defaultScopes: z.array(z.string()).optional(), // Optional per contracts interface\n // Phase 3 fields (all optional for backward compatibility)\n customParams: z.record(z.string(), z.string()).optional(),\n tokenEndpointAuthMethod: z.enum(['client_secret_post', 'client_secret_basic']).optional(),\n responseType: z.string().optional(),\n grantType: z.string().optional(),\n // KYA-OS coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)\n configured: z.boolean().optional(), // Whether this provider is configured for the project\n mode: OAuthModeSchema.optional(), // OAuth flow mode: 'direct' (PKCE) or 'proxy' (Checkpoint)\n // KYA-OS Provider Registry: Secret resolution metadata\n metadata: z\n .object({\n clientSecretName: z.string().optional(),\n clientIdSecretName: z.string().optional(),\n apiKeySecretName: z.string().optional(),\n clientSecretVersion: z.number().optional(),\n lastRotatedAt: z.string().optional(),\n })\n .optional(),\n});\nexport type OAuthProviderMetadata = z.infer<typeof OAuthProviderMetadataSchema>;\n\n/**\n * Providers API Response Schema\n * Used for /api/v1/bouncer/projects/{projectId}/providers endpoint\n */\nexport const ProvidersResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n providers: z.record(z.string(), OAuthProviderMetadataSchema),\n configuredProvider: z.string().nullable(),\n }),\n metadata: z.object({\n requestId: z.string(),\n timestamp: z.string().datetime(),\n }),\n});\nexport type ProvidersResponse = z.infer<typeof ProvidersResponseSchema>;\n\n/**\n * OAuth Tokens Response Schema\n * Used for GET /api/v1/bouncer/delegations/{delegationId}/tokens endpoint\n */\nexport const OAuthTokensResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n oauth_access_token: z.string(),\n oauth_refresh_token: z.string().nullable(),\n oauth_expires_at: z.string().datetime().nullable(), // ISO 8601\n oauth_expires_in: z.number().nullable(), // Seconds\n oauth_token_type: z.string(), // Token type (e.g., \"Bearer\")\n oauth_scope: z.string().nullable(), // Granted scopes (space-separated string)\n }),\n metadata: z.object({\n requestId: z.string(),\n timestamp: z.string().datetime(),\n }),\n});\n\n// ==============================================================================\n// PROVIDERS CONFIG ENVELOPE (Provider Registry Alignment)\n// ==============================================================================\n\n/**\n * Checkpoint Provider Definition Schema\n *\n * This is the Checkpoint-specific provider definition used in API responses\n * and configuration. It has field naming differences from the canonical\n * @kya-os/provider-registry ProviderDefinition:\n *\n * | Checkpoint Field | Provider Registry Field | Notes |\n * |---------------------|----------------------------|--------------------------|\n * | type | authType | Both accept 'password' |\n * | authorizationUrl | oauthConfig.authorizationEndpoint | Nested in registry |\n * | tokenUrl | oauthConfig.tokenEndpoint | Nested in registry |\n * | userInfoUrl | oauthConfig.userInfoEndpoint | Nested in registry |\n *\n * SECURITY: This schema NEVER contains actual secret values.\n * Only metadata.clientSecretName (reference to secure storage) is included.\n *\n * @see ProviderRegistryDefinition from @kya-os/provider-registry for canonical format\n */\nconst ProviderDefinitionSchema = z.object({\n id: z.string().min(1),\n type: AuthProviderTypeSchema,\n displayName: z.string().optional(),\n configured: z.boolean().default(false),\n // OAuth2 specific fields (flat structure for API compat)\n authorizationUrl: z.string().optional(),\n tokenUrl: z.string().optional(),\n userInfoUrl: z.string().optional(),\n supportsPKCE: z.boolean().optional(),\n requiresClientSecret: z.boolean().optional(),\n // Credentials (only clientId is safe - NEVER clientSecret)\n clientId: z.string().nullable().optional(),\n hasClientSecret: z.boolean().default(false),\n // Scopes\n scopes: z.array(z.string()).optional(),\n defaultScopes: z.array(z.string()).optional(),\n // Mode\n mode: z.enum(['direct', 'proxy']).optional(),\n // Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\n\n/**\n * Canonical provider definition from @kya-os/provider-registry\n *\n * Re-exported for consumers who need the canonical format.\n */\nexport type { ProviderRegistryDefinition } from './provider-registry';\n\n/**\n * Providers Config Source Metadata\n * Tracks where the config came from for debugging and auditing\n */\nexport const ProvidersConfigSourceSchema = z.object({\n projectId: z.string().uuid(),\n projectFriendlyId: z.string(),\n deployId: z.string().uuid().optional(),\n generatedAt: z.string().datetime(),\n agentShieldVersion: z.string(),\n});\nexport type ProvidersConfigSource = z.infer<typeof ProvidersConfigSourceSchema>;\n\n/**\n * Providers Config Envelope\n *\n * The full signed configuration document served to KYA-OS agents.\n * Includes HMAC signature for tamper detection.\n *\n * SECURITY:\n * - NEVER contains actual secret values (clientSecret, apiKey, etc.)\n * - Agents MUST verify HMAC signature before loading\n * - Agents resolve secrets from secure storage at runtime using metadata.clientSecretName\n */\nexport const ProvidersConfigEnvelopeSchema = z.object({\n // Version for atomic updates (incrementing integer)\n version: z.number().int().positive(),\n // Source metadata for debugging and auditing\n source: ProvidersConfigSourceSchema,\n // Provider definitions (keyed by provider ID)\n providers: z.record(z.string(), ProviderDefinitionSchema),\n // HMAC signature for tamper detection (SHA-256 hex)\n signature: z\n .string()\n .regex(/^[a-f0-9]{64}$/)\n .optional(),\n // Which fields are included in the signature\n signedFields: z.array(z.string()).optional(),\n});\nexport type ProvidersConfigEnvelope = z.infer<typeof ProvidersConfigEnvelopeSchema>;\n","/**\n * Organization Types and Interfaces\n *\n * Types related to organization management, validation, and errors\n */\n\nimport { z } from 'zod';\nimport { httpUrlSchema } from '../schemas/bouncer';\n\nconst organizationDomainSchema = z\n .string()\n .trim()\n .toLowerCase()\n .min(1, 'Domain is required')\n .max(255, 'Domain must be less than 255 characters')\n .regex(\n /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/,\n 'Domain must be a valid hostname'\n );\n\nconst clearableOptionalString = <TSchema extends z.ZodTypeAny>(schema: TSchema) =>\n schema.nullable().optional();\n\nconst HOSTNAME_REGEX = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;\n\n/**\n * Accepted org logo values:\n * - an http(s) image URL (manually pasted), OR\n * - a `d:<domain>` token, which the app resolves to a logo.dev CDN URL at\n * read time (the auto-fetch-from-domain path), OR\n * - '' (and, at the field level, null) to clear.\n *\n * Implemented as a single refined string (not a `z.union`) to avoid Zod\n * union-inference pitfalls (TS2345). The `d:` form is validated against the\n * same hostname rule as claimed domains so a junk value can't be persisted.\n */\nconst organizationLogoSchema = z\n .string()\n .max(500)\n .refine(\n (v) => {\n if (v === '') return true; // explicit clear\n if (v.startsWith('d:')) return HOSTNAME_REGEX.test(v.slice(2));\n return httpUrlSchema(500).safeParse(v).success;\n },\n { message: 'Logo must be an http(s) URL or a d:domain token' }\n );\n\n/**\n * Organization-level SSO provider and policy settings.\n */\nexport const OrganizationSsoProviderSchema = z.enum(['rippling', 'saml']);\nexport type OrganizationSsoProvider = z.infer<typeof OrganizationSsoProviderSchema>;\n\nexport const OrganizationSsoModeSchema = z.enum(['optional', 'required']);\nexport type OrganizationSsoMode = z.infer<typeof OrganizationSsoModeSchema>;\n\nexport const OrganizationSsoSettingsSchema = z\n .object({\n enabled: z.boolean().optional(),\n mode: OrganizationSsoModeSchema.optional(),\n provider: OrganizationSsoProviderSchema.optional(),\n loginUrl: clearableOptionalString(z.string().url('SSO login URL must be a valid URL').max(500)),\n metadataUrl: clearableOptionalString(\n z.string().url('Metadata URL must be a valid URL').max(1000)\n ),\n metadataXml: clearableOptionalString(\n z.string().min(1, 'Metadata XML cannot be empty').max(500000)\n ),\n idpEntityId: clearableOptionalString(z.string().max(1000)),\n idpSsoUrl: clearableOptionalString(z.string().url('IdP SSO URL must be a valid URL').max(1000)),\n domains: z.array(organizationDomainSchema).max(50).optional(),\n allowPasswordFallback: z.boolean().optional(),\n autoProvisionMembers: z.boolean().optional(),\n /**\n * ISO-8601 timestamp of the last successful \"Test connection\". Lets the\n * verified state survive navigation (it's persisted JSON, re-parsed on\n * read — must stay a string, not z.date()). Cleared (null) when a\n * connection-affecting field changes, so a stale verification can't show\n * as current.\n */\n lastVerifiedAt: clearableOptionalString(z.string().datetime()),\n })\n .superRefine((value, ctx) => {\n // Validate strict login URL requirements only when callers explicitly submit\n // a full \"required SSO with no fallback\" configuration in this payload.\n // Partial updates are merged server-side with existing settings.\n const explicitlyRequiresSso =\n value.enabled === true && value.mode === 'required' && value.allowPasswordFallback === false;\n\n if (explicitlyRequiresSso && !value.loginUrl && !value.idpSsoUrl) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['loginUrl'],\n message:\n 'SSO login URL is required when mode is required and password fallback is disabled',\n });\n }\n });\n\n/**\n * Organization settings schema\n */\nexport const OrganizationSettingsSchema = z.object({\n maxProjects: z.number().optional(),\n maxMembers: z.number().optional(),\n /** Whether this is a personal/default organization created for a user */\n isPersonalOrg: z.boolean().optional(),\n sso: OrganizationSsoSettingsSchema.optional(),\n features: z\n .object({\n advancedAnalytics: z.boolean().optional(),\n customBranding: z.boolean().optional(),\n ssoEnabled: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type OrganizationSettings = z.infer<typeof OrganizationSettingsSchema>;\n\n/**\n * Organization role schema and type\n * Single source of truth for runtime validation and TypeScript types.\n * Adding a role here will update both; used when parsing DB role values.\n */\nexport const OrganizationRoleSchema = z.enum(['owner', 'admin', 'member']);\nexport type OrganizationRole = z.infer<typeof OrganizationRoleSchema>;\n\n/**\n * Base organization interface\n */\nexport interface Organization {\n id: string;\n name: string;\n slug: string;\n logoUrl?: string | null;\n settings: OrganizationSettings;\n /**\n * The org's designated primary project — the deterministic default anchor for\n * navigation (land on a chosen project) and the gateway merchant-consent flow.\n * Nullable: unset, or the referenced project was hard-deleted (FK ON DELETE\n * SET NULL). It may still point at a SOFT-deleted project, so resolve through\n * `resolveOrgPrimaryProject` before relying on it rather than reading raw.\n */\n primaryProjectId?: string | null;\n deletedAt?: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Organization with member information\n */\nexport interface OrganizationWithMembers extends Organization {\n members: OrganizationMember[];\n memberCount: number;\n projectCount: number;\n}\n\n/**\n * Organization member interface\n */\nexport interface OrganizationMember {\n organizationId: string;\n userId: string;\n role: OrganizationRole;\n joinedAt: Date;\n user?: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n };\n}\n\n/**\n * User organizations response\n */\nexport interface UserOrganizations {\n organizations: (Organization & { role: OrganizationRole })[];\n defaultOrganizationId?: string;\n}\n\n/**\n * Create organization input with enhanced validation\n */\nexport const CreateOrganizationInputSchema = z.object({\n name: z\n .string()\n .min(2, 'Organization name must be at least 2 characters')\n .max(100, 'Organization name must be less than 100 characters')\n .trim()\n .regex(\n /^[a-zA-Z0-9\\s\\-&.,]+$/,\n 'Organization name can only contain letters, numbers, spaces, hyphens, ampersands, periods, and commas'\n )\n .transform((val) => val.trim()),\n slug: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9-]+$/, 'Slug can only contain lowercase letters, numbers, and hyphens')\n .optional(),\n settings: OrganizationSettingsSchema.optional(),\n});\n\nexport type CreateOrganizationInput = z.infer<typeof CreateOrganizationInputSchema>;\n\n/**\n * Update organization input\n */\nexport const UpdateOrganizationInputSchema = z.object({\n name: z\n .string()\n .min(2, 'Organization name must be at least 2 characters')\n .max(100, 'Organization name must be less than 100 characters')\n .trim()\n .regex(\n /^[a-zA-Z0-9\\s\\-&.,]+$/,\n 'Organization name can only contain letters, numbers, spaces, hyphens, ampersands, periods, and commas'\n )\n .transform((val) => val.trim())\n .optional(),\n logoUrl: organizationLogoSchema.nullable().optional(),\n // REASON: single refined string (max 500) — http(s) URL, d:<hostname>, or '' to clear.\n settings: OrganizationSettingsSchema.optional(),\n});\n\nexport type UpdateOrganizationInput = z.infer<typeof UpdateOrganizationInputSchema>;\n\n/**\n * Organization error codes\n */\nexport enum OrganizationErrorCode {\n NAME_DUPLICATE = 'ORG_NAME_DUPLICATE',\n SLUG_DUPLICATE = 'ORG_SLUG_DUPLICATE',\n NOT_FOUND = 'ORG_NOT_FOUND',\n ACCESS_DENIED = 'ORG_ACCESS_DENIED',\n LIMIT_EXCEEDED = 'ORG_LIMIT_EXCEEDED',\n INVALID_NAME = 'ORG_INVALID_NAME',\n OPERATION_FAILED = 'ORG_OPERATION_FAILED',\n}\n\n/**\n * Organization suggestion for similar names\n */\nexport interface OrganizationSuggestion {\n id: string;\n name: string;\n slug: string;\n similarity: number; // 0-100 percentage\n}\n\n/**\n * Validation helpers\n */\nexport function normalizeOrganizationName(name: string): string {\n return name.trim().toLowerCase();\n}\n","/**\n * Authorization Host resolution — draft-kya-http-02 §7 (H1.1 #3244).\n *\n * The **Authorization Host** is the per-project host that renders the\n * delegation consent screen and serves delegation pickup. Every PEP\n * (Policy Enforcement Point) config payload — routing entry, gateway\n * config, policy config, bouncer config — carries the RESOLVED host so a\n * PEP can build a challenge's `consent_uri` / `pickup_uri` against it.\n * Per spec §7, PEPs MUST read it from config and never hardcode it.\n *\n * Representation: a **bare host** (no scheme, no trailing slash), matching\n * the spec's `authorization_host` field (e.g. `auth.merchant.com`). The\n * challenge emitter (H2.1-WF) prepends `https://` and the path, exactly as\n * the golden fixtures show: `authorization_host=\"auth.merchant.com\"` →\n * `consent_uri=\"https://auth.merchant.com/consent?sid=…\"`.\n *\n * Resolution rule:\n * - project value set → org-branded host (e.g. `authenticate.acme.com`)\n * - project value null → the platform default host\n *\n * This module is intentionally pure (no env access): each caller supplies\n * its own `platformDefaultHost` so the Next.js web app (NEXT_PUBLIC_APP_URL)\n * and the Fly gateway can each resolve against the host they front. The\n * `DEFAULT_AUTHORIZATION_HOST` constant is the last-resort fallback when a\n * caller has no configured origin.\n */\n\n/**\n * Last-resort platform Authorization Host (bare host) when a caller passes no\n * `platformDefaultHost`. Mirrors the web app's production origin\n * (`https://kya.vouched.id`) reduced to its host.\n *\n * NOTE for non-web callers (Fly gateway, edge worker): you MUST pass your own\n * `platformDefaultHost` to {@link resolveAuthorizationHost}. This constant is a\n * web-origin fallback only — relying on it from another deployment silently\n * brands every unset project as the web app instead of the host you front.\n */\nexport const DEFAULT_AUTHORIZATION_HOST = 'kya.vouched.id';\n\n/**\n * Reduce an origin or host string to a normalized bare host: strips any\n * `http(s)://` scheme and trailing slashes, then lower-cases it. Hosts are\n * case-insensitive, so lower-casing keeps two equivalent configs byte-identical\n * on the wire (the golden fixtures are lower-case). Idempotent on values that\n * are already bare + lower-case.\n *\n * `https://Kya.Vouched.id/` → `kya.vouched.id`\n * `authenticate.acme.com` → `authenticate.acme.com`\n *\n * Normalization only — it does NOT validate. Use {@link isValidAuthorizationHost}\n * at the write boundary to reject paths, userinfo, whitespace, and bad labels.\n */\nexport function toBareHost(value: string): string {\n const withoutScheme = value.trim().replace(/^https?:\\/\\//i, '');\n // Strip trailing slashes with a linear scan rather than `/\\/+$/` — that\n // anchored, unbounded-repetition regex is a polynomial-ReDoS vector on\n // host strings with many trailing slashes (CodeQL js/polynomial-redos).\n let end = withoutScheme.length;\n while (end > 0 && withoutScheme.charCodeAt(end - 1) === 47 /* '/' */) {\n end--;\n }\n return withoutScheme.slice(0, end).toLowerCase();\n}\n\n/**\n * Validate that a value is a usable Authorization Host: it becomes the\n * authority of an `https://<host>/…` challenge URI, so anything that smuggles\n * a path, query, fragment, userinfo (`@`), or whitespace would silently produce\n * a broken or misdirected consent URL. After scheme/slash normalization the\n * value must be a bare `host[:port]` of RFC 1123 labels (`:port` allowed for\n * dev). Reject everything else at the write boundary.\n *\n * `authenticate.acme.com` → true\n * `localhost:3000` → true\n * `authenticate.acme.com/evil` → false (path)\n * `legit.com@evil.com` → false (userinfo)\n * `bad host.com` / `-acme.com` → false (whitespace / bad label)\n */\nexport function isValidAuthorizationHost(value: string): boolean {\n const bare = toBareHost(value);\n if (!bare || bare.length > 255) return false;\n // No path / query / fragment / userinfo / backslash / whitespace.\n if (/[/\\\\?#@\\s]/.test(bare)) return false;\n\n const parts = bare.split(':');\n if (parts.length > 2) return false; // at most one `:port`\n const [host, port] = parts;\n if (port !== undefined) {\n // A port must be 1-65535. The `1*5DIGIT` shape alone let \"99999\" through;\n // range-check it so an out-of-range port can't become a URL authority.\n if (!/^\\d{1,5}$/.test(port)) return false;\n const portNum = Number(port);\n if (portNum < 1 || portNum > 65535) return false;\n }\n if (host.length === 0 || host.length > 253) return false;\n\n // RFC 1123 labels: 1-63 of [a-z0-9-], no leading/trailing hyphen. The bounded\n // {0,61} keeps this linear (no catastrophic backtracking).\n const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n return host.split('.').every((l) => label.test(l));\n}\n\n/**\n * Resolve a project's effective Authorization Host as a bare host.\n *\n * @param authorizationHost - the `projects.authorization_host` column value\n * (null/blank → use the platform default).\n * @param platformDefaultHost - the caller's platform origin or host, used\n * when the project has no override. Defaults to\n * {@link DEFAULT_AUTHORIZATION_HOST}.\n */\nexport function resolveAuthorizationHost(\n authorizationHost: string | null | undefined,\n platformDefaultHost: string = DEFAULT_AUTHORIZATION_HOST\n): string {\n const override = authorizationHost?.trim();\n return toBareHost(override && override.length > 0 ? override : platformDefaultHost);\n}\n","import { z } from 'zod';\nimport {\n MAX_POSTURE_ORIGINS,\n MAX_POSTURE_ORIGIN_LENGTH,\n validatePostureOrigins,\n} from '../posture-origins';\n\n/**\n * `settings.postureOrigins` on a project write: the additional page origins\n * browser posture may be issued for. Validated and NORMALIZED by the one\n * shared resolver (`../posture-origins`), so what the settings APIs store is\n * exactly what the issuer and gateway later match. Each rejected entry\n * surfaces as its own issue at `[index]` with a readable message, which the\n * routes return in their 400 `details`.\n */\nexport const PostureOriginsSchema = z\n .array(z.string().max(MAX_POSTURE_ORIGIN_LENGTH))\n .max(MAX_POSTURE_ORIGINS)\n .transform((origins, ctx) => {\n const result = validatePostureOrigins(origins);\n if (result.ok) return result.origins;\n for (const error of result.errors) {\n ctx.addIssue({\n code: 'custom',\n message: error.message,\n path: error.index >= 0 ? [error.index] : [],\n });\n }\n return z.NEVER;\n });\n","import { z } from 'zod';\n\nexport const MAX_POSTURE_REPORT_PATHS = 50;\nexport const MAX_POSTURE_REPORT_PATH_LENGTH = 200;\n\nconst WHITESPACE = /\\s/;\n\nfunction isAllowedPathCharacter(char: string): boolean {\n const code = char.charCodeAt(0);\n return code > 0x1f && code !== 0x7f && char !== '?' && char !== '#' && !WHITESPACE.test(char);\n}\n\nexport function normalizePostureReportPath(input: string): string | null {\n const trimmed = input.trim();\n if (trimmed.length > MAX_POSTURE_REPORT_PATH_LENGTH || !trimmed.startsWith('/')) return null;\n return [...trimmed].every(isAllowedPathCharacter) ? trimmed : null;\n}\n\nexport const PostureReportPathsSchema = z\n .array(z.string().max(MAX_POSTURE_REPORT_PATH_LENGTH * 2))\n .max(MAX_POSTURE_REPORT_PATHS)\n .transform((paths, ctx) => {\n const normalized: string[] = [];\n let valid = true;\n paths.forEach((path, index) => {\n const value = normalizePostureReportPath(path);\n if (value === null) {\n valid = false;\n ctx.addIssue({\n code: 'custom',\n message: `Enter a path that starts with / and has no spaces, ? or # (up to ${MAX_POSTURE_REPORT_PATH_LENGTH} characters)`,\n path: [index],\n });\n return;\n }\n if (!normalized.includes(value)) normalized.push(value);\n });\n return valid ? normalized : z.NEVER;\n });\n\nexport function readPostureReportPathsSetting(settings: unknown): string[] {\n if (!settings || typeof settings !== 'object') return [];\n const raw = (settings as { postureReportPaths?: unknown }).postureReportPaths;\n if (!Array.isArray(raw)) return [];\n const paths: string[] = [];\n for (const entry of raw.slice(0, MAX_POSTURE_REPORT_PATHS)) {\n if (typeof entry !== 'string') continue;\n const value = normalizePostureReportPath(entry);\n if (value !== null && !paths.includes(value)) paths.push(value);\n }\n return paths;\n}\n","/**\n * Internal API Schemas\n *\n * Schemas for internal dashboard API endpoints\n * Used for validation and type safety in internal routes\n */\n\nimport type { JWK } from 'jose';\nimport { z } from 'zod';\nimport { PAGINATION_DEFAULTS } from '../constants';\nimport {\n ApiKeyPermissionSchema,\n ApiKeyRateLimitsSchema,\n PixelConfigurationSchema,\n} from '../types/entities';\nimport {\n CreateOrganizationInputSchema,\n UpdateOrganizationInputSchema,\n} from '../types/organization';\nimport { isValidAuthorizationHost } from '../mcpi/authorization-host';\nimport { PostureOriginsSchema } from '../types/posture-origins-schema';\nimport { PostureReportPathsSchema } from '../types/posture-report-paths-schema';\n\n/**\n * Flexible Project ID Schema\n * Accepts UUID format, kta- format, and friendly ID format\n *\n * \"Friendly ID format\" covers two shapes: a slug-suffix pair (e.g.\n * \"my-project-a1b2c3\") minted only to disambiguate a name collision, and a\n * bare slug with no suffix (e.g. \"my-project\"): the common case, minted by\n * apps/web's resolveUniqueFriendlyProjectId whenever a project's name is\n * unique. The bare-slug branch is capped at 20 characters to match\n * slugify()'s own truncation (apps/web/lib/utils/project-id.ts), so this\n * doesn't also swallow unrelated garbage (e.g. a truncated UUID) that\n * happens to be lowercase-alnum-and-hyphens shaped.\n */\nexport const ProjectIdSchema = z.string().refine(\n (val) => {\n // UUID v4 format\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n // Legacy kta- format (kta-XXXXXX where X is alphanumeric)\n const ktaIdRegex = /^kta-[a-z0-9]{6}$/;\n // Friendly ID format (slug-suffix, e.g., \"my-project-a1b2c3\")\n const friendlyIdRegex = /^[a-z0-9-]+-[a-z0-9]{6}$/;\n // Bare slug, no suffix (e.g. \"my-project\")\n const bareSlugRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n return (\n uuidRegex.test(val) ||\n ktaIdRegex.test(val) ||\n friendlyIdRegex.test(val) ||\n (val.length <= 20 && bareSlugRegex.test(val))\n );\n },\n {\n message:\n 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., \"my-project-a1b2c3\" or \"my-project\")',\n }\n);\n\n/**\n * Flexible Organization ID Schema\n * Accepts UUID format and slug format (e.g., \"kya-os-kerjid\")\n * Mirrors ProjectIdSchema pattern for consistency\n */\nexport const OrganizationIdSchema = z.string().refine(\n (val) => {\n // UUID v4 format (all versions, not just v4)\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n // Organization slug format (lowercase alphanumeric with hyphens, e.g., \"kya-os-kerjid\")\n const slugRegex = /^[a-z0-9-]+$/i;\n return uuidRegex.test(val) || slugRegex.test(val);\n },\n {\n message: 'Invalid organization ID format. Must be a UUID or slug (e.g., \"kya-os-kerjid\")',\n }\n);\n\n/**\n * Common Query Parameters Schema\n * Used across multiple internal endpoints for pagination and filtering\n */\nexport const QuerySchema = z.object({\n page: z.coerce.number().min(1).default(1).optional(),\n limit: z.coerce\n .number()\n .min(1)\n .max(PAGINATION_DEFAULTS.maxPageSize)\n .default(PAGINATION_DEFAULTS.defaultPageSize)\n .optional(),\n sortBy: z.string().optional(),\n order: z.enum(['asc', 'desc']).default('desc').optional(),\n search: z.string().optional(),\n});\nexport type QueryParams = z.infer<typeof QuerySchema>;\n\n/**\n * Non-sensitive KYA-OS configuration projection returned by organization-wide\n * deployment inventory endpoints. Values are deliberately empty; consumers\n * use only the keys to count configured providers and discovered tools.\n */\nexport interface KyaosDeploymentInventoryConfig {\n oauthProviders: Record<string, Record<string, never>>;\n discoveredTools: Record<string, Record<string, never>>;\n}\n\n/**\n * Projects Schemas\n */\nexport const CreateProjectSchema = z.object({\n name: z.string().min(1).max(255),\n domain: z.string().optional(), // Changed: removed .url() validation to be more lenient\n organizationId: z.string().uuid().optional(), // Optional - backend uses auth session as fallback\n // Setup Flow v2 step 1 (\"What brings you here?\") — the stable\n // SetupV2NeedDef.id keys the user selected (apps/web's\n // lib/setup-v2/flow-types.ts owns the id -> label/product mapping; this\n // shared package only validates shape, not membership, matching\n // settings.allowedOrigins/blockedAgents below). Optional: only the\n // setup-v2 flow ever sends it.\n setupGoals: z.array(z.string().min(1).max(100)).max(50).optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\nexport type CreateProjectRequest = z.infer<typeof CreateProjectSchema>;\n\nexport const UpdateProjectSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n domain: z.string().optional(), // Changed: removed .url() validation to be more lenient\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The org-branded\n // bare host (e.g. `authenticate.acme.com`) that renders consent + serves\n // delegation pickup for this project. Empty string clears it → the web-app\n // platform default. This value becomes a challenge URI authority, so it's\n // validated strictly (no path / userinfo / whitespace / bad labels) rather\n // than left lenient like `domain` — see `isValidAuthorizationHost`.\n authorizationHost: z\n .string()\n .max(255)\n .refine((v) => v === '' || isValidAuthorizationHost(v), {\n message:\n 'Authorization host must be a bare hostname (e.g. authenticate.acme.com), optionally with a :port — no scheme path, \"@\", or spaces',\n })\n .optional(),\n // Detection retention window (project settings page). Min 7 enforced\n // here (application layer), not a DB CHECK — see schema.ts's column\n // comment. Default lives on the column (365), not here, so an update\n // that omits this field never resets an existing project's window.\n detectionRetentionDays: z.number().int().min(7).max(3650).optional(),\n // Per-project consent for publishing this project's agent site-visit\n // interactions to Know That AI's PUBLIC activity feed (project settings\n // page). Omitted on update leaves the column's own default/current value\n // untouched, same convention as detectionRetentionDays above.\n publishSiteVisitToKnowThatAi: z.boolean().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n beaconRateLimitPerMinute: z.number().int().positive().optional(),\n // Additional page origins browser posture may be issued for, beyond\n // the primary derived from `domain`. Replaces the stored list; send\n // `[]` to clear it. Normalized by the shared resolver.\n postureOrigins: PostureOriginsSchema.optional(),\n postureReportPaths: PostureReportPathsSchema.optional(),\n })\n .optional(),\n});\nexport type UpdateProjectRequest = z.infer<typeof UpdateProjectSchema>;\n\n/**\n * Pixels Schemas\n */\nexport const CreatePixelSchema = z.object({\n projectId: ProjectIdSchema,\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n isActive: z.boolean().default(true),\n configuration: PixelConfigurationSchema.optional(),\n});\nexport type CreatePixelRequest = z.infer<typeof CreatePixelSchema>;\n\nexport const UpdatePixelSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n isActive: z.boolean().optional(),\n configuration: PixelConfigurationSchema.optional(),\n});\nexport type UpdatePixelRequest = z.infer<typeof UpdatePixelSchema>;\n\n/**\n * API Keys Schemas\n */\n\nexport const CreateApiKeySchema = z.object({\n name: z.string().min(1).max(255),\n projectId: ProjectIdSchema.optional(),\n permissions: z.array(ApiKeyPermissionSchema).default(['read']),\n rateLimits: ApiKeyRateLimitsSchema.optional(),\n expiresAt: z.string().datetime().optional(),\n});\nexport type CreateApiKeyRequest = z.infer<typeof CreateApiKeySchema>;\n\nexport const UpdateApiKeySchema = z.object({\n name: z.string().min(1).max(255).optional(),\n permissions: z.array(ApiKeyPermissionSchema).optional(),\n rateLimits: ApiKeyRateLimitsSchema.optional(),\n expiresAt: z.string().datetime().optional().nullable(),\n});\nexport type UpdateApiKeyRequest = z.infer<typeof UpdateApiKeySchema>;\n\n/**\n * Marketplace Provisioning Schemas\n *\n * Contract for the internal `POST/DELETE /api/provisioning/keys` endpoint that the\n * KYA-OS Integrations Platform (Vercel/Netlify/… adapters) calls to mint and revoke a\n * per-resource KYA-OS project + API key. Idempotent on (source, externalId, resourceId).\n */\n\n/** Provider kinds that can drive provisioning. Grows as adapters are added. */\nexport const MarketplaceSourceSchema = z.enum([\n 'vercel',\n 'shopify',\n 'netlify',\n 'railway',\n 'shopware',\n 'mixer',\n]);\nexport type MarketplaceSource = z.infer<typeof MarketplaceSourceSchema>;\n\n/** Enforcement posture — mirrors the SDK's `enforcementMode` ('observe' = detect-only). */\nexport const ProvisioningModeSchema = z.enum(['observe', 'enforce']);\nexport type ProvisioningMode = z.infer<typeof ProvisioningModeSchema>;\n\n/** Backend-verifiable installer identity. Caller-supplied verification flags confer no authority. */\nexport const ProvisioningIdentityProofSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('vercel-oidc'), token: z.string().min(1).max(16384) }),\n z.object({ type: z.literal('railway-oauth'), accessToken: z.string().min(1).max(16384) }),\n z.object({ type: z.literal('checkpoint-account-link'), token: z.string().min(1).max(16384) }),\n]);\nexport type ProvisioningIdentityProof = z.infer<typeof ProvisioningIdentityProofSchema>;\n\n/** A signed account-link capability issued only from the installer's authenticated session. */\nexport const ProvisioningAccountLinkRequestSchema = z.object({\n source: MarketplaceSourceSchema,\n externalId: z.string().min(1).max(255),\n resourceId: z.string().min(1).max(255).optional(),\n});\nexport type ProvisioningAccountLinkRequest = z.infer<typeof ProvisioningAccountLinkRequestSchema>;\n\nexport const ProvisioningAccountLinkResponseSchema = z.object({\n identityProof: z.object({ type: z.literal('checkpoint-account-link'), token: z.string().min(1) }),\n expiresIn: z.literal(600),\n});\nexport type ProvisioningAccountLinkResponse = z.infer<typeof ProvisioningAccountLinkResponseSchema>;\n\nexport const ProvisionKeyRequestSchema = z.object({\n identityProof: ProvisioningIdentityProofSchema.optional(),\n source: MarketplaceSourceSchema,\n /** Provider installation/configuration id (e.g. Vercel configurationId). */\n externalId: z.string().min(1).max(255),\n /**\n * Provider resource id (e.g. one Vercel project); idempotency key with (source, externalId).\n * Single-resource providers repeat `externalId` here rather than inventing a sentinel — a\n * Shopware shop, for instance, has no sub-resource comparable to a Vercel project, so its\n * triple is ('shopware', shopId, shopId). Intentional, not a caller bug.\n */\n resourceId: z.string().min(1).max(255),\n /** Human-readable label for the dashboard (e.g. \"Vercel / team_xxx / my-project\"). */\n label: z.string().min(1).max(200),\n /** Installer email must match the identity established by identityProof. */\n owner: z.object({\n email: z.string().email(),\n name: z.string().min(1).max(255).optional(),\n }),\n /** Recorded on the provision for the dashboard; the SDK's enforcementMode is code-level today. */\n mode: ProvisioningModeSchema.default('observe'),\n /**\n * Org the installer chose in the adapter UI. Treated as a HINT: the backend binds the\n * installation to it and mints there only when the resolved user OWNS or ADMINISTERS it\n * (matching the orgs the list endpoint surfaces) — otherwise it falls back to the personal\n * org (owner/admin backstop in `mintWithinTx`). Omitted = legacy behavior (personal/default\n * org).\n */\n organizationId: z.string().uuid().optional(),\n /** Optional non-secret provider context (teamId, userId, resource name). */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ProvisionKeyRequest = z.infer<typeof ProvisionKeyRequestSchema>;\n\nexport const ProvisionKeyResponseSchema = z.object({\n /**\n * Plaintext API key — injected by the adapter as CHECKPOINT_API_KEY. Returned once on mint;\n * on idempotent re-provision the same key is returned (decrypted from storage).\n */\n apiKey: z.string().min(1),\n /** The KYA-OS project the key is scoped to. */\n projectId: z.string().uuid(),\n /** The API key row id (revoke is keyed by source/externalId/resourceId, not this). */\n apiKeyId: z.string().uuid(),\n organizationId: z.string().uuid(),\n /** True when an existing provision was returned rather than a new one created. */\n idempotent: z.boolean(),\n});\nexport type ProvisionKeyResponse = z.infer<typeof ProvisionKeyResponseSchema>;\n\n/**\n * Request for `POST /api/provisioning/sso-link` — the \"Open in Provider\" handoff.\n * The backend verifies `ownerEmail` using provider evidence or an authenticated account-link ticket.\n */\nexport const SsoLinkRequestSchema = z.object({\n identityProof: ProvisioningIdentityProofSchema.optional(),\n source: MarketplaceSourceSchema,\n /** Provider installation/configuration id (e.g. Vercel configurationId). */\n externalId: z.string().min(1).max(255),\n /** Optional provider resource id — present → deep-link to that project; absent → org landing. */\n resourceId: z.string().min(1).max(255).optional(),\n /** Installer email must match the identity established by identityProof. */\n ownerEmail: z.string().email(),\n});\nexport type SsoLinkRequest = z.infer<typeof SsoLinkRequestSchema>;\n\nexport const SsoLinkResponseSchema = z.object({\n /** Ready-to-redirect URL: the integration 302s the browser here. Establishes the session and lands on the friendly-id dashboard route. */\n url: z.string().min(1),\n});\nexport type SsoLinkResponse = z.infer<typeof SsoLinkResponseSchema>;\n\n/**\n * DELETE query for `/api/provisioning/keys`. Omitting `resourceId` revokes ALL keys for the\n * installation (the uninstall path); supplying it revokes a single resource.\n */\nexport const RevokeProvisionQuerySchema = z.object({\n source: MarketplaceSourceSchema,\n externalId: z.string().min(1).max(255),\n resourceId: z.string().min(1).max(255).optional(),\n});\nexport type RevokeProvisionQuery = z.infer<typeof RevokeProvisionQuerySchema>;\n\nexport const RevokeProvisionResponseSchema = z.object({\n /** Number of provisions revoked (0 if nothing matched — DELETE is idempotent). */\n revoked: z.number().int().nonnegative(),\n});\nexport type RevokeProvisionResponse = z.infer<typeof RevokeProvisionResponseSchema>;\n\n/**\n * Provisioning Organization-Selection Schemas\n *\n * Contract for the service-authenticated org chooser the KYA-OS Integrations adapter\n * (Vercel/…) drives so an installer can pick which Checkpoint org to link — or create a\n * new one — instead of always landing in their default/personal org. The end user is\n * identified ONLY by the verified `email` (the account-linking key); never a session.\n * - `POST /api/provisioning/organizations/list` → { organizations }\n * - `POST /api/provisioning/organizations` → { organization }\n * Both authenticate with the `sk_service_provisioning_` service key and wrap the payloads\n * below in the standard `{ success, data }` envelope at the route.\n */\n\n/** Roles the adapter may bind an installation to — an installer can only choose an org they administer. */\nexport const ProvisioningOrganizationRoleSchema = z.enum(['owner', 'admin']);\nexport type ProvisioningOrganizationRole = z.infer<typeof ProvisioningOrganizationRoleSchema>;\n\n/** One org the resolved user owns or administers (the adapter's `OrganizationSummary`). */\nexport const ProvisioningOrganizationSummarySchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n slug: z.string(),\n role: ProvisioningOrganizationRoleSchema,\n});\nexport type ProvisioningOrganizationSummary = z.infer<typeof ProvisioningOrganizationSummarySchema>;\n\n/** List a user's administrable orgs by verified email. No user match ⇒ `{ organizations: [] }`. */\nexport const ListProvisioningOrganizationsRequestSchema = z.object({\n source: MarketplaceSourceSchema.optional(),\n externalId: z.string().min(1).max(255).optional(),\n resourceId: z.string().min(1).max(255).optional(),\n identityProof: ProvisioningIdentityProofSchema.optional(),\n email: z.string().email(),\n});\nexport type ListProvisioningOrganizationsRequest = z.infer<\n typeof ListProvisioningOrganizationsRequestSchema\n>;\n\nexport const ListProvisioningOrganizationsResponseSchema = z.object({\n organizations: z.array(ProvisioningOrganizationSummarySchema),\n});\nexport type ListProvisioningOrganizationsResponse = z.infer<\n typeof ListProvisioningOrganizationsResponseSchema\n>;\n\n/**\n * Create an org for a (found-or-created) user by verified email. `name`/`slug` reuse the\n * dashboard's `CreateOrganizationInputSchema` validators so the service + session paths\n * accept exactly the same input.\n */\nexport const CreateProvisioningOrganizationRequestSchema = z.object({\n source: MarketplaceSourceSchema.optional(),\n externalId: z.string().min(1).max(255).optional(),\n resourceId: z.string().min(1).max(255).optional(),\n identityProof: ProvisioningIdentityProofSchema.optional(),\n email: z.string().email(),\n name: CreateOrganizationInputSchema.shape.name,\n slug: CreateOrganizationInputSchema.shape.slug,\n});\nexport type CreateProvisioningOrganizationRequest = z.infer<\n typeof CreateProvisioningOrganizationRequestSchema\n>;\n\nexport const CreateProvisioningOrganizationResponseSchema = z.object({\n /** The just-created org; `role` is always `owner` (the creator is inserted as owner). */\n organization: ProvisioningOrganizationSummarySchema,\n});\nexport type CreateProvisioningOrganizationResponse = z.infer<\n typeof CreateProvisioningOrganizationResponseSchema\n>;\n\n/**\n * Organizations Schemas\n * Using enhanced schemas from organization types\n */\nexport const CreateOrganizationSchema = CreateOrganizationInputSchema;\nexport type CreateOrganizationRequest = z.infer<typeof CreateOrganizationSchema>;\n\nexport const UpdateOrganizationSchema = UpdateOrganizationInputSchema;\nexport type UpdateOrganizationRequest = z.infer<typeof UpdateOrganizationSchema>;\n\n/**\n * Analytics Schemas\n */\nexport const AnalyticsQuerySchema = z.object({\n projectId: ProjectIdSchema.optional(),\n pixelId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n timeWindow: z\n .enum(['realtime', 'hourly', 'daily', 'weekly', 'monthly'])\n .default('daily')\n .optional(),\n groupBy: z.enum(['hour', 'day', 'week', 'month']).optional(),\n aiAgentsOnly: z.coerce.boolean().optional(),\n});\nexport type AnalyticsQueryRequest = z.infer<typeof AnalyticsQuerySchema>;\n\nexport const ExportAnalyticsSchema = z.object({\n projectId: ProjectIdSchema.optional(),\n organizationId: z.string().uuid().optional(),\n pixelId: z.string().uuid().optional(),\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n format: z.enum(['csv', 'json']).default('csv'),\n sections: z\n .array(z.enum(['overview', 'traffic', 'agents', 'confidence', 'sessions']))\n .optional()\n .default(['overview', 'traffic', 'agents']),\n includeRawData: z.boolean().optional().default(false),\n showAIAgentsOnly: z.boolean().optional().default(false),\n});\nexport type ExportAnalyticsRequest = z.infer<typeof ExportAnalyticsSchema>;\n\n/**\n * Settings Schemas\n */\nexport const UpdateSettingsSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n // No `email`: roles are derived from the stored address (partner service\n // and superadmin allowlists), so it must not change without proof of the\n // new mailbox. PUT /api/internal/settings refuses a body that carries one.\n // Note: Plan updates would typically be handled through billing/subscription endpoints\n});\nexport type UpdateSettingsRequest = z.infer<typeof UpdateSettingsSchema>;\n\nexport const DeleteAccountSchema = z.object({\n confirmation: z.literal('DELETE_MY_ACCOUNT'),\n});\nexport type DeleteAccountRequest = z.infer<typeof DeleteAccountSchema>;\n\n/**\n * Specialized Query Schemas\n */\nexport const ProjectsQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'updatedAt', 'name']).default('createdAt').optional(),\n // Accept both UUID and slug format for organization ID\n organizationId: OrganizationIdSchema.optional(),\n});\nexport type ProjectsQueryParams = z.infer<typeof ProjectsQuerySchema>;\n\nexport const PixelsQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'updatedAt', 'name']).default('createdAt').optional(),\n projectId: ProjectIdSchema.optional(),\n isActive: z.coerce.boolean().optional(),\n});\nexport type PixelsQueryParams = z.infer<typeof PixelsQuerySchema>;\n\nexport const ApiKeysQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'lastUsedAt', 'name']).default('createdAt').optional(),\n projectId: ProjectIdSchema.optional(),\n organizationId: z.string().uuid().optional(),\n includeRevoked: z.coerce.boolean().default(false).optional(),\n});\nexport type ApiKeysQueryParams = z.infer<typeof ApiKeysQuerySchema>;\n\n/**\n * Response Schemas\n */\nexport const PaginatedResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.boolean(),\n data: z.array(itemSchema),\n pagination: z.object({\n page: z.number(),\n limit: z.number(),\n total: z.number(),\n totalPages: z.number(),\n hasMore: z.boolean(),\n }),\n });\n\nexport const SingleItemResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.boolean(),\n data: itemSchema,\n });\n\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false),\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }),\n});\nexport type ErrorResponse = z.infer<typeof ErrorResponseSchema>;\n\n/**\n * Generic Response Types\n */\nexport type SuccessResponse<T> = {\n success: true;\n data: T;\n};\n\nexport type PaginatedData<T> = {\n items: T[];\n pagination: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n };\n};\n\nexport type PaginatedResponse<T> = {\n success: true;\n data: T[];\n pagination: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n // Optional field for client-side filtered results\n filteredCount?: number;\n };\n};\n\n/**\n * Analytics Response Types\n */\nexport type TimeSeriesPoint = {\n timestamp: string | Date;\n total: number;\n agents: number;\n humans: number;\n avgConfidence: number;\n // Session-based metrics\n totalSessions: number;\n agentSessions: number;\n humanSessions: number;\n // Separated bot and AI agent sessions\n botSessions: number;\n aiAgentSessions: number;\n};\n\nexport type AgentTypeDistribution = {\n agentType: string;\n count: number;\n uniqueSessions: number;\n avgConfidence: number;\n // Surfaced from the agent_types leftJoin so callers can filter on the\n // canonical category (e.g. 'ai_assistant') without re-running the JS\n // string heuristic in `lib/utils/agent-category.ts`. Optional because\n // a leftJoin miss returns null at runtime; consumers treat falsy as\n // \"unknown\" (#2275). Other join columns the route emits\n // (agentTypeId, displayName, isLegitimate, lastSeen) are intentionally\n // omitted — downstream consumers model those locally with stricter\n // shapes that conflict with the leftJoin nullability.\n category?: string;\n};\n\nexport type PixelStatsData = {\n pixel: {\n id: string;\n name: string;\n };\n detectionCount: number;\n agentCount: number;\n};\n\nexport type ConfidenceRange = {\n range: string;\n count: number;\n};\n\nexport type AnalyticsOverview = {\n totalDetections: number;\n totalAgents: number;\n averageConfidence: number;\n uniqueSessions: number;\n // Add unique session breakdowns to avoid double-counting\n uniqueAgentSessions?: number;\n uniqueHumanSessions?: number;\n uniqueBotSessions?: number;\n uniqueAIAgentSessions?: number;\n uniqueIncompleteDataSessions?: number;\n mostActiveHour?: {\n hour: number;\n detections: number;\n label: string;\n };\n detectionChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n sessionChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n aiAgentChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n botChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n humanChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n};\n\nexport type AnalyticsDetailRange = {\n start: string;\n end: string;\n lastDay: string;\n};\n\nexport type AnalyticsUnavailableField = {\n field:\n | 'hourlyDistribution'\n | 'mostActiveHour'\n | 'confidenceDistribution'\n | 'topPages'\n | 'topPixels';\n reason: 'raw_detail_history';\n requestedRange: AnalyticsDetailRange;\n availableRange: AnalyticsDetailRange | null;\n};\n\nexport type AnalyticsSessionCounting = 'per_utc_day';\n\nexport type AnalyticsMeta = {\n source?: string;\n aiAgentsOnly?: boolean;\n lastUpdated?: string;\n rollupCount?: number;\n current?: boolean;\n sessionCounting?: AnalyticsSessionCounting;\n};\n\nexport type AnalyticsData = {\n overview: AnalyticsOverview;\n timeSeries: TimeSeriesPoint[];\n agentTypes: AgentTypeDistribution[];\n topPixels: PixelStatsData[];\n confidenceDistribution: ConfidenceRange[];\n dateRange: {\n start: string;\n end: string;\n };\n unavailable?: AnalyticsUnavailableField[];\n _meta?: AnalyticsMeta;\n};\n\n/**\n * Project Response Types\n */\nexport type ProjectWithStats = {\n id: string;\n friendlyId?: string | null;\n userId: string;\n organizationId?: string | null;\n name: string;\n domain?: string | null;\n /**\n * `projects.authorization_host`: the bare host consent is served on, or null\n * for the platform default. Returned by GET /api/internal/projects/[id].\n */\n authorizationHost?: string | null;\n /** Detection retention window in days (project settings page). Default 365, minimum 7. */\n detectionRetentionDays?: number;\n /** Whether this project's site-visit interactions publish to Know That AI's public activity feed. Default true. */\n publishSiteVisitToKnowThatAi?: boolean;\n /** Set once \"Browser posture\" is enabled for this project — never the private key itself. */\n postureKeyId?: string | null;\n posturePublicKey?: JWK | null;\n /** Cloudflare Turnstile site key (gateway-enforcement-step-up, build item\n * 6) — public, safe to send to the dashboard. Presence is the\n * \"configured\" flag; the secret key never leaves the server. */\n turnstileSiteKey?: string | null;\n settings: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n userAccessLevel?: 'owner' | 'admin' | 'editor' | 'viewer' | null;\n stats: {\n pixelCount: number;\n detectionCount: number;\n sessionCount: number;\n weeklySessionCount: number;\n weeklyAgentSessionCount: number;\n lastDetection: Date | null;\n recentDetections?: number;\n recentAgents?: number;\n /**\n * Per-day session counts over the trailing 7 days (oldest first).\n * Always length 7 — days with no rollup row fill as 0 so the\n * sparkline renders a continuous timeline rather than a gappy\n * one. Drives the project card's sparkline.\n */\n dailySessions?: number[];\n /**\n * Total sessions in the **previous** 7-day window (days 8-14 ago).\n * Used to derive the week-over-week trend % on the project card.\n *\n * Note: this is the value used as the DENOMINATOR of the\n * trend calculation. When zero, no honest % can be computed\n * (division undefined) — the renderer drops the trend pill.\n */\n prevWeekSessionCount?: number;\n };\n};\n\n/**\n * Pixel Response Types\n */\nexport type PixelWithStats = {\n id: string;\n projectId: string;\n name: string;\n secretKey: string;\n configuration: Record<string, unknown>;\n isActive: boolean;\n createdAt: Date;\n updatedAt: Date;\n // Matches the actual shape returned by GET /api/internal/pixels:\n // `detectionCount` is the trigger-maintained ALL-TIME total and\n // `lastDetection` the trigger-maintained last-detection timestamp (both\n // denormalized pixels columns, no detections scan); `recentDetections` is\n // a live 24h rolling count. There is no per-agent/per-session breakdown\n // at this endpoint (see `/api/internal/pixels/[pixelId]` for the richer\n // single-pixel shape, which this type does not describe).\n stats?: {\n detectionCount: number;\n recentDetections: number;\n lastDetection: Date | null;\n };\n};\n\n/**\n * Settings Response Types\n */\nexport type UserUsage = {\n projects: {\n used: number;\n limit: number;\n percentage: number;\n };\n pixels: {\n used: number;\n limit: number;\n percentage: number;\n };\n apiKeys: {\n used: number;\n limit: number;\n percentage: number;\n };\n};\n\nexport type PlanLimits = {\n projects: number;\n pixelsPerProject: number;\n apiKeys: number;\n teamMembers: number;\n dataRetentionDays: number;\n customDomains: number;\n webhooks: number;\n alertRules: number;\n sessionsTracked: number;\n exportSizeLimit: number;\n};\n\nexport type PlanFeatures = {\n customDomains: boolean;\n webhooks: boolean;\n alertRules: boolean;\n teamMembers: boolean;\n unlimitedProjects: boolean;\n unlimitedPixels: boolean;\n unlimitedApiKeys: boolean;\n};\n\n/**\n * Dashboard Stats Types\n */\nexport type DashboardStatItem = {\n current: number;\n previous?: number;\n percentageChange?: number;\n};\n\nexport type DashboardStatsResponse = {\n domains: {\n current: number;\n activeProjects: number;\n inactiveProjects: number;\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n totalSessions: DashboardStatItem & {\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n agentSessions: DashboardStatItem & {\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n sessionBreakdown?: {\n botSessions: number;\n humanSessions: number;\n incompleteDataSessions: number;\n };\n /**\n * Distinct agent types seen in the last 7 days across the org's\n * projects. Computed from a 14-day detections scan with PG `FILTER`\n * clauses so `current` and `previous` are produced in a single pass.\n * Optional fields preserve backwards compatibility with older\n * response payloads that emitted `current` only.\n */\n uniqueAgents?: DashboardStatItem;\n /**\n * Distinct users seen in the last 7 days across the org's AI-agent\n * detections. Same 14-day single-scan strategy as uniqueAgents.\n * Tier-coalesced identity (email > userId > ipAddress > 'unattributed').\n */\n uniqueUsers?: DashboardStatItem;\n};\n\nexport const DashboardStatsRequestSchema = z.object({\n organizationId: z.string().uuid().optional(),\n});\nexport type DashboardStatsRequest = z.infer<typeof DashboardStatsRequestSchema>;\n\n/* ─────────────────────────────────────────────────────────────────────\n Home-rail rollups — single payload for the four rollup-backed v2\n home-rail widgets (NOW, AGENT MIX, ACTIVE HOURS, CONFIDENCE).\n Service: apps/web/lib/services/analytics/home-rail-rollups.service.ts\n Route: GET /api/internal/home-rail/rollups\n ────────────────────────────────────────────────────────────────── */\n\n/** YYYY-MM-DD slot inside the 7-day sparkline / heatmap window. */\nexport interface HomeRailDailyPoint {\n /** UTC date as YYYY-MM-DD — same shape as the rollup column. */\n date: string;\n totalSessions: number;\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n /** 24-element histogram of distinct sessions per hour-of-day (UTC). */\n hourDistribution: number[];\n}\n\n/** Aggregated metrics over a 7-day window. */\nexport interface HomeRailWindowAggregate {\n totalSessions: number;\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n totalDetections: number;\n highConfidenceDetections: number;\n /**\n * Detection-weighted avg confidence — sum of (per-day avg × per-day\n * detections) / sum of detections. Reads honest even when one day\n * has 10x the traffic of the others.\n *\n * Cross-class — includes both ai_agent and bot detections, matching\n * how `organization_rollups.avg_confidence` is computed. For an\n * AI-only confidence number, use `HomeRailRollupsResponse.aiAgent7d`.\n */\n avgConfidence: number;\n}\n\n/**\n * AI-agent-only aggregate over the same 7-day window as `current7d`.\n *\n * Sourced from `agent_daily_rollup` filtered to `detection_class =\n * 'ai_agent'`, summed across all of the org's projects in the window.\n * Uses `totalConfidenceSum / detections` for the detection-weighted\n * average — same shape as `agent_daily_rollup.avg_confidence` math in\n * top-agents.service.ts.\n *\n * Why a separate aggregate (not a field on `current7d`)?\n * - `current7d` reads from `organization_rollups`, whose confidence\n * column is cross-class by design (and the schema comment warns\n * against narrowing only the numerator).\n * - `agent_daily_rollup` has the per-class breakdown we need, but\n * it's keyed per (project, agent_type, class, date) instead of\n * (org, date) — different scan, different aggregate.\n *\n * `high_confidence_detections` is *not* available per-class in the\n * rollups today, so the AI-only response only carries the avg and\n * the total. Surfacing a ratio bar honestly would require a new\n * column + backfill (F-05 follow-up).\n */\nexport interface HomeRailAiAgentAggregate {\n totalDetections: number;\n avgConfidence: number;\n}\n\nexport interface HomeRailRollupsResponse {\n today: HomeRailDailyPoint;\n current7d: HomeRailWindowAggregate;\n previous7d: HomeRailWindowAggregate;\n /** 7 daily points covering the current 7d window, ordered oldest → newest. */\n trend7d: HomeRailDailyPoint[];\n /**\n * AI-agent-only aggregate over the current 7d window. Powers\n * `ConfidenceWidget`, which deliberately scopes to AI agents (the\n * cross-class number in `current7d.avgConfidence` reads as\n * \"AI + bot confidence\" and was confusing operators).\n */\n aiAgent7d: HomeRailAiAgentAggregate;\n /** Newest `refreshedAt` across the read rows; null when no rows exist. */\n refreshedAt: string | null;\n /** Current 7d window bounds, UTC dates as YYYY-MM-DD. */\n windowStart: string;\n windowEnd: string;\n}\n\n// Accepts slug or UUID — matches the route's\n// `PermissionService.resolveOrganizationAccess` resolver and the\n// dashboard's URL pattern (orgs are navigated via slugs). The previous\n// `z.string().uuid()` constraint would have rejected every dashboard\n// call at runtime had any consumer validated input against this shared\n// schema (cursor-bot flagged the divergence on 6ceea5f24).\nexport const HomeRailRollupsRequestSchema = z.object({\n organizationId: OrganizationIdSchema,\n});\nexport type HomeRailRollupsRequest = z.infer<typeof HomeRailRollupsRequestSchema>;\n\nexport type SettingsData = {\n user: {\n id: string;\n email: string;\n name?: string | null;\n image?: string | null;\n plan?: string | null;\n emailVerified?: Date | null;\n createdAt: Date;\n updatedAt: Date;\n };\n usage: UserUsage;\n planLimits: PlanLimits;\n features: PlanFeatures;\n};\n\n/**\n * API Key Response Types\n */\nexport type ApiKeyWithProject = {\n id: string;\n userId: string;\n projectId?: string | null;\n name: string;\n key: string;\n permissions: string[];\n rateLimits: Record<string, unknown>;\n lastUsedAt?: Date | null;\n expiresAt?: Date | null;\n createdAt: Date;\n revokedAt?: Date | null;\n project?: {\n id: string;\n name: string;\n } | null;\n};\n","/**\n * Detection signal exposure: the wire shape of the \"full signal set\"\n * block on the `/api/v1/enforce` detection response (KYA-1107, \"Adobe\n * Golden Snapshot\").\n *\n * Every enforce detection payload carries these fields in addition to the\n * condensed summary fields. Additive only: consumers must ignore keys they\n * do not know (every current consumer was verified lenient to unknown keys\n * before this became unconditional).\n *\n * This schema is the SSOT for the exposed shape:\n * - the generated reference (`docs/architecture/detection-signal-exposure.generated.md`)\n * is derived from the `.describe()` strings here by\n * `scripts/generate-signal-exposure-docs.ts`, CI-gated so docs and wire\n * cannot drift (`detection-signal-exposure-check.yml`, same pattern as\n * the error-code and reason-code registries);\n * - the golden example `fixtures/detection/signal-exposure-example.json`\n * is parsed against it in `__tests__/signal-exposure.test.ts`.\n *\n * Extension point: `signals[]` is deliberately the ONLY place new detection\n * capabilities surface. A future signal family (request-velocity, platform\n * bot-management corroboration, …) ships as new `signals[].source` values\n * plus new `detection/*` reason codes (both additive), so this shape never\n * needs a breaking change to absorb them.\n */\nimport { z } from 'zod';\n\nimport { ConfidenceLevelSchema } from '../core/confidence';\nimport { DetectionSignalSchema } from '../core/detection';\nimport { DetectionReasonCodeSchema } from '../core/detection-reason-code-schema';\nimport { RiskScoreSchema, RiskScoreSourceSchema } from '../core/risk-score';\n\nexport { DetectionReasonCodeSchema };\n\n/**\n * The exposure block, spread flat onto the enforce response's\n * `detection` object (NOT nested) so it stays symmetric with the gateway\n * plane's detection detail, where `signals` already rides inline.\n */\nexport const DetectionSignalExposureSchema = z.object({\n signals: z\n .array(DetectionSignalSchema)\n .describe(\n \"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.\"\n ),\n reasonCodes: z\n .array(DetectionReasonCodeSchema)\n .min(1)\n .describe(\n '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.'\n ),\n confidenceLevel: ConfidenceLevelSchema.optional().describe(\n \"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).\"\n ),\n isAiCrawler: z\n .boolean()\n .optional()\n .describe(\n 'True when the engine classified the client as an AI training crawler (GPTBot, ClaudeBot, …) rather than an interactive agent. Omitted when the engine did not run.'\n ),\n riskScore: RiskScoreSchema.optional().describe(\n 'The Noisy-Or probability that the request is automated (0-1, two decimals), uncalibrated (see riskScoreSource), derived from detectionDetail.metadata.shadow_noisy_or_confidence. Null when the combiner did not run. Distinct from `confidence` above, which is never derived from it.'\n ),\n riskScoreSource: RiskScoreSourceSchema.optional().describe(\n \"Which metadata key riskScore was derived from: 'uncalibrated' (always true today) or 'calibrated' (not yet wired). Null exactly when riskScore is null.\"\n ),\n});\nexport type DetectionSignalExposure = z.infer<typeof DetectionSignalExposureSchema>;\n","/**\n * Fingerprint API Types and Schemas\n *\n * Comprehensive type definitions for the fingerprinting system\n * used to detect and analyze bot/AI agent characteristics\n */\n\nimport { z } from 'zod';\n\n/**\n * Fingerprint analysis result\n */\nexport const FingerprintAnalysisSchema = z.object({\n // Detection results\n hasChromiumHeaders: z.boolean(),\n hasBrowserHeaders: z.boolean(),\n hasSecFetchHeaders: z.boolean(),\n isAutomated: z.boolean(),\n suspiciousPatterns: z.array(z.string()),\n confidence: z.number().min(0).max(1),\n detectedAgent: z.string(),\n\n // Additional detection flags\n isLikelyBot: z.boolean().optional(),\n isLikelyAI: z.boolean().optional(),\n isLikelyClaude: z.boolean().optional(),\n\n // Detailed detection\n detection: z\n .object({\n isAutomatedBrowser: z.boolean().optional(),\n isPuppeteer: z.boolean().optional(),\n isPlaywright: z.boolean().optional(),\n isHeadless: z.boolean().optional(),\n hasWebDriverApi: z.boolean().optional(),\n isLikelyMCPTool: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type FingerprintAnalysis = z.infer<typeof FingerprintAnalysisSchema>;\n\n/**\n * Comprehensive fingerprint response\n */\nexport const FingerprintResponseSchema = z.object({\n timestamp: z.string(),\n method: z.string(),\n url: z.string(),\n path: z.string(),\n queryParams: z.record(z.string(), z.string()),\n headers: z.record(z.string(), z.string()),\n headerCount: z.number(),\n ip: z.string(),\n httpVersion: z.string(),\n\n // Analysis results\n fingerprint: FingerprintAnalysisSchema,\n\n // Detailed analysis\n analysis: z.object({\n userAgent: z.string(),\n acceptHeader: z.string(),\n acceptLanguage: z.string(),\n acceptEncoding: z.string(),\n hasReferer: z.boolean(),\n hasCookies: z.boolean(),\n hasAuthorization: z.boolean(),\n secChUa: z.string(),\n secChUaMobile: z.string(),\n secChUaPlatform: z.string(),\n secFetchSite: z.string(),\n secFetchMode: z.string(),\n secFetchDest: z.string(),\n }),\n\n // Detection summary\n detection: z.object({\n isLikelyBot: z.boolean(),\n isLikelyAI: z.boolean(),\n agentType: z.string(),\n confidence: z.string(),\n }),\n\n // For POST requests\n body: z.unknown().optional(),\n bodyType: z.string().optional(),\n contentType: z.string().optional(),\n});\n\nexport type FingerprintResponse = z.infer<typeof FingerprintResponseSchema>;\n\n/**\n * TLS fingerprint data\n */\nexport const TLSFingerprintSchema = z.object({\n version: z.string().optional(),\n cipherSuites: z.array(z.string()).optional(),\n extensions: z.array(z.string()).optional(),\n supportedGroups: z.array(z.string()).optional(),\n signatureAlgorithms: z.array(z.string()).optional(),\n ja3: z.string().optional(),\n ja3s: z.string().optional(),\n});\n\nexport type TLSFingerprint = z.infer<typeof TLSFingerprintSchema>;\n\n/**\n * Network timing data\n */\nexport const NetworkTimingSchema = z.object({\n dns: z.number().optional(),\n tcp: z.number().optional(),\n tls: z.number().optional(),\n ttfb: z.number().optional(),\n download: z.number().optional(),\n total: z.number().optional(),\n});\n\nexport type NetworkTiming = z.infer<typeof NetworkTimingSchema>;\n","/**\n * Shopify Integration Types\n *\n * Type definitions for Shopify app integration endpoints and data structures\n */\n\nimport { z } from 'zod';\nimport { PostureOriginsSchema } from './posture-origins-schema';\n\n/**\n * Shopify Project Provision Request\n */\nexport const ShopifyProjectProvisionRequestSchema = z.object({\n domain: z.string().min(1).max(255),\n email: z.string().email(),\n name: z.string().min(1).max(255),\n source: z.string().optional().default('shopify_app'),\n});\n\nexport type ShopifyProjectProvisionRequest = z.infer<typeof ShopifyProjectProvisionRequestSchema>;\n\n/**\n * Shopify Project Provision Result\n */\nexport const ShopifyProjectProvisionResultSchema = z.object({\n projectId: z.string().uuid(),\n friendlyId: z.string(),\n pixelId: z.string().uuid(),\n apiKey: z.string(),\n domain: z.string(),\n status: z.literal('active'),\n createdAt: z.string().datetime(),\n // User account information (for Shopify merchants)\n user: z.object({\n email: z.string().email(),\n userId: z.string().uuid(),\n accountCreated: z.boolean(), // true = new account, false = existing\n welcomeEmailSent: z.boolean(),\n setupTokenExpiry: z.string().datetime().nullable(),\n }),\n});\n\nexport type ShopifyProjectProvisionResult = z.infer<typeof ShopifyProjectProvisionResultSchema>;\n\n/**\n * Shopify Threat Information\n * Now represents a session (grouped by consolidated_session_id) rather than individual detections\n */\nexport const ShopifyThreatSchema = z.object({\n sessionId: z.string(), // consolidated_session_id for session grouping\n timestamp: z.string().datetime(), // lastSeen timestamp for the session\n type: z.string(), // agent type (e.g., \"ChatGPT\", \"Claude\")\n ip: z.string(),\n userAgent: z.string(),\n action: z.string(),\n pagesVisited: z.number().int().nonnegative(), // Count of unique pages visited in session\n});\n\nexport type ShopifyThreat = z.infer<typeof ShopifyThreatSchema>;\n\n/**\n * Pagination Information\n */\nexport const PaginationInfoSchema = z.object({\n page: z.number().int().positive(),\n limit: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n hasMore: z.boolean(),\n});\n\n/** The three session classes of the ai_agent > bot > human priority partition. */\nexport const ShopifySessionClassSchema = z.enum(['ai_agent', 'bot', 'human']);\n\n/**\n * One visit (consolidated session) of the stats window, returned with\n * `include=sessions`. Carries no IP, user agent or device data.\n */\nexport const ShopifySessionSchema = z.object({\n sessionId: z.string().describe('Consolidated session id (UUID).'),\n firstSeenAt: z\n .string()\n .datetime()\n .describe('ISO-8601 instant of the first detection of the session in the window.'),\n lastSeenAt: z\n .string()\n .datetime()\n .describe('ISO-8601 instant of the latest detection of the session in the window.'),\n eventCount: z\n .number()\n .int()\n .nonnegative()\n .describe('Detections of the session in the window, every class included.'),\n detectionClass: ShopifySessionClassSchema.describe(\n 'Session class by priority: ai_agent if any detection is an AI agent, else bot if any is a bot, else human.'\n ),\n agentName: z\n .string()\n .nullable()\n .describe('Agent type of the latest detection of the session class that names one.'),\n agentCategory: z.string().nullable().describe('Agent category of that same detection.'),\n geoCountry: z\n .string()\n .nullable()\n .describe('ISO 3166-1 alpha-2 country of the latest detection that has one.'),\n uniquePathCount: z\n .number()\n .int()\n .nonnegative()\n .describe('Distinct request paths of the session in the window.'),\n paths: z.array(z.string()).describe('Distinct request paths in first-arrival order, at most 25.'),\n});\n\nexport type ShopifySession = z.infer<typeof ShopifySessionSchema>;\n\n/** Pagination of `sessions`. `total` is exact; `totalPages` stops at the highest page accepted (200). */\nexport const ShopifySessionsPaginationSchema = z.object({\n page: z.number().int().positive(),\n limit: z.number().int().positive(),\n total: z\n .number()\n .int()\n .nonnegative()\n .describe(\n 'Sessions matching `sessionsClass` in the window: equal to the headline count for that class (`totalRequests` with no class).'\n ),\n totalPages: z\n .number()\n .int()\n .nonnegative()\n .describe('`min(ceil(total / limit), 200)`: the last page `sessionsPage` accepts.'),\n hasMore: z.boolean().describe('True when `page < totalPages`.'),\n});\n\nexport type ShopifySessionsPagination = z.infer<typeof ShopifySessionsPaginationSchema>;\n\nexport const ShopifyStatsResponseSchema = z.object({\n totalRequests: z.number().int().nonnegative(),\n blockedBots: z.number().int().nonnegative(),\n allowedRequests: z.number().int().nonnegative(),\n crawlerSessions: z.number().int().nonnegative().optional(),\n humanSessions: z.number().int().nonnegative().optional(),\n unidentifiedSessions: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe(\n 'Sessions in the window with no ai_agent, bot or human detection and at least one incomplete-data detection that carries the no_evidence basis: an idle visitor the engine had nothing to weigh. They are counted in `totalRequests` and `humanSessions`, so this says how many of the human sessions the engine could not classify. Sessions whose incomplete-data detections all have another reason, such as suspicious headers, are in no counter. A window over 31 days is counted the same way, one UTC day at a time, from the daily rollups. Omitted when the session split is unavailable: a window over 31 days served from a cached result that predates the split, and older deployments.'\n ),\n threatLevel: z.enum(['low', 'medium', 'high']),\n recentThreats: z.array(ShopifyThreatSchema),\n pagination: PaginationInfoSchema,\n sessions: z.array(ShopifySessionSchema).optional(),\n sessionsPagination: ShopifySessionsPaginationSchema.optional(),\n});\n\nexport type ShopifyStatsResponse = z.infer<typeof ShopifyStatsResponseSchema>;\n\n/**\n * Shopify Project Settings Update Request\n */\nexport const ShopifyProjectSettingsUpdateSchema = z.object({\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n // The store's domains (primary + custom), synced by the Shopify app so\n // shoppers on a custom domain get browser posture. Replaces the stored\n // list; the app merges with what is already there before sending.\n postureOrigins: PostureOriginsSchema.optional(),\n })\n .optional(),\n});\n","/**\n * Shared SDK event contracts.\n */\n\nimport { z } from 'zod';\nimport type { RequestContext } from '../core/detection';\n\n/**\n * Context attached to SDK lifecycle events.\n */\nexport type SdkEventContext = RequestContext;\n\n/**\n * Cookie/header-backed session data emitted when an AI agent session continues.\n */\nexport const SdkSessionDataSchema = z.object({\n id: z.string(),\n agent: z.string(),\n confidence: z.number(),\n detectedAt: z.number(),\n expires: z.number(),\n});\nexport type SdkSessionData = z.infer<typeof SdkSessionDataSchema>;\n\nexport type SdkMetricValue = string | number | boolean | null | undefined;\nexport type SdkMetricTags = Record<string, SdkMetricValue>;\n","/**\n * Real-time event types\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\n\n/**\n * Real-time event types\n */\nexport const RealtimeEventTypeSchema = z.enum([\n 'detection',\n 'blocked',\n 'allowed',\n 'error',\n 'pattern_update',\n 'config_change',\n 'stats_update',\n]);\nexport type RealtimeEventType = z.infer<typeof RealtimeEventTypeSchema>;\n\n/**\n * Base real-time event\n */\nexport const RealtimeEventSchema = z.object({\n type: RealtimeEventTypeSchema,\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.any(),\n});\nexport type RealtimeEvent = z.infer<typeof RealtimeEventSchema>;\n\n/**\n * Detection event\n */\nexport const DetectionEventSchema = z.object({\n type: z.literal('detection'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n result: DetectionResultSchema,\n request: z.object({\n userAgent: z.string(),\n ipAddress: z.string().optional(),\n url: z.string().optional(),\n }),\n }),\n});\nexport type DetectionEvent = z.infer<typeof DetectionEventSchema>;\n\n/**\n * Block event\n */\nexport const BlockEventSchema = z.object({\n type: z.literal('blocked'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n reason: z.string(),\n agentType: z.string(),\n confidence: z.number(),\n ipAddress: z.string().optional(),\n url: z.string().optional(),\n }),\n});\nexport type BlockEvent = z.infer<typeof BlockEventSchema>;\n\n/**\n * Stats update event\n */\nexport const StatsUpdateEventSchema = z.object({\n type: z.literal('stats_update'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n period: z.enum(['minute', 'hour', 'day']),\n totalRequests: z.number(),\n agentsDetected: z.number(),\n averageConfidence: z.number(),\n }),\n});\nexport type StatsUpdateEvent = z.infer<typeof StatsUpdateEventSchema>;\n\n/**\n * Event emitter interface\n */\nexport interface EventEmitter {\n emit(event: RealtimeEvent): void;\n on(type: RealtimeEventType, handler: (event: RealtimeEvent) => void): void;\n off(type: RealtimeEventType, handler: (event: RealtimeEvent) => void): void;\n}\n","/**\n * Managed Agent Deployment + Compute Process Contracts (checkpoint-owned subset)\n *\n * Schemas for the managed hosting tier (agents on Fly.io) and the\n * `@kya-os/compute` ⇄ Checkpoint heartbeat/config/control protocol.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/agent-deployment` +\n * `@kya-os/contracts/compute` as part of the E6 / C-series decommission\n * (#2914 / #2917). Only the symbols re-exported by\n * `apps/web/lib/types/molti-deploy-contracts.ts` (plus their transitive deps —\n * `DidStringSchema`, the compute command sub-schemas) are ported.\n *\n * @module @kya-os/checkpoint-shared/deploy\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Cross-repo endpoint contract\n// ============================================================================\n\n/**\n * The KYA-OS activity-events ingest path (SPEC-EVENTS v0.1 batch endpoint).\n *\n * This is a CROSS-REPO CONTRACT. The Tier 2 worker runtime\n * (`@kya-os/mcp-i-cloudflare`) POSTs `tool.invoked` (and the other SPEC-EVENTS\n * types) to `${AGENTSHIELD_API_URL}${KYA_OS_EVENTS_PATH}`, authenticated by the\n * project API key. Checkpoint serves the batch ingest at this exact path\n * (`apps/web/app${KYA_OS_EVENTS_PATH}/route.ts`) and fans events out into the\n * `detections` table behind `/activity`.\n *\n * Managed deploy deliberately injects NO `KYA_OS_EVENTS_*` secret and relies on\n * this derivation instead, so the two sides agree only by matching this literal.\n * Changing it on either side silently drops all managed activity — it is pinned\n * by a contract test. Keep this value and the worker's derivation in sync.\n */\nexport const KYA_OS_EVENTS_PATH = '/api/v1/kya-os/events';\n\n// ============================================================================\n// Shared Schemas\n// ============================================================================\n\n/**\n * Validated DID string schema.\n * Reusable across all contract files that reference agent DIDs.\n *\n * Format: `did:<method>:<method-specific-id>`\n * - method: 1+ lowercase alphanumeric chars\n * - method-specific-id: 1+ non-whitespace chars\n *\n * Examples: `did:key:z6Mk...`, `did:web:example.com`\n */\nexport const DidStringSchema = z\n .string()\n .min(8, 'DID must be at least 8 characters')\n .regex(/^did:[a-z0-9]+:\\S+$/, 'DID must match format did:<method>:<method-specific-id>');\n\n/**\n * Fly.io deployment regions.\n * Enumerated to prevent arbitrary strings from being accepted.\n * @see https://fly.io/docs/reference/regions/\n */\nexport const FlyRegionSchema = z.enum([\n 'ams', // Amsterdam, Netherlands\n 'arn', // Stockholm, Sweden\n 'atl', // Atlanta, Georgia (US)\n 'bog', // Bogotá, Colombia\n 'bos', // Boston, Massachusetts (US)\n 'cdg', // Paris, France\n 'den', // Denver, Colorado (US)\n 'dfw', // Dallas, Texas (US)\n 'ewr', // Secaucus, NJ (US)\n 'eze', // Ezeiza, Argentina\n 'fra', // Frankfurt, Germany\n 'gdl', // Guadalajara, Mexico\n 'gig', // Rio de Janeiro, Brazil\n 'gru', // São Paulo, Brazil\n 'hkg', // Hong Kong\n 'iad', // Ashburn, Virginia (US)\n 'jnb', // Johannesburg, South Africa\n 'lax', // Los Angeles, California (US)\n 'lhr', // London, United Kingdom\n 'mad', // Madrid, Spain\n 'mia', // Miami, Florida (US)\n 'nrt', // Tokyo, Japan\n 'ord', // Chicago, Illinois (US)\n 'otp', // Bucharest, Romania\n 'phx', // Phoenix, Arizona (US)\n 'qro', // Querétaro, Mexico\n 'scl', // Santiago, Chile\n 'sea', // Seattle, Washington (US)\n 'sin', // Singapore\n 'sjc', // San Jose, California (US)\n 'syd', // Sydney, Australia\n 'waw', // Warsaw, Poland\n 'yul', // Montreal, Canada\n 'yyz', // Toronto, Canada\n]);\n\nexport type FlyRegion = z.infer<typeof FlyRegionSchema>;\n\n/**\n * Hosting mode discriminator — differentiates between deploy backends:\n * - `byok`: self-managed deploy in the customer's own Cloudflare account\n * (customer runs the deploy themselves).\n * - `managed`: platform-managed deploy in our Cloudflare account via Workers\n * for Platforms (dispatch namespace).\n * - `managed-byoa`: platform-managed deploy that lands in the customer's own\n * (\"bring your own account\") Cloudflare account via the standard Workers API,\n * after the org connects Cloudflare over OAuth/token (KYA-906-C).\n */\nexport const HostingModeSchema = z.enum(['byok', 'managed', 'managed-byoa']);\n\nexport type HostingMode = z.infer<typeof HostingModeSchema>;\n\n// ============================================================================\n// Protocol audit deployment contract\n// ============================================================================\n\nexport const AuditAssuranceProfileSchema = z.enum(['AAP-0', 'AAP-1', 'AAP-2', 'AAP-3', 'AAP-4']);\nexport const AuditDeliveryModeSchema = z.enum(['best-effort', 'buffered', 'required']);\n\n/**\n * Serializable request contract shared by the wizard and every deploy lane.\n * `requestedProfile` is intent, never an assurance claim. Only readiness\n * evaluation against observed runtime capabilities yields `effectiveProfile`.\n */\nexport const AuditDeploymentConfigSchema = z\n .object({\n enabled: z.boolean(),\n requestedProfile: AuditAssuranceProfileSchema,\n delivery: AuditDeliveryModeSchema,\n evidenceMode: z.enum(['none', 'encrypted-separate', 'encrypted-inline']),\n retentionClass: z.string().min(1).max(128),\n retentionDays: z.number().int().min(0).max(3650),\n residency: z.enum(['inherit-project', 'us', 'eu', 'global']),\n keyCustody: z.enum(['none', 'checkpoint-managed', 'customer-managed-kms']),\n recorderTopology: z.enum(['none', 'self-hosted', 'managed', 'verified-mirror']),\n })\n .strict()\n .superRefine((value, context) => {\n if (!value.enabled && value.requestedProfile !== 'AAP-0') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['requestedProfile'],\n message: 'Disabled audit configuration must request AAP-0',\n });\n }\n if (value.enabled && value.requestedProfile === 'AAP-0') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['requestedProfile'],\n message: 'Enabled audit configuration must request AAP-1 or higher',\n });\n }\n if (Number(value.requestedProfile.slice(-1)) >= 2 && value.delivery === 'best-effort') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['delivery'],\n message: 'AAP-2 or higher cannot use best-effort delivery',\n });\n }\n if (!value.enabled && (value.keyCustody !== 'none' || value.recorderTopology !== 'none')) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Disabled audit configuration cannot claim key custody or recorder topology',\n });\n }\n });\n\nexport type AuditDeploymentConfig = z.infer<typeof AuditDeploymentConfigSchema>;\nexport type AuditAssuranceProfile = z.infer<typeof AuditAssuranceProfileSchema>;\n\n/** Applied only when a user starts a new platform-managed deployment. */\nexport const NEW_MANAGED_AUDIT_DEPLOYMENT_DEFAULT: Readonly<AuditDeploymentConfig> = Object.freeze({\n enabled: true,\n requestedProfile: 'AAP-2',\n delivery: 'buffered',\n evidenceMode: 'encrypted-separate',\n retentionClass: 'integrity-ledger',\n retentionDays: 365,\n residency: 'inherit-project',\n keyCustody: 'checkpoint-managed',\n recorderTopology: 'managed',\n});\n\n/**\n * Missing audit config in an already persisted manifest is always AAP-0.\n * This prevents a dashboard or redeploy from silently upgrading old workers.\n */\nexport const ABSENT_AUDIT_DEPLOYMENT_CONFIG: Readonly<AuditDeploymentConfig> = Object.freeze({\n enabled: false,\n requestedProfile: 'AAP-0',\n delivery: 'best-effort',\n evidenceMode: 'none',\n retentionClass: 'none',\n retentionDays: 0,\n residency: 'inherit-project',\n keyCustody: 'none',\n recorderTopology: 'none',\n});\n\nexport const AuditRuntimeCapabilitiesSchema = z\n .object({\n recorderTopology: z.enum(['none', 'self-hosted', 'managed', 'verified-mirror']),\n delivery: AuditDeliveryModeSchema,\n journalDurability: z.enum(['none', 'ephemeral', 'durable']),\n atomicAppend: z.boolean(),\n sourceHighWater: z.boolean(),\n merkleCheckpoints: z.boolean(),\n independentObservation: z.boolean(),\n supportingAnchors: z.array(z.enum(['worm', 'rfc3161', 'scitt'])),\n evidenceRetention: z.enum(['none', 'inline', 'separate']),\n })\n .strict();\n\nexport type AuditRuntimeCapabilities = z.infer<typeof AuditRuntimeCapabilitiesSchema>;\n\nexport const AuditRuntimeCanaryResultSchema = z\n .object({\n passed: z.boolean(),\n observedAt: z.number().int().nonnegative(),\n capabilities: AuditRuntimeCapabilitiesSchema,\n checks: z\n .array(\n z\n .object({\n id: z.string().min(1).max(128),\n passed: z.boolean(),\n })\n .strict()\n )\n .min(1),\n bundleHash: z.string().min(1).max(256).optional(),\n })\n .strict()\n .superRefine((value, context) => {\n if (value.passed !== value.checks.every((check) => check.passed)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['passed'],\n message: 'Canary result must equal the aggregate of its mechanical checks',\n });\n }\n });\n\nexport type AuditRuntimeCanaryResult = z.infer<typeof AuditRuntimeCanaryResultSchema>;\n\nexport function requiredAuditRuntimeCanaryChecks(capabilities: AuditRuntimeCapabilities): string[] {\n const checks = [\n 'recorder_round_trip',\n 'verified_receipt',\n 'idempotent_retry',\n 'event_identity_conflict',\n 'source_state',\n ];\n if (capabilities.delivery === 'buffered') checks.push('buffered_outbox');\n if (capabilities.evidenceRetention !== 'none') checks.push('evidence_write_verified');\n return checks;\n}\n\nexport const AuditDeploymentReadinessSchema = z\n .object({\n requestedProfile: AuditAssuranceProfileSchema,\n effectiveProfile: AuditAssuranceProfileSchema,\n status: z.enum(['disabled', 'ready', 'degraded']),\n capabilities: AuditRuntimeCapabilitiesSchema.nullable(),\n canary: AuditRuntimeCanaryResultSchema.nullable(),\n reasonCodes: z.array(z.string().min(1).max(128)),\n })\n .strict();\n\nexport type AuditDeploymentReadiness = z.infer<typeof AuditDeploymentReadinessSchema>;\n\nconst PROFILE_BY_LEVEL = ['AAP-0', 'AAP-1', 'AAP-2', 'AAP-3', 'AAP-4'] as const;\n\nexport function resolveAuditDeploymentReadiness(\n config: AuditDeploymentConfig | undefined,\n capabilities: AuditRuntimeCapabilities | undefined,\n canary?: AuditRuntimeCanaryResult\n): AuditDeploymentReadiness {\n const requested = AuditDeploymentConfigSchema.parse(config ?? ABSENT_AUDIT_DEPLOYMENT_CONFIG);\n const observedCanary = canary ? AuditRuntimeCanaryResultSchema.parse(canary) : null;\n if (!requested.enabled) {\n return {\n requestedProfile: 'AAP-0',\n effectiveProfile: 'AAP-0',\n status: 'disabled',\n capabilities: capabilities ?? null,\n canary: observedCanary,\n reasonCodes: ['audit_not_configured'],\n };\n }\n const observedCapabilities = capabilities ?? observedCanary?.capabilities;\n if (!observedCapabilities) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: null,\n canary: observedCanary,\n reasonCodes: ['runtime_capabilities_unavailable'],\n };\n }\n const observed = AuditRuntimeCapabilitiesSchema.parse(observedCapabilities);\n if (!observedCanary) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: null,\n reasonCodes: ['runtime_canary_required'],\n };\n }\n if (\n !observedCanary.passed ||\n JSON.stringify(observedCanary.capabilities) !== JSON.stringify(observed)\n ) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: [\n observedCanary.passed ? 'runtime_canary_capability_mismatch' : 'runtime_canary_failed',\n ],\n };\n }\n const passedChecks = new Set(\n observedCanary.checks.filter((check) => check.passed).map((check) => check.id)\n );\n if (requiredAuditRuntimeCanaryChecks(observed).some((check) => !passedChecks.has(check))) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: ['runtime_canary_incomplete'],\n };\n }\n let maximum = 0;\n const reasons: string[] = [];\n if (observed.recorderTopology !== requested.recorderTopology) {\n reasons.push('recorder_topology_mismatch');\n }\n const deliveryRank = { 'best-effort': 0, buffered: 1, required: 2 } as const;\n if (deliveryRank[observed.delivery] < deliveryRank[requested.delivery]) {\n reasons.push('delivery_mode_mismatch');\n }\n const expectedEvidence =\n requested.evidenceMode === 'none'\n ? 'none'\n : requested.evidenceMode === 'encrypted-inline'\n ? 'inline'\n : 'separate';\n if (expectedEvidence !== observed.evidenceRetention) {\n reasons.push('evidence_retention_mismatch');\n }\n // These are explicit deployment-contract mismatches, not merely unavailable\n // higher-assurance services. Never activate a recorder against mechanics\n // weaker than (or topologically different from) the binding it was given.\n if (reasons.length > 0) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: reasons,\n };\n }\n if (observed.recorderTopology !== 'none' && observed.journalDurability !== 'none') maximum = 1;\n else reasons.push('recorder_or_journal_unavailable');\n if (\n maximum >= 1 &&\n observed.journalDurability === 'durable' &&\n observed.atomicAppend &&\n observed.delivery !== 'best-effort'\n ) {\n maximum = 2;\n } else if (Number(requested.requestedProfile.slice(-1)) >= 2) {\n reasons.push('durable_atomic_buffered_append_unavailable');\n }\n if (maximum >= 2 && observed.merkleCheckpoints && observed.sourceHighWater) maximum = 3;\n else if (Number(requested.requestedProfile.slice(-1)) >= 3) {\n reasons.push('checkpoint_or_source_high_water_unavailable');\n }\n if (maximum >= 3 && observed.independentObservation && observed.supportingAnchors.length > 0) {\n maximum = 4;\n } else if (Number(requested.requestedProfile.slice(-1)) >= 4) {\n reasons.push('independent_observation_or_anchor_unavailable');\n }\n const requestedLevel = Number(requested.requestedProfile.slice(-1));\n const effectiveLevel = Math.min(requestedLevel, maximum);\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: PROFILE_BY_LEVEL[effectiveLevel]!,\n status: effectiveLevel === requestedLevel && reasons.length === 0 ? 'ready' : 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: reasons,\n };\n}\n\n/**\n * Deploy step status — reuses same status enum as BYOK.\n */\nexport const ManagedDeployStepStatusSchema = z.enum([\n 'pending',\n 'in_progress',\n 'completed',\n 'failed',\n 'skipped',\n]);\n\nexport type ManagedDeployStepStatus = z.infer<typeof ManagedDeployStepStatusSchema>;\n\n// ============================================================================\n// Heartbeat Protocol (@kya-os/compute ⇄ AgentShield)\n// ============================================================================\n\n/**\n * Heartbeat request body.\n * Sent by compute process: POST /api/v1/molti/agents/{did}/heartbeat\n * Auth: X-Heartbeat-Token header\n */\nexport const HeartbeatRequestSchema = z.object({\n /** Agent DID this heartbeat is for */\n agentDid: DidStringSchema,\n /** Current compute process status */\n status: z.enum(['starting', 'running', 'error', 'stopping']),\n /** @kya-os/compute package version (from package.json) */\n computeVersion: z.string().min(1).max(50),\n /** Installed OpenClaw version (from npm ls) */\n openclawVersion: z.string().max(50).optional(),\n /** Fly machine ID (from FLY_MACHINE_ID env var) */\n machineId: z.string().max(255).optional(),\n /** Seconds since compute process started */\n uptimeSeconds: z.number().nonnegative().optional(),\n /** Current RSS memory in MB */\n memoryMb: z.number().nonnegative().optional(),\n});\n\nexport type HeartbeatRequest = z.infer<typeof HeartbeatRequestSchema>;\n\n// ============================================================================\n// Compute Commands (Discriminated Union)\n// ============================================================================\n\n/**\n * Stop command — graceful shutdown, no payload accepted.\n */\nexport const StopCommandSchema = z\n .object({\n type: z.literal('stop'),\n })\n .strict();\n\n/**\n * Restart command — restart the compute process, no payload accepted.\n */\nexport const RestartCommandSchema = z\n .object({\n type: z.literal('restart'),\n })\n .strict();\n\n/**\n * Update config command — triggers config re-fetch, no payload accepted.\n */\nexport const UpdateConfigCommandSchema = z\n .object({\n type: z.literal('update_config'),\n })\n .strict();\n\n/**\n * Update version command — requires target version in payload.\n */\nexport const UpdateVersionCommandSchema = z\n .object({\n type: z.literal('update_version'),\n payload: z.object({\n /** Target OpenClaw version to install */\n version: z.string().min(1).max(50),\n }),\n })\n .strict();\n\n/**\n * Command that Agent Shield can send to the compute process\n * via the heartbeat response.\n *\n * Discriminated union by `type` field:\n * - `stop` / `restart` / `update_config` — no payload\n * - `update_version` — requires `{ version: string }` payload\n */\nexport const ComputeCommandSchema = z.discriminatedUnion('type', [\n StopCommandSchema,\n RestartCommandSchema,\n UpdateConfigCommandSchema,\n UpdateVersionCommandSchema,\n]);\n\nexport type ComputeCommand = z.infer<typeof ComputeCommandSchema>;\n\n/**\n * Heartbeat response from Agent Shield.\n * Returned by: POST /api/v1/molti/agents/{did}/heartbeat\n */\nexport const HeartbeatResponseSchema = z.object({\n /** Always true for successful heartbeats */\n ack: z.literal(true),\n /** Pending commands for the compute process to execute */\n commands: z.array(ComputeCommandSchema).default([]),\n /** ISO timestamp of last config change (compute compares to detect updates) */\n configUpdatedAt: z.string().datetime().optional(),\n});\n\nexport type HeartbeatResponse = z.infer<typeof HeartbeatResponseSchema>;\n\n// ============================================================================\n// Config Bundle\n// ============================================================================\n\n/**\n * Config bundle returned by Agent Shield to the compute process.\n * Fetched on boot: GET /api/v1/molti/deployments/{did}/config-bundle\n * Auth: X-Heartbeat-Token header (for managed) or X-API-Key (for BYOK)\n *\n * **Private Key Delivery**: The agent's private key is NOT included in the config bundle.\n * It is delivered as the `AGENT_PRIVATE_KEY` environment variable at Fly machine creation\n * time and persists in the machine's env. This avoids transmitting the key on every\n * config fetch and keeps it out of the config-bundle response surface.\n */\nexport const ConfigBundleSchema = z.object({\n /** Schema version — 2 for managed bundles */\n version: z.number().int().positive(),\n /** Kill switch — if true, compute must exit immediately */\n killed: z.boolean(),\n /** Target OpenClaw version to install */\n openclawVersion: z.string().min(1).max(50),\n /** Agent personality/system prompt file contents (max 100KB) */\n soulFile: z.string().max(100_000).nullable(),\n /** Gateway auth token for OpenClaw */\n gatewayToken: z.string().min(1).max(500),\n /** Channel configurations */\n channels: z.object({\n telegram: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n })\n .optional(),\n discord: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n })\n .optional(),\n slack: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n appToken: z.string().optional(),\n })\n .optional(),\n whatsapp: z\n .object({\n enabled: z.boolean(),\n })\n .strict()\n .optional(),\n }),\n /** AI provider configuration — key is decrypted, sent over TLS */\n aiProvider: z.object({\n type: z.enum(['anthropic', 'openai']),\n apiKey: z.string().min(1).max(500),\n /**\n * Optional base URL override. When set, OpenClaw routes all provider\n * traffic through this URL instead of the provider's default endpoint.\n * Used by managed deployments where AgentShield issues a per-deployment\n * gateway token and proxies to the upstream provider with budget tracking.\n */\n baseUrl: z.string().url().optional(),\n }),\n /**\n * Optional OpenClaw heartbeat interval (`agents.defaults.heartbeat.every`).\n * Drives how often OpenClaw wakes the agent for HEARTBEAT.md processing —\n * the primary token-cost lever. Examples: \"30m\" (active), \"6h\" (idle),\n * \"off\" (dormant — heartbeat disabled entirely). When absent, the patcher\n * preserves whatever value already lives in openclaw.json (OpenClaw's\n * built-in default of \"30m\").\n */\n heartbeatEvery: z.string().min(1).max(20).optional(),\n /**\n * Optional override for `agents.defaults.model.primary` (e.g.\n * \"anthropic/claude-haiku-4-5\" for idle agents). When absent, the patcher\n * derives the model from `aiProvider.type` as before. Format must be\n * \"<provider>/<model-id>\".\n */\n modelOverride: z.string().min(1).max(100).optional(),\n /** ISO timestamp of last config modification */\n updatedAt: z.string().datetime(),\n});\n\nexport type ConfigBundle = z.infer<typeof ConfigBundleSchema>;\n\n// ============================================================================\n// Control Server (WebSocket :18790)\n// ============================================================================\n\n/**\n * Status frame pushed from compute control server to dashboard.\n * Sent on connect + every 5 seconds.\n */\nexport const ControlStatusSchema = z.object({\n /** Whether the agent runtime is healthy */\n healthy: z.boolean(),\n /** Seconds since compute process started */\n uptimeSeconds: z.number().nonnegative(),\n /** Installed OpenClaw version */\n openclawVersion: z.string().min(1).max(50),\n /** @kya-os/compute version */\n computeVersion: z.string().min(1).max(50),\n /** Number of active WS connections to control server */\n activeConnections: z.number().int().nonnegative(),\n /** Current RSS memory in MB */\n memoryMb: z.number().nonnegative(),\n /** CPU usage percentage (0-100) */\n cpuPercent: z.number().nonnegative().max(100),\n});\n\nexport type ControlStatus = z.infer<typeof ControlStatusSchema>;\n","/**\n * Deploy Progress Event Types\n *\n * Types for real-time deployment progress tracking via SSE.\n * Used by the one-click deploy feature to stream step-by-step updates.\n *\n * @module events/deploy-progress\n */\n\nimport { z } from 'zod';\nimport { AuditDeploymentConfigSchema } from '../deploy';\n\n/**\n * All possible deployment steps in order\n */\nexport const DEPLOY_STEPS = [\n { id: 'github_verify', label: 'Verifying your GitHub connection', order: 1 },\n { id: 'repo_check', label: 'Checking your repository name', order: 2 },\n { id: 'project_create', label: 'Creating your project', order: 3 },\n { id: 'api_key', label: 'Generating your API key', order: 4 },\n { id: 'scaffold', label: 'Generating your server files', order: 5 },\n { id: 'kta_register', label: 'Setting up your agent identity', order: 6 },\n { id: 'repo_create', label: 'Creating your GitHub repository', order: 7 },\n { id: 'commit_files', label: 'Committing your server code', order: 8 },\n { id: 'add_secrets', label: 'Securing your repository secrets', order: 9 },\n { id: 'cloudflare_deploy', label: 'Deploying your server to Cloudflare', order: 10 },\n { id: 'complete', label: 'Deployment complete!', order: 11 },\n] as const;\n\n/**\n * Step ID enum\n */\nexport const DeployStepIdSchema = z.enum([\n 'github_verify',\n 'repo_check',\n 'project_create',\n 'api_key',\n 'scaffold',\n 'kta_register',\n 'repo_create',\n 'commit_files',\n 'add_secrets',\n 'cloudflare_deploy',\n 'complete',\n]);\nexport type DeployStepId = z.infer<typeof DeployStepIdSchema>;\n\n/**\n * Step status\n */\nexport const DeployStepStatusSchema = z.enum([\n 'pending',\n 'running',\n 'complete',\n 'error',\n 'skipped',\n]);\nexport type DeployStepStatus = z.infer<typeof DeployStepStatusSchema>;\n\n/**\n * Individual step state\n */\nexport const DeployStepStateSchema = z.object({\n id: DeployStepIdSchema,\n status: DeployStepStatusSchema,\n message: z.string().optional(),\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n});\nexport type DeployStepState = z.infer<typeof DeployStepStateSchema>;\n\n/**\n * Full deployment progress event\n */\nexport const DeployProgressEventSchema = z.object({\n type: z.literal('deploy_progress'),\n deploymentId: z.string(),\n timestamp: z.number(),\n currentStep: DeployStepIdSchema,\n steps: z.array(DeployStepStateSchema),\n result: z\n .object({\n repoUrl: z.string(),\n repoFullName: z.string(),\n deployUrl: z.string(),\n projectId: z.string(),\n /** Human-readable project ID for URL construction */\n friendlyId: z.string().nullable().optional(),\n /** kyaosDeployments row id — drives the live-step \"Go to server\" deployment-detail link. */\n deploymentId: z.string().optional(),\n /** Full API key - only shown once at completion! */\n apiKey: z.string(),\n /** Preview (sk_...xxx) for display after initial view */\n apiKeyPreview: z.string(),\n cloudflareUrl: z.string().optional(),\n cloudflareDeployed: z.boolean().optional(),\n /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */\n cloudflareError: z.string().optional(),\n /** Agent DID (decentralized identifier) - did:web for reputation enabled, did:key for disabled */\n agentDid: z.string().optional(),\n /** Whether agent was registered with Know That AI for reputation tracking */\n ktaRegistered: z.boolean().optional(),\n /** Claim URL for KTA registration (only when using cli-register with did:web) */\n ktaClaimUrl: z.string().optional(),\n })\n .optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n step: DeployStepIdSchema.optional(),\n })\n .optional(),\n});\nexport type DeployProgressEvent = z.infer<typeof DeployProgressEventSchema>;\n\n/**\n * Deployment metadata stored in Redis\n */\nexport const DeploymentMetadataSchema = z.object({\n id: z.string(),\n userId: z.string(),\n organizationId: z.string(),\n repoName: z.string(),\n template: z.string(),\n platform: z.string(),\n /** Hosting mode: 'managed' (Checkpoint hosted) or 'byok' (Bring Your Own Cloudflare) */\n hostingMode: z.enum(['managed', 'byok']).optional().default('byok'),\n /** 'repo-only' scaffolds + pushes the repo but never triggers the Cloudflare worker upload, regardless of connection state (defaults to 'cloudflare') */\n deployTarget: z.enum(['cloudflare', 'repo-only']).optional(),\n status: z.enum(['pending', 'running', 'complete', 'error']),\n /** Enable reputation tracking via Know That AI (defaults to true) */\n enableReputation: z.boolean().optional(),\n /** Requested audit posture. Old stored metadata may omit this and resolves to AAP-0 at use. */\n audit: AuditDeploymentConfigSchema.optional(),\n /** Existing project ID to deploy to (if provided, skips project creation) - Unified Project Schema v1.3 */\n existingProjectId: z.string().uuid().optional(),\n /** Pre-generated source supplied by another intake flow (for example OpenAPI). */\n generatedFiles: z\n .array(\n z.object({\n path: z.string(),\n content: z.string(),\n isBase64: z.boolean().optional(),\n })\n )\n .optional(),\n /** Identity paired with pre-generated source. */\n generatedIdentity: z\n .object({\n did: z.string(),\n // Optional so historical metadata already sitting in Redis without a\n // kid still parses. The producing route always populates it now (see\n // KYA-956 phase 3); the deploy pipeline treats a missing kid as a\n // scaffold-time failure rather than injecting a broken identity.\n kid: z.string().optional(),\n publicKey: z.string(),\n privateKey: z.string(),\n })\n .optional(),\n /** Validated source-specific secrets forwarded to GitHub/Cloudflare. */\n additionalSecrets: z.record(z.string(), z.string()).optional(),\n /** Semantic source type used for descriptions and registry metadata. */\n agentType: z.string().optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n /** Result data (populated on completion) */\n result: z\n .object({\n /** GitHub repo URL (BYOK deploy only) */\n repoUrl: z.string().optional(),\n /** GitHub repo full name e.g. \"user/repo\" (BYOK deploy only) */\n repoFullName: z.string().optional(),\n /** GitHub Actions deploy URL (BYOK deploy only) */\n deployUrl: z.string().optional(),\n projectId: z.string(),\n /** Human-readable project ID for URL construction */\n friendlyId: z.string().nullable().optional(),\n /** kyaosDeployments row id — powers the live-step deployment-detail link (all sources). */\n deploymentId: z.string().optional(),\n /** API key preview e.g. \"sk_...xxx\" (BYOK deploy only) */\n apiKeyPreview: z.string().optional(),\n cloudflareUrl: z.string().optional(),\n cloudflareDeployed: z.boolean().optional(),\n /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */\n cloudflareError: z.string().optional(),\n agentDid: z.string().optional(),\n ktaRegistered: z.boolean().optional(),\n ktaClaimUrl: z.string().optional(),\n })\n .optional(),\n});\nexport type DeploymentMetadata = z.infer<typeof DeploymentMetadataSchema>;\n\n/**\n * Helper to get step info by ID\n */\nexport function getStepInfo(stepId: DeployStepId) {\n return DEPLOY_STEPS.find((s) => s.id === stepId);\n}\n\n/**\n * Helper to get step order\n */\nexport function getStepOrder(stepId: DeployStepId): number {\n const step = DEPLOY_STEPS.find((s) => s.id === stepId);\n return step?.order ?? 0;\n}\n\n/**\n * Calculate completion percentage\n */\nexport function calculateDeployProgress(\n currentStep: DeployStepId,\n status: DeployStepStatus\n): number {\n const totalSteps = DEPLOY_STEPS.length - 1; // Exclude 'complete' step\n const currentOrder = getStepOrder(currentStep);\n\n if (currentStep === 'complete') return 100;\n\n // If running, we're partially through the step\n if (status === 'running') {\n return Math.round(((currentOrder - 0.5) / totalSteps) * 100);\n }\n\n // If complete, we've finished this step\n if (status === 'complete') {\n return Math.round((currentOrder / totalSteps) * 100);\n }\n\n return Math.round(((currentOrder - 1) / totalSteps) * 100);\n}\n\n/**\n * Build initial steps state (all pending)\n */\nexport function buildInitialStepsState(): DeployStepState[] {\n return DEPLOY_STEPS.map((step) => ({\n id: step.id as DeployStepId,\n status: 'pending' as const,\n }));\n}\n\n/**\n * Update steps state for a given step\n */\nexport function updateStepsState(\n currentSteps: DeployStepState[],\n stepId: DeployStepId,\n status: DeployStepStatus,\n options?: { message?: string; error?: { code: string; message: string } }\n): DeployStepState[] {\n const now = Date.now();\n\n return currentSteps.map((step) => {\n if (step.id === stepId) {\n return {\n ...step,\n status,\n message: options?.message,\n error: options?.error,\n startedAt: status === 'running' ? now : step.startedAt,\n completedAt: status === 'complete' || status === 'error' ? now : step.completedAt,\n };\n }\n return step;\n });\n}\n","/**\n * Analytics Types\n *\n * Types for analytics data, exports, and monitoring\n */\n\nimport { z } from 'zod';\n\n/**\n * Analytics export parameters\n */\nexport const AnalyticsExportParamsSchema = z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('json'),\n dateRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n filters: z\n .object({\n projectId: z.string().uuid().optional(),\n pixelId: z.string().uuid().optional(),\n isAgent: z.boolean().optional(),\n agentTypes: z.array(z.string()).optional(),\n minConfidence: z.number().min(0).max(100).optional(),\n })\n .optional(),\n fields: z.array(z.string()).optional(), // Specific fields to export\n includeMetadata: z.boolean().default(false),\n compression: z.boolean().default(false),\n});\nexport type AnalyticsExportParams = z.infer<typeof AnalyticsExportParamsSchema>;\n\n/**\n * Legacy analytics rollup shapes stored in the web app's analytics_rollups JSONB\n * column. Keep these shared so background services and admin routes agree on\n * the persisted structure while the legacy rollup service is migrated away.\n */\nexport type AnalyticsRollupPeriod = 'daily' | 'weekly' | 'monthly';\n\nexport interface LegacyAnalyticsSessionMetrics {\n total: number;\n unique: number;\n events: number;\n avgDuration: number;\n}\n\nexport interface LegacyAnalyticsAiDetectionMetrics {\n total: number;\n aiAgents: number;\n bots: number;\n humans: number;\n aiRate: number;\n botRate: number;\n humanRate: number;\n}\n\nexport interface LegacyAnalyticsEventMetrics {\n total: number;\n uniquePaths: number;\n avgPerSession: number;\n}\n\nexport interface LegacyAnalyticsRollupMetrics {\n sessions: LegacyAnalyticsSessionMetrics;\n aiDetection: LegacyAnalyticsAiDetectionMetrics;\n events: LegacyAnalyticsEventMetrics;\n}\n\nexport interface LegacyAnalyticsCalculatedMetrics {\n sessionMetrics: LegacyAnalyticsSessionMetrics;\n aiMetrics: LegacyAnalyticsAiDetectionMetrics;\n eventMetrics: LegacyAnalyticsEventMetrics;\n}\n\nexport interface LegacyAnalyticsIndustryAverages {\n avgSessions: number;\n avgEvents: number;\n avgAiRate: number;\n avgDuration: number;\n}\n\nexport interface LegacyAnalyticsIndustryTrendDay {\n date: string;\n totalSessions: number;\n aiSessions: number;\n aiRate: number;\n organizations: number;\n}\n\nexport interface LegacyAnalyticsAgentBreakdownItem {\n name: string | null;\n category: string | null;\n count: number;\n}\n\nexport interface LegacyAnalyticsAgentCategoryBreakdown {\n category: string;\n total: number;\n agents: Array<{\n name: string | null;\n count: number;\n }>;\n}\n\nexport interface LegacyAnalyticsAgentTypeBreakdown {\n byAgent: LegacyAnalyticsAgentBreakdownItem[];\n byCategory: LegacyAnalyticsAgentCategoryBreakdown[];\n topAgents: Array<{\n name: string | null;\n count: number;\n }>;\n}\n\nexport interface LegacyAnalyticsPeriodMetrics {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n}\n\nexport interface LegacyAnalyticsGrowthMetrics {\n weekOverWeek: {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n };\n monthOverMonth: {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n };\n current: {\n weekSessions: number;\n weekAiRate: number;\n monthSessions: number;\n monthAiRate: number;\n };\n}\n\nexport type AnalyticsCacheParamValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | { readonly [key: string]: AnalyticsCacheParamValue }\n | readonly AnalyticsCacheParamValue[];\nexport type AnalyticsCacheParams = Record<string, AnalyticsCacheParamValue>;\nexport type AnalyticsCacheType = 'realtime' | 'frequent' | 'historical';\n\nexport interface AnalyticsCacheStats {\n [cacheName: string]: {\n size: number;\n calculatedSize: number;\n };\n}\n\nexport interface AnalyticsPreloadQueryFunction<T = unknown> {\n type: string;\n params: AnalyticsCacheParams;\n fn: () => Promise<T>;\n}\n\nexport type TrafficPatternGranularity = 'hour' | 'day' | 'week';\n\nexport interface TrafficTimeSeriesPoint {\n timestamp: string;\n totalSessions: number;\n totalEvents: number;\n uniqueIPs: number | null;\n avgEventsPerSession: number;\n aiAgentSessions: number;\n humanSessions: number;\n}\n\nexport interface TrafficTopPage {\n path: string;\n visits: number;\n uniqueSessions: number;\n uniqueVisitors: number;\n avgTimeOnPage: number;\n fromAI: number;\n fromHuman: number;\n}\n\nexport interface TrafficNavigationPath {\n fromPage: string;\n toPage: string;\n count: number;\n}\n\nexport interface OrganizationTrafficPatterns {\n timeSeries: TrafficTimeSeriesPoint[];\n topPages: TrafficTopPage[];\n navigationPaths: TrafficNavigationPath[];\n}\n\nexport interface OrganizationTrafficPatternsSummary {\n organizationId: string;\n organizationName: string;\n patterns: OrganizationTrafficPatterns;\n}\n\nexport interface SystemWideTrafficPatterns extends OrganizationTrafficPatterns {\n byOrganization: OrganizationTrafficPatternsSummary[];\n}\n\nexport type TrafficPatterns = OrganizationTrafficPatterns | SystemWideTrafficPatterns;\n\nexport interface SessionFrequencyDay {\n date: string;\n newSessions: number;\n returningSessions: number;\n totalSessions: number;\n returnRate: number;\n uniqueVisitors: number;\n}\n\nexport interface SessionFrequencyPatterns {\n daily: SessionFrequencyDay[];\n summary: {\n totalNewSessions: number;\n totalReturningSessions: number;\n averageReturnRate: number;\n };\n}\n\nexport interface PeakTrafficHour {\n hour: number;\n sessions: number;\n events: number;\n aiPercentage: number;\n}\n\nexport interface PeakTrafficDay {\n day: string;\n sessions: number;\n events: number;\n aiPercentage: number;\n}\n\nexport interface TrafficSpike {\n timestamp: string;\n sessions: number;\n magnitude: number;\n composition: {\n ai: number;\n human: number;\n };\n}\n\nexport interface PeakTrafficPatterns {\n peakHours: PeakTrafficHour[];\n peakDays: PeakTrafficDay[];\n trafficSpikes: TrafficSpike[];\n statistics?: {\n meanSessions: number;\n stdDeviation: number;\n spikeThreshold: number;\n };\n}\n\nexport interface AgentNavigationBehavior {\n agentTypes: Array<{\n type: string;\n sessions: number;\n eventsPerSession: number;\n uniquePathsVisited: number;\n avgTimeOnPage: number;\n }>;\n topPagesByAgent: Array<{\n path: string;\n agentType: string;\n visits: number;\n }>;\n}\n","/**\n * Detection Metadata Types\n *\n * Type definitions for detection metadata stored in the database\n */\n\nimport { z } from 'zod';\n\n/**\n * Detection metadata stored in database JSONB field\n * This represents the metadata field in the detections table\n */\nexport const DatabaseDetectionMetadataSchema = z.object({\n // Agent information\n detectedAgent: z\n .object({\n type: z.string(),\n name: z.string(),\n })\n .optional(),\n\n // Verification details\n verificationMethod: z.enum(['signature', 'pattern', 'mcp_i', 'none']).optional(),\n riskLevel: z.enum(['low', 'medium', 'high', 'unknown']).optional(),\n\n // Detection details\n reasons: z.array(z.string()).optional(),\n\n // Request context\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Browser fingerprint data\n clientDetection: z\n .object({\n headless: z.boolean().optional(),\n webrtc: z.boolean().optional(),\n canvas: z.string().optional(),\n plugins: z.number().optional(),\n automation: z.boolean().optional(),\n chrome: z.boolean().optional(),\n languages: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Additional metadata\n agent: z.string().optional(),\n processingTime: z.number().optional(),\n cached: z.boolean().optional(),\n});\n\nexport type DatabaseDetectionMetadata = z.infer<typeof DatabaseDetectionMetadataSchema>;\n","/**\n * Authentication Session\n */\nexport interface AuthSession {\n user: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n emailVerified?: Date | null;\n defaultOrganizationId?: string;\n currentOrganizationId?: string;\n organizationRole?: 'owner' | 'admin' | 'member';\n };\n expires: string;\n}\n\n/**\n * Authentication Error Types\n */\nexport enum AuthErrorType {\n INVALID_CREDENTIALS = 'INVALID_CREDENTIALS',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n EMAIL_NOT_VERIFIED = 'EMAIL_NOT_VERIFIED',\n ACCOUNT_DISABLED = 'ACCOUNT_DISABLED',\n ACCOUNT_LOCKED = 'ACCOUNT_LOCKED',\n PASSWORD_EXPIRED = 'PASSWORD_EXPIRED',\n INVALID_TOKEN = 'INVALID_TOKEN',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n EMAIL_ALREADY_EXISTS = 'EMAIL_ALREADY_EXISTS',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n PASSWORDS_DO_NOT_MATCH = 'PASSWORDS_DO_NOT_MATCH',\n OAUTH_ACCOUNT_NOT_LINKED = 'OAUTH_ACCOUNT_NOT_LINKED',\n OAUTH_ERROR = 'OAUTH_ERROR',\n RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',\n}\n\n/**\n * Authentication Response\n */\nexport interface AuthResponse {\n success: boolean;\n message?: string;\n user?: AuthSession['user'];\n token?: string;\n redirectUrl?: string;\n error?: {\n type: AuthErrorType;\n message: string;\n };\n}\n\n/**\n * Sign Up Response\n */\nexport interface SignUpResponse extends AuthResponse {\n requiresEmailVerification?: boolean;\n verificationEmailSent?: boolean;\n}\n","/**\n * Fingerprint Types and Schemas\n *\n * Comprehensive type definitions for the AI fingerprinting system\n * Supporting multiple integration types and detection methods\n */\n\nimport { z } from 'zod';\n\n// Re-export legacy types for backward compatibility\nexport * from './fingerprint-legacy';\n\n// Integration types that determine what data is available\nexport const IntegrationTypeSchema = z.enum([\n 'pixel', // Client-side pixel (minimal data)\n 'beacon', // Enhanced beacon (more client data)\n 'noscript', // Server-side only (headers + IP)\n 'middleware', // Full request context\n 'express', // Node.js server integration\n 'edge', // Edge runtime data\n 'wasm', // Full WASM detection\n]);\n\nexport type IntegrationType = z.infer<typeof IntegrationTypeSchema>;\n\nexport interface CanvasFingerprintData {\n supported: boolean;\n hash?: string;\n dataUrl?: string;\n renderTime?: number;\n error?: string;\n}\n\nexport interface WebGLFingerprintData {\n supported: boolean;\n vendor?: string;\n renderer?: string;\n extensions?: string[];\n error?: string;\n}\n\nexport interface AudioFingerprintData {\n supported: boolean;\n sampleRate?: number;\n channelCount?: number;\n fingerprint?: string;\n error?: string;\n}\n\nexport interface BrowserFingerprintScreenData {\n resolution: string;\n colorDepth: number;\n pixelRatio: number;\n orientation: string;\n}\n\nexport interface BrowserFingerprintFeatures {\n webWorker: boolean;\n serviceWorker: boolean;\n webAssembly: boolean;\n webRTC: boolean;\n notifications: boolean;\n bluetooth: boolean;\n battery: boolean;\n}\n\nexport interface BrowserFingerprintTouchSupport {\n maxTouchPoints: number;\n touchEvent: boolean;\n touchStart: boolean;\n}\n\nexport interface BrowserFingerprintConnectionData {\n effectiveType?: string;\n rtt?: number;\n downlink?: number;\n saveData?: boolean;\n}\n\nexport interface BrowserClientSideFingerprintData {\n canvas?: CanvasFingerprintData;\n webgl?: WebGLFingerprintData;\n audio?: AudioFingerprintData;\n screen?: BrowserFingerprintScreenData;\n features?: BrowserFingerprintFeatures;\n touchSupport?: BrowserFingerprintTouchSupport;\n connection?: BrowserFingerprintConnectionData;\n timezone?: string;\n languages?: string[];\n plugins?: string[];\n cookiesEnabled?: boolean;\n localStorage?: boolean;\n sessionStorage?: boolean;\n doNotTrack?: string | null;\n hardwareConcurrency?: number;\n deviceMemory?: number;\n fonts?: string[];\n}\n\n// Comprehensive collected data from fingerprinting\nexport const CollectedDataSchema = z.object({\n id: z.string().uuid(),\n testId: z.string().optional(), // Query parameter for lookup\n integrationType: IntegrationTypeSchema,\n timestamp: z.date(),\n\n // What each integration can see\n availableData: z.object({\n // ALWAYS available (all integrations)\n core: z.object({\n userAgent: z.string(),\n ip: z.string(),\n url: z.string(),\n method: z.string(),\n timestamp: z.date(),\n }),\n\n // HEADERS (noscript, middleware, express, edge)\n headers: z.record(z.string(), z.string()).optional(),\n\n // CLIENT-SIDE (pixel, beacon only)\n clientSide: z\n .object({\n canvas: z\n .object({\n supported: z.boolean(),\n hash: z.string().optional(),\n dataUrl: z.string().optional(),\n renderTime: z.number().optional(),\n })\n .optional(),\n webgl: z\n .object({\n supported: z.boolean(),\n vendor: z.string().optional(),\n renderer: z.string().optional(),\n extensions: z.array(z.string()).optional(),\n })\n .optional(),\n audio: z\n .object({\n supported: z.boolean(),\n sampleRate: z.number().optional(),\n channelCount: z.number().optional(),\n fingerprint: z.string().optional(),\n })\n .optional(),\n screen: z\n .object({\n resolution: z.string(),\n colorDepth: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().optional(),\n })\n .optional(),\n timezone: z.string().optional(),\n languages: z.array(z.string()).optional(),\n fonts: z.array(z.string()).optional(),\n plugins: z.array(z.string()).optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n cookiesEnabled: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n hardwareConcurrency: z.number().optional(),\n deviceMemory: z.number().optional(),\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .optional(),\n // Touch and input capabilities\n touchSupport: z\n .object({\n maxTouchPoints: z.number(),\n touchEvent: z.boolean(),\n touchStart: z.boolean(),\n })\n .optional(),\n // Browser features\n features: z\n .object({\n webWorker: z.boolean(),\n serviceWorker: z.boolean(),\n webAssembly: z.boolean(),\n webRTC: z.boolean(),\n notifications: z.boolean(),\n bluetooth: z.boolean(),\n battery: z.boolean(),\n })\n .optional(),\n })\n .optional(),\n\n // SERVER-SIDE ENHANCED (middleware, express)\n serverEnhanced: z\n .object({\n tls: z\n .object({\n version: z.string(),\n cipher: z.string(),\n ja3: z.string().optional(), // TLS fingerprint\n ja3s: z.string().optional(), // Server TLS fingerprint\n })\n .optional(),\n httpVersion: z.string(),\n protocol: z.string(),\n requestSize: z.number().optional(),\n cookies: z.record(z.string(), z.string()).optional(),\n sessionData: z.any().optional(),\n // Visitor geo comes from Vercel/Cloudflare edge headers, which give a\n // country and usually a region and city, and never a coordinate pair\n // or timezone. Only `country` is guaranteed when the object is\n // present; the rest are omitted when the edge did not supply them.\n // They were all required until the producer stopped returning a\n // hardcoded San Francisco for every request.\n geoLocation: z\n .object({\n country: z.string(),\n region: z.string().optional(),\n city: z.string().optional(),\n latitude: z.number().optional(),\n longitude: z.number().optional(),\n timezone: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n\n // BEHAVIORAL (pixel, beacon with time)\n behavioral: z\n .object({\n timeOnPage: z.number(),\n mouseMovements: z.number(),\n mouseClicks: z.number(),\n keystrokes: z.number(),\n scrollEvents: z.number(),\n scrollDepth: z.number(),\n touchEvents: z.number().optional(),\n visibility: z\n .array(\n z.object({\n hidden: z.boolean(),\n timestamp: z.number(),\n })\n )\n .optional(),\n performance: z\n .object({\n loadTime: z.number(),\n domReady: z.number(),\n firstPaint: z.number().optional(),\n firstContentfulPaint: z.number().optional(),\n })\n .optional(),\n interactions: z\n .array(\n z.object({\n type: z.string(),\n timestamp: z.number(),\n target: z.string().optional(),\n })\n )\n .optional(),\n })\n .optional(),\n }),\n\n // Detection results from different engines\n detectionResults: z\n .object({\n // partialRecord, not record: Zod 4 makes an enum-keyed record exhaustive, and\n // these are per-integration results where any subset of integrations may be present.\n wouldDetectAs: z\n .partialRecord(\n IntegrationTypeSchema,\n z.object({\n isAgent: z.boolean(),\n confidence: z.number(),\n agentType: z.string().optional(),\n reasons: z.array(z.string()),\n processingTime: z.number().optional(),\n })\n )\n .optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z\n .object({\n collectionDuration: z.number().optional(),\n errors: z.array(z.string()).optional(),\n warnings: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\nexport type CollectedData = z.infer<typeof CollectedDataSchema>;\n\n// Fingerprint record stored in database\nexport const FingerprintRecordSchema = z.object({\n id: z.string().uuid(),\n testId: z.string().optional(),\n timestamp: z.date(),\n\n // Core fingerprint data\n integrationType: IntegrationTypeSchema,\n userAgent: z.string(),\n ipAddress: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Fingerprint hashes\n canvasHash: z.string().optional(),\n webglHash: z.string().optional(),\n audioHash: z.string().optional(),\n\n // Full collected data\n collectedData: CollectedDataSchema,\n\n // Classification results\n classification: z\n .object({\n aiType: z.string().optional(),\n vendor: z.string().optional(),\n confidence: z.number(),\n matchedRules: z.array(z.string()).optional(),\n patterns: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Association\n profileId: z.string().uuid().optional(),\n notes: z.string().optional(),\n tags: z.array(z.string()).optional(),\n\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nexport type FingerprintRecord = z.infer<typeof FingerprintRecordSchema>;\n\n// Export request/response types for API\nexport const CollectFingerprintRequestSchema = z.object({\n testId: z.string().optional(),\n integrationType: IntegrationTypeSchema,\n data: z.any(), // Will be validated based on integration type\n});\n\nexport const CollectFingerprintResponseSchema = z.object({\n success: z.boolean(),\n sessionId: z.string(),\n fingerprintId: z.string(),\n message: z.string().optional(),\n});\n\nexport const TestDetectionRequestSchema = z.object({\n // `fingerprints.id` is a uuid column, so a value that is not one cannot\n // address a row; refusing it here makes it a 400 rather than a Postgres\n // error surfacing as a 500.\n fingerprintId: z.string().uuid(),\n // Omit the member to test every integration type. An EMPTY array would run\n // nothing and write a 0/0 mean (NaN) into an integer column, so it is a 400.\n integrationTypes: z\n .array(IntegrationTypeSchema)\n .min(1, 'integrationTypes must list at least one integration type, or be omitted entirely')\n .optional(),\n});\n\n// Helper function to generate test ID\nexport function generateTestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `test-${timestamp}-${random}`;\n}\n\n// Helper to check if integration supports client-side data\nexport function supportsClientSide(integration: IntegrationType): boolean {\n return ['pixel', 'beacon'].includes(integration);\n}\n\n// Helper to check if integration supports headers\nexport function supportsHeaders(integration: IntegrationType): boolean {\n return ['noscript', 'middleware', 'express', 'edge', 'wasm'].includes(integration);\n}\n\n// Helper to check if integration supports enhanced server data\nexport function supportsServerEnhanced(integration: IntegrationType): boolean {\n return ['middleware', 'express'].includes(integration);\n}\n","// GENERATED FILE — do not hand-edit.\n//\n// Source of truth: rust/crates/kya-os-engine/data/vendor-keys/*.json —\n// the RFC 9421 vendor key directories the engine actually pins and\n// verifies at the edge. Regenerate with:\n//\n// pnpm tsx scripts/sync-signing-vendors.ts\n//\n// apps/web/tests/unit/lib/signing-vendors-parity.test.ts fails the build\n// when this list drifts from the directory, so adding or removing a\n// vendor key file forces this manifest (and therefore every derived\n// `signatureSupport` flag) to follow. Existing agent_types rows in\n// deployed databases still need a data migration when the list changes —\n// the sync script prints a reminder.\n\n/** Vendors with a pinned, edge-verified RFC 9421 signing-key directory. */\nexport const PINNED_SIGNING_VENDORS: readonly string[] = ['openai'];\n","/**\n * Agent Classification Types\n *\n * Centralized type definitions for agent classification system\n */\n\nimport { z } from 'zod';\n\nimport { PINNED_SIGNING_VENDORS } from './signing-vendors.generated';\n\n/**\n * True iff any of the agent's signature-vendor aliases has a pinned,\n * edge-verified RFC 9421 key directory in the engine\n * (rust/crates/kya-os-engine/data/vendor-keys, via the generated\n * manifest). This is the ONLY way `signatureSupport` may become true —\n * hand-seeding it let `claude` claim verified signatures for months\n * while Anthropic published no keys and the engine pinned none.\n */\nexport function hasPinnedSigningVendor(aliases: readonly string[] | undefined): boolean {\n return aliases?.some((alias) => PINNED_SIGNING_VENDORS.includes(alias)) ?? false;\n}\n\n/**\n * Agent categories for classification\n */\nexport const AgentCategorySchema = z.enum([\n 'ai_assistant', // ChatGPT, Claude, Gemini, Perplexity\n 'search_engine', // Googlebot, Bingbot, DuckDuckBot\n 'social_media', // Facebook, Twitter, LinkedIn crawlers\n 'monitoring', // Uptime monitors, health checkers\n 'scraper', // Web scrapers, data extractors\n 'automation', // Puppeteer, Playwright, Selenium\n 'security', // Security scanners, vulnerability testers\n 'analytics', // Analytics bots, SEO tools\n 'unknown', // Unclassified agents\n]);\nexport type AgentCategory = z.infer<typeof AgentCategorySchema>;\n\n/**\n * Operator-facing vocabulary for `agent_category`.\n *\n * ## Why this lives here\n *\n * Beside `AgentCategorySchema`, not in a UI package, because the same\n * words have to hold across the dashboard, the gateway, exports, the\n * public API, and the .NET plane. A display map that lives in one app is\n * a map the other surfaces will silently disagree with.\n *\n * `Record<AgentCategory, …>` is load-bearing: TypeScript refuses to\n * compile a missing key, so widening the enum without designing its copy\n * cannot ship. The previous web-only map had a `titleCase` fallback that\n * silently invented a label for any new value, which is exactly the drift\n * this replaces.\n *\n * ## What `unknown` means, and why it is labelled \"Other\"\n *\n * `agent_category` answers *which named family is this*. It is a\n * DIFFERENT axis from `detection_class`, which answers *is this human, an\n * agent, or a bot*. A miss on `detection_class` is a detection gap and\n * has its own value (`incomplete_data`). A miss here is an ATTRIBUTION\n * gap: the request was detected and classified, we just have not matched\n * it to a named vendor.\n *\n * `getAgentCategory` (apps/web/lib/utils/agent-category.ts) writes\n * `'unknown'` for exactly two cases: traffic matched only a generic\n * bot/crawler/spider/scraper signature, and the final default. Both are\n * \"real traffic, no vendor attributed\" — the ordinary long tail of the\n * internet, not a failure. Labelling it \"Unrecognized\" or \"Uncategorized\"\n * describes the engine as having failed at something it did not attempt,\n * and reads as weakness on a chart where it is routinely the largest\n * slice.\n *\n * \"Other\" is the sibling term to the eight named families and carries no\n * such claim. Where the bucket deserves a second look (it is where an\n * agent nobody has written a signature for shows up first) that belongs\n * in prose and drill-in, not compressed into a bar label.\n */\nexport interface AgentCategoryMeta {\n /** Title-case form for chart axes, table cells, chips, filters. */\n label: string;\n /**\n * Lower-case form for mid-sentence prose (\"led by search engine\n * traffic\"). Acronyms keep their casing — lowercasing \"AI\" is a worse\n * error than an odd-looking capital.\n */\n inline: string;\n /**\n * One-line operator-facing definition. Single source for tooltips and\n * for the knowledge-base article, so the docs cannot drift from the\n * code the way they did before.\n */\n definition: string;\n}\n\nexport const AGENT_CATEGORY_META: Record<AgentCategory, AgentCategoryMeta> = {\n ai_assistant: {\n label: 'AI assistant',\n inline: 'AI assistant',\n definition: 'An AI assistant acting for a person in real time (ChatGPT, Claude, Perplexity).',\n },\n search_engine: {\n label: 'Search engine',\n inline: 'search engine',\n definition: 'An indexing crawler that makes your pages findable (Googlebot, Bingbot).',\n },\n social_media: {\n label: 'Social media',\n inline: 'social media',\n definition: 'A crawler building link previews for a social platform.',\n },\n monitoring: {\n label: 'Monitoring',\n inline: 'monitoring',\n definition: 'An uptime or health checker polling your endpoints.',\n },\n scraper: {\n label: 'Scraper',\n inline: 'scraper',\n definition:\n 'Bulk content extraction, including AI training crawlers such as GPTBot and ClaudeBot.',\n },\n automation: {\n label: 'Automation',\n inline: 'automation',\n definition: 'A headless browser or scripted driver (Puppeteer, Playwright, Selenium).',\n },\n security: {\n label: 'Security',\n inline: 'security',\n definition: 'A vulnerability scanner or security research crawler.',\n },\n analytics: {\n label: 'Analytics',\n inline: 'analytics',\n definition: 'An SEO or analytics tool sampling your pages.',\n },\n unknown: {\n label: 'Other',\n inline: 'other',\n definition:\n 'Detected and classified traffic that has not been attributed to a named vendor, ' +\n 'usually because it matched only a generic bot signature. Not a detection failure, ' +\n 'and worth sampling periodically: a new agent lands here before anyone writes a ' +\n 'signature for it.',\n },\n};\n\n/**\n * Non-canonical values reach the formatters only from pre-CHECK-constraint\n * rows in old snapshots and jsonb (`ai_crawler` is the known example, see\n * `docs/taxonomy/canonical-entities.md`).\n *\n * They get underscores expanded and nothing else. Expanding keeps them\n * readable where they land mid-sentence; NOT title-casing them is the\n * point, because inventing a polished label is exactly how an undesigned\n * value slips into the UI looking official. A stray `ai crawler` among\n * `AI assistant` and `Search engine` is legible and visibly not one of\n * the family.\n */\nfunction formatUnrecognizedValue(value: string): string {\n return value.replace(/_/g, ' ');\n}\n\n/**\n * Sentinels a previous revision briefly wrote into the category axis.\n *\n * #4875 replaced the `COALESCE`'s inline `'unknown'` with `__uncategorized__`\n * / `__unidentified__`. That shipped, so the strings are now sitting in\n * persisted chat history as jsonb, and history has no backfill. Dropping the\n * mapping when the sentinels were removed would leave rehydrated turns\n * rendering the raw `uncategorized` and treating the bucket as a real family\n * rather than the catch-all.\n *\n * Reads stay tolerant even though writes never produce these again.\n */\nconst LEGACY_CATEGORY_SENTINELS = new Set(['__uncategorized__', '__unidentified__']);\n\n/**\n * Render an `agent_category` value for display.\n *\n * `null` / `undefined` fold into the catch-all: `getAgentCategory` returns\n * NULL for humans and no-signal rows, which should never reach a category\n * chart, but folding beats crashing or rendering blank if one does.\n */\nexport function formatAgentCategory(value: string | null | undefined): string {\n if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.label;\n const meta = AGENT_CATEGORY_META[value as AgentCategory];\n return meta ? meta.label : formatUnrecognizedValue(value);\n}\n\n/** Lower-case form of {@link formatAgentCategory} for use inside a sentence. */\nexport function formatAgentCategoryInline(value: string | null | undefined): string {\n if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.inline;\n const meta = AGENT_CATEGORY_META[value as AgentCategory];\n return meta ? meta.inline : formatUnrecognizedValue(value);\n}\n\n/**\n * Display name for an agent whose `agent_type` was never resolved.\n *\n * Deliberately NOT one of the category words. This appears on the\n * top-agents table, a different surface from the category bars, so it\n * never sits beside them and does not need to be told apart from them by\n * spelling. Callers should prefer the agent's CATEGORY when they have one\n * (\"Scraper\" says more than \"Unnamed agent\") and fall back to this only\n * when both name and category are missing.\n */\nexport const UNNAMED_AGENT_LABEL = 'Unnamed agent';\n\n/**\n * Agent type definition (full entity)\n * Named as AgentTypeDefinition to avoid conflict with existing AgentType enum\n */\nexport const AgentTypeDefinitionSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n description: z.string().optional(),\n isLegitimate: z.boolean(),\n confidenceThreshold: z.number().min(0).max(100),\n detectionPatterns: z.array(z.string()),\n signatureSupport: z.boolean(),\n // Vendor tokens (own name + company aliases, e.g. ['chatgpt','openai']) matched\n // against a host-VERIFIED RFC 9421 Signature-Agent value to attribute a signed\n // agent to this type at ingest. Optional/additive; empty or absent ⇒ this type is\n // not resolvable by signature (only signatureSupport vendors carry aliases).\n signatureVendorAliases: z.array(z.string()).optional(),\n documentationUrl: z.string().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type AgentTypeDefinition = z.infer<typeof AgentTypeDefinitionSchema>;\n\n/**\n * Agent classification result\n */\nexport const AgentClassificationResultSchema = z.object({\n agentTypeId: z.string().uuid(),\n agentType: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n confidence: z.number().min(0).max(100),\n isLegitimate: z.boolean(),\n signatureVerified: z.boolean().optional(),\n matchedPatterns: z.array(z.string()),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AgentClassificationResult = z.infer<typeof AgentClassificationResultSchema>;\n\n/**\n * Agent classification request\n */\nexport const AgentClassificationRequestSchema = z.object({\n userAgent: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n ipAddress: z.string().optional(),\n sessionId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AgentClassificationRequest = z.infer<typeof AgentClassificationRequestSchema>;\n\n/**\n * Agent statistics for analytics\n */\nexport const AgentStatisticsSchema = z.object({\n agentTypeId: z.string().uuid(),\n agentType: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n detectionCount: z.number(),\n sessionCount: z.number(),\n averageConfidence: z.number(),\n lastSeen: z.date(),\n isLegitimate: z.boolean(),\n percentageOfTotal: z.number().optional(),\n});\nexport type AgentStatistics = z.infer<typeof AgentStatisticsSchema>;\n\n/**\n * Helper functions\n */\n\n/**\n * Check if an agent category is considered legitimate\n */\nexport function isLegitimateCategory(category: AgentCategory): boolean {\n const legitimateCategories: AgentCategory[] = [\n 'ai_assistant',\n 'search_engine',\n 'social_media',\n 'monitoring',\n 'analytics',\n ];\n return legitimateCategories.includes(category);\n}\n\n/**\n * Get display color for agent category (for UI)\n */\nexport function getCategoryColor(category: AgentCategory): string {\n const colors: Record<AgentCategory, string> = {\n ai_assistant: '#10b981', // green\n search_engine: '#3b82f6', // blue\n social_media: '#8b5cf6', // purple\n monitoring: '#06b6d4', // cyan\n scraper: '#ef4444', // red\n automation: '#f97316', // orange\n security: '#dc2626', // dark red\n analytics: '#6366f1', // indigo\n unknown: '#6b7280', // gray\n };\n return colors[category] || '#6b7280';\n}\n\n/**\n * Get category badge variant for UI\n */\nexport function getCategoryBadgeVariant(\n category: AgentCategory\n): 'default' | 'success' | 'warning' | 'destructive' {\n switch (category) {\n case 'ai_assistant':\n case 'search_engine':\n return 'success';\n case 'social_media':\n case 'monitoring':\n case 'analytics':\n return 'default';\n case 'scraper':\n case 'automation':\n case 'security':\n return 'destructive';\n case 'unknown':\n default:\n return 'warning';\n }\n}\n\n/**\n * Default agent types (for initialization)\n */\nexport const DEFAULT_AGENT_TYPES: Partial<AgentTypeDefinition>[] = [\n {\n name: 'chatgpt',\n displayName: 'ChatGPT',\n category: 'ai_assistant',\n description: 'OpenAI ChatGPT Browser',\n isLegitimate: true,\n confidenceThreshold: 95,\n signatureSupport: hasPinnedSigningVendor(['chatgpt', 'openai']),\n signatureVendorAliases: ['chatgpt', 'openai'],\n detectionPatterns: ['GPTBot', 'ChatGPT-User', 'x-gpt-signature'],\n },\n {\n name: 'claude',\n displayName: 'Claude',\n category: 'ai_assistant',\n description: 'Anthropic Claude Assistant',\n isLegitimate: true,\n confidenceThreshold: 95,\n // Derived FALSE today: Anthropic publishes no web-bot-auth key\n // directory (verified 2026-08-26) and the engine pins no anthropic\n // key. Flips automatically once anthropic.json lands in vendor-keys\n // and the manifest is regenerated.\n signatureSupport: hasPinnedSigningVendor(['claude', 'anthropic']),\n signatureVendorAliases: ['claude', 'anthropic'],\n detectionPatterns: ['Claude-Web', 'Claude-User', 'anthropic-ai', 'x-claude-signature'],\n },\n {\n name: 'perplexity',\n displayName: 'Perplexity',\n category: 'ai_assistant',\n description: 'Perplexity AI Assistant',\n isLegitimate: true,\n confidenceThreshold: 90,\n signatureSupport: false,\n detectionPatterns: ['PerplexityBot', 'Perplexica'],\n },\n {\n name: 'googlebot',\n displayName: 'Googlebot',\n category: 'search_engine',\n description: 'Google Search Crawler',\n isLegitimate: true,\n confidenceThreshold: 95,\n signatureSupport: false,\n detectionPatterns: ['Googlebot', 'Googlebot-Image', 'Googlebot-Video'],\n },\n {\n name: 'puppeteer',\n displayName: 'Puppeteer',\n category: 'automation',\n description: 'Headless Chrome Automation',\n isLegitimate: false,\n confidenceThreshold: 75,\n signatureSupport: false,\n detectionPatterns: ['HeadlessChrome', 'Puppeteer'],\n },\n];\n","/**\n * Admin API Types\n *\n * Types for administrative endpoints and operations\n */\n\nimport { z } from 'zod';\n\n/**\n * Project Reset Request Schema\n */\nexport const projectResetRequestSchema = z.object({\n confirmation: z.literal('RESET_PROJECT_DATA'),\n dryRun: z.boolean().optional().default(false),\n preserveMembers: z.boolean().optional().default(true),\n includeFingerprints: z.boolean().optional().default(true),\n});\n\nexport type ProjectResetRequest = z.infer<typeof projectResetRequestSchema>;\n\n/**\n * Project Reset Statistics\n */\nexport interface ProjectResetStats {\n detectionsDeleted: number;\n pixelsDeleted: number; // @deprecated Always 0 - pixels are never deleted during reset\n apiKeysDeleted: number;\n activityLogsDeleted: number;\n permissionCacheCleared: number;\n fingerprintLogsDeleted: number;\n onboardingProgressDeleted: number;\n membersRemoved: number;\n}\n\n/**\n * Project Reset Response\n */\nexport interface ProjectResetResponse {\n success: boolean;\n dryRun: boolean;\n project: {\n id: string;\n name: string;\n domain: string | null;\n friendlyId: string | null;\n };\n stats: ProjectResetStats;\n message: string;\n totalRecordsAffected: number;\n timestamp: string;\n}\n\n/**\n * Project Reset Preview Response\n */\nexport interface ProjectResetPreviewResponse {\n project: {\n id: string;\n name: string;\n domain: string | null;\n friendlyId: string | null;\n createdAt: Date;\n };\n preview: ProjectResetStats;\n totalRecords: number;\n message: string;\n requiredConfirmation: string;\n options: {\n preserveMembers: {\n description: string;\n default: boolean;\n };\n includeFingerprints: {\n description: string;\n default: boolean;\n };\n dryRun: {\n description: string;\n default: boolean;\n };\n };\n}\n\n/**\n * Admin Route Context\n * Used for admin-specific routes that require superadmin access\n */\nexport interface AdminRouteContext {\n adminId: string;\n adminEmail: string;\n isAdmin: boolean;\n}\n\n/**\n * Admin Project Route Context\n * Used for admin project management routes\n */\nexport interface AdminProjectRouteContext extends AdminRouteContext {\n params: {\n projectId: string;\n };\n}\n\n/**\n * User-Organization Assignment Types\n */\n\n/**\n * User Organization Assignment\n */\nexport interface UserOrganizationAssignment {\n userId: string;\n organizationId: string;\n role: 'owner' | 'admin' | 'member';\n joinedAt: Date;\n organizationName: string;\n organizationSlug: string;\n}\n\n/**\n * Assignment Change Request Schema\n */\nexport const assignmentChangeRequestSchema = z.object({\n userId: z.string().uuid('Invalid user ID'),\n organizationId: z.string().uuid('Invalid organization ID'),\n role: z.enum(['owner', 'admin', 'member'], {\n error: 'Role must be owner, admin, or member',\n }),\n action: z.enum(['assign', 'remove', 'update_role']),\n});\n\nexport type AssignmentChangeRequest = z.infer<typeof assignmentChangeRequestSchema>;\n\n/**\n * Batch Assignment Request Schema\n */\nexport const batchAssignmentRequestSchema = z.object({\n userIds: z.array(z.string().uuid()).min(1, 'At least one user ID required'),\n organizationId: z.string().uuid('Invalid organization ID'),\n role: z.enum(['owner', 'admin', 'member']),\n action: z.enum(['assign', 'remove']),\n});\n\nexport type BatchAssignmentRequest = z.infer<typeof batchAssignmentRequestSchema>;\n\n/**\n * Organization Membership Response\n */\nexport interface OrganizationMembershipResponse {\n success: boolean;\n data: UserOrganizationAssignment[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n hasNext: boolean;\n hasPrev: boolean;\n };\n error?: {\n code: string;\n message: string;\n details?: unknown;\n };\n}\n\n/**\n * Extended Audit Log Entry for User-Organization Operations\n */\nexport interface UserOrgAuditLogEntry {\n id: string;\n adminId: string;\n adminEmail: string;\n action: string;\n targetType: 'user' | 'organization' | 'system' | 'project';\n targetId?: string;\n details: {\n userId?: string;\n userEmail?: string;\n organizationId?: string;\n organizationName?: string;\n previousRole?: string;\n newRole?: string;\n role?: string;\n reason?: string;\n [key: string]: unknown;\n };\n ipAddress?: string;\n userAgent?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Audit Log Query Request Schema\n */\nexport const auditLogQuerySchema = z.object({\n page: z.coerce.number().min(1).default(1).optional(),\n limit: z.coerce.number().min(1).max(100).default(50).optional(),\n adminId: z.string().uuid().optional(),\n action: z.string().optional(),\n targetType: z.enum(['user', 'organization', 'system', 'project']).optional(),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n search: z.string().optional(),\n});\n\nexport type AuditLogQueryRequest = z.infer<typeof auditLogQuerySchema>;\n\nexport type GrowthConfigurationType = 'bouncer' | 'enterprise' | 'support' | 'integration';\n\nexport type GrowthOpportunityType = GrowthConfigurationType;\n\nexport type GrowthPriority = 'low' | 'medium' | 'high' | 'critical';\n\nexport interface GrowthBouncerThresholds {\n minAiTrafficRate: number;\n aiTrafficSpikeMultiplier: number;\n highAiTrafficThreshold: number;\n consistentHighTrafficDays: number;\n criticalAiTrafficRate: number;\n}\n\nexport interface GrowthEnterpriseThresholds {\n highVolumeThreshold: number;\n rapidGrowthRate: number;\n multiDomainCount: number;\n largeTeamSize: number;\n multiProjectCount: number;\n highPercentileThreshold: number;\n minEnterpriseIndicators: number;\n}\n\nexport interface GrowthSupportThresholds {\n inactiveDays: number;\n minSupportIndicators: number;\n criticalSupportScore: number;\n}\n\nexport interface GrowthIntegrationThresholds {\n minSessionsForBenefit: number;\n minAiRateForBenefit: number;\n}\n\nexport interface GrowthConfigurationThresholdMap {\n bouncer: GrowthBouncerThresholds;\n enterprise: GrowthEnterpriseThresholds;\n support: GrowthSupportThresholds;\n integration: GrowthIntegrationThresholds;\n}\n\nexport type GrowthConfigurationThreshold = GrowthConfigurationThresholdMap[GrowthConfigurationType];\n\nexport interface GrowthAgentConcentration {\n name: string;\n percentage: number;\n}\n\nexport interface GrowthBouncerOpportunityDetails {\n avgAiRate: number;\n latestAiRate: number;\n weekOverWeekChange: number;\n highTrafficDays: number;\n topAgents: GrowthAgentConcentration[];\n}\n\nexport interface GrowthBouncerOpportunityMetrics {\n sessionVolume: number;\n aiDetections: number;\n trend: 'increasing' | 'stable';\n}\n\nexport interface GrowthEnterpriseOpportunityDetails {\n sessionVolume: number;\n growthRate: number;\n domainCount: number;\n memberCount: number;\n projectCount: number;\n percentileRank: number | null;\n}\n\nexport interface GrowthEnterpriseOpportunityMetrics {\n weeklyVolume: number;\n monthlyGrowth: number;\n enterpriseIndicators: number;\n}\n\nexport interface GrowthSupportOpportunityDetails {\n unverifiedCount: number;\n inactiveCount: number;\n patterns: Record<string, number>;\n}\n\nexport interface GrowthSupportOpportunityMetrics {\n supportIndicators: number;\n integrationHealth: 'none' | 'partial' | 'healthy';\n}\n\nexport interface GrowthIntegrationOpportunityDetails {\n pixelCount: number;\n domainCount: number;\n wasmEnabled: boolean;\n}\n\nexport interface GrowthIntegrationOpportunityMetrics {\n sessionVolume: number;\n aiRate: number;\n}\n\ninterface BaseGrowthOpportunity<\n TType extends GrowthOpportunityType,\n TDetails extends object,\n TMetrics extends object,\n> {\n type: TType;\n score: number;\n priority: GrowthPriority;\n reason: string;\n details: TDetails;\n metrics: TMetrics;\n}\n\nexport type GrowthOpportunityDetails =\n | BaseGrowthOpportunity<\n 'bouncer',\n GrowthBouncerOpportunityDetails,\n GrowthBouncerOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'enterprise',\n GrowthEnterpriseOpportunityDetails,\n GrowthEnterpriseOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'support',\n GrowthSupportOpportunityDetails,\n GrowthSupportOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'integration',\n GrowthIntegrationOpportunityDetails,\n GrowthIntegrationOpportunityMetrics\n >;\n\nexport interface GrowthRecommendationPerformance {\n sessionGrowthRate?: number | null;\n sessionCount?: number | null;\n overallPercentile?: number | null;\n}\n\nexport interface GrowthRecommendationAnalytics {\n totalSessions?: number | null;\n averageDuration?: number | null;\n bounceRate?: number | null;\n timestamp?: string | number | Date | null;\n}\n\nexport interface GrowthRecommendationOnboarding {\n createdAt?: Date | string | null;\n hasActiveProjects: boolean;\n hasPixels: boolean;\n activePixels: number;\n teamSize: number;\n}\n\nexport interface GrowthRecommendationIntegration {\n projectCount: number;\n pixelCount: number;\n activePixels: number;\n}\n\nexport interface GrowthRecommendationContext {\n organizationId: string;\n performance?: GrowthRecommendationPerformance | null;\n analytics?: GrowthRecommendationAnalytics | null;\n onboarding?: GrowthRecommendationOnboarding;\n integration?: GrowthRecommendationIntegration;\n}\n\nexport type AdminExecutiveSummaryPeriod = '7d' | '30d' | '90d' | 'all';\n\nexport interface AdminExecutiveSummaryResponse {\n period: AdminExecutiveSummaryPeriod;\n /**\n * Counted exactly as the admin overview counts (its exclusion rules, customer\n * orgs only, deleted orgs and projects left out), so the two pages agree.\n */\n platformHealth: {\n totals: {\n /** Customer orgs: not deleted, at least one counted member, no test name. */\n orgs: number;\n /** Live projects in customer orgs. */\n projects: number;\n /** The overview's \"Signed up\", counted side. */\n users: number;\n /** Accounts the overview's exclusion rules leave out of `users`. */\n usersExcluded: number;\n /** Counted users who signed up in the period. */\n signupsInPeriod: number;\n /** Customer orgs created in the period. */\n newOrgsInPeriod: number;\n };\n /** The overview's \"Onboarded\": counted users whose org has a verified, working installation. */\n onboarded: number;\n /** The overview's \"Active users\": used the dashboard in the last 30 days, whatever the period. */\n activeUsers: {\n /** null when the dashboard activity source is unavailable. */\n last30d: number | null;\n };\n /** The overview's warnings for these numbers, shown with them. */\n warnings: string[];\n };\n enforce: {\n checkpoints: Record<string, unknown> | undefined;\n sessions: Record<string, unknown> | undefined;\n proofs: Record<string, unknown> | undefined;\n topAgents: Array<{\n agentName: string;\n proofCount: number;\n successCount: number;\n blockedCount: number;\n }>;\n };\n govern: {\n deployments: Record<string, unknown> | undefined;\n delegations: Record<string, unknown> | undefined;\n managedUsage: Record<string, unknown> | undefined;\n oneClickDeploys: {\n total: number;\n cfDeployed: number;\n newInPeriod: number;\n byTemplate: Array<{\n template: string | null;\n count: number;\n }>;\n };\n pendingApprovals: Record<string, unknown> | undefined;\n customDomains: Record<string, unknown> | undefined;\n };\n molti: {\n status: Record<string, unknown> | undefined;\n health: Record<string, unknown> | undefined;\n hostingBreakdown: Array<{\n hostingMode: string | null;\n region: string;\n aiProvider: string | null;\n count: number;\n }>;\n };\n detect: {\n trend: {\n currentPeriod: number | null;\n previousPeriod: number | null;\n changePercent: number | null;\n };\n classification: Array<{\n class: string;\n count: number;\n }>;\n pixels: Record<string, unknown> | undefined;\n };\n growthPipeline: {\n leads: {\n total: number;\n inPeriod: number;\n uncontacted: number;\n bySource: Array<{\n source: string | null;\n count: number;\n }>;\n };\n assessments: {\n total: number;\n inPeriod: number;\n withEmail: number;\n byTier: Array<{\n tier: string | null;\n count: number;\n }>;\n };\n integrations: Record<string, unknown> | undefined;\n };\n generatedAt: string;\n}\n\n/**\n * Every user, org and project count here is the admin overview's own: its\n * exclusion rules, customer orgs only, deleted orgs and projects left out.\n */\nexport interface AdminMetricsResponse {\n totals: {\n /** The overview's \"Signed up\", counted side. */\n users: number;\n /** Customer orgs. */\n organizations: number;\n /** Live projects in customer orgs. */\n projects: number;\n };\n /** Counted users by plan. */\n planDistribution: Array<{\n plan: string | null;\n count: number;\n }>;\n /** Counted users with and without a verified email. */\n verificationStats: {\n verified: number;\n unverified: number;\n };\n /**\n * The overview's installation-based \"Onboarded\": counted users whose org has\n * a verified, working installation, and the counted users who aren't.\n */\n onboardingStats: {\n onboarded: number;\n notOnboarded: number;\n };\n /** Counted users who signed up each day of the last 30 (UTC dates). */\n signupTrends: Array<{\n date: string;\n count: number;\n }>;\n /** Customer orgs by their number of counted members: up to 5, 6 to 20, over 20. */\n organizationSizes: {\n small: number;\n medium: number;\n large: number;\n };\n /** Traffic totals cover every project; the two org counts are customer orgs only. */\n detection: {\n totalDetectionsToday: number;\n totalDetections7d: number;\n totalDetections30d: number;\n aiAgentRate: number;\n /** Customer orgs whose live projects had rollup traffic in the last 30 days. */\n activeOrgsWithTraffic: number;\n /** Customer orgs with a gateway checkpoint on a live project. */\n orgsWithEnforcement: number;\n };\n enforcement: {\n totalDecisions: number;\n blocked: number;\n allowed: number;\n challenged: number;\n blockRate: number;\n allowRate: number;\n topBlockedAgents: Array<{ agentName: string; count: number }>;\n topAllowedAgents: Array<{ agentName: string; count: number }>;\n dataQuality: {\n partial: boolean;\n includedSources: string[];\n omittedSources: string[];\n message: string | null;\n };\n };\n timestamp: string;\n}\n\nexport interface AdminSessionDurationBucket {\n range: string;\n min: number;\n max: number;\n count: number;\n percentage: number;\n}\n\nexport interface AdminOrganizationSessionAnalytics {\n organizationId: string;\n organizationName: string;\n metrics: {\n totalSessions: number;\n uniqueSessions: number;\n averageDuration: number;\n medianDuration: number;\n minDuration: number;\n maxDuration: number;\n distribution: AdminSessionDurationBucket[];\n bounceRate: number;\n pagesPerSession: number;\n isSampled: boolean;\n sampleSize?: number;\n };\n comparison: {\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n incompleteDataSessions?: number;\n aiAgentPercentage: number;\n botPercentage: number;\n humanPercentage: number;\n incompleteDataPercentage?: number;\n };\n patterns: {\n peakHours: unknown[];\n mostVisitedPages: unknown[];\n navigationPatterns: unknown[];\n };\n trends: {\n sessionGrowth: number;\n durationTrend: number;\n bounceRateTrend: number;\n };\n}\n\nexport interface AdminSessionIndustryAverages {\n averageSessionDuration: number;\n averageBounceRate: number;\n averagePagesPerSession: number;\n averageSessionsPerOrg: number;\n medianSessionDuration: number;\n distribution: {\n aiAgentPercentage: number;\n botPercentage: number;\n humanPercentage: number;\n incompleteDataPercentage?: number;\n };\n}\n\nexport interface AdminSessionAnomaly {\n organizationId: string;\n organizationName: string;\n reasons: string[];\n severity: 'low' | 'medium' | 'high';\n metrics: {\n sessions: number;\n duration: number;\n bounceRate: number;\n aiPercentage: number;\n botPercentage: number;\n };\n}\n\nexport interface AdminSessionInsights {\n topPerformers: Array<{\n organizationName: string;\n reason: string;\n metrics: {\n bounceRate: number;\n pagesPerSession: number;\n };\n }>;\n needsAttention: Array<{\n organizationName: string;\n reason: string;\n recommendation: string;\n }>;\n opportunities: Array<{\n organizationName: string;\n opportunity: string;\n description: string;\n }>;\n trends: {\n growingOrganizations: Array<{\n organizationName: string;\n growth: number;\n }>;\n decliningOrganizations: Array<{\n organizationName: string;\n decline: number;\n }>;\n };\n}\n\nexport interface AdminSessionAnalyticsResponse {\n success: true;\n data: {\n organizations: AdminOrganizationSessionAnalytics[];\n industryAverages: AdminSessionIndustryAverages;\n anomalies: AdminSessionAnomaly[];\n insights: AdminSessionInsights;\n dateRange: {\n start: string;\n end: string;\n };\n metadata: {\n totalOrganizations: number;\n sortBy: 'sessions' | 'duration' | 'bounceRate' | 'growth';\n sortOrder: 'asc' | 'desc';\n };\n };\n}\n","/**\n * Wire contract for GET /api/admin/overview.\n *\n * `meta.warnings` carries every methodology caveat the response embeds\n * (attribution gaps, partial sections, stale rollups, and so on) so the\n * dashboard never hides one behind a silently-dropped field. All\n * timestamps are ISO-8601 strings; all dates are YYYY-MM-DD strings.\n */\n\nimport { z } from 'zod';\n\n/** Supported lookback windows for the admin overview. */\nexport const ADMIN_OVERVIEW_WINDOWS = ['7d', '30d', '90d'] as const;\nexport type AdminOverviewWindow = (typeof ADMIN_OVERVIEW_WINDOWS)[number];\n/** Window applied when the request omits one. */\nexport const DEFAULT_ADMIN_OVERVIEW_WINDOW: AdminOverviewWindow = '30d';\n/** Row cap applied to each list section when the request omits `listLimit`. */\nexport const ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT = 100;\n/** Hard ceiling on `listLimit`, regardless of what the request asks for. */\nexport const ADMIN_OVERVIEW_LIST_LIMIT_MAX = 500;\n\n/**\n * Split on '-' and round-trip through `Date.UTC` so a value like\n * 2026-02-30 (day overflow) or 2026-13-01 (month overflow) is rejected\n * instead of silently rolling into the next month or year.\n */\nfunction isCalendarDate(value: string): boolean {\n const [year, month, day] = value.split('-').map(Number);\n if (!year || !month || !day) return false;\n const date = new Date(Date.UTC(year, month - 1, day));\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n );\n}\n\n/** Query params for GET /api/admin/overview (parsed from URLSearchParams, so numbers are coerced). */\nexport const adminOverviewQuerySchema = z.object({\n window: z.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),\n // YYYY-MM-DD, must be a real calendar date (reject 2026-02-30, 2026-13-01, '2026-1-5', ISO datetimes)\n compareTo: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .refine(isCalendarDate, {\n message: 'compareTo must be a real calendar date in YYYY-MM-DD form',\n })\n .optional(),\n listLimit: z.coerce\n .number()\n .int()\n .min(1)\n .max(ADMIN_OVERVIEW_LIST_LIMIT_MAX)\n .default(ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT),\n});\nexport type AdminOverviewQuery = z.infer<typeof adminOverviewQuerySchema>;\n\n/** How a headline delta's `previous` value was computed. */\nexport const ADMIN_DELTA_BASES = ['created_at', 'rollup', 'none'] as const;\nexport type AdminDeltaBasis = (typeof ADMIN_DELTA_BASES)[number];\n/** A headline number with its value as of `compareTo`. previous is null when no prior value is computable (basis 'none'). */\nexport interface AdminDelta {\n current: number;\n previous: number | null;\n basis: AdminDeltaBasis;\n}\n\n/** The kinds of instrumentation an organization can have installed. */\nexport const INSTALLATION_KINDS = [\n 'agent',\n 'pixel',\n 'middleware',\n 'dns_gateway',\n 'mcp_server',\n 'beacon',\n] as const;\nexport type InstallationKind = (typeof INSTALLATION_KINDS)[number];\n/** The distinct installation records tracked, one level more specific than InstallationKind (middleware splits by runtime). */\nexport const INSTALLATION_TYPES = [\n 'pixel',\n 'middleware_node',\n 'middleware_dotnet',\n 'middleware_jvm',\n 'middleware_android',\n 'middleware_ios',\n 'middleware_no_traffic',\n 'dns_gateway',\n 'beacon',\n] as const;\nexport type InstallationType = (typeof INSTALLATION_TYPES)[number];\n/** The four buckets the admin overview classifies every traffic event into. */\nexport const TRAFFIC_TAXONOMY_BUCKETS = [\n 'human',\n 'ai_agent',\n 'ai_crawler',\n 'other_automation',\n] as const;\nexport type TrafficTaxonomyBucket = (typeof TRAFFIC_TAXONOMY_BUCKETS)[number];\n/** Order is precedence: a user matching several rules is attributed to the first. */\nexport const EXCLUSION_BUCKETS = [\n 'vouched',\n 'internal_team',\n 'test_pattern',\n 'shopify_review',\n 'cohort',\n] as const;\nexport type ExclusionBucket = (typeof EXCLUSION_BUCKETS)[number];\n/** The independently-fetchable sections of the admin overview response. */\nexport const ADMIN_OVERVIEW_SECTIONS = [\n 'ladder',\n 'installations',\n 'traffic',\n 'lists',\n 'hiAi',\n 'accounts',\n] as const;\nexport type AdminOverviewSection = (typeof ADMIN_OVERVIEW_SECTIONS)[number];\n/** Cache states a section can report in `meta.cache.status`. */\nexport const ADMIN_OVERVIEW_CACHE_STATUSES = ['hit', 'stale', 'miss', 'bypass'] as const;\nexport type AdminOverviewCacheStatus = (typeof ADMIN_OVERVIEW_CACHE_STATUSES)[number];\n\n/** events in the bucket, share = events / totalEvents (0 when totalEvents is 0), totalEvents = denominator for the whole scope. */\nexport interface TaxonomyTotals {\n events: number;\n share: number;\n totalEvents: number;\n}\nexport type TaxonomyBreakdown = Record<TrafficTaxonomyBucket, TaxonomyTotals>;\n\n/** The customer-acquisition funnel headline row, each stage a delta against `compareTo`. */\nexport interface AdminOverviewLadder {\n emailsCollected: AdminDelta;\n users: AdminDelta;\n signedInProxy: AdminDelta;\n onboarded: AdminDelta;\n activated: AdminDelta;\n}\n\n/** One per InstallationKind, customer-scoped. activeInWindow = installs with activity inside the window. orgCount = distinct customer organizations behind those installs (an org with 3 middleware pixels still counts once). */\nexport interface InstallationCard {\n kind: InstallationKind;\n total: AdminDelta;\n activeInWindow: number;\n orgCount: number;\n}\n/** Count of installations of one InstallationType, split into customer-owned vs excluded. */\nexport interface InstallationTypeCount {\n type: InstallationType;\n customer: number;\n excluded: number;\n total: number;\n}\n/** The installations section: per-kind summary cards plus the finer-grained type breakdown. */\nexport interface AdminOverviewInstallations {\n cards: InstallationCard[];\n byType: InstallationTypeCount[];\n}\n\n/**\n * Keys for the by-service traffic table. By-service traffic is attributed\n * per project installation profile: a project with exactly one\n * InstallationKind lands under that kind, a project with more than one kind\n * lands in 'mixed' (counting it under a single kind would double count), and\n * a project with none lands in 'none'.\n */\nexport const SERVICE_TRAFFIC_KEYS = [...INSTALLATION_KINDS, 'mixed', 'none'] as const;\nexport type ServiceTrafficKey = (typeof SERVICE_TRAFFIC_KEYS)[number];\n\n/** attribution is always 'project-profile' until the rollups carry a source dimension; the server adds a standing warning. */\nexport interface ServiceTrafficRow {\n service: ServiceTrafficKey;\n events: number;\n share: number;\n projects: number;\n attribution: 'project-profile';\n}\n/** One project's traffic for the window, broken into the four taxonomy buckets. */\nexport interface SiteTrafficRow {\n projectId: string;\n projectName: string;\n domain: string | null;\n organizationId: string;\n organizationName: string;\n events: number;\n share: number;\n buckets: Record<TrafficTaxonomyBucket, number>;\n}\n/** The traffic section: taxonomy breakdowns, per-service rollups, and the per-site list. */\nexport interface AdminOverviewTraffic {\n taxonomy: { window: TaxonomyBreakdown; allTime: TaxonomyBreakdown };\n byService: ServiceTrafficRow[];\n /** Capped by listLimit; bySiteTotal is the uncapped count. */\n bySite: SiteTrafficRow[];\n bySiteTotal: number;\n /** Earliest rollup date (YYYY-MM-DD); allTime means \"since this date\". null when no rollups exist. */\n coverageFrom: string | null;\n}\n\n/** An onboarded user who is a member of an org with at least one installation. */\nexport interface ActivatedUserRow {\n userId: string;\n email: string;\n name: string | null;\n organizationId: string;\n organizationName: string;\n installationKinds: InstallationKind[];\n onboardingCompletedAt: string | null;\n createdAt: string;\n}\n/**\n * Every new user, NOT gated on onboarding/installation status at all —\n * unlike `ActivatedUserRow`'s two lists (both scoped to a qualifying org's\n * membership), this is the raw `users` population itself: a user with zero\n * org membership and zero installs still appears here, with `organizationId`/\n * `organizationName` null and `installationKinds` empty. Exists to close the\n * gap where a legitimate signup with no installs was invisible in every\n * other per-person list.\n */\nexport interface NewSignupRow {\n userId: string;\n email: string;\n name: string | null;\n /** The user's earliest-joined organization, if any; null for a user with no org membership at all. */\n organizationId: string | null;\n organizationName: string | null;\n installationKinds: InstallationKind[];\n createdAt: string;\n}\n/**\n * The three person-level funnel stages the admin Customer Journey view\n * classifies every non-excluded user into. Deliberately three, not four:\n * the schema has no \"installed\" step distinct from \"onboarded\" (see\n * `orgActiveInstallationsCte`'s doc comment: activated is a strictly\n * stronger condition over the SAME verified-installation evidence\n * `orgInstallationsCte` checks, not a separate install event), so a row is\n * exactly one of:\n * - `signed_up`: a non-excluded user with no qualifying (onboarded) org.\n * - `onboarded`: member of a qualifying org (see `ActivatedUserRow`'s own\n * doc comment for what \"qualifying\" means) that is NOT also activated.\n * - `activated`: member of a qualifying org that also satisfies\n * `orgActiveInstallationsCte` (verified AND active in the window).\n * The admin Customer Journey page labels the `onboarded` stage \"Installed\"\n * in its own UI copy (plainer for a fast scan) while this type keeps the\n * same word Overview's ladder already uses for the identical population,\n * so the two never drift into two different predicates under two different\n * names.\n */\nexport type CustomerJourneyStage = 'signed_up' | 'onboarded' | 'activated';\n\n/**\n * One row per non-excluded user, for the admin Customer Journey view: the\n * per-person drill-down behind the aggregate ladder/funnel-breakdown numbers\n * already on `/admin`: same population, same exclusion rules, same\n * onboarded/activated predicates, just one row per person instead of one\n * count per stage. `organizationId`/`organizationName` are the org this\n * row's stage is attributed to (the qualifying org for `onboarded`/\n * `activated`, or the user's earliest-joined org of any kind for\n * `signed_up`, mirroring `NewSignupRow`'s `first_membership` for a user\n * with no qualifying org); both are null for a user with no org membership\n * at all.\n */\nexport interface CustomerJourneyRow {\n userId: string;\n email: string;\n name: string | null;\n organizationId: string | null;\n organizationName: string | null;\n /** Distinct members of organizationId; null when organizationId is null. */\n teamSize: number | null;\n /**\n * Installations configured for the attributed org, from the same source\n * the ladder's own rows use. Not gated on the verified/counted-kind\n * predicate that decides `stage`: an org can appear here with an\n * unverified pixel, or with the `agent` kind, even though neither counts\n * toward `onboarded`/`activated`. [] when the attributed org has none.\n */\n installationKinds: InstallationKind[];\n stage: CustomerJourneyStage;\n /**\n * Days since this row entered its current stage. null when not\n * computable: always for `activated` (no per-user activation timestamp\n * exists today, so this is never fabricated from a proxy), and for\n * `onboarded` when the qualifying org's install came from a teammate\n * (this user's own `onboardingCompletedAt` was never set, and the\n * installation tables only carry \"last seen/detected\" timestamps, not\n * \"first verified\" ones, so no honest fallback exists either).\n */\n daysInStage: number | null;\n /** True once daysInStage reaches or exceeds the stage's threshold (inclusive at the boundary). Always false when daysInStage is null. */\n stalled: boolean;\n createdAt: string; // ISO\n}\n\n/**\n * An account that finished setup and has no detection anywhere it can reach\n * (`listCompletedNotInstalled`, admin-activation.service.ts): one to reach\n * out to.\n */\nexport interface CompletedNotInstalledRow {\n userId: string;\n email: string;\n name: string | null;\n onboardingCompletedAt: string; // ISO, UTC\n /** As stored: setup_v2, setup_legacy, onboarding_agent, qualification, or a partner channel. */\n onboardingChannel: string | null;\n /** The user's earliest-joined non-deleted organization, for display; null when they have none. */\n organizationId: string | null;\n organizationName: string | null;\n}\n\n/** One `pixels` row joined to its project and org; `type` is derived from the middleware marker and engine probe. */\nexport interface PixelInstallationRow {\n pixelId: string;\n pixelName: string;\n type: InstallationType;\n projectId: string;\n projectName: string;\n domain: string | null;\n organizationId: string;\n organizationName: string;\n scope: 'customer' | 'excluded';\n detectionCount: number;\n lastDetectionAt: string | null;\n activeInWindow: boolean;\n createdAt: string;\n}\n/** An email that never became a user, sourced from `email_leads` or `assessments.lead_email`; sourceDetail is the raw source string. */\nexport interface LeadRow {\n email: string;\n source: 'email_lead' | 'assessment';\n sourceDetail: string | null;\n company: string | null;\n firstSeenAt: string;\n lastSeenAt: string;\n}\n/** How many users and organizations one exclusion rule (bucket) removed from the counts. */\nexport interface ExclusionAuditRow {\n bucket: ExclusionBucket;\n users: number;\n organizations: number;\n}\n/** A server-capped list: rows.length <= listLimit, total is the uncapped count. */\nexport interface AdminOverviewList<T> {\n rows: T[];\n total: number;\n}\n/**\n * A Hi-AI report requested by email, linked to the exact host that was\n * audited (apps/web/app/api/hi-ai/share/route.ts inserts `sourceUrl` from\n * the already-validated `host` at request time). `sourceUrl` is null for a\n * row recorded before that column existed, until\n * `scripts/backfill-hi-ai-lead-source-url.ts` fills it in from the legacy\n * `referer` header.\n */\nexport interface HiAiLeadRow {\n email: string;\n sourceUrl: string | null;\n createdAt: string;\n}\n/**\n * One host audited through the public Hi-AI tool (`/hi-ai/<host>`), sourced\n * from Amplitude `Page Viewed` events rather than a database row —\n * unattributed to any person, unlike {@link HiAiLeadRow}: this counts every\n * visit, with or without an email capture. `visits` is unique visitors in\n * the selected window (Amplitude `uniques`).\n */\nexport interface HiAiAuditRow {\n host: string;\n visits: number;\n}\n/** The Hi-AI section: leads linked to a person (email -> audited host) alongside the unattributed per-host audit breakdown. */\nexport interface AdminOverviewHiAi {\n leads: AdminOverviewList<HiAiLeadRow>;\n audits: AdminOverviewList<HiAiAuditRow>;\n}\n/**\n * The lists section shown below the headline numbers. `activatedUsers`,\n * `installationUsers`, `pixelInstallations`, and `leads` are server-capped by\n * listLimit; `exclusionAudit` is one row per ExclusionBucket and is not\n * capped.\n */\nexport interface AdminOverviewLists {\n activatedUsers: AdminOverviewList<ActivatedUserRow>;\n /**\n * Every member of a customer org with >=1 installation, regardless of\n * whether that individual user has personally completed the onboarding\n * wizard — the superset `activatedUsers` is filtered down from. Tag a row\n * to a specific installation kind client-side via\n * `installationKinds.includes(kind)`.\n */\n installationUsers: AdminOverviewList<ActivatedUserRow>;\n /**\n * Every new user, not gated on onboarding/installation status at all — a\n * strict superset of `installationUsers`' membership. See `NewSignupRow`.\n */\n newSignups: AdminOverviewList<NewSignupRow>;\n pixelInstallations: AdminOverviewList<PixelInstallationRow>;\n leads: AdminOverviewList<LeadRow>;\n exclusionAudit: ExclusionAuditRow[];\n}\n\n/** Everything the UI needs to explain the numbers, including every methodology caveat in `warnings`. */\nexport interface AdminOverviewMeta {\n generatedAt: string;\n window: AdminOverviewWindow;\n windowStart: string;\n windowEnd: string;\n /** The compareTo date the deltas were computed against, or null when no compareTo was given. */\n previousSnapshotAt: string | null;\n partial: boolean;\n failedSections: AdminOverviewSection[];\n warnings: string[];\n exclusions: { version: string; hash: string; buckets: ExclusionBucket[] };\n cache: { status: AdminOverviewCacheStatus; ageSeconds: number | null };\n rollupFreshness: { refreshedAt: string | null; fresh: boolean; ageSeconds: number | null };\n durationsMs: Partial<Record<AdminOverviewSection | 'total', number>>;\n}\n\n/**\n * Headline numbers that show \"N counted · M excluded\" and open a drill-down\n * of every account behind them. The first five mirror the ladder steps\n * (signedIn is the ladder's signedInProxy); the last three are the KYA-1147\n * people numbers.\n */\nexport const ADMIN_TRUSTED_METRICS = [\n 'emailsCollected',\n 'users',\n 'signedIn',\n 'onboarded',\n 'activated',\n 'activeUsers',\n 'peopleInOrgs',\n 'installedOrgs',\n] as const;\nexport type AdminTrustedMetric = (typeof ADMIN_TRUSTED_METRICS)[number];\n\n/**\n * Why an account a user-level exclusion did not catch is still left out:\n * every org that would count it is test-named (`test_org`), or, for an org\n * row, none of its members is a counted person (`no_counted_members`).\n */\nexport const ADMIN_ORG_EXCLUSION_REASONS = ['test_org', 'no_counted_members'] as const;\n\n/** `counted`, or the first rule that left the account out (user buckets take precedence). */\nexport const ADMIN_ACCOUNT_STATUSES = [\n 'counted',\n ...EXCLUSION_BUCKETS,\n ...ADMIN_ORG_EXCLUSION_REASONS,\n] as const;\nexport type AdminAccountStatus = (typeof ADMIN_ACCOUNT_STATUSES)[number];\n\nexport interface AdminCountSplit {\n counted: number;\n excluded: number;\n}\n\n/** One day of dashboard activity, `date` as YYYY-MM-DD. */\nexport interface AdminDailyActive {\n date: string;\n counted: number;\n excluded: number;\n}\n\n/**\n * Dashboard activity from Amplitude (`_active`, platform Web), the same\n * source the /cpun report uses for MAU. `available: false` means the source\n * could not be read: the card says \"unavailable\", never 0.\n */\nexport interface AdminActiveUsersSummary {\n available: boolean;\n /** Mean of `daily` per day, unrounded. Null when unavailable. */\n dailyAverage: { counted: number; excluded: number } | null;\n daily: AdminDailyActive[];\n}\n\n/** Overview section: the split behind every trusted metric. A null split means its source was unavailable. */\nexport interface AdminOverviewAccounts {\n splits: Record<AdminTrustedMetric, AdminCountSplit | null>;\n activeUsers: AdminActiveUsersSummary;\n}\n\n/** GET /api/admin/overview/accounts query. */\n/** Drill-down status filter: everyone, any exclusion, or one status. */\nexport const ADMIN_ACCOUNTS_STATUS_FILTERS = [\n 'all',\n 'excluded',\n ...ADMIN_ACCOUNT_STATUSES,\n] as const;\nexport type AdminAccountsStatusFilter = (typeof ADMIN_ACCOUNTS_STATUS_FILTERS)[number];\n\n/**\n * GET /api/admin/overview/accounts query. `status` filters on the server,\n * so the row cap applies to the filtered list and an exclusion is never cut\n * off by counted rows.\n */\nexport const adminAccountsQuerySchema = z.object({\n metric: z.enum(ADMIN_TRUSTED_METRICS),\n window: z.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),\n status: z.enum(ADMIN_ACCOUNTS_STATUS_FILTERS).default('all'),\n});\n\n/** 30-day activity behind one account or org. Dashboard fields are null when Amplitude is unavailable. */\nexport interface AdminAccountActivity {\n /** Days with dashboard activity in the last 30. */\n dashboardActiveDays: number | null;\n /** Most recent dashboard day in the last 30, YYYY-MM-DD. */\n lastDashboardDay: string | null;\n /** Most recent action this person took that the app logged (activity_logs). */\n lastActionAt: string | null;\n /** Live projects across the person's (or org's) orgs. */\n projects: number;\n /** Detections on those projects in the last 30 days (daily rollup). */\n detections30d: number;\n apiKeyLastUsedAt: string | null;\n}\n\nexport interface AdminPersonRow {\n subject: 'person';\n /** User id. */\n id: string;\n email: string;\n name: string | null;\n organizationId: string | null;\n organizationName: string | null;\n status: AdminAccountStatus;\n createdAt: string;\n /** YYYY-MM-DD: the later of the last dashboard day and the last logged action. */\n lastActiveAt: string | null;\n activity: AdminAccountActivity;\n}\n\n/** emailsCollected only: an address that never became an account. */\nexport interface AdminLeadRow {\n subject: 'lead';\n /** The lowercased email. */\n id: string;\n email: string;\n status: AdminAccountStatus;\n createdAt: string;\n}\n\nexport interface AdminOrgRow {\n subject: 'org';\n /** Organization id. */\n id: string;\n name: string;\n status: AdminAccountStatus;\n /** Members split by the user-level exclusion rules. */\n members: AdminCountSplit;\n createdAt: string;\n /** YYYY-MM-DD: the latest day any member was active. */\n lastActiveAt: string | null;\n activity: AdminAccountActivity;\n}\n\nexport type AdminAccountRow = AdminPersonRow | AdminLeadRow | AdminOrgRow;\n\n/** The full GET /api/admin/overview/accounts payload. */\nexport interface AdminAccountsResponse {\n metric: AdminTrustedMetric;\n window: AdminOverviewWindow;\n /**\n * False when the source behind the number could not be read (activeUsers\n * with Amplitude down). `rows`, `total` and `split` are then empty and mean\n * \"unknown\", not 0.\n */\n available: boolean;\n rows: AdminAccountRow[];\n /** The status filter `rows` was read with. */\n status: AdminAccountsStatusFilter;\n /** Every account behind the metric, whatever the filter. */\n total: number;\n /** Accounts matching `status`, before the row cap. */\n matching: number;\n split: AdminCountSplit;\n byStatus: Partial<Record<AdminAccountStatus, number>>;\n /** True when `rows` stops short of `matching`. */\n truncated: boolean;\n dashboardActivity: { available: boolean };\n warnings: string[];\n generatedAt: string;\n}\n\n/** The full GET /api/admin/overview payload. */\nexport interface AdminOverviewResponse {\n ladder: AdminOverviewLadder;\n installations: AdminOverviewInstallations;\n traffic: AdminOverviewTraffic;\n lists: AdminOverviewLists;\n hiAi: AdminOverviewHiAi;\n accounts: AdminOverviewAccounts;\n meta: AdminOverviewMeta;\n}\n","/**\n * Display-time Claude runtime delineation.\n *\n * The user-visible problem: every Claude assistant runtime — Claude Code (the\n * CLI), Claude on the web, the user-initiated fetcher, the search assistant —\n * collapses into one undifferentiated \"Claude\" row, so the dashboard can't tell\n * an operator *which* Claude touched their site. The ratified taxonomy north-star\n * (`docs/architecture/agent-identity-taxonomy.md` §3.1) is explicit that this is\n * \"one product, one vendor, three runtimes — NOT three catalog rows.\" So we do\n * NOT split `agent_types`; we refine the *rendered* label from the request's\n * User-Agent at display time.\n *\n * Pure and display-only: these helpers MUST NEVER influence `category` /\n * `detection_class` / classification — they only change the string shown to a\n * human. Keyed off the real `anthropic-claude` SSOT tokens in\n * `constants/agents.ts`; mirrors the UA→variant precedent in\n * `apps/web/lib/agents/canonical-ids.ts` (which already splits claude-code vs\n * claude-desktop for the connect flow).\n *\n * @module utils/agent-runtime-label\n */\n\n/** Canonical display name of the single Claude product row (SSOT `anthropic-claude`, name: 'Claude'). */\nconst CLAUDE_CANONICAL_DISPLAY = 'Claude';\n\n/**\n * The retired-duplicate Claude twin keeps `display_name` of the form\n * \"Claude (deprecated duplicate — see <uuid>)\" (only its `name` slug is mutated\n * with `-DEPRECATED-`). Per-event surfaces that aren't WHERE-guarded can still\n * render a historical detection FK'd to it, so the gate matches the twin too —\n * refining it cleans the ugly label down to a real runtime label.\n */\nconst CLAUDE_DEPRECATED_TWIN = /^Claude \\(deprecated/i;\n\n/**\n * True when a *displayed* agent label refers to the canonical Claude product\n * (or its retired twin). Deliberately does NOT match the separate catalog rows\n * \"ClaudeBot\" (training crawler) or \"Anthropic AI Crawler\" — those are distinct\n * agents, not Claude runtimes, and must keep their own labels.\n */\nexport function isClaudeProductLabel(displayName: string | null | undefined): boolean {\n if (!displayName) return false;\n const d = displayName.trim();\n return d === CLAUDE_CANONICAL_DISPLAY || CLAUDE_DEPRECATED_TWIN.test(d);\n}\n\n/**\n * The Claude UA-token vocabulary, exported so KYA-1099's runtime_surface\n * derivation (`apps/web/lib/services/detections/claude-runtime-surface.ts`)\n * shares this ONE tokenization with the display label above, rather than\n * hand-copying the token list into a second, independently-maintained regex.\n * Case-insensitive; `userAgent` is lowercased once per call.\n */\nexport function hasClaudeCodeToken(userAgent: string | null | undefined): boolean {\n const ua = (userAgent ?? '').toLowerCase();\n return ua.includes('claude-code') || ua.includes('claude code');\n}\n\nexport function hasClaudeUserToken(userAgent: string | null | undefined): boolean {\n return (userAgent ?? '').toLowerCase().includes('claude-user');\n}\n\nexport function hasClaudeSearchBotToken(userAgent: string | null | undefined): boolean {\n return (userAgent ?? '').toLowerCase().includes('claude-searchbot');\n}\n\n/**\n * Map a Claude request's User-Agent (plus, KYA-1099, the persisted\n * `detections.runtime_surface`) to its runtime sub-label. Always returns a\n * \"Claude…\"-prefixed string (never a non-Claude label), so a caller that has\n * already established the agent is Claude can use the result directly.\n *\n * Token source (`constants/agents.ts` `anthropic-claude.patterns`):\n * - `claude-code` AND `Claude-User` (Claude Code's OWN WebFetch UA embeds\n * both) → \"Claude Code (web fetch)\"\n * - `claude-code` / `claude code` alone → \"Claude Code\" (the CLI)\n * - `Claude-SearchBot` → \"Claude SearchBot\"\n * - `Claude-User` alone → \"Claude (web fetch)\" (assistant browsing for a user)\n * - `Claude-Web` / model UAs / unknown → \"Claude\"\n *\n * `runtimeSurface` (KYA-1099 W1/W2, optional — existing callers compile\n * unchanged) is consulted ONLY when none of the UA tokens above matched: a\n * plain `curl`/`Wget` (or Claude Desktop) request carries no\n * Claude-identifying UA token at all — including an EMPTY UA, checked here\n * too (Bugbot KYA-1099 review: an empty UA used to short-circuit to bare\n * \"Claude\" before runtimeSurface was ever read; KYA-1099 W7's session-grain\n * rows have no UA at ALL, so this path is their only signal) — so a request\n * that a VERIFIED delegation (not a UA guess — see\n * `resolve-delegation-rung-agent-type.ts`) resolved to Claude still gets a\n * runtime-flavored label:\n * - `runtimeSurface === 'cli'` AND UA starts with `curl/` → \"Claude Code (curl)\"\n * - `runtimeSurface === 'cli'` AND UA starts with `Wget/`/`wget/` → \"Claude Code (wget)\"\n * - `runtimeSurface === 'cli'`, anything else → \"Claude Code\"\n * - `runtimeSurface === 'native_app'` → \"Claude Desktop\"\n * - `runtimeSurface === 'browser'` → \"Claude (browser)\"\n *\n * The `claude-cowork` branch is DORMANT (Part C, capture-first): Claude Cowork\n * has no published User-Agent as of 2026-06 (it runs in a sandboxed VM behind a\n * MITM proxy; absent from Anthropic's crawler docs). The branch is keyed on a\n * placeholder token and must be reconfirmed against real traffic before it can\n * fire on anything live.\n */\nexport function claudeRuntimeLabel(\n userAgent: string | null | undefined,\n runtimeSurface?: string | null\n): string {\n const ua = (userAgent ?? '').toLowerCase();\n if (ua) {\n const hasClaudeCode = hasClaudeCodeToken(ua);\n const hasClaudeUser = hasClaudeUserToken(ua);\n if (hasClaudeCode && hasClaudeUser) return 'Claude Code (web fetch)';\n if (hasClaudeCode) return 'Claude Code';\n if (ua.includes('claude-cowork')) return 'Claude Cowork'; // Part C: placeholder token, capture-first\n if (hasClaudeSearchBotToken(ua)) return 'Claude SearchBot';\n if (hasClaudeUser) return 'Claude (web fetch)';\n }\n if (runtimeSurface === 'cli') {\n if (ua.startsWith('curl/')) return 'Claude Code (curl)';\n if (ua.startsWith('wget/')) return 'Claude Code (wget)';\n return 'Claude Code';\n }\n if (runtimeSurface === 'native_app') return 'Claude Desktop';\n // KYA-1099 W7 — session rows have no UA at all (the carrier is the only\n // signal), so 'browser' needs its own label here too, not just 'cli'/\n // 'native_app'.\n if (runtimeSurface === 'browser') return 'Claude (browser)';\n return 'Claude';\n}\n\n/**\n * Refine a displayed agent label: when it's the canonical Claude product (or its\n * retired twin), return the UA-derived (+ KYA-1099 runtime_surface-derived)\n * runtime sub-label; otherwise return the label unchanged. Idempotent —\n * re-applying to an already-refined label (e.g. \"Claude Code\") is a no-op,\n * because the gate fires only on exact \"Claude\" or the deprecated twin.\n * Preserves `null` / `undefined` so it can sit directly on a nullable display\n * column. `runtimeSurface` is optional and additive — existing 2-arg call\n * sites compile and behave unchanged.\n */\nexport function refineClaudeDisplayLabel<T extends string | null | undefined>(\n displayName: T,\n userAgent: string | null | undefined,\n runtimeSurface?: string | null\n): T | string {\n return isClaudeProductLabel(displayName)\n ? claudeRuntimeLabel(userAgent, runtimeSurface)\n : displayName;\n}\n\n/**\n * `refineClaudeDisplayLabel` for a SESSION-grain row (KYA-1099 W7):\n * `unified_agent_sessions` carries no raw User-Agent at all, so every\n * session-row read path (`activity-lens.service.ts`, `recent-agent-sessions\n * .service.ts`, `agent-session-detail.service.ts`) was pinning `userAgent` to\n * `null` at the call site. Pinning it here instead means each of those three\n * call sites, and any future one, can't accidentally pass a stale/wrong UA to\n * a session-grain row.\n */\nexport function refineSessionGrainClaudeLabel<T extends string | null | undefined>(\n displayName: T,\n runtimeSurface: string | null | undefined\n): T | string {\n return refineClaudeDisplayLabel(displayName, null, runtimeSurface);\n}\n","/**\n * Isomorphic request correlation-id derivation.\n *\n * Every detection surface — the Cloudflare gateway worker, the published SDK\n * middleware (Next.js / Express), the Next.js detector route, and the browser\n * beacon — needs the SAME canonical id for a request so its records can be\n * correlated across surfaces. This module is the single producer of that id:\n * one 32-hex `correlation_id` derived from request headers, with a fixed\n * precedence and a guaranteed-valid output.\n *\n * Precedence (first match wins):\n * 1. W3C `traceparent` trace-id (the 32-hex middle segment), rejecting the\n * all-zero \"invalid\" sentinel,\n * 2. the `x-kya-correlation-id` header,\n * 3. a caller-provided `fallback` (e.g. an existing per-surface request id),\n * 4. a freshly minted UUIDv4 (dashes stripped → 32-hex).\n *\n * Edge/Node/browser safe: the mint path uses `globalThis.crypto.randomUUID`,\n * available on Node 18+, Cloudflare Workers, and browsers. Header lookup accepts\n * a `Headers` instance OR a plain record (case-insensitive), so it works on\n * every surface without callers pre-normalizing.\n */\n\nimport { z } from 'zod';\n\n/** Header carrying our canonical 32-hex correlation id between surfaces. */\nexport const CORRELATION_ID_HEADER = 'x-kya-correlation-id';\n\n/** Canonical stored shape: 32 lowercase hex chars. */\nexport const CorrelationIdSchema = z.string().regex(/^[0-9a-f]{32}$/);\n\n/**\n * W3C `traceparent` grammar: `version-traceId-spanId-flags`.\n * Only `trace` is used downstream; `ver`/`span`/`flags` are matched but ignored.\n */\nconst TRACEPARENT_RE =\n /^(?<ver>[0-9a-f]{2})-(?<trace>[0-9a-f]{32})-(?<span>[0-9a-f]{16})-(?<flags>[0-9a-f]{2})$/;\n\n/** The W3C \"invalid\" trace-id sentinel — must never be used as a correlation id. */\nconst ZERO_TRACE_ID = '0'.repeat(32);\n\n/**\n * Case-insensitive single-header lookup over both a `Headers` instance and a\n * plain record. For a record, keys are matched case-insensitively and a\n * `string[]` value resolves to its first element. Returns `null` for a missing\n * or empty value.\n */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | null {\n const lower = name.toLowerCase();\n\n if (typeof (headers as Headers).get === 'function') {\n const value = (headers as Headers).get(lower);\n return value && value.length > 0 ? value : null;\n }\n\n const record = headers as Record<string, string | string[] | undefined>;\n for (const key of Object.keys(record)) {\n if (key.toLowerCase() !== lower) continue;\n const raw = record[key];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value && value.length > 0 ? value : null;\n }\n return null;\n}\n\n/**\n * Normalize any candidate to canonical 32-hex (lowercase, dashes stripped) or\n * `null` if it does not validate. Both bare 32-hex strings and dashed UUIDs\n * funnel through here.\n */\nfunction normalizeHex(value: string | null | undefined): string | null {\n if (typeof value !== 'string' || value.length === 0) return null;\n const candidate = value.toLowerCase().replace(/-/g, '');\n const parsed = CorrelationIdSchema.safeParse(candidate);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Extract the trace-id from a `traceparent` value, or `null` when it is absent,\n * malformed, or carries the all-zero invalid sentinel. The extracted trace-id is\n * already canonical 32 lowercase hex by the grammar.\n */\nfunction extractTraceId(traceparent: string | null): string | null {\n if (!traceparent) return null;\n const match = TRACEPARENT_RE.exec(traceparent);\n const trace = match?.groups?.trace;\n if (!trace || trace === ZERO_TRACE_ID) return null;\n return trace;\n}\n\n/**\n * Normalize any candidate to 32-hex, or `null` if it isn't valid. Lowercases and\n * strips dashes (so a canonical UUID is accepted) before validating against\n * {@link CorrelationIdSchema}.\n */\nexport function toStoredCorrelationId(value: string | null | undefined): string | null {\n return normalizeHex(value);\n}\n\n/**\n * Derive the correlation id for a request, by precedence:\n * 1. W3C `traceparent` trace-id (the 32-hex middle segment; reject the\n * all-zero \"invalid\" sentinel),\n * 2. `x-kya-correlation-id` header,\n * 3. the provided `fallback` (e.g. an existing per-surface request id),\n * 4. a freshly minted UUIDv4 (dashes stripped → 32-hex).\n * Always returns a valid 32-hex string. Accepts a `Headers` instance OR a\n * plain record (case-insensitive lookup) so it works on every surface.\n *\n * NOTE on a client-supplied BODY id: `fallback` is the LOWEST trusted source\n * (below transport `traceparent` / header). Surfaces vary intentionally on where\n * a client-body correlation id sits: the pixel surfaces (pixel identify / track,\n * log-detection) trust their own SDK's body id ABOVE traceparent — they pass it\n * as a pre-check, not via `fallback` — while bouncer (proof.service) trusts the\n * inbound transport `traceparent` over a client claim and passes the body id AS\n * the `fallback`. That asymmetry is a deliberate per-surface trust decision, not\n * a uniform rule — match the surface's existing pattern when adding a caller.\n */\n/**\n * Extract a correlation id that was PROPAGATED on the request headers (W3C\n * `traceparent` trace-id, else `x-kya-correlation-id`), or `null` when neither\n * is present. Unlike {@link deriveCorrelationId} this NEVER falls back or mints —\n * use it when a minted id would be useless, e.g. an alias anchor that must match\n * an id actually stamped on another surface's row rather than a fresh orphan.\n */\nexport function extractCorrelationIdFromHeaders(\n headers: Headers | Record<string, string | string[] | undefined>\n): string | null {\n const fromTrace = extractTraceId(getHeader(headers, 'traceparent'));\n if (fromTrace) return fromTrace;\n\n return normalizeHex(getHeader(headers, CORRELATION_ID_HEADER));\n}\n\nexport function deriveCorrelationId(\n headers: Headers | Record<string, string | string[] | undefined>,\n fallback?: string | null\n): string {\n const fromHeaders = extractCorrelationIdFromHeaders(headers);\n if (fromHeaders) return fromHeaders;\n\n const fromFallback = normalizeHex(fallback);\n if (fromFallback) return fromFallback;\n\n return globalThis.crypto.randomUUID().replace(/-/g, '').toLowerCase();\n}\n","/**\n * Authentication Validation Schemas\n *\n * Zod schemas for validating authentication-related data\n * Used across the application for consistent validation\n */\n\nimport { z } from 'zod';\n\n/**\n * Base password validation schema\n * Enforces password security requirements\n */\nexport const passwordSchema = z\n .string()\n .min(8, 'Password must be at least 8 characters long')\n .max(128, 'Password must not exceed 128 characters')\n .regex(\n /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)/,\n 'Password must contain at least one lowercase letter, one uppercase letter, and one number'\n );\n\n/**\n * Password reset confirmation validation schema\n * Validates token and ensures passwords match\n */\nexport const resetPasswordSchema = z\n .object({\n token: z.string().min(1, 'Token is required'),\n password: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.password === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\nexport type ResetPasswordData = z.infer<typeof resetPasswordSchema>;\n","/**\n * Admin API Validation Schemas\n *\n * Schemas for admin-specific endpoints\n * Used for validation and type safety in admin routes\n */\n\nimport { z } from 'zod';\n\n/**\n * Performance recalculation request schema\n * Used for POST /api/admin/organizations/[id]/performance\n */\nexport const PerformanceRecalculationRequestSchema = z.object({\n periodType: z.enum(['daily', 'weekly', 'monthly']).optional().default('weekly'),\n});\n\n/**\n * Growth opportunity status update schema\n * Used for PATCH /api/admin/growth-opportunities\n */\nexport const GrowthOpportunityUpdateSchema = z.object({\n opportunityId: z.string().min(1, 'Opportunity ID is required'),\n status: z.enum(['active', 'contacted', 'converted', 'dismissed']).optional(),\n assignedTo: z.string().nullable().optional(),\n notes: z.string().nullable().optional(),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n dismissedReason: z.string().nullable().optional(),\n});\n\n/**\n * Growth batch identification request schema\n * Used for POST /api/admin/growth-opportunities\n */\nexport const GrowthBatchRequestSchema = z\n .object({\n runBatch: z.boolean().optional().default(false),\n organizationIds: z.array(z.string()).optional(),\n })\n .refine((data) => data.runBatch || (data.organizationIds && data.organizationIds.length > 0), {\n message: 'Either runBatch must be true or organizationIds must be provided',\n });\n\n/**\n * Growth configuration thresholds schema\n * Used for PUT /api/admin/growth-configurations\n */\nexport const GrowthConfigurationThresholdsSchema = z\n .object({\n // Bouncer thresholds\n minAiTrafficRate: z.number().min(0).max(100).optional(),\n highAiTrafficThreshold: z.number().min(0).max(100).optional(),\n aiTrafficSpikeMultiplier: z.number().min(1).optional(),\n consistentHighTrafficDays: z.number().int().min(1).optional(),\n criticalAiTrafficRate: z.number().min(0).max(100).optional(),\n\n // Enterprise thresholds\n highVolumeThreshold: z.number().int().min(1).optional(),\n rapidGrowthRate: z.number().min(0).optional(),\n multiDomainCount: z.number().int().min(1).optional(),\n largeTeamSize: z.number().int().min(1).optional(),\n multiProjectCount: z.number().int().min(1).optional(),\n highPercentileThreshold: z.number().min(0).max(100).optional(),\n minEnterpriseIndicators: z.number().int().min(1).optional(),\n\n // Support thresholds\n minIntegrationMethods: z.number().int().min(1).optional(),\n maxInactivePixels: z.number().int().min(0).optional(),\n inactiveDays: z.number().int().min(1).optional(),\n minSupportIndicators: z.number().int().min(1).optional(),\n criticalSupportScore: z.number().min(0).optional(),\n\n // Integration thresholds\n minSessionsForBenefit: z.number().int().min(1).optional(),\n minAiRateForBenefit: z.number().min(0).max(100).optional(),\n })\n .strict();\n\n/**\n * Growth configuration update request schema\n */\nexport const GrowthConfigurationUpdateSchema = z.object({\n configType: z.enum(['bouncer', 'enterprise', 'support', 'integration']),\n thresholds: GrowthConfigurationThresholdsSchema,\n});\n\n/**\n * Growth configuration reset request schema\n */\nexport const GrowthConfigurationResetSchema = z.object({\n configType: z.enum(['bouncer', 'enterprise', 'support', 'integration', 'all']),\n});\n\n/**\n * Admin query parameters validation\n */\nexport const AdminQueryParamsSchema = z.object({\n limit: z.coerce.number().min(1).max(500).optional().default(100),\n offset: z.coerce.number().min(0).optional().default(0),\n sortBy: z.string().optional(),\n sortOrder: z.enum(['asc', 'desc']).optional().default('desc'),\n});\n\n/**\n * Growth opportunities query parameters\n */\nexport const GrowthOpportunitiesQuerySchema = AdminQueryParamsSchema.extend({\n type: z.enum(['bouncer', 'enterprise', 'support', 'integration']).optional(),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n status: z.enum(['active', 'contacted', 'converted', 'dismissed']).optional(),\n assignedTo: z.string().optional(),\n});\n\n/**\n * Recommendation query parameters\n * Used for GET /api/admin/recommendations\n */\nexport const RecommendationQuerySchema = z.object({\n organizationId: z.string().min(1).optional(),\n type: z.enum(['bouncer', 'enterprise', 'support', 'integration']).optional(),\n minConfidence: z.coerce.number().min(0).max(1).optional(),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n});\n\n/**\n * Recommendation generation request schema\n * Used for POST /api/admin/recommendations\n */\nexport const RecommendationGenerationSchema = z.object({\n organizationId: z.string().min(1, 'Organization ID is required'),\n forceRefresh: z.boolean().optional().default(false),\n});\n","import { z } from 'zod';\n\n/**\n * Wire shape of `GET /api/v1/kya-os/consent-policy`, defined once here. The\n * response is the project's consent policy as a client needs to render and\n * pre-check it; it is authenticated with the project API key.\n *\n * `etag` is the BARE hash (lowercase hex). The HTTP `ETag` header carries the\n * same value as a quoted strong validator, `\"<etag>\"`, on 200 and 304.\n * `riskLevel` is ConsentConfig's capability risk set, unchanged.\n */\nexport const ConsentPolicyRiskLevelSchema = z.enum(['low', 'medium', 'high', 'critical']);\nexport type ConsentPolicyRiskLevel = z.infer<typeof ConsentPolicyRiskLevelSchema>;\n\nexport const ConsentPolicyCapabilitySchema = z.strictObject({\n scope: z.string().min(1),\n defaultOn: z.boolean(),\n riskLevel: ConsentPolicyRiskLevelSchema,\n});\n\nexport const ConsentPolicyResponseSchema = z.strictObject({\n allowedScopes: z.array(z.string().min(1)).optional(),\n maxGrantSeconds: z.number().int().positive().optional(),\n capabilities: z.array(ConsentPolicyCapabilitySchema).optional(),\n etag: z.string().regex(/^[0-9a-f]{64}$/),\n});\nexport type ConsentPolicyResponse = z.infer<typeof ConsentPolicyResponseSchema>;\n","/**\n * Wire contract for the Fly gateway's internal tools endpoints\n * (#2029, #2027).\n *\n * Routes:\n * GET /api/gateway/internal/tools/:orgId\n * — org-level aggregated tool list from the 60s cache\n * POST /api/gateway/internal/tools/:orgId/discover\n * — user-scoped single-upstream discovery (Phase 4 #1990)\n *\n * These are Fly → Vercel bodies. The Vercel dashboard's proxy\n * routes and hooks validate incoming responses against these\n * schemas, and the gateway route handlers validate their outgoing\n * body to keep both sides pinned to the same shape.\n */\n\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// Discovered tool (shared shape across endpoints)\n// ---------------------------------------------------------------------------\n\nexport const discoveredToolSchema = z\n .object({\n name: z.string(),\n description: z.string().optional(),\n /**\n * JSON-schema object describing the tool's arguments. Shape\n * comes from the upstream MCP server and varies widely —\n * permissive `record(unknown)` rather than pinning the JSON\n * Schema draft here. The Tool Testing Panel renders a\n * skeleton from whatever it gets.\n */\n inputSchema: z.record(z.string(), z.unknown()).optional(),\n })\n .strict();\n\nexport type DiscoveredTool = z.infer<typeof discoveredToolSchema>;\n\n// ---------------------------------------------------------------------------\n// Per-upstream error — new in #2027's partial-success envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Categorized failure mode for a single upstream during org-level\n * aggregation. The dashboard uses the `code` to drive retry\n * behavior and the user-facing label; `message` surfaces in the\n * tooltip so operators can diagnose.\n */\nexport const upstreamDiscoveryErrorSchema = z\n .object({\n code: z.enum([\n /** Upstream returned 401/403 or the MCP handshake was rejected. */\n 'auth_failed',\n /** Upstream was healthy but refused tools/list (e.g. requires per-user auth). */\n 'per_user_auth_required',\n /** Upstream timed out during the handshake or tools/list call. */\n 'timeout',\n /** MCP handshake failed — protocol negotiation, bad JSON, etc. */\n 'handshake_failed',\n /** Upstream returned a non-MCP error shape we couldn't classify. */\n 'unknown',\n ]),\n message: z.string(),\n /** Upstream HTTP status if we got one. */\n status: z.number().int().optional(),\n })\n .strict();\n\nexport type UpstreamDiscoveryError = z.infer<typeof upstreamDiscoveryErrorSchema>;\n\n// ---------------------------------------------------------------------------\n// GET /api/gateway/internal/tools/:orgId — aggregated list\n// ---------------------------------------------------------------------------\n\n/**\n * Partial-success envelope (#2027). `tools` carries every tool the\n * gateway successfully discovered; `upstreamCounts` is the\n * histogram by slug; `errors` is a sparse map of upstream slug →\n * categorized failure for every upstream that *couldn't* contribute\n * tools this call. An empty `errors` map means full success.\n *\n * Callers render per-upstream error state from `errors` instead of\n * collapsing a failed upstream to a silent `0` count. Before #2027\n * the gateway cached empty results as success and the dashboard\n * had no signal that an upstream was broken.\n */\nexport const gatewayInternalToolsListSchema = z\n .object({\n totalCount: z.number().int().min(0),\n upstreamCounts: z.record(z.string(), z.number().int().min(0)),\n tools: z.array(discoveredToolSchema),\n /**\n * Sparse map keyed by upstream slug. Empty / absent when every\n * upstream contributed successfully. Present as an empty object\n * when serialized — always-object keeps the shape stable for\n * consumers that read `Object.keys(errors).length`.\n */\n errors: z.record(z.string(), upstreamDiscoveryErrorSchema),\n })\n .strict();\n\nexport type GatewayInternalToolsList = z.infer<typeof gatewayInternalToolsListSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /api/gateway/internal/tools/:orgId/discover — user-scoped\n// ---------------------------------------------------------------------------\n\nexport const gatewayInternalDiscoverSuccessSchema = z\n .object({\n tools: z.array(discoveredToolSchema),\n })\n .strict();\n\nexport type GatewayInternalDiscoverSuccess = z.infer<typeof gatewayInternalDiscoverSuccessSchema>;\n\nexport const gatewayInternalDiscoverErrorSchema = z\n .object({\n error: z.string(),\n })\n .strict();\n\nexport type GatewayInternalDiscoverError = z.infer<typeof gatewayInternalDiscoverErrorSchema>;\n","/**\n * Gateway Schemas\n *\n * Zod schemas for gateway configuration, upstream server validation,\n * and tool call audit records.\n *\n * SSRF Protection: The safeUrl validator blocks private/reserved IPs\n * at config time. Runtime DNS resolution checks (in GatewayProxy) are\n * still required to defeat DNS rebinding and redirect-based bypasses.\n */\n\nimport { z } from 'zod';\n\nimport { discoveredToolSchema } from '../wire/gateway-internal-tools';\n\n// ---------------------------------------------------------------------------\n// SSRF-safe URL validator\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a hostname or IP string resolves to a private, reserved,\n * or link-local address that must never be used as an upstream target.\n *\n * This is a config-time check on the literal URL string. It does NOT\n * replace runtime DNS resolution validation (needed for DNS rebinding\n * and redirect attacks).\n */\n/**\n * Exported for direct unit testing of the defense-in-depth path. Production\n * code should go through `safeUrl` instead — the WHATWG URL parser does most\n * IPv4 normalization up front, but this function still has to be correct on\n * its own so the blocklist holds if a runtime's URL parser ever changes.\n */\nexport function isPrivateOrReservedHost(hostname: string): boolean {\n const lower = hostname.toLowerCase();\n\n // Block localhost and any *.localhost subdomain.\n // Per RFC 6761 the entire `.localhost` TLD is reserved and compliant\n // resolvers map all names under it to loopback (e.g. evil.localhost → 127.0.0.1).\n if (lower === 'localhost' || lower === 'localhost.') return true;\n if (lower.endsWith('.localhost') || lower.endsWith('.localhost.')) return true;\n\n // Strip IPv6 brackets for uniform parsing\n const bare = lower.startsWith('[') && lower.endsWith(']') ? lower.slice(1, -1) : lower;\n\n // IPv6 loopback\n if (bare === '::1' || bare === '0:0:0:0:0:0:0:1') return true;\n\n // IPv6 unspecified / all-zeros (::) — routes to localhost on most systems,\n // analogous to IPv4 0.0.0.0\n if (bare === '::' || bare === '0:0:0:0:0:0:0:0') return true;\n\n // IPv6 ULA (fc00::/7 → fc00:: – fdff::)\n if (/^f[cd][0-9a-f]{2}:/.test(bare)) return true;\n\n // IPv6 link-local (fe80::/10 → fe80:: – febf::) — direct analog of\n // IPv4 169.254.x.x, same class of bug as reaching the cloud metadata endpoint\n if (/^fe[89ab][0-9a-f]:/.test(bare)) return true;\n\n // IPv4-mapped IPv6 (::ffff:x.x.x.x or ::ffff:0a00:0001 etc.)\n const v4MappedMatch = bare.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (v4MappedMatch) {\n return isPrivateIPv4(v4MappedMatch[1]);\n }\n // Hex form: ::ffff:XXYY:ZZWW\n const v4MappedHexMatch = bare.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n if (v4MappedHexMatch) {\n const hi = parseInt(v4MappedHexMatch[1], 16);\n const lo = parseInt(v4MappedHexMatch[2], 16);\n const a = (hi >> 8) & 0xff;\n const b = hi & 0xff;\n const c = (lo >> 8) & 0xff;\n const d = lo & 0xff;\n return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n }\n\n // Dotted-quad IPv4 — per WHATWG URL spec and historical BSD convention,\n // each octet may independently be decimal, octal (leading zero), or hex\n // (`0x` prefix). Examples: `127.0.0.1`, `0177.0.0.01`, `0x7f.0.0.1`,\n // `0177.0x0.0.01`. This unified handler replaces three separate branches\n // that had a subtle ordering bug — the old decimal check matched any\n // string of digit characters, so `0177.0.0.01` fell through and was\n // parsed as decimal 177 instead of octal 127.\n const dottedParts = bare.split('.');\n if (dottedParts.length === 4) {\n const octets: number[] = [];\n let allValid = true;\n for (const part of dottedParts) {\n const n = parseIPv4Octet(part);\n if (n === null || n < 0 || n > 255) {\n allValid = false;\n break;\n }\n octets.push(n);\n }\n if (allValid) {\n return isPrivateIPv4(octets.join('.'));\n }\n }\n\n // Single-integer IPv4 encodings (no dots) — per BSD/WHATWG conventions,\n // a bare 32-bit integer is equivalent to its dotted-quad representation.\n // Examples: `0x7f000001` (hex), `017700000001` (octal), `2130706433` (decimal)\n // all mean `127.0.0.1`.\n //\n // Order matters: hex (`0x` prefix) and octal (leading `0`) must be tested\n // before decimal, otherwise `/^(0|[1-9]\\d*)$/` would eat the literal `0`\n // (harmless but the octal and hex branches have their own shape).\n if (/^0x[0-9a-f]+$/i.test(bare)) {\n const num = parseInt(bare, 16);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n if (/^0[0-7]+$/.test(bare)) {\n const num = parseInt(bare, 8);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n if (/^(0|[1-9]\\d*)$/.test(bare)) {\n const num = parseInt(bare, 10);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n\n return false;\n}\n\n/**\n * Parses a single IPv4 octet in decimal, octal (leading zero), or hex\n * (`0x` prefix). Returns null for anything that isn't a valid octet in any\n * of the three bases. Used by the dotted-quad handler to defeat\n * octal/hex-encoded SSRF bypasses like `0177.0.0.01` → `127.0.0.1`.\n */\nfunction parseIPv4Octet(part: string): number | null {\n if (/^0x[0-9a-f]+$/i.test(part)) {\n return parseInt(part, 16);\n }\n if (/^0[0-7]+$/.test(part)) {\n return parseInt(part, 8);\n }\n if (/^(0|[1-9]\\d*)$/.test(part)) {\n return parseInt(part, 10);\n }\n return null;\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n const parts = ip.split('.').map(Number);\n if (parts.some((p) => p > 255)) return false;\n\n const [a, b] = parts;\n\n // 0.0.0.0/8 — entire range routes to localhost on Linux/Unix\n if (a === 0) return true;\n\n // 127.0.0.0/8 (loopback)\n if (a === 127) return true;\n\n // 10.0.0.0/8\n if (a === 10) return true;\n\n // 172.16.0.0/12\n if (a === 172 && b >= 16 && b <= 31) return true;\n\n // 192.168.0.0/16\n if (a === 192 && b === 168) return true;\n\n // 169.254.0.0/16 (link-local, includes cloud metadata 169.254.169.254)\n if (a === 169 && b === 254) return true;\n\n // 100.64.0.0/10 (RFC 6598 Shared Address Space / CGNAT) — may reach\n // internal services in AWS VPCs and other cloud environments.\n // Matches the existing blocklist in apps/web/lib/utils/url-security.ts.\n if (a === 100 && b >= 64 && b <= 127) return true;\n\n return false;\n}\n\nfunction numToIPv4(num: number): string {\n return [(num >>> 24) & 0xff, (num >>> 16) & 0xff, (num >>> 8) & 0xff, num & 0xff].join('.');\n}\n\n/**\n * Zod refinement that rejects URLs pointing at private/reserved addresses.\n * Only http and https schemes are permitted.\n */\nexport const safeUrl = z\n .string()\n .url()\n .superRefine((val, ctx) => {\n let parsed: URL;\n try {\n parsed = new URL(val);\n } catch {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid URL' });\n return;\n }\n\n // Scheme allowlist\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Scheme \"${parsed.protocol.replace(':', '')}\" is not allowed; use http or https`,\n });\n return;\n }\n\n if (isPrivateOrReservedHost(parsed.hostname)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL points to a private or reserved IP address',\n });\n }\n });\n\n// ---------------------------------------------------------------------------\n// Slug regex — no consecutive underscores (__ is reserved as namespace sep)\n// ---------------------------------------------------------------------------\n\n/**\n * Upstream slug regex — lowercase alphanumerics with single underscores\n * between groups. No leading/trailing underscores. No consecutive `__`\n * (reserved as the namespace separator in the gateway proxy's\n * `parseNamespacedTool`).\n *\n * Single source of truth. Imported by:\n * - `upstreamServerSchema.slug` (this file) — admin-time validation\n * - `apps/gateway/src/lib/namespace.ts` — `slugify` output contract\n *\n * If this regex ever tightens (e.g. forbid leading digits, require min\n * length), both consumers pick up the change automatically.\n */\nexport const SLUG_REGEX = /^[a-z0-9]+(_[a-z0-9]+)*$/;\n\n// ---------------------------------------------------------------------------\n// Upstream Server Schema\n// ---------------------------------------------------------------------------\n\nexport const upstreamServerSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(100),\n slug: z.string().regex(SLUG_REGEX, {\n message:\n 'Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)',\n }),\n url: safeUrl,\n transport: z.enum(['http', 'sse']).default('http'),\n authType: z.enum(['none', 'vault', 'static']).default('none'),\n envVarNames: z.array(z.string()).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Static-header credential plane (hygiene-scorecard gap #1)\n //\n // `staticHeaders` (plaintext) is DEPRECATED as an at-rest field —\n // kept here only so `.parse()` doesn't silently drop rows written\n // before this fix while they wait to be re-encrypted. It remains the\n // wire-input field name (the admin form still submits plaintext\n // header values; the PUT handler encrypts them into\n // `staticHeadersEncrypted` before persisting and opportunistically\n // migrates any legacy plaintext it finds on every save that touches\n // an upstream). Never populated in an API response.\n staticHeaders: z.record(z.string(), z.string()).optional(),\n // AES-256-GCM ciphertext (base64: iv|ciphertext|authTag) of the\n // JSON-serialized staticHeaders map — the at-rest form going\n // forward. Encrypt/decrypt via `@kya-os/checkpoint-db/crypto`'s\n // `encryptStaticHeaders`/`resolveStaticHeaders`. Never populated in\n // an API response — see `staticHeaderKeys` for the redacted view.\n staticHeadersEncrypted: z.string().nullable().optional(),\n // Read-only projection of the configured header NAMES (never\n // values). Populated by the gateway-mcp config GET/PUT response\n // serializer (`redactGatewayConfig`) so the dashboard can render\n // \"N headers configured\" without ever receiving secret material or\n // ciphertext. Ignored on write — `upstreamServerInputSchema` omits it.\n staticHeaderKeys: z.array(z.string()).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // #1600 Phase 1 Part 2 — credential flow method selection\n //\n // `supportedAuthMethods` declares which of the two user-facing\n // credential-entry flows this upstream exposes to end users. The\n // admin picks this at upstream-create time; the user credential\n // modal reads it to decide whether to render the \"Connect GitHub\"\n // OAuth button, the paste-a-token form, or both (hybrid).\n //\n // Default `['paste']` keeps every pre-#1600 upstream row working\n // unchanged on read: the modal shows only the paste form, which\n // is what Bouncer + existing vault-authType upstreams expect.\n //\n // `oauthProvider` is only meaningful when `supportedAuthMethods`\n // includes `'oauth'`. It names a provider in the static registry\n // at `apps/web/lib/gateway/oauth-providers.ts`. Validation here\n // is the narrow enum of known IDs — the same set declared in\n // `OAUTH_PROVIDER_IDS` on the registry side.\n //\n // Intentionally omitted: per-upstream custom scope overrides.\n // Scopes live on the registry entry's `defaultScopes` field and\n // are NOT admin-configurable in v1 — see the operator setup doc\n // at `content/docs/govern/connections-github.mdx` for the\n // rationale (scope sprawl hesitancy).\n // ─────────────────────────────────────────────────────────────────\n supportedAuthMethods: z.array(z.enum(['paste', 'oauth'])).default(['paste']),\n oauthProvider: z.enum(['github', 'slack', 'notion', 'linear']).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Stateless (UCP-style) upstreams\n //\n // Some MCP-transport endpoints reject `initialize` and `tools/list`\n // outright and treat every POST as an independent request — UCP\n // servers (ucp.dev) such as the Shopify Global Catalog are the\n // motivating case. `sessionMode: 'stateless'` tells the gateway to\n // skip the initialize handshake and the per-user session cache for\n // this upstream, and to serve its tool list ONLY from a persisted\n // manifest (live discovery cannot succeed by design, and attempting\n // it would feed the health tracker until the upstream is marked\n // down). Absent means the standard MCP handshake — optional rather\n // than defaulted so the field stays optional on the inferred type\n // and pre-existing rows/fixtures parse unchanged.\n //\n // `ucpProfileUrl` is the UCP agent-profile document the gateway\n // injects as `arguments.meta[\"ucp-agent\"].profile` on tools/call\n // when the caller didn't supply its own — UCP servers reject calls\n // without it. `safeUrl` (not a plain URL check) because the value\n // is fetched by third-party upstreams and must never point at a\n // private/internal host.\n // ─────────────────────────────────────────────────────────────────\n sessionMode: z.enum(['standard', 'stateless']).optional(),\n ucpProfileUrl: safeUrl.optional(),\n\n enabled: z.boolean().default(true),\n // No default on purpose: A `.default('healthy')` here made every upstream render a\n // false green \"Healthy\" dot. `undefined` means \"never checked\" and\n // consumers must render a neutral \"Unchecked\" state for it.\n healthStatus: z.enum(['healthy', 'degraded', 'down']).optional(),\n consecutiveFailures: z.number().int().min(0).default(0),\n\n // ─────────────────────────────────────────────────────────────────\n // v1.1 KTA Trust Layer forward-compat (see #1549)\n // All fields nullable/optional. v1 code does NOT populate or read these.\n // v1.1 Phase A populates them from KTA registry lookups on upstream add.\n // DO NOT wire these to KTA in this sprint.\n // ─────────────────────────────────────────────────────────────────\n ktaRegistryId: z.string().nullable().optional(),\n ktaVerifiedOperator: z.boolean().nullable().optional(),\n ktaReputationScore: z.number().min(0).max(5).nullable().optional(),\n ktaFlaggedIssues: z\n .array(\n z.object({\n severity: z.enum(['info', 'warning', 'critical']),\n category: z.string(),\n message: z.string(),\n })\n )\n .nullable()\n .optional(),\n ktaLastFetchedAt: z.string().datetime().nullable().optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Per-upstream project lifecycle (Option A — #1566)\n // Links this upstream to a dedicated Checkpoint project for\n // per-upstream detection, policy, and audit isolation.\n // ─────────────────────────────────────────────────────────────────\n projectId: z.string().uuid().nullable().optional(),\n\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The RESOLVED bare\n // host for this upstream's project — where the Hono gateway points a\n // Delegation challenge's consent_uri / pickup_uri. Forward contract: the\n // wire shape is established here in H1.1; the gateway populates it per\n // upstream from `projects.authorization_host` when its challenge emitter\n // lands (H2.1-WF), resolved out-of-band from `DbGatewayConfigProvider` so\n // that provider keeps its single-query invariant. Never authored by the\n // dashboard. The same resolved value is already live on the per-project\n // policy config the gateway worker fetches (`/api/internal/policies`), which\n // is AUTHORITATIVE — consumers prefer it and treat this copy as a hint.\n authorizationHost: z.string().max(255).nullable().optional(),\n});\n\nexport type UpstreamServer = z.infer<typeof upstreamServerSchema>;\n\n/**\n * Input variant — id/slug optional for new upstreams (auto-generated by PUT\n * handler). Also omits server-managed project ownership and the two\n * server-managed static-headers fields:\n * `staticHeadersEncrypted` (ciphertext — clients never author this\n * directly) and `staticHeaderKeys` (a read-only projection echoed back on\n * GET/PUT responses). The plaintext `staticHeaders` field is intentionally\n * NOT omitted — it's still how the admin form submits new/changed header\n * values; the PUT handler encrypts it before persisting.\n */\nexport const upstreamServerInputSchema = upstreamServerSchema\n .omit({ projectId: true, staticHeadersEncrypted: true, staticHeaderKeys: true })\n .extend({\n id: z.string().uuid().optional(),\n slug: z\n .string()\n .regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/, {\n message:\n 'Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)',\n })\n .optional(),\n });\nexport type UpstreamServerInput = z.infer<typeof upstreamServerInputSchema>;\n\n// ---------------------------------------------------------------------------\n// Upstream Tool Manifest — DB row shape\n// ---------------------------------------------------------------------------\n\n/**\n * Shape of a cached tool manifest row (`upstream_tool_manifests` table).\n * The gateway reads this at runtime to serve org-level `tools/list`\n * without needing a per-user OAuth token — the manifest was captured\n * at add-time using the viewing user's credential, which is the only\n * moment in the flow where per-user auth is available to us.\n *\n * Validated on writes from the dashboard and on reads by the Fly\n * gateway; the table's `tools` column is `jsonb` so nothing DB-side\n * enforces the shape.\n */\nexport const upstreamToolManifestSchema = z\n .object({\n upstreamId: z.string().uuid(),\n orgId: z.string().uuid(),\n tools: z.array(discoveredToolSchema),\n discoveredByUserId: z.string().uuid().nullable().optional(),\n discoveredAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n })\n .strict();\n\nexport type UpstreamToolManifest = z.infer<typeof upstreamToolManifestSchema>;\n\n/**\n * Insert/upsert variant — omits DB-managed timestamps so callers can\n * pass the payload they actually own. The DB defaults `discovered_at`\n * and `updated_at` to `now()` on insert; updates bump `updated_at`\n * explicitly via the write path.\n */\nexport const upstreamToolManifestInputSchema = z\n .object({\n upstreamId: z.string().uuid(),\n orgId: z.string().uuid(),\n tools: z.array(discoveredToolSchema),\n discoveredByUserId: z.string().uuid().nullable().optional(),\n })\n .strict();\n\nexport type UpstreamToolManifestInput = z.infer<typeof upstreamToolManifestInputSchema>;\n\n// ---------------------------------------------------------------------------\n// Gateway Config Schema\n// ---------------------------------------------------------------------------\n\nexport const oauthClientSchema = z.object({\n clientId: z.string().min(1),\n name: z.string().min(1),\n redirectUris: z.array(z.string().url()).min(1),\n});\n\nexport type OAuthClient = z.infer<typeof oauthClientSchema>;\n\n// Defaults for nested config objects — single source of truth to prevent\n// inner-field and outer-object defaults from drifting apart.\nconst DEFAULT_RATE_LIMITS = { toolCallsPerMinute: 600 } as const;\nconst DEFAULT_EXTERNAL_ACCESS = {\n enabled: false,\n allowedDids: [] as string[],\n externalScopes: {} as Record<string, string[]>,\n} as const;\n\nexport const gatewayConfigSchema = z.object({\n enabled: z.boolean().default(false),\n upstreamServers: z.array(upstreamServerSchema).default([]),\n roleScopes: z.record(z.string(), z.array(z.string())).optional(),\n oauthClients: z.array(oauthClientSchema).default([]),\n rateLimits: z\n .object({\n toolCallsPerMinute: z\n .number()\n .int()\n .positive()\n .default(DEFAULT_RATE_LIMITS.toolCallsPerMinute),\n })\n .default(DEFAULT_RATE_LIMITS),\n externalAccess: z\n .object({\n enabled: z.boolean().default(DEFAULT_EXTERNAL_ACCESS.enabled),\n allowedDids: z.array(z.string()).default(DEFAULT_EXTERNAL_ACCESS.allowedDids),\n externalScopes: z\n .record(z.string(), z.array(z.string()))\n .default(DEFAULT_EXTERNAL_ACCESS.externalScopes),\n })\n .default(DEFAULT_EXTERNAL_ACCESS),\n // T6 #2899 M2 — per-org fleet-server endpoint. When set, the gateway's\n // DiscoveryUpstreamProvider injects a synthetic `fleet` upstream so\n // callers can dispatch tools by capability or name (not just raw DID).\n // Validated via `safeUrl` so a misconfigured endpoint targeting\n // private-network IPs cannot become an SSRF pivot.\n fleetEndpoint: safeUrl.optional(),\n});\n\nexport type GatewayConfig = z.infer<typeof gatewayConfigSchema>;\n/** Gateway config input variant for PUT — uses optional id/slug */\nexport const gatewayConfigInputSchema = gatewayConfigSchema.extend({\n upstreamServers: z.array(upstreamServerInputSchema).default([]),\n});\n\n// ---------------------------------------------------------------------------\n// Gateway Tool Call Schema (audit record — mirrors gateway_tool_calls table)\n// ---------------------------------------------------------------------------\n\nexport const gatewayToolCallSchema = z.object({\n id: z.string().uuid(),\n orgId: z.string().uuid(),\n projectId: z.string().uuid().nullable().optional(),\n userId: z.string().uuid().nullable().optional(),\n userEmail: z.string().email(),\n sessionId: z.string().min(1).max(100),\n upstreamId: z.string().uuid(),\n upstreamName: z.string().min(1).max(255),\n toolName: z.string().min(1).max(500),\n prefixedName: z.string().min(1).max(500),\n argsHash: z.string().max(64).nullable().optional(),\n status: z.enum(['success', 'error', 'denied', 'timeout']).default('success'),\n latencyMs: z.number().int().min(0).nullable().optional(),\n errorMessage: z.string().nullable().optional(),\n // Provenance identity (Phase 2, #1979)\n clientDid: z.string().max(500).nullable().optional(),\n clientName: z.string().max(100).nullable().optional(),\n serverDid: z.string().max(500).nullable().optional(),\n agentName: z.string().max(255).nullable().optional(),\n delegationId: z.string().max(255).nullable().optional(),\n attestationHash: z.string().max(64).nullable().optional(),\n verificationMethod: z.string().max(50).nullable().optional(),\n createdAt: z.coerce.date().default(() => new Date()),\n});\n\nexport type GatewayToolCall = z.infer<typeof gatewayToolCallSchema>;\n\n// ---------------------------------------------------------------------------\n// Gateway Connections Summary (derived aggregate over gateway_tool_calls)\n// ---------------------------------------------------------------------------\n\n/**\n * One distinct agent/client observed calling the gateway within the lookback\n * window. Identity is keyed on `clientDid` (canonical) falling back to\n * `agentName` when a client hasn't presented a DID.\n */\nexport const gatewayConnectedAgentSchema = z.object({\n clientDid: z.string().nullable(),\n clientName: z.string().nullable(),\n agentName: z.string().nullable(),\n lastSeenAt: z.coerce.date(),\n callCount: z.number().int().min(1),\n /** Calls carrying an attestation hash — the cryptographically signed subset. */\n verifiedCalls: z.number().int().min(0),\n});\n\nexport type GatewayConnectedAgent = z.infer<typeof gatewayConnectedAgentSchema>;\n\n/**\n * Aggregate of the agents/clients that have connected *in* to an org's gateway\n * over a lookback window, derived from `gateway_tool_calls`. Powers the\n * Connections hub hero (\"agents in\" side) — distinct from the upstream servers\n * the org reaches *out* to (those live in `GatewayConfig.upstreamServers`).\n */\nexport const gatewayConnectionsSummarySchema = z.object({\n orgId: z.string().uuid(),\n windowHours: z.number().int().positive(),\n /** Distinct agents (by clientDid|agentName) active in the window. */\n distinctAgents: z.number().int().min(0),\n /** Total gateway tool calls in the window. */\n totalCalls: z.number().int().min(0),\n agents: z.array(gatewayConnectedAgentSchema),\n});\n\nexport type GatewayConnectionsSummary = z.infer<typeof gatewayConnectionsSummarySchema>;\n","/**\n * Schemas Export\n *\n * Central export point for all Zod schemas\n * These schemas are used for runtime validation across all packages\n *\n * ## Provider Registry Integration\n *\n * As of v0.3.0, provider types are imported from @kya-os/provider-registry\n * to ensure type parity between Checkpoint and KYA-OS. See provider-registry.ts\n * for re-exports and backward compatibility helpers.\n */\n\n// Detection schemas\nexport {\n DetectionInputSchema,\n RequestContextSchema,\n DetectionDetailSchema,\n DetectionResultSchema,\n DetectionModeSchema,\n CustomRuleSchema,\n DetectionOptionsSchema,\n} from '../core/detection';\n\n// Agent schemas\nexport {\n AgentTypeSchema,\n AgentInfoSchema,\n AgentPatternSchema,\n AgentClassificationSchema,\n} from '../core/agent';\n\n// Confidence schemas\nexport {\n ConfidenceLevelSchema,\n ForgeabilityRiskSchema,\n ConfidenceBreakdownSchema,\n} from '../core/confidence';\n\n// API schemas\nexport { BatchDetectionRequestSchema, VerificationRequestSchema } from '../api/request';\n\nexport {\n ApiResponseSchema,\n DetectionResponseSchema,\n BatchDetectionResponseSchema,\n VerificationResponseSchema,\n HealthResponseSchema,\n StatsResponseSchema,\n} from '../api/response';\n\n// Internal API schemas\nexport {\n CreateApiKeySchema,\n UpdateApiKeySchema,\n CreateOrganizationSchema,\n UpdateOrganizationSchema,\n CreateProjectSchema,\n UpdateProjectSchema,\n AnalyticsQuerySchema,\n ApiKeysQuerySchema,\n ProjectsQuerySchema,\n PixelsQuerySchema,\n ProjectIdSchema,\n ExportAnalyticsSchema,\n} from '../api/internal';\n\n// Event schemas\nexport {\n MouseEventSchema,\n KeyboardEventSchema,\n ScrollEventSchema,\n ClickEventSchema,\n TouchEventSchema,\n BehavioralDataSchema,\n BehavioralAnalysisSchema,\n} from '../events/behavioral';\n\nexport {\n RealtimeEventTypeSchema,\n RealtimeEventSchema,\n DetectionEventSchema,\n BlockEventSchema,\n StatsUpdateEventSchema,\n} from '../events/realtime';\n\n// Entity schemas\nexport {\n UserPlanSchema,\n ApiKeyPermissionSchema,\n UserSchema,\n ProjectSettingsSchema,\n ProjectSchema,\n PixelConfigurationSchema,\n PixelSchema,\n PixelStatsSchema,\n ApiKeyRateLimitsSchema,\n ApiKeySchema,\n DetectionLogSchema,\n SessionSchema,\n AccountSchema,\n VerificationTokenSchema,\n} from '../types/entities';\n\n// Pixel schemas\nexport {\n PixelTrackingRequestSchema,\n PixelTrackingResponseSchema,\n PixelVerificationStatusSchema,\n} from '../types/pixel';\n\n// Auth schemas\nexport { passwordSchema, resetPasswordSchema, type ResetPasswordData } from './auth';\n\n// Admin schemas\nexport {\n PerformanceRecalculationRequestSchema,\n GrowthOpportunityUpdateSchema,\n GrowthBatchRequestSchema,\n GrowthConfigurationThresholdsSchema,\n GrowthConfigurationUpdateSchema,\n GrowthConfigurationResetSchema,\n AdminQueryParamsSchema,\n GrowthOpportunitiesQuerySchema,\n RecommendationQuerySchema,\n RecommendationGenerationSchema,\n} from './admin';\n\n// Bouncer schemas\nexport {\n OAuthProviderTypeSchema,\n OAuthConnectionStatusSchema,\n OAuthModeSchema,\n ScopeSchema,\n CRISPBudgetSchema,\n BouncerConfigSchema,\n UpdateBouncerConfigSchema,\n RefreshScopesRequestSchema,\n OAuthProviderMetadataSchema,\n ProvidersResponseSchema,\n OAuthTokensResponseSchema,\n // Multi-provider OAuth types (CRED-001)\n BaseAuthProviderSchema,\n OAuth2ProviderSchema,\n CredentialProviderSchema,\n ConfiguredProviderSchema,\n OAuthProvidersMapSchema,\n AddUpdateProviderRequestSchema,\n // Provider Definition (Provider Registry aligned)\n // Consent schemas (CRED-002)\n ConsentBrandingSchema,\n ConsentTermsSchema,\n ConsentUISchema,\n ConsentConfigSchema,\n ConsentConfigMetadataSchema,\n ConsentCapabilitySchema,\n ConsentCapabilityGroupSchema,\n ConsentAgentMetadataSchema,\n ConsentInputCopySchema,\n ConsentSignInCopySchema,\n ConsentScopeLabelsSchema,\n // Format conversion helpers (Provider Registry <-> Checkpoint)\n mapLegacyAuthType,\n mapToLegacyAuthType,\n type OAuthProviderType,\n type Scope,\n type BouncerConfig,\n type UpdateBouncerConfig,\n type RefreshScopesRequest,\n type BouncerOutcome,\n type OAuthProviderMetadata,\n type ProvidersResponse,\n // Multi-provider OAuth types (CRED-001)\n type OAuth2Provider,\n type CredentialProvider,\n type ConfiguredProvider,\n // Provider Definition types\n type ProviderRegistryDefinition,\n // Canonical types from provider-registry\n type ProviderAuthType,\n type ConsentProviderType,\n // Consent types (CRED-002)\n type ConsentBranding,\n type ConsentTerms,\n type ConsentUI,\n type ConsentConfig,\n type ConsentConfigMetadata,\n type ConsentCapabilityGroup,\n} from './bouncer';\n\n// Consent policy endpoint\nexport {\n ConsentPolicyRiskLevelSchema,\n ConsentPolicyCapabilitySchema,\n ConsentPolicyResponseSchema,\n type ConsentPolicyRiskLevel,\n type ConsentPolicyResponse,\n} from './consent-policy-endpoint';\n\n// Gateway schemas\nexport {\n SLUG_REGEX,\n safeUrl,\n isPrivateOrReservedHost,\n upstreamServerSchema,\n oauthClientSchema,\n gatewayConfigSchema,\n gatewayConfigInputSchema,\n upstreamServerInputSchema,\n gatewayToolCallSchema,\n gatewayConnectedAgentSchema,\n gatewayConnectionsSummarySchema,\n type UpstreamServer,\n type OAuthClient,\n type GatewayConfig,\n type GatewayToolCall,\n type GatewayConnectedAgent,\n type GatewayConnectionsSummary,\n} from './gateway';\n\n// Provider Registry exports (canonical types from @kya-os/provider-registry)\n// NOTE: Runtime registry (defaultProviderRegistry) should be imported directly\n// from @kya-os/provider-registry in server-side code to avoid bundling issues.\n// The registry's runtime values are on `@kya-os/checkpoint-shared/provider-registry`.\nexport {\n AUTHORIZATION_MODES,\n type AuthMode,\n type AuthorizationMode,\n // Type definitions for registry (runtime should be imported directly)\n type IProviderRegistry,\n type RegistryLogger,\n // Canonical config types\n type OAuthProviderConfig,\n type CredentialProviderConfig,\n type ProviderConfig,\n} from './provider-registry';\n\n/**\n * Schema validation utilities\n */\nimport { z } from 'zod';\n\n/**\n * Validate data against a schema\n */\nexport function validate<T>(\n schema: z.ZodSchema<T>,\n data: unknown\n): { success: true; data: T } | { success: false; error: z.ZodError } {\n const result = schema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, error: result.error };\n}\n\n/**\n * Validate and throw on error\n */\nexport function validateOrThrow<T>(schema: z.ZodSchema<T>, data: unknown): T {\n return schema.parse(data);\n}\n\n/**\n * Create a partial schema (all fields optional)\n */\nexport function partial<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.partial();\n}\n\n/**\n * Create a strict schema (no additional properties)\n */\nexport function strict<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.strict();\n}\n","/**\n * Rule Validation Schemas\n *\n * Zod schemas for runtime validation of detection rules\n * Ensures rule integrity at build time and runtime\n */\n\nimport { z } from 'zod';\n\n/**\n * User agent rule schema\n */\nexport const UserAgentRuleSchema = z.object({\n patterns: z.array(z.string().min(1)).min(1),\n confidence: z.number().min(0).max(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n});\n\n/**\n * IP range rule schema\n */\nexport const IpRangeRuleSchema = z.object({\n ranges: z.array(z.string().regex(/^(\\d{1,3}\\.){3}\\d{1,3}\\/\\d{1,2}$/)).min(1),\n confidence: z.number().min(0).max(1),\n provider: z.string().optional(),\n lastUpdated: z.string().optional(),\n});\n\n/**\n * Signature rule schema\n */\nexport const SignatureRuleSchema = z.object({\n publicKey: z.string().min(1),\n algorithm: z.enum([\n 'RS256',\n 'RS384',\n 'RS512',\n 'HS256',\n 'HS384',\n 'HS512',\n 'ES256',\n 'ES384',\n 'ES512',\n ]),\n headerName: z.string().min(1),\n confidence: z.number().min(0).max(1),\n issuer: z.string().optional(),\n});\n\n/**\n * Behavioral threshold schema\n */\nexport const BehavioralThresholdSchema = z.object({\n minTimeOnPage: z.number().min(0).optional(),\n maxRequestsPerSecond: z.number().min(0).optional(),\n minMouseMovements: z.number().min(0).optional(),\n minKeyboardEvents: z.number().min(0).optional(),\n maxScrollVariance: z.number().min(0).optional(),\n timeWindow: z.number().min(0).optional(),\n});\n\n/**\n * Behavioral pattern schema\n */\nexport const BehavioralPatternSchema = z.object({\n name: z.string().min(1),\n type: z.enum(['rapid_requests', 'no_interaction', 'perfect_scrolling', 'sequential_access']),\n config: z.record(z.string(), z.any()),\n confidenceModifier: z.number().min(-1).max(1),\n});\n\n/**\n * Behavioral rules schema\n */\nexport const BehavioralRulesSchema = z.object({\n thresholds: BehavioralThresholdSchema,\n patterns: z.array(BehavioralPatternSchema).optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Header rule schema\n */\nexport const HeaderRuleSchema = z.object({\n name: z.string().min(1),\n pattern: z.string().optional(),\n required: z.boolean().optional(),\n suspiciousIfMissing: z.boolean().optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Header rules schema\n */\nexport const HeaderRulesSchema = z.object({\n suspicious: z.array(HeaderRuleSchema),\n required: z.array(HeaderRuleSchema),\n forbidden: z.array(HeaderRuleSchema).optional(),\n});\n\n/**\n * IP range collection schema\n * Flexible to handle both old (with providers) and new (direct) structures\n */\nexport const IpRangeCollectionSchema = z.union([\n // Old structure with providers\n z.object({\n providers: z.record(z.string(), IpRangeRuleSchema),\n updateUrl: z.string().url().optional(),\n updateFrequency: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n cacheDuration: z.number().min(0).optional(),\n }),\n // New merged structure - IP ranges directly as properties\n z.record(z.string(), IpRangeRuleSchema).refine(\n (val) => {\n // Ensure at least one valid IP range entry exists\n return Object.values(val).some(\n (v) => v && typeof v === 'object' && 'ranges' in v && Array.isArray(v.ranges)\n );\n },\n { message: 'At least one valid IP range entry required' }\n ),\n]);\n\n/**\n * Complete detection rules schema\n */\nexport const DetectionRulesSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n lastUpdated: z.string(),\n metadata: z\n .object({\n author: z.string().optional(),\n description: z.string().optional(),\n minVersion: z.string().optional(),\n source: z.string().optional(),\n })\n .optional(),\n rules: z.object({\n userAgents: z.record(z.string(), UserAgentRuleSchema),\n ipRanges: IpRangeCollectionSchema,\n signatures: z.record(z.string(), SignatureRuleSchema),\n behavioral: BehavioralRulesSchema,\n headers: HeaderRulesSchema,\n }),\n});\n\n/**\n * Rule load options schema\n */\nconst RuleLoadOptionsSchema = z.object({\n /** @deprecated Refused at runtime; see `RuleLoader.loadRules`. */\n cdnUrl: z.string().url().optional(),\n forceRefresh: z.boolean().optional(),\n cacheDuration: z.number().min(0).optional(),\n validationMode: z.enum(['strict', 'loose', 'none']).optional(),\n});\n\n/**\n * Rule validation result schema\n */\nexport const RuleValidationResultSchema = z.object({\n valid: z.boolean(),\n errors: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n type: z.string(),\n })\n )\n .optional(),\n warnings: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n })\n )\n .optional(),\n});\n\n/**\n * Rule update event schema\n */\nconst RuleUpdateEventSchema = z.object({\n previousVersion: z.string(),\n newVersion: z.string(),\n timestamp: z.string(),\n changes: z\n .object({\n added: z.array(z.string()),\n modified: z.array(z.string()),\n removed: z.array(z.string()),\n })\n .optional(),\n});\n\n/**\n * Rule match result schema\n */\nconst RuleMatchResultSchema = z.object({\n matched: z.boolean(),\n rule: z.string().optional(),\n category: z.enum(['userAgent', 'ipRange', 'signature', 'behavioral', 'header']).optional(),\n confidence: z.number().min(0).max(1).optional(),\n details: z.record(z.string(), z.any()).optional(),\n});\n\n/**\n * Type exports inferred from schemas\n */\nexport type UserAgentRule = z.infer<typeof UserAgentRuleSchema>;\nexport type IpRangeRule = z.infer<typeof IpRangeRuleSchema>;\nexport type SignatureRule = z.infer<typeof SignatureRuleSchema>;\nexport type BehavioralThreshold = z.infer<typeof BehavioralThresholdSchema>;\nexport type BehavioralPattern = z.infer<typeof BehavioralPatternSchema>;\nexport type BehavioralRules = z.infer<typeof BehavioralRulesSchema>;\nexport type HeaderRule = z.infer<typeof HeaderRuleSchema>;\nexport type HeaderRules = z.infer<typeof HeaderRulesSchema>;\nexport type IpRangeCollection = z.infer<typeof IpRangeCollectionSchema>;\nexport type DetectionRules = z.infer<typeof DetectionRulesSchema>;\nexport type RuleLoadOptions = z.infer<typeof RuleLoadOptionsSchema>;\nexport type RuleValidationResult = z.infer<typeof RuleValidationResultSchema>;\nexport type RuleUpdateEvent = z.infer<typeof RuleUpdateEventSchema>;\nexport type RuleMatchResult = z.infer<typeof RuleMatchResultSchema>;\n\n/**\n * Validate detection rules\n */\nexport function validateRules(rules: unknown): RuleValidationResult {\n try {\n DetectionRulesSchema.parse(rules);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n type: e.code,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: '',\n message: 'Unknown validation error',\n type: 'unknown',\n },\n ],\n };\n }\n}\n\n/**\n * Validate rules with loose mode (allows extra fields)\n */\nexport function validateRulesLoose(rules: unknown): RuleValidationResult {\n try {\n DetectionRulesSchema.passthrough().parse(rules);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n type: e.code,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: '',\n message: 'Unknown validation error',\n type: 'unknown',\n },\n ],\n };\n }\n}\n","/**\n * Rule Validator\n *\n * Validates detection rules against schemas\n */\n\nimport { z } from 'zod';\nimport { DetectionRulesSchema, validateRules, validateRulesLoose } from '../schemas/rules';\nimport { DetectionRules, RuleValidationResult } from '../types/rules';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Rule validation utilities\n */\nexport class RuleValidator {\n /**\n * Validate rules with specified mode\n */\n static validate(\n rules: unknown,\n mode: 'strict' | 'loose' | 'none' = 'strict'\n ): RuleValidationResult {\n switch (mode) {\n case 'strict':\n return validateRules(rules);\n case 'loose':\n return validateRulesLoose(rules);\n case 'none':\n return { valid: true };\n default:\n return validateRules(rules);\n }\n }\n\n /**\n * Validate and throw on error\n */\n static validateOrThrow(\n rules: unknown,\n mode: 'strict' | 'loose' | 'none' = 'strict'\n ): DetectionRules {\n const result = this.validate(rules, mode);\n\n if (!result.valid) {\n const errors = result.errors?.map((e) => `${e.path}: ${e.message}`).join(', ');\n throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);\n }\n\n return rules as DetectionRules;\n }\n\n /**\n * Parse and validate rules\n */\n static parse(rules: unknown): DetectionRules {\n try {\n return DetectionRulesSchema.parse(rules);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errors = error.issues.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ');\n throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if rules are valid\n */\n static isValid(rules: unknown): boolean {\n return this.validate(rules).valid;\n }\n\n /**\n * Validate rule version compatibility\n */\n static validateVersion(rules: DetectionRules, minVersion: string): boolean {\n const [ruleMajor, ruleMinor, rulePatch] = rules.version.split('.').map(Number);\n const [minMajor, minMinor, minPatch] = minVersion.split('.').map(Number);\n\n if (ruleMajor > minMajor) return true;\n if (ruleMajor < minMajor) return false;\n\n if (ruleMinor > minMinor) return true;\n if (ruleMinor < minMinor) return false;\n\n return rulePatch >= minPatch;\n }\n\n /**\n * Validate confidence scores\n */\n static validateConfidenceScores(rules: DetectionRules): boolean {\n // Check user agent confidence scores\n for (const rule of Object.values(rules.rules.userAgents)) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check IP range confidence scores\n // Handle both old (with providers) and new (direct) structures\n const ipRanges =\n 'providers' in rules.rules.ipRanges ? rules.rules.ipRanges.providers : rules.rules.ipRanges;\n\n for (const rule of Object.values(ipRanges)) {\n // Skip non-rule entries\n if (!rule || typeof rule !== 'object' || !('confidence' in rule)) continue;\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check signature confidence scores\n for (const rule of Object.values(rules.rules.signatures)) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check behavioral confidence\n if (rules.rules.behavioral.confidence < 0 || rules.rules.behavioral.confidence > 1) {\n return false;\n }\n\n // Check header confidence scores\n for (const rule of [...rules.rules.headers.suspicious, ...rules.rules.headers.required]) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Get validation errors as formatted string\n */\n static formatErrors(result: RuleValidationResult): string {\n if (result.valid) {\n return '';\n }\n\n const errors = result.errors || [];\n return errors.map((e) => ` - ${e.path}: ${e.message}`).join('\\n');\n }\n\n /**\n * Get validation warnings as formatted string\n */\n static formatWarnings(result: RuleValidationResult): string {\n const warnings = result.warnings || [];\n return warnings.map((w) => ` - ${w.path}: ${w.message}`).join('\\n');\n }\n}\n","","/**\n * Rule Loader\n *\n * Loads the detection rules compiled into the package.\n * NO FALLBACKS - Fail fast if rules cannot be loaded\n *\n * Remote rule delivery is not done here. Rules fetched over the network are\n * only accepted when a signature verifies against keys compiled into the\n * engine.\n */\n\nimport { DetectionRules, RuleLoadOptions } from '../types/rules';\nimport { RuleValidator } from './rule-validator';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Rule loader class - Singleton pattern\n */\nexport class RuleLoader {\n private static instance: RuleLoader | null = null;\n private rules: DetectionRules | null = null;\n\n /**\n * Private constructor for singleton\n */\n private constructor() {}\n\n /**\n * Get singleton instance\n */\n static getInstance(): RuleLoader {\n if (!this.instance) {\n this.instance = new RuleLoader();\n }\n return this.instance;\n }\n\n /**\n * Load rules synchronously from bundled JSON\n * This is the primary method for middleware packages\n * NO FALLBACKS - If this fails, the package should not work\n */\n static loadSync(): DetectionRules {\n try {\n // Load compiled rules - FAIL FAST if missing\n // NO fallback to prevent using stale/buggy rules\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const rules = require('../data/compiled/merged-rules.json');\n\n // Validate the rules - fail fast if invalid\n const validated = RuleValidator.validateOrThrow(rules, 'strict');\n\n return validated;\n } catch (error) {\n // NO FALLBACK - Fail immediately\n throw new Error(\n `${RULE_ERRORS.LOAD_FAILED}: Cannot load detection rules from merged-rules.json. ` +\n `This is likely a package build issue - run 'npm run compile-rules' to regenerate. ` +\n `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n /**\n * Load the bundled rules, memoised for the life of the loader.\n *\n * A `cdnUrl` is refused: schema validation alone would accept any\n * well-formed document from whoever controls the URL.\n */\n async loadRules(options: RuleLoadOptions = {}): Promise<DetectionRules> {\n if (options.cdnUrl !== undefined) {\n throw new Error(\n `${RULE_ERRORS.LOAD_FAILED}: cdnUrl is not supported; unsigned remote rules are not ` +\n `accepted. Use a signed rule bundle.`\n );\n }\n if (options.forceRefresh || !this.rules) {\n this.rules = RuleLoader.loadSync();\n }\n return this.rules;\n }\n\n /**\n * Get current loaded rules\n */\n getRules(): DetectionRules | null {\n return this.rules;\n }\n\n /**\n * Clear the memoised rules\n */\n clearCache(): void {\n this.rules = null;\n }\n\n /**\n * Reset singleton instance (mainly for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearCache();\n this.instance = null;\n }\n }\n}\n\n// `loadRulesSync` convenience function was removed in Phase-D.8.\n// All consumers now call `RuleLoader.loadSync()` directly. The class\n// surface didn't change.\n\n/**\n * Export convenience function for async loading\n */\nexport async function loadRulesAsync(options?: RuleLoadOptions): Promise<DetectionRules> {\n const loader = RuleLoader.getInstance();\n return loader.loadRules(options);\n}\n","/**\n * Rule Parser\n *\n * Parses YAML/JSON rule definitions\n */\n\nimport * as yaml from 'js-yaml';\nimport { DetectionRules } from '../types/rules';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Parse rule content (YAML or JSON)\n */\nexport class RuleParser {\n /**\n * Parse rule content from string\n */\n static parse(content: string): DetectionRules {\n if (!content || content.trim().length === 0) {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n\n // Try to detect format\n const trimmed = content.trim();\n\n try {\n // Try JSON first (faster)\n if (trimmed.startsWith('{')) {\n return JSON.parse(trimmed);\n }\n\n // Try YAML\n const parsed = yaml.load(trimmed);\n\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n\n return parsed as DetectionRules;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n // Format error message to match test expectations\n if (\n errorMessage.includes('JSON') ||\n errorMessage.includes('Unexpected') ||\n errorMessage.includes('Expected')\n ) {\n throw new Error('Parse failed: Invalid JSON');\n }\n throw new Error(`Parse failed: ${errorMessage}`);\n }\n }\n\n /**\n * Parse JSON rules\n */\n static parseJSON(content: string): DetectionRules {\n try {\n return JSON.parse(content);\n } catch (error) {\n throw new Error('Parse failed: Invalid JSON');\n }\n }\n\n /**\n * Parse YAML rules\n */\n static parseYAML(content: string): DetectionRules {\n try {\n const parsed = yaml.load(content);\n // Check if parsed result is a plain object (not array, string, number, etc.)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n return parsed as DetectionRules;\n } catch (error) {\n // If we threw INVALID_FORMAT, re-throw it\n if (error instanceof Error && error.message === RULE_ERRORS.INVALID_FORMAT) {\n throw error;\n }\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n // Format error message to match test expectations\n if (\n errorMessage.includes('unknown escape sequence') ||\n errorMessage.includes('YAML') ||\n errorMessage.includes('bad indentation')\n ) {\n throw new Error('Parse failed: Invalid YAML');\n }\n throw new Error('Parse failed: Invalid YAML');\n }\n }\n\n /**\n * Convert rules to JSON string\n */\n static toJSON(rules: DetectionRules, pretty = false): string {\n return JSON.stringify(rules, null, pretty ? 2 : 0);\n }\n\n /**\n * Convert rules to YAML string\n */\n static toYAML(rules: DetectionRules): string {\n return yaml.dump(rules, {\n indent: 2,\n lineWidth: -1,\n noRefs: true,\n sortKeys: false,\n });\n }\n\n /**\n * Validate basic rule structure\n */\n static validateStructure(rules: unknown): boolean {\n if (!rules || typeof rules !== 'object') return false;\n const candidate = rules as Record<string, unknown>;\n return !!(\n typeof candidate.version === 'string' &&\n typeof candidate.lastUpdated === 'string' &&\n candidate.rules &&\n typeof candidate.rules === 'object'\n );\n }\n}\n","/**\n * vendor-range-freshness.ts (checkpoint P35).\n *\n * Independent staleness gate for the AIVF-1 vendor IP-range catalogue\n * (`packages/checkpoint-rules/data/agent-types.yaml`). Deliberately\n * decoupled from `scripts/refresh-ai-vendor-ips.ts`'s own exit-code\n * contract: that script exits 1 only when EVERY enabled vendor's fetch\n * fails in a single run (a runner-side incident signal), so one vendor\n * that has been failing quietly for weeks — DNS drift, a moved feed URL,\n * a persistent 403 — never fails the job as long as the other rows keep\n * succeeding. This module checks the RESULT (how long since we last\n * successfully checked this vendor) rather than the process (did today's\n * fetch succeed), so it catches the failure mode the exit code can't see.\n *\n * This is the same shape of defect that let the Tier-1 OpenAI signing-key\n * pin (rust/crates/kya-os-engine/data/vendor-keys/openai.json) sit\n * expired for ~2 months: a refresh script existed, nothing ran it on a\n * schedule, and nothing alarmed when the pinned data went stale. See that\n * file's `_meta.comment` for the incident this module exists to prevent\n * from recurring here.\n *\n * Reads `ip_feed.last_checked`, NOT `ip_feed.last_refreshed`. Those two\n * fields answer different questions — `last_refreshed` is the VENDOR's\n * own `creationTime` for the data currently stored (can legitimately sit\n * unchanged for months on a vendor whose prefix list simply hasn't\n * moved), while `last_checked` is the RUNNER's wall clock, stamped on\n * every successful evaluation regardless of whether the data changed.\n * An earlier version of this module read `last_refreshed`, which made\n * every low-churn vendor read as permanently stale even on a perfectly\n * healthy refresh cadence (Cursor Bugbot finding on the PR that\n * introduced this gate — fixed before merge, kept here as the\n * cautionary note for why this distinction matters).\n */\n\nexport interface VendorFreshnessInput {\n id: string;\n /** Vendor rows with `enabled === false` are skipped — they aren't refreshed, so their age is expected and not an incident. */\n enabled?: boolean;\n /** The vendor's `ip_feed.last_checked` value (runner wall clock, stamped on every successful check — see file header for why this is NOT `last_refreshed`), in whatever ISO-ish shape agent-types.yaml stores (with or without a `Z`/offset). A missing/empty value is treated as unparseable, i.e. maximally stale — see `findStaleVendorRanges`. */\n lastCheckedIso: string;\n}\n\nexport interface StaleVendorDetail {\n id: string;\n lastCheckedIso: string;\n /** Milliseconds between `now` and the parsed `lastCheckedIso`. `Infinity` when the timestamp couldn't be parsed at all. */\n ageMs: number;\n}\n\n// Daily cron cadence (see .github/workflows/refresh-ai-vendor-ips.yml) plus\n// a 3-day grace window: one missed run shouldn't page anyone, but three in\n// a row — or one vendor silently failing for that long — should.\nexport const DEFAULT_MAX_VENDOR_RANGE_AGE_MS = 4 * 24 * 60 * 60 * 1000;\n\n/**\n * Returns every ENABLED vendor whose `lastCheckedIso` is older than\n * `maxAgeMs`. An unparseable (or missing/empty) timestamp is treated as\n * maximally stale (`ageMs: Infinity`) rather than skipped — a row this\n * module can't prove is fresh must never be reported as fresh; failing\n * closed toward alarming is the whole point of this module (see file\n * header).\n */\nexport function findStaleVendorRanges(\n vendors: VendorFreshnessInput[],\n now: Date,\n maxAgeMs: number = DEFAULT_MAX_VENDOR_RANGE_AGE_MS\n): StaleVendorDetail[] {\n const stale: StaleVendorDetail[] = [];\n for (const v of vendors) {\n if (v.enabled === false) continue;\n\n const parsedMs = Date.parse(v.lastCheckedIso);\n const ageMs = Number.isNaN(parsedMs) ? Infinity : now.getTime() - parsedMs;\n\n if (ageMs > maxAgeMs) {\n stale.push({ id: v.id, lastCheckedIso: v.lastCheckedIso, ageMs });\n }\n }\n return stale;\n}\n\nexport class StaleVendorRangesError extends Error {\n constructor(readonly stale: StaleVendorDetail[]) {\n const detail = stale\n .map((s) => {\n const age =\n s.ageMs === Infinity\n ? `unparseable/missing last_checked (${JSON.stringify(s.lastCheckedIso)})`\n : `${(s.ageMs / (24 * 60 * 60 * 1000)).toFixed(1)}d old`;\n return `${s.id} (${age})`;\n })\n .join(', ');\n super(\n `${stale.length} vendor range set(s) exceeded the staleness threshold and must not be ` +\n `served quietly: ${detail}. Refresh has stopped keeping up for these vendors — ` +\n `investigate scripts/refresh-ai-vendor-ips.ts's recent runs before treating the ` +\n `existing data as trustworthy.`\n );\n this.name = 'StaleVendorRangesError';\n }\n}\n\n/**\n * Throws `StaleVendorRangesError` when any enabled vendor's range set is\n * older than `maxAgeMs`. This is the \"raise rather than serve quietly\"\n * half of the contract — callers that need a hard stop (the CI freshness\n * gate in scripts/check-vendor-ranges-freshness.ts) call this directly;\n * a caller on a hot request path that must never throw (e.g. a future\n * runtime consumer) should use `findStaleVendorRanges` and log instead.\n */\nexport function assertVendorRangesFresh(\n vendors: VendorFreshnessInput[],\n now: Date,\n maxAgeMs: number = DEFAULT_MAX_VENDOR_RANGE_AGE_MS\n): void {\n const stale = findStaleVendorRanges(vendors, now, maxAgeMs);\n if (stale.length > 0) {\n throw new StaleVendorRangesError(stale);\n }\n}\n","import {\n PROBE_CLASSES,\n lacksBaselinePermit,\n statementId,\n unnarrowedDenyStatements,\n} from './cedar-principal-scope';\nimport { NO_EVIDENCE_CATEGORY, NO_EVIDENCE_EXCLUSION_TERM } from './legacy-carve-out';\n\nexport interface LintFinding {\n ruleId?: string;\n line: number;\n message: string;\n}\n\nconst NARROW_ADVICE =\n 'Add a `principal.category == \"ai_agent\"` (or `principal.name`) condition, or confirm you intend to affect them.';\nconst EVERYONE_MESSAGE = `This rule denies every visitor, including humans and ${NO_EVIDENCE_CATEGORY} visitors, because it does not narrow the principal. ${NARROW_ADVICE}`;\nconst HUMAN_MESSAGE = `This rule denies human visitors because it does not narrow the principal. ${NARROW_ADVICE}`;\nconst NO_EVIDENCE_MESSAGE =\n `This rule also applies to ${NO_EVIDENCE_CATEGORY} visitors, who are real people whose browser sent no evidence to classify. ` +\n `Add a \\`${NO_EVIDENCE_EXCLUSION_TERM}\\` condition, or confirm you intend to affect them.`;\n\nconst messageFor = (classes: readonly string[]): string =>\n classes.length === PROBE_CLASSES.length\n ? EVERYONE_MESSAGE\n : classes.includes(NO_EVIDENCE_CATEGORY)\n ? NO_EVIDENCE_MESSAGE\n : HUMAN_MESSAGE;\n\nexport function lintUnnarrowedDenyRules(cedar: string): LintFinding[] {\n return unnarrowedDenyStatements(cedar).map(({ statement, classes, line }) => ({\n ruleId: statementId(statement),\n line,\n message: messageFor(classes),\n }));\n}\n\nconst MISSING_BASELINE_MESSAGE =\n `This policy has no baseline permit, so every visitor that no permit rule covers is denied, humans and ${NO_EVIDENCE_CATEGORY} visitors included. ` +\n 'Add `permit(principal, action, resource);` if you want unmatched traffic allowed.';\n\nexport function lintMissingBaselinePermit(cedar: string): LintFinding[] {\n return lacksBaselinePermit(cedar) ? [{ line: 1, message: MISSING_BASELINE_MESSAGE }] : [];\n}\n","/**\n * Policy Module\n *\n * Shared policy types and schemas, the policy fetcher, and the helpers an\n * enforcement point uses around the engine's Cedar decision. The decision\n * itself comes from the engine (`@kya-os/checkpoint-wasm-runtime`).\n */\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nexport {\n // Enforcement actions (Vocab-1: PERMIT canonical, ALLOW + LOG deprecated aliases)\n ENFORCEMENT_ACTIONS,\n type EnforcementAction,\n // Enforcement modes (Vocab-1: orthogonal axis to Decision)\n ENFORCEMENT_MODES,\n type EnforcementMode,\n // Condition operators\n CONDITION_OPERATORS,\n type ConditionOperator,\n // Condition fields\n CONDITION_FIELDS,\n type ConditionField,\n // Defaults\n DEFAULT_THRESHOLDS,\n DEFAULT_POLICY,\n DEFAULT_RULE_PRIORITY,\n CACHE_TTL,\n CURRENT_POLICY_VERSION,\n} from './constants';\n\n// ============================================================================\n// Schemas (for runtime validation)\n// ============================================================================\n\nexport {\n // Action & match schemas (Vocab-1)\n EnforcementActionSchema,\n EnforcementModeSchema,\n // Decision schemas (Vocab-1: TS mirror of Rust Decision enum)\n BlockReasonSchema,\n AssuranceTierSchema,\n ChallengeParamsSchema,\n RedirectTargetSchema,\n SuggestedActionSchema,\n InstructPayloadSchema,\n DecisionSchema,\n // Threshold schemas\n ThresholdConfigSchema,\n // List entry schemas\n DenyListEntrySchema,\n AllowListEntrySchema,\n // Condition schemas\n ConditionOperatorSchema,\n ConditionFieldSchema,\n ConditionValueSchema,\n PolicyConditionSchema,\n // Rule schemas\n RuleMetadataSchema,\n PolicyRuleSchema,\n // Policy config schemas\n PolicyMetadataSchema,\n PolicyConfigSchema,\n // Validation helpers\n safeParsePolicyConfig,\n // Human step-up (gateway-enforcement-step-up, build item 5): normalize a\n // wire `challengeType` to the kind every renderer must treat it as.\n normalizeChallengeType,\n isEngineEnforcing,\n} from './schemas';\n\nexport { FAIL_CLOSED_BODY, FAIL_CLOSED_HEADERS, FAIL_CLOSED_STATUS } from './fail-closed-response';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type {\n ThresholdConfig,\n DenyListEntry,\n AllowListEntry,\n ConditionValue,\n PolicyCondition,\n RuleMetadata,\n PolicyRule,\n PolicyMetadata,\n PolicyConfig,\n // Vocab-1 Decision types (TS mirror of Rust Decision enum)\n BlockReason,\n AssuranceTier,\n ChallengeParams,\n RedirectTarget,\n SuggestedAction,\n InstructPayload,\n Decision,\n // Note: EnforcementMode is exported above from constants.ts (the\n // value-side const lives there; the schema lives here). Re-exporting\n // both keeps consumers from having to import from two paths.\n} from './schemas';\n\n// ============================================================================\n// Path patterns (skip and include path lists)\n// ============================================================================\n\nexport { matchPath } from './match-path';\n\n// ============================================================================\n// Composed-policy required scopes (the @scopes a CHALLENGE rule demands)\n// ============================================================================\n\nexport { requiredScopesForRequest } from './required-scopes';\nexport { ByteBoundedMemo } from './byte-bounded-memo';\n// #3236 / #3272 PR3: position-per-kind extraction of the determining policy's\n// authored @id from a Decision (the policies-index join key).\nexport { decisionPolicyId, type DecisionLike } from './decision-policy-id';\n// KYA-862 follow-up: synthetic `@id`s for the gateway's bespoke (non-Cedar)\n// policy mechanisms, so `/activity` attributes them (friendly non-linked label)\n// instead of an em-dash. (The `bespoke-` prefix const + id type stay internal to\n// the module — readers use exact membership via `isBespokePolicyId`, not the\n// prefix.)\nexport {\n BASELINE_ALLOW_POLICY_ID,\n BESPOKE_POLICY_IDS,\n bespokePolicyLabel,\n isBespokePolicyId,\n isNonNavigablePolicyId,\n nonNavigablePolicyLabel,\n} from './bespoke-policy';\nexport type { RequestFacts, PolicyHazardAnalysis } from './cedar-rule-match';\nexport {\n splitCedarBlocks,\n blockEqualityLiterals,\n pathLiteralsInBlock,\n pathHasUnnarrowedDenyRuleFor,\n analyzePolicySource,\n} from './cedar-rule-match';\nexport type { ProbeClass } from './cedar-principal-scope';\nexport { parseCedarStatements, statementApplies, statementId } from './cedar-principal-scope';\nexport {\n NO_EVIDENCE_CATEGORY,\n NO_EVIDENCE_EQUALITY_TERM,\n NO_EVIDENCE_EXCLUSION_TERM,\n withNoEvidenceExclusion,\n} from './legacy-carve-out';\n\n// ============================================================================\n// Author-time lint (Task 3)\n// ============================================================================\n\nexport type { LintFinding } from './policy-lint';\nexport { lintUnnarrowedDenyRules, lintMissingBaselinePermit } from './policy-lint';\n\n// ============================================================================\n// Cedar string grammar (escape codec + capture) — shared by the compose engine\n// emitter/parser and the enforcement-path readers so the grammar can't drift.\n// ============================================================================\n\nexport { escapeCedarString, unescapeCedarString, cedarQuotedValueRegExp } from './cedar-string';\n\n// ============================================================================\n// Composed-policy approval quorum (the @approvers / @quorum a CHALLENGE demands)\n// — the step-up case, distinct from the consent @scopes case (ADR D7).\n// ============================================================================\n\nexport { approvalQuorumForRequest, type ApprovalQuorum } from './approval-quorum';\n\n// ============================================================================\n// Step-up quorum validation (T3-edge) — the fail-closed guard the enforce path\n// runs before approval-signature verification. Shared so every edge runtime\n// applies the same gate as the central gateway PEP.\n// ============================================================================\n\nexport {\n validateStepUpQuorum,\n type InvalidStepUpReason,\n type StepUpQuorumCheck,\n type StepUpQuorumLike,\n} from './step-up';\n\n// ============================================================================\n// Fetcher\n// ============================================================================\n\nexport {\n // Types\n type PolicyCacheAdapter,\n type PolicyFetcherConfig,\n type CachedPolicy,\n // Class\n PolicyFetcher,\n PolicyUnavailableError,\n isPolicyUnavailableError,\n} from './fetcher';\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Check if an action is a \"blocking\" action — i.e. one where the host wrapper\n * does NOT pass the original request/response through unchanged. `instruct` is\n * blocking-class because the request is held pending guidance (matches the\n * dashboard's outcome bucket and the Decision-priority ordering in ADR-001).\n */\nexport function isBlockingAction(action: string): boolean {\n return (\n action === 'block' || action === 'redirect' || action === 'challenge' || action === 'instruct'\n );\n}\n","/**\n * Wire contract for the gateway ↔ vault bridge on Vercel (#1532,\n * #2025, #2029).\n *\n * Route: `POST /api/v1/gateway/vault/:projectId/resolve`\n *\n * The Fly gateway posts a signed Ed25519 assertion; the Vercel\n * route resolves per-user credentials and returns them. The two\n * sides used to keep independent TypeScript types for the envelope,\n * which let the success shape drift unnoticed when Vercel wrapped\n * the body in the standard `{ success, data }` envelope but Fly\n * kept reading `body.secrets` at the root. Both sides now import\n * and validate through these schemas, so shape drift becomes a\n * typecheck / runtime validation error instead of a silent bug.\n *\n * The schemas are exhaustive for their path — no `.passthrough()`,\n * no optional fields that aren't actually optional. If the live\n * wire format grows a field, land the schema change in the same\n * commit as the code that writes/reads it.\n */\n\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// Success body — 200 response from /api/v1/gateway/vault/:projectId/resolve\n// ---------------------------------------------------------------------------\n\n/**\n * Optional metadata attached to the 200 response when the vault side\n * has the org / upstream slug context. The gateway uses these to\n * build deep-link `actionUrl`s when the secrets map is empty\n * (CREDENTIALS_NOT_CONFIGURED path).\n */\nexport const vaultResolveMetaSchema = z\n .object({\n orgSlug: z.string().optional(),\n upstreamSlug: z.string().optional(),\n })\n .strict();\n\n/**\n * The inner `data` payload on a 200 response.\n *\n * `secrets` is always an object keyed by `envVarName`. Empty object\n * is valid and distinct from missing — an empty map signals \"user\n * hasn't connected this upstream yet\" while a missing field would\n * be a broken response. Values are always strings per §3.4 of the\n * #1532 wire contract; no nested secret types.\n */\nexport const vaultResolveDataSchema = z\n .object({\n secrets: z.record(z.string(), z.string()),\n _meta: vaultResolveMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Canonical envelope for every successful vault resolve. Every\n * 200 response on this path MUST match this schema exactly. The\n * `.strict()` on the outer object catches stray top-level fields\n * — if a new claim needs to land on the envelope, it gets a\n * schema update in the same PR.\n */\nexport const vaultResolveSuccessSchema = z\n .object({\n success: z.literal(true),\n data: vaultResolveDataSchema,\n })\n .strict();\n\nexport type VaultResolveSuccess = z.infer<typeof vaultResolveSuccessSchema>;\nexport type VaultResolveData = z.infer<typeof vaultResolveDataSchema>;\nexport type VaultResolveMeta = z.infer<typeof vaultResolveMetaSchema>;\n\n// ---------------------------------------------------------------------------\n// Error body — 4xx/5xx responses from the same route\n// ---------------------------------------------------------------------------\n\n/**\n * Every error response uses the nested `error: { code, message, data }`\n * envelope established in #1532 step 4 (commit 95994b751). The\n * `code` is a machine-readable string (`NOT_FOUND`, `INVALID_SIGNATURE`,\n * `GONE`, etc.) — see `vault-response-mapping.ts` on the gateway\n * side for the full list of recognized codes.\n */\nexport const vaultResolveErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n data: z\n .object({\n orgSlug: z.string().optional(),\n upstreamSlug: z.string().optional(),\n retryAfter: z.number().optional(),\n })\n .passthrough()\n .optional(),\n })\n .strict(),\n })\n .strict();\n\nexport type VaultResolveError = z.infer<typeof vaultResolveErrorSchema>;\n\n/**\n * Discriminated union over the two shapes. Callers that receive a\n * parsed body can branch on `success` without a separate status\n * check.\n */\nexport const vaultResolveResponseSchema = z.discriminatedUnion('success', [\n vaultResolveSuccessSchema,\n vaultResolveErrorSchema,\n]);\n\nexport type VaultResolveResponse = z.infer<typeof vaultResolveResponseSchema>;\n","/**\n * Canonical KYA-OS per-organization did:web derivation.\n *\n * The org slug becomes a single path segment in\n * `https://kya.vouched.id/orgs/<slug>/did.json`, so validation here is a\n * security boundary shared by issuers and verifiers.\n */\n\n/** did:web host for org issuer DIDs. */\nexport const MCPI_ORG_DID_HOST = 'kya.vouched.id';\n\nconst ORG_SLUG_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/**\n * True when `slug` is a valid `did:web` org path segment — i.e. it can be fed\n * to {@link deriveMcpiOrgDid} without throwing. Callers that accept a\n * user-supplied slug MUST gate on this before persisting it, since the org DID\n * is derived from the slug at every mint/publish/verify site; an invalid slug\n * bricks credential issuance for that org.\n */\nexport function isValidMcpiOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug);\n}\n\n/** Build the org's `did:web` issuer DID from its slug. Throws on invalid slugs. */\nexport function deriveMcpiOrgDid(slug: string): string {\n if (!ORG_SLUG_PATTERN.test(slug)) {\n throw new Error(`Invalid org slug for did:web derivation: ${JSON.stringify(slug)}`);\n }\n return `did:web:${MCPI_ORG_DID_HOST}:orgs:${slug}`;\n}\n\n/**\n * The verification-method fragment of an org's signing key number `sequence`\n * (`key-<sequence>`). An org's keys are numbered from 1 and a number is never\n * reused, so `<org did>#key-<sequence>` names one key forever; it is that\n * key's verification method in the org DID document and the JWT `kid` of\n * everything it signs. Which key is active is the issuer's business: a\n * verifier takes the key the kid names from the issuer's DID document.\n */\nexport function mcpiOrgKeyFragment(sequence: number): string {\n if (!Number.isSafeInteger(sequence) || sequence < 1) {\n throw new RangeError(`An org key sequence is a positive integer, got ${sequence}`);\n }\n return `key-${sequence}`;\n}\n\nconst ORG_KEY_FRAGMENT_PATTERN = /^key-[1-9]\\d{0,8}$/;\n\n/**\n * True when `kid` names one of the org's signing keys: `<orgDid>#key-<n>`,\n * n ≥ 1. Verifiers pin a credential's `kid` with this before resolving the\n * issuer's DID document, then take the key from the method with that id.\n */\nexport function isMcpiOrgKeyId(orgDid: string, kid: unknown): boolean {\n return (\n typeof kid === 'string' &&\n kid.startsWith(`${orgDid}#`) &&\n ORG_KEY_FRAGMENT_PATTERN.test(kid.slice(orgDid.length + 1))\n );\n}\n\n/**\n * The delegation root DIDs an org trusts — the value the policies route resolves\n * SERVER-SIDE and returns on the policy payload, which each surface forwards into\n * the engine's `ContextSpec.trustedDelegationRoots` allow-list.\n *\n * Option 1 (first-party): an org trusts ONLY delegations rooted at its own DID.\n * This is the single place trust-root composition lives — called server-side in\n * the policies route, never on a surface. Option 2 (configurable partner issuer\n * DIDs) and the #3020 `resolveOrgDid(org)` multi-host generalization extend ONLY\n * this function; the engine, wire format, orchestrator threading, and every\n * surface stay unchanged.\n *\n * Throws on an invalid slug (same boundary as {@link deriveMcpiOrgDid}) rather\n * than returning `[]`: an empty list makes the engine reject every delegation,\n * so an org with a broken slug is a configuration error to surface loudly\n * server-side, not a silent outage of every delegated agent.\n */\nexport function resolveTrustedDelegationRoots(org: { slug: string }): string[] {\n return [deriveMcpiOrgDid(org.slug)];\n}\n","/**\n * Canonical KYA-OS user DID derivation: a user's did:web under the org's DID\n * tree. Every sign-in method and every consent leg names its user here, so the\n * mapping from a user id to a DID is one function.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { deriveMcpiOrgDid } from './org-did';\n\n/**\n * Marks a hashed user id segment: `sha256-` plus the RFC 4648 base32\n * (lowercase, unpadded) of SHA-256 over the UTF-8 bytes of `<slug>:<userId>`.\n */\nexport const MCPI_HASHED_USER_ID_PREFIX = 'sha256-';\n\n/** A did:web path segment: letters, digits, `.`, `_`, `-`, alphanumeric at both ends, ≤ 255. */\nconst USER_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\nconst BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';\n\n/** RFC 4648 base32, lowercase, without padding. */\nfunction base32(bytes: Uint8Array): string {\n let out = '';\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = ((buffer << 8) | byte) & 0xfff;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += BASE32_ALPHABET[(buffer >> bits) & 31];\n }\n }\n if (bits > 0) out += BASE32_ALPHABET[(buffer << (5 - bits)) & 31];\n return out;\n}\n\n/**\n * The DID path segment that names `userId` in org `slug`.\n *\n * - A user id that is a valid path segment is used as it is, so those DIDs\n * never move.\n * - Any other id (an Auth0 `auth0|…` subject, an email, a URL, anything over\n * 255 characters) is hashed: `sha256-` + base32(SHA-256(\"<slug>:<userId>\")),\n * 59 characters. The DID then carries no personal data and keeps a fixed\n * length, and a merchant can recompute it from its own customer id. The hash\n * is over the id exactly as given, with no trimming or Unicode normalisation.\n * - An id that already starts with the prefix (in any case) is hashed too, so\n * no raw id can equal another id's hash.\n *\n * Throws on a blank user id: a blank principal is never a user.\n */\nexport function mcpiUserIdSegment(slug: string, userId: string): string {\n if (userId.trim() === '') {\n throw new Error(`Invalid user id for did:web derivation: ${JSON.stringify(userId)}`);\n }\n const reserved = userId.toLowerCase().startsWith(MCPI_HASHED_USER_ID_PREFIX);\n if (USER_ID_PATTERN.test(userId) && !reserved) return userId;\n const digest = sha256(new TextEncoder().encode(`${slug}:${userId}`));\n return `${MCPI_HASHED_USER_ID_PREFIX}${base32(digest)}`;\n}\n\n/**\n * Build a user's `did:web` DID under the org's DID tree. Resolves to\n * `https://kya.vouched.id/orgs/<slug>/users/<segment>/did.json`, where the\n * segment is {@link mcpiUserIdSegment}.\n *\n * Throws on an invalid slug or a blank user id.\n */\nexport function deriveMcpiUserDid(slug: string, userId: string): string {\n const orgDid = deriveMcpiOrgDid(slug);\n return `${orgDid}:users:${mcpiUserIdSegment(slug, userId)}`;\n}\n","/**\n * Canonical principals + MCP client DID derivation.\n *\n * Standard requires `did:web` or `did:key` for any DID we emit — no\n * ad-hoc methods. This module defines:\n *\n * - {@link ANONYMOUS_PRINCIPAL_DID}: a known anonymous-principal `did:web`\n * used as the sentinel when the gateway cannot determine the subject\n * (replaces the pre-#3022 `did:kya:anonymous` ad-hoc form).\n * - {@link deriveMcpClientDid}: derives an MCP client's canonical `did:web`\n * from its client id (replaces the pre-#3022 `did:client:<id>` shape).\n *\n * The anonymous principal resolves to a minimal stub DID document at\n * `https://kya.vouched.id/principals/anonymous/did.json` (no verification\n * methods — the principal can't sign anything, it's a sentinel).\n *\n * The client DID resolves to `https://knowthat.ai/clients/<id>/did.json`.\n * Known first-party clients (Cursor, Claude Desktop, etc.) have docs served\n * by the KTA registry; unknown clients use the same shape and may 404 on\n * resolution today.\n *\n * `deriveMcpClientDid` also accepts a CIMD `client_id` (an OAuth Client ID\n * Metadata Document URL, SEP-991 / draft-ietf-oauth-client-id-metadata-\n * document). This is NOT the ratified `did:web` <-> HTTPS bijection from\n * SPEC-ENTITY-CARD.md §7.1 (`didFromClientId` in `@kya-os/mcp`'s\n * `src/card/cimd.ts`) — applying that bijection to a third-party CIMD URL\n * (e.g. `https://claude.ai/...`) would mint a `did:web:claude.ai:...`, a\n * different host than `knowthat.ai`, which this module's callers require\n * and which would 404 (Anthropic doesn't serve a DID document there). So a\n * CIMD URL is instead mapped onto the SAME `knowthat.ai:clients:<slug>`\n * shape every other client id already produces — see `CIMD_CLIENT_SLUGS`.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\n\nexport { ANONYMOUS_PRINCIPAL_DID } from './anonymous-principal';\n\n/** did:web host for MCP client DIDs (KnowThatAi registry). */\nexport const MCP_CLIENT_DID_HOST = 'knowthat.ai';\n\nconst CLIENT_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/** Deterministic-fallback slug prefix for a CIMD URL with no known mapping below. */\nconst CIMD_FALLBACK_PREFIX = 'cimd-';\n\n/**\n * Known CIMD `client_id` URLs mapped onto the SAME slug `KNOWN_CLIENTS`\n * already uses in `apps/web/lib/gateway/mcp-client-did.ts` — resolving one\n * of these produces the EXACT DID string that id already resolves to today\n * (no migration). Keyed on the full, exact `client_id` string, never the\n * host: `claude.ai` alone serves distinct CIMD documents for Claude Code vs.\n * Claude Desktop/web/Cowork, and host-only keying would merge slugs\n * `KNOWN_CLIENTS` deliberately keeps separate.\n *\n * `https://claude.ai/oauth/mcp-oauth-client-metadata` (Claude Desktop, the\n * claude.ai web app, mobile, and Cowork) is deliberately left OUT: that one\n * client_id is shared by four distinct surfaces, and mapping it to a single\n * `claude-desktop` slug would over-claim a precision the id doesn't carry.\n * It falls through to the deterministic `cimd-<hash>` slug below instead.\n * Revisit if/when KTA adds a broader registry entry for it.\n */\nconst CIMD_CLIENT_SLUGS: Readonly<Record<string, string>> = {\n 'https://claude.ai/oauth/claude-code-client-metadata': 'claude-code',\n 'https://vscode.dev/oauth/client-metadata.json': 'vscode',\n};\n\n/**\n * The slugs `CIMD_CLIENT_SLUGS` maps CIMD URLs onto — reserved so an\n * OPAQUE (non-URL) client id can never collide with one. Without this, an\n * opaque `client_id: 'claude-code'` would mint the exact same\n * `did:web:knowthat.ai:clients:claude-code` a domain-verified CIMD\n * resolution produces, distinguishable only by the caller's separately-\n * tracked provenance (`oauth_client_derived` vs `oauth_client_cimd`) —\n * any downstream consumer that keys off `agentDid` alone can't tell them\n * apart. `isCimdClientId` already rejects non-URL strings before this\n * function's CIMD branch ever runs, so the only way to reach a reserved\n * slug through the opaque path is by supplying the bare slug text itself.\n */\nconst RESERVED_CIMD_SLUGS = new Set(Object.values(CIMD_CLIENT_SLUGS));\n\n/**\n * Build an MCP client's `did:web` from its client id. Throws on invalid ids.\n *\n * Accepts two client id shapes:\n * - An opaque, pattern-valid id (e.g. a DCR-issued UUID or a known slug)\n * — unchanged behavior, byte-identical output to before CIMD support.\n * - A CIMD `client_id` URL — must be `https:` with a non-empty path.\n * A known KYA-OS-issued URL (`CIMD_CLIENT_SLUGS`) resolves to its\n * existing slug; an unknown one gets a deterministic `cimd-<sha256\n * prefix>` slug, stable for the life of that client_id. Either way the\n * DID keeps the exact same `did:web:knowthat.ai:clients:<slug>` shape,\n * so no migration is required.\n *\n * The resulting DID resolves to `https://knowthat.ai/clients/<id>/did.json`.\n */\nexport function deriveMcpClientDid(clientId: string): string {\n const cimdUrl = tryParseUrl(clientId);\n const slug = cimdUrl ? slugForCimdUrl(cimdUrl, clientId) : clientId;\n\n if (!CLIENT_ID_PATTERN.test(slug)) {\n throw new Error(`Invalid client id for did:web derivation: ${JSON.stringify(clientId)}`);\n }\n // Reject an opaque client id that collides with a slug CIMD_CLIENT_SLUGS\n // reserves for domain-verified resolution — see RESERVED_CIMD_SLUGS.\n if (!cimdUrl && RESERVED_CIMD_SLUGS.has(slug)) {\n throw new Error(`Reserved CIMD client slug, cannot use as an opaque client id: ${slug}`);\n }\n return `did:web:${MCP_CLIENT_DID_HOST}:clients:${slug}`;\n}\n\n/** Parse `value` as a URL, or null if it isn't URL-shaped (an opaque client id). */\nfunction tryParseUrl(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a CIMD `client_id` URL to its did:web slug. CIMD requires `https`\n * and a path component; a non-https scheme or a bare origin throws rather\n * than silently falling back to the opaque-id path.\n */\nfunction slugForCimdUrl(url: URL, originalClientId: string): string {\n if (url.protocol !== 'https:' || url.pathname === '' || url.pathname === '/') {\n throw new Error(\n `Invalid client id for did:web derivation: ${JSON.stringify(originalClientId)}`\n );\n }\n const known = CIMD_CLIENT_SLUGS[originalClientId];\n if (known) return known;\n const digest = bytesToHex(sha256(new TextEncoder().encode(originalClientId)));\n return `${CIMD_FALLBACK_PREFIX}${digest.slice(0, 32)}`;\n}\n","/**\n * Reported identity — the wire block a KYA-OS-aware enforcement point (a\n * \"verifier\", e.g. the in-process `@kya-os/id/mcp` reporter the Hobbsidian\n * reference customer runs) sends to Checkpoint's `/api/v1/log-detection` to\n * describe WHO acted and on WHOSE behalf.\n *\n * This is the M1 hinge contract of `docs/architecture/agent-identity-taxonomy.md`\n * (§5.1) — the shape both Checkpoint ingest and every KYA-OS reporter converge\n * on, and the draft of the proposed \"Verifier Reporting Profile\" (§10). Field\n * names track KYA-OS / draft-kya-http vocabulary (issuer / audience / capability\n * / jti) so the block can graduate into a non-normative DIF companion without a\n * rename.\n *\n * THREE deliberate properties:\n *\n * 1. **Asserted vs verified is explicit.** `agent` and `principal` are\n * identities the reporter ASSERTS; only `delegation.result` carries a\n * verification OUTCOME, and `delegation.verifiedBy` says who did the\n * cryptography. Checkpoint derives an *assurance* tier\n * ({@link AssuranceTier}) from these server-side — the reporter does not\n * get to assert its own assurance.\n *\n * 2. **agent ≠ principal, structurally.** The bug that motivated this block\n * (a reporter sending a *user* DID under a generic `signals[{kind:\n * \"agent_did\"}]` entry, rendering \"on behalf of: unattributed\") is\n * impossible to express here: the principal's DID lives on `principal.did`,\n * the agent's on `agent.did`. They are separate objects.\n *\n * 3. **`clientInfoName` is a DECLARED hint, never identity.** MCP `initialize`\n * `clientInfo.name` and User-Agent are unauthenticated; a verifier MUST NOT\n * treat them as agent identity (this is the spec security-considerations\n * posture, §10.2). They are recorded as declared metadata at most — the\n * resolution ladder caps their assurance at `attested-bearer`.\n *\n * Additive-optional, mirroring every prior `log-detection` evolution\n * (enforcement #2446, engine Phase-0.1, sdk #3076, engineSteps #3164): the whole\n * block is optional, and objects are non-strict (unknown keys strip) so a newer\n * reporter field never 400s an older Checkpoint. The reporter may emit this\n * block immediately — pre-M1 ingest silently strips it (see §5.3 dual-emit pin).\n *\n * NOT carried here: the full delegation JWS/VC body. `delegations` /\n * `bouncer_proofs` remain the credential stores; this block carries the\n * *reference* (`jti`) and the *outcome*, not the proof.\n */\n\nimport { z } from 'zod';\nimport { REGISTERED_SID_MAX_LENGTH } from './registered-sid';\n\n/**\n * A W3C DID string. Required form per the KYA-OS standard: `did:web` or\n * `did:key` (no ad-hoc methods). We validate only the `did:` scheme prefix here\n * — method-specific structure is the resolver's concern — but the prefix alone\n * is enough to reject the junk that an untyped signals array used to admit (a\n * bare userId, an email, a UA string).\n */\nconst DidStringSchema = z\n .string()\n .trim()\n .min(1)\n .regex(/^did:/, 'must be a DID (did:web / did:key)');\n\n/** A non-empty, trimmed free string (rejects whitespace-only values). */\nconst NonEmptyTrimmed = z.string().trim().min(1);\n\n/**\n * The acting agent's asserted identity. Every field is optional — a reporter\n * fills in what it actually knows: an enterprise A2A agent has a `did`; a\n * generic OAuth MCP client has only an `oauthClientId` (Checkpoint derives its\n * `did:web` server-side via `deriveMcpClientDid`); an unauthenticated client\n * offers only the declared `clientInfoName`.\n */\nexport const ReportedAgentSchema = z\n .object({\n /** The agent's own DID, when it has one (enterprise A2A / provisioned). */\n did: DidStringSchema.optional(),\n /**\n * OAuth `client_id` of an authenticated MCP client. Checkpoint derives the\n * canonical `did:web` from this (DR-9 `deriveMcpClientDid`); the reporter\n * sends the raw id, not the derived DID.\n */\n oauthClientId: NonEmptyTrimmed.optional(),\n /**\n * MCP `initialize` `clientInfo.name` (e.g. `claude-ai`, `cursor`). DECLARED,\n * unauthenticated — recorded as a hint, never resolved as identity above\n * `attested-bearer` assurance.\n */\n clientInfoName: NonEmptyTrimmed.optional(),\n /** MCP `initialize` `clientInfo.version`. Declared. */\n clientInfoVersion: NonEmptyTrimmed.optional(),\n })\n .describe('Asserted identity of the acting agent');\nexport type ReportedAgent = z.infer<typeof ReportedAgentSchema>;\n\n/**\n * The human (or upstream) principal the agent acted on behalf of — the \"on\n * behalf of\" attribution. `did` is preferred (e.g.\n * `did:web:h0bb5.dev:u:<userId>`); `sub` is the issuer-local subject when no\n * DID is minted; `email` is an optional display identity only.\n */\nexport const ReportedPrincipalSchema = z\n .object({\n /** The principal's DID (the delegation issuer, typically). */\n did: DidStringSchema.optional(),\n /** Issuer-local subject identifier, when the principal has no DID. */\n sub: NonEmptyTrimmed.optional(),\n /** Optional display email. Never the identity key — `did`/`sub` are. */\n email: NonEmptyTrimmed.email().optional(),\n })\n .describe('Asserted identity of the principal the agent acted for');\nexport type ReportedPrincipal = z.infer<typeof ReportedPrincipalSchema>;\n\n/**\n * Outcome of presenting a delegation. `verified` = the signed delegation\n * checked out; `failed` = presented but rejected; `not_presented` = none on the\n * request. Required whenever a `delegation` block is sent — an outcome-less\n * delegation block is meaningless.\n */\nexport const DelegationResultSchema = z.enum(['verified', 'failed', 'not_presented']);\nexport type DelegationResult = z.infer<typeof DelegationResultSchema>;\n\n/**\n * Who performed the delegation cryptography — the trust provenance of\n * `result`. `reporter` = the customer's own in-process verifier checked it\n * (same trust class as all SDK self-reporting, bounded by the API key's project\n * scope); `gateway` = a Checkpoint gateway verified it in-path; `checkpoint` =\n * the ingest plane re-verified. Persisted so a future in-path mode can rank\n * above self-reported without a schema change.\n */\nexport const DelegationVerifiedBySchema = z.enum(['reporter', 'gateway', 'checkpoint']);\nexport type DelegationVerifiedBy = z.infer<typeof DelegationVerifiedBySchema>;\n\nexport { REGISTERED_SID_MAX_LENGTH, SID_ATTRIBUTABLE_RESULT } from './registered-sid';\n\n/**\n * The delegation the agent presented (a reference + outcome, not the proof).\n * `result` and `verifiedBy` are required; the JWT claims (`jti` / `iss` / `aud`\n * / `capabilities` / `exp`) are optional because `not_presented` carries none.\n */\nexport const ReportedDelegationSchema = z\n .object({\n /** Delegation credential id — the join key into `delegations`. */\n jti: NonEmptyTrimmed.optional(),\n /**\n * The registered session anchor: the draft-kya-http-02 `sid` claim of the\n * presented credential (the top-level VC-JWT `sid` minted in\n * `mint-vc-jwt.ts`), distinct from any gateway or MCP session id. Optional,\n * and attributed to a session timeline only when `result` is `verified`\n * ({@link SID_ATTRIBUTABLE_RESULT}); ingest nulls it for any other result.\n * No refine here: the identity block must never fail a request.\n */\n sid: NonEmptyTrimmed.max(REGISTERED_SID_MAX_LENGTH).optional(),\n /** Issuer DID (usually the principal). */\n iss: DidStringSchema.optional(),\n /** Audience DID (the intended verifier / resource). */\n aud: DidStringSchema.optional(),\n /** Granted capabilities, e.g. `['vault:read']`. */\n capabilities: z.array(NonEmptyTrimmed).optional(),\n /** Expiry, unix seconds. */\n exp: z.number().int().positive().optional(),\n /** Verification outcome — required. */\n result: DelegationResultSchema,\n /** Who verified — required. */\n verifiedBy: DelegationVerifiedBySchema,\n })\n .describe('Presented delegation: reference + verification outcome');\nexport type ReportedDelegation = z.infer<typeof ReportedDelegationSchema>;\n\n/**\n * The full reported-identity block. All three sub-blocks are optional so a\n * reporter sends only what it has; an empty `{}` is valid (a reporter that\n * carries no identity at all). Checkpoint resolves the agent against its\n * catalog, attributes the principal, and derives the assurance tier from this\n * block plus the engine verdict.\n */\nexport const ReportedIdentitySchema = z\n .object({\n agent: ReportedAgentSchema.optional(),\n principal: ReportedPrincipalSchema.optional(),\n delegation: ReportedDelegationSchema.optional(),\n })\n .describe('KYA-OS reported identity (verifier → observability plane)');\nexport type ReportedIdentity = z.infer<typeof ReportedIdentitySchema>;\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Tolerant + canonical multibase codec for Ed25519 public keys used across\n * checkpoint's mcp-i auth surfaces (org DID docs, approver keys, worker\n * signed-agent verification).\n *\n * Lifts two previously-divergent decoders into one shared implementation:\n * - apps/gateway/src/lib/multibase.ts's `decodeEd25519PublicKeyMultibase`\n * accepted ONLY `z` (base58btc) + exactly 34 bytes (multicodec), throwing\n * on anything else.\n * - apps/web/workers/gateway/src/detection/did-verifier.ts's local\n * `decodeMultibase` accepted `z` and `m` (read as base64url, which\n * deviates from the multibase spec where `m` = standard base64, but\n * matches what knowthat.ai's DID generator actually emits), plus 32-byte\n * raw or 34-byte multicodec bodies.\n *\n * Neither accepted `u`, the actual multibase-spec prefix for base64url.\n * `decodeEd25519PublicKeyMultibaseTolerant` accepts z/m/u and both body\n * shapes, and — unlike the strict gateway decoder — never throws; callers\n * treat `null` as \"not a decodable Ed25519 key\" and route it into their\n * existing fail-closed paths.\n *\n * Reuses the base58btc codec from `./did-key` rather than adding a third\n * copy (a THIRD near-identical implementation was the state before this\n * module existed).\n */\n\nimport { base58btcDecode, base58btcEncode } from './did-key';\n\nconst ED25519_PUB_MULTICODEC = [0xed, 0x01] as const;\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Length ceiling applied BEFORE decoding. The longest legitimate body is a\n * 34-byte multicodec key: 47 chars in base58btc, 48 in padded base64. Bodies\n * past this cap are rejected by the length check anyway — the point is to\n * reject them before `base58btcDecode`'s O(n^2) repeated division runs, since\n * `publicKeyMultibase` / `publicKeyBase58` arrive from DID documents fetched\n * over the network and a hostile document could otherwise burn seconds of\n * event-loop (gateway) or isolate (worker) CPU per key. Mirrors the same guard\n * on `decodeDidKeyEd25519` in ./did-key.\n */\nexport const MAX_ED25519_KEY_BODY_LENGTH = 64;\n\n/**\n * Decode a base64 body to bytes, accepting both the url-safe (`-`, `_`) and\n * standard (`+`, `/`) alphabets and tolerating the presence or absence of\n * `=` padding. Returns null on any malformed input — never throws.\n */\nfunction base64AnyToBytes(body: string): Uint8Array | null {\n if (body.length === 0) return null;\n let normalized = body.replace(/-/g, '+').replace(/_/g, '/');\n const remainder = normalized.length % 4;\n if (remainder === 1) return null; // no valid base64 encoding has this length\n if (remainder === 2) normalized += '==';\n else if (remainder === 3) normalized += '=';\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;\n\n try {\n const bin = atob(normalized);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\n/** Strip the ed25519-pub multicodec prefix if present; validate the length either way. */\nfunction toRawEd25519Key(decoded: Uint8Array): Uint8Array | null {\n if (decoded.length === ED25519_PUBKEY_LENGTH) return decoded;\n if (\n decoded.length === ED25519_MULTIKEY_LENGTH &&\n decoded[0] === ED25519_PUB_MULTICODEC[0] &&\n decoded[1] === ED25519_PUB_MULTICODEC[1]\n ) {\n return decoded.slice(ED25519_PUB_MULTICODEC.length);\n }\n return null;\n}\n\n/**\n * Decode a `publicKeyMultibase` value to a raw 32-byte Ed25519 public key.\n * Accepts multibase prefixes `z` (base58btc), `m` (base64url — the value\n * checkpoint's own DID documents emit, though not per the multibase spec),\n * and `u` (base64url per the multibase spec). The decoded body may be 32\n * raw key bytes or 34 bytes prefixed with the ed25519-pub multicodec\n * (`0xed 0x01`), which is stripped. Returns null for any other prefix,\n * length, or invalid encoding — never throws.\n */\nexport function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null {\n if (typeof mb !== 'string' || mb.length < 2) return null;\n\n const prefix = mb[0];\n const body = mb.slice(1);\n if (body.length > MAX_ED25519_KEY_BODY_LENGTH) return null;\n\n let decoded: Uint8Array | null;\n if (prefix === 'z') {\n decoded = base58btcDecode(body);\n } else if (prefix === 'm' || prefix === 'u') {\n decoded = base64AnyToBytes(body);\n } else {\n return null;\n }\n if (!decoded) return null;\n\n return toRawEd25519Key(decoded);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a canonical `z`-prefixed,\n * ed25519-pub-multicodec multibase string. Throws if the key is not\n * exactly 32 bytes — an emitter handing in the wrong length is a\n * programming error, not untrusted input (unlike the tolerant decoder).\n */\nexport function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string {\n if (rawPubKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `Ed25519 public key must be ${ED25519_PUBKEY_LENGTH} bytes, got ${rawPubKey.length}`\n );\n }\n const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n prefixed[0] = ED25519_PUB_MULTICODEC[0];\n prefixed[1] = ED25519_PUB_MULTICODEC[1];\n prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);\n return 'z' + base58btcEncode(prefixed);\n}\n\n// Re-exported so a single subpath import also covers: (1) the legacy\n// `Ed25519VerificationKey2018` `publicKeyBase58` form (raw base58btc, no\n// multibase prefix, no multicodec) the worker needs, and (2) constructing\n// non-canonical-but-valid multibase fixtures (e.g. raw-32-byte z bodies) in\n// tests — without pulling the full package index either way.\nexport { base58btcDecode, base58btcEncode };\n","/**\n * Common delegation-verdict shape (verifier/engine unification series).\n *\n * The `delegation` cross-runtime-parity track\n * (`tests/cross-runtime-parity/delegation/`) checks multiple independent\n * delegation-verify implementations — the Fly gateway (`apps/gateway/src/lib/\n * mcpi-auth-resolver.ts` + `dashboard-delegation-verifier.ts`, both engine-\n * backed as of PR6/PR7) and `rust/crates/kya-os-engine`'s `verify_delegation`\n * — against one canonical vector set. Every emitter normalizes its runtime's\n * result to this shape before writing `runtime-outputs/<name>.json`. Lives\n * under the package's main entrypoint (not `test-fixtures`) because the\n * parity-harness test imports it as production infrastructure;\n * `test-fixtures/delegation-verdict.ts` re-exports it for the existing\n * parity-harness imports.\n *\n * Deliberately verdict-only (`kind` + coarse `reason.kind`), not the full\n * delegation record: the gateway's audit extractions (`delegationId`,\n * `clientDid`, `orgId`, `accountableAdminDid`) are deterministic claim reads,\n * not verification decisions, so they don't belong in a cross-implementation\n * agreement check — their correctness is covered by the gateway's own unit\n * tests (`mcpi-auth-resolver.test.ts`, `dashboard-delegation-verifier.test.ts`),\n * which is their natural home. Keeping this shape to exactly what\n * `scripts/assert-cross-runtime-parity.ts` already matches on (`kind`,\n * `reason.kind`, `reason.kindStartsWith`, `oneOf`) means that script needs no\n * per-track special-casing.\n *\n * `reason.kind` is deliberately coarse — a structural reason CLASS, not a\n * fine-grained cause. Each runtime's native vocabulary is many-to-one mapped\n * onto this fixed set via `toCoarseReasonKind`:\n *\n * - `signature` — bad/absent cryptographic signature\n * - `claim` — any issuer / audience / subject / orgId / other claim or\n * authorization mismatch (including \"no identity material\n * presented at all\")\n * - `time` — expired OR not-yet-valid\n * - `revocation` — revoked, or status-unavailable (fail-closed)\n * - `scope` — delegation doesn't grant the requested scope\n * - `resolve` — DID / context could not be resolved\n *\n * This is the coarsest granularity both the gateway (whose own top-level\n * verifier already folds iss/aud/orgId/sub into one `claim_invalid` /\n * `claim_mismatch`) and the engine (whose `BlockReason` has no\n * audience/issuer/not-yet-valid-specific variants) can already express\n * without changing either side's production reason taxonomy. Fine-grained\n * reason parity is an observability nice-to-have, not a security property —\n * the gate's job is to catch security-relevant WHY-drift (a different\n * structural reason class, or accept-vs-reject), not whether both sides spell\n * a claim rejection the same way. If per-cause parity is ever wanted, extend\n * each runtime's own reason vocabulary deliberately on its own timeline —\n * never bundle it with this track's blocking gate.\n */\n\nexport type DelegationVerdictKind = 'Permit' | 'Block';\n\nexport type CoarseReasonKind = 'signature' | 'claim' | 'time' | 'revocation' | 'scope' | 'resolve';\n\nexport interface DelegationVerdictReason {\n kind: CoarseReasonKind;\n}\n\nexport interface DelegationVerdict {\n kind: DelegationVerdictKind;\n reason: DelegationVerdictReason | null;\n}\n\n/**\n * Every raw reason discriminator either runtime can natively emit for the\n * delegation path, mapped onto the coarse taxonomy above.\n *\n * Gateway (`McpiAuthErrorReason` in `mcpi-auth-resolver.ts`,\n * `DashboardVerifyFailure['reason']` in `dashboard-delegation-verifier.ts`):\n * snake_case. Engine (`BlockReason` in `rust/crates/kya-os-engine/src/types.rs`):\n * PascalCase variant names. Unrecognized input is a harness bug (an emitter\n * started producing a reason string neither side has ever emitted before) —\n * `toCoarseReasonKind` throws rather than silently defaulting, so a new raw\n * reason gets a deliberate classification instead of landing in the wrong\n * bucket unnoticed.\n */\nconst REASON_KIND_MAP: Record<string, CoarseReasonKind> = {\n // --- gateway: apps/gateway/src/lib/mcpi-auth-resolver.ts ---\n missing_bearer_token: 'claim',\n parse_error: 'claim',\n did_resolve_failed: 'resolve',\n signature_invalid: 'signature',\n audience_mismatch: 'claim',\n expired: 'time',\n not_yet_valid: 'time',\n revoked: 'revocation',\n delegation_inactive: 'revocation',\n missing_claim: 'claim',\n claim_invalid: 'claim',\n // --- gateway: apps/gateway/src/lib/dashboard-delegation-verifier.ts ---\n not_configured: 'claim',\n header_missing: 'claim',\n claim_mismatch: 'claim',\n malformed: 'claim',\n // --- engine-rust: rust/crates/kya-os-engine/src/types.rs BlockReason ---\n Revoked: 'revocation',\n InvalidSignature: 'signature',\n Unauthenticated: 'claim',\n Expired: 'time',\n OutOfScope: 'scope',\n};\n\n/** Map a runtime's native reason discriminator onto the coarse taxonomy. */\nexport function toCoarseReasonKind(rawReasonKind: string): CoarseReasonKind {\n const coarse = REASON_KIND_MAP[rawReasonKind];\n if (!coarse) {\n throw new Error(\n `toCoarseReasonKind: unrecognized raw reason kind ${JSON.stringify(rawReasonKind)} — ` +\n `add it to REASON_KIND_MAP in delegation-verdict.ts with a deliberate coarse classification`\n );\n }\n return coarse;\n}\n\n/** Build a `Permit` verdict. */\nexport function permitDelegationVerdict(): DelegationVerdict {\n return { kind: 'Permit', reason: null };\n}\n\n/** Build a `Block` verdict from a runtime-native reason discriminator. */\nexport function blockDelegationVerdict(rawReasonKind: string): DelegationVerdict {\n return { kind: 'Block', reason: { kind: toCoarseReasonKind(rawReasonKind) } };\n}\n","/**\n * JAFAR feed parser (TypeScript prep-side — AIVF-1).\n *\n * Single-shape parser for the IETF draft `draft-illyes-webbotauth-jafar`.\n * All 14 vendor endpoints catalogued in `AI-Vendor-IP-Feeds-1.md` §2\n * conform to the same JSON shape; differences are purely whitespace +\n * timestamp format. The Rust engine-side counterpart lands later when\n * Bench-Before-After-1 §3.8 unblocks.\n *\n * Out of scope here: CIDR membership semantics, IP arithmetic, vendor\n * cross-match. Engine consumes the parsed prefixes; this layer only\n * validates the wire shape.\n *\n * Empirical 2026-05-17 across all 14 fixtures:\n * - `creationTime`: 2 of 14 emit RFC 3339 with `Z` (Anthropic, CCBot);\n * the other 12 emit Python `datetime.isoformat()` output with\n * microsecond precision and no offset (e.g.\n * `2026-05-15T14:45:52.000000`). JavaScript's Date constructor\n * interprets ISO-like strings without offset as local time per\n * ES2019+; the parser explicitly appends `Z` when no offset is\n * present so naive Python output is treated as UTC.\n * - `prefixes`: every entry has exactly one of `ipv4Prefix` or\n * `ipv6Prefix`; never both, never neither.\n * - Top-level extension fields: CCBot's feed carries `synctoken`\n * and `notes` in addition to the two JAFAR-spec fields. The\n * top-level schema therefore uses `passthrough()` so vendor\n * extensions don't trip Postel's Law; the typed surface exposes\n * `synctoken` and `notes` since they're useful provenance for\n * the daily-refresh cron (synctoken can short-circuit no-op\n * refreshes; notes can land in the auto-PR body). Per-prefix\n * entries stay strict — no vendor adds extras there today.\n */\n\nimport { z } from 'zod';\n\nconst IPV4_CIDR_RE =\n /^(?:(?: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)$/;\n\n// Relaxed IPv6 address recogniser. Strict semantic validation (canonical\n// form, zero-compression rules) is engine-side.\nconst IPV6_CIDR_RE = /^[0-9a-fA-F:]+\\/(?:12[0-8]|1[01]\\d|\\d{1,2})$/;\n\nconst HAS_OFFSET_RE = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\nconst creationTimeSchema = z\n .string()\n .min(1)\n .transform((raw, ctx) => {\n const normalized = HAS_OFFSET_RE.test(raw) ? raw : `${raw}Z`;\n const ms = Date.parse(normalized);\n if (Number.isNaN(ms)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `creationTime is not a parseable ISO 8601 timestamp: ${raw}`,\n });\n return z.NEVER;\n }\n return new Date(ms);\n });\n\nconst prefixSchema = z\n .object({\n ipv4Prefix: z.string().regex(IPV4_CIDR_RE).optional(),\n ipv6Prefix: z.string().regex(IPV6_CIDR_RE).optional(),\n })\n .strict()\n .refine((p) => (p.ipv4Prefix != null) !== (p.ipv6Prefix != null), {\n message: 'prefix entry must have exactly one of ipv4Prefix or ipv6Prefix',\n });\n\nconst jafarFeedSchema = z\n .object({\n creationTime: creationTimeSchema,\n prefixes: z.array(prefixSchema),\n synctoken: z.string().optional(),\n notes: z.string().optional(),\n })\n .passthrough();\n\nexport type JafarPrefix = {\n ipv4Prefix?: string;\n ipv6Prefix?: string;\n};\n\nexport type JafarFeed = {\n creationTime: Date;\n prefixes: JafarPrefix[];\n synctoken?: string;\n notes?: string;\n};\n\nexport class JafarParseError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown\n ) {\n super(message);\n this.name = 'JafarParseError';\n }\n}\n\n/**\n * Parse a JAFAR-format feed payload.\n *\n * Throws `JafarParseError` on malformed JSON or schema violation. The\n * thrown error's `cause` carries the underlying `SyntaxError` (JSON\n * parse) or `ZodError` (schema mismatch) so callers can drill in when\n * needed without leaking framework types in the happy path.\n */\nexport function parseJafarFeed(json: string): JafarFeed {\n let raw: unknown;\n try {\n raw = JSON.parse(json);\n } catch (err) {\n throw new JafarParseError('JAFAR feed is not valid JSON', err);\n }\n\n const result = jafarFeedSchema.safeParse(raw);\n if (!result.success) {\n throw new JafarParseError(\n `JAFAR feed failed schema validation: ${result.error.message}`,\n result.error\n );\n }\n return result.data;\n}\n","import { z } from 'zod';\n\n/** I1 additive wire records. Parsing does not establish authority or reviewer trust. */\nconst Id = z\n .string()\n .min(1)\n .max(256)\n .regex(/^[\\x21-\\x7e]+$/);\nconst Count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst Revision = Count.positive();\nconst ContentDigest = z\n .string()\n .length(64)\n .regex(/^[a-f0-9]{64}$/);\nconst RecordDigest = z\n .string()\n .length(71)\n .regex(/^sha256:[a-f0-9]{64}$/);\nconst AcceptanceId = z\n .string()\n .length(68)\n .regex(/^acc:[a-f0-9]{64}$/);\nconst GitObjectId = z\n .string()\n .regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)\n .refine((v) => v.length === 40 || v.length === 64);\nconst Kind = z.enum([\n 'workspace_snapshot',\n 'commit',\n 'pull_request',\n 'test_report',\n 'package',\n 'document',\n]);\nexport const ImmutableArtifactLocatorSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('local_snapshot'), digest: ContentDigest }).strict(),\n z.object({ type: z.literal('git_commit'), objectId: GitObjectId }).strict(),\n z\n .object({\n type: z.literal('pull_request_head'),\n repositoryId: Id,\n number: Revision,\n headObjectId: GitObjectId,\n })\n .strict(),\n z.object({ type: z.literal('content_blob'), digest: ContentDigest }).strict(),\n]);\nexport const ArtifactIdentitySchema = z\n .object({\n kind: Kind,\n repositoryId: Id,\n baseCommit: GitObjectId,\n contentDigest: ContentDigest,\n locator: ImmutableArtifactLocatorSchema,\n })\n .strict()\n .superRefine((v, ctx) => {\n const expected = {\n workspace_snapshot: 'local_snapshot',\n commit: 'git_commit',\n pull_request: 'pull_request_head',\n test_report: 'content_blob',\n package: 'content_blob',\n document: 'content_blob',\n }[v.kind];\n if (v.locator.type !== expected)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Artifact kind and locator disagree' });\n if (\n (v.locator.type === 'local_snapshot' || v.locator.type === 'content_blob') &&\n v.locator.digest !== v.contentDigest\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Locator does not identify content' });\n if (v.locator.type === 'pull_request_head' && v.locator.repositoryId !== v.repositoryId)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Pull request repository mismatch' });\n });\nexport const AcceptedArtifactRevisionSchema = z\n .object({\n schemaVersion: z.literal(1),\n acceptanceId: AcceptanceId,\n taskId: Id,\n specRevision: Revision,\n manifestDigest: RecordDigest,\n trackGeneration: Revision.nullable(),\n artifact: ArtifactIdentitySchema,\n reviewDigest: RecordDigest,\n reviewer: Id,\n acceptedAtMs: Count,\n supersedes: AcceptanceId.nullable(),\n })\n .strict()\n .refine((v) => v.supersedes !== v.acceptanceId, 'Acceptance cannot supersede itself');\nexport const AcceptanceWithdrawalSchema = z\n .object({\n schemaVersion: z.literal(1),\n acceptanceId: AcceptanceId,\n reason: z.string().min(1).max(4096),\n triggerTaskId: Id,\n withdrawnBy: Id,\n withdrawnAtMs: Count,\n })\n .strict();\nexport const ConsumedArtifactSchema = z\n .object({\n prerequisiteTaskId: Id,\n prerequisiteSpecRevision: Revision,\n requirement: z.enum(['accepted_patch', 'merged']),\n acceptanceId: AcceptanceId,\n repositoryId: Id,\n kind: Kind,\n contentDigest: ContentDigest,\n mergedCommit: GitObjectId.nullable(),\n })\n .strict()\n .refine(\n (v) => (v.requirement === 'merged') === (v.mergedCommit !== null),\n 'Merge evidence is required exactly for merged prerequisites'\n );\nexport const DependencyBindingSchema = z\n .object({\n schemaVersion: z.literal(1),\n bindingId: z\n .string()\n .length(69)\n .regex(/^bind:[a-f0-9]{64}$/),\n dependentTaskId: Id,\n dependentSpecRevision: Revision,\n trackId: Id,\n trackGeneration: Revision,\n consumed: z.array(ConsumedArtifactSchema).min(1).max(2000),\n materializationPlanDigest: RecordDigest,\n })\n .strict()\n .superRefine((v, ctx) => {\n let previous: string[] | undefined;\n for (const row of v.consumed) {\n const slot = [row.prerequisiteTaskId, row.repositoryId, row.kind];\n const order = previous && compareSlot(previous, slot);\n if (order !== undefined && order >= 0)\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Consumed artifact slots must be unique and sorted',\n });\n if (row.prerequisiteTaskId === v.dependentTaskId)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Self dependency' });\n previous = slot;\n }\n });\nfunction compareSlot(a: string[], b: string[]): number {\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n return 0;\n}\n/**\n * Why a binding no longer matches the graph and acceptance ledger (D2). A stale\n * binding is reviewed and replaced, never silently rebound.\n */\nexport const StaleReasonSchema = z\n .discriminatedUnion('type', [\n z.object({ type: z.literal('track_mismatch'), bindingTrackId: Id, trackId: Id }).strict(),\n z.object({ type: z.literal('dependent_removed') }).strict(),\n z\n .object({ type: z.literal('dependent_revision_changed'), from: Revision, to: Revision })\n .strict(),\n z.object({ type: z.literal('edge_added'), prerequisiteTaskId: Id }).strict(),\n z.object({ type: z.literal('edge_removed'), prerequisiteTaskId: Id }).strict(),\n z\n .object({\n type: z.literal('prerequisite_revision_changed'),\n taskId: Id,\n from: Revision,\n to: Revision,\n })\n .strict(),\n z.object({ type: z.literal('requirement_changed'), prerequisiteTaskId: Id }).strict(),\n z.object({ type: z.literal('acceptance_withdrawn'), acceptanceId: AcceptanceId }).strict(),\n z\n .object({\n type: z.literal('acceptance_superseded'),\n acceptanceId: AcceptanceId,\n by: AcceptanceId,\n })\n .strict(),\n z.object({ type: z.literal('acceptance_unknown'), acceptanceId: AcceptanceId }).strict(),\n z.object({ type: z.literal('acceptance_mismatch'), acceptanceId: AcceptanceId }).strict(),\n ])\n .superRefine((v, ctx) => {\n const unchanged =\n (v.type === 'track_mismatch' && v.bindingTrackId === v.trackId) ||\n ((v.type === 'dependent_revision_changed' || v.type === 'prerequisite_revision_changed') &&\n v.from === v.to) ||\n (v.type === 'acceptance_superseded' && v.acceptanceId === v.by);\n if (unchanged)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'A stale reason must name a change' });\n });\n/** One to 2000 distinct reasons. */\nexport const StaleReasonsSchema = z\n .array(StaleReasonSchema)\n .min(1)\n .max(2000)\n .refine(\n (reasons) => new Set(reasons.map(canonical)).size === reasons.length,\n 'Duplicate stale reason'\n );\nexport const BindingStatusSchema = z.discriminatedUnion('state', [\n z.object({ state: z.literal('current') }).strict(),\n z.object({ state: z.literal('stale'), reasons: StaleReasonsSchema }).strict(),\n]);\nexport type StaleReason = z.infer<typeof StaleReasonSchema>;\nexport type BindingStatus = z.infer<typeof BindingStatusSchema>;\nexport type AcceptedArtifactRevision = z.infer<typeof AcceptedArtifactRevisionSchema>;\nexport type AcceptanceWithdrawal = z.infer<typeof AcceptanceWithdrawalSchema>;\nexport type DependencyBinding = z.infer<typeof DependencyBindingSchema>;\n\n// All admitted numbers are safe integers. UTF-16 key sorting and JSON.stringify\n// implement the applicable RFC8785 domain without a Node-only hashing dependency.\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';\n if (value !== null && typeof value === 'object') {\n const object = value as Record<string, unknown>;\n return (\n '{' +\n Object.keys(object)\n .sort()\n .map((k) => JSON.stringify(k) + ':' + canonical(object[k]))\n .join(',') +\n '}'\n );\n }\n const result = JSON.stringify(value);\n if (result === undefined) throw new Error('Unsupported canonical value');\n return result;\n}\n/** Lowercase SHA-256 hex of the value's canonical (RFC8785) form. */\nexport async function contractDigest(value: unknown): Promise<string> {\n const hash = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(canonical(value))\n );\n return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');\n}\nexport async function verifyContractRecordIdentity(\n record: Record<string, unknown>,\n field: string,\n prefix: string\n): Promise<void> {\n const body = { ...record };\n delete body[field];\n if (record[field] !== prefix + (await contractDigest(body)))\n throw new Error('Record identity does not match canonical content');\n}\n/** Use this boundary before storing/admitting a record; shape validation alone is insufficient. */\nexport async function parseAcceptedArtifactRevision(\n input: unknown\n): Promise<AcceptedArtifactRevision> {\n const value = AcceptedArtifactRevisionSchema.parse(input);\n await verifyContractRecordIdentity(value, 'acceptanceId', 'acc:');\n return value;\n}\nexport async function parseDependencyBinding(input: unknown): Promise<DependencyBinding> {\n const value = DependencyBindingSchema.parse(input);\n await verifyContractRecordIdentity(value, 'bindingId', 'bind:');\n return value;\n}\n","import { z } from 'zod';\nimport {\n contractDigest,\n ImmutableArtifactLocatorSchema,\n StaleReasonsSchema,\n verifyContractRecordIdentity,\n} from './artifact-bindings';\nconst Id = z\n .string()\n .min(1)\n .max(256)\n .regex(/^[\\x21-\\x7e]+$/);\nconst Count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst Revision = Count.positive();\nconst Digest = z\n .string()\n .length(64)\n .regex(/^[a-f0-9]{64}$/);\nconst RecordDigest = z\n .string()\n .length(71)\n .regex(/^sha256:[a-f0-9]{64}$/);\nconst AcceptanceId = z\n .string()\n .length(68)\n .regex(/^acc:[a-f0-9]{64}$/);\nconst GitObject = z\n .string()\n .regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)\n .refine((v) => v.length === 40 || v.length === 64);\nconst Text = z.string().min(1).max(4096);\n// Claims remain inert until a separately authorized resolver handles them.\nconst ClaimUri = Text.refine((uri) => {\n const unsafe = [...uri].some((character) => {\n const code = character.charCodeAt(0);\n return code <= 32 || code === 127 || character === '\\\\';\n });\n if (unsafe || uri.startsWith('//')) return false;\n try {\n const parsed = new URL(uri);\n return (\n ['https:', 'http:'].includes(parsed.protocol) &&\n !!parsed.hostname &&\n !parsed.username &&\n !parsed.password\n );\n } catch {\n return !uri.includes(':');\n }\n}, 'Evidence must be an HTTP(S) or inert relative reference');\nconst Path = z\n .string()\n .min(1)\n .max(4096)\n .refine(\n (v) =>\n !v.includes('\\\\') &&\n !v.includes(':') &&\n !v.split('/').some((p) => !p || p === '.' || p === '..' || p.toLowerCase() === '.git') &&\n [...v].every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127),\n 'Unsafe materialization path'\n );\nconst unique = <T>(items: T[]) => new Set(items).size === items.length;\n/** Unicode code point order, which is UTF-8 byte order and Rust `str` order. */\nfunction compareCodePoints(a: string, b: string): number {\n const left = Array.from(a, (c) => c.codePointAt(0) as number);\n const right = Array.from(b, (c) => c.codePointAt(0) as number);\n for (let i = 0; i < Math.min(left.length, right.length); i++)\n if (left[i] !== right[i]) return left[i] - right[i];\n return left.length - right.length;\n}\n/** Strictly ascending, so each path appears at most once. */\nconst canonicalPaths = (paths: string[]) =>\n paths.every((path, i) => i === 0 || compareCodePoints(paths[i - 1], path) < 0);\nconst Ids = z.array(Id).max(2000).refine(unique, 'Duplicate identity');\nexport const TrackDependencyV2Schema = z\n .object({\n prerequisiteTaskId: Id,\n dependentTaskId: Id,\n requirement: z.enum(['accepted_patch', 'merged']),\n origin: z.enum(['source', 'local_edit', 'decomposition', 'lead_proposal']),\n })\n .strict()\n .refine((v) => v.prerequisiteTaskId !== v.dependentTaskId, 'Self dependency');\nconst IssueId = z\n .string()\n .length(70)\n .regex(/^issue:[a-f0-9]{64}$/);\nexport const ImportIssueV2Schema = z\n .object({\n issueId: IssueId,\n taskId: Id.nullable(),\n code: Id,\n message: Text,\n origin: z.enum(['import_diagnostic', 'reviewer_question']),\n blocking: z.boolean(),\n })\n .strict();\nexport const MaterializationPlanSchema = z\n .object({\n schemaVersion: z.literal(1),\n repositoryId: Id,\n baseCommit: GitObject,\n order: z.array(AcceptanceId).min(1).max(2000).refine(unique, 'Duplicate acceptance'),\n entries: z\n .array(\n z\n .object({\n path: Path,\n sourceAcceptanceId: AcceptanceId,\n kind: z.enum(['file', 'executable', 'delete']),\n contentDigest: Digest.nullable(),\n })\n .strict()\n .refine(\n (v) => (v.kind === 'delete') === (v.contentDigest === null),\n 'Deletion must not name content'\n )\n )\n .max(10000),\n conflicts: z\n .array(\n z\n .object({\n path: Path,\n acceptanceIds: z.array(AcceptanceId).min(2).max(2000).refine(unique),\n reason: z.enum(['divergent_content', 'delete_modify', 'type_change']),\n })\n .strict()\n )\n .max(10000),\n planDigest: RecordDigest,\n })\n .strict()\n .superRefine((v, ctx) => {\n if (\n !canonicalPaths(v.entries.map((e) => e.path)) ||\n !canonicalPaths(v.conflicts.map((c) => c.path))\n )\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Planned entries and conflicts must be unique and in canonical path order',\n });\n const planned = new Set(v.entries.map((e) => e.path));\n if (v.conflicts.some((c) => planned.has(c.path)))\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'A path is either planned or in conflict, never both',\n });\n if (\n v.entries.some((e) => !v.order.includes(e.sourceAcceptanceId)) ||\n v.conflicts.some((c) => c.acceptanceIds.some((id) => !v.order.includes(id)))\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unknown source acceptance' });\n });\nexport const ReconciliationDecisionSetSchema = z\n .object({\n schemaVersion: z.literal(1),\n importId: Id,\n expectedGeneration: Revision,\n expectedDraftDigest: RecordDigest,\n conflicts: z\n .array(z.object({ conflictId: Id, choice: z.enum(['base', 'local', 'incoming']) }).strict())\n .max(2000),\n removals: z\n .array(\n z\n .object({ taskId: Id, decision: z.enum(['remove_from_track', 'retain_as_local']) })\n .strict()\n )\n .max(2000),\n issues: z\n .array(\n z\n .object({\n issueId: Id,\n action: z.discriminatedUnion('type', [\n z.object({ type: z.literal('keep') }).strict(),\n z.object({ type: z.literal('resolve'), note: Text }).strict(),\n ]),\n })\n .strict()\n )\n .max(2000),\n decidedBy: Id,\n decidedAtMs: Count,\n })\n .strict()\n .refine(\n (v) =>\n unique(v.conflicts.map((c) => c.conflictId)) &&\n unique(v.removals.map((r) => r.taskId)) &&\n unique(v.issues.map((i) => i.issueId)),\n 'Duplicate reconciliation decision'\n );\nexport const ClaimVerificationSchema = z\n .object({\n schemaVersion: z.literal(1),\n verificationId: z\n .string()\n .length(71)\n .regex(/^claimv:[a-f0-9]{64}$/),\n taskId: Id,\n specRevision: Revision,\n claim: z.object({ uri: ClaimUri, label: z.string().max(4096).nullable() }).strict(),\n subject: z\n .object({ repositoryId: Id, locator: ImmutableArtifactLocatorSchema })\n .strict()\n .nullable(),\n criteriaIds: Ids,\n checkReceiptIds: Ids,\n verdict: z.enum(['valid', 'invalid', 'indeterminate']),\n reasons: z.array(Text).max(2000),\n reviewer: Id.nullable(),\n reviewedAtMs: Count.nullable(),\n })\n .strict()\n .superRefine((v, ctx) => {\n if ((v.reviewer === null) !== (v.reviewedAtMs === null))\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Incomplete review attestation' });\n if (\n v.verdict === 'valid' &&\n (!v.subject || !v.criteriaIds.length || !v.checkReceiptIds.length || !v.reviewer)\n )\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Valid claims require pinned subject, criteria, checks and review',\n });\n if (\n v.subject?.locator.type === 'pull_request_head' &&\n v.subject.repositoryId !== v.subject.locator.repositoryId\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Claim repository mismatch' });\n });\nconst ChildState = z.discriminatedUnion('type', [\n z.object({ type: z.literal('accepted'), acceptanceId: AcceptanceId }).strict(),\n z.object({ type: z.literal('pending') }).strict(),\n z.object({ type: z.literal('blocked'), reasons: z.array(Text).min(1).max(2000) }).strict(),\n z.object({ type: z.literal('stale'), reasons: StaleReasonsSchema }).strict(),\n]);\nexport const ParentIntegrationStatusSchema = z\n .object({\n schemaVersion: z.literal(1),\n parentTaskId: Id,\n parentSpecRevision: Revision,\n children: z\n .array(z.object({ taskId: Id, repositoryId: Id, state: ChildState }).strict())\n .min(1)\n .max(2000),\n parentOnlyCriteria: z\n .array(z.object({ criterionId: Id, evidence: RecordDigest.nullable() }).strict())\n .max(2000),\n state: z.enum(['not_started', 'partial', 'awaiting_integration', 'satisfied', 'stale']),\n })\n .strict()\n .superRefine((v, ctx) => {\n if (\n !unique(v.children.map((c) => c.taskId)) ||\n !unique(v.parentOnlyCriteria.map((c) => c.criterionId)) ||\n v.children.some((c) => c.taskId === v.parentTaskId)\n )\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid integration identities' });\n const accepted = v.children.filter((c) => c.state.type === 'accepted').length;\n const expected = v.children.some((c) => c.state.type === 'stale')\n ? 'stale'\n : accepted === v.children.length\n ? v.parentOnlyCriteria.every((c) => c.evidence !== null)\n ? 'satisfied'\n : 'awaiting_integration'\n : accepted\n ? 'partial'\n : 'not_started';\n if (v.state !== expected)\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Integration state contradicts evidence',\n });\n });\nexport type TrackDependencyV2 = z.infer<typeof TrackDependencyV2Schema>;\nexport type ImportIssueV2 = z.infer<typeof ImportIssueV2Schema>;\nexport type MaterializationPlan = z.infer<typeof MaterializationPlanSchema>;\nexport type ReconciliationDecisionSet = z.infer<typeof ReconciliationDecisionSetSchema>;\nexport type ClaimVerification = z.infer<typeof ClaimVerificationSchema>;\nexport type ParentIntegrationStatus = z.infer<typeof ParentIntegrationStatusSchema>;\nexport async function parseMaterializationPlan(input: unknown): Promise<MaterializationPlan> {\n const value = MaterializationPlanSchema.parse(input);\n await verifyContractRecordIdentity(value, 'planDigest', 'sha256:');\n return value;\n}\n/** D7: `issue:` + SHA-256 of the canonical `{origin, taskId, code, message}`. */\nexport async function deriveImportIssueId(\n issue: Pick<ImportIssueV2, 'origin' | 'taskId' | 'code' | 'message'>\n): Promise<string> {\n const { origin, taskId, code, message } = issue;\n return 'issue:' + (await contractDigest({ origin, taskId, code, message }));\n}\n/** D7: `conf:` + SHA-256 of the canonical `{taskId, field, base, local, incoming}`. */\nexport async function deriveConflictId(conflict: {\n taskId: string | null;\n field: string;\n base: unknown;\n local: unknown;\n incoming: unknown;\n}): Promise<string> {\n const { taskId, field, base, local, incoming } = conflict;\n return 'conf:' + (await contractDigest({ taskId, field, base, local, incoming }));\n}\n/** Shape plus content identity; use before trusting an issue ID. */\nexport async function parseImportIssueV2(input: unknown): Promise<ImportIssueV2> {\n const value = ImportIssueV2Schema.parse(input);\n if (value.issueId !== (await deriveImportIssueId(value)))\n throw new Error('Record identity does not match canonical content');\n return value;\n}\nexport async function parseClaimVerification(input: unknown): Promise<ClaimVerification> {\n const value = ClaimVerificationSchema.parse(input);\n await verifyContractRecordIdentity(value, 'verificationId', 'claimv:');\n return value;\n}\n\n/** Reviewed claim-resolution mapping; it confers no repository access. HTTPS is the v1 transport profile. */\nexport const RepositoryIdentitySchema = z\n .object({\n schemaVersion: z.literal(1),\n repositoryId: Id,\n remote: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => {\n try {\n const url = new URL(value);\n return (\n url.protocol === 'https:' &&\n !url.username &&\n !url.password &&\n !url.search &&\n !url.hash &&\n // An empty query or fragment leaves search and hash empty but is\n // still part of the remote; Rust refuses both.\n !/[?#]/.test(value) &&\n url.pathname.split('/').filter(Boolean).length >= 2 &&\n url.href === value\n );\n } catch {\n return false;\n }\n }, 'Expected a canonical credential-free HTTPS repository remote'),\n })\n .strict();\nexport type RepositoryIdentity = z.infer<typeof RepositoryIdentitySchema>;\n","import { z } from 'zod';\nimport { LinearInstallationWorkflowSchema } from './task-ingress';\n\nexport const LinearInstallationProviderStatusSchema = z.enum(['connected', 'expired', 'revoked']);\nexport const LinearInstallationStatusReasonSchema = z.enum([\n 'uninstalled',\n 'refresh_rejected',\n 'token_rejected',\n 'reinstall_required',\n]);\n/** Provider identity and credentials are obtained by the server-side OAuth callback. */\nexport const StartLinearInstallationSchema = z\n .object({\n projectId: z.string().uuid(),\n enabled: z.boolean().default(true),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict();\n/** Additive replacement. C2 switches the route and retires the legacy configure body atomically. */\nexport const ConfigureLinearInstallationV2Schema = StartLinearInstallationSchema.extend({\n installationId: z.string().uuid(),\n}).strict();\nexport const LinearInstallationAuthorizationSchema = z\n .object({\n authorizationUrl: z\n .string()\n .max(8192)\n .url()\n .refine((value) => {\n try {\n const url = new URL(value);\n const required = [\n 'client_id',\n 'redirect_uri',\n 'response_type',\n 'scope',\n 'state',\n 'actor',\n 'code_challenge',\n 'code_challenge_method',\n ];\n return (\n url.origin === 'https://linear.app' &&\n url.pathname === '/oauth/authorize' &&\n !url.username &&\n !url.password &&\n !url.hash &&\n required.every(\n (key) =>\n url.searchParams.getAll(key).length === 1 && Boolean(url.searchParams.get(key))\n ) &&\n url.searchParams.get('response_type') === 'code' &&\n url.searchParams.get('actor') === 'app' &&\n url.searchParams.get('code_challenge_method') === 'S256'\n );\n } catch {\n return false;\n }\n }, 'Expected the managed Linear app authorization with state and S256'),\n expiresAt: z.string().datetime(),\n })\n .strict();\n/** Token-free owner/admin projection. This record is not a workload credential. */\nexport const LinearInstallationStatusSchema = z\n .object({\n installationId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n provider: z.literal('linear'),\n workspaceId: z.string().min(1).max(255),\n appUserId: z.string().min(1).max(255),\n enabled: z.boolean(),\n providerStatus: LinearInstallationProviderStatusSchema,\n providerStatusReason: LinearInstallationStatusReasonSchema.nullable(),\n providerStatusChangedAt: z.string().datetime().nullable(),\n providerAuthenticatedAt: z.string().datetime().nullable(),\n accessTokenExpiresAt: z.string().datetime().nullable(),\n admissible: z.boolean(),\n workflow: LinearInstallationWorkflowSchema,\n })\n .strict()\n .refine(\n (v) => v.admissible === (v.enabled && v.providerStatus === 'connected'),\n 'Admissibility contradicts installation policy and lifecycle'\n );\nexport type StartLinearInstallation = z.infer<typeof StartLinearInstallationSchema>;\nexport type ConfigureLinearInstallationV2 = z.infer<typeof ConfigureLinearInstallationV2Schema>;\nexport type LinearInstallationAuthorization = z.infer<typeof LinearInstallationAuthorizationSchema>;\nexport type LinearInstallationStatus = z.infer<typeof LinearInstallationStatusSchema>;\n","import { z } from 'zod';\nimport { PostureOriginsSchema } from '../types/posture-origins-schema';\n\n/**\n * C3: a human management session for the KYA-OS CLI, distinct from project API keys, workload\n * proofs and the gateway's delegation tokens. Browser (loopback) and device pairing both bind\n * PKCE S256; access tokens are short-lived and refresh tokens rotate. Workloads never accept it.\n */\nexport const MANAGEMENT_CLIENT_ID = 'kya-os-cli';\nexport const MANAGEMENT_AUDIENCE = 'urn:kya-os:checkpoint:management';\nexport const MANAGEMENT_ACCESS_PREFIX = 'kyam_';\nexport const MANAGEMENT_REFRESH_PREFIX = 'kyamr_';\n/** Seconds between device polls; `slow_down` adds 5 (RFC 8628 §3.5). */\nexport const MANAGEMENT_DEVICE_INTERVAL = 5;\n/** User codes avoid vowels and look-alike characters (RFC 8628 §6.1). */\nexport const MANAGEMENT_USER_CODE_ALPHABET = 'BCDFGHJKLMNPQRSTVWXZ';\n\nexport const ManagementScopeSchema = z.enum(['workbench.read', 'workbench.manage']);\nexport type ManagementScope = z.infer<typeof ManagementScopeSchema>;\n\nconst Base64Url43 = z\n .string()\n .length(43)\n .regex(/^[A-Za-z0-9_-]{43}$/);\nconst Verifier = z\n .string()\n .min(43)\n .max(128)\n .regex(/^[A-Za-z0-9._~-]+$/);\nconst Opaque = (prefix: string) =>\n z\n .string()\n .length(prefix.length + 43)\n .regex(new RegExp(`^${prefix}[A-Za-z0-9_-]{43}$`));\nexport const ManagementAccessTokenSchema = Opaque(MANAGEMENT_ACCESS_PREFIX);\nexport const ManagementRefreshTokenSchema = Opaque(MANAGEMENT_REFRESH_PREFIX);\nconst Timestamp = z.string().datetime();\nconst UserCode = z.string().regex(/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/);\n/** Space-separated, as in OAuth requests; at least one known scope, each once. */\nexport const ManagementScopeRequestSchema = z\n .string()\n .max(128)\n .transform((value, ctx) => {\n const scopes = value.split(' ').filter(Boolean);\n const parsed = z.array(ManagementScopeSchema).min(1).safeParse(scopes);\n if (!parsed.success || new Set(scopes).size !== scopes.length) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'invalid scope' });\n return z.NEVER;\n }\n return parsed.data;\n });\n\n/** RFC 8252 loopback redirect: exact path, any port, never a hostname that could resolve. */\nexport const ManagementLoopbackRedirectSchema = z\n .string()\n .max(64)\n .regex(/^http:\\/\\/(127\\.0\\.0\\.1|\\[::1\\]):([1-9][0-9]{0,4})\\/callback$/)\n .refine((value) => {\n const port = Number(/:(\\d+)\\/callback$/.exec(value)?.[1]);\n return port >= 1024 && port <= 65535;\n }, 'Loopback port must be 1024-65535');\n\nexport const ManagementPrincipalSchema = z\n .object({\n userId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectIds: z.array(z.string().uuid()).min(1).max(50),\n })\n .strict()\n .refine((value) => new Set(value.projectIds).size === value.projectIds.length, {\n message: 'Each project appears once',\n });\n\n/**\n * A name the CLI proposes for a project the user creates at consent, usually the repository's.\n * Printable ASCII with no space at either end, so the CLI can check it the same way.\n */\nexport const ManagementProjectNameSchema = z\n .string()\n .min(1)\n .max(100)\n .regex(/^[\\x21-\\x7E]([\\x20-\\x7E]*[\\x21-\\x7E])?$/);\n\n/** Query of `GET /cli/management/authorize`, validated before the consent page renders. */\nexport const ManagementAuthorizeQuerySchema = z\n .object({\n response_type: z.literal('code'),\n client_id: z.literal(MANAGEMENT_CLIENT_ID),\n redirect_uri: ManagementLoopbackRedirectSchema,\n code_challenge: Base64Url43,\n code_challenge_method: z.literal('S256'),\n state: z.string().min(22).max(512),\n resource: z.string().url().max(256),\n scope: ManagementScopeRequestSchema,\n project_hint: z.string().uuid().optional(),\n /** Prefills the consent page's new-project name; the grant itself never depends on it. */\n project_name: ManagementProjectNameSchema.optional(),\n })\n .strict();\n\n/** `POST /api/cli/management/device`. */\nexport const ManagementDeviceRequestSchema = z\n .object({\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n codeChallenge: Base64Url43,\n codeChallengeMethod: z.literal('S256'),\n scope: ManagementScopeRequestSchema,\n resource: z.string().url().max(256),\n projectHint: z.string().uuid().optional(),\n /** Prefills the consent page's new-project name, as `project_name` does for the browser. */\n projectName: ManagementProjectNameSchema.optional(),\n })\n .strict();\nexport const ManagementDeviceResponseSchema = z\n .object({\n deviceCode: Base64Url43,\n userCode: UserCode,\n verificationUri: z.string().url(),\n verificationUriComplete: z.string().url(),\n expiresAt: Timestamp,\n interval: z.number().int().min(MANAGEMENT_DEVICE_INTERVAL).max(60),\n })\n .strict();\n\n/** `POST /api/cli/management/token`. */\nexport const ManagementTokenRequestSchema = z.discriminatedUnion('grantType', [\n z\n .object({\n grantType: z.literal('authorization_code'),\n code: Base64Url43,\n codeVerifier: Verifier,\n redirectUri: ManagementLoopbackRedirectSchema,\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n })\n .strict(),\n z\n .object({\n grantType: z.literal('device_code'),\n deviceCode: Base64Url43,\n codeVerifier: Verifier,\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n })\n .strict(),\n z\n .object({\n grantType: z.literal('refresh_token'),\n refreshToken: ManagementRefreshTokenSchema,\n clientId: z.literal(MANAGEMENT_CLIENT_ID),\n })\n .strict(),\n]);\nexport const ManagementTokenResponseSchema = z\n .object({\n accessToken: ManagementAccessTokenSchema,\n tokenType: z.literal('Bearer'),\n expiresAt: Timestamp,\n refreshToken: ManagementRefreshTokenSchema,\n refreshExpiresAt: Timestamp,\n scope: z.array(ManagementScopeSchema).min(1).max(2),\n audience: z.literal(MANAGEMENT_AUDIENCE),\n issuer: z.string().url(),\n principal: ManagementPrincipalSchema,\n sessionId: z.string().uuid(),\n })\n .strict();\n\n/** `POST /api/cli/management/revoke`: a Bearer access token, or this body once it expired. */\nexport const ManagementRevokeRequestSchema = z\n .object({ refreshToken: ManagementRefreshTokenSchema })\n .strict();\n\n/** `GET /api/cli/management/session`. */\nexport const ManagementSessionSchema = z\n .object({\n sessionId: z.string().uuid(),\n principal: ManagementPrincipalSchema,\n scope: z.array(ManagementScopeSchema).min(1).max(2),\n audience: z.literal(MANAGEMENT_AUDIENCE),\n issuer: z.string().url(),\n createdAt: Timestamp,\n expiresAt: Timestamp,\n refreshExpiresAt: Timestamp,\n })\n .strict();\n\n/** `GET /api/cli/management/projects`: only the session's projects. */\nexport const ManagementProjectsSchema = z\n .object({\n organizationId: z.string().uuid(),\n projects: z\n .array(z.object({ id: z.string().uuid(), name: z.string().min(1).max(255) }).strict())\n .max(50),\n })\n .strict();\n\n/**\n * `GET /api/cli/management/profile`: who the session belongs to, by name, so `kya-os whoami`\n * can show names next to the principal's IDs. The CLI ignores fields it does not know here\n * (unlike the session and projects responses), so this may grow without breaking it.\n */\nexport const ManagementProfileSchema = z\n .object({\n userId: z.string().uuid(),\n email: z.string().min(1).max(255).optional(),\n name: z.string().min(1).max(255).optional(),\n organizationId: z.string().uuid(),\n organizationName: z.string().min(1).max(255).optional(),\n })\n .strict();\n\n/**\n * What an app's runtime key is for, which fixes its permissions: `sdk` reads (detection,\n * enforcement, policy fetches); `mcp` also writes (server registration, proofs, sessions,\n * events).\n */\nexport const ManagementRuntimeKeyPurposeSchema = z.enum(['sdk', 'mcp', 'proxy']);\n\n/**\n * `POST /api/cli/management/projects/{projectId}/runtime-keys`. `label` names where the key\n * will live (a host and repository), so each machine's key can be told apart and revoked alone.\n */\nexport const ManagementRuntimeKeyRequestSchema = z\n .object({\n purpose: ManagementRuntimeKeyPurposeSchema,\n label: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[\\x20-\\x7E]+$/),\n })\n .strict();\n\n/** A minted project runtime key. `key` is returned once, here, and never again. */\nexport const ManagementRuntimeKeySchema = z\n .object({\n keyId: z.string().uuid(),\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n key: z.string().regex(/^sk_[0-9a-f]{64}$/),\n preview: z.string().min(1).max(20),\n permissions: z\n .array(z.enum(['read', 'write', 'forward']))\n .min(1)\n .max(2),\n createdAt: Timestamp,\n })\n .strict();\n\nexport const ManagementPostureJwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n x: z.string(),\n y: z.string(),\n kid: z.string().min(1),\n alg: z.literal('ES256'),\n use: z.literal('sig'),\n })\n .strict();\n\nexport const ManagementPostureSchema = z\n .object({\n enabled: z.literal(true),\n keyId: z.string().min(1),\n publicJwk: ManagementPostureJwkSchema,\n primaryOrigin: z.string().nullable(),\n origins: z.array(z.string()),\n keysUrl: z.string().url(),\n })\n .strict();\n\nexport const ManagementPostureOriginsRequestSchema = z\n .object({ origins: PostureOriginsSchema })\n .strict();\n\nexport const ManagementErrorCodeSchema = z.enum([\n 'invalid_request',\n 'invalid_client',\n 'invalid_grant',\n 'invalid_target',\n 'access_denied',\n 'expired_token',\n 'authorization_pending',\n 'slow_down',\n 'invalid_token',\n 'insufficient_scope',\n 'temporarily_unavailable',\n // 429 from the per-client limiter; honour Retry-After.\n 'rate_limit_exceeded',\n]);\nexport const ManagementErrorReasonSchema = z.enum(['management_issuer_unconfigured']);\nexport const ManagementErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: ManagementErrorCodeSchema,\n message: z.string().min(1).max(256),\n reason: ManagementErrorReasonSchema.optional(),\n })\n .strict(),\n })\n .strict();\n\n/**\n * A resource route's own refusal (grants, delegations, tasks), distinct from the session codes\n * above: an uppercase domain code at its real HTTP status, for example 409 GRANT_EXCEEDS_POLICY.\n */\nexport const ManagementDomainErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: z.string().regex(/^[A-Z][A-Z0-9_]{2,63}$/),\n message: z.string().min(1).max(256),\n })\n .strict(),\n })\n .strict();\n\n/**\n * Browser consent posts, same-origin behind the signed-in session. Approval names one\n * organization and its projects; denial needs no choice, so it carries only the request.\n */\nconst ConsentChoice = {\n decision: z.literal('approve'),\n organizationId: z.string().uuid(),\n projectIds: z.array(z.string().uuid()).min(1).max(50),\n};\nconst ConsentFlow = {\n authorization_code: {\n flow: z.literal('authorization_code'),\n query: ManagementAuthorizeQuerySchema,\n },\n device: { flow: z.literal('device'), userCode: z.string().min(8).max(16) },\n};\nexport const ManagementConsentSchema = z.union([\n z.object({ ...ConsentFlow.authorization_code, ...ConsentChoice }).strict(),\n z.object({ ...ConsentFlow.authorization_code, decision: z.literal('deny') }).strict(),\n z.object({ ...ConsentFlow.device, ...ConsentChoice }).strict(),\n z.object({ ...ConsentFlow.device, decision: z.literal('deny') }).strict(),\n]);\n\n/** The consent pickers list at most this many organizations, and projects per organization. */\nexport const MANAGEMENT_CONSENT_MAX_ORGANIZATIONS = 100;\nexport const MANAGEMENT_CONSENT_MAX_PROJECTS = 500;\n\n/** What the signed-in user may grant: live organizations, their role, and live projects. */\nexport const ManagementConsentContextSchema = z\n .object({\n organizations: z\n .array(\n z\n .object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255),\n role: z.enum(['owner', 'admin', 'member']),\n projects: z\n .array(z.object({ id: z.string().uuid(), name: z.string().min(1).max(255) }).strict())\n .max(MANAGEMENT_CONSENT_MAX_PROJECTS),\n /** More live projects exist than are listed; the hinted project is always listed. */\n projectsTruncated: z.boolean(),\n })\n .strict()\n )\n .max(MANAGEMENT_CONSENT_MAX_ORGANIZATIONS),\n organizationsTruncated: z.boolean(),\n })\n .strict();\n/** A pending device request, as shown to the user deciding it. */\nexport const ManagementDeviceDescriptionSchema = z\n .object({\n scope: z.array(ManagementScopeSchema).min(1).max(2),\n projectHint: z.string().uuid().nullable(),\n projectName: ManagementProjectNameSchema.nullable(),\n expiresAt: z.string().datetime(),\n })\n .strict();\n\nexport type ManagementPrincipal = z.infer<typeof ManagementPrincipalSchema>;\nexport type ManagementAuthorizeQuery = z.infer<typeof ManagementAuthorizeQuerySchema>;\nexport type ManagementDeviceRequest = z.infer<typeof ManagementDeviceRequestSchema>;\nexport type ManagementDeviceResponse = z.infer<typeof ManagementDeviceResponseSchema>;\nexport type ManagementTokenRequest = z.infer<typeof ManagementTokenRequestSchema>;\nexport type ManagementTokenResponse = z.infer<typeof ManagementTokenResponseSchema>;\nexport type ManagementSession = z.infer<typeof ManagementSessionSchema>;\nexport type ManagementProjects = z.infer<typeof ManagementProjectsSchema>;\nexport type ManagementProfile = z.infer<typeof ManagementProfileSchema>;\nexport type ManagementRuntimeKeyPurpose = z.infer<typeof ManagementRuntimeKeyPurposeSchema>;\nexport type ManagementRuntimeKeyRequest = z.infer<typeof ManagementRuntimeKeyRequestSchema>;\nexport type ManagementRuntimeKey = z.infer<typeof ManagementRuntimeKeySchema>;\nexport type ManagementPosture = z.infer<typeof ManagementPostureSchema>;\nexport type ManagementPostureOriginsRequest = z.infer<typeof ManagementPostureOriginsRequestSchema>;\nexport type ManagementErrorCode = z.infer<typeof ManagementErrorCodeSchema>;\nexport type ManagementErrorReason = z.infer<typeof ManagementErrorReasonSchema>;\nexport type ManagementDomainError = z.infer<typeof ManagementDomainErrorSchema>;\nexport type ManagementConsent = z.infer<typeof ManagementConsentSchema>;\n/** What the browser posts: the authorize query still carries its raw scope string. */\nexport type ManagementConsentInput = z.input<typeof ManagementConsentSchema>;\nexport type ManagementConsentContext = z.infer<typeof ManagementConsentContextSchema>;\nexport type ManagementDeviceDescription = z.infer<typeof ManagementDeviceDescriptionSchema>;\n","import { z } from 'zod';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport {\n TaskStandingAdmissionRequestBaseSchema,\n TaskStandingAdmissionReceiptBaseSchema,\n TaskStandingCapabilitySchema,\n validModelAdmission,\n} from './task-ingress';\n\n/**\n * C11: protocol grants for standing work. A grant binds one runner key (never a human) to exact\n * actions, one repository, one lead and optionally exact arguments, under one installation\n * policy revision. Grants form a revocable chain up to a root an owner or admin issued. Every\n * admission reserves against the whole chain in one PostgreSQL transaction, so siblings share\n * their ancestors' allowances. A grant is never edited: renewal or new limits issue a\n * replacement, and admitted operations keep the grant they were admitted under.\n */\n\n/** Operation-admission protocols this server speaks, oldest first. Negotiate before use. */\nexport const TASK_ADMISSION_PROTOCOLS = ['kya.task.admission.v1', 'kya.task.admission.v2'] as const;\nexport const TaskAdmissionProtocolSchema = z.enum(TASK_ADMISSION_PROTOCOLS);\nexport type TaskAdmissionProtocol = z.infer<typeof TaskAdmissionProtocolSchema>;\n\n/** `GET /api/v1/task-mailbox/protocol`: public, tenant-free. */\n/**\n * Advertised by a deployment that answers an identical admission resend (same project, source,\n * execution operation and body, from the lead it recorded) by the admission it created, before\n * any current-policy check. Against such a deployment a 4xx on an identical resend proves the\n * original never committed. Absent from older deployments, where it proves nothing.\n */\nexport const TASK_ADMISSION_RESEND = 'kya.task.admission-resend.v1' as const;\nexport const TaskMailboxProtocolSchema = z\n .object({\n admissionProtocols: z.array(TaskAdmissionProtocolSchema).min(1),\n grantStatus: z.literal('kya.task.grant-status.v1'),\n admissionResend: z.literal(TASK_ADMISSION_RESEND).optional(),\n })\n .strict();\nexport type TaskMailboxProtocol = z.infer<typeof TaskMailboxProtocolSchema>;\n\nconst KeyDid = z.string().startsWith('did:key:').max(512);\nconst Sha256Digest = z.string().regex(/^sha256:[a-f0-9]{64}$/);\n/** Lowercase so a binding compares exactly; admission lowercases the repository it reserves. */\nconst GrantRepository = z\n .string()\n .max(255)\n .regex(/^[a-z0-9_.-]+\\/[a-z0-9_.-]+$/);\nconst GrantActions = z\n .array(TaskStandingCapabilitySchema)\n .min(1)\n .max(4)\n .refine(\n (values) => values.every((value, index) => index === 0 || values[index - 1] < value),\n 'Actions are unique and sorted'\n );\n\n/** What an admission must match exactly. */\nexport const TaskGrantBindingSchema = z\n .object({\n holderDid: KeyDid,\n actions: GrantActions,\n repository: GrantRepository,\n leadDid: KeyDid,\n /** `null` binds any arguments within the repository; otherwise exactly one argument set. */\n argumentsDigest: Sha256Digest.nullable(),\n policyRevision: z.number().int().positive(),\n })\n .strict();\nexport type TaskGrantBinding = z.infer<typeof TaskGrantBindingSchema>;\n\n/** The arguments an admission's digest covers. */\nexport const TaskGrantArgumentsSchema = z\n .object({\n taskId: z.string().uuid(),\n sourceRevision: z.number().int().positive(),\n specRevision: z.number().int().positive(),\n manifestDigest: Sha256Digest,\n repository: GrantRepository,\n baseSha: z.string().regex(/^[a-f0-9]{40}$/),\n })\n .strict();\nexport type TaskGrantArguments = z.infer<typeof TaskGrantArgumentsSchema>;\n\n/**\n * RFC 8785 (JCS) for a flat object of strings and safe integers: members sorted by UTF-16 code\n * units, each serialized as `JSON.stringify` does, which is what JCS specifies for them. Local\n * because `canonicalize` is ESM-only and this module ships in the CJS root barrel.\n */\nfunction canonicalFlat(value: Readonly<Record<string, string | number>>): string {\n const members = Object.keys(value)\n .sort()\n .map((key) => {\n const item = value[key];\n if (typeof item !== 'string' && !Number.isSafeInteger(item))\n throw new TypeError(`Cannot canonicalize ${key}: only strings and safe integers`);\n return `${JSON.stringify(key)}:${JSON.stringify(item)}`;\n });\n return `{${members.join(',')}}`;\n}\n\n/** `sha256:` over the RFC 8785 (JCS) form of the arguments. */\nexport function taskGrantArgumentsDigest(input: TaskGrantArguments): string {\n const args = TaskGrantArgumentsSchema.parse(input);\n return `sha256:${bytesToHex(sha256(new TextEncoder().encode(canonicalFlat(args))))}`;\n}\n\n/** Shared by the grant and every descendant: each admission reserves against all of them. */\nexport const TaskGrantAllowanceSchema = z\n .object({\n maxOperations: z.number().int().min(1).max(10000),\n maxCostMicrousd: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n maxConcurrentOperations: z.number().int().min(1).max(100),\n })\n .strict();\nexport type TaskGrantAllowance = z.infer<typeof TaskGrantAllowanceSchema>;\n\n/** Nearest parent first, root last. A chain is at most eight grants deep. */\nexport const MAX_TASK_GRANT_DEPTH = 8;\n\nexport const TaskGrantSchema = z\n .object({\n schema: z.literal('kya.task.grant.v1'),\n grantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n projectId: z.string().uuid(),\n installationId: z.string().uuid(),\n parentGrantId: z.string().uuid().nullable(),\n replacesGrantId: z.string().uuid().nullable(),\n ancestors: z.array(z.string().uuid()).max(MAX_TASK_GRANT_DEPTH - 1),\n binding: TaskGrantBindingSchema,\n allowance: TaskGrantAllowanceSchema,\n notBefore: z.string().datetime(),\n expiresAt: z.string().datetime(),\n issuedByUserId: z.string().uuid(),\n issuedAt: z.string().datetime(),\n })\n .strict()\n .refine((grant) => grant.ancestors[0] === (grant.parentGrantId ?? undefined), {\n message: 'The nearest ancestor is the parent',\n })\n .refine((grant) => grant.notBefore < grant.expiresAt, { message: 'Validity is not empty' });\nexport type TaskGrant = z.infer<typeof TaskGrantSchema>;\n\nexport const TaskGrantStatusValueSchema = z.enum(['active', 'revoked', 'expired', 'replaced']);\n/** Why a grant cannot admit now; `active` only when it and every ancestor can. */\nexport const TaskGrantEffectiveStatusSchema = z.enum([\n 'active',\n 'not_yet_valid',\n 'revoked',\n 'expired',\n 'replaced',\n 'ancestor_inactive',\n]);\n\n/**\n * Recorded revocation, the server's first enforcement of it and already-admitted effects are\n * reported separately. A revoked in-flight effect stays recorded and charged; nothing here says\n * it was undone, and no notification is the authority gate.\n */\nexport const TaskGrantStatusSchema = z\n .object({\n schema: z.literal('kya.task.grant-status.v1'),\n grantId: z.string().uuid(),\n status: TaskGrantStatusValueSchema,\n effectiveStatus: TaskGrantEffectiveStatusSchema,\n revokedAt: z.string().datetime().nullable(),\n revocationReason: z.string().max(500).nullable(),\n replacedByGrantId: z.string().uuid().nullable(),\n /** First time the server refused an admission or action because this grant is inactive. */\n enforcementObservedAt: z.string().datetime().nullable(),\n admitted: z\n .object({\n operations: z.number().int().nonnegative(),\n inFlight: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n reservedCostMicrousd: z.string().regex(/^\\d+$/),\n })\n .strict(),\n observedAt: z.string().datetime(),\n })\n .strict();\nexport type TaskGrantStatus = z.infer<typeof TaskGrantStatusSchema>;\n\n/** Mailbox `grant-status`: the holder, the lead, or an ancestor's holder may read it. */\nexport const TaskGrantStatusRequestSchema = z\n .object({ ownerEpoch: z.number().int().positive(), grantId: z.string().uuid() })\n .strict();\n\n/** Admission under a grant. v1 requests stay byte-identical and never carry a grant. */\nexport const TaskGrantAdmissionRequestSchema = TaskStandingAdmissionRequestBaseSchema.extend({\n protocolVersion: z.literal('kya.task.admission.v2'),\n grant: z.object({ grantId: z.string().uuid(), binding: TaskGrantBindingSchema }).strict(),\n})\n .strict()\n .refine(validModelAdmission, 'Model capability requires a bounded policy');\nexport type TaskGrantAdmissionRequest = z.infer<typeof TaskGrantAdmissionRequestSchema>;\n\n/** The v2 receipt: the v1 receipt plus the exact chain the admission reserved against. */\nexport const TaskGrantAdmissionSchema = TaskStandingAdmissionReceiptBaseSchema.extend({\n schema: z.literal('kya.task.admission.v2'),\n grant: z\n .object({\n grantId: z.string().uuid(),\n ancestors: z.array(z.string().uuid()).max(MAX_TASK_GRANT_DEPTH - 1),\n binding: TaskGrantBindingSchema,\n })\n .strict(),\n})\n .strict()\n .refine(validModelAdmission, 'Model capability requires a bounded policy');\nexport type TaskGrantAdmission = z.infer<typeof TaskGrantAdmissionSchema>;\n\n/** Management: issue a root or child grant. `operationId` makes a retried issue idempotent. */\nexport const IssueTaskGrantSchema = z\n .object({\n operationId: z.string().uuid(),\n installationId: z.string().uuid(),\n parentGrantId: z.string().uuid().nullable(),\n binding: TaskGrantBindingSchema,\n allowance: TaskGrantAllowanceSchema,\n notBefore: z.string().datetime().optional(),\n expiresAt: z.string().datetime(),\n })\n .strict();\nexport type IssueTaskGrant = z.infer<typeof IssueTaskGrantSchema>;\n\n/** Management: renew or change limits. The binding stays, at the current policy revision. */\nexport const ReplaceTaskGrantSchema = z\n .object({\n operationId: z.string().uuid(),\n allowance: TaskGrantAllowanceSchema,\n notBefore: z.string().datetime().optional(),\n expiresAt: z.string().datetime(),\n })\n .strict();\nexport type ReplaceTaskGrant = z.infer<typeof ReplaceTaskGrantSchema>;\n\nexport const RevokeTaskGrantSchema = z\n .object({ reason: z.string().trim().min(1).max(500) })\n .strict();\n\nexport const TaskGrantViewSchema = z\n .object({ grant: TaskGrantSchema, status: TaskGrantStatusSchema })\n .strict();\nexport const TaskGrantListSchema = z\n .object({ grants: z.array(TaskGrantViewSchema).max(200) })\n .strict();\nexport type TaskGrantView = z.infer<typeof TaskGrantViewSchema>;\n\n/** Issue and replace: a retried `operationId` with the same body returns the same grant. */\nexport const TaskGrantIssueResultSchema = z\n .object({ grant: TaskGrantSchema, status: TaskGrantStatusSchema, duplicate: z.boolean() })\n .strict();\nexport type TaskGrantIssueResult = z.infer<typeof TaskGrantIssueResultSchema>;\n\n/** Revocation is recorded at commit; it never reports admitted effects as undone. */\nexport const TaskGrantRevocationSchema = z\n .object({\n grant: TaskGrantSchema,\n status: TaskGrantStatusSchema,\n wasAlreadyRevoked: z.boolean(),\n })\n .strict();\nexport type TaskGrantRevocation = z.infer<typeof TaskGrantRevocationSchema>;\n\n/** A grant may not outlive this many days from `notBefore`; renewal issues a replacement. */\nexport const MAX_TASK_GRANT_DAYS = 90;\n\n/** Mailbox `grants`: the grants a runner may present, as their holder or their lead. */\nexport const TaskGrantHolderListRequestSchema = z\n .object({ ownerEpoch: z.number().int().positive() })\n .strict();\n","import { z } from 'zod';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\n/**\n * C10: reviewed identity provisioning and workload enrollment, behind the C3 management session.\n * A read never provisions, mints or probes. Each fact the project identity view reports keeps its\n * own evidence: configured (a stored record), observed (an explicit probe, when it ran),\n * authoritative (the registry's current record, when last read), history (verified by the CLI's\n * identity sidecar, never claimed by the server) and receiving authorization (an explicit link).\n */\n\nconst Timestamp = z.string().datetime();\nconst Uuid = z.string().uuid();\nconst KeyDid = z.string().startsWith('did:key:').max(512);\nconst PublicUrl = z\n .string()\n .url()\n .max(2048)\n .refine((value) => {\n const url = new URL(value);\n return (\n ['https:', 'http:'].includes(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.search &&\n !url.hash\n );\n }, 'A public URL has no credentials, query or fragment');\nconst Code = z.string().regex(/^[A-Z][A-Z0-9_]{2,63}$/);\n\n/** The last explicit observation of a subject; `not_observed` until someone ran one. */\nexport const IdentityObservationSchema = z\n .object({\n state: z.enum(['healthy', 'unhealthy', 'unavailable', 'not_observed']),\n observedAt: Timestamp.nullable(),\n })\n .strict();\n\nexport const RegistryAuthorityStateSchema = z.enum([\n // The registry's current record names the recorded DID, is active, and its current key is\n // the organization's signing key.\n 'matches',\n 'differs',\n 'deactivated',\n 'not_found',\n 'unavailable',\n 'not_observed',\n]);\n\nexport const ProjectIdentitySchema = z\n .object({\n schema: z.literal('kya.identity.project.v1'),\n organizationId: Uuid,\n projectId: Uuid,\n readAt: Timestamp,\n signingIdentity: z\n .object({\n /** A key exists in Checkpoint's encrypted custody. The key itself never leaves it. */\n configured: z.boolean(),\n didWeb: z.string().startsWith('did:web:').max(512).nullable(),\n })\n .strict(),\n registry: z\n .object({\n /** This deployment can register organizations. */\n configured: z.boolean(),\n recorded: z\n .object({\n did: z.string().startsWith('did:webvh:').max(512),\n entityId: z.string().min(1).max(64),\n multikey: z.string().min(1).max(128),\n })\n .strict()\n .nullable(),\n authoritative: z\n .object({\n state: RegistryAuthorityStateSchema,\n observedAt: Timestamp.nullable(),\n currentGeneration: z.number().int().positive().nullable(),\n })\n .strict(),\n /** Signed history is verified by the CLI identity sidecar; the server never claims it. */\n history: z\n .object({\n verifiedByServer: z.literal(false),\n logUrl: PublicUrl.nullable(),\n })\n .strict(),\n })\n .strict(),\n services: z\n .array(\n z\n .object({\n id: z.string().min(1).max(255),\n kind: z.enum(['authorization_host', 'mcp']),\n url: PublicUrl.nullable(),\n configured: z.boolean(),\n /** A probe Checkpoint ran; MCP deployments are never probed, only self-reported. */\n observed: IdentityObservationSchema,\n selfReportedAt: Timestamp.nullable(),\n receiving: z\n .object({\n state: z.enum(['authorized', 'not_linked', 'not_applicable']),\n linkedAt: Timestamp.nullable(),\n })\n .strict(),\n })\n .strict()\n )\n .max(102),\n })\n .strict();\nexport type ProjectIdentity = z.infer<typeof ProjectIdentitySchema>;\n\n/**\n * `create` a signing identity in encrypted custody; `register` the organization's did:webvh root\n * with that key; `repair` a registration whose response was lost (only from a verified registry\n * read whose current key is the organization's key; never a re-mint); `link` a recorded MCP\n * deployment as authorized to receive for this organization.\n */\nexport const IdentityIntentActionSchema = z.enum(['create', 'register', 'repair', 'link']);\nexport type IdentityIntentAction = z.infer<typeof IdentityIntentActionSchema>;\n\n/** `POST …/identity/intents`: a review; nothing changes until it is applied. */\nexport const IdentityIntentRequestSchema = z.discriminatedUnion('action', [\n z.object({ operationId: Uuid, action: z.literal('create') }).strict(),\n z.object({ operationId: Uuid, action: z.literal('register') }).strict(),\n z.object({ operationId: Uuid, action: z.literal('repair') }).strict(),\n z.object({ operationId: Uuid, action: z.literal('link'), deploymentId: Uuid }).strict(),\n]);\nexport type IdentityIntentRequest = z.infer<typeof IdentityIntentRequestSchema>;\n\n/** Review and outcome text is read back in terminals and the dashboard. */\nconst Readable = (max: number) => z.string().max(max).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\nconst PublicMetadata = z.record(Readable(64), Readable(512));\n\nexport const IdentityIntentStateSchema = z.enum([\n 'reviewed',\n 'applying',\n 'succeeded',\n 'failed',\n // The external effect may or may not have happened; `repair` or a re-read resolves it.\n 'unknown',\n 'expired',\n]);\n\nexport const IdentityIntentSchema = z\n .object({\n schema: z.literal('kya.identity.intent.v1'),\n operationId: Uuid,\n organizationId: Uuid,\n projectId: Uuid,\n action: IdentityIntentActionSchema,\n deploymentId: Uuid.nullable(),\n state: IdentityIntentStateSchema,\n review: z\n .object({\n /** Plain-language effects the reviewer approves, in order. */\n effects: z.array(Readable(300).min(1)).min(1).max(8),\n /** Public metadata only: DIDs, entity IDs, URLs. Never key material. */\n publicMetadata: PublicMetadata,\n digest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n expiresAt: Timestamp,\n })\n .strict(),\n outcome: z\n .object({\n code: Code,\n publicMetadata: PublicMetadata,\n /** True when a later `repair` or a retried apply can settle it. */\n recoverable: z.boolean(),\n })\n .strict()\n .nullable(),\n requestedByUserId: Uuid,\n requestedAt: Timestamp,\n appliedByUserId: Uuid.nullable(),\n completedAt: Timestamp.nullable(),\n })\n .strict()\n // Only a link names a deployment. A link whose deployment was deleted since names none;\n // its review and outcome still record which deployment it was.\n .refine((intent) => intent.action === 'link' || intent.deploymentId === null, {\n message: 'Only a link intent names a deployment',\n path: ['deploymentId'],\n });\nexport type IdentityIntent = z.infer<typeof IdentityIntentSchema>;\n\n/** `POST …/identity/intents/{operationId}/apply`: the reviewer's approval of exactly that review. */\nexport const ApplyIdentityIntentSchema = z\n .object({ reviewDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/) })\n .strict();\n\n// Workload enrollment (B05): a runner's own key, bound to one host and runner in one project.\n\n/** `POST …/enrollments/challenge`: a single-use nonce the holder key must sign. */\nexport const WorkloadEnrollmentChallengeSchema = z\n .object({\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n audience: z.string().url().max(512),\n expiresAt: Timestamp,\n })\n .strict();\n\nconst HostId = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/);\nconst Signature = z.string().regex(/^[A-Za-z0-9_-]{86}$/);\n\n/**\n * What an enrollment proof signs: the JCS form of this object, Ed25519 by the holder key, base64url.\n * Rotation signs `kya.workload.enrollment-rotation.v1` with both the old and the new key.\n */\nexport const WorkloadEnrollmentProofPayloadSchema = z\n .object({\n schema: z.literal('kya.workload.enrollment-proof.v1'),\n audience: z.string().url().max(512),\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n organizationId: Uuid,\n projectId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n holderDid: KeyDid,\n })\n .strict();\nexport const WorkloadRotationProofPayloadSchema = z\n .object({\n schema: z.literal('kya.workload.enrollment-rotation.v1'),\n audience: z.string().url().max(512),\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n enrollmentId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n oldHolderDid: KeyDid,\n newHolderDid: KeyDid,\n })\n .strict();\n\nexport const EnrollWorkloadSchema = z\n .object({\n operationId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n holderDid: KeyDid,\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n proof: Signature,\n /** When the owner's approval lapses; at most 180 days, default 90. */\n approvalExpiresAt: Timestamp.optional(),\n })\n .strict();\n\nexport const RotateWorkloadEnrollmentSchema = z\n .object({\n operationId: Uuid,\n newHolderDid: KeyDid,\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),\n oldProof: Signature,\n newProof: Signature,\n })\n .strict();\n\nexport const RevokeWorkloadEnrollmentSchema = z\n .object({ reason: z.string().trim().min(1).max(500) })\n .strict();\n\n/**\n * Approval, credential and renewal times are separate: the owner's approval can outlive many\n * credential periods, and renewal opens before the credential expires. A retiring enrollment\n * still identifies attempts admitted under it; it enrolls nothing new.\n */\nexport const WorkloadEnrollmentSchema = z\n .object({\n schema: z.literal('kya.workload.enrollment.v1'),\n enrollmentId: Uuid,\n operationId: Uuid,\n organizationId: Uuid,\n projectId: Uuid,\n hostId: HostId,\n runnerId: HostId,\n holderDid: KeyDid,\n status: z.enum(['active', 'retiring', 'retired', 'revoked']),\n approvedByUserId: Uuid,\n approvedAt: Timestamp,\n approvalExpiresAt: Timestamp,\n credentialExpiresAt: Timestamp,\n renewalWindowStartsAt: Timestamp,\n replacesEnrollmentId: Uuid.nullable(),\n replacedByEnrollmentId: Uuid.nullable(),\n retiresAt: Timestamp.nullable(),\n revokedAt: Timestamp.nullable(),\n revokedByUserId: Uuid.nullable(),\n revocationReason: z.string().max(500).nullable(),\n })\n .strict();\nexport type WorkloadEnrollment = z.infer<typeof WorkloadEnrollmentSchema>;\n\n/** `POST …/enrollments/{id}/revoke`: a repeated revoke returns the recorded revocation. */\nexport const WorkloadEnrollmentRevocationSchema = z\n .object({ enrollment: WorkloadEnrollmentSchema, wasAlreadyRevoked: z.boolean() })\n .strict();\n\nexport const WorkloadEnrollmentResultSchema = z\n .object({ enrollment: WorkloadEnrollmentSchema, duplicate: z.boolean() })\n .strict();\nexport const WorkloadEnrollmentListSchema = z\n .object({ enrollments: z.array(WorkloadEnrollmentSchema).max(200) })\n .strict();\n","import { z } from 'zod';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\n/**\n * C11: human management of legacy delegations through a C3 management session. Reads need any\n * current role in the project; revocation needs a current owner or admin, rechecked when it\n * commits. Another organization's or project's delegation is indistinguishable from none.\n */\n\nconst Timestamp = z.string().datetime();\n\n/** A revocation reason is free text read back in terminals and the dashboard: readable text. */\nconst RevocationReason = z.string().max(500).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\n\n/** The stored lifecycle column. It is never flipped to `expired` by time alone. */\nexport const DelegationStoredStatusSchema = z.enum(['active', 'expired', 'revoked']);\nexport type DelegationStoredStatus = z.infer<typeof DelegationStoredStatusSchema>;\n\n/**\n * What verification would decide from the record alone at `evaluatedAt`: revocation first, then\n * expiry (`expiresAt` or the `notAfter` constraint), then the `notBefore` constraint.\n */\nexport const DelegationEffectiveStatusSchema = z.enum([\n 'active',\n 'not_yet_valid',\n 'expired',\n 'revoked',\n]);\nexport type DelegationEffectiveStatus = z.infer<typeof DelegationEffectiveStatusSchema>;\n\n/**\n * List filter over the effective status. `active` means neither revoked nor expired, so it also\n * lists delegations that are not yet valid.\n */\nexport const DelegationListStatusFilterSchema = z.enum(['active', 'revoked', 'expired', 'all']);\nexport type DelegationListStatusFilter = z.infer<typeof DelegationListStatusFilterSchema>;\n\n/** The bounds verification enforces. A stored bound of 0 means none, as in verification. */\nexport const DelegationConstraintSummarySchema = z\n .object({\n notBefore: Timestamp.nullable(),\n notAfter: Timestamp.nullable(),\n maxCalls: z.number().nullable(),\n })\n .strict();\nexport type DelegationConstraintSummary = z.infer<typeof DelegationConstraintSummarySchema>;\n\n/**\n * One delegation as its project's members see it. `usageCount` counts verifications accepted\n * against `maxCalls`; verification never counts uses of a delegation without a cap, so both\n * `usageCount` and `remainingCalls` are null there rather than a misleading 0.\n */\nexport const DelegationManagementItemSchema = z\n .object({\n delegationId: z.string().uuid(),\n agentDid: z.string().max(500),\n agentName: z.string().max(255).nullable(),\n userDid: z.string().max(500).nullable(),\n userIdentifier: z.string().max(500).nullable(),\n scopes: z.array(z.string().min(1)),\n constraints: DelegationConstraintSummarySchema,\n status: DelegationStoredStatusSchema,\n effectiveStatus: DelegationEffectiveStatusSchema,\n issuedAt: Timestamp,\n expiresAt: Timestamp.nullable(),\n revokedAt: Timestamp.nullable(),\n revocationReason: RevocationReason.nullable(),\n usageCount: z.number().int().nonnegative().nullable(),\n remainingCalls: z.number().int().nonnegative().nullable(),\n lastUsedAt: Timestamp.nullable(),\n })\n .strict();\nexport type DelegationManagementItem = z.infer<typeof DelegationManagementItemSchema>;\n\n/** `GET /api/cli/management/projects/{projectId}/delegations`: newest first. */\nexport const DelegationManagementListSchema = z\n .object({\n delegations: z.array(DelegationManagementItemSchema).max(200),\n /** Opaque; pass back as `?cursor=` for the next page. Null on the last page. */\n nextCursor: z.string().min(1).max(256).nullable(),\n /** The instant every `effectiveStatus` in this page was evaluated at. */\n evaluatedAt: Timestamp,\n })\n .strict();\nexport type DelegationManagementList = z.infer<typeof DelegationManagementListSchema>;\n\n/** Audit records that name this delegation, counted within its organization and project. */\nexport const DelegationAuditSourceSchema = z.enum([\n 'bouncer_proofs',\n 'gateway_tool_calls',\n 'usage_events',\n]);\nexport type DelegationAuditSource = z.infer<typeof DelegationAuditSourceSchema>;\nexport const DelegationAuditSummarySchema = z\n .object({\n source: DelegationAuditSourceSchema,\n count: z.number().int().nonnegative(),\n latestAt: Timestamp.nullable(),\n })\n .strict();\nexport type DelegationAuditSummary = z.infer<typeof DelegationAuditSummarySchema>;\n\n/**\n * Where Checkpoint handed the delegation's persisted bearer credential out: the verify response,\n * the dashboard list, gateway pickup polls, the JSON gateway consent approval, managed native\n * issuance and OpenClaw approvals. Freshly minted per-response tokens are separate credentials.\n */\nexport const DelegationExportChannelSchema = z.enum([\n 'verify_response',\n 'dashboard_list',\n 'gateway_pickup',\n 'gateway_consent',\n 'native_issuance',\n 'openclaw_approval',\n]);\nexport type DelegationExportChannel = z.infer<typeof DelegationExportChannelSchema>;\n\nexport const DelegationExportRecordSchema = z\n .object({\n channel: DelegationExportChannelSchema,\n firstExportedAt: Timestamp,\n lastExportedAt: Timestamp,\n /** Exports counted at most once a minute per credential, so a lower bound. */\n exportCount: z.number().int().positive(),\n })\n .strict();\nexport type DelegationExportRecord = z.infer<typeof DelegationExportRecordSchema>;\n\n/**\n * The compatibility export ledger's view of one delegation. It lists recorded exports only:\n * a ledger write that failed was logged, not retried, and credentials minted fresh for a\n * response (rather than read from the delegation record) are not exports of this credential.\n *\n * `historical` is `unknown` when the delegation was created before `ledgerStartedAt` (or this\n * environment has no ledger), because exports before then were never recorded; unknown is not\n * none. It is `none` only when the ledger covered the delegation's whole life, so `recorded` is\n * then every recorded channel. Revoking never retracts an export: `retractedByRevocation` is\n * always false, and whoever holds an exported credential still holds it.\n */\nexport const DelegationExposureSchema = z\n .object({\n ledgerStartedAt: Timestamp.nullable(),\n historical: z.enum(['unknown', 'none']),\n recorded: z\n .array(DelegationExportRecordSchema)\n .max(DelegationExportChannelSchema.options.length),\n retractedByRevocation: z.literal(false),\n })\n .strict();\nexport type DelegationExposure = z.infer<typeof DelegationExposureSchema>;\n\n/** `GET /api/cli/management/projects/{projectId}/delegations/{delegationId}`. */\nexport const DelegationManagementDetailSchema = DelegationManagementItemSchema.extend({\n audit: z.array(DelegationAuditSummarySchema).max(DelegationAuditSourceSchema.options.length),\n exposure: DelegationExposureSchema,\n}).strict();\nexport type DelegationManagementDetail = z.infer<typeof DelegationManagementDetailSchema>;\n\n/** `POST .../delegations/{delegationId}/revoke`. The reason is stored and shown to members. */\nexport const DelegationRevokeRequestSchema = z\n .object({ reason: z.string().trim().pipe(RevocationReason.min(1)) })\n .strict();\nexport type DelegationRevokeRequest = z.infer<typeof DelegationRevokeRequestSchema>;\n\n/**\n * The outcome of a human revocation. Revoking is idempotent: a delegation that was already\n * revoked answers `wasAlreadyRevoked: true` with its original `revokedAt`.\n *\n * `enforcement` names the only gate: Checkpoint verification. Every verification that consults\n * Checkpoint refuses the delegation once the revocation commits, whatever channel the credential\n * left through; `revokedAt` is when the revoking transaction began, at most moments earlier.\n * Exported bearer credentials are not retracted or deleted (see `exposure`), a verifier that\n * never consults Checkpoint is not stopped, and any status-list publication may lag. No\n * notification sent afterwards is part of the gate.\n *\n * `inFlight` is what the delegation had admitted when it was revoked: those uses may still be\n * completing downstream, and none is admitted after it. `admittedUses` is null for a delegation\n * without a call cap, whose uses verification never counts.\n */\nexport const DelegationRevokeResponseSchema = z\n .object({\n delegationId: z.string().uuid(),\n status: z.literal('revoked'),\n revokedAt: Timestamp,\n wasAlreadyRevoked: z.boolean(),\n inFlight: z\n .object({\n admittedUses: z.number().int().nonnegative().nullable(),\n lastUsedAt: Timestamp.nullable(),\n })\n .strict(),\n exposure: DelegationExposureSchema,\n enforcement: z.literal('checkpoint_verification'),\n })\n .strict();\nexport type DelegationRevokeResponse = z.infer<typeof DelegationRevokeResponseSchema>;\n","import { z } from 'zod';\n\n/** Why an item may not start. Frozen with Rust `ReadinessCode`: a new code is a contract change. */\nexport const TrackingReadinessReasonCodeSchema = z.enum([\n 'invalid_track',\n 'unknown_task',\n 'completion_claim_requires_verification',\n 'source_needs_reconciliation',\n 'not_queued',\n 'unapproved_revision',\n 'missing_acceptance_criteria',\n 'repositories_not_ready',\n 'authority_not_ready',\n 'external_blocker',\n 'blocking_issue_unresolved',\n 'dependency_artifact_invalid',\n 'dependency_artifact_ambiguous',\n 'dependency_artifact_missing',\n 'dependency_requires_merge',\n 'dependency_binding_missing',\n 'dependency_binding_stale',\n]);\nexport const TrackingReadinessSchema = z\n .object({\n startable: z.boolean(),\n reasons: z.array(\n z.object({ code: TrackingReadinessReasonCodeSchema, message: z.string() }).strict()\n ),\n })\n .strict();\n","import { z } from 'zod';\nimport { READABLE_TEXT, READABLE_TEXT_MESSAGE } from './readable-text';\n\nexport const CLI_PAIRING_PROTOCOL_VERSION = 2 as const;\nexport const CLI_PAIRING_UPGRADE_MESSAGE =\n 'Upgrade the KYA-OS CLI and run checkpoint init again. This pairing requires independent terminal proof.';\n\nexport const CliPairingProofSchema = z.string().regex(/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/);\nexport const CLI_PAIRING_FRAMEWORKS = ['nextjs', 'express', 'static', 'unknown'] as const;\nconst readable = z.string().max(255).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\nconst label = readable.min(1);\nconst hint = z.string().trim().min(1).max(255).regex(READABLE_TEXT, READABLE_TEXT_MESSAGE);\nconst uuid = z.string().uuid();\n\nexport const CliPairingRegisterRequestSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n exchangeChallenge: CliPairingProofSchema,\n domainHint: hint.optional(),\n repoName: hint.optional(),\n framework: z.enum(CLI_PAIRING_FRAMEWORKS).optional(),\n })\n .strict();\n\nexport const CliPairingApprovedClaimSchema = z\n .object({\n userId: uuid,\n organizationId: uuid,\n projectId: uuid,\n })\n .strict();\nexport const CliPairingClaimSchema = z\n .object({\n userId: uuid,\n userEmail: label,\n userName: readable.nullable(),\n organizationId: uuid,\n organizationName: label,\n organizationSlug: readable.nullable(),\n projectId: uuid,\n projectName: label,\n projectDomain: readable.nullable(),\n })\n .strict();\nexport const CliPairingExchangeRequestSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n registrationId: uuid,\n exchangeVerifier: CliPairingProofSchema,\n approvedClaim: CliPairingApprovedClaimSchema,\n })\n .strict();\n\nexport const CliPairingRegisterDataSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n registrationId: uuid,\n claimToken: z.string().regex(/^cliclaim_[a-f0-9]{64}$/),\n claimUrl: z.string().url(),\n confirmationCode: z.string().regex(/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/),\n expiresAt: z.string().datetime(),\n })\n .strict();\nexport const CliPairingPrivateStatusDataSchema = z.discriminatedUnion('status', [\n z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n status: z.literal('pending'),\n claimed: z.null(),\n })\n .strict(),\n z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n status: z.literal('claimed'),\n claimed: CliPairingClaimSchema,\n })\n .strict(),\n]);\nexport const CliPairingExchangeDataSchema = z\n .object({\n protocolVersion: z.literal(CLI_PAIRING_PROTOCOL_VERSION),\n userId: uuid,\n projectId: uuid,\n organizationId: uuid,\n friendlyId: z.string().nullable(),\n apiKey: z.string().regex(/^sk_[a-f0-9]{64}$/),\n dashboardUrl: z.string().url(),\n })\n .strict();\n\nexport type CliPairingClaim = z.infer<typeof CliPairingClaimSchema>;\nexport type CliPairingApprovedClaim = z.infer<typeof CliPairingApprovedClaimSchema>;\nexport type CliPairingExchangeRequest = z.infer<typeof CliPairingExchangeRequestSchema>;\nexport type CliPairingPrivateStatusData = z.infer<typeof CliPairingPrivateStatusDataSchema>;\n","/**\n * @kya-os/checkpoint-shared\n *\n * Shared types, schemas, and constants for Checkpoint\n * This is the single source of truth for all TypeScript types\n */\n\n// Core types\nexport * from './core/detection';\nexport * from './core/ruleset-hash';\nexport * from './core/enforcement';\nexport * from './core/agent';\nexport * from './core/confidence';\nexport * from './core/risk-score';\nexport * from './core/verdict-evidence';\nexport * from './core/detection-reason-codes';\nexport * from './core/detection-reason-code-schema';\nexport * from './core/detection-reason-mapping';\n\n// Configuration types\n\n// Constants\nexport * from './constants/agents';\nexport * from './agent-catalog';\nexport * from './constants/bots';\nexport * from './constants/delegation';\nexport * from './constants/errors';\nexport * from './constants/limits';\nexport * from './constants/patterns';\nexport * from './constants/rules';\n\n// API types\nexport * from './api/request';\nexport * from './api/response';\nexport * from './api/event';\nexport * from './api/task-ingress';\nexport * from './api/task-a2a';\nexport * from './api/cli-identity';\nexport * from './api/bulk';\nexport * from './api/internal';\nexport * from './api/signal-exposure';\nexport type * from './api/delegation-lifecycle';\n// Fingerprint analysis types\nexport {\n FingerprintAnalysisSchema,\n FingerprintResponseSchema,\n TLSFingerprintSchema,\n NetworkTimingSchema,\n} from './api/fingerprint';\n\nexport type {\n FingerprintAnalysis,\n FingerprintResponse,\n TLSFingerprint,\n NetworkTiming,\n} from './api/fingerprint';\n\n// Re-export specific types that might be missed by wildcard exports\nexport type { SuccessResponse, PaginatedResponse, ApiKeyWithProject } from './api/internal';\n\n// Organization and multi-user types\nexport * from './types/organization';\n\n// Shopify integration types\nexport * from './types/shopify';\nexport * from './types/posture-origins-schema';\nexport * from './types/posture-report-paths-schema';\n\n// Event types\nexport * from './events/agent-shield';\nexport * from './events/behavioral';\nexport * from './events/realtime';\nexport * from './events/deploy-progress';\n\n// All type definitions\nexport * from './types';\n\n// API route types\nexport type {\n NextRouteContext,\n OptionalNextRouteContext,\n RouteParamValue,\n RouteParams,\n RouteParamsFromContext,\n} from './types/api';\n\n// All constants\nexport * from './constants';\n\n// Utility functions\nexport * from './utils/verification';\nexport * from './utils/detection-class';\nexport * from './utils/agent-runtime-label';\nexport * from './utils/client-ip';\nexport * from './utils/bot-signals';\nexport * from './utils/zod-helpers';\nexport * from './utils/allowed-domains';\nexport * from './utils/bot-signals';\n\n// Isomorphic request correlation-id derivation (traceparent → x-kya-correlation-id →\n// fallback → minted UUID). One helper every detection surface uses so a request keeps a\n// single canonical 32-hex id across surfaces. Edge/Node/browser safe (globalThis.crypto).\nexport * from './utils/correlation-id';\n\n// All schemas (for runtime validation)\nexport * from './schemas';\n\n// Rule system exports - Types\nexport type {\n UserAgentRule,\n IpRangeRule,\n SignatureRule,\n BehavioralThreshold,\n BehavioralPattern,\n BehavioralRules,\n HeaderRule,\n HeaderRules,\n IpRangeCollection,\n DetectionRules,\n RuleLoadOptions,\n RuleValidationResult,\n} from './types/rules';\n\n// Rule system exports - Schemas (these export both schemas and types)\nexport {\n UserAgentRuleSchema,\n IpRangeRuleSchema,\n SignatureRuleSchema,\n BehavioralThresholdSchema,\n BehavioralPatternSchema,\n BehavioralRulesSchema,\n HeaderRuleSchema,\n HeaderRulesSchema,\n IpRangeCollectionSchema,\n DetectionRulesSchema,\n RuleValidationResultSchema,\n validateRules,\n validateRulesLoose,\n} from './schemas/rules';\n\n// Rule system exports - Constants\nexport * from './constants/rules';\n\n// Rule system exports - Classes and functions\nexport { RuleLoader, loadRulesAsync } from './rules/rule-loader';\nexport { RuleParser } from './rules/rule-parser';\nexport { RuleValidator } from './rules/rule-validator';\nexport {\n assertVendorRangesFresh,\n DEFAULT_MAX_VENDOR_RANGE_AGE_MS,\n findStaleVendorRanges,\n StaleVendorRangesError,\n type StaleVendorDetail,\n type VendorFreshnessInput,\n} from './rules/vendor-range-freshness';\n\n// Policy module (shared between middleware packages)\nexport * from './policy';\n\n// Host-adapter primitives (shared between framework wrappers — checkpoint-nextjs, checkpoint-express)\nexport * from './host-adapter';\n\n// Wire-contract Zod schemas for Vercel ↔ Fly boundaries (#2029).\n// Both the Fly gateway and the Vercel routes import + validate\n// through these schemas, so shape drift becomes a validation\n// error instead of a silent runtime bug.\nexport * from './wire';\n\n// Canonical KYA-OS signer (Sign-1 / #2500) -- value exports live ONLY at\n// the dedicated `@kya-os/checkpoint-shared/canonical-signer` subpath\n// (tsup.config.ts ships it as its own bundle entry precisely so barrel\n// consumers don't drag in `canonicalize`, an ESM-only package with no\n// `require` export condition -- pulling it into this CJS-built barrel\n// broke every tsx/CJS consumer, e.g. scripts/sync-agent-types.ts, with\n// ERR_PACKAGE_PATH_NOT_EXPORTED). `export *` here defeated that\n// isolation. Only `McpIPayload` (a type, erased at compile time) is\n// consumed through the bare barrel anywhere in the repo\n// (checkpoint-wasm-runtime/src/engine/types.ts); every value-level\n// consumer (bouncer-middleware) already imports the subpath directly.\nexport type { McpIPayload } from './canonical-signer';\n\n// KYA-OS org issuer DID derivation shared by credential issuers and verifiers.\nexport * from './mcpi/org-did';\n\n// KYA-OS user DID derivation under the org's DID tree, hashing ids that are not path segments.\nexport * from './mcpi/user-did';\n\n// KYA-OS delegation-proof request detection (P2 / DR-1) — the single header set\n// every verifier surface uses to gate org trusted-root resolution.\nexport * from './mcpi/delegation-headers';\n\n// Canonical principals + MCP client DID derivation (#3022).\nexport * from './mcpi/principal';\n\n// Reported-identity wire block — the M1 verifier→ingest contract for\n// KYA-OS-attested tool calls (agent identity taxonomy v2 §5.1). Reporter asserts\n// agent/principal/delegation; Checkpoint derives assurance.\nexport * from './mcpi/reported-identity';\n\n// Authorization Host resolution — draft-kya-http-02 §7 PEP config discovery (H1.1 #3244).\nexport * from './mcpi/authorization-host';\n\n// did:key (Ed25519 multikey) codec — pure-JS base58btc/0xed01 decode+encode for\n// RFC 9421 keyid pinning (draft-kya-http-02 / H1.2 #3245).\nexport * from './mcpi/did-key';\n\n// Tolerant + canonical publicKeyMultibase codec (z/m/u prefixes) for Ed25519\n// DID-document verification methods — the single decoder shared by\n// apps/gateway's mcp-i auth/approver resolvers and the gateway worker.\nexport * from './mcpi/multibase-ed25519';\n\n// KYA-HTTP error code registry (draft-kya-http-02 §9) — the kyaos/* wire\n// constants, parity-guarded against fixtures/kya-http/error-codes.json.\nexport * from './mcpi/kya-http-error-codes';\n\n// Common delegation-verdict shape (verifier/engine unification PR 1) — the\n// coarse kind+reason.kind both the delegation cross-runtime-parity track and\n// the gateway's engine shadow-verify (PR 5) normalize each runtime's result\n// onto.\nexport * from './mcpi/delegation-verdict';\n\n// JAFAR vendor-feed parser (AIVF-1 prep). TS-side counterpart to the\n// engine-side Rust parser that lands when Bench-Before-After-1 unblocks.\nexport * from './parsers/jafar';\n\n// Utility types\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type Nullable<T> = T | null;\n\nexport type Optional<T> = T | undefined;\n\nexport type AsyncResult<T, E = Error> = Promise<{ data: T } | { error: E }>;\n\n// Version info\nexport const VERSION = '0.1.0';\nexport const PACKAGE_NAME = '@kya-os/checkpoint-shared';\n\nexport * from './api/artifact-bindings';\nexport * from './api/graph-interfaces';\nexport * from './api/linear-installation';\nexport * from './api/task-status-projection';\nexport * from './api/management-session';\nexport * from './api/task-grant';\nexport * from './api/identity-provisioning';\nexport * from './api/model-credentials';\nexport * from './api/readable-text';\nexport * from './api/delegation-management';\nexport * from './api/tracking-readiness';\nexport * from './api/cli-registration';\nexport * from './default-sign-in-host';\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAa,eAAe;CACxB,cAAc;CACd,SAAS;CACT,WAAW;CACX,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,eAAe;CACf,aAAa;CACb,iBAAiB;CACjB,eAAe;CACf,QAAQ;AACZ;;AAaA,IAAW;AAER,0BAA0B,wBAAwB,CAAC;;;;ACzBtD,SAAgB,OAAO,QAAQ;CAC3B,OAAOA,eAAoBC,WAAmB,MAAM;AACxD;AACA,SAAgB,QAAQ,QAAQ;CAC5B,OAAOC,gBAAqBC,YAAoB,MAAM;AAC1D;AAIA,SAAgB,KAAK,QAAQ;CACzB,OAAOC,aAAkBC,SAAiB,MAAM;AACpD;;;;ACdA,MAAa,6BAA6BC,MAAO;CAC/C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,eAAeC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,YAAY;AAC7D,MAAM,aAAaA,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;;AAGlD,MAAa,uBAAuBC,OAC1B;CAEN,MAAMC,OAAS,CAAC,CAAC,IAAI,CAAC;CACtB,QAAQA,OAAS,C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