@7h3/protocol 0.1.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/.dockerignore +19 -0
  2. package/.github/dependabot.yml +32 -0
  3. package/.github/workflows/ci.yml +31 -0
  4. package/.github/workflows/publish.yml +59 -0
  5. package/.github/workflows/scorecard.yml +37 -0
  6. package/7h3.example.yaml +125 -0
  7. package/CHANGELOG.md +152 -0
  8. package/CONTRIBUTING.md +82 -0
  9. package/Dockerfile +73 -0
  10. package/GOVERNANCE.md +62 -0
  11. package/README.md +1317 -6
  12. package/SECURITY.md +70 -0
  13. package/bench-results/replay-cache-full-1777891033256.json +10 -0
  14. package/bench-results/replay-cache-full-1777896317488.json +10 -0
  15. package/bench-results/replay-cache-full-1777900993184.json +10 -0
  16. package/bench-results/replay-cache-full-1777901019285.json +10 -0
  17. package/bench-results/replay-cache-quick-1777870170126.json +10 -0
  18. package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
  19. package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
  20. package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
  21. package/bench-results/wire-codecs-full-1777891019803.json +93 -0
  22. package/bench-results/wire-codecs-full-1777896260964.json +93 -0
  23. package/bench-results/wire-codecs-full-1777901004247.json +93 -0
  24. package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
  25. package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
  26. package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
  27. package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
  28. package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
  29. package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
  30. package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
  31. package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
  32. package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
  33. package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
  34. package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
  35. package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
  36. package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
  37. package/bin/7h3.ts +406 -0
  38. package/conformance/7h3_v0_1.json +77 -0
  39. package/conformance/7h3_v0_1_binary.json +20 -0
  40. package/conformance/aip_v0_1_binary.json +20 -0
  41. package/docker-compose.yaml +77 -0
  42. package/docs/ADOPTION_PLAN.md +120 -0
  43. package/docs/AGENTS.md +77 -0
  44. package/docs/AIP_RFC_v0.1.md +97 -0
  45. package/docs/AI_DECISION_CARD.md +122 -0
  46. package/docs/AI_RUNTIME_POLICY.json +126 -0
  47. package/docs/AI_RUNTIME_POLICY.yaml +110 -0
  48. package/docs/BACKPRESSURE_TUNING.md +65 -0
  49. package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
  50. package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
  51. package/docs/BINARY_CODEC_BENCH.md +23 -0
  52. package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
  53. package/docs/CLOCK_SKEW_POLICY.md +30 -0
  54. package/docs/DISTRIBUTED_REPLAY.md +142 -0
  55. package/docs/FUZZ_CAMPAIGN.md +121 -0
  56. package/docs/GATEWAY.md +195 -0
  57. package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
  58. package/docs/KEY_REVOCATION.md +69 -0
  59. package/docs/MCP_WRAPPER.md +159 -0
  60. package/docs/MIGRATION_GUIDE.md +40 -0
  61. package/docs/OPERATORS.md +184 -0
  62. package/docs/PERF_REGRESSION_POLICY.md +34 -0
  63. package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
  64. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
  65. package/docs/RELEASE_GATE.md +25 -0
  66. package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
  67. package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
  68. package/docs/TELEMETRY.md +41 -0
  69. package/docs/THREAT_MODEL.md +89 -0
  70. package/docs/VERSIONING_POLICY.md +30 -0
  71. package/docs/assets/banner-github.png +0 -0
  72. package/docs/assets/banner.png +0 -0
  73. package/docs/assets/banner.svg +123 -0
  74. package/eslint.config.js +15 -0
  75. package/fuzz/ts/harness-decode.ts +136 -0
  76. package/fuzz/ts/harness-verify.ts +121 -0
  77. package/fuzz/ts/run.ts +35 -0
  78. package/mcp-server/README.md +38 -0
  79. package/mcp-server/package-lock.json +1187 -0
  80. package/mcp-server/package.json +35 -0
  81. package/mcp-server/src/index.ts +236 -0
  82. package/mcp-server/tsconfig.json +14 -0
  83. package/package.json +121 -13
  84. package/scripts/aip-framework-quickstart.ts +110 -0
  85. package/scripts/aip-mcp-gateway.ts +38 -0
  86. package/scripts/aip-mcp-wrap-demo.ts +72 -0
  87. package/scripts/aip-quickstart.ts +60 -0
  88. package/scripts/bench-diff.ts +118 -0
  89. package/scripts/bench-protocol-e2e.ts +937 -0
  90. package/scripts/bench-protocol-openloop.ts +1397 -0
  91. package/scripts/bench-replay-cache.ts +76 -0
  92. package/scripts/bench-signature-profiles.ts +180 -0
  93. package/scripts/bench-wire-codecs.ts +161 -0
  94. package/scripts/build-binary-conformance.ts +36 -0
  95. package/scripts/build-release-dashboard.ts +175 -0
  96. package/scripts/canary-rollout.ts +38 -0
  97. package/scripts/mcpGatewayCli.test.ts +116 -0
  98. package/scripts/prepare-aip-package.ts +88 -0
  99. package/scripts/regen-conformance-sigs.ts +18 -0
  100. package/scripts/release-gate.ts +19 -0
  101. package/scripts/validate-runtime-policy.ts +18 -0
  102. package/sdk/browser/index.test.ts +162 -0
  103. package/sdk/browser/index.ts +257 -0
  104. package/sdk/browser/package.json +13 -0
  105. package/sdk/go/cbor.go +551 -0
  106. package/sdk/go/cbor_test.go +232 -0
  107. package/sdk/go/encryption.go +280 -0
  108. package/sdk/go/encryption_test.go +318 -0
  109. package/sdk/go/go.mod +7 -0
  110. package/sdk/go/go.sum +4 -0
  111. package/sdk/go/http.go +135 -0
  112. package/sdk/go/protocol.go +324 -0
  113. package/sdk/go/protocol_test.go +334 -0
  114. package/sdk/go/replay.go +121 -0
  115. package/sdk/go/replay_test.go +149 -0
  116. package/sdk/go/webhook.go +136 -0
  117. package/sdk/pq/package-lock.json +1358 -0
  118. package/sdk/pq/package.json +42 -0
  119. package/sdk/pq/src/index.test.ts +143 -0
  120. package/sdk/pq/src/index.ts +166 -0
  121. package/sdk/pq/tsconfig.json +14 -0
  122. package/sdk/pq/vitest.config.ts +7 -0
  123. package/sdk/python/README.md +18 -0
  124. package/sdk/python/protocol_7h3/__init__.py +46 -0
  125. package/sdk/python/protocol_7h3/encryption.py +252 -0
  126. package/sdk/python/protocol_7h3/http.py +212 -0
  127. package/sdk/python/protocol_7h3/keys.py +149 -0
  128. package/sdk/python/protocol_7h3/pq.py +244 -0
  129. package/sdk/python/protocol_7h3/protocol.py +525 -0
  130. package/sdk/python/protocol_7h3/queue.py +118 -0
  131. package/sdk/python/protocol_7h3/replay.py +98 -0
  132. package/sdk/python/protocol_7h3/webhook.py +116 -0
  133. package/sdk/python/pyproject.toml +40 -0
  134. package/sdk/python/tests/test_conformance.py +110 -0
  135. package/sdk/python/tests/test_encryption.py +206 -0
  136. package/sdk/python/tests/test_http.py +305 -0
  137. package/sdk/python/tests/test_keys.py +417 -0
  138. package/sdk/python/tests/test_queue.py +120 -0
  139. package/sdk/python/tests/test_webhook.py +345 -0
  140. package/sdk/rust/Cargo.lock +371 -0
  141. package/sdk/rust/Cargo.toml +25 -0
  142. package/sdk/rust/README.md +31 -0
  143. package/sdk/rust/fuzz/Cargo.toml +29 -0
  144. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
  145. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
  146. package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
  147. package/sdk/rust/src/http.rs +145 -0
  148. package/sdk/rust/src/keys.rs +161 -0
  149. package/sdk/rust/src/lib.rs +688 -0
  150. package/sdk/rust/src/queue.rs +79 -0
  151. package/sdk/rust/src/webhook.rs +86 -0
  152. package/sdk/rust/tests/conformance.rs +148 -0
  153. package/sdk/rust/tests/gateway.rs +130 -0
  154. package/sdk/rust/tests/http_webhook_queue.rs +201 -0
  155. package/sdk/rust/tests/keys.rs +189 -0
  156. package/sdk/threshold/index.d.ts +68 -0
  157. package/sdk/threshold/index.d.ts.map +1 -0
  158. package/sdk/threshold/index.js +254 -0
  159. package/sdk/threshold/package-lock.json +1361 -0
  160. package/sdk/threshold/package.json +39 -0
  161. package/sdk/threshold/src/index.d.ts +68 -0
  162. package/sdk/threshold/src/index.d.ts.map +1 -0
  163. package/sdk/threshold/src/index.js +254 -0
  164. package/sdk/threshold/src/index.test.ts +238 -0
  165. package/sdk/threshold/src/index.ts +355 -0
  166. package/sdk/threshold/tsconfig.json +19 -0
  167. package/sdk/threshold/vitest.config.ts +12 -0
  168. package/src/agentAdapter.test.ts +48 -0
  169. package/src/agentAdapter.ts +56 -0
  170. package/src/auditLog.test.ts +145 -0
  171. package/src/auditLog.ts +147 -0
  172. package/src/capability.test.ts +504 -0
  173. package/src/capability.ts +380 -0
  174. package/src/cborCodec.test.ts +263 -0
  175. package/src/cborCodec.ts +339 -0
  176. package/src/conformance.test.ts +136 -0
  177. package/src/conformanceVectors.ts +99 -0
  178. package/src/encryption.test.ts +206 -0
  179. package/src/encryption.ts +245 -0
  180. package/src/envelopeCbor.ts +140 -0
  181. package/src/frameworkAdapters.test.ts +290 -0
  182. package/src/frameworkAdapters.ts +261 -0
  183. package/src/gateway.test.ts +343 -0
  184. package/src/gateway.ts +246 -0
  185. package/src/grpcBinding.test.ts +211 -0
  186. package/src/grpcBinding.ts +103 -0
  187. package/src/httpBinding.test.ts +376 -0
  188. package/src/httpBinding.ts +189 -0
  189. package/src/index.ts +39 -0
  190. package/src/keyInfra.test.ts +278 -0
  191. package/src/keyInfra.ts +228 -0
  192. package/src/keyRegistry.ts +59 -0
  193. package/src/keyRotation.test.ts +78 -0
  194. package/src/keyRotation.ts +72 -0
  195. package/src/mcpGateway.test.ts +129 -0
  196. package/src/mcpGateway.ts +250 -0
  197. package/src/mcpTransports.test.ts +92 -0
  198. package/src/mcpTransports.ts +169 -0
  199. package/src/mcpWrapper.test.ts +179 -0
  200. package/src/mcpWrapper.ts +206 -0
  201. package/src/otel.ts +136 -0
  202. package/src/policyEnforcer.test.ts +99 -0
  203. package/src/policyEnforcer.ts +169 -0
  204. package/src/policyTelemetryFeedback.test.ts +25 -0
  205. package/src/policyTelemetryFeedback.ts +38 -0
  206. package/src/protocol.bench.ts +37 -0
  207. package/{protocol.d.ts → src/protocol.d.ts} +2 -1
  208. package/src/protocol.d.ts.map +1 -0
  209. package/src/protocol.js +294 -0
  210. package/src/protocol.test.ts +155 -0
  211. package/src/protocol.ts +414 -0
  212. package/src/protocolAgent.test.ts +105 -0
  213. package/src/protocolAgent.ts +169 -0
  214. package/src/protocolBinary.test.ts +165 -0
  215. package/src/protocolBinary.ts +312 -0
  216. package/src/protocolCapabilities.ts +70 -0
  217. package/src/protocolFuzz.advanced.test.ts +235 -0
  218. package/src/protocolFuzz.test.ts +111 -0
  219. package/src/protocolNegative.test.ts +97 -0
  220. package/src/protocolReplay.test.ts +71 -0
  221. package/src/protocolReplay.ts +194 -0
  222. package/src/protocolTransport.test.ts +556 -0
  223. package/src/protocolTransport.ts +483 -0
  224. package/src/queueBinding.test.ts +130 -0
  225. package/src/queueBinding.ts +102 -0
  226. package/src/rateLimiter.test.ts +96 -0
  227. package/src/rateLimiter.ts +46 -0
  228. package/src/redisClient.ts +140 -0
  229. package/src/redisIntegration.test.ts +134 -0
  230. package/src/replayStores.test.ts +273 -0
  231. package/src/replayStores.ts +215 -0
  232. package/src/revocation.test.ts +98 -0
  233. package/src/revocation.ts +0 -0
  234. package/src/routePolicy.test.ts +87 -0
  235. package/src/routePolicy.ts +72 -0
  236. package/src/runtimePolicy.test.ts +49 -0
  237. package/src/runtimePolicy.ts +81 -0
  238. package/src/runtimePolicyManager.test.ts +29 -0
  239. package/src/runtimePolicyManager.ts +50 -0
  240. package/src/runtimePolicyPresets.ts +43 -0
  241. package/src/signedResponse.test.ts +111 -0
  242. package/src/signedResponse.ts +83 -0
  243. package/src/stream.test.ts +254 -0
  244. package/src/stream.ts +417 -0
  245. package/src/telemetry.test.ts +251 -0
  246. package/src/telemetry.ts +299 -0
  247. package/src/webhookBinding.test.ts +144 -0
  248. package/src/webhookBinding.ts +115 -0
  249. package/src/wsBinding.test.ts +221 -0
  250. package/src/wsBinding.ts +200 -0
  251. package/tsconfig.json +15 -0
  252. package/tsconfig.lib.json +23 -0
  253. package/vite.lib.config.ts +16 -0
  254. package/vitest.config.ts +11 -0
  255. package/agentAdapter.d.ts +0 -26
  256. package/conformanceVectors.d.ts +0 -20
  257. package/frameworkAdapters.d.ts +0 -72
  258. package/index.d.ts +0 -20
  259. package/index.js +0 -1702
  260. package/keyRotation.d.ts +0 -20
  261. package/mcpGateway.d.ts +0 -37
  262. package/mcpTransports.d.ts +0 -62
  263. package/mcpWrapper.d.ts +0 -83
  264. package/policyEnforcer.d.ts +0 -50
  265. package/policyTelemetryFeedback.d.ts +0 -11
  266. package/protocolAgent.d.ts +0 -58
  267. package/protocolBinary.d.ts +0 -8
  268. package/protocolCapabilities.d.ts +0 -24
  269. package/protocolReplay.d.ts +0 -35
  270. package/protocolTransport.d.ts +0 -73
  271. package/redisClient.d.ts +0 -49
  272. package/replayStores.d.ts +0 -32
  273. package/revocation.d.ts +0 -71
  274. package/runtimePolicy.d.ts +0 -24
  275. package/runtimePolicyManager.d.ts +0 -15
  276. package/runtimePolicyPresets.d.ts +0 -11
@@ -0,0 +1,414 @@
1
+ export type ProtocolVersion = '7h3/0.1'
2
+
3
+ export type IntentKind =
4
+ | 'PING'
5
+ | 'PONG'
6
+ | 'CAPS'
7
+ | 'TASK'
8
+ | 'RESULT'
9
+ | 'ERROR'
10
+ | 'ENCRYPTED'
11
+
12
+ export interface ProtocolHeader {
13
+ version: ProtocolVersion
14
+ messageId: string
15
+ timestampMs: number
16
+ ttlMs: number
17
+ sender: string
18
+ recipient?: string
19
+ nonce: string
20
+ }
21
+
22
+ export interface ProtocolBody {
23
+ intent: IntentKind
24
+ content: string
25
+ capability?: string
26
+ correlationId?: string
27
+ }
28
+
29
+ export interface ProtocolSignature {
30
+ alg: 'HS256' | 'ED25519'
31
+ keyId: string
32
+ value: string
33
+ }
34
+
35
+ export interface ProtocolEnvelope {
36
+ header: ProtocolHeader
37
+ body: ProtocolBody
38
+ signature?: ProtocolSignature
39
+ }
40
+
41
+ export interface ProtocolDiagnostic {
42
+ level: 'error' | 'warning'
43
+ message: string
44
+ }
45
+
46
+ const textEncoder = new TextEncoder()
47
+ const HMAC_KEY_CACHE_LIMIT = 256
48
+ const hmacKeyCache = new Map<string, Promise<CryptoKey>>()
49
+ const ED25519_KEY_CACHE_LIMIT = 256
50
+ const ed25519PrivateKeyCache = new Map<string, Promise<CryptoKey>>()
51
+ const ed25519PublicKeyCache = new Map<string, Promise<CryptoKey>>()
52
+
53
+ export type SignatureVerificationMaterial =
54
+ | { alg: 'HS256'; secret: string }
55
+ | { alg: 'ED25519'; publicKey: string }
56
+
57
+ type BufferLike = {
58
+ from: (input: string | Uint8Array, encoding?: string) => Uint8Array & { toString: (encoding?: string) => string }
59
+ }
60
+
61
+ function getBufferLike(): BufferLike | null {
62
+ const candidate = globalThis as unknown as { Buffer?: BufferLike }
63
+ return candidate.Buffer ?? null
64
+ }
65
+
66
+ function serializeHeaderCanonical(header: ProtocolHeader): string {
67
+ const parts: string[] = [
68
+ `"messageId":${JSON.stringify(header.messageId)}`,
69
+ `"nonce":${JSON.stringify(header.nonce)}`,
70
+ ]
71
+ if (header.recipient !== undefined) {
72
+ parts.push(`"recipient":${JSON.stringify(header.recipient)}`)
73
+ }
74
+ parts.push(`"sender":${JSON.stringify(header.sender)}`)
75
+ parts.push(`"timestampMs":${header.timestampMs}`)
76
+ parts.push(`"ttlMs":${header.ttlMs}`)
77
+ parts.push(`"version":${JSON.stringify(header.version)}`)
78
+ return `{${parts.join(',')}}`
79
+ }
80
+
81
+ function serializeBodyCanonical(body: ProtocolBody): string {
82
+ const parts: string[] = []
83
+ if (body.capability !== undefined) {
84
+ parts.push(`"capability":${JSON.stringify(body.capability)}`)
85
+ }
86
+ parts.push(`"content":${JSON.stringify(body.content)}`)
87
+ if (body.correlationId !== undefined) {
88
+ parts.push(`"correlationId":${JSON.stringify(body.correlationId)}`)
89
+ }
90
+ parts.push(`"intent":${JSON.stringify(body.intent)}`)
91
+ return `{${parts.join(',')}}`
92
+ }
93
+
94
+ function getCachedHmacKey(secret: string): Promise<CryptoKey> {
95
+ const cacheKey = `hs256:${secret}`
96
+ const cached = hmacKeyCache.get(cacheKey)
97
+ if (cached) return cached
98
+
99
+ if (hmacKeyCache.size >= HMAC_KEY_CACHE_LIMIT) {
100
+ hmacKeyCache.clear()
101
+ }
102
+
103
+ const subtle = requireCryptoSubtle()
104
+ const imported = subtle
105
+ .importKey(
106
+ 'raw',
107
+ textEncoder.encode(secret),
108
+ { name: 'HMAC', hash: 'SHA-256' },
109
+ false,
110
+ ['sign', 'verify'],
111
+ )
112
+ .catch((error: unknown) => {
113
+ hmacKeyCache.delete(cacheKey)
114
+ throw error
115
+ })
116
+
117
+ hmacKeyCache.set(cacheKey, imported)
118
+ return imported
119
+ }
120
+
121
+ function getCachedEd25519PrivateKey(privateKeyPkcs8Base64Url: string): Promise<CryptoKey> {
122
+ const cacheKey = `ed25519:pkcs8:${privateKeyPkcs8Base64Url}`
123
+ const cached = ed25519PrivateKeyCache.get(cacheKey)
124
+ if (cached) return cached
125
+
126
+ if (ed25519PrivateKeyCache.size >= ED25519_KEY_CACHE_LIMIT) {
127
+ ed25519PrivateKeyCache.clear()
128
+ }
129
+
130
+ const subtle = requireCryptoSubtle()
131
+ const imported = subtle
132
+ .importKey('pkcs8', toArrayBuffer(fromBase64Url(privateKeyPkcs8Base64Url)), { name: 'Ed25519' }, false, ['sign'])
133
+ .catch((error: unknown) => {
134
+ ed25519PrivateKeyCache.delete(cacheKey)
135
+ throw error
136
+ })
137
+ ed25519PrivateKeyCache.set(cacheKey, imported)
138
+ return imported
139
+ }
140
+
141
+ function getCachedEd25519PublicKey(publicKeySpkiBase64Url: string): Promise<CryptoKey> {
142
+ const cacheKey = `ed25519:spki:${publicKeySpkiBase64Url}`
143
+ const cached = ed25519PublicKeyCache.get(cacheKey)
144
+ if (cached) return cached
145
+
146
+ if (ed25519PublicKeyCache.size >= ED25519_KEY_CACHE_LIMIT) {
147
+ ed25519PublicKeyCache.clear()
148
+ }
149
+
150
+ const subtle = requireCryptoSubtle()
151
+ const imported = subtle
152
+ .importKey('spki', toArrayBuffer(fromBase64Url(publicKeySpkiBase64Url)), { name: 'Ed25519' }, false, ['verify'])
153
+ .catch((error: unknown) => {
154
+ ed25519PublicKeyCache.delete(cacheKey)
155
+ throw error
156
+ })
157
+ ed25519PublicKeyCache.set(cacheKey, imported)
158
+ return imported
159
+ }
160
+
161
+ function toBase64Url(bytes: Uint8Array): string {
162
+ const bufferLike = getBufferLike()
163
+ const base64 = bufferLike ? bufferLike.from(bytes).toString('base64') : btoa(String.fromCharCode(...bytes))
164
+ return base64
165
+ .replace(/\+/g, '-')
166
+ .replace(/\//g, '_')
167
+ .replace(/=+$/g, '')
168
+ }
169
+
170
+ function fromBase64Url(value: string): Uint8Array {
171
+ const padded = value
172
+ .replace(/-/g, '+')
173
+ .replace(/_/g, '/')
174
+ .padEnd(Math.ceil(value.length / 4) * 4, '=')
175
+
176
+ const bufferLike = getBufferLike()
177
+ if (bufferLike) {
178
+ return new Uint8Array(bufferLike.from(padded, 'base64'))
179
+ }
180
+
181
+ const binary = atob(padded)
182
+ const bytes = new Uint8Array(binary.length)
183
+ for (let i = 0; i < binary.length; i += 1) {
184
+ bytes[i] = binary.charCodeAt(i)
185
+ }
186
+ return bytes
187
+ }
188
+
189
+ function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
190
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
191
+ }
192
+
193
+ export function canonicalizeEnvelope(envelope: Omit<ProtocolEnvelope, 'signature'>): string {
194
+ return `{"body":${serializeBodyCanonical(envelope.body)},"header":${serializeHeaderCanonical(envelope.header)}}`
195
+ }
196
+
197
+ function requireCryptoSubtle(): SubtleCrypto {
198
+ if (typeof crypto === 'undefined' || !crypto.subtle) {
199
+ throw new Error('Web Crypto API is not available in this runtime')
200
+ }
201
+ return crypto.subtle
202
+ }
203
+
204
+ async function hmacSign(payload: string, secret: string): Promise<string> {
205
+ const subtle = requireCryptoSubtle()
206
+ const key = await getCachedHmacKey(secret)
207
+ const signature = await subtle.sign('HMAC', key, textEncoder.encode(payload))
208
+ return toBase64Url(new Uint8Array(signature))
209
+ }
210
+
211
+ async function hmacVerify(payload: string, signature: string, secret: string): Promise<boolean> {
212
+ const subtle = requireCryptoSubtle()
213
+ const key = await getCachedHmacKey(secret)
214
+ const signatureBytes = fromBase64Url(signature)
215
+ return subtle.verify('HMAC', key, signatureBytes.buffer as ArrayBuffer, textEncoder.encode(payload))
216
+ }
217
+
218
+ async function ed25519Sign(payload: string, privateKeyPkcs8Base64Url: string): Promise<string> {
219
+ const subtle = requireCryptoSubtle()
220
+ const key = await getCachedEd25519PrivateKey(privateKeyPkcs8Base64Url)
221
+ const signature = await subtle.sign('Ed25519', key, textEncoder.encode(payload))
222
+ return toBase64Url(new Uint8Array(signature))
223
+ }
224
+
225
+ async function ed25519Verify(payload: string, signature: string, publicKeySpkiBase64Url: string): Promise<boolean> {
226
+ const subtle = requireCryptoSubtle()
227
+ const key = await getCachedEd25519PublicKey(publicKeySpkiBase64Url)
228
+ const signatureBytes = fromBase64Url(signature)
229
+ return subtle.verify('Ed25519', key, signatureBytes.buffer as ArrayBuffer, textEncoder.encode(payload))
230
+ }
231
+
232
+ export async function signCanonicalPayloadHmac(payload: string, secret: string): Promise<string> {
233
+ return hmacSign(payload, secret)
234
+ }
235
+
236
+ export async function verifyCanonicalPayloadHmac(payload: string, signature: string, secret: string): Promise<boolean> {
237
+ return hmacVerify(payload, signature, secret)
238
+ }
239
+
240
+ export async function generateEd25519KeypairBase64Url(): Promise<{ publicKey: string; privateKey: string }> {
241
+ const subtle = requireCryptoSubtle()
242
+ const pair = await subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])
243
+ const privateKeyRaw = await subtle.exportKey('pkcs8', pair.privateKey)
244
+ const publicKeyRaw = await subtle.exportKey('spki', pair.publicKey)
245
+ return {
246
+ privateKey: toBase64Url(new Uint8Array(privateKeyRaw)),
247
+ publicKey: toBase64Url(new Uint8Array(publicKeyRaw)),
248
+ }
249
+ }
250
+
251
+ export async function signCanonicalPayloadEd25519(payload: string, privateKeyPkcs8Base64Url: string): Promise<string> {
252
+ return ed25519Sign(payload, privateKeyPkcs8Base64Url)
253
+ }
254
+
255
+ export async function verifyCanonicalPayloadEd25519(
256
+ payload: string,
257
+ signature: string,
258
+ publicKeySpkiBase64Url: string,
259
+ ): Promise<boolean> {
260
+ return ed25519Verify(payload, signature, publicKeySpkiBase64Url)
261
+ }
262
+
263
+ export async function signEnvelopeHmac(
264
+ envelope: Omit<ProtocolEnvelope, 'signature'>,
265
+ secret: string,
266
+ keyId = 'local-dev-key',
267
+ ): Promise<ProtocolEnvelope> {
268
+ const payload = canonicalizeEnvelope(envelope)
269
+ const signature = await hmacSign(payload, secret)
270
+ return {
271
+ ...envelope,
272
+ signature: {
273
+ alg: 'HS256',
274
+ keyId,
275
+ value: signature,
276
+ },
277
+ }
278
+ }
279
+
280
+ export async function verifyEnvelopeHmac(envelope: ProtocolEnvelope, secret: string): Promise<boolean> {
281
+ if (!envelope.signature) return false
282
+ if (envelope.signature.alg !== 'HS256') return false
283
+
284
+ const unsigned: Omit<ProtocolEnvelope, 'signature'> = {
285
+ header: envelope.header,
286
+ body: envelope.body,
287
+ }
288
+ const payload = canonicalizeEnvelope(unsigned)
289
+ return hmacVerify(payload, envelope.signature.value, secret)
290
+ }
291
+
292
+ export async function signEnvelopeEd25519(
293
+ envelope: Omit<ProtocolEnvelope, 'signature'>,
294
+ privateKeyPkcs8Base64Url: string,
295
+ keyId = 'local-ed25519-key',
296
+ ): Promise<ProtocolEnvelope> {
297
+ const payload = canonicalizeEnvelope(envelope)
298
+ const signature = await ed25519Sign(payload, privateKeyPkcs8Base64Url)
299
+ return {
300
+ ...envelope,
301
+ signature: {
302
+ alg: 'ED25519',
303
+ keyId,
304
+ value: signature,
305
+ },
306
+ }
307
+ }
308
+
309
+ export async function verifyEnvelopeEd25519(envelope: ProtocolEnvelope, publicKeySpkiBase64Url: string): Promise<boolean> {
310
+ if (!envelope.signature) return false
311
+ if (envelope.signature.alg !== 'ED25519') return false
312
+
313
+ const unsigned: Omit<ProtocolEnvelope, 'signature'> = {
314
+ header: envelope.header,
315
+ body: envelope.body,
316
+ }
317
+ const payload = canonicalizeEnvelope(unsigned)
318
+ return ed25519Verify(payload, envelope.signature.value, publicKeySpkiBase64Url)
319
+ }
320
+
321
+ export async function verifyEnvelopeSignature(
322
+ envelope: ProtocolEnvelope,
323
+ material: SignatureVerificationMaterial,
324
+ ): Promise<boolean> {
325
+ if (!envelope.signature) return false
326
+ if (envelope.signature.alg !== material.alg) return false
327
+ if (material.alg === 'HS256') {
328
+ return verifyEnvelopeHmac(envelope, material.secret)
329
+ }
330
+ return verifyEnvelopeEd25519(envelope, material.publicKey)
331
+ }
332
+
333
+ export async function verifyCanonicalPayloadSignature(
334
+ payload: string,
335
+ signature: ProtocolSignature | undefined,
336
+ material: SignatureVerificationMaterial,
337
+ ): Promise<boolean> {
338
+ if (!signature) return false
339
+ if (signature.alg !== material.alg) return false
340
+ if (material.alg === 'HS256') {
341
+ return verifyCanonicalPayloadHmac(payload, signature.value, material.secret)
342
+ }
343
+ return verifyCanonicalPayloadEd25519(payload, signature.value, material.publicKey)
344
+ }
345
+
346
+ export function validateEnvelope(envelope: ProtocolEnvelope, nowMs = Date.now()): ProtocolDiagnostic[] {
347
+ const diagnostics: ProtocolDiagnostic[] = []
348
+ const header = (envelope as Partial<ProtocolEnvelope>).header ?? ({} as Partial<ProtocolHeader>)
349
+ const body = (envelope as Partial<ProtocolEnvelope>).body ?? ({} as Partial<ProtocolBody>)
350
+
351
+ const version = typeof header.version === 'string' ? header.version : ''
352
+ const messageId = typeof header.messageId === 'string' ? header.messageId : ''
353
+ const sender = typeof header.sender === 'string' ? header.sender : ''
354
+ const nonce = typeof header.nonce === 'string' ? header.nonce : ''
355
+ const timestampMs = typeof header.timestampMs === 'number' ? header.timestampMs : 0
356
+ const ttlMs = typeof header.ttlMs === 'number' ? header.ttlMs : 0
357
+ const content = typeof body.content === 'string' ? body.content : ''
358
+
359
+ if (version !== '7h3/0.1') {
360
+ diagnostics.push({ level: 'error', message: `Unsupported protocol version '${version}'` })
361
+ }
362
+ if (!messageId.trim()) {
363
+ diagnostics.push({ level: 'error', message: 'Missing messageId' })
364
+ }
365
+ if (!sender.trim()) {
366
+ diagnostics.push({ level: 'error', message: 'Missing sender identity' })
367
+ }
368
+ if (!nonce.trim()) {
369
+ diagnostics.push({ level: 'error', message: 'Missing nonce — replay protection requires a unique nonce per message' })
370
+ }
371
+ if (ttlMs <= 0) {
372
+ diagnostics.push({ level: 'error', message: 'ttlMs must be greater than zero' })
373
+ }
374
+ if (timestampMs + ttlMs < nowMs) {
375
+ diagnostics.push({ level: 'error', message: 'Message TTL expired' })
376
+ }
377
+ if (!content.trim()) {
378
+ diagnostics.push({ level: 'warning', message: 'Empty content payload' })
379
+ }
380
+
381
+ return diagnostics
382
+ }
383
+
384
+ export function createEnvelope(input: {
385
+ sender: string
386
+ recipient?: string
387
+ intent: IntentKind
388
+ content: string
389
+ capability?: string
390
+ correlationId?: string
391
+ ttlMs?: number
392
+ messageId?: string
393
+ nonce?: string
394
+ nowMs?: number
395
+ }): Omit<ProtocolEnvelope, 'signature'> {
396
+ const nowMs = input.nowMs ?? Date.now()
397
+ return {
398
+ header: {
399
+ version: '7h3/0.1',
400
+ messageId: input.messageId ?? `msg-${nowMs}-${Math.random().toString(36).slice(2, 10)}`,
401
+ timestampMs: nowMs,
402
+ ttlMs: input.ttlMs ?? 60_000,
403
+ sender: input.sender,
404
+ recipient: input.recipient,
405
+ nonce: input.nonce ?? Math.random().toString(36).slice(2, 12),
406
+ },
407
+ body: {
408
+ intent: input.intent,
409
+ content: input.content,
410
+ capability: input.capability,
411
+ correlationId: input.correlationId,
412
+ },
413
+ }
414
+ }
@@ -0,0 +1,105 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { AgentSession } from './protocolAgent'
3
+ import { negotiateAipCapabilities, parseAipCapabilities } from './protocolCapabilities'
4
+ import { encodeEnvelope, receiveEnvelope } from './protocolTransport'
5
+
6
+ describe('AgentSession protocol loop', () => {
7
+ const alpha = new AgentSession({
8
+ agentId: 'agent.alpha',
9
+ outboundSecret: 'alpha-secret',
10
+ sharedSecrets: {
11
+ 'agent.beta': 'beta-secret',
12
+ },
13
+ })
14
+
15
+ const beta = new AgentSession({
16
+ agentId: 'agent.beta',
17
+ outboundSecret: 'beta-secret',
18
+ capabilities: ['math.mul2', 'task.plan'],
19
+ sharedSecrets: {
20
+ 'agent.alpha': 'alpha-secret',
21
+ },
22
+ onTask: async (envelope) => ({
23
+ intent: 'RESULT',
24
+ content: `task accepted:${envelope.body.content}`,
25
+ capability: envelope.body.capability,
26
+ }),
27
+ })
28
+
29
+ it('responds to PING with signed PONG', async () => {
30
+ const ping = await alpha.createSignedIntent({
31
+ recipient: 'agent.beta',
32
+ intent: 'PING',
33
+ content: 'hello',
34
+ messageId: 'p-1',
35
+ nonce: 'n-1',
36
+ nowMs: 1000,
37
+ })
38
+
39
+ const receivedByBeta = await beta.receiveAndRespond(encodeEnvelope(ping), 1000)
40
+ expect(receivedByBeta.ok).toBe(true)
41
+ expect(receivedByBeta.response?.body.intent).toBe('PONG')
42
+
43
+ const receivedByAlpha = await receiveEnvelope(receivedByBeta.response!, {
44
+ nowMs: 1001,
45
+ secretResolver: async () => 'beta-secret',
46
+ requireSignature: true,
47
+ })
48
+ expect(receivedByAlpha.ok).toBe(true)
49
+ expect(receivedByAlpha.envelope?.body.correlationId).toBe('p-1')
50
+ })
51
+
52
+ it('responds to CAPS with capability payload', async () => {
53
+ const capsReq = await alpha.createSignedIntent({
54
+ recipient: 'agent.beta',
55
+ intent: 'CAPS',
56
+ content: 'what can you do?',
57
+ messageId: 'c-1',
58
+ nonce: 'n-2',
59
+ nowMs: 1100,
60
+ })
61
+
62
+ const receivedByBeta = await beta.receiveAndRespond(capsReq, 1100)
63
+ expect(receivedByBeta.ok).toBe(true)
64
+ expect(receivedByBeta.response?.body.intent).toBe('RESULT')
65
+
66
+ const parsed = JSON.parse(receivedByBeta.response?.body.content ?? '{}') as {
67
+ agent?: string
68
+ capabilities?: string[]
69
+ wireFormats?: string[]
70
+ batchMax?: number
71
+ }
72
+ expect(parsed.agent).toBe('agent.beta')
73
+ expect(parsed.capabilities).toContain('math.mul2')
74
+ expect(parsed.wireFormats).toContain('compact')
75
+ expect(parsed.batchMax).toBe(1)
76
+ })
77
+
78
+ it('negotiates shared wire capabilities from CAPS payloads', () => {
79
+ const local = parseAipCapabilities('{"agent":"local","capabilities":[],"wireFormats":["binary","compact"],"batchMax":16,"ackModes":["fast","receipt"]}')
80
+ const remote = parseAipCapabilities('{"agent":"remote","capabilities":[],"wireFormats":["compact","json"],"batchMax":8,"ackModes":["receipt"]}')
81
+ expect(local).not.toBeNull()
82
+ expect(remote).not.toBeNull()
83
+
84
+ const negotiated = negotiateAipCapabilities(local!, remote!)
85
+ expect(negotiated).toEqual({ wireFormat: 'compact', batchMax: 8, ackMode: 'receipt' })
86
+ })
87
+
88
+ it('handles TASK with custom task handler', async () => {
89
+ const task = await alpha.createSignedIntent({
90
+ recipient: 'agent.beta',
91
+ intent: 'TASK',
92
+ content: 'plan route',
93
+ capability: 'task.plan',
94
+ messageId: 't-1',
95
+ nonce: 'n-3',
96
+ nowMs: 1200,
97
+ })
98
+
99
+ const receivedByBeta = await beta.receiveAndRespond(task, 1200)
100
+ expect(receivedByBeta.ok).toBe(true)
101
+ expect(receivedByBeta.response?.body.intent).toBe('RESULT')
102
+ expect(receivedByBeta.response?.body.content).toContain('task accepted:plan route')
103
+ expect(receivedByBeta.response?.body.correlationId).toBe('t-1')
104
+ })
105
+ })
@@ -0,0 +1,169 @@
1
+ import { createEnvelope, signEnvelopeHmac, type IntentKind, type ProtocolDiagnostic, type ProtocolEnvelope } from './protocol'
2
+ import { createAipCapabilities, encodeAipCapabilities, type AckMode } from './protocolCapabilities'
3
+ import { InMemoryReplayCache } from './protocolReplay'
4
+ import { receiveEnvelope, type WireEnvelope, type WireFormat } from './protocolTransport'
5
+
6
+ export interface TaskHandlerResult {
7
+ intent?: 'RESULT' | 'ERROR'
8
+ content: string
9
+ capability?: string
10
+ }
11
+
12
+ export interface AgentSessionConfig {
13
+ agentId: string
14
+ outboundSecret: string
15
+ keyId?: string
16
+ capabilities?: string[]
17
+ supportedWireFormats?: WireFormat[]
18
+ maxBatchSize?: number
19
+ ackModes?: AckMode[]
20
+ requireSignature?: boolean
21
+ replayCache?: InMemoryReplayCache
22
+ sharedSecrets?: Record<string, string>
23
+ resolveInboundSecret?: (keyId: string, sender: string) => string | undefined | Promise<string | undefined>
24
+ onTask?: (envelope: ProtocolEnvelope) => TaskHandlerResult | Promise<TaskHandlerResult>
25
+ }
26
+
27
+ export interface AgentReceiveResult {
28
+ ok: boolean
29
+ diagnostics: ProtocolDiagnostic[]
30
+ received: ProtocolEnvelope | null
31
+ response: ProtocolEnvelope | null
32
+ }
33
+
34
+ export class AgentSession {
35
+ private readonly agentId: string
36
+ private readonly outboundSecret: string
37
+ private readonly keyId: string
38
+ private readonly capabilities: string[]
39
+ private readonly supportedWireFormats: WireFormat[]
40
+ private readonly maxBatchSize: number
41
+ private readonly ackModes: AckMode[]
42
+ private readonly requireSignature: boolean
43
+ private readonly replayCache: InMemoryReplayCache
44
+ private readonly sharedSecrets: Record<string, string>
45
+ private readonly resolveInboundSecret?: (keyId: string, sender: string) => string | undefined | Promise<string | undefined>
46
+ private readonly onTask?: (envelope: ProtocolEnvelope) => TaskHandlerResult | Promise<TaskHandlerResult>
47
+
48
+ constructor(config: AgentSessionConfig) {
49
+ this.agentId = config.agentId
50
+ this.outboundSecret = config.outboundSecret
51
+ this.keyId = config.keyId ?? `${config.agentId}-k1`
52
+ this.capabilities = config.capabilities ?? []
53
+ this.supportedWireFormats = config.supportedWireFormats ?? ['compact', 'json']
54
+ this.maxBatchSize = config.maxBatchSize ?? 1
55
+ this.ackModes = config.ackModes ?? ['receipt']
56
+ this.requireSignature = config.requireSignature ?? true
57
+ this.replayCache = config.replayCache ?? new InMemoryReplayCache()
58
+ this.sharedSecrets = config.sharedSecrets ?? {}
59
+ this.resolveInboundSecret = config.resolveInboundSecret
60
+ this.onTask = config.onTask
61
+ }
62
+
63
+ private async inboundSecretResolver(keyId: string, sender: string): Promise<string | undefined> {
64
+ if (this.resolveInboundSecret) {
65
+ return this.resolveInboundSecret(keyId, sender)
66
+ }
67
+ return this.sharedSecrets[sender]
68
+ }
69
+
70
+ async createSignedIntent(input: {
71
+ recipient?: string
72
+ intent: IntentKind
73
+ content: string
74
+ capability?: string
75
+ correlationId?: string
76
+ ttlMs?: number
77
+ messageId?: string
78
+ nonce?: string
79
+ nowMs?: number
80
+ }): Promise<ProtocolEnvelope> {
81
+ const unsigned = createEnvelope({
82
+ sender: this.agentId,
83
+ recipient: input.recipient,
84
+ intent: input.intent,
85
+ content: input.content,
86
+ capability: input.capability,
87
+ correlationId: input.correlationId,
88
+ ttlMs: input.ttlMs,
89
+ messageId: input.messageId,
90
+ nonce: input.nonce,
91
+ nowMs: input.nowMs,
92
+ })
93
+ return signEnvelopeHmac(unsigned, this.outboundSecret, this.keyId)
94
+ }
95
+
96
+ async receiveAndRespond(input: WireEnvelope | ProtocolEnvelope, nowMs = Date.now()): Promise<AgentReceiveResult> {
97
+ const received = await receiveEnvelope(input, {
98
+ nowMs,
99
+ requireSignature: this.requireSignature,
100
+ replayCache: this.replayCache,
101
+ secretResolver: (keyId, sender) => this.inboundSecretResolver(keyId, sender),
102
+ })
103
+
104
+ if (!received.ok || !received.envelope) {
105
+ return {
106
+ ok: false,
107
+ diagnostics: received.diagnostics,
108
+ received: received.envelope,
109
+ response: null,
110
+ }
111
+ }
112
+
113
+ const envelope = received.envelope
114
+ const response = await this.buildAutoResponse(envelope, nowMs)
115
+ return {
116
+ ok: true,
117
+ diagnostics: received.diagnostics,
118
+ received: envelope,
119
+ response,
120
+ }
121
+ }
122
+
123
+ private async buildAutoResponse(envelope: ProtocolEnvelope, nowMs: number): Promise<ProtocolEnvelope | null> {
124
+ if (envelope.body.intent === 'PING') {
125
+ return this.createSignedIntent({
126
+ recipient: envelope.header.sender,
127
+ intent: 'PONG',
128
+ content: 'pong',
129
+ correlationId: envelope.header.messageId,
130
+ nowMs,
131
+ })
132
+ }
133
+
134
+ if (envelope.body.intent === 'CAPS') {
135
+ return this.createSignedIntent({
136
+ recipient: envelope.header.sender,
137
+ intent: 'RESULT',
138
+ content: encodeAipCapabilities(
139
+ createAipCapabilities({
140
+ agent: this.agentId,
141
+ capabilities: this.capabilities,
142
+ wireFormats: this.supportedWireFormats,
143
+ batchMax: this.maxBatchSize,
144
+ ackModes: this.ackModes,
145
+ }),
146
+ ),
147
+ capability: 'caps',
148
+ correlationId: envelope.header.messageId,
149
+ nowMs,
150
+ })
151
+ }
152
+
153
+ if (envelope.body.intent === 'TASK') {
154
+ const taskResult = this.onTask
155
+ ? await this.onTask(envelope)
156
+ : { intent: 'RESULT' as const, content: 'ACK', capability: envelope.body.capability }
157
+ return this.createSignedIntent({
158
+ recipient: envelope.header.sender,
159
+ intent: taskResult.intent ?? 'RESULT',
160
+ content: taskResult.content,
161
+ capability: taskResult.capability,
162
+ correlationId: envelope.header.messageId,
163
+ nowMs,
164
+ })
165
+ }
166
+
167
+ return null
168
+ }
169
+ }