@7h3/protocol 0.5.0 → 0.5.2

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 (294) hide show
  1. package/README.md +6 -1317
  2. package/agentAdapter.d.ts +26 -0
  3. package/auditLog.d.ts +54 -0
  4. package/capability.d.ts +67 -0
  5. package/cborCodec.d.ts +34 -0
  6. package/conformanceVectors.d.ts +20 -0
  7. package/encryption.d.ts +85 -0
  8. package/envelopeCbor.d.ts +33 -0
  9. package/frameworkAdapters.d.ts +72 -0
  10. package/gateway.d.ts +53 -0
  11. package/grpcBinding.d.ts +29 -0
  12. package/httpBinding.d.ts +50 -0
  13. package/index.d.ts +39 -0
  14. package/index.js +3670 -0
  15. package/keyInfra.d.ts +64 -0
  16. package/keyRegistry.d.ts +9 -0
  17. package/keyRotation.d.ts +20 -0
  18. package/mcpGateway.d.ts +37 -0
  19. package/mcpTransports.d.ts +62 -0
  20. package/mcpWrapper.d.ts +83 -0
  21. package/otel.d.ts +65 -0
  22. package/package.json +13 -121
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/{src/protocol.d.ts → protocol.d.ts} +6 -2
  26. package/protocolAgent.d.ts +58 -0
  27. package/protocolBinary.d.ts +8 -0
  28. package/protocolCapabilities.d.ts +24 -0
  29. package/protocolReplay.d.ts +35 -0
  30. package/protocolTransport.d.ts +73 -0
  31. package/queueBinding.d.ts +43 -0
  32. package/rateLimiter.d.ts +18 -0
  33. package/{src/redisClient.ts → redisClient.d.ts} +25 -75
  34. package/replayStores.d.ts +98 -0
  35. package/revocation.d.ts +71 -0
  36. package/routePolicy.d.ts +30 -0
  37. package/runtimePolicy.d.ts +24 -0
  38. package/runtimePolicyManager.d.ts +15 -0
  39. package/runtimePolicyPresets.d.ts +11 -0
  40. package/signedResponse.d.ts +21 -0
  41. package/stream.d.ts +59 -0
  42. package/telemetry.d.ts +79 -0
  43. package/webhookBinding.d.ts +30 -0
  44. package/wsBinding.d.ts +52 -0
  45. package/.dockerignore +0 -19
  46. package/.github/dependabot.yml +0 -32
  47. package/.github/workflows/ci.yml +0 -31
  48. package/.github/workflows/publish.yml +0 -59
  49. package/.github/workflows/scorecard.yml +0 -37
  50. package/7h3.example.yaml +0 -125
  51. package/CHANGELOG.md +0 -152
  52. package/CONTRIBUTING.md +0 -82
  53. package/Dockerfile +0 -73
  54. package/GOVERNANCE.md +0 -62
  55. package/SECURITY.md +0 -70
  56. package/bench-results/replay-cache-full-1777891033256.json +0 -10
  57. package/bench-results/replay-cache-full-1777896317488.json +0 -10
  58. package/bench-results/replay-cache-full-1777900993184.json +0 -10
  59. package/bench-results/replay-cache-full-1777901019285.json +0 -10
  60. package/bench-results/replay-cache-quick-1777870170126.json +0 -10
  61. package/bench-results/signature-profiles-quick-1775875160079.json +0 -85
  62. package/bench-results/signature-profiles-quick-1775983539716.json +0 -85
  63. package/bench-results/signature-profiles-quick-1776237913190.json +0 -85
  64. package/bench-results/wire-codecs-full-1777891019803.json +0 -93
  65. package/bench-results/wire-codecs-full-1777896260964.json +0 -93
  66. package/bench-results/wire-codecs-full-1777901004247.json +0 -93
  67. package/bench-results/wire-codecs-quick-1775972879056.json +0 -93
  68. package/bench-results/wire-codecs-quick-1775983541111.json +0 -93
  69. package/bench-results/wire-codecs-quick-1776237914299.json +0 -93
  70. package/bench-results/wire-codecs-quick-1777841285236.json +0 -93
  71. package/bench-results/wire-codecs-quick-1777841321772.json +0 -93
  72. package/bench-results/wire-codecs-quick-1777841330408.json +0 -93
  73. package/bench-results/wire-codecs-quick-1777852886082.json +0 -93
  74. package/bench-results/wire-codecs-quick-1777852988773.json +0 -93
  75. package/bench-results/wire-codecs-quick-1777870188095.json +0 -93
  76. package/bench-results/wire-codecs-quick-1777870263918.json +0 -93
  77. package/bench-results/wire-codecs-quick-1777870455034.json +0 -93
  78. package/bench-results/wire-codecs-quick-1778816163081.json +0 -93
  79. package/bench-results/wire-codecs-quick-1778843936130.json +0 -93
  80. package/bin/7h3.ts +0 -406
  81. package/conformance/7h3_v0_1.json +0 -77
  82. package/conformance/7h3_v0_1_binary.json +0 -20
  83. package/conformance/aip_v0_1_binary.json +0 -20
  84. package/docker-compose.yaml +0 -77
  85. package/docs/ADOPTION_PLAN.md +0 -120
  86. package/docs/AGENTS.md +0 -77
  87. package/docs/AIP_RFC_v0.1.md +0 -97
  88. package/docs/AI_DECISION_CARD.md +0 -122
  89. package/docs/AI_RUNTIME_POLICY.json +0 -126
  90. package/docs/AI_RUNTIME_POLICY.yaml +0 -110
  91. package/docs/BACKPRESSURE_TUNING.md +0 -65
  92. package/docs/BENCHMARK_CLAIM_MATRIX.md +0 -42
  93. package/docs/BENCHMARK_REPORT_TEMPLATE.md +0 -169
  94. package/docs/BINARY_CODEC_BENCH.md +0 -23
  95. package/docs/CLEAN_CLONE_RUNBOOK.md +0 -36
  96. package/docs/CLOCK_SKEW_POLICY.md +0 -30
  97. package/docs/DISTRIBUTED_REPLAY.md +0 -142
  98. package/docs/FUZZ_CAMPAIGN.md +0 -121
  99. package/docs/GATEWAY.md +0 -195
  100. package/docs/KEY_MANAGEMENT_POLICY.md +0 -53
  101. package/docs/KEY_REVOCATION.md +0 -69
  102. package/docs/MCP_WRAPPER.md +0 -159
  103. package/docs/MIGRATION_GUIDE.md +0 -40
  104. package/docs/OPERATORS.md +0 -184
  105. package/docs/PERF_REGRESSION_POLICY.md +0 -34
  106. package/docs/PROJECT_EXAMINATION_2026-05-31.md +0 -219
  107. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +0 -135
  108. package/docs/RELEASE_GATE.md +0 -25
  109. package/docs/RELEASE_NOTES_v0.1.0.md +0 -54
  110. package/docs/SECURITY_REVIEW_2026-06-05.md +0 -165
  111. package/docs/TELEMETRY.md +0 -41
  112. package/docs/THREAT_MODEL.md +0 -89
  113. package/docs/VERSIONING_POLICY.md +0 -30
  114. package/docs/assets/banner-github.png +0 -0
  115. package/docs/assets/banner.png +0 -0
  116. package/docs/assets/banner.svg +0 -123
  117. package/eslint.config.js +0 -15
  118. package/fuzz/ts/harness-decode.ts +0 -136
  119. package/fuzz/ts/harness-verify.ts +0 -121
  120. package/fuzz/ts/run.ts +0 -35
  121. package/mcp-server/README.md +0 -38
  122. package/mcp-server/package-lock.json +0 -1187
  123. package/mcp-server/package.json +0 -35
  124. package/mcp-server/src/index.ts +0 -236
  125. package/mcp-server/tsconfig.json +0 -14
  126. package/scripts/aip-framework-quickstart.ts +0 -110
  127. package/scripts/aip-mcp-gateway.ts +0 -38
  128. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  129. package/scripts/aip-quickstart.ts +0 -60
  130. package/scripts/bench-diff.ts +0 -118
  131. package/scripts/bench-protocol-e2e.ts +0 -937
  132. package/scripts/bench-protocol-openloop.ts +0 -1397
  133. package/scripts/bench-replay-cache.ts +0 -76
  134. package/scripts/bench-signature-profiles.ts +0 -180
  135. package/scripts/bench-wire-codecs.ts +0 -161
  136. package/scripts/build-binary-conformance.ts +0 -36
  137. package/scripts/build-release-dashboard.ts +0 -175
  138. package/scripts/canary-rollout.ts +0 -38
  139. package/scripts/mcpGatewayCli.test.ts +0 -116
  140. package/scripts/prepare-aip-package.ts +0 -88
  141. package/scripts/regen-conformance-sigs.ts +0 -18
  142. package/scripts/release-gate.ts +0 -19
  143. package/scripts/validate-runtime-policy.ts +0 -18
  144. package/sdk/browser/index.test.ts +0 -162
  145. package/sdk/browser/index.ts +0 -257
  146. package/sdk/browser/package.json +0 -13
  147. package/sdk/go/cbor.go +0 -551
  148. package/sdk/go/cbor_test.go +0 -232
  149. package/sdk/go/encryption.go +0 -280
  150. package/sdk/go/encryption_test.go +0 -318
  151. package/sdk/go/go.mod +0 -7
  152. package/sdk/go/go.sum +0 -4
  153. package/sdk/go/http.go +0 -135
  154. package/sdk/go/protocol.go +0 -324
  155. package/sdk/go/protocol_test.go +0 -334
  156. package/sdk/go/replay.go +0 -121
  157. package/sdk/go/replay_test.go +0 -149
  158. package/sdk/go/webhook.go +0 -136
  159. package/sdk/pq/package-lock.json +0 -1358
  160. package/sdk/pq/package.json +0 -42
  161. package/sdk/pq/src/index.test.ts +0 -143
  162. package/sdk/pq/src/index.ts +0 -166
  163. package/sdk/pq/tsconfig.json +0 -14
  164. package/sdk/pq/vitest.config.ts +0 -7
  165. package/sdk/python/README.md +0 -18
  166. package/sdk/python/protocol_7h3/__init__.py +0 -46
  167. package/sdk/python/protocol_7h3/encryption.py +0 -252
  168. package/sdk/python/protocol_7h3/http.py +0 -212
  169. package/sdk/python/protocol_7h3/keys.py +0 -149
  170. package/sdk/python/protocol_7h3/pq.py +0 -244
  171. package/sdk/python/protocol_7h3/protocol.py +0 -525
  172. package/sdk/python/protocol_7h3/queue.py +0 -118
  173. package/sdk/python/protocol_7h3/replay.py +0 -98
  174. package/sdk/python/protocol_7h3/webhook.py +0 -116
  175. package/sdk/python/pyproject.toml +0 -40
  176. package/sdk/python/tests/test_conformance.py +0 -110
  177. package/sdk/python/tests/test_encryption.py +0 -206
  178. package/sdk/python/tests/test_http.py +0 -305
  179. package/sdk/python/tests/test_keys.py +0 -417
  180. package/sdk/python/tests/test_queue.py +0 -120
  181. package/sdk/python/tests/test_webhook.py +0 -345
  182. package/sdk/rust/Cargo.lock +0 -371
  183. package/sdk/rust/Cargo.toml +0 -25
  184. package/sdk/rust/README.md +0 -31
  185. package/sdk/rust/fuzz/Cargo.toml +0 -29
  186. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  187. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  188. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  189. package/sdk/rust/src/http.rs +0 -145
  190. package/sdk/rust/src/keys.rs +0 -161
  191. package/sdk/rust/src/lib.rs +0 -688
  192. package/sdk/rust/src/queue.rs +0 -79
  193. package/sdk/rust/src/webhook.rs +0 -86
  194. package/sdk/rust/tests/conformance.rs +0 -148
  195. package/sdk/rust/tests/gateway.rs +0 -130
  196. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  197. package/sdk/rust/tests/keys.rs +0 -189
  198. package/sdk/threshold/index.d.ts +0 -68
  199. package/sdk/threshold/index.d.ts.map +0 -1
  200. package/sdk/threshold/index.js +0 -254
  201. package/sdk/threshold/package-lock.json +0 -1361
  202. package/sdk/threshold/package.json +0 -39
  203. package/sdk/threshold/src/index.d.ts +0 -68
  204. package/sdk/threshold/src/index.d.ts.map +0 -1
  205. package/sdk/threshold/src/index.js +0 -254
  206. package/sdk/threshold/src/index.test.ts +0 -238
  207. package/sdk/threshold/src/index.ts +0 -355
  208. package/sdk/threshold/tsconfig.json +0 -19
  209. package/sdk/threshold/vitest.config.ts +0 -12
  210. package/src/agentAdapter.test.ts +0 -48
  211. package/src/agentAdapter.ts +0 -56
  212. package/src/auditLog.test.ts +0 -145
  213. package/src/auditLog.ts +0 -147
  214. package/src/capability.test.ts +0 -504
  215. package/src/capability.ts +0 -380
  216. package/src/cborCodec.test.ts +0 -263
  217. package/src/cborCodec.ts +0 -339
  218. package/src/conformance.test.ts +0 -136
  219. package/src/conformanceVectors.ts +0 -99
  220. package/src/encryption.test.ts +0 -206
  221. package/src/encryption.ts +0 -245
  222. package/src/envelopeCbor.ts +0 -140
  223. package/src/frameworkAdapters.test.ts +0 -290
  224. package/src/frameworkAdapters.ts +0 -261
  225. package/src/gateway.test.ts +0 -343
  226. package/src/gateway.ts +0 -246
  227. package/src/grpcBinding.test.ts +0 -211
  228. package/src/grpcBinding.ts +0 -103
  229. package/src/httpBinding.test.ts +0 -376
  230. package/src/httpBinding.ts +0 -189
  231. package/src/index.ts +0 -39
  232. package/src/keyInfra.test.ts +0 -278
  233. package/src/keyInfra.ts +0 -228
  234. package/src/keyRegistry.ts +0 -59
  235. package/src/keyRotation.test.ts +0 -78
  236. package/src/keyRotation.ts +0 -72
  237. package/src/mcpGateway.test.ts +0 -129
  238. package/src/mcpGateway.ts +0 -250
  239. package/src/mcpTransports.test.ts +0 -92
  240. package/src/mcpTransports.ts +0 -169
  241. package/src/mcpWrapper.test.ts +0 -179
  242. package/src/mcpWrapper.ts +0 -206
  243. package/src/otel.ts +0 -136
  244. package/src/policyEnforcer.test.ts +0 -99
  245. package/src/policyEnforcer.ts +0 -169
  246. package/src/policyTelemetryFeedback.test.ts +0 -25
  247. package/src/policyTelemetryFeedback.ts +0 -38
  248. package/src/protocol.bench.ts +0 -37
  249. package/src/protocol.d.ts.map +0 -1
  250. package/src/protocol.js +0 -294
  251. package/src/protocol.test.ts +0 -155
  252. package/src/protocol.ts +0 -414
  253. package/src/protocolAgent.test.ts +0 -105
  254. package/src/protocolAgent.ts +0 -169
  255. package/src/protocolBinary.test.ts +0 -165
  256. package/src/protocolBinary.ts +0 -312
  257. package/src/protocolCapabilities.ts +0 -70
  258. package/src/protocolFuzz.advanced.test.ts +0 -235
  259. package/src/protocolFuzz.test.ts +0 -111
  260. package/src/protocolNegative.test.ts +0 -97
  261. package/src/protocolReplay.test.ts +0 -71
  262. package/src/protocolReplay.ts +0 -194
  263. package/src/protocolTransport.test.ts +0 -556
  264. package/src/protocolTransport.ts +0 -483
  265. package/src/queueBinding.test.ts +0 -130
  266. package/src/queueBinding.ts +0 -102
  267. package/src/rateLimiter.test.ts +0 -96
  268. package/src/rateLimiter.ts +0 -46
  269. package/src/redisIntegration.test.ts +0 -134
  270. package/src/replayStores.test.ts +0 -273
  271. package/src/replayStores.ts +0 -215
  272. package/src/revocation.test.ts +0 -98
  273. package/src/revocation.ts +0 -0
  274. package/src/routePolicy.test.ts +0 -87
  275. package/src/routePolicy.ts +0 -72
  276. package/src/runtimePolicy.test.ts +0 -49
  277. package/src/runtimePolicy.ts +0 -81
  278. package/src/runtimePolicyManager.test.ts +0 -29
  279. package/src/runtimePolicyManager.ts +0 -50
  280. package/src/runtimePolicyPresets.ts +0 -43
  281. package/src/signedResponse.test.ts +0 -111
  282. package/src/signedResponse.ts +0 -83
  283. package/src/stream.test.ts +0 -254
  284. package/src/stream.ts +0 -417
  285. package/src/telemetry.test.ts +0 -251
  286. package/src/telemetry.ts +0 -299
  287. package/src/webhookBinding.test.ts +0 -144
  288. package/src/webhookBinding.ts +0 -115
  289. package/src/wsBinding.test.ts +0 -221
  290. package/src/wsBinding.ts +0 -200
  291. package/tsconfig.json +0 -15
  292. package/tsconfig.lib.json +0 -23
  293. package/vite.lib.config.ts +0 -16
  294. package/vitest.config.ts +0 -11
package/index.js ADDED
@@ -0,0 +1,3670 @@
1
+ //#region \0rolldown/runtime.js
2
+ var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => {
3
+ if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, {
4
+ get: ((e) => i[e]).bind(null, d),
5
+ enumerable: !(s = n(i, d)) || s.enumerable
6
+ });
7
+ return e;
8
+ }, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", {
9
+ value: n,
10
+ enumerable: !0
11
+ }) : a, n)), l = new TextEncoder(), u = 256, d = /* @__PURE__ */ new Map(), f = 256, p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map();
12
+ function ee() {
13
+ return globalThis.Buffer ?? null;
14
+ }
15
+ function te(e) {
16
+ let t = [`"messageId":${JSON.stringify(e.messageId)}`, `"nonce":${JSON.stringify(e.nonce)}`];
17
+ return e.recipient !== void 0 && t.push(`"recipient":${JSON.stringify(e.recipient)}`), t.push(`"sender":${JSON.stringify(e.sender)}`), t.push(`"timestampMs":${e.timestampMs}`), t.push(`"ttlMs":${e.ttlMs}`), t.push(`"version":${JSON.stringify(e.version)}`), `{${t.join(",")}}`;
18
+ }
19
+ function ne(e) {
20
+ let t = [];
21
+ return e.capability !== void 0 && t.push(`"capability":${JSON.stringify(e.capability)}`), t.push(`"content":${JSON.stringify(e.content)}`), e.correlationId !== void 0 && t.push(`"correlationId":${JSON.stringify(e.correlationId)}`), t.push(`"intent":${JSON.stringify(e.intent)}`), `{${t.join(",")}}`;
22
+ }
23
+ function re(e) {
24
+ let t = `hs256:${e}`, n = d.get(t);
25
+ if (n) return n;
26
+ d.size >= u && d.clear();
27
+ let r = v().importKey("raw", l.encode(e), {
28
+ name: "HMAC",
29
+ hash: "SHA-256"
30
+ }, !1, ["sign", "verify"]).catch((e) => {
31
+ throw d.delete(t), e;
32
+ });
33
+ return d.set(t, r), r;
34
+ }
35
+ function ie(e) {
36
+ let t = `ed25519:pkcs8:${e}`, n = p.get(t);
37
+ if (n) return n;
38
+ p.size >= f && p.clear();
39
+ let r = v().importKey("pkcs8", oe(g(e)), { name: "Ed25519" }, !1, ["sign"]).catch((e) => {
40
+ throw p.delete(t), e;
41
+ });
42
+ return p.set(t, r), r;
43
+ }
44
+ function ae(e) {
45
+ let t = `ed25519:spki:${e}`, n = m.get(t);
46
+ if (n) return n;
47
+ m.size >= f && m.clear();
48
+ let r = v().importKey("spki", oe(g(e)), { name: "Ed25519" }, !1, ["verify"]).catch((e) => {
49
+ throw m.delete(t), e;
50
+ });
51
+ return m.set(t, r), r;
52
+ }
53
+ function h(e) {
54
+ let t = ee();
55
+ return (t ? t.from(e).toString("base64") : btoa(String.fromCharCode(...e))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
56
+ }
57
+ function g(e) {
58
+ let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = ee();
59
+ if (n) return new Uint8Array(n.from(t, "base64"));
60
+ let r = atob(t), i = new Uint8Array(r.length);
61
+ for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
62
+ return i;
63
+ }
64
+ function oe(e) {
65
+ return e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength);
66
+ }
67
+ function _(e) {
68
+ return `{"body":${ne(e.body)},"header":${te(e.header)}}`;
69
+ }
70
+ function v() {
71
+ if (typeof crypto > "u" || !crypto.subtle) throw Error("Web Crypto API is not available in this runtime");
72
+ return crypto.subtle;
73
+ }
74
+ function y(e = 12) {
75
+ if (typeof crypto > "u" || !crypto.getRandomValues) throw Error("Web Crypto API is not available in this runtime");
76
+ let t = new Uint8Array(e);
77
+ crypto.getRandomValues(t);
78
+ let n = "";
79
+ for (let e of t) n += e.toString(16).padStart(2, "0");
80
+ return n;
81
+ }
82
+ async function se(e, t) {
83
+ let n = v(), r = await re(t), i = await n.sign("HMAC", r, l.encode(e));
84
+ return h(new Uint8Array(i));
85
+ }
86
+ async function ce(e, t, n) {
87
+ let r = v(), i = await re(n), a = g(t);
88
+ return r.verify("HMAC", i, a.buffer, l.encode(e));
89
+ }
90
+ async function le(e, t) {
91
+ let n = v(), r = await ie(t), i = await n.sign("Ed25519", r, l.encode(e));
92
+ return h(new Uint8Array(i));
93
+ }
94
+ async function ue(e, t, n) {
95
+ let r = v(), i = await ae(n), a = g(t);
96
+ return r.verify("Ed25519", i, a.buffer, l.encode(e));
97
+ }
98
+ async function de(e, t) {
99
+ return se(e, t);
100
+ }
101
+ async function fe(e, t, n) {
102
+ return ce(e, t, n);
103
+ }
104
+ async function pe() {
105
+ let e = v(), t = await e.generateKey({ name: "Ed25519" }, !0, ["sign", "verify"]), n = await e.exportKey("pkcs8", t.privateKey), r = await e.exportKey("spki", t.publicKey);
106
+ return {
107
+ privateKey: h(new Uint8Array(n)),
108
+ publicKey: h(new Uint8Array(r))
109
+ };
110
+ }
111
+ async function b(e, t) {
112
+ return le(e, t);
113
+ }
114
+ async function x(e, t, n) {
115
+ return ue(e, t, n);
116
+ }
117
+ async function S(e, t, n = "local-dev-key") {
118
+ let r = await se(_(e), t);
119
+ return {
120
+ ...e,
121
+ signature: {
122
+ alg: "HS256",
123
+ keyId: n,
124
+ value: r
125
+ }
126
+ };
127
+ }
128
+ async function C(e, t) {
129
+ return !e.signature || e.signature.alg !== "HS256" ? !1 : ce(_({
130
+ header: e.header,
131
+ body: e.body
132
+ }), e.signature.value, t);
133
+ }
134
+ async function w(e, t, n = "local-ed25519-key") {
135
+ let r = await le(_(e), t);
136
+ return {
137
+ ...e,
138
+ signature: {
139
+ alg: "ED25519",
140
+ keyId: n,
141
+ value: r
142
+ }
143
+ };
144
+ }
145
+ async function T(e, t) {
146
+ return !e.signature || e.signature.alg !== "ED25519" ? !1 : ue(_({
147
+ header: e.header,
148
+ body: e.body
149
+ }), e.signature.value, t);
150
+ }
151
+ async function me(e, t) {
152
+ return !e.signature || e.signature.alg !== t.alg ? !1 : t.alg === "HS256" ? C(e, t.secret) : T(e, t.publicKey);
153
+ }
154
+ async function he(e, t, n) {
155
+ return !t || t.alg !== n.alg ? !1 : n.alg === "HS256" ? fe(e, t.value, n.secret) : x(e, t.value, n.publicKey);
156
+ }
157
+ function E(e, t = Date.now()) {
158
+ let n = [], r = e.header ?? {}, i = e.body ?? {}, a = typeof r.version == "string" ? r.version : "", o = typeof r.messageId == "string" ? r.messageId : "", s = typeof r.sender == "string" ? r.sender : "", c = typeof r.nonce == "string" ? r.nonce : "", l = typeof r.timestampMs == "number" ? r.timestampMs : 0, u = typeof r.ttlMs == "number" ? r.ttlMs : 0, d = typeof i.content == "string" ? i.content : "";
159
+ return a !== "7h3/0.1" && n.push({
160
+ level: "error",
161
+ message: `Unsupported protocol version '${a}'`
162
+ }), o.trim() || n.push({
163
+ level: "error",
164
+ message: "Missing messageId"
165
+ }), s.trim() || n.push({
166
+ level: "error",
167
+ message: "Missing sender identity"
168
+ }), c.trim() || n.push({
169
+ level: "error",
170
+ message: "Missing nonce — replay protection requires a unique nonce per message"
171
+ }), u <= 0 && n.push({
172
+ level: "error",
173
+ message: "ttlMs must be greater than zero"
174
+ }), l + u < t && n.push({
175
+ level: "error",
176
+ message: "Message TTL expired"
177
+ }), d.trim() || n.push({
178
+ level: "warning",
179
+ message: "Empty content payload"
180
+ }), n;
181
+ }
182
+ function D(e) {
183
+ let t = e.nowMs ?? Date.now();
184
+ return {
185
+ header: {
186
+ version: "7h3/0.1",
187
+ messageId: e.messageId ?? `msg-${t}-${y(6)}`,
188
+ timestampMs: t,
189
+ ttlMs: e.ttlMs ?? 6e4,
190
+ sender: e.sender,
191
+ recipient: e.recipient,
192
+ nonce: e.nonce ?? y(12)
193
+ },
194
+ body: {
195
+ intent: e.intent,
196
+ content: e.content,
197
+ capability: e.capability,
198
+ correlationId: e.correlationId
199
+ }
200
+ };
201
+ }
202
+ //#endregion
203
+ //#region src/protocolBinary.ts
204
+ var ge = [
205
+ 65,
206
+ 73,
207
+ 80,
208
+ 66
209
+ ], _e = Uint8Array.from(ge), ve = 1, ye = 1024 * 1024, be = 1, xe = 2, Se = 4, Ce = 8, we = new TextEncoder(), Te = new TextDecoder(), Ee = new Set([
210
+ "PING",
211
+ "PONG",
212
+ "CAPS",
213
+ "TASK",
214
+ "RESULT",
215
+ "ERROR"
216
+ ]);
217
+ function De(e) {
218
+ return we.encode(e);
219
+ }
220
+ function Oe(e) {
221
+ return Te.decode(e);
222
+ }
223
+ function ke(e) {
224
+ return e === "ED25519" ? 2 : 1;
225
+ }
226
+ function Ae(e) {
227
+ return e === 1 ? "HS256" : e === 2 ? "ED25519" : null;
228
+ }
229
+ function O(e) {
230
+ return { bytes: De(e) };
231
+ }
232
+ function k(e) {
233
+ return e ? 4 + e.bytes.byteLength : 0;
234
+ }
235
+ var je = class {
236
+ bytes;
237
+ view;
238
+ offset = 0;
239
+ constructor(e) {
240
+ this.bytes = new Uint8Array(e), this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);
241
+ }
242
+ writeU8(e) {
243
+ this.bytes[this.offset] = e & 255, this.offset += 1;
244
+ }
245
+ writeU32(e) {
246
+ this.view.setUint32(this.offset, e, !1), this.offset += 4;
247
+ }
248
+ writeU64(e) {
249
+ this.view.setBigUint64(this.offset, BigInt(e), !1), this.offset += 8;
250
+ }
251
+ writeBytes(e) {
252
+ this.bytes.set(e, this.offset), this.offset += e.byteLength;
253
+ }
254
+ writeString(e) {
255
+ this.writeU32(e.bytes.byteLength), this.writeBytes(e.bytes);
256
+ }
257
+ finish() {
258
+ return this.bytes;
259
+ }
260
+ }, Me = class {
261
+ bytes;
262
+ offset = 0;
263
+ constructor(e) {
264
+ this.bytes = e;
265
+ }
266
+ remaining() {
267
+ return this.bytes.byteLength - this.offset;
268
+ }
269
+ readU8() {
270
+ if (this.remaining() < 1) throw Error("Unexpected end of binary envelope");
271
+ let e = this.bytes[this.offset];
272
+ return this.offset += 1, e ?? 0;
273
+ }
274
+ readU32() {
275
+ if (this.remaining() < 4) throw Error("Unexpected end of binary envelope");
276
+ let e = new DataView(this.bytes.buffer, this.bytes.byteOffset + this.offset, 4).getUint32(0, !1);
277
+ return this.offset += 4, e;
278
+ }
279
+ readU64() {
280
+ if (this.remaining() < 8) throw Error("Unexpected end of binary envelope");
281
+ let e = new DataView(this.bytes.buffer, this.bytes.byteOffset + this.offset, 8).getBigUint64(0, !1);
282
+ return this.offset += 8, Number(e);
283
+ }
284
+ readBytes(e) {
285
+ if (e < 0 || this.remaining() < e) throw Error("Unexpected end of binary envelope");
286
+ let t = this.bytes.slice(this.offset, this.offset + e);
287
+ return this.offset += e, t;
288
+ }
289
+ readString() {
290
+ let e = this.readU32();
291
+ return Oe(this.readBytes(e));
292
+ }
293
+ };
294
+ function Ne(e) {
295
+ let t = (e.header.recipient ? be : 0) | (e.body.capability ? xe : 0) | (e.body.correlationId ? Se : 0) | (e.signature ? Ce : 0), n = O(e.header.version), r = O(e.header.messageId), i = O(e.header.sender), a = O(e.header.nonce), o = O(e.body.intent), s = O(e.body.content), c = e.header.recipient ? O(e.header.recipient) : null, l = e.body.capability ? O(e.body.capability) : null, u = e.body.correlationId ? O(e.body.correlationId) : null, d = e.signature ? O(e.signature.keyId) : null, f = e.signature ? O(e.signature.value) : null, p = new je(_e.byteLength + 1 + 1 + 8 + 4 + k(n) + k(r) + k(i) + k(a) + k(o) + k(s) + k(c) + k(l) + k(u) + +!!e.signature + k(d) + k(f));
296
+ return p.writeBytes(_e), p.writeU8(ve), p.writeU8(t), p.writeU64(e.header.timestampMs), p.writeU32(e.header.ttlMs), p.writeString(n), p.writeString(r), p.writeString(i), p.writeString(a), p.writeString(o), p.writeString(s), c && p.writeString(c), l && p.writeString(l), u && p.writeString(u), e.signature && d && f && (p.writeU8(ke(e.signature.alg)), p.writeString(d), p.writeString(f)), p.finish();
297
+ }
298
+ function Pe(e, t = {}) {
299
+ try {
300
+ let n = t.maxFrameBytes ?? 1048576;
301
+ if (e.byteLength > n) return {
302
+ ok: !1,
303
+ diagnostics: [{
304
+ level: "error",
305
+ message: `Binary envelope exceeds maximum frame size '${n}'`
306
+ }],
307
+ envelope: null
308
+ };
309
+ let r = new Me(e);
310
+ if ([
311
+ r.readU8(),
312
+ r.readU8(),
313
+ r.readU8(),
314
+ r.readU8()
315
+ ].some((e, t) => e !== ge[t])) return {
316
+ ok: !1,
317
+ diagnostics: [{
318
+ level: "error",
319
+ message: "Invalid binary envelope magic"
320
+ }],
321
+ envelope: null
322
+ };
323
+ let i = r.readU8();
324
+ if (i !== ve) return {
325
+ ok: !1,
326
+ diagnostics: [{
327
+ level: "error",
328
+ message: `Unsupported binary envelope version '${i}'`
329
+ }],
330
+ envelope: null
331
+ };
332
+ let a = r.readU8(), o = r.readU64(), s = r.readU32(), c = {
333
+ header: {
334
+ version: r.readString(),
335
+ messageId: r.readString(),
336
+ timestampMs: o,
337
+ ttlMs: s,
338
+ sender: r.readString(),
339
+ nonce: r.readString()
340
+ },
341
+ body: {
342
+ intent: r.readString(),
343
+ content: r.readString()
344
+ }
345
+ };
346
+ if (c.header.version !== "7h3/0.1") return {
347
+ ok: !1,
348
+ diagnostics: [{
349
+ level: "error",
350
+ message: `Unsupported protocol version '${c.header.version}'`
351
+ }],
352
+ envelope: null
353
+ };
354
+ if (!Ee.has(c.body.intent)) return {
355
+ ok: !1,
356
+ diagnostics: [{
357
+ level: "error",
358
+ message: `Unsupported intent '${c.body.intent}'`
359
+ }],
360
+ envelope: null
361
+ };
362
+ if (a & be && (c.header.recipient = r.readString()), a & xe && (c.body.capability = r.readString()), a & Se && (c.body.correlationId = r.readString()), a & Ce) {
363
+ let e = r.readU8(), t = Ae(e);
364
+ if (!t) return {
365
+ ok: !1,
366
+ diagnostics: [{
367
+ level: "error",
368
+ message: `Unsupported binary signature algorithm '${e}'`
369
+ }],
370
+ envelope: null
371
+ };
372
+ c.signature = {
373
+ alg: t,
374
+ keyId: r.readString(),
375
+ value: r.readString()
376
+ };
377
+ }
378
+ return r.remaining() === 0 ? {
379
+ ok: !0,
380
+ diagnostics: [],
381
+ envelope: c
382
+ } : {
383
+ ok: !1,
384
+ diagnostics: [{
385
+ level: "error",
386
+ message: "Trailing bytes found in binary envelope"
387
+ }],
388
+ envelope: null
389
+ };
390
+ } catch (e) {
391
+ return {
392
+ ok: !1,
393
+ diagnostics: [{
394
+ level: "error",
395
+ message: e instanceof Error ? e.message : "Invalid binary envelope"
396
+ }],
397
+ envelope: null
398
+ };
399
+ }
400
+ }
401
+ //#endregion
402
+ //#region src/protocolReplay.ts
403
+ var Fe = class {
404
+ items = [];
405
+ peek() {
406
+ return this.items[0];
407
+ }
408
+ push(e) {
409
+ this.items.push(e), this.bubbleUp(this.items.length - 1);
410
+ }
411
+ pop() {
412
+ if (this.items.length === 0) return;
413
+ let e = this.items[0], t = this.items.pop();
414
+ return this.items.length > 0 && t && (this.items[0] = t, this.bubbleDown(0)), e;
415
+ }
416
+ bubbleUp(e) {
417
+ let t = e;
418
+ for (; t > 0;) {
419
+ let e = Math.floor((t - 1) / 2), n = this.items[e], r = this.items[t];
420
+ if (!n || !r || n.expiresAt <= r.expiresAt) break;
421
+ this.items[e] = r, this.items[t] = n, t = e;
422
+ }
423
+ }
424
+ bubbleDown(e) {
425
+ let t = e;
426
+ for (;;) {
427
+ let e = t * 2 + 1, n = t * 2 + 2, r = t, i = this.items[t], a = this.items[e], o = this.items[n];
428
+ a && i && a.expiresAt < i.expiresAt && (r = e);
429
+ let s = this.items[r];
430
+ if (o && s && o.expiresAt < s.expiresAt && (r = n), r === t) break;
431
+ let c = this.items[t], l = this.items[r];
432
+ if (!c || !l) break;
433
+ this.items[t] = l, this.items[r] = c, t = r;
434
+ }
435
+ }
436
+ }, A = class {
437
+ entries = /* @__PURE__ */ new Map();
438
+ maxEntries;
439
+ expiries = new Fe();
440
+ constructor(e = 1e4) {
441
+ this.maxEntries = e;
442
+ }
443
+ makeKey(e) {
444
+ return `${encodeURIComponent(e.header.sender)}|${encodeURIComponent(e.header.messageId)}|${encodeURIComponent(e.header.nonce)}`;
445
+ }
446
+ prune(e = Date.now()) {
447
+ for (;;) {
448
+ let t = this.expiries.peek();
449
+ if (!t || t.expiresAt > e) break;
450
+ this.expiries.pop();
451
+ let n = this.entries.get(t.key);
452
+ n !== void 0 && n === t.expiresAt && n <= e && this.entries.delete(t.key);
453
+ }
454
+ }
455
+ evictOne() {
456
+ for (; this.entries.size >= this.maxEntries;) {
457
+ let e = this.expiries.pop();
458
+ if (!e) break;
459
+ let t = this.entries.get(e.key);
460
+ if (t !== void 0 && t === e.expiresAt) {
461
+ this.entries.delete(e.key);
462
+ return;
463
+ }
464
+ }
465
+ if (this.entries.size >= this.maxEntries) {
466
+ let e = this.entries.keys().next().value;
467
+ e && this.entries.delete(e);
468
+ }
469
+ }
470
+ consume(e, t = Date.now()) {
471
+ this.prune(t);
472
+ let n = this.makeKey(e), r = this.entries.get(n);
473
+ if (r && r > t) return {
474
+ ok: !1,
475
+ reason: "Replay detected for sender/messageId/nonce"
476
+ };
477
+ this.entries.size >= this.maxEntries && this.evictOne();
478
+ let i = e.header.timestampMs + e.header.ttlMs;
479
+ return this.entries.set(n, i), this.expiries.push({
480
+ key: n,
481
+ expiresAt: i
482
+ }), { ok: !0 };
483
+ }
484
+ consumeMany(e, t = Date.now()) {
485
+ return e.map((e) => this.consume(e, t));
486
+ }
487
+ }, Ie = class {
488
+ store;
489
+ constructor(e) {
490
+ this.store = e;
491
+ }
492
+ makeKey(e) {
493
+ return `${encodeURIComponent(e.header.sender)}|${encodeURIComponent(e.header.messageId)}|${encodeURIComponent(e.header.nonce)}`;
494
+ }
495
+ async consume(e, t = Date.now()) {
496
+ let n = this.makeKey(e), r = e.header.timestampMs + e.header.ttlMs;
497
+ return await this.store.reserve(n, r, t) ? { ok: !0 } : {
498
+ ok: !1,
499
+ reason: "Replay detected for sender/messageId/nonce"
500
+ };
501
+ }
502
+ async consumeMany(e, t = Date.now()) {
503
+ if (this.store.reserveMany) {
504
+ let n = e.map((e) => ({
505
+ key: this.makeKey(e),
506
+ expiresAtMs: e.header.timestampMs + e.header.ttlMs
507
+ }));
508
+ return (await this.store.reserveMany(n, t)).map((e) => e ? { ok: !0 } : {
509
+ ok: !1,
510
+ reason: "Replay detected for sender/messageId/nonce"
511
+ });
512
+ }
513
+ return Promise.all(e.map((e) => this.consume(e, t)));
514
+ }
515
+ }, Le = class {
516
+ entries = /* @__PURE__ */ new Map();
517
+ maxEntries;
518
+ constructor(e = 512) {
519
+ this.maxEntries = e;
520
+ }
521
+ get(e, t = Date.now()) {
522
+ let n = this.entries.get(e);
523
+ if (n) {
524
+ if (n.expiresAtMs <= t) {
525
+ this.entries.delete(e);
526
+ return;
527
+ }
528
+ return n.material;
529
+ }
530
+ }
531
+ set(e, t, n) {
532
+ if (this.entries.size >= this.maxEntries) {
533
+ let e = this.entries.keys().next().value;
534
+ e && this.entries.delete(e);
535
+ }
536
+ this.entries.set(e, {
537
+ expiresAtMs: n,
538
+ material: t
539
+ });
540
+ }
541
+ delete(e) {
542
+ this.entries.delete(e);
543
+ }
544
+ };
545
+ function Re(e, t) {
546
+ return `${t}|${e.alg}|${e.keyId}`;
547
+ }
548
+ function ze(e) {
549
+ if (!e || typeof e != "object") return !1;
550
+ let t = e;
551
+ return !!(t.header && t.body);
552
+ }
553
+ function Be(e) {
554
+ if (!e || typeof e != "object") return !1;
555
+ let t = e;
556
+ return t.v === "7h3/0.1" && typeof t.mid == "string" && typeof t.i == "string";
557
+ }
558
+ function Ve(e) {
559
+ return {
560
+ header: {
561
+ version: e.v,
562
+ messageId: e.mid,
563
+ timestampMs: e.ts,
564
+ ttlMs: e.ttl,
565
+ sender: e.s,
566
+ recipient: e.r,
567
+ nonce: e.n
568
+ },
569
+ body: {
570
+ intent: e.i,
571
+ content: e.c,
572
+ capability: e.cap,
573
+ correlationId: e.cid
574
+ },
575
+ signature: e.sig ? {
576
+ alg: e.sig.a ?? "HS256",
577
+ keyId: e.sig.k,
578
+ value: e.sig.v
579
+ } : void 0
580
+ };
581
+ }
582
+ function He(e) {
583
+ return {
584
+ v: e.header.version,
585
+ mid: e.header.messageId,
586
+ ts: e.header.timestampMs,
587
+ ttl: e.header.ttlMs,
588
+ s: e.header.sender,
589
+ r: e.header.recipient,
590
+ n: e.header.nonce,
591
+ i: e.body.intent,
592
+ c: e.body.content,
593
+ cap: e.body.capability,
594
+ cid: e.body.correlationId,
595
+ sig: e.signature ? {
596
+ a: e.signature.alg,
597
+ k: e.signature.keyId,
598
+ v: e.signature.value
599
+ } : void 0
600
+ };
601
+ }
602
+ function Ue(e) {
603
+ if (e instanceof Uint8Array) return Pe(e);
604
+ try {
605
+ let t = JSON.parse(e);
606
+ return Be(t) ? {
607
+ ok: !0,
608
+ diagnostics: [],
609
+ envelope: Ve(t)
610
+ } : ze(t) ? {
611
+ ok: !0,
612
+ diagnostics: [],
613
+ envelope: t
614
+ } : {
615
+ ok: !1,
616
+ diagnostics: [{
617
+ level: "error",
618
+ message: "Envelope JSON shape is not recognized"
619
+ }],
620
+ envelope: null
621
+ };
622
+ } catch {
623
+ return {
624
+ ok: !1,
625
+ diagnostics: [{
626
+ level: "error",
627
+ message: "Invalid JSON envelope"
628
+ }],
629
+ envelope: null
630
+ };
631
+ }
632
+ }
633
+ function j(e, t = "json") {
634
+ return t === "binary" ? Ne(e) : JSON.stringify(t === "compact" ? He(e) : e);
635
+ }
636
+ function We(e, t = "compact") {
637
+ return JSON.stringify(t === "compact" ? e.map(He) : e);
638
+ }
639
+ function Ge(e) {
640
+ try {
641
+ let t = JSON.parse(e);
642
+ return Array.isArray(t) ? t.map((e) => Be(e) ? {
643
+ ok: !0,
644
+ diagnostics: [],
645
+ envelope: Ve(e)
646
+ } : ze(e) ? {
647
+ ok: !0,
648
+ diagnostics: [],
649
+ envelope: e
650
+ } : {
651
+ ok: !1,
652
+ diagnostics: [{
653
+ level: "error",
654
+ message: "Batch item has unrecognized envelope shape"
655
+ }],
656
+ envelope: null
657
+ }) : [{
658
+ ok: !1,
659
+ diagnostics: [{
660
+ level: "error",
661
+ message: "Batch payload must be a JSON array"
662
+ }],
663
+ envelope: null
664
+ }];
665
+ } catch {
666
+ return [{
667
+ ok: !1,
668
+ diagnostics: [{
669
+ level: "error",
670
+ message: "Invalid JSON batch payload"
671
+ }],
672
+ envelope: null
673
+ }];
674
+ }
675
+ }
676
+ async function M(e, t = {}) {
677
+ let n = t.nowMs ?? Date.now(), r = t.requireSignature ?? !0, i = t.maxClockSkewMs ?? 3e4;
678
+ async function a(e) {
679
+ t.telemetry && await t.telemetry({
680
+ nowMs: n,
681
+ ...e
682
+ });
683
+ }
684
+ let o = typeof e == "string" || e instanceof Uint8Array ? Ue(e) : {
685
+ ok: !0,
686
+ diagnostics: [],
687
+ envelope: e
688
+ };
689
+ if (!o.ok || !o.envelope) return o;
690
+ if (await a({
691
+ phase: "decoded",
692
+ sender: o.envelope.header.sender,
693
+ messageId: o.envelope.header.messageId
694
+ }), o.envelope.header.timestampMs > n + i) {
695
+ let e = "Message timestamp exceeds allowed clock skew", t = [{
696
+ level: "error",
697
+ message: e
698
+ }];
699
+ return await a({
700
+ phase: "rejected_clock_skew",
701
+ sender: o.envelope.header.sender,
702
+ messageId: o.envelope.header.messageId,
703
+ reason: e
704
+ }), {
705
+ ok: !1,
706
+ diagnostics: t,
707
+ envelope: o.envelope
708
+ };
709
+ }
710
+ let s = [...E(o.envelope, n)];
711
+ if (s.some((e) => e.level === "error")) return await a({
712
+ phase: "rejected_validation",
713
+ sender: o.envelope.header.sender,
714
+ messageId: o.envelope.header.messageId,
715
+ reason: s.find((e) => e.level === "error")?.message
716
+ }), {
717
+ ok: !1,
718
+ diagnostics: s,
719
+ envelope: o.envelope
720
+ };
721
+ if (!o.envelope.signature) return r ? (s.push({
722
+ level: "error",
723
+ message: "Missing signature"
724
+ }), await a({
725
+ phase: "rejected_missing_signature",
726
+ sender: o.envelope.header.sender,
727
+ messageId: o.envelope.header.messageId,
728
+ reason: "Missing signature"
729
+ }), {
730
+ ok: !1,
731
+ diagnostics: s,
732
+ envelope: o.envelope
733
+ }) : (await a({
734
+ phase: "accepted",
735
+ sender: o.envelope.header.sender,
736
+ messageId: o.envelope.header.messageId
737
+ }), {
738
+ ok: !0,
739
+ diagnostics: s,
740
+ envelope: o.envelope
741
+ });
742
+ let c, l = o.envelope.signature, u = Re(l, o.envelope.header.sender);
743
+ if (t.verificationMaterialCache && (c = t.verificationMaterialCache.get(u, n)), t.signatureResolver && (c ??= await t.signatureResolver(l, o.envelope.header.sender)), !c && l.alg === "HS256" && t.secretResolver) {
744
+ let e = await t.secretResolver(l.keyId, o.envelope.header.sender);
745
+ e && (c = {
746
+ alg: "HS256",
747
+ secret: e
748
+ });
749
+ }
750
+ if (c && t.verificationMaterialCache) {
751
+ let e = Math.max(n + 1, o.envelope.header.timestampMs + o.envelope.header.ttlMs);
752
+ t.verificationMaterialCache.set(u, c, e);
753
+ }
754
+ if (!c) return s.push({
755
+ level: "error",
756
+ message: "No signature verification material found for keyId/sender"
757
+ }), await a({
758
+ phase: "rejected_missing_material",
759
+ sender: o.envelope.header.sender,
760
+ messageId: o.envelope.header.messageId,
761
+ reason: "No signature verification material found for keyId/sender"
762
+ }), {
763
+ ok: !1,
764
+ diagnostics: s,
765
+ envelope: o.envelope
766
+ };
767
+ if (!await he(_({
768
+ header: o.envelope.header,
769
+ body: o.envelope.body
770
+ }), o.envelope.signature, c)) return s.push({
771
+ level: "error",
772
+ message: "Signature verification failed"
773
+ }), await a({
774
+ phase: "rejected_bad_signature",
775
+ sender: o.envelope.header.sender,
776
+ messageId: o.envelope.header.messageId,
777
+ reason: "Signature verification failed"
778
+ }), {
779
+ ok: !1,
780
+ diagnostics: s,
781
+ envelope: o.envelope
782
+ };
783
+ if (t.replayCache) {
784
+ let e = await t.replayCache.consume(o.envelope, n);
785
+ if (!e.ok) return s.push({
786
+ level: "error",
787
+ message: e.reason ?? "Replay detected"
788
+ }), await a({
789
+ phase: "rejected_replay",
790
+ sender: o.envelope.header.sender,
791
+ messageId: o.envelope.header.messageId,
792
+ reason: e.reason
793
+ }), {
794
+ ok: !1,
795
+ diagnostics: s,
796
+ envelope: o.envelope
797
+ };
798
+ }
799
+ return await a({
800
+ phase: "accepted",
801
+ sender: o.envelope.header.sender,
802
+ messageId: o.envelope.header.messageId
803
+ }), {
804
+ ok: !0,
805
+ diagnostics: s,
806
+ envelope: o.envelope
807
+ };
808
+ }
809
+ async function Ke(e, t = {}) {
810
+ let n = Math.max(1, Math.floor(t.batchConcurrency ?? Infinity));
811
+ return (async (e) => {
812
+ let r = Array(e.length), i = 0, a = Number.isFinite(n) ? Math.min(n, e.length) : e.length;
813
+ return await Promise.all(Array.from({ length: a }, async () => {
814
+ for (; i < e.length;) {
815
+ let n = i;
816
+ i += 1;
817
+ let a = e[n];
818
+ a && typeof a == "object" && "ok" in a && "diagnostics" in a && "envelope" in a ? r[n] = a : r[n] = await M(a, t);
819
+ }
820
+ })), await t.telemetry?.({
821
+ phase: "batch_summary",
822
+ nowMs: t.nowMs ?? Date.now(),
823
+ reason: `items=${e.length};accepted=${r.filter((e) => e?.ok).length}`
824
+ }), r;
825
+ })(typeof e == "string" ? Ge(e).map((e) => e.ok && e.envelope ? e.envelope : e) : e);
826
+ }
827
+ var qe = class {
828
+ options;
829
+ constructor(e = {}) {
830
+ this.options = {
831
+ ...e,
832
+ replayCache: e.replayCache ?? new A(),
833
+ verificationMaterialCache: e.verificationMaterialCache ?? new Le()
834
+ };
835
+ }
836
+ receive(e, t = Date.now()) {
837
+ return M(e, {
838
+ ...this.options,
839
+ nowMs: t
840
+ });
841
+ }
842
+ receiveBatch(e, t = Date.now()) {
843
+ return Ke(e, {
844
+ ...this.options,
845
+ nowMs: t
846
+ });
847
+ }
848
+ };
849
+ async function Je(e) {
850
+ return S(D(e), e.secret, e.keyId);
851
+ }
852
+ //#endregion
853
+ //#region src/protocolCapabilities.ts
854
+ var Ye = [
855
+ "binary",
856
+ "compact",
857
+ "json"
858
+ ], Xe = ["fast", "receipt"];
859
+ function Ze(e) {
860
+ return {
861
+ agent: e.agent,
862
+ capabilities: e.capabilities ?? [],
863
+ wireFormats: e.wireFormats ?? ["compact", "json"],
864
+ batchMax: e.batchMax ?? 1,
865
+ ackModes: e.ackModes ?? ["receipt"]
866
+ };
867
+ }
868
+ function Qe(e) {
869
+ return JSON.stringify(e);
870
+ }
871
+ function $e(e) {
872
+ try {
873
+ let t = JSON.parse(e);
874
+ return typeof t.agent != "string" || !Array.isArray(t.capabilities) || !Array.isArray(t.wireFormats) || !Array.isArray(t.ackModes) || typeof t.batchMax != "number" || t.batchMax < 1 ? null : {
875
+ agent: t.agent,
876
+ capabilities: t.capabilities.filter((e) => typeof e == "string"),
877
+ wireFormats: t.wireFormats.filter((e) => e === "json" || e === "compact" || e === "binary"),
878
+ batchMax: Math.floor(t.batchMax),
879
+ ackModes: t.ackModes.filter((e) => e === "fast" || e === "receipt")
880
+ };
881
+ } catch {
882
+ return null;
883
+ }
884
+ }
885
+ function et(e, t) {
886
+ let n = Ye.find((n) => e.wireFormats.includes(n) && t.wireFormats.includes(n)) ?? "compact", r = Xe.find((n) => e.ackModes.includes(n) && t.ackModes.includes(n)) ?? "receipt";
887
+ return {
888
+ wireFormat: n,
889
+ batchMax: Math.max(1, Math.min(e.batchMax, t.batchMax)),
890
+ ackMode: r
891
+ };
892
+ }
893
+ //#endregion
894
+ //#region src/keyRotation.ts
895
+ var tt = class {
896
+ records;
897
+ constructor(e = []) {
898
+ this.records = [...e];
899
+ }
900
+ add(e) {
901
+ this.records.push(e);
902
+ }
903
+ revoke(e, t, n = Date.now()) {
904
+ let r = this.records.find((n) => n.sender === e && n.keyId === t);
905
+ return r ? (r.status = "revoked", r.notAfterMs = Math.min(r.notAfterMs, n), !0) : !1;
906
+ }
907
+ selectSigningKey(e, t, n = Date.now()) {
908
+ return this.records.filter((r) => r.sender === e && r.alg === t && r.status === "active" && r.notBeforeMs <= n && n < r.notAfterMs).sort((e, t) => t.notBeforeMs - e.notBeforeMs)[0] ?? null;
909
+ }
910
+ resolveVerificationMaterial(e, t, n = Date.now()) {
911
+ return this.records.filter((r) => r.sender === t && r.keyId === e.keyId && r.alg === e.alg && r.status !== "revoked" && r.notBeforeMs <= n && n < r.notAfterMs).sort((e, t) => t.notBeforeMs - e.notBeforeMs)[0]?.material;
912
+ }
913
+ };
914
+ function nt(e, t = () => Date.now()) {
915
+ return async (n, r) => e.resolveVerificationMaterial(n, r, t());
916
+ }
917
+ //#endregion
918
+ //#region src/protocolAgent.ts
919
+ var rt = class {
920
+ agentId;
921
+ outboundSecret;
922
+ keyId;
923
+ capabilities;
924
+ supportedWireFormats;
925
+ maxBatchSize;
926
+ ackModes;
927
+ requireSignature;
928
+ replayCache;
929
+ sharedSecrets;
930
+ resolveInboundSecret;
931
+ onTask;
932
+ constructor(e) {
933
+ this.agentId = e.agentId, this.outboundSecret = e.outboundSecret, this.keyId = e.keyId ?? `${e.agentId}-k1`, this.capabilities = e.capabilities ?? [], this.supportedWireFormats = e.supportedWireFormats ?? ["compact", "json"], this.maxBatchSize = e.maxBatchSize ?? 1, this.ackModes = e.ackModes ?? ["receipt"], this.requireSignature = e.requireSignature ?? !0, this.replayCache = e.replayCache ?? new A(), this.sharedSecrets = e.sharedSecrets ?? {}, this.resolveInboundSecret = e.resolveInboundSecret, this.onTask = e.onTask;
934
+ }
935
+ async inboundSecretResolver(e, t) {
936
+ return this.resolveInboundSecret ? this.resolveInboundSecret(e, t) : this.sharedSecrets[t];
937
+ }
938
+ async createSignedIntent(e) {
939
+ return S(D({
940
+ sender: this.agentId,
941
+ recipient: e.recipient,
942
+ intent: e.intent,
943
+ content: e.content,
944
+ capability: e.capability,
945
+ correlationId: e.correlationId,
946
+ ttlMs: e.ttlMs,
947
+ messageId: e.messageId,
948
+ nonce: e.nonce,
949
+ nowMs: e.nowMs
950
+ }), this.outboundSecret, this.keyId);
951
+ }
952
+ async receiveAndRespond(e, t = Date.now()) {
953
+ let n = await M(e, {
954
+ nowMs: t,
955
+ requireSignature: this.requireSignature,
956
+ replayCache: this.replayCache,
957
+ secretResolver: (e, t) => this.inboundSecretResolver(e, t)
958
+ });
959
+ if (!n.ok || !n.envelope) return {
960
+ ok: !1,
961
+ diagnostics: n.diagnostics,
962
+ received: n.envelope,
963
+ response: null
964
+ };
965
+ let r = n.envelope, i = await this.buildAutoResponse(r, t);
966
+ return {
967
+ ok: !0,
968
+ diagnostics: n.diagnostics,
969
+ received: r,
970
+ response: i
971
+ };
972
+ }
973
+ async buildAutoResponse(e, t) {
974
+ if (e.body.intent === "PING") return this.createSignedIntent({
975
+ recipient: e.header.sender,
976
+ intent: "PONG",
977
+ content: "pong",
978
+ correlationId: e.header.messageId,
979
+ nowMs: t
980
+ });
981
+ if (e.body.intent === "CAPS") return this.createSignedIntent({
982
+ recipient: e.header.sender,
983
+ intent: "RESULT",
984
+ content: Qe(Ze({
985
+ agent: this.agentId,
986
+ capabilities: this.capabilities,
987
+ wireFormats: this.supportedWireFormats,
988
+ batchMax: this.maxBatchSize,
989
+ ackModes: this.ackModes
990
+ })),
991
+ capability: "caps",
992
+ correlationId: e.header.messageId,
993
+ nowMs: t
994
+ });
995
+ if (e.body.intent === "TASK") {
996
+ let n = this.onTask ? await this.onTask(e) : {
997
+ intent: "RESULT",
998
+ content: "ACK",
999
+ capability: e.body.capability
1000
+ };
1001
+ return this.createSignedIntent({
1002
+ recipient: e.header.sender,
1003
+ intent: n.intent ?? "RESULT",
1004
+ content: n.content,
1005
+ capability: n.capability,
1006
+ correlationId: e.header.messageId,
1007
+ nowMs: t
1008
+ });
1009
+ }
1010
+ return null;
1011
+ }
1012
+ }, it = class {
1013
+ session;
1014
+ wireFormat;
1015
+ constructor(e) {
1016
+ this.session = new rt(e), this.wireFormat = e.wireFormat ?? "compact";
1017
+ }
1018
+ toRaw(e) {
1019
+ return j(e, this.wireFormat);
1020
+ }
1021
+ async createRawIntent(e) {
1022
+ let t = await this.session.createSignedIntent(e);
1023
+ return this.toRaw(t);
1024
+ }
1025
+ async receiveRaw(e, t = Date.now()) {
1026
+ return this.session.receiveAndRespond(e, t);
1027
+ }
1028
+ async handleRaw(e, t, n = Date.now()) {
1029
+ let r = await this.session.receiveAndRespond(e, n);
1030
+ return r.response && await t(this.toRaw(r.response), r.response), r;
1031
+ }
1032
+ };
1033
+ function at(e) {
1034
+ return new it(e);
1035
+ }
1036
+ //#endregion
1037
+ //#region src/frameworkAdapters.ts
1038
+ async function ot(e, t, n = {}) {
1039
+ return e.createRawIntent({
1040
+ recipient: n.recipient,
1041
+ intent: "TASK",
1042
+ content: t.content,
1043
+ capability: n.capability,
1044
+ correlationId: n.correlationId
1045
+ });
1046
+ }
1047
+ function st(e) {
1048
+ return {
1049
+ content: e.body.content,
1050
+ name: e.body.intent,
1051
+ additionalKwargs: {
1052
+ capability: e.body.capability,
1053
+ correlationId: e.body.correlationId,
1054
+ sender: e.header.sender,
1055
+ recipient: e.header.recipient,
1056
+ messageId: e.header.messageId,
1057
+ timestampMs: e.header.timestampMs
1058
+ }
1059
+ };
1060
+ }
1061
+ async function ct(e, t, n = {}) {
1062
+ return e.createRawIntent({
1063
+ recipient: n.recipient,
1064
+ intent: "TASK",
1065
+ content: t.content,
1066
+ capability: n.capability,
1067
+ correlationId: n.correlationId
1068
+ });
1069
+ }
1070
+ function lt(e) {
1071
+ return {
1072
+ role: e.body.intent === "TASK" ? "user" : "assistant",
1073
+ content: e.body.content,
1074
+ additionalKwargs: {
1075
+ intent: e.body.intent,
1076
+ capability: e.body.capability,
1077
+ correlationId: e.body.correlationId,
1078
+ sender: e.header.sender,
1079
+ recipient: e.header.recipient
1080
+ }
1081
+ };
1082
+ }
1083
+ function ut(e) {
1084
+ return `mcp.${e}`;
1085
+ }
1086
+ async function dt(e, t, n = {}) {
1087
+ async function r(e) {
1088
+ n.onPolicyEvent && await n.onPolicyEvent(e);
1089
+ }
1090
+ if (n.allowedMethods && !n.allowedMethods.includes(t.method)) {
1091
+ let e = n.methodToCapability ? n.methodToCapability(t.method) : ut(t.method), i = {
1092
+ intent: "TASK",
1093
+ recipient: n.recipient,
1094
+ capability: e,
1095
+ correlationId: String(t.id),
1096
+ createdAtMs: Date.now()
1097
+ };
1098
+ throw await r({
1099
+ stage: "allowlist",
1100
+ decision: "deny",
1101
+ method: t.method,
1102
+ context: i,
1103
+ reason: "method_not_allowed"
1104
+ }), Error(`JSON-RPC method '${t.method}' is not allowed`);
1105
+ }
1106
+ let i = n.methodToCapability ? n.methodToCapability(t.method) : ut(t.method), a = {
1107
+ intent: "TASK",
1108
+ recipient: n.recipient,
1109
+ capability: i,
1110
+ correlationId: String(t.id),
1111
+ createdAtMs: Date.now()
1112
+ };
1113
+ if (await r({
1114
+ stage: "allowlist",
1115
+ decision: "allow",
1116
+ method: t.method,
1117
+ context: a
1118
+ }), n.authorizeMethod) {
1119
+ if (!await n.authorizeMethod(t, a)) throw await r({
1120
+ stage: "authorize",
1121
+ decision: "deny",
1122
+ method: t.method,
1123
+ context: a,
1124
+ reason: "not_authorized"
1125
+ }), Error(`JSON-RPC method '${t.method}' is not authorized`);
1126
+ await r({
1127
+ stage: "authorize",
1128
+ decision: "allow",
1129
+ method: t.method,
1130
+ context: a
1131
+ });
1132
+ }
1133
+ if (n.rateLimiter) {
1134
+ let e = n.rateLimitKey ? n.rateLimitKey(t, a) : t.method;
1135
+ if (!await n.rateLimiter.consume(e, t, a)) throw await r({
1136
+ stage: "rateLimit",
1137
+ decision: "deny",
1138
+ method: t.method,
1139
+ context: a,
1140
+ reason: "rate_limited"
1141
+ }), Error(`JSON-RPC method '${t.method}' is rate-limited`);
1142
+ await r({
1143
+ stage: "rateLimit",
1144
+ decision: "allow",
1145
+ method: t.method,
1146
+ context: a
1147
+ });
1148
+ }
1149
+ return e.createRawIntent({
1150
+ recipient: n.recipient,
1151
+ intent: "TASK",
1152
+ capability: i,
1153
+ correlationId: String(t.id),
1154
+ content: JSON.stringify({
1155
+ method: t.method,
1156
+ params: t.params ?? null
1157
+ })
1158
+ });
1159
+ }
1160
+ function ft(e, t, n = {}) {
1161
+ if (e.body.intent === "ERROR") return {
1162
+ jsonrpc: "2.0",
1163
+ id: t,
1164
+ error: {
1165
+ code: n.defaultErrorCode ?? -32e3,
1166
+ message: e.body.content,
1167
+ data: {
1168
+ capability: e.body.capability,
1169
+ correlationId: e.body.correlationId
1170
+ }
1171
+ }
1172
+ };
1173
+ let r = e.body.content;
1174
+ try {
1175
+ r = JSON.parse(e.body.content);
1176
+ } catch {
1177
+ r = e.body.content;
1178
+ }
1179
+ return {
1180
+ jsonrpc: "2.0",
1181
+ id: t,
1182
+ result: r
1183
+ };
1184
+ }
1185
+ //#endregion
1186
+ //#region src/runtimePolicy.ts
1187
+ function pt(e) {
1188
+ return typeof e == "object" && !!e && !Array.isArray(e);
1189
+ }
1190
+ function mt(e, t) {
1191
+ if (typeof e != "string" || e.trim().length === 0) throw Error(`Invalid runtime policy: '${t}' must be a non-empty string`);
1192
+ return e;
1193
+ }
1194
+ function ht(e) {
1195
+ if (!pt(e)) throw Error("Invalid runtime policy: root must be an object");
1196
+ let t = mt(e.version, "version"), n = mt(e.name, "name"), r = mt(e.status, "status");
1197
+ return {
1198
+ ...e,
1199
+ version: t,
1200
+ name: n,
1201
+ status: r
1202
+ };
1203
+ }
1204
+ function gt(e) {
1205
+ let t;
1206
+ try {
1207
+ t = JSON.parse(e);
1208
+ } catch (e) {
1209
+ let t = e instanceof Error ? e.message : String(e);
1210
+ throw Error(`Invalid runtime policy JSON: ${t}`);
1211
+ }
1212
+ return ht(t);
1213
+ }
1214
+ async function _t(e) {
1215
+ if (typeof fetch == "function") {
1216
+ let t = await fetch(e);
1217
+ if (!t.ok) throw Error(`Failed to fetch runtime policy at '${e}': ${t.status} ${t.statusText}`);
1218
+ return t.text();
1219
+ }
1220
+ throw Error("No default runtime file reader available in this environment. Provide 'readTextFile' in loadRuntimePolicy(options).");
1221
+ }
1222
+ async function vt(e = {}) {
1223
+ let t = e.path ?? "AI_RUNTIME_POLICY.json";
1224
+ return gt(await (e.readTextFile ?? _t)(t));
1225
+ }
1226
+ //#endregion
1227
+ //#region src/policyEnforcer.ts
1228
+ function yt(e, t) {
1229
+ if (!Array.isArray(e) || e.length !== 2) throw Error(`Invalid policy tuning range '${t}': expected [min,max]`);
1230
+ let n = Number(e[0]), r = Number(e[1]);
1231
+ if (!Number.isFinite(n) || !Number.isFinite(r) || n <= 0 || r < n) throw Error(`Invalid policy tuning range '${t}': expected positive ascending numbers`);
1232
+ return [Math.floor(n), Math.floor(r)];
1233
+ }
1234
+ function bt(e) {
1235
+ return e === "http" || e === "ws" || e === "http-binary" || e === "http-batch" || e === "http-binary-batch" || e === "ws-batch" || e === "ws-binary" || e === "ws-binary-batch";
1236
+ }
1237
+ function xt(e) {
1238
+ let t = Number((e.slo_defaults ?? {}).drop_pct_max ?? .1), n = Number((e.slo_defaults ?? {}).p99_ms_max ?? 20), r = Number((e.tuning ?? {}).max_retry_attempts ?? 3), i = Array.isArray((e.tuning ?? {}).retriable_status_codes) ? (e.tuning ?? {}).retriable_status_codes.map((e) => Number(e)).filter((e) => Number.isFinite(e)) : [503], a = e.tuning ?? {}, o = a.batch_size, s = a.inflight_cap, c = a.retry_backoff_ms, l = (e) => ({
1239
+ batchSizeRange: yt(o?.[`${e}_traffic`], `batch_size.${e}_traffic`),
1240
+ inflightCapRange: yt(s?.[`${e}_traffic`], `inflight_cap.${e}_traffic`),
1241
+ retryBackoffMsRange: yt(c?.[`${e}_traffic`], `retry_backoff_ms.${e}_traffic`)
1242
+ });
1243
+ function u(e) {
1244
+ return e.concurrency >= 100 ? "http-binary-batch" : e.latencySensitive ? "ws-batch" : e.compatibilityFirst ? "http" : "ws-batch";
1245
+ }
1246
+ function d(e) {
1247
+ let r = l(e.trafficClass), i = [];
1248
+ return typeof e.dropPct == "number" && e.dropPct > t && (i.push("reduce inflight cap"), i.push("reduce batch size"), i.push("increase retry backoff"), i.push("switch to binary-batch mode")), typeof e.p99Ms == "number" && e.p99Ms > n && (i.push("reduce batch size"), i.push("reduce inflight cap"), i.push("re-run adaptive benchmark")), {
1249
+ ...r,
1250
+ actions: i
1251
+ };
1252
+ }
1253
+ function f(e) {
1254
+ if (e.attempt >= r) return !1;
1255
+ let t = e.error instanceof Error ? e.error.message : String(e.error), n = /http status\s+(\d+)/i.exec(t), a = n ? Number(n[1]) : NaN;
1256
+ return Number.isFinite(a) && i.includes(a);
1257
+ }
1258
+ function p(e) {
1259
+ let t = [];
1260
+ if (e.signatureVerification || t.push("signatureVerification=false"), e.canonicalization || t.push("canonicalization=false"), e.replayDefense || t.push("replayDefense=false"), e.ttlClockSkewEnforcement || t.push("ttlClockSkewEnforcement=false"), t.length > 0) throw Error(`Invariant violation: ${t.join(", ")}`);
1261
+ }
1262
+ return {
1263
+ selectMode: u,
1264
+ tune: d,
1265
+ shouldRetry: f,
1266
+ assertInvariant: p,
1267
+ metadata: {
1268
+ policyName: e.name,
1269
+ policyVersion: e.version,
1270
+ policyStatus: e.status,
1271
+ enforcedSlo: {
1272
+ dropPctMax: t,
1273
+ p99MsMax: n
1274
+ }
1275
+ }
1276
+ };
1277
+ }
1278
+ async function N(e = {}) {
1279
+ let t = await vt(e);
1280
+ return {
1281
+ policy: t,
1282
+ enforcer: xt(t)
1283
+ };
1284
+ }
1285
+ function St(e) {
1286
+ return bt(e);
1287
+ }
1288
+ //#endregion
1289
+ //#region src/mcpGateway.ts
1290
+ var Ct = [
1291
+ "tools/call",
1292
+ "resources/read",
1293
+ "prompts/get"
1294
+ ];
1295
+ function wt(e) {
1296
+ return JSON.stringify(e);
1297
+ }
1298
+ function Tt(e, t, n) {
1299
+ return wt({
1300
+ jsonrpc: "2.0",
1301
+ id: e,
1302
+ error: {
1303
+ code: t,
1304
+ message: n
1305
+ }
1306
+ });
1307
+ }
1308
+ function Et(e) {
1309
+ let t = JSON.parse(e);
1310
+ return t.jsonrpc !== "2.0" || typeof t.method != "string" || t.method.length === 0 || typeof t.id != "string" && typeof t.id != "number" ? null : {
1311
+ jsonrpc: "2.0",
1312
+ id: t.id,
1313
+ method: t.method,
1314
+ params: t.params
1315
+ };
1316
+ }
1317
+ function Dt(e) {
1318
+ return e.includes("not allowed") ? -32601 : e.includes("not authorized") ? -32001 : e.includes("rate-limited") ? -32002 : -32603;
1319
+ }
1320
+ function Ot(e) {
1321
+ let t = e.gatewayAgentId ?? "agent.gateway", n = e.workerAgentId ?? "agent.worker", r = e.allowedMethods ?? Ct, i = e.workerCapabilityPrefix ?? "mcp.", a = e.gatewayWireFormat ?? "compact", o = e.workerWireFormat ?? "compact";
1322
+ async function s(t) {
1323
+ e.onAuditEvent && await e.onAuditEvent({
1324
+ ...t,
1325
+ timestampMs: Date.now()
1326
+ });
1327
+ }
1328
+ let c = at({
1329
+ agentId: t,
1330
+ outboundSecret: e.sharedSecret,
1331
+ sharedSecrets: { [n]: e.sharedSecret },
1332
+ wireFormat: a
1333
+ }), l = at({
1334
+ agentId: n,
1335
+ outboundSecret: e.sharedSecret,
1336
+ sharedSecrets: { [t]: e.sharedSecret },
1337
+ wireFormat: o,
1338
+ onTask: async (e) => ({
1339
+ intent: "RESULT",
1340
+ content: wt({
1341
+ ok: !0,
1342
+ capability: e.body.capability,
1343
+ content: e.body.content
1344
+ }),
1345
+ capability: e.body.capability?.startsWith(i) ? e.body.capability : `${i}${e.body.capability ?? "unknown"}`
1346
+ })
1347
+ });
1348
+ return { async handleLine(t) {
1349
+ let i = t.trim();
1350
+ if (!i) return null;
1351
+ let a = null;
1352
+ try {
1353
+ let t = Et(i);
1354
+ if (!t) return await s({
1355
+ phase: "request_error",
1356
+ code: -32600,
1357
+ message: "Invalid Request"
1358
+ }), Tt(null, -32600, "Invalid Request");
1359
+ a = t.id, await s({
1360
+ phase: "request_received",
1361
+ id: t.id,
1362
+ method: t.method
1363
+ });
1364
+ let o = await dt(c, t, {
1365
+ recipient: n,
1366
+ allowedMethods: r,
1367
+ methodToCapability: e.methodToCapability,
1368
+ authorizeMethod: e.authorizeMethod,
1369
+ rateLimitKey: e.rateLimitKey,
1370
+ rateLimiter: e.rateLimiter,
1371
+ onPolicyEvent: async (e) => {
1372
+ await s({
1373
+ phase: "policy",
1374
+ id: t.id,
1375
+ method: t.method,
1376
+ policy: e
1377
+ });
1378
+ }
1379
+ }), u = null;
1380
+ if (await l.handleRaw(o, async (e) => {
1381
+ u = e;
1382
+ }), !u) return await s({
1383
+ phase: "verification_failed",
1384
+ id: t.id,
1385
+ method: t.method,
1386
+ code: -32603,
1387
+ message: "AIP worker did not produce a response"
1388
+ }), Tt(a, -32603, "AIP worker did not produce a response");
1389
+ let d = await c.receiveRaw(u);
1390
+ return !d.ok || !d.received ? (await s({
1391
+ phase: "verification_failed",
1392
+ id: t.id,
1393
+ method: t.method,
1394
+ code: -32603,
1395
+ message: "AIP verification failed"
1396
+ }), Tt(a, -32603, "AIP verification failed")) : (await s({
1397
+ phase: "request_success",
1398
+ id: t.id,
1399
+ method: t.method
1400
+ }), wt(ft(d.received, t.id)));
1401
+ } catch (e) {
1402
+ let t = e instanceof Error ? e.message : "Internal error", n = Dt(t);
1403
+ return await s({
1404
+ phase: "request_error",
1405
+ id: a,
1406
+ code: n,
1407
+ message: t
1408
+ }), Tt(a, n, t);
1409
+ }
1410
+ } };
1411
+ }
1412
+ async function kt(e) {
1413
+ if (!e.runtimePolicy?.enabled) return Ot(e);
1414
+ let { enforcer: t } = await N(e.runtimePolicy.options);
1415
+ t.assertInvariant({
1416
+ signatureVerification: !0,
1417
+ canonicalization: !0,
1418
+ replayDefense: !0,
1419
+ ttlClockSkewEnforcement: !0
1420
+ });
1421
+ let n = t.selectMode({
1422
+ concurrency: e.runtimePolicy.concurrencyHint ?? 1,
1423
+ latencySensitive: e.runtimePolicy.latencySensitive,
1424
+ compatibilityFirst: e.runtimePolicy.compatibilityFirst
1425
+ }), r = n.includes("binary") ? "binary" : "compact";
1426
+ return Ot({
1427
+ ...e,
1428
+ gatewayWireFormat: r,
1429
+ workerWireFormat: r,
1430
+ gatewayAgentId: e.gatewayAgentId,
1431
+ workerAgentId: e.workerAgentId,
1432
+ onAuditEvent: async (t) => {
1433
+ e.onAuditEvent && await e.onAuditEvent({
1434
+ ...t,
1435
+ message: t.message ?? `policy-mode=${n};wire-format=${r}`
1436
+ });
1437
+ }
1438
+ });
1439
+ }
1440
+ //#endregion
1441
+ //#region src/runtimePolicyManager.ts
1442
+ var At = class {
1443
+ snapshot = null;
1444
+ options;
1445
+ constructor(e = {}) {
1446
+ this.options = e;
1447
+ }
1448
+ async loadInitial() {
1449
+ let e = await N(this.options);
1450
+ return this.snapshot = {
1451
+ ...e,
1452
+ loadedAtMs: Date.now()
1453
+ }, this.snapshot;
1454
+ }
1455
+ current() {
1456
+ if (!this.snapshot) throw Error("Runtime policy not loaded. Call loadInitial() first.");
1457
+ return this.snapshot;
1458
+ }
1459
+ async refresh() {
1460
+ let e = this.snapshot;
1461
+ try {
1462
+ let e = await N(this.options);
1463
+ return this.snapshot = {
1464
+ ...e,
1465
+ loadedAtMs: Date.now()
1466
+ }, this.snapshot;
1467
+ } catch (t) {
1468
+ if (e) return e;
1469
+ throw t;
1470
+ }
1471
+ }
1472
+ }, jt = {
1473
+ dev: {
1474
+ environment: "dev",
1475
+ mode: "ws-batch",
1476
+ poolSize: 1,
1477
+ batchSize: 8,
1478
+ inflightCap: 64,
1479
+ retryMaxAttempts: 2
1480
+ },
1481
+ staging: {
1482
+ environment: "staging",
1483
+ mode: "http-binary-batch",
1484
+ poolSize: 2,
1485
+ batchSize: 32,
1486
+ inflightCap: 256,
1487
+ retryMaxAttempts: 3
1488
+ },
1489
+ prod: {
1490
+ environment: "prod",
1491
+ mode: "http-binary-batch",
1492
+ poolSize: 4,
1493
+ batchSize: 64,
1494
+ inflightCap: 1024,
1495
+ retryMaxAttempts: 3
1496
+ }
1497
+ };
1498
+ function Mt(e) {
1499
+ return jt[e];
1500
+ }
1501
+ //#endregion
1502
+ //#region src/policyTelemetryFeedback.ts
1503
+ function Nt(e) {
1504
+ let t = [], n = "normal";
1505
+ return e.dropPct > .1 && (t.push("reduce inflight cap"), t.push("reduce batch size"), t.push("increase retry backoff"), e.mode === "http" && e.concurrency >= 100 && t.push("switch to http-binary-batch"), n = e.dropPct > 2 ? "critical" : "warn"), e.p99Ms > 20 && (t.push("reduce batch size"), t.push("run adaptive benchmark and re-baseline"), n === "normal" && (n = "warn"), e.p99Ms > 100 && (n = "critical")), {
1506
+ severity: n,
1507
+ actions: t
1508
+ };
1509
+ }
1510
+ //#endregion
1511
+ //#region src/redisClient.ts
1512
+ var Pt = class {
1513
+ entries = /* @__PURE__ */ new Map();
1514
+ now;
1515
+ constructor(e = {}) {
1516
+ this.now = e.now ?? (() => Date.now());
1517
+ }
1518
+ live(e) {
1519
+ let t = this.entries.get(e);
1520
+ if (t) {
1521
+ if (t.expiresAt !== void 0 && t.expiresAt <= this.now()) {
1522
+ this.entries.delete(e);
1523
+ return;
1524
+ }
1525
+ return t;
1526
+ }
1527
+ }
1528
+ async set(e, t, n = {}) {
1529
+ if (n.nx && this.live(e)) return null;
1530
+ let r = n.pxMs === void 0 ? void 0 : this.now() + n.pxMs;
1531
+ return this.entries.set(e, {
1532
+ value: t,
1533
+ expiresAt: r
1534
+ }), "OK";
1535
+ }
1536
+ async get(e) {
1537
+ return this.live(e)?.value ?? null;
1538
+ }
1539
+ async del(e) {
1540
+ let t = this.live(e) !== void 0;
1541
+ return this.entries.delete(e), +!!t;
1542
+ }
1543
+ pipeline() {
1544
+ let e = [], t = {
1545
+ set: (n, r, i) => (e.push({
1546
+ key: n,
1547
+ value: r,
1548
+ options: i
1549
+ }), t),
1550
+ exec: async () => {
1551
+ let t = [];
1552
+ for (let n of e) t.push(await this.set(n.key, n.value, n.options));
1553
+ return t;
1554
+ }
1555
+ };
1556
+ return t;
1557
+ }
1558
+ }, Ft = class {
1559
+ keyPrefix;
1560
+ client;
1561
+ constructor(e = {}) {
1562
+ if (this.keyPrefix = e.keyPrefix ?? "7h3:nonce:", e.client) this.client = e.client;
1563
+ else {
1564
+ let e = new Pt();
1565
+ this.client = {
1566
+ set: (t, n, r) => e.set(t, n, {
1567
+ nx: r?.nx,
1568
+ pxMs: r?.px
1569
+ }),
1570
+ get: (t) => e.get ? e.get(t) : Promise.resolve(null),
1571
+ del: (t) => e.del ? e.del(t) : Promise.resolve(0),
1572
+ quit: () => Promise.resolve()
1573
+ };
1574
+ }
1575
+ }
1576
+ async check(e, t) {
1577
+ let n = `${this.keyPrefix}${e}`;
1578
+ return await this.client.set(n, "1", {
1579
+ nx: !0,
1580
+ px: Math.max(1, t)
1581
+ }) === null;
1582
+ }
1583
+ }, It = class {
1584
+ nodes;
1585
+ constructor(e) {
1586
+ this.nodes = e;
1587
+ }
1588
+ async check(e, t) {
1589
+ return (await Promise.all(this.nodes.map((n) => n.check(e, t)))).some((e) => e);
1590
+ }
1591
+ };
1592
+ function Lt(e, t = {}) {
1593
+ return Rt(e) ? Bt(e, t) : new Ft(e);
1594
+ }
1595
+ function Rt(e) {
1596
+ return typeof e == "object" && !!e && typeof e.set == "function" && (typeof e.pipeline == "function" || !("quit" in e));
1597
+ }
1598
+ function zt(e) {
1599
+ return new It(e.map((e) => new Ft({ redisUrl: e })));
1600
+ }
1601
+ function Bt(e, t = {}) {
1602
+ let n = t.keyPrefix ?? "aip:replay:", r = t.errorBehavior ?? "fallback", i = t.onDegraded, a = t.fallback ?? (r === "fallback" ? Bt(new Pt(), {
1603
+ keyPrefix: n,
1604
+ errorBehavior: "reject"
1605
+ }) : void 0);
1606
+ function o(e, t, n, o) {
1607
+ return i?.(e, {
1608
+ key: t,
1609
+ behavior: r
1610
+ }), r === "allow" ? !0 : r === "reject" ? !1 : a ? a.reserve(t, n, o) : !1;
1611
+ }
1612
+ return {
1613
+ async reserve(t, r, i) {
1614
+ let a = Math.max(1, r - i);
1615
+ try {
1616
+ return await e.set(`${n}${t}`, "1", {
1617
+ nx: !0,
1618
+ pxMs: a
1619
+ }) === "OK";
1620
+ } catch (e) {
1621
+ return o(e, t, r, i);
1622
+ }
1623
+ },
1624
+ async reserveMany(t, r) {
1625
+ if (t.length === 0) return [];
1626
+ if (e.pipeline) try {
1627
+ let i = e.pipeline();
1628
+ for (let { key: e, expiresAtMs: a } of t) i.set(`${n}${e}`, "1", {
1629
+ nx: !0,
1630
+ pxMs: Math.max(1, a - r)
1631
+ });
1632
+ return (await i.exec()).map((e) => e === "OK");
1633
+ } catch (e) {
1634
+ return Promise.all(t.map((t) => o(e, t.key, t.expiresAtMs, r)));
1635
+ }
1636
+ return Promise.all(t.map((e) => this.reserve(e.key, e.expiresAtMs, r)));
1637
+ }
1638
+ };
1639
+ }
1640
+ //#endregion
1641
+ //#region src/revocation.ts
1642
+ var Vt = class {
1643
+ revoked = /* @__PURE__ */ new Map();
1644
+ now;
1645
+ constructor(e = {}) {
1646
+ this.now = e.now ?? (() => Date.now());
1647
+ }
1648
+ makeKey(e, t) {
1649
+ return `${e}${t}`;
1650
+ }
1651
+ isRevoked(e, t, n = this.now()) {
1652
+ let r = this.revoked.get(this.makeKey(e, t));
1653
+ return r === void 0 ? !1 : r <= n ? (this.revoked.delete(this.makeKey(e, t)), !1) : !0;
1654
+ }
1655
+ revoke(e, t, n = {}) {
1656
+ this.revoked.set(this.makeKey(e, t), n.untilMs ?? Infinity);
1657
+ }
1658
+ };
1659
+ function Ht(e, t = {}) {
1660
+ let n = t.keyPrefix ?? "aip:revoked:", r = t.errorBehavior ?? "reject", i = t.cacheTtlMs ?? 5e3, a = t.onDegraded, o = t.now ?? (() => Date.now()), s = /* @__PURE__ */ new Map();
1661
+ function c(e, t) {
1662
+ return `${n}${e}${t}`;
1663
+ }
1664
+ return {
1665
+ async isRevoked(t, n, l = o()) {
1666
+ let u = c(t, n), d = s.get(u);
1667
+ if (d && d.freshUntil > l) return d.revoked;
1668
+ try {
1669
+ if (!e.get) throw Error("RedisLikeClient.get is required for revocation reads");
1670
+ let t = await e.get(u) !== null;
1671
+ return s.set(u, {
1672
+ revoked: t,
1673
+ freshUntil: l + i
1674
+ }), t;
1675
+ } catch (e) {
1676
+ return a?.(e, {
1677
+ sender: t,
1678
+ keyId: n
1679
+ }), d ? d.revoked : r === "reject";
1680
+ }
1681
+ },
1682
+ async revoke(t, n, r = {}) {
1683
+ let a = c(t, n), l = r.untilMs === void 0 ? void 0 : Math.max(1, r.untilMs - o());
1684
+ await e.set(a, "1", l === void 0 ? void 0 : { pxMs: l }), s.set(a, {
1685
+ revoked: !0,
1686
+ freshUntil: o() + i
1687
+ });
1688
+ }
1689
+ };
1690
+ }
1691
+ function Ut(e, t, n = {}) {
1692
+ let r = n.nowMsProvider ?? (() => Date.now());
1693
+ return async (n, i) => {
1694
+ if (!await t.isRevoked(i, n.keyId, r())) return e(n, i);
1695
+ };
1696
+ }
1697
+ //#endregion
1698
+ //#region src/mcpWrapper.ts
1699
+ function Wt(e, t, n) {
1700
+ return {
1701
+ jsonrpc: "2.0",
1702
+ id: e,
1703
+ error: {
1704
+ code: t,
1705
+ message: n
1706
+ }
1707
+ };
1708
+ }
1709
+ function Gt(e, t) {
1710
+ return {
1711
+ requireSignature: !0,
1712
+ ...e.receive,
1713
+ replayCache: t
1714
+ };
1715
+ }
1716
+ function Kt(e, t) {
1717
+ let n = t.wireFormat ?? "compact", r = t.ttlMs ?? 6e4, i = Gt(t, t.receive?.replayCache ?? new A());
1718
+ async function a(e) {
1719
+ return j(await t.sign(e), n);
1720
+ }
1721
+ function o(e, n, i, o) {
1722
+ return a(D({
1723
+ sender: t.selfAgentId,
1724
+ recipient: e,
1725
+ intent: n,
1726
+ content: JSON.stringify(i),
1727
+ correlationId: o,
1728
+ ttlMs: r
1729
+ }));
1730
+ }
1731
+ return async (n) => {
1732
+ let r = await M(n, i), a = r.envelope?.header.sender, s = r.envelope?.header.messageId;
1733
+ if (!r.ok || !r.envelope) return o(a, "ERROR", Wt(null, -32600, r.diagnostics.find((e) => e.level === "error")?.message ?? "AIP verification failed"), s);
1734
+ if (r.envelope.header.recipient !== t.selfAgentId) return o(a, "ERROR", Wt(null, -32600, "Recipient mismatch: envelope not addressed to this agent"), s);
1735
+ let c;
1736
+ try {
1737
+ c = JSON.parse(r.envelope.body.content);
1738
+ } catch {
1739
+ return o(a, "ERROR", Wt(null, -32700, "Parse error: envelope body is not JSON-RPC"), s);
1740
+ }
1741
+ let l;
1742
+ try {
1743
+ l = await e(c);
1744
+ } catch (e) {
1745
+ l = Wt(c.id ?? null, -32603, e instanceof Error ? e.message : "Internal error");
1746
+ }
1747
+ return o(r.envelope.header.sender, "RESULT", l, s);
1748
+ };
1749
+ }
1750
+ function qt(e) {
1751
+ let t = e.wireFormat ?? "compact", n = e.ttlMs ?? 6e4, r = Gt(e, e.receive?.replayCache ?? new A());
1752
+ return {
1753
+ async encodeRequest(r) {
1754
+ let i = D({
1755
+ sender: e.selfAgentId,
1756
+ recipient: e.peerAgentId,
1757
+ intent: "TASK",
1758
+ content: JSON.stringify(r),
1759
+ ttlMs: n
1760
+ });
1761
+ return {
1762
+ raw: j(await e.sign(i), t),
1763
+ messageId: i.header.messageId
1764
+ };
1765
+ },
1766
+ async decodeResponse(t, n = {}) {
1767
+ let i = await M(t, r);
1768
+ if (!i.ok || !i.envelope) {
1769
+ let e = i.diagnostics.find((e) => e.level === "error")?.message ?? "unknown";
1770
+ throw Error(`AIP response verification failed: ${e}`);
1771
+ }
1772
+ if (!e.peerAgentId) throw Error("createMcpClientCodec requires peerAgentId to bind the response sender");
1773
+ if (i.envelope.header.sender !== e.peerAgentId) throw Error(`AIP response sender '${i.envelope.header.sender}' is not the expected peer '${e.peerAgentId}'`);
1774
+ if (n.expectCorrelationId !== void 0 && i.envelope.body.correlationId !== n.expectCorrelationId) throw Error(`AIP response correlationId '${i.envelope.body.correlationId ?? ""}' does not match request '${n.expectCorrelationId}'`);
1775
+ return JSON.parse(i.envelope.body.content);
1776
+ }
1777
+ };
1778
+ }
1779
+ function Jt(e, t) {
1780
+ let n = qt(t);
1781
+ return async (t) => {
1782
+ let { raw: r, messageId: i } = await n.encodeRequest(t);
1783
+ return n.decodeResponse(await e(r), { expectCorrelationId: i });
1784
+ };
1785
+ }
1786
+ //#endregion
1787
+ //#region src/mcpTransports.ts
1788
+ var P = /* @__PURE__ */ c((/* @__PURE__ */ o(((e, t) => {
1789
+ t.exports = {};
1790
+ })))(), 1);
1791
+ function Yt(e) {
1792
+ if (typeof e != "string") throw Error("stdio adapter supports json/compact (string) wire formats; use the HTTP adapter for binary");
1793
+ return e;
1794
+ }
1795
+ function Xt(e, t = {}) {
1796
+ let n = t.input ?? process.stdin, r = t.output ?? process.stdout, i = P.default.createInterface({
1797
+ input: n,
1798
+ crlfDelay: Infinity
1799
+ }), a = Promise.resolve(), o = (n) => {
1800
+ let i = n.trim();
1801
+ i && (a = a.then(async () => {
1802
+ try {
1803
+ let t = await e(i);
1804
+ r.write(`${Yt(t)}\n`);
1805
+ } catch (e) {
1806
+ t.onError?.(e);
1807
+ }
1808
+ }));
1809
+ };
1810
+ return i.on("line", o), { close() {
1811
+ i.off("line", o), i.close();
1812
+ } };
1813
+ }
1814
+ function Zt(e) {
1815
+ let t = P.default.createInterface({
1816
+ input: e.input,
1817
+ crlfDelay: Infinity
1818
+ }), n = [], r = (e) => {
1819
+ let t = e.trim();
1820
+ if (!t) return;
1821
+ let r = n.shift();
1822
+ r && r(t);
1823
+ };
1824
+ return t.on("line", r), {
1825
+ send(t) {
1826
+ let r = Yt(t);
1827
+ return new Promise((t) => {
1828
+ n.push(t), e.output.write(`${r}\n`);
1829
+ });
1830
+ },
1831
+ close() {
1832
+ t.off("line", r), t.close();
1833
+ }
1834
+ };
1835
+ }
1836
+ function Qt(e, t = {}) {
1837
+ return (n, r) => {
1838
+ let i = [];
1839
+ n.on("data", (e) => i.push(e)), n.on("error", () => {
1840
+ r.writeHead(400), r.end();
1841
+ }), n.on("end", () => {
1842
+ (async () => {
1843
+ try {
1844
+ let n = Buffer.concat(i), a = await e(t.binary ? new Uint8Array(n) : n.toString("utf8"));
1845
+ typeof a == "string" ? (r.writeHead(200, { "content-type": "application/json" }), r.end(a)) : (r.writeHead(200, { "content-type": "application/octet-stream" }), r.end(Buffer.from(a)));
1846
+ } catch (e) {
1847
+ r.writeHead(500, { "content-type": "application/json" }), r.end(JSON.stringify({
1848
+ jsonrpc: "2.0",
1849
+ id: null,
1850
+ error: {
1851
+ code: -32603,
1852
+ message: e instanceof Error ? e.message : "internal error"
1853
+ }
1854
+ }));
1855
+ }
1856
+ })();
1857
+ });
1858
+ };
1859
+ }
1860
+ function $t(e) {
1861
+ let t = e.fetchImpl ?? fetch, n = e.binary ? "application/octet-stream" : "application/json";
1862
+ return { async send(r) {
1863
+ let i = await t(e.url, {
1864
+ method: "POST",
1865
+ headers: {
1866
+ "content-type": n,
1867
+ ...e.headers
1868
+ },
1869
+ body: typeof r == "string" ? r : Buffer.from(r)
1870
+ });
1871
+ return e.binary ? new Uint8Array(await i.arrayBuffer()) : i.text();
1872
+ } };
1873
+ }
1874
+ //#endregion
1875
+ //#region src/keyRegistry.ts
1876
+ function en(e) {
1877
+ return { async getPublicKey(t) {
1878
+ return e[t] ?? null;
1879
+ } };
1880
+ }
1881
+ function tn(...e) {
1882
+ return {
1883
+ async getPublicKey(t) {
1884
+ for (let n of e) {
1885
+ let e = await n.getPublicKey(t);
1886
+ if (e !== null) return e;
1887
+ }
1888
+ return null;
1889
+ },
1890
+ async getSharedSecret(t) {
1891
+ for (let n of e) {
1892
+ if (!n.getSharedSecret) continue;
1893
+ let e = await n.getSharedSecret(t);
1894
+ if (e !== null) return e;
1895
+ }
1896
+ return null;
1897
+ }
1898
+ };
1899
+ }
1900
+ function nn(e, t) {
1901
+ let n = t?.ttlMs ?? 6e4, r = /* @__PURE__ */ new Map();
1902
+ async function i(e, t) {
1903
+ let i = Date.now(), a = r.get(e);
1904
+ if (a && a.expiresAt > i) return a.value;
1905
+ let o = await t();
1906
+ return r.set(e, {
1907
+ value: o,
1908
+ expiresAt: i + n
1909
+ }), o;
1910
+ }
1911
+ return {
1912
+ async getPublicKey(t) {
1913
+ return i(`pk:${t}`, () => e.getPublicKey(t));
1914
+ },
1915
+ async getSharedSecret(t) {
1916
+ return e.getSharedSecret ? i(`ss:${t}`, () => e.getSharedSecret(t)) : null;
1917
+ }
1918
+ };
1919
+ }
1920
+ //#endregion
1921
+ //#region src/cborCodec.ts
1922
+ var F = new TextEncoder(), rn = new TextDecoder(), I = 0, an = 1, on = 2, L = 3, sn = 4, cn = 5, ln = 7, un = 244, dn = 245, fn = 246, pn = 24, mn = 25, hn = 26, gn = 27, _n = 27, vn = class {
1923
+ chunks = [];
1924
+ encode(e) {
1925
+ return this.chunks = [], this._encode(e), this._concat();
1926
+ }
1927
+ _encode(e) {
1928
+ if (e == null) {
1929
+ this.chunks.push(new Uint8Array([fn]));
1930
+ return;
1931
+ }
1932
+ if (typeof e == "boolean") {
1933
+ this.chunks.push(new Uint8Array([e ? dn : un]));
1934
+ return;
1935
+ }
1936
+ if (typeof e == "number") {
1937
+ this._encodeNumber(e);
1938
+ return;
1939
+ }
1940
+ if (typeof e == "string") {
1941
+ this._encodeString(e);
1942
+ return;
1943
+ }
1944
+ if (e instanceof Uint8Array) {
1945
+ this._encodeByteString(e);
1946
+ return;
1947
+ }
1948
+ if (Array.isArray(e)) {
1949
+ this._encodeArray(e);
1950
+ return;
1951
+ }
1952
+ if (e instanceof Map) {
1953
+ let t = [...e.entries()];
1954
+ this._encodeMapFromAnyEntries(t);
1955
+ return;
1956
+ }
1957
+ if (typeof e == "object") {
1958
+ let t = Object.entries(e);
1959
+ this._encodeMapFromEntries(t);
1960
+ return;
1961
+ }
1962
+ throw Error(`CborEncoder: unsupported type: ${typeof e}`);
1963
+ }
1964
+ _encodeNumber(e) {
1965
+ if (!Number.isFinite(e) || !Number.isInteger(e)) {
1966
+ this.chunks.push(this._float64Header());
1967
+ let t = /* @__PURE__ */ new ArrayBuffer(8);
1968
+ new DataView(t).setFloat64(0, e, !1), this.chunks.push(new Uint8Array(t));
1969
+ return;
1970
+ }
1971
+ e >= 0 ? this._encodeHead(I, e) : this._encodeHead(an, -1 - e);
1972
+ }
1973
+ _float64Header() {
1974
+ return new Uint8Array([251]);
1975
+ }
1976
+ _encodeString(e) {
1977
+ let t = F.encode(e);
1978
+ this._encodeHead(L, t.length), this.chunks.push(t);
1979
+ }
1980
+ _encodeByteString(e) {
1981
+ this._encodeHead(on, e.length), this.chunks.push(e);
1982
+ }
1983
+ _encodeArray(e) {
1984
+ this._encodeHead(sn, e.length);
1985
+ for (let t of e) this._encode(t);
1986
+ }
1987
+ _encodeMapFromAnyEntries(e) {
1988
+ let t = e.map(([e, t]) => {
1989
+ let n;
1990
+ if (typeof e == "number" && Number.isInteger(e)) n = this._encodeHeadBytes(I, e);
1991
+ else {
1992
+ let t = F.encode(String(e)), r = this._encodeHeadBytes(L, t.length);
1993
+ n = this._concatPair(r, t);
1994
+ }
1995
+ return {
1996
+ keyEncoded: n,
1997
+ key: e,
1998
+ value: t
1999
+ };
2000
+ });
2001
+ t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(cn, t.length);
2002
+ for (let { key: e, value: n } of t) {
2003
+ if (typeof e == "number" && Number.isInteger(e)) this._encodeHead(I, e);
2004
+ else {
2005
+ let t = F.encode(String(e));
2006
+ this._encodeHead(L, t.length), this.chunks.push(t);
2007
+ }
2008
+ this._encode(n);
2009
+ }
2010
+ }
2011
+ _encodeMapFromEntries(e) {
2012
+ let t = e.map(([e, t]) => {
2013
+ let n = F.encode(e), r = this._encodeHeadBytes(L, n.length);
2014
+ return {
2015
+ keyBytes: n,
2016
+ keyEncoded: this._concatPair(r, n),
2017
+ value: t
2018
+ };
2019
+ });
2020
+ t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(cn, t.length);
2021
+ for (let { keyBytes: e, value: n } of t) this._encodeHead(L, e.length), this.chunks.push(e), this._encode(n);
2022
+ }
2023
+ _compareBytes(e, t) {
2024
+ let n = Math.min(e.length, t.length);
2025
+ for (let r = 0; r < n; r++) {
2026
+ let n = (e[r] ?? 0) - (t[r] ?? 0);
2027
+ if (n !== 0) return n;
2028
+ }
2029
+ return e.length - t.length;
2030
+ }
2031
+ _concatPair(e, t) {
2032
+ let n = new Uint8Array(e.length + t.length);
2033
+ return n.set(e, 0), n.set(t, e.length), n;
2034
+ }
2035
+ _encodeHead(e, t) {
2036
+ this.chunks.push(this._encodeHeadBytes(e, t));
2037
+ }
2038
+ _encodeHeadBytes(e, t) {
2039
+ let n = e << 5;
2040
+ if (t <= 23) return new Uint8Array([n | t]);
2041
+ if (t <= 255) return new Uint8Array([n | pn, t]);
2042
+ if (t <= 65535) {
2043
+ let e = /* @__PURE__ */ new ArrayBuffer(3), r = new DataView(e);
2044
+ return r.setUint8(0, n | mn), r.setUint16(1, t, !1), new Uint8Array(e);
2045
+ }
2046
+ if (t <= 4294967295) {
2047
+ let e = /* @__PURE__ */ new ArrayBuffer(5), r = new DataView(e);
2048
+ return r.setUint8(0, n | hn), r.setUint32(1, t, !1), new Uint8Array(e);
2049
+ }
2050
+ let r = /* @__PURE__ */ new ArrayBuffer(9), i = new DataView(r);
2051
+ return i.setUint8(0, n | gn), i.setBigUint64(1, BigInt(t), !1), new Uint8Array(r);
2052
+ }
2053
+ _concat() {
2054
+ let e = this.chunks.reduce((e, t) => e + t.length, 0), t = new Uint8Array(e), n = 0;
2055
+ for (let e of this.chunks) t.set(e, n), n += e.length;
2056
+ return t;
2057
+ }
2058
+ }, yn = class {
2059
+ data;
2060
+ offset = 0;
2061
+ decode(e) {
2062
+ return this.data = e, this.offset = 0, this._decode();
2063
+ }
2064
+ _decode() {
2065
+ let e = this._readByte(), t = e >> 5 & 7, n = e & 31;
2066
+ switch (t) {
2067
+ case I: return this._decodeUint(n);
2068
+ case an: return -1 - this._decodeUint(n);
2069
+ case on: {
2070
+ let e = this._decodeUint(n);
2071
+ return this._readBytes(e);
2072
+ }
2073
+ case L: {
2074
+ let e = this._decodeUint(n), t = this._readBytes(e);
2075
+ return rn.decode(t);
2076
+ }
2077
+ case sn: {
2078
+ let e = this._decodeUint(n), t = [];
2079
+ for (let n = 0; n < e; n++) t.push(this._decode());
2080
+ return t;
2081
+ }
2082
+ case cn: {
2083
+ let e = this._decodeUint(n), t = {};
2084
+ for (let n = 0; n < e; n++) {
2085
+ let e = this._decode();
2086
+ t[String(e)] = this._decode();
2087
+ }
2088
+ return t;
2089
+ }
2090
+ case ln:
2091
+ if (n === 20) return !1;
2092
+ if (n === 21) return !0;
2093
+ if (n === 22) return null;
2094
+ if (n === _n) {
2095
+ let e = this._readBytes(8);
2096
+ return new DataView(e.buffer, e.byteOffset, 8).getFloat64(0, !1);
2097
+ }
2098
+ throw Error(`CborDecoder: unsupported simple value ${n}`);
2099
+ default: throw Error(`CborDecoder: unsupported major type ${t}`);
2100
+ }
2101
+ }
2102
+ _decodeUint(e) {
2103
+ if (e <= 23) return e;
2104
+ if (e === pn) return this._readByte();
2105
+ if (e === mn) {
2106
+ let e = this._readBytes(2);
2107
+ return new DataView(e.buffer, e.byteOffset, 2).getUint16(0, !1);
2108
+ }
2109
+ if (e === hn) {
2110
+ let e = this._readBytes(4);
2111
+ return new DataView(e.buffer, e.byteOffset, 4).getUint32(0, !1);
2112
+ }
2113
+ if (e === gn) {
2114
+ let e = this._readBytes(8);
2115
+ return Number(new DataView(e.buffer, e.byteOffset, 8).getBigUint64(0, !1));
2116
+ }
2117
+ throw Error(`CborDecoder: unsupported additional info ${e}`);
2118
+ }
2119
+ _readByte() {
2120
+ if (this.offset >= this.data.length) throw Error("CborDecoder: unexpected end of data");
2121
+ return this.data[this.offset++] ?? 0;
2122
+ }
2123
+ _readBytes(e) {
2124
+ if (this.offset + e > this.data.length) throw Error("CborDecoder: unexpected end of data");
2125
+ let t = this.data.slice(this.offset, this.offset + e);
2126
+ return this.offset += e, t;
2127
+ }
2128
+ };
2129
+ function bn(e) {
2130
+ return new vn().encode(e);
2131
+ }
2132
+ function xn(e) {
2133
+ return new yn().decode(e);
2134
+ }
2135
+ //#endregion
2136
+ //#region src/envelopeCbor.ts
2137
+ var Sn = "application/7h3-cbor";
2138
+ function Cn(e) {
2139
+ let t = /* @__PURE__ */ new Map();
2140
+ t.set(1, e.header.version), t.set(2, e.header.messageId), t.set(3, e.header.timestampMs), t.set(4, e.header.ttlMs), t.set(5, e.header.sender), e.header.recipient !== void 0 && t.set(6, e.header.recipient), t.set(7, e.header.nonce);
2141
+ let n = /* @__PURE__ */ new Map();
2142
+ n.set(1, e.body.intent), n.set(2, e.body.content), e.body.capability !== void 0 && n.set(3, e.body.capability), e.body.correlationId !== void 0 && n.set(4, e.body.correlationId);
2143
+ let r = /* @__PURE__ */ new Map();
2144
+ r.set(1, t), r.set(2, n);
2145
+ let i = e.signature;
2146
+ if (i) {
2147
+ let e = /* @__PURE__ */ new Map();
2148
+ e.set(1, i.alg), e.set(2, i.keyId), e.set(3, i.value), r.set(3, e);
2149
+ }
2150
+ return bn(r);
2151
+ }
2152
+ function wn(e) {
2153
+ let t = xn(e);
2154
+ if (!t || typeof t != "object" || Array.isArray(t)) throw Error("decodeEnvelopeCbor: expected a map at top level");
2155
+ let n = t, r = n[1];
2156
+ if (!r || typeof r != "object" || Array.isArray(r)) throw Error("decodeEnvelopeCbor: missing header map (key 1)");
2157
+ let i = r, a = n[2];
2158
+ if (!a || typeof a != "object" || Array.isArray(a)) throw Error("decodeEnvelopeCbor: missing body map (key 2)");
2159
+ let o = a, s = {
2160
+ header: {
2161
+ version: i[1],
2162
+ messageId: i[2],
2163
+ timestampMs: i[3],
2164
+ ttlMs: i[4],
2165
+ sender: i[5],
2166
+ nonce: i[7]
2167
+ },
2168
+ body: {
2169
+ intent: o[1],
2170
+ content: o[2]
2171
+ }
2172
+ };
2173
+ i[6] !== void 0 && (s.header.recipient = i[6]), o[3] !== void 0 && (s.body.capability = o[3]), o[4] !== void 0 && (s.body.correlationId = o[4]);
2174
+ let c = n[3];
2175
+ if (c != null) {
2176
+ if (typeof c != "object" || Array.isArray(c)) throw Error("decodeEnvelopeCbor: expected signature map at key 3");
2177
+ let e = c;
2178
+ s.signature = {
2179
+ alg: e[1],
2180
+ keyId: e[2],
2181
+ value: e[3]
2182
+ };
2183
+ }
2184
+ return s;
2185
+ }
2186
+ //#endregion
2187
+ //#region src/httpBinding.ts
2188
+ var Tn = "x-7h3-envelope";
2189
+ async function En(e, t, n) {
2190
+ let r = t.headerName ?? "x-7h3-envelope", i = (Array.isArray(e["content-type"]) ? e["content-type"][0] : e["content-type"]) ?? "", a;
2191
+ if (i.includes("7h3-cbor") && n instanceof Uint8Array) try {
2192
+ a = wn(n);
2193
+ } catch (e) {
2194
+ return {
2195
+ ok: !1,
2196
+ reason: "malformed-envelope",
2197
+ detail: e instanceof Error ? e.message : "CBOR decode failed"
2198
+ };
2199
+ }
2200
+ else {
2201
+ let t = e[r], n = Array.isArray(t) ? t[0] : t;
2202
+ if (!n) return {
2203
+ ok: !1,
2204
+ reason: "missing-header"
2205
+ };
2206
+ try {
2207
+ a = JSON.parse(n);
2208
+ } catch {
2209
+ return {
2210
+ ok: !1,
2211
+ reason: "malformed-envelope",
2212
+ detail: "JSON parse failed"
2213
+ };
2214
+ }
2215
+ }
2216
+ if (!a?.signature || !a?.header) return {
2217
+ ok: !1,
2218
+ reason: "malformed-envelope",
2219
+ detail: "missing required fields"
2220
+ };
2221
+ if (t.strictTtl ?? !0) {
2222
+ let e = E(a).filter((e) => e.level === "error");
2223
+ if (e.length > 0) return {
2224
+ ok: !1,
2225
+ reason: "ttl-expired",
2226
+ detail: e.map((e) => e.message).join("; ")
2227
+ };
2228
+ }
2229
+ let o = a.header.sender, s = a.signature.alg;
2230
+ if (s === "ED25519") {
2231
+ let e = await t.keyRegistry.getPublicKey(o);
2232
+ if (!e) return {
2233
+ ok: !1,
2234
+ reason: "unknown-sender",
2235
+ detail: o
2236
+ };
2237
+ if (!await T(a, e)) return {
2238
+ ok: !1,
2239
+ reason: "invalid-signature"
2240
+ };
2241
+ } else if (s === "HS256") {
2242
+ let e = await t.keyRegistry.getSharedSecret?.(a.signature.keyId);
2243
+ if (!e) return {
2244
+ ok: !1,
2245
+ reason: "unknown-sender",
2246
+ detail: a.signature.keyId
2247
+ };
2248
+ if (!await C(a, e)) return {
2249
+ ok: !1,
2250
+ reason: "invalid-signature"
2251
+ };
2252
+ } else return {
2253
+ ok: !1,
2254
+ reason: "malformed-envelope",
2255
+ detail: `unsupported alg: ${String(a.signature.alg)}`
2256
+ };
2257
+ return {
2258
+ ok: !0,
2259
+ envelope: a
2260
+ };
2261
+ }
2262
+ async function Dn(e, t, n) {
2263
+ let r = await w(e, t);
2264
+ if (n?.format === "cbor") {
2265
+ let e = Cn(r);
2266
+ return {
2267
+ headers: { "content-type": Sn },
2268
+ body: e
2269
+ };
2270
+ }
2271
+ return { headers: { [n?.headerName ?? "x-7h3-envelope"]: JSON.stringify(r) } };
2272
+ }
2273
+ async function On(e, t, n, r) {
2274
+ let i = await S(e, t, n);
2275
+ return { headers: { [r?.headerName ?? "x-7h3-envelope"]: JSON.stringify(i) } };
2276
+ }
2277
+ function kn(e) {
2278
+ return async function(t, n, r) {
2279
+ let i = await En(t.headers, e);
2280
+ if (!i.ok) {
2281
+ n.status(401).json({
2282
+ error: "7h3: request verification failed",
2283
+ reason: i.reason,
2284
+ detail: i.detail
2285
+ });
2286
+ return;
2287
+ }
2288
+ t["7h3Envelope"] = i.envelope, r();
2289
+ };
2290
+ }
2291
+ async function An(e, t, n, r) {
2292
+ let { headers: i } = await Dn(t, n, r), a = new Headers(e.headers);
2293
+ for (let [e, t] of Object.entries(i)) a.set(e, t);
2294
+ return new Request(e, { headers: a });
2295
+ }
2296
+ async function jn(e, t) {
2297
+ return An(e, D({
2298
+ sender: t.sender,
2299
+ recipient: t.recipient,
2300
+ ttlMs: t.ttlMs ?? 6e4,
2301
+ intent: "TASK",
2302
+ content: e.url
2303
+ }), t.privateKey, { headerName: t.headerName });
2304
+ }
2305
+ //#endregion
2306
+ //#region src/webhookBinding.ts
2307
+ var R = "x-7h3-sig", z = "x-7h3-ts", Mn = 3e5;
2308
+ function B(e, t) {
2309
+ return `${e}.${t}`;
2310
+ }
2311
+ async function Nn(e, t) {
2312
+ let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await b(B(r, n), t.privateKey);
2313
+ return {
2314
+ [R]: i,
2315
+ [z]: String(r)
2316
+ };
2317
+ }
2318
+ async function Pn(e, t) {
2319
+ let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await de(B(r, n), t.secret);
2320
+ return {
2321
+ [R]: i,
2322
+ [z]: String(r)
2323
+ };
2324
+ }
2325
+ async function Fn(e, t, n) {
2326
+ let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[R], a = t[z];
2327
+ if (!i || !a) return !1;
2328
+ let o = Number(a);
2329
+ if (!Number.isFinite(o)) return !1;
2330
+ let s = n.maxAgeMs ?? 3e5;
2331
+ return Date.now() - o > s ? !1 : x(B(o, r), i, n.publicKey);
2332
+ }
2333
+ async function In(e, t, n) {
2334
+ let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[R], a = t[z];
2335
+ if (!i || !a) return !1;
2336
+ let o = Number(a);
2337
+ if (!Number.isFinite(o)) return !1;
2338
+ let s = n.maxAgeMs ?? 3e5;
2339
+ return Date.now() - o > s ? !1 : fe(B(o, r), i, n.secret);
2340
+ }
2341
+ async function Ln(e, t, n) {
2342
+ if (!await Fn(e, t, n)) throw Error("7h3: webhook signature verification failed");
2343
+ return JSON.parse(e);
2344
+ }
2345
+ //#endregion
2346
+ //#region src/queueBinding.ts
2347
+ async function Rn(e, t) {
2348
+ let n = t.ttlMs ?? 36e5, r = typeof e == "string" ? e : JSON.stringify(e), i = {
2349
+ envelope: await w(D({
2350
+ sender: t.sender,
2351
+ recipient: t.recipient,
2352
+ intent: "TASK",
2353
+ content: r,
2354
+ ttlMs: n
2355
+ }), t.privateKey, t.keyId),
2356
+ payload: e
2357
+ };
2358
+ return JSON.stringify(i);
2359
+ }
2360
+ async function zn(e, t) {
2361
+ let n;
2362
+ try {
2363
+ n = JSON.parse(e);
2364
+ } catch {
2365
+ throw Error("Queue message is not valid JSON");
2366
+ }
2367
+ if (!n.envelope || typeof n.envelope != "object") throw Error("Queue message missing envelope");
2368
+ if (!await T(n.envelope, t.publicKey)) throw Error("Queue message signature verification failed");
2369
+ return {
2370
+ payload: n.payload,
2371
+ envelope: n.envelope
2372
+ };
2373
+ }
2374
+ async function Bn(e, t) {
2375
+ return Promise.all(e.map(async (e) => {
2376
+ try {
2377
+ let { payload: n, envelope: r } = await zn(e, t);
2378
+ return {
2379
+ ok: !0,
2380
+ payload: n,
2381
+ envelope: r
2382
+ };
2383
+ } catch (t) {
2384
+ return {
2385
+ ok: !1,
2386
+ raw: e,
2387
+ error: t instanceof Error ? t.message : String(t)
2388
+ };
2389
+ }
2390
+ }));
2391
+ }
2392
+ //#endregion
2393
+ //#region src/stream.ts
2394
+ var Vn = "x-7h3-stream", V = new TextEncoder();
2395
+ function H() {
2396
+ if (typeof crypto > "u" || !crypto.subtle) throw Error("Web Crypto API is not available in this runtime");
2397
+ return crypto.subtle;
2398
+ }
2399
+ function U(e) {
2400
+ let t = globalThis.Buffer;
2401
+ return (t ? t.from(e).toString("base64") : btoa(String.fromCharCode(...e))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
2402
+ }
2403
+ function W(e) {
2404
+ let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = globalThis.Buffer;
2405
+ if (n) return new Uint8Array(n.from(t, "base64"));
2406
+ let r = atob(t), i = new Uint8Array(r.length);
2407
+ for (let e = 0; e < r.length; e++) i[e] = r.charCodeAt(e);
2408
+ return i;
2409
+ }
2410
+ function G(e) {
2411
+ return e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength);
2412
+ }
2413
+ function Hn() {
2414
+ let e = new Uint8Array(16);
2415
+ return crypto.getRandomValues(e), U(e);
2416
+ }
2417
+ var K = /* @__PURE__ */ new Map(), Un = 128;
2418
+ function Wn(e, t) {
2419
+ let n = `${e}:${t}`, r = K.get(n);
2420
+ if (r) return r;
2421
+ K.size >= Un && K.clear();
2422
+ let i = H(), a = W(e), o = (async () => {
2423
+ let e = await i.importKey("raw", G(a), "HKDF", !1, ["deriveBits"]), n = await i.deriveBits({
2424
+ name: "HKDF",
2425
+ hash: "SHA-256",
2426
+ salt: V.encode(t),
2427
+ info: V.encode("7h3-stream/1")
2428
+ }, e, 256);
2429
+ return i.importKey("raw", n, {
2430
+ name: "HMAC",
2431
+ hash: "SHA-256"
2432
+ }, !1, ["sign"]);
2433
+ })();
2434
+ return o.catch(() => K.delete(n)), K.set(n, o), o;
2435
+ }
2436
+ var q = /* @__PURE__ */ new Map(), Gn = 64;
2437
+ function Kn(e) {
2438
+ let t = q.get(e);
2439
+ if (t) return t;
2440
+ q.size >= Gn && q.clear();
2441
+ let n = H().importKey("pkcs8", G(W(e)), { name: "Ed25519" }, !1, ["sign"]).catch((t) => {
2442
+ throw q.delete(e), t;
2443
+ });
2444
+ return q.set(e, n), n;
2445
+ }
2446
+ var J = /* @__PURE__ */ new Map(), qn = 64;
2447
+ function Jn(e) {
2448
+ let t = J.get(e);
2449
+ if (t) return t;
2450
+ J.size >= qn && J.clear();
2451
+ let n = H().importKey("spki", G(W(e)), { name: "Ed25519" }, !1, ["verify"]).catch((t) => {
2452
+ throw J.delete(e), t;
2453
+ });
2454
+ return J.set(e, n), n;
2455
+ }
2456
+ function Yn(e) {
2457
+ let t = e.map((e) => `${e.i}:${e.d}`);
2458
+ return V.encode(t.join("\n"));
2459
+ }
2460
+ async function Xn(e) {
2461
+ let t = await H().digest("SHA-256", G(e));
2462
+ return new Uint8Array(t);
2463
+ }
2464
+ var Zn = class {
2465
+ opts;
2466
+ seq = 0;
2467
+ accum = [];
2468
+ hmacKeyPromise = null;
2469
+ constructor(e) {
2470
+ this.opts = {
2471
+ nonce: e.nonce ?? Hn(),
2472
+ keyId: e.keyId ?? "stream-key",
2473
+ ...e
2474
+ };
2475
+ }
2476
+ get nonce() {
2477
+ return this.opts.nonce;
2478
+ }
2479
+ getHmacKey() {
2480
+ return this.hmacKeyPromise ||= Wn(this.opts.privateKey, this.opts.nonce), this.hmacKeyPromise;
2481
+ }
2482
+ async computeChunkHmac(e, t) {
2483
+ let n = H(), r = await this.getHmacKey(), i = `${this.opts.nonce}:${e}:${t}`, a = await n.sign("HMAC", r, V.encode(i));
2484
+ return U(new Uint8Array(a));
2485
+ }
2486
+ async writeChunk(e) {
2487
+ let t = this.seq++, n = await this.computeChunkHmac(t, e);
2488
+ return this.accum.push({
2489
+ i: t,
2490
+ d: e
2491
+ }), {
2492
+ i: t,
2493
+ d: e,
2494
+ h: n,
2495
+ f: !1
2496
+ };
2497
+ }
2498
+ async finalize() {
2499
+ let e = H(), t = await Kn(this.opts.privateKey), n = await Xn(Yn(this.accum)), r = await e.sign("Ed25519", t, G(n)), i = U(new Uint8Array(r)), a = this.seq;
2500
+ return {
2501
+ i: a,
2502
+ d: "",
2503
+ h: await this.computeChunkHmac(a, U(n)),
2504
+ f: !0,
2505
+ sig: i,
2506
+ kid: this.opts.keyId
2507
+ };
2508
+ }
2509
+ }, Qn = class {
2510
+ opts;
2511
+ expectedSeq = 0;
2512
+ accum = [];
2513
+ totalBytes = 0;
2514
+ done = !1;
2515
+ constructor(e) {
2516
+ this.opts = e;
2517
+ }
2518
+ async receiveChunk(e) {
2519
+ if (this.done) return {
2520
+ ok: !1,
2521
+ reason: "stream already finalized"
2522
+ };
2523
+ let t = this.opts.maxChunks ?? 1e4;
2524
+ return this.accum.length >= t ? {
2525
+ ok: !1,
2526
+ reason: `exceeded maxChunks (${t})`
2527
+ } : e.i === this.expectedSeq ? (this.expectedSeq++, this.accum.push({
2528
+ i: e.i,
2529
+ d: e.d
2530
+ }), this.totalBytes += V.encode(e.d).length, { ok: !0 }) : {
2531
+ ok: !1,
2532
+ reason: `sequence error: expected ${this.expectedSeq}, got ${e.i}`
2533
+ };
2534
+ }
2535
+ async finalize(e) {
2536
+ if (this.done) return {
2537
+ ok: !1,
2538
+ reason: "stream already finalized"
2539
+ };
2540
+ if (this.done = !0, !e.sig) return {
2541
+ ok: !1,
2542
+ reason: "missing signature on final chunk"
2543
+ };
2544
+ let t = H(), n;
2545
+ try {
2546
+ n = await Jn(this.opts.publicKey);
2547
+ } catch {
2548
+ return {
2549
+ ok: !1,
2550
+ reason: "invalid public key"
2551
+ };
2552
+ }
2553
+ let r = await Xn(Yn(this.accum)), i = W(e.sig);
2554
+ return await t.verify("Ed25519", n, G(i), G(r)) ? {
2555
+ ok: !0,
2556
+ totalBytes: this.totalBytes,
2557
+ chunkCount: this.accum.length
2558
+ } : {
2559
+ ok: !1,
2560
+ reason: "signature verification failed"
2561
+ };
2562
+ }
2563
+ };
2564
+ function $n(e) {
2565
+ return new Zn(e);
2566
+ }
2567
+ function er(e) {
2568
+ return new Qn(e);
2569
+ }
2570
+ async function tr(e, t) {
2571
+ let n = new Zn(t), r = [];
2572
+ if (Array.isArray(e)) for (let t of e) r.push(await n.writeChunk(t));
2573
+ else for await (let t of e) r.push(await n.writeChunk(t));
2574
+ return r.push(await n.finalize()), r;
2575
+ }
2576
+ async function nr(e, t) {
2577
+ let n = new Qn(t), r = e.slice(0, -1), i = e[e.length - 1];
2578
+ if (e.length === 0) return {
2579
+ ok: !1,
2580
+ reason: "empty chunk array — missing final frame"
2581
+ };
2582
+ for (let e of r) {
2583
+ let t = await n.receiveChunk(e);
2584
+ if (!t.ok) return {
2585
+ ok: !1,
2586
+ reason: t.reason,
2587
+ chunkIndex: e.i
2588
+ };
2589
+ }
2590
+ if (!i.f) {
2591
+ let e = await n.receiveChunk(i);
2592
+ return e.ok ? {
2593
+ ok: !1,
2594
+ reason: "missing final frame"
2595
+ } : {
2596
+ ok: !1,
2597
+ reason: e.reason,
2598
+ chunkIndex: i.i
2599
+ };
2600
+ }
2601
+ return n.finalize(i);
2602
+ }
2603
+ function rr(e) {
2604
+ return JSON.stringify(e);
2605
+ }
2606
+ function ir(e) {
2607
+ let t;
2608
+ try {
2609
+ t = JSON.parse(e);
2610
+ } catch {
2611
+ throw Error("decodeStreamChunk: invalid JSON");
2612
+ }
2613
+ let n = t;
2614
+ if (typeof n.i != "number" || typeof n.d != "string" || typeof n.h != "string" || typeof n.f != "boolean") throw Error("decodeStreamChunk: missing required fields (i, d, h, f)");
2615
+ let r = {
2616
+ i: n.i,
2617
+ d: n.d,
2618
+ h: n.h,
2619
+ f: n.f
2620
+ };
2621
+ if (n.sig !== void 0) {
2622
+ if (typeof n.sig != "string") throw Error("decodeStreamChunk: sig must be string");
2623
+ r.sig = n.sig;
2624
+ }
2625
+ if (n.kid !== void 0) {
2626
+ if (typeof n.kid != "string") throw Error("decodeStreamChunk: kid must be string");
2627
+ r.kid = n.kid;
2628
+ }
2629
+ return r;
2630
+ }
2631
+ //#endregion
2632
+ //#region src/wsBinding.ts
2633
+ function ar(e, t) {
2634
+ let n = 0, r = [], i = [];
2635
+ function a(e, n) {
2636
+ t.onVerifyFail?.(e, n);
2637
+ for (let t of i) t(e, n);
2638
+ }
2639
+ let o = async (e) => {
2640
+ let n = typeof e.data == "string" ? e.data : e.data.toString("utf8"), i;
2641
+ try {
2642
+ i = JSON.parse(n);
2643
+ } catch {
2644
+ a(/* @__PURE__ */ Error("malformed frame"), n);
2645
+ return;
2646
+ }
2647
+ let o = i?.header?.sender;
2648
+ if (!o) {
2649
+ a(/* @__PURE__ */ Error("missing sender"), n);
2650
+ return;
2651
+ }
2652
+ let s = await t.keyRegistry.getPublicKey(o);
2653
+ if (!s) {
2654
+ a(/* @__PURE__ */ Error(`unknown sender: ${o}`), n);
2655
+ return;
2656
+ }
2657
+ if (!await T(i, s).catch(() => !1)) {
2658
+ a(/* @__PURE__ */ Error("invalid signature"), n);
2659
+ return;
2660
+ }
2661
+ let c = E(i);
2662
+ if (c.some((e) => e.level === "error")) {
2663
+ a(/* @__PURE__ */ Error(`envelope invalid: ${c.map((e) => e.message).join("; ")}`), n);
2664
+ return;
2665
+ }
2666
+ let l = i.body.content;
2667
+ try {
2668
+ l = JSON.parse(i.body.content);
2669
+ } catch {}
2670
+ for (let e of r) e(l, i);
2671
+ };
2672
+ return e.addEventListener("message", o), e.addEventListener("close", () => {
2673
+ e.removeEventListener("message", o);
2674
+ }), {
2675
+ get seq() {
2676
+ return n;
2677
+ },
2678
+ async send(r) {
2679
+ let i = typeof r == "string" ? r : JSON.stringify(r), a = D({
2680
+ sender: t.sender,
2681
+ recipient: t.recipient,
2682
+ ttlMs: t.ttlMs ?? 3e4,
2683
+ intent: "TASK",
2684
+ content: i
2685
+ });
2686
+ a.body.correlationId = String(++n);
2687
+ let o = await w(a, t.privateKey);
2688
+ e.send(JSON.stringify(o));
2689
+ },
2690
+ onMessage(e) {
2691
+ r.push(e);
2692
+ },
2693
+ onVerifyFail(e) {
2694
+ i.push(e);
2695
+ }
2696
+ };
2697
+ }
2698
+ function or(e, t) {
2699
+ let n = new Zn(t), r = async (t) => {
2700
+ let r = typeof t.data == "string" ? t.data : t.data.toString("utf8"), i = await n.writeChunk(r);
2701
+ e.send(rr(i));
2702
+ }, i = async () => {
2703
+ e.removeEventListener("message", r), e.removeEventListener("close", i);
2704
+ let t = await n.finalize();
2705
+ e.send(rr(t));
2706
+ };
2707
+ return e.addEventListener("message", r), e.addEventListener("close", i), n;
2708
+ }
2709
+ function sr(e, t) {
2710
+ return new Promise((n, r) => {
2711
+ let i = [], a = async (e) => {
2712
+ let a = typeof e.data == "string" ? e.data : e.data.toString("utf8"), o;
2713
+ try {
2714
+ o = ir(a);
2715
+ } catch (e) {
2716
+ s(), r(e);
2717
+ return;
2718
+ }
2719
+ i.push(o), o.f && (s(), n(await nr(i, t)));
2720
+ }, o = () => {
2721
+ s(), n({
2722
+ ok: !1,
2723
+ reason: "connection closed before final frame"
2724
+ });
2725
+ };
2726
+ function s() {
2727
+ e.removeEventListener("message", a), e.removeEventListener("close", o);
2728
+ }
2729
+ e.addEventListener("message", a), e.addEventListener("close", o);
2730
+ });
2731
+ }
2732
+ //#endregion
2733
+ //#region src/grpcBinding.ts
2734
+ var cr = "7h3-envelope-bin";
2735
+ async function lr(e) {
2736
+ let t = await w(D({
2737
+ sender: e.sender,
2738
+ recipient: e.recipient,
2739
+ ttlMs: e.ttlMs ?? 6e4,
2740
+ intent: "TASK",
2741
+ content: "grpc-call"
2742
+ }), e.privateKey);
2743
+ return { [e.metadataKey ?? "7h3-envelope-bin"]: JSON.stringify(t) };
2744
+ }
2745
+ async function ur(e, t) {
2746
+ let n = e[t.metadataKey ?? "7h3-envelope-bin"], r = Array.isArray(n) ? n[0] : n instanceof Uint8Array ? new TextDecoder().decode(n) : n;
2747
+ if (!r) return {
2748
+ ok: !1,
2749
+ code: 16,
2750
+ message: "7h3: missing gRPC envelope metadata"
2751
+ };
2752
+ let i;
2753
+ try {
2754
+ i = JSON.parse(typeof r == "string" ? r : String(r));
2755
+ } catch {
2756
+ return {
2757
+ ok: !1,
2758
+ code: 3,
2759
+ message: "7h3: malformed envelope metadata"
2760
+ };
2761
+ }
2762
+ if (t.strictTtl !== !1 && E(i).some((e) => e.level === "error")) return {
2763
+ ok: !1,
2764
+ code: 4,
2765
+ message: "7h3: envelope expired or invalid"
2766
+ };
2767
+ let a = i.header?.sender, o = i.signature?.alg;
2768
+ if (!a || !o) return {
2769
+ ok: !1,
2770
+ code: 3,
2771
+ message: "7h3: missing sender or alg"
2772
+ };
2773
+ if (o === "ED25519") {
2774
+ let e = await t.keyRegistry.getPublicKey(a);
2775
+ if (!e) return {
2776
+ ok: !1,
2777
+ code: 16,
2778
+ message: `7h3: unknown sender ${a}`
2779
+ };
2780
+ if (!await T(i, e)) return {
2781
+ ok: !1,
2782
+ code: 16,
2783
+ message: "7h3: invalid signature"
2784
+ };
2785
+ } else if (o === "HS256") {
2786
+ let e = await t.keyRegistry.getSharedSecret?.(i.signature.keyId);
2787
+ if (!e) return {
2788
+ ok: !1,
2789
+ code: 16,
2790
+ message: "7h3: unknown key"
2791
+ };
2792
+ if (!await C(i, e)) return {
2793
+ ok: !1,
2794
+ code: 16,
2795
+ message: "7h3: invalid signature"
2796
+ };
2797
+ } else return {
2798
+ ok: !1,
2799
+ code: 3,
2800
+ message: `7h3: unsupported alg ${String(o)}`
2801
+ };
2802
+ return {
2803
+ ok: !0,
2804
+ envelope: i
2805
+ };
2806
+ }
2807
+ function dr(e, t) {
2808
+ return async (n) => {
2809
+ let r = await ur(n.metadata, t);
2810
+ if (!r.ok) throw Object.assign(Error(r.message), { code: r.code });
2811
+ return n["7h3Envelope"] = r.envelope, e(n);
2812
+ };
2813
+ }
2814
+ //#endregion
2815
+ //#region src/keyInfra.ts
2816
+ function fr(e) {
2817
+ return JSON.stringify(e);
2818
+ }
2819
+ function pr(e) {
2820
+ let t = JSON.parse(e);
2821
+ if (t.version !== "7h3/0.1") throw Error(`unsupported version: ${t.version}`);
2822
+ return t;
2823
+ }
2824
+ async function mr(e, t) {
2825
+ let n = e.replace(/\/$/, "") + "/.well-known/7h3-keys", r = new AbortController(), i = t?.timeout ? setTimeout(() => r.abort(), t.timeout) : void 0;
2826
+ try {
2827
+ let e = await fetch(n, { signal: r.signal });
2828
+ if (!e.ok) throw Error(`HTTP ${e.status} from ${n}`);
2829
+ return pr(await e.text());
2830
+ } finally {
2831
+ i !== void 0 && clearTimeout(i);
2832
+ }
2833
+ }
2834
+ function hr(e) {
2835
+ let t = /* @__PURE__ */ new Map(), n = e?.cacheMs ?? 6e4, r = e?.timeout ?? 5e3;
2836
+ async function i(e) {
2837
+ let i = Date.now(), a = t.get(e);
2838
+ if (a && a.expiresAt > i) return a.doc;
2839
+ let o = await mr(e, { timeout: r });
2840
+ return t.set(e, {
2841
+ doc: o,
2842
+ expiresAt: i + n
2843
+ }), o;
2844
+ }
2845
+ return { async getPublicKey(e) {
2846
+ let t = e.includes("@") ? e.split("@")[1] : e.split(".").slice(-2).join(".");
2847
+ if (!t) return null;
2848
+ try {
2849
+ let n = await i(`https://${t}`), r = Date.now();
2850
+ return n.keys.find((t) => (t.id === e || t.id === e.split("@")[0]) && !t.revoked && (!t.expires || t.expires > r))?.publicKey ?? null;
2851
+ } catch {
2852
+ return null;
2853
+ }
2854
+ } };
2855
+ }
2856
+ var gr = class {
2857
+ maxAgeMs;
2858
+ overlapMs;
2859
+ keys = [];
2860
+ constructor(e) {
2861
+ this.maxAgeMs = e.maxAgeMs, this.overlapMs = e.overlapMs ?? Math.floor(e.maxAgeMs * .1);
2862
+ }
2863
+ addKey(e) {
2864
+ this.keys.push(e);
2865
+ }
2866
+ getCurrentKey() {
2867
+ let e = Date.now(), t = this.keys.filter((t) => !t.expiresAt || t.expiresAt > e);
2868
+ return t.length === 0 ? null : t.reduce((e, t) => e.createdAt > t.createdAt ? e : t);
2869
+ }
2870
+ async rotateIfNeeded() {
2871
+ let e = Date.now(), t = this.getCurrentKey();
2872
+ if (t && e - t.createdAt < this.maxAgeMs - this.overlapMs) return null;
2873
+ t && !t.expiresAt && (t.expiresAt = e + this.overlapMs);
2874
+ let { publicKey: n, privateKey: r } = await pe(), i = {
2875
+ id: `key-${e}-${y(4)}`,
2876
+ publicKey: n,
2877
+ privateKey: r,
2878
+ createdAt: e
2879
+ };
2880
+ return this.keys.push(i), i;
2881
+ }
2882
+ getWellKnownDocument() {
2883
+ let e = Date.now();
2884
+ return {
2885
+ version: "7h3/0.1",
2886
+ updated: e,
2887
+ keys: this.keys.map((t) => ({
2888
+ id: t.id,
2889
+ algorithm: "Ed25519",
2890
+ publicKey: t.publicKey,
2891
+ created: t.createdAt,
2892
+ ...t.expiresAt ? { expires: t.expiresAt } : {},
2893
+ ...t.expiresAt && t.expiresAt < e ? {
2894
+ revoked: !0,
2895
+ revokedAt: t.expiresAt
2896
+ } : {}
2897
+ }))
2898
+ };
2899
+ }
2900
+ toKeyRegistry() {
2901
+ return { getPublicKey: async (e) => {
2902
+ let t = Date.now();
2903
+ return this.keys.find((n) => n.id === e && (!n.expiresAt || n.expiresAt > t))?.publicKey ?? this.getCurrentKey()?.publicKey ?? null;
2904
+ } };
2905
+ }
2906
+ }, _r = class {
2907
+ revoked = /* @__PURE__ */ new Map();
2908
+ revoke(e, t) {
2909
+ this.revoked.set(e, {
2910
+ id: e,
2911
+ revokedAt: Date.now(),
2912
+ reason: t
2913
+ });
2914
+ }
2915
+ isRevoked(e) {
2916
+ return this.revoked.has(e);
2917
+ }
2918
+ getList() {
2919
+ return {
2920
+ version: "7h3/0.1",
2921
+ updated: Date.now(),
2922
+ revokedKeys: [...this.revoked.values()]
2923
+ };
2924
+ }
2925
+ importList(e) {
2926
+ for (let t of e.revokedKeys) this.revoked.has(t.id) || this.revoked.set(t.id, t);
2927
+ }
2928
+ wrapRegistry(e) {
2929
+ let t = this;
2930
+ return {
2931
+ async getPublicKey(n) {
2932
+ return t.isRevoked(n) ? null : e.getPublicKey(n);
2933
+ },
2934
+ getSharedSecret: e.getSharedSecret?.bind(e)
2935
+ };
2936
+ }
2937
+ }, vr = class {
2938
+ windows = /* @__PURE__ */ new Map();
2939
+ check(e, t, n = Date.now()) {
2940
+ let r = n - t.windowMs, i = (this.windows.get(e) ?? []).filter((e) => e > r), a = i.length, o = a < t.requests;
2941
+ return {
2942
+ allowed: o,
2943
+ remaining: Math.max(0, t.requests - a - +!!o),
2944
+ resetMs: i.length > 0 ? Math.max(0, i[0] + t.windowMs - n) : 0
2945
+ };
2946
+ }
2947
+ consume(e, t, n = Date.now()) {
2948
+ let r = n - t.windowMs, i = (this.windows.get(e) ?? []).filter((e) => e > r), a = i.length < t.requests;
2949
+ return a && (i.push(n), this.windows.set(e, i)), {
2950
+ allowed: a,
2951
+ remaining: Math.max(0, t.requests - i.length),
2952
+ resetMs: i.length > 0 ? Math.max(0, i[0] + t.windowMs - n) : 0
2953
+ };
2954
+ }
2955
+ reset(e) {
2956
+ this.windows.delete(e);
2957
+ }
2958
+ clear() {
2959
+ this.windows.clear();
2960
+ }
2961
+ }, yr = new vr();
2962
+ //#endregion
2963
+ //#region src/routePolicy.ts
2964
+ function br(e, t) {
2965
+ let n = "^", r = 0;
2966
+ for (; r < e.length;) {
2967
+ let t = e[r];
2968
+ t === "*" ? e[r + 1] === "*" ? (n += ".*", r += 2) : (n += "[^/]*", r += 1) : t === "?" ? (n += "[^/]", r += 1) : (n += t.replace(/[.+^${}()|[\]\\]/g, "\\$&"), r += 1);
2969
+ }
2970
+ return n += "$", new RegExp(n).test(t);
2971
+ }
2972
+ function xr(e, t) {
2973
+ for (let n of e) if (br(n.path, t)) return n;
2974
+ return null;
2975
+ }
2976
+ function Sr(e, t) {
2977
+ return !e.allowedSenders || e.allowedSenders.length === 0 ? !0 : e.allowedSenders.includes(t);
2978
+ }
2979
+ //#endregion
2980
+ //#region src/signedResponse.ts
2981
+ var Cr = "x-7h3-response";
2982
+ async function wr(e, t) {
2983
+ let n = await w(D({
2984
+ sender: t.sender,
2985
+ recipient: t.recipient,
2986
+ intent: "RESULT",
2987
+ content: e,
2988
+ correlationId: t.correlationId,
2989
+ ttlMs: t.ttlMs ?? 6e4
2990
+ }), t.privateKey);
2991
+ return { headers: { [Cr]: JSON.stringify(n) } };
2992
+ }
2993
+ async function Tr(e, t, n) {
2994
+ let r = t[Cr], i = Array.isArray(r) ? r[0] : r;
2995
+ if (!i) return {
2996
+ ok: !1,
2997
+ reason: "missing-header"
2998
+ };
2999
+ let a;
3000
+ try {
3001
+ a = JSON.parse(i);
3002
+ } catch {
3003
+ return {
3004
+ ok: !1,
3005
+ reason: "malformed-envelope"
3006
+ };
3007
+ }
3008
+ let o = Date.now(), { timestampMs: s, ttlMs: c } = a.header;
3009
+ return s + c < o || n.maxAgeMs !== void 0 && o - s > n.maxAgeMs ? {
3010
+ ok: !1,
3011
+ reason: "ttl-expired",
3012
+ envelope: a
3013
+ } : await T(a, n.publicKey) ? a.body.content === e ? {
3014
+ ok: !0,
3015
+ envelope: a
3016
+ } : {
3017
+ ok: !1,
3018
+ reason: "content-mismatch",
3019
+ envelope: a
3020
+ } : {
3021
+ ok: !1,
3022
+ reason: "invalid-signature",
3023
+ envelope: a
3024
+ };
3025
+ }
3026
+ //#endregion
3027
+ //#region src/telemetry.ts
3028
+ function Y(e) {
3029
+ return !e || Object.keys(e).length === 0 ? "__default__" : Object.entries(e).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}=${t}`).join(",");
3030
+ }
3031
+ function Er(e) {
3032
+ return !e || Object.keys(e).length === 0 ? "" : `{${Object.entries(e).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}="${t}"`).join(",")}}`;
3033
+ }
3034
+ var X = class {
3035
+ counts = /* @__PURE__ */ new Map();
3036
+ labelSets = /* @__PURE__ */ new Map();
3037
+ increment(e) {
3038
+ let t = Y(e);
3039
+ this.counts.set(t, (this.counts.get(t) ?? 0) + 1), this.labelSets.has(t) || this.labelSets.set(t, e);
3040
+ }
3041
+ value(e) {
3042
+ return this.counts.get(Y(e)) ?? 0;
3043
+ }
3044
+ entries() {
3045
+ let e = [];
3046
+ for (let [t, n] of this.counts) e.push({
3047
+ labels: this.labelSets.get(t),
3048
+ value: n
3049
+ });
3050
+ return e;
3051
+ }
3052
+ }, Dr = class {
3053
+ bucketBounds;
3054
+ states = /* @__PURE__ */ new Map();
3055
+ labelSets = /* @__PURE__ */ new Map();
3056
+ constructor(e = [
3057
+ .005,
3058
+ .01,
3059
+ .025,
3060
+ .05,
3061
+ .1,
3062
+ .25,
3063
+ .5,
3064
+ 1,
3065
+ 2.5,
3066
+ 5,
3067
+ 10
3068
+ ]) {
3069
+ this.bucketBounds = [...e].sort((e, t) => e - t);
3070
+ }
3071
+ observe(e, t) {
3072
+ let n = Y(t);
3073
+ this.states.has(n) || (this.states.set(n, {
3074
+ count: 0,
3075
+ sum: 0,
3076
+ observations: []
3077
+ }), this.labelSets.set(n, t));
3078
+ let r = this.states.get(n);
3079
+ r.count++, r.sum += e, r.observations.push(e);
3080
+ }
3081
+ snapshot(e) {
3082
+ let t = Y(e), n = this.states.get(t) ?? {
3083
+ count: 0,
3084
+ sum: 0,
3085
+ observations: []
3086
+ }, r = {};
3087
+ for (let e of this.bucketBounds) r[String(e)] = n.observations.filter((t) => t <= e).length;
3088
+ return r["+Inf"] = n.count, {
3089
+ count: n.count,
3090
+ sum: n.sum,
3091
+ buckets: r
3092
+ };
3093
+ }
3094
+ entries() {
3095
+ let e = [];
3096
+ for (let [t] of this.states) {
3097
+ let n = this.labelSets.get(t);
3098
+ e.push({
3099
+ labels: n,
3100
+ snapshot: this.snapshot(n)
3101
+ });
3102
+ }
3103
+ return e;
3104
+ }
3105
+ getBounds() {
3106
+ return [...this.bucketBounds];
3107
+ }
3108
+ }, Or = class {
3109
+ verifications_total = new X();
3110
+ verification_duration_ms = new Dr([
3111
+ .1,
3112
+ .5,
3113
+ 1,
3114
+ 5,
3115
+ 10,
3116
+ 50,
3117
+ 100
3118
+ ]);
3119
+ rate_limit_hits_total = new X();
3120
+ sender_denials_total = new X();
3121
+ replay_detections_total = new X();
3122
+ audit_entries_total = new X();
3123
+ active_connections = new X();
3124
+ }, Z = new Or();
3125
+ function kr(e, t = "7h3") {
3126
+ let n = [];
3127
+ function r(e, r, i) {
3128
+ let a = `${t}_${e}`;
3129
+ n.push(`# HELP ${a} ${r}`), n.push(`# TYPE ${a} counter`);
3130
+ let o = i.entries();
3131
+ if (o.length === 0) n.push(`${a} 0`);
3132
+ else for (let { labels: e, value: t } of o) e && Object.keys(e).length > 0 ? n.push(`${a}${Er(e)} ${t}`) : n.push(`${a} ${t}`);
3133
+ }
3134
+ function i(e, r, i) {
3135
+ let a = `${t}_${e}`;
3136
+ n.push(`# HELP ${a} ${r}`), n.push(`# TYPE ${a} histogram`);
3137
+ let o = i.entries();
3138
+ if (o.length === 0) {
3139
+ for (let e of i.getBounds()) n.push(`${a}_bucket{le="${e}"} 0`);
3140
+ n.push(`${a}_bucket{le="+Inf"} 0`), n.push(`${a}_sum 0`), n.push(`${a}_count 0`);
3141
+ } else for (let { labels: e, snapshot: t } of o) {
3142
+ let r = e && Object.keys(e).length > 0 ? Er(e) : "";
3143
+ for (let [e, i] of Object.entries(t.buckets)) {
3144
+ if (e === "+Inf") continue;
3145
+ let t = r ? r.slice(0, -1) + `,le="${e}"}` : `{le="${e}"}`;
3146
+ n.push(`${a}_bucket${t} ${i}`);
3147
+ }
3148
+ let i = r ? r.slice(0, -1) + ",le=\"+Inf\"}" : "{le=\"+Inf\"}";
3149
+ n.push(`${a}_bucket${i} ${t.count}`), n.push(`${a}_sum${r} ${t.sum}`), n.push(`${a}_count${r} ${t.count}`);
3150
+ }
3151
+ }
3152
+ return r("verifications_total", "Total number of AIP envelope verifications, by result, algorithm, and transport", e.verifications_total), i("verification_duration_ms", "Verification latency in milliseconds", e.verification_duration_ms), r("rate_limit_hits_total", "Total number of rate-limit rejections, by sender and path", e.rate_limit_hits_total), r("sender_denials_total", "Total number of sender-denied (403) rejections, by sender and path", e.sender_denials_total), r("replay_detections_total", "Total number of replay-detected events, by transport", e.replay_detections_total), r("audit_entries_total", "Total number of audit log entries written, by type", e.audit_entries_total), r("active_connections", "Current active connections, by transport (WS/gRPC)", e.active_connections), n.join("\n") + "\n";
3153
+ }
3154
+ function Ar(e = "/metrics", t = Z, n = "7h3") {
3155
+ return (r, i, a) => {
3156
+ if (r.url === e && (r.method === "GET" || r.method === void 0)) {
3157
+ let e = kr(t, n);
3158
+ i.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" }), i.end(e);
3159
+ } else a();
3160
+ };
3161
+ }
3162
+ //#endregion
3163
+ //#region src/capability.ts
3164
+ var jr = "x-7h3-capability";
3165
+ function Mr(e) {
3166
+ let t = [];
3167
+ return e.maxDelegations !== void 0 && t.push(`"maxDelegations":${e.maxDelegations}`), e.methods !== void 0 && t.push(`"methods":${JSON.stringify(e.methods)}`), t.push(`"pathGlob":${JSON.stringify(e.pathGlob)}`), `{${t.join(",")}}`;
3168
+ }
3169
+ function Q(e) {
3170
+ let t = [];
3171
+ t.push(`"delegationDepth":${e.delegationDepth}`), t.push(`"expiresAt":${e.expiresAt}`), t.push(`"id":${JSON.stringify(e.id)}`), t.push(`"issuedAt":${e.issuedAt}`), t.push(`"issuer":${JSON.stringify(e.issuer)}`), t.push(`"keyId":${JSON.stringify(e.keyId)}`), e.maxDelegations !== void 0 && t.push(`"maxDelegations":${e.maxDelegations}`), e.parentTokenId !== void 0 && t.push(`"parentTokenId":${JSON.stringify(e.parentTokenId)}`);
3172
+ let n = `[${e.scopes.map(Mr).join(",")}]`;
3173
+ return t.push(`"scopes":${n}`), t.push(`"subject":${JSON.stringify(e.subject)}`), t.push(`"version":${JSON.stringify(e.version)}`), `{${t.join(",")}}`;
3174
+ }
3175
+ async function Nr(e) {
3176
+ let t = Date.now(), n = `cap-${t}-${y(6)}`, r = e.keyId ?? `${e.issuerId}-key`, i = e.maxDelegations ?? 0, a = {
3177
+ id: n,
3178
+ version: "7h3-cap/1",
3179
+ issuer: e.issuerId,
3180
+ subject: e.subject,
3181
+ scopes: e.scopes,
3182
+ issuedAt: t,
3183
+ expiresAt: t + e.ttlMs,
3184
+ delegationDepth: 0,
3185
+ maxDelegations: i,
3186
+ keyId: r
3187
+ }, o = await b(Q(a), e.issuerPrivateKey);
3188
+ return {
3189
+ ...a,
3190
+ signature: o
3191
+ };
3192
+ }
3193
+ function Pr(e, t) {
3194
+ if (!br(t.pathGlob, e.pathGlob)) return !1;
3195
+ if (t.methods !== void 0) {
3196
+ if (e.methods === void 0) return !1;
3197
+ for (let n of e.methods) if (!t.methods.includes(n)) return !1;
3198
+ }
3199
+ return !0;
3200
+ }
3201
+ function Fr(e, t) {
3202
+ for (let n of e) if (!t.some((e) => Pr(n, e))) return !1;
3203
+ return !0;
3204
+ }
3205
+ async function Ir(e) {
3206
+ let { parentToken: t, delegatorId: n, newSubject: r } = e;
3207
+ if (n !== t.subject) throw Error(`delegatorId '${n}' does not match parentToken.subject '${t.subject}'`);
3208
+ let i = Date.now();
3209
+ if (i >= t.expiresAt) throw Error("Parent token is expired");
3210
+ if (t.maxDelegations !== void 0 && t.maxDelegations <= 0) throw Error("Parent token does not allow further delegation (maxDelegations=0)");
3211
+ let a = e.scopes ?? t.scopes;
3212
+ if (!Fr(a, t.scopes)) throw Error("Delegated scopes exceed parent token scopes");
3213
+ let o = t.expiresAt - i;
3214
+ if (e.ttlMs > o) throw Error(`Delegated ttlMs (${e.ttlMs}) exceeds parent token remaining TTL (${o})`);
3215
+ let s = `cap-${i}-${y(6)}`, c = e.keyId ?? `${n}-key`, l = t.maxDelegations === void 0 ? void 0 : t.maxDelegations - 1, u = {
3216
+ id: s,
3217
+ version: "7h3-cap/1",
3218
+ issuer: n,
3219
+ subject: r,
3220
+ scopes: a,
3221
+ issuedAt: i,
3222
+ expiresAt: i + e.ttlMs,
3223
+ delegationDepth: t.delegationDepth + 1,
3224
+ parentTokenId: t.id,
3225
+ maxDelegations: l,
3226
+ keyId: c
3227
+ }, d = await b(Q(u), e.delegatorPrivateKey);
3228
+ return {
3229
+ ...u,
3230
+ signature: d
3231
+ };
3232
+ }
3233
+ async function Lr(e, t, n) {
3234
+ if ((n?.now ?? Date.now()) >= e.expiresAt) return !1;
3235
+ let { signature: r, ...i } = e;
3236
+ return x(Q(i), r, t);
3237
+ }
3238
+ async function Rr(e, t, n) {
3239
+ if (e.length === 0) return {
3240
+ ok: !1,
3241
+ reason: "empty-chain"
3242
+ };
3243
+ let r = n?.now ?? Date.now();
3244
+ for (let n = 0; n < e.length; n++) {
3245
+ let i = e[n];
3246
+ if (n === 0 && i.delegationDepth !== 0) return {
3247
+ ok: !1,
3248
+ reason: "root-token-delegation-depth-must-be-zero"
3249
+ };
3250
+ if (n > 0) {
3251
+ let t = e[n - 1];
3252
+ if (i.issuer !== t.subject) return {
3253
+ ok: !1,
3254
+ reason: `chain-broken: token[${n}].issuer '${i.issuer}' !== token[${n - 1}].subject '${t.subject}'`
3255
+ };
3256
+ if (i.parentTokenId !== t.id) return {
3257
+ ok: !1,
3258
+ reason: `chain-broken: token[${n}].parentTokenId '${i.parentTokenId}' !== token[${n - 1}].id '${t.id}'`
3259
+ };
3260
+ if (i.delegationDepth !== t.delegationDepth + 1) return {
3261
+ ok: !1,
3262
+ reason: `chain-broken: token[${n}].delegationDepth ${i.delegationDepth} !== ${t.delegationDepth + 1}`
3263
+ };
3264
+ }
3265
+ if (r >= i.expiresAt) return {
3266
+ ok: !1,
3267
+ reason: `token[${n}]-expired`
3268
+ };
3269
+ let a = await t.getPublicKey(i.issuer);
3270
+ if (!a) return {
3271
+ ok: !1,
3272
+ reason: `no-public-key-for-issuer:${i.issuer}`
3273
+ };
3274
+ let { signature: o, ...s } = i;
3275
+ if (!await x(Q(s), o, a)) return {
3276
+ ok: !1,
3277
+ reason: `invalid-signature-at-index:${n}`
3278
+ };
3279
+ }
3280
+ let i = e[e.length - 1];
3281
+ return n?.requiredPathGlob !== void 0 && !zr(i, n.requiredPathGlob, n.requiredMethod) ? {
3282
+ ok: !1,
3283
+ reason: "leaf-token-does-not-cover-required-scope"
3284
+ } : {
3285
+ ok: !0,
3286
+ token: i,
3287
+ chain: e
3288
+ };
3289
+ }
3290
+ function zr(e, t, n) {
3291
+ for (let r of e.scopes) if (br(r.pathGlob, t) && (r.methods === void 0 || n === void 0 || r.methods.includes(n.toUpperCase()))) return !0;
3292
+ return !1;
3293
+ }
3294
+ function Br(e) {
3295
+ return JSON.stringify(e);
3296
+ }
3297
+ function Vr(e) {
3298
+ return JSON.parse(e);
3299
+ }
3300
+ //#endregion
3301
+ //#region src/gateway.ts
3302
+ var Hr = class {
3303
+ config;
3304
+ rateLimiter;
3305
+ constructor(e) {
3306
+ this.config = e, this.rateLimiter = new vr();
3307
+ }
3308
+ async verify(e) {
3309
+ let t = performance.now(), n = xr(this.config.policies ?? [], e.path);
3310
+ if (n?.require === "none" || !n && (this.config.defaultPolicy ?? "allow") === "allow") {
3311
+ let e = performance.now() - t;
3312
+ return Z.verifications_total.increment({
3313
+ result: "ok",
3314
+ alg: "none",
3315
+ transport: "http"
3316
+ }), Z.verification_duration_ms.observe(e), {
3317
+ ok: !0,
3318
+ sender: ""
3319
+ };
3320
+ }
3321
+ if (this.config.capabilityRegistry) {
3322
+ let n = e.headers[jr], r = Array.isArray(n) ? n[0] : n;
3323
+ if (r) try {
3324
+ let n = await Rr(Vr(r), this.config.capabilityRegistry, {
3325
+ requiredPathGlob: e.path,
3326
+ requiredMethod: e.method
3327
+ });
3328
+ if (n.ok && zr(n.token, e.path, e.method)) {
3329
+ let e = performance.now() - t;
3330
+ return Z.verifications_total.increment({
3331
+ result: "ok",
3332
+ alg: "ED25519",
3333
+ transport: "http"
3334
+ }), Z.verification_duration_ms.observe(e), {
3335
+ ok: !0,
3336
+ sender: n.token.subject
3337
+ };
3338
+ }
3339
+ let i = performance.now() - t;
3340
+ return Z.verifications_total.increment({
3341
+ result: "fail",
3342
+ alg: "none",
3343
+ transport: "http"
3344
+ }), Z.verification_duration_ms.observe(i), {
3345
+ ok: !1,
3346
+ status: 401,
3347
+ reason: n.ok ? "capability-scope-mismatch" : n.reason
3348
+ };
3349
+ } catch {
3350
+ let e = performance.now() - t;
3351
+ return Z.verifications_total.increment({
3352
+ result: "fail",
3353
+ alg: "none",
3354
+ transport: "http"
3355
+ }), Z.verification_duration_ms.observe(e), {
3356
+ ok: !1,
3357
+ status: 401,
3358
+ reason: "invalid-capability-chain"
3359
+ };
3360
+ }
3361
+ }
3362
+ if (!n && (this.config.defaultPolicy ?? "allow") === "deny") {
3363
+ let n = performance.now() - t;
3364
+ return Z.verifications_total.increment({
3365
+ result: "fail",
3366
+ alg: "none",
3367
+ transport: "http"
3368
+ }), Z.verification_duration_ms.observe(n), Z.sender_denials_total.increment({
3369
+ sender: "",
3370
+ path: e.path
3371
+ }), {
3372
+ ok: !1,
3373
+ status: 403,
3374
+ reason: "no-matching-policy"
3375
+ };
3376
+ }
3377
+ let r = await En(e.headers, {
3378
+ keyRegistry: this.config.keyRegistry,
3379
+ headerName: this.config.headerName
3380
+ });
3381
+ if (!r.ok) {
3382
+ let e = performance.now() - t;
3383
+ return Z.verifications_total.increment({
3384
+ result: "fail",
3385
+ alg: "none",
3386
+ transport: "http"
3387
+ }), Z.verification_duration_ms.observe(e), {
3388
+ ok: !1,
3389
+ status: 401,
3390
+ reason: r.reason
3391
+ };
3392
+ }
3393
+ let i = r.envelope, a = i.header.sender, o = i.header.messageId, s = i.signature?.alg ?? "none";
3394
+ if (this.config.replayStore && await this.config.replayStore.check(i.header.nonce, i.header.ttlMs)) return {
3395
+ ok: !1,
3396
+ status: 401,
3397
+ reason: "replay-detected"
3398
+ };
3399
+ if (n && n.require !== "any") {
3400
+ let e = i.signature?.alg, r = n.require === "ed25519" && e !== "ED25519", a = n.require === "hmac" && e !== "HS256";
3401
+ if (r || a) {
3402
+ let e = performance.now() - t;
3403
+ return Z.verifications_total.increment({
3404
+ result: "fail",
3405
+ alg: s,
3406
+ transport: "http"
3407
+ }), Z.verification_duration_ms.observe(e), {
3408
+ ok: !1,
3409
+ status: 401,
3410
+ reason: "invalid-signature"
3411
+ };
3412
+ }
3413
+ }
3414
+ if (n && !Sr(n, a)) {
3415
+ let n = performance.now() - t;
3416
+ return Z.verifications_total.increment({
3417
+ result: "fail",
3418
+ alg: s,
3419
+ transport: "http"
3420
+ }), Z.verification_duration_ms.observe(n), Z.sender_denials_total.increment({
3421
+ sender: a,
3422
+ path: e.path
3423
+ }), {
3424
+ ok: !1,
3425
+ status: 403,
3426
+ reason: "sender-denied"
3427
+ };
3428
+ }
3429
+ if (n?.rateLimit && !this.rateLimiter.consume(a, n.rateLimit).allowed) {
3430
+ let n = performance.now() - t;
3431
+ return Z.verifications_total.increment({
3432
+ result: "fail",
3433
+ alg: s,
3434
+ transport: "http"
3435
+ }), Z.verification_duration_ms.observe(n), Z.rate_limit_hits_total.increment({
3436
+ sender: a,
3437
+ path: e.path
3438
+ }), {
3439
+ ok: !1,
3440
+ status: 429,
3441
+ reason: "rate-limited"
3442
+ };
3443
+ }
3444
+ let c = performance.now() - t;
3445
+ return Z.verifications_total.increment({
3446
+ result: "ok",
3447
+ alg: s,
3448
+ transport: "http"
3449
+ }), Z.verification_duration_ms.observe(c), {
3450
+ ok: !0,
3451
+ sender: a,
3452
+ envelopeId: o
3453
+ };
3454
+ }
3455
+ async handle(e) {
3456
+ let t = await this.verify(e);
3457
+ if (!t.ok) return {
3458
+ status: t.status,
3459
+ headers: { "content-type": "application/json" },
3460
+ body: JSON.stringify({ error: t.reason })
3461
+ };
3462
+ let n = this.config.upstream.replace(/\/$/, "") + e.path, r = {};
3463
+ for (let [t, n] of Object.entries(e.headers)) r[t] = Array.isArray(n) ? n[0] : n;
3464
+ t.sender && (r["x-7h3-sender"] = t.sender), r["x-7h3-verified"] = "true";
3465
+ let i = await fetch(n, {
3466
+ method: e.method,
3467
+ headers: r,
3468
+ body: e.body
3469
+ }), a = await i.text(), o = { "content-type": i.headers.get("content-type") ?? "application/json" };
3470
+ if (this.config.privateKey !== void 0 && (this.config.signResponses ?? !0) && this.config.sender !== void 0) {
3471
+ let e = await wr(a, {
3472
+ privateKey: this.config.privateKey,
3473
+ sender: this.config.sender,
3474
+ recipient: t.sender || void 0
3475
+ });
3476
+ Object.assign(o, e.headers);
3477
+ }
3478
+ return {
3479
+ status: i.status,
3480
+ headers: o,
3481
+ body: a
3482
+ };
3483
+ }
3484
+ getRateLimiter() {
3485
+ return this.rateLimiter;
3486
+ }
3487
+ };
3488
+ function Ur(e) {
3489
+ return new Hr(e);
3490
+ }
3491
+ //#endregion
3492
+ //#region src/auditLog.ts
3493
+ function Wr(e) {
3494
+ let t = [
3495
+ `"id":${JSON.stringify(e.id)}`,
3496
+ `"timestampMs":${e.timestampMs}`,
3497
+ `"type":${JSON.stringify(e.type)}`
3498
+ ];
3499
+ return e.sender !== void 0 && t.push(`"sender":${JSON.stringify(e.sender)}`), e.path !== void 0 && t.push(`"path":${JSON.stringify(e.path)}`), e.method !== void 0 && t.push(`"method":${JSON.stringify(e.method)}`), e.envelopeId !== void 0 && t.push(`"envelopeId":${JSON.stringify(e.envelopeId)}`), e.failReason !== void 0 && t.push(`"failReason":${JSON.stringify(e.failReason)}`), e.upstream !== void 0 && t.push(`"upstream":${JSON.stringify(e.upstream)}`), e.responseStatus !== void 0 && t.push(`"responseStatus":${e.responseStatus}`), `{${t.join(",")}}`;
3500
+ }
3501
+ var Gr = class {
3502
+ entries = [];
3503
+ privateKey;
3504
+ maxEntries;
3505
+ constructor(e, t = 1e4) {
3506
+ this.privateKey = e, this.maxEntries = t;
3507
+ }
3508
+ async log(e) {
3509
+ let t = {
3510
+ id: `audit-${Date.now()}-${y(5)}`,
3511
+ timestampMs: Date.now(),
3512
+ ...e
3513
+ }, n = await b(Wr(t), this.privateKey), r = {
3514
+ ...t,
3515
+ entrySignature: n
3516
+ };
3517
+ this.entries.length >= this.maxEntries && this.entries.shift(), this.entries.push(r);
3518
+ }
3519
+ async query(e) {
3520
+ let t = [...this.entries];
3521
+ return e?.type !== void 0 && (t = t.filter((t) => t.type === e.type)), e?.sender !== void 0 && (t = t.filter((t) => t.sender === e.sender)), e?.since !== void 0 && (t = t.filter((t) => t.timestampMs >= e.since)), e?.limit !== void 0 && (t = t.slice(-e.limit)), t;
3522
+ }
3523
+ async verify(e, t) {
3524
+ return x(Wr({
3525
+ id: e.id,
3526
+ timestampMs: e.timestampMs,
3527
+ type: e.type,
3528
+ sender: e.sender,
3529
+ path: e.path,
3530
+ method: e.method,
3531
+ envelopeId: e.envelopeId,
3532
+ failReason: e.failReason,
3533
+ upstream: e.upstream,
3534
+ responseStatus: e.responseStatus
3535
+ }), e.entrySignature, t);
3536
+ }
3537
+ size() {
3538
+ return this.entries.length;
3539
+ }
3540
+ }, Kr = class {
3541
+ async log(e) {}
3542
+ async query(e) {
3543
+ return [];
3544
+ }
3545
+ async verify(e, t) {
3546
+ return !1;
3547
+ }
3548
+ size() {
3549
+ return 0;
3550
+ }
3551
+ };
3552
+ function qr(e, t) {
3553
+ return new Gr(e, t?.maxEntries);
3554
+ }
3555
+ //#endregion
3556
+ //#region src/otel.ts
3557
+ var Jr = null;
3558
+ function Yr(e) {
3559
+ Jr = e;
3560
+ }
3561
+ function Xr() {
3562
+ if (Jr === null) return null;
3563
+ try {
3564
+ return Jr.getTracer("7h3/protocol");
3565
+ } catch {
3566
+ return null;
3567
+ }
3568
+ }
3569
+ async function Zr(e, t) {
3570
+ let n = Xr();
3571
+ if (n === null) return e(null);
3572
+ let r = n.startSpan("7h3.verify", t);
3573
+ try {
3574
+ return await e(r);
3575
+ } catch (e) {
3576
+ throw e instanceof Error ? r.recordException(e) : r.recordException(Error(String(e))), e;
3577
+ } finally {
3578
+ r.end();
3579
+ }
3580
+ }
3581
+ async function Qr(e) {
3582
+ let t = Xr();
3583
+ if (t === null) return e(null);
3584
+ let n = t.startSpan("7h3.audit.write");
3585
+ try {
3586
+ return await e(n);
3587
+ } catch (e) {
3588
+ throw e instanceof Error ? n.recordException(e) : n.recordException(Error(String(e))), e;
3589
+ } finally {
3590
+ n.end();
3591
+ }
3592
+ }
3593
+ //#endregion
3594
+ //#region src/encryption.ts
3595
+ function $r(e) {
3596
+ return Buffer.from(e).toString("base64url");
3597
+ }
3598
+ function $(e) {
3599
+ return Buffer.from(e, "base64url");
3600
+ }
3601
+ var ei = Buffer.from("302e020100300506032b656e04220420", "hex"), ti = Buffer.from("302a300506032b656e032100", "hex");
3602
+ function ni(e) {
3603
+ let t = $(e);
3604
+ return (0, P.createPrivateKey)({
3605
+ key: Buffer.concat([ei, t]),
3606
+ format: "der",
3607
+ type: "pkcs8"
3608
+ });
3609
+ }
3610
+ function ri(e) {
3611
+ let t = $(e);
3612
+ return (0, P.createPublicKey)({
3613
+ key: Buffer.concat([ti, t]),
3614
+ format: "der",
3615
+ type: "spki"
3616
+ });
3617
+ }
3618
+ function ii() {
3619
+ let { privateKey: e, publicKey: t } = (0, P.generateKeyPairSync)("x25519"), n = e.export({ format: "jwk" });
3620
+ return {
3621
+ publicKey: t.export({ format: "jwk" }).x,
3622
+ privateKey: n.d
3623
+ };
3624
+ }
3625
+ function ai(e, t, n) {
3626
+ let r = (0, P.hkdfSync)("sha256", (0, P.diffieHellman)({
3627
+ privateKey: ni(e),
3628
+ publicKey: ri(t)
3629
+ }), $(n), Buffer.from("7h3-enc/1", "utf8"), 32);
3630
+ return Buffer.from(r);
3631
+ }
3632
+ function oi(e, t) {
3633
+ let n = ii(), r = (0, P.randomBytes)(12), i = $r(r), a = ai(n.privateKey, t, i), o = Buffer.from(JSON.stringify(e), "utf8"), s = (0, P.createCipheriv)("chacha20-poly1305", a, r, { authTagLength: 16 }), c = Buffer.concat([s.update(o), s.final()]), l = s.getAuthTag(), u = {
3634
+ ephemeralPublic: n.publicKey,
3635
+ nonce: i,
3636
+ ciphertext: $r(c),
3637
+ tag: $r(l)
3638
+ };
3639
+ return {
3640
+ encryptedContent: $r(Buffer.from(JSON.stringify(u), "utf8")),
3641
+ ephemeralPublic: n.publicKey
3642
+ };
3643
+ }
3644
+ function si(e, t) {
3645
+ let n = $(e).toString("utf8"), { ephemeralPublic: r, nonce: i, ciphertext: a, tag: o } = JSON.parse(n), s = ai(t, r, i), c = $(i), l = $(a), u = $(o), d = (0, P.createDecipheriv)("chacha20-poly1305", s, c, { authTagLength: 16 });
3646
+ d.setAuthTag(u);
3647
+ let f = Buffer.concat([d.update(l), d.final()]);
3648
+ return JSON.parse(f.toString("utf8"));
3649
+ }
3650
+ async function ci(e, t) {
3651
+ let { encryptedContent: n } = oi(e.body, t.recipientX25519PublicKey);
3652
+ return w({
3653
+ header: e.header,
3654
+ body: {
3655
+ intent: "ENCRYPTED",
3656
+ content: n,
3657
+ capability: "x25519-chacha20poly1305",
3658
+ correlationId: e.body.correlationId
3659
+ }
3660
+ }, t.senderEd25519PrivateKey);
3661
+ }
3662
+ async function li(e, t) {
3663
+ if (!await T(e, t.senderEd25519PublicKey)) throw Error("7h3/encryption: Ed25519 signature verification failed");
3664
+ return {
3665
+ envelope: e,
3666
+ body: si(e.body.content, t.recipientX25519PrivateKey)
3667
+ };
3668
+ }
3669
+ //#endregion
3670
+ export { rt as AgentSession, it as AipAgentAdapter, jr as CAP_HEADER, Sn as CBOR_CONTENT_TYPE, yn as CborDecoder, vn as CborEncoder, It as ClusterRedisReplayStore, Tn as DEFAULT_HEADER, ye as DEFAULT_MAX_BINARY_ENVELOPE_BYTES, Ie as DistributedReplayCache, cr as GRPC_METADATA_KEY, Gr as InMemoryAuditLog, Pt as InMemoryRedisLikeClient, A as InMemoryReplayCache, Vt as InMemoryRevocationStore, Le as InMemoryVerificationMaterialCache, gr as KeyRotationManager, Kr as NoopAuditLog, Hr as Protocol7h3Gateway, Or as Protocol7h3Metrics, Cr as RESPONSE_HEADER, Ft as RedisReplayStore, _r as RevocationRegistry, tt as RollingKeyring, At as RuntimePolicyManager, Vn as STREAM_HEADER, qe as SessionTransport, Qn as SignedStreamReader, Zn as SignedStreamWriter, X as SimpleCounter, Dr as SimpleHistogram, vr as SlidingWindowRateLimiter, Mn as WEBHOOK_DEFAULT_TTL_MS, R as WEBHOOK_SIG_HEADER, z as WEBHOOK_TS_HEADER, N as bootstrapRuntimePolicyEnforcer, Q as canonicalizeCapabilityToken, _ as canonicalizeEnvelope, Ln as consumeWebhook, at as createAipAgentAdapter, Ze as createAipCapabilities, Ot as createAipMcpGatewayRuntime, kt as createAipMcpGatewayRuntimeWithPolicy, qr as createAuditLog, nn as createCachingKeyRegistry, zt as createClusterReplayStore, tn as createCompositeKeyRegistry, D as createEnvelope, Ur as createGateway, hr as createHttpKeyRegistry, $t as createHttpMcpClient, Qt as createHttpMcpHandler, kn as createHttpMiddleware, nt as createKeyringSignatureResolver, qt as createMcpClientCodec, Ar as createMetricsMiddleware, xt as createPolicyEnforcer, dt as createRawTaskFromJsonRpc, ot as createRawTaskFromLangChain, ct as createRawTaskFromLlamaIndex, Lt as createRedisReplayStore, Ht as createRedisRevocationStore, jn as createSignedFetchRequest, Je as createSignedMessage, $n as createSignedStream, or as createSignedWebSocketStream, en as createStaticKeyRegistry, Zt as createStdioMcpClient, er as createStreamVerifier, xn as decodeCbor, Ue as decodeEnvelope, Ge as decodeEnvelopeBatch, Pe as decodeEnvelopeBinary, wn as decodeEnvelopeCbor, ir as decodeStreamChunk, si as decryptBody, Ir as delegateCapabilityToken, ai as deriveEncryptionKey, Qe as encodeAipCapabilities, bn as encodeCbor, j as encodeEnvelope, We as encodeEnvelopeBatch, Ne as encodeEnvelopeBinary, Cn as encodeEnvelopeCbor, rr as encodeStreamChunk, oi as encryptBody, mr as fetchWellKnownKeys, pe as generateEd25519KeypairBase64Url, ii as generateX25519KeyPair, Xr as getOtelTracer, Mt as getRuntimeTuningPreset, yr as globalRateLimiter, Sr as isAllowedSender, St as isRuntimeMode, Nr as issueCapabilityToken, vt as loadRuntimePolicy, br as matchGlob, xr as matchPolicy, Z as metrics, et as negotiateAipCapabilities, li as openEnvelope, $e as parseAipCapabilities, Vr as parseCapabilityChain, gt as parseRuntimePolicyJson, pr as parseWellKnownKeys, y as randomHex, M as receiveEnvelope, Ke as receiveEnvelopeBatch, sr as receiveSignedWebSocketStream, Nt as recommendPolicyAdjustments, kr as renderPrometheusText, ci as sealEnvelope, Br as serializeCapabilityChain, Xt as serveMcpOverStdio, fr as serveWellKnownKeys, Yr as setOtelProvider, b as signCanonicalPayloadEd25519, de as signCanonicalPayloadHmac, w as signEnvelopeEd25519, S as signEnvelopeHmac, An as signFetchRequest, lr as signGrpcCall, Dn as signHttpRequest, On as signHttpRequestHmac, Rn as signQueueMessage, wr as signResponse, tr as signStream, Nn as signWebhook, Pn as signWebhookHmac, ft as toJsonRpcResponse, st as toLangChainMessage, lt as toLlamaIndexMessage, zr as tokenMatchesScope, E as validateEnvelope, ht as validateRuntimePolicy, x as verifyCanonicalPayloadEd25519, fe as verifyCanonicalPayloadHmac, he as verifyCanonicalPayloadSignature, Rr as verifyCapabilityChain, Lr as verifyCapabilityToken, T as verifyEnvelopeEd25519, C as verifyEnvelopeHmac, me as verifyEnvelopeSignature, ur as verifyGrpcCall, En as verifyHttpEnvelope, Bn as verifyQueueBatch, zn as verifyQueueMessage, Tr as verifyResponse, nr as verifyStream, Fn as verifyWebhook, In as verifyWebhookHmac, Qr as withAuditSpan, dr as withGrpcVerification, Ut as withRevocationCheck, Zr as withVerificationSpan, Jt as wrapMcpClient, Kt as wrapMcpServer, ar as wrapWebSocket };