@7h3/protocol 0.4.0 → 0.5.1

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