@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,165 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { createEnvelope, signEnvelopeEd25519, signEnvelopeHmac } from './protocol'
3
+ import { DEFAULT_MAX_BINARY_ENVELOPE_BYTES, decodeEnvelopeBinary, encodeEnvelopeBinary } from './protocolBinary'
4
+
5
+ function stringFieldOffset(raw: Uint8Array, fieldIndex: number): { lengthOffset: number; valueOffset: number; length: number } {
6
+ let offset = 4 + 1 + 1 + 8 + 4
7
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength)
8
+ for (let index = 0; index <= fieldIndex; index += 1) {
9
+ const lengthOffset = offset
10
+ const length = view.getUint32(lengthOffset, false)
11
+ const valueOffset = lengthOffset + 4
12
+ if (index === fieldIndex) return { lengthOffset, valueOffset, length }
13
+ offset = valueOffset + length
14
+ }
15
+ throw new Error(`missing string field ${fieldIndex}`)
16
+ }
17
+
18
+ function replaceAscii(raw: Uint8Array, fieldIndex: number, value: string): Uint8Array {
19
+ const copy = raw.slice()
20
+ const field = stringFieldOffset(copy, fieldIndex)
21
+ if (value.length !== field.length) throw new Error('replacement must preserve encoded length')
22
+ for (let index = 0; index < value.length; index += 1) {
23
+ copy[field.valueOffset + index] = value.charCodeAt(index)
24
+ }
25
+ return copy
26
+ }
27
+
28
+ describe('AIP binary wire codec', () => {
29
+ it('roundtrips HS256 signed envelope', async () => {
30
+ const signed = await signEnvelopeHmac(
31
+ createEnvelope({
32
+ sender: 'agent.alpha',
33
+ recipient: 'agent.beta',
34
+ intent: 'TASK',
35
+ content: 'route:binary',
36
+ capability: 'task.plan',
37
+ correlationId: 'corr-b1',
38
+ messageId: 'bin-1',
39
+ nonce: 'nb1',
40
+ nowMs: 1000,
41
+ ttlMs: 60_000,
42
+ }),
43
+ 'shared-secret',
44
+ 'k1',
45
+ )
46
+
47
+ const raw = encodeEnvelopeBinary(signed)
48
+ const decoded = decodeEnvelopeBinary(raw)
49
+ expect(decoded.ok).toBe(true)
50
+ expect(decoded.envelope).toEqual(signed)
51
+ })
52
+
53
+ it('roundtrips ED25519 signed envelope', async () => {
54
+ const privateKey = 'MC4CAQAwBQYDK2VwBCIEICheZbQGuDVb6hezIlcs0QnCHGxz6IhiLkC9M0qr8OOZ'
55
+ const signed = await signEnvelopeEd25519(
56
+ createEnvelope({
57
+ sender: 'agent.ed',
58
+ recipient: 'agent.verify',
59
+ intent: 'TASK',
60
+ content: 'route:ed25519-binary',
61
+ capability: 'task.sign',
62
+ correlationId: 'corr-ed-b1',
63
+ messageId: 'bin-ed-1',
64
+ nonce: 'n-ed-b1',
65
+ nowMs: 1000,
66
+ ttlMs: 45_000,
67
+ }),
68
+ privateKey,
69
+ 'ed-k1',
70
+ )
71
+
72
+ const raw = encodeEnvelopeBinary(signed)
73
+ const decoded = decodeEnvelopeBinary(raw)
74
+ expect(decoded.ok).toBe(true)
75
+ expect(decoded.envelope).toEqual(signed)
76
+ })
77
+
78
+ it('rejects bad magic and trailing bytes', async () => {
79
+ const signed = await signEnvelopeHmac(
80
+ createEnvelope({
81
+ sender: 'agent.alpha',
82
+ intent: 'PING',
83
+ content: 'x',
84
+ messageId: 'bin-2',
85
+ nonce: 'nb2',
86
+ nowMs: 1000,
87
+ ttlMs: 60_000,
88
+ }),
89
+ 'shared-secret',
90
+ 'k1',
91
+ )
92
+
93
+ const raw = encodeEnvelopeBinary(signed)
94
+ const badMagic = raw.slice()
95
+ badMagic[0] = 0
96
+ const decodedMagic = decodeEnvelopeBinary(badMagic)
97
+ expect(decodedMagic.ok).toBe(false)
98
+ expect(decodedMagic.diagnostics.some((d) => d.message.includes('magic'))).toBe(true)
99
+
100
+ const trailing = new Uint8Array(raw.byteLength + 1)
101
+ trailing.set(raw)
102
+ trailing[raw.byteLength] = 1
103
+ const decodedTrailing = decodeEnvelopeBinary(trailing)
104
+ expect(decodedTrailing.ok).toBe(false)
105
+ expect(decodedTrailing.diagnostics.some((d) => d.message.includes('Trailing bytes'))).toBe(true)
106
+ })
107
+
108
+ it('rejects oversized binary frames before parsing', () => {
109
+ const oversized = new Uint8Array(DEFAULT_MAX_BINARY_ENVELOPE_BYTES + 1)
110
+ const decoded = decodeEnvelopeBinary(oversized)
111
+
112
+ expect(decoded.ok).toBe(false)
113
+ expect(decoded.diagnostics.some((d) => d.message.includes('maximum frame size'))).toBe(true)
114
+ })
115
+
116
+ it('rejects malformed string lengths', async () => {
117
+ const signed = await signEnvelopeHmac(
118
+ createEnvelope({
119
+ sender: 'agent.alpha',
120
+ intent: 'PING',
121
+ content: 'x',
122
+ messageId: 'bin-malformed-length',
123
+ nonce: 'nb-malformed-length',
124
+ nowMs: 1000,
125
+ ttlMs: 60_000,
126
+ }),
127
+ 'shared-secret',
128
+ 'k1',
129
+ )
130
+
131
+ const raw = encodeEnvelopeBinary(signed)
132
+ const malformed = raw.slice()
133
+ const version = stringFieldOffset(malformed, 0)
134
+ new DataView(malformed.buffer, malformed.byteOffset, malformed.byteLength).setUint32(version.lengthOffset, raw.byteLength, false)
135
+
136
+ const decoded = decodeEnvelopeBinary(malformed)
137
+ expect(decoded.ok).toBe(false)
138
+ expect(decoded.diagnostics.some((d) => d.message.includes('Unexpected end'))).toBe(true)
139
+ })
140
+
141
+ it('rejects unsupported decoded protocol fields', async () => {
142
+ const signed = await signEnvelopeHmac(
143
+ createEnvelope({
144
+ sender: 'agent.alpha',
145
+ intent: 'TASK',
146
+ content: 'x',
147
+ messageId: 'bin-invalid-fields',
148
+ nonce: 'nb-invalid-fields',
149
+ nowMs: 1000,
150
+ ttlMs: 60_000,
151
+ }),
152
+ 'shared-secret',
153
+ 'k1',
154
+ )
155
+
156
+ const raw = encodeEnvelopeBinary(signed)
157
+ const badVersion = decodeEnvelopeBinary(replaceAscii(raw, 0, 'aip/0.2'))
158
+ const badIntent = decodeEnvelopeBinary(replaceAscii(raw, 4, 'NOPE'))
159
+
160
+ expect(badVersion.ok).toBe(false)
161
+ expect(badVersion.diagnostics.some((d) => d.message.includes('Unsupported protocol version'))).toBe(true)
162
+ expect(badIntent.ok).toBe(false)
163
+ expect(badIntent.diagnostics.some((d) => d.message.includes('Unsupported intent'))).toBe(true)
164
+ })
165
+ })
@@ -0,0 +1,312 @@
1
+ import type { ProtocolEnvelope, ProtocolSignature } from './protocol'
2
+ import type { ReceiveEnvelopeResult } from './protocolTransport'
3
+
4
+ const MAGIC = [0x41, 0x49, 0x50, 0x42] as const // AIPB
5
+ const MAGIC_BYTES = Uint8Array.from(MAGIC)
6
+ const FORMAT_VERSION = 1
7
+ export const DEFAULT_MAX_BINARY_ENVELOPE_BYTES = 1024 * 1024
8
+
9
+ const FLAG_RECIPIENT = 1 << 0
10
+ const FLAG_CAPABILITY = 1 << 1
11
+ const FLAG_CORRELATION = 1 << 2
12
+ const FLAG_SIGNATURE = 1 << 3
13
+ const textEncoder = new TextEncoder()
14
+ const textDecoder = new TextDecoder()
15
+ const INTENT_KINDS = new Set(['PING', 'PONG', 'CAPS', 'TASK', 'RESULT', 'ERROR'])
16
+
17
+ export interface BinaryDecodeOptions {
18
+ maxFrameBytes?: number
19
+ }
20
+
21
+ function utf8Encode(value: string): Uint8Array {
22
+ return textEncoder.encode(value)
23
+ }
24
+
25
+ function utf8Decode(value: Uint8Array): string {
26
+ return textDecoder.decode(value)
27
+ }
28
+
29
+ function signatureAlgCode(alg: ProtocolSignature['alg']): number {
30
+ return alg === 'ED25519' ? 2 : 1
31
+ }
32
+
33
+ function signatureAlgFromCode(code: number): ProtocolSignature['alg'] | null {
34
+ if (code === 1) return 'HS256'
35
+ if (code === 2) return 'ED25519'
36
+ return null
37
+ }
38
+
39
+ interface EncodedString {
40
+ bytes: Uint8Array
41
+ }
42
+
43
+ function encodeString(value: string): EncodedString {
44
+ return { bytes: utf8Encode(value) }
45
+ }
46
+
47
+ function encodedStringSize(encoded: EncodedString | null): number {
48
+ return encoded ? 4 + encoded.bytes.byteLength : 0
49
+ }
50
+
51
+ class BinaryWriter {
52
+ private readonly bytes: Uint8Array
53
+
54
+ private readonly view: DataView
55
+
56
+ private offset = 0
57
+
58
+ constructor(size: number) {
59
+ this.bytes = new Uint8Array(size)
60
+ this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)
61
+ }
62
+
63
+ writeU8(value: number): void {
64
+ this.bytes[this.offset] = value & 0xff
65
+ this.offset += 1
66
+ }
67
+
68
+ writeU32(value: number): void {
69
+ this.view.setUint32(this.offset, value, false)
70
+ this.offset += 4
71
+ }
72
+
73
+ writeU64(value: number): void {
74
+ this.view.setBigUint64(this.offset, BigInt(value), false)
75
+ this.offset += 8
76
+ }
77
+
78
+ writeBytes(value: Uint8Array): void {
79
+ this.bytes.set(value, this.offset)
80
+ this.offset += value.byteLength
81
+ }
82
+
83
+ writeString(encoded: EncodedString): void {
84
+ this.writeU32(encoded.bytes.byteLength)
85
+ this.writeBytes(encoded.bytes)
86
+ }
87
+
88
+ finish(): Uint8Array {
89
+ return this.bytes
90
+ }
91
+ }
92
+
93
+ class BinaryReader {
94
+ private readonly bytes: Uint8Array
95
+
96
+ private offset = 0
97
+
98
+ constructor(bytes: Uint8Array) {
99
+ this.bytes = bytes
100
+ }
101
+
102
+ remaining(): number {
103
+ return this.bytes.byteLength - this.offset
104
+ }
105
+
106
+ readU8(): number {
107
+ if (this.remaining() < 1) throw new Error('Unexpected end of binary envelope')
108
+ const value = this.bytes[this.offset]
109
+ this.offset += 1
110
+ return value ?? 0
111
+ }
112
+
113
+ readU32(): number {
114
+ if (this.remaining() < 4) throw new Error('Unexpected end of binary envelope')
115
+ const value = new DataView(this.bytes.buffer, this.bytes.byteOffset + this.offset, 4).getUint32(0, false)
116
+ this.offset += 4
117
+ return value
118
+ }
119
+
120
+ readU64(): number {
121
+ if (this.remaining() < 8) throw new Error('Unexpected end of binary envelope')
122
+ const value = new DataView(this.bytes.buffer, this.bytes.byteOffset + this.offset, 8).getBigUint64(0, false)
123
+ this.offset += 8
124
+ return Number(value)
125
+ }
126
+
127
+ readBytes(length: number): Uint8Array {
128
+ if (length < 0 || this.remaining() < length) throw new Error('Unexpected end of binary envelope')
129
+ const value = this.bytes.slice(this.offset, this.offset + length)
130
+ this.offset += length
131
+ return value
132
+ }
133
+
134
+ readString(): string {
135
+ const length = this.readU32()
136
+ const value = this.readBytes(length)
137
+ return utf8Decode(value)
138
+ }
139
+ }
140
+
141
+ export function encodeEnvelopeBinary(envelope: ProtocolEnvelope): Uint8Array {
142
+ const flags =
143
+ (envelope.header.recipient ? FLAG_RECIPIENT : 0) |
144
+ (envelope.body.capability ? FLAG_CAPABILITY : 0) |
145
+ (envelope.body.correlationId ? FLAG_CORRELATION : 0) |
146
+ (envelope.signature ? FLAG_SIGNATURE : 0)
147
+
148
+ const version = encodeString(envelope.header.version)
149
+ const messageId = encodeString(envelope.header.messageId)
150
+ const sender = encodeString(envelope.header.sender)
151
+ const nonce = encodeString(envelope.header.nonce)
152
+ const intent = encodeString(envelope.body.intent)
153
+ const content = encodeString(envelope.body.content)
154
+ const recipient = envelope.header.recipient ? encodeString(envelope.header.recipient) : null
155
+ const capability = envelope.body.capability ? encodeString(envelope.body.capability) : null
156
+ const correlationId = envelope.body.correlationId ? encodeString(envelope.body.correlationId) : null
157
+ const signatureKeyId = envelope.signature ? encodeString(envelope.signature.keyId) : null
158
+ const signatureValue = envelope.signature ? encodeString(envelope.signature.value) : null
159
+
160
+ const size =
161
+ MAGIC_BYTES.byteLength +
162
+ 1 +
163
+ 1 +
164
+ 8 +
165
+ 4 +
166
+ encodedStringSize(version) +
167
+ encodedStringSize(messageId) +
168
+ encodedStringSize(sender) +
169
+ encodedStringSize(nonce) +
170
+ encodedStringSize(intent) +
171
+ encodedStringSize(content) +
172
+ encodedStringSize(recipient) +
173
+ encodedStringSize(capability) +
174
+ encodedStringSize(correlationId) +
175
+ (envelope.signature ? 1 : 0) +
176
+ encodedStringSize(signatureKeyId) +
177
+ encodedStringSize(signatureValue)
178
+
179
+ const writer = new BinaryWriter(size)
180
+ writer.writeBytes(MAGIC_BYTES)
181
+ writer.writeU8(FORMAT_VERSION)
182
+ writer.writeU8(flags)
183
+ writer.writeU64(envelope.header.timestampMs)
184
+ writer.writeU32(envelope.header.ttlMs)
185
+
186
+ writer.writeString(version)
187
+ writer.writeString(messageId)
188
+ writer.writeString(sender)
189
+ writer.writeString(nonce)
190
+ writer.writeString(intent)
191
+ writer.writeString(content)
192
+
193
+ if (recipient) writer.writeString(recipient)
194
+ if (capability) writer.writeString(capability)
195
+ if (correlationId) writer.writeString(correlationId)
196
+
197
+ if (envelope.signature && signatureKeyId && signatureValue) {
198
+ writer.writeU8(signatureAlgCode(envelope.signature.alg))
199
+ writer.writeString(signatureKeyId)
200
+ writer.writeString(signatureValue)
201
+ }
202
+
203
+ return writer.finish()
204
+ }
205
+
206
+ export function decodeEnvelopeBinary(payload: Uint8Array, options: BinaryDecodeOptions = {}): ReceiveEnvelopeResult {
207
+ try {
208
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_BINARY_ENVELOPE_BYTES
209
+ if (payload.byteLength > maxFrameBytes) {
210
+ return {
211
+ ok: false,
212
+ diagnostics: [{ level: 'error', message: `Binary envelope exceeds maximum frame size '${maxFrameBytes}'` }],
213
+ envelope: null,
214
+ }
215
+ }
216
+
217
+ const reader = new BinaryReader(payload)
218
+ const magic = [reader.readU8(), reader.readU8(), reader.readU8(), reader.readU8()]
219
+ if (magic.some((value, idx) => value !== MAGIC[idx])) {
220
+ return {
221
+ ok: false,
222
+ diagnostics: [{ level: 'error', message: 'Invalid binary envelope magic' }],
223
+ envelope: null,
224
+ }
225
+ }
226
+
227
+ const version = reader.readU8()
228
+ if (version !== FORMAT_VERSION) {
229
+ return {
230
+ ok: false,
231
+ diagnostics: [{ level: 'error', message: `Unsupported binary envelope version '${version}'` }],
232
+ envelope: null,
233
+ }
234
+ }
235
+
236
+ const flags = reader.readU8()
237
+ const timestampMs = reader.readU64()
238
+ const ttlMs = reader.readU32()
239
+
240
+ const envelope: ProtocolEnvelope = {
241
+ header: {
242
+ version: reader.readString() as '7h3/0.1',
243
+ messageId: reader.readString(),
244
+ timestampMs,
245
+ ttlMs,
246
+ sender: reader.readString(),
247
+ nonce: reader.readString(),
248
+ },
249
+ body: {
250
+ intent: reader.readString() as ProtocolEnvelope['body']['intent'],
251
+ content: reader.readString(),
252
+ },
253
+ }
254
+
255
+ if (envelope.header.version !== '7h3/0.1') {
256
+ return {
257
+ ok: false,
258
+ diagnostics: [{ level: 'error', message: `Unsupported protocol version '${envelope.header.version}'` }],
259
+ envelope: null,
260
+ }
261
+ }
262
+
263
+ if (!INTENT_KINDS.has(envelope.body.intent)) {
264
+ return {
265
+ ok: false,
266
+ diagnostics: [{ level: 'error', message: `Unsupported intent '${envelope.body.intent}'` }],
267
+ envelope: null,
268
+ }
269
+ }
270
+
271
+ if (flags & FLAG_RECIPIENT) envelope.header.recipient = reader.readString()
272
+ if (flags & FLAG_CAPABILITY) envelope.body.capability = reader.readString()
273
+ if (flags & FLAG_CORRELATION) envelope.body.correlationId = reader.readString()
274
+
275
+ if (flags & FLAG_SIGNATURE) {
276
+ const algCode = reader.readU8()
277
+ const alg = signatureAlgFromCode(algCode)
278
+ if (!alg) {
279
+ return {
280
+ ok: false,
281
+ diagnostics: [{ level: 'error', message: `Unsupported binary signature algorithm '${algCode}'` }],
282
+ envelope: null,
283
+ }
284
+ }
285
+ envelope.signature = {
286
+ alg,
287
+ keyId: reader.readString(),
288
+ value: reader.readString(),
289
+ }
290
+ }
291
+
292
+ if (reader.remaining() !== 0) {
293
+ return {
294
+ ok: false,
295
+ diagnostics: [{ level: 'error', message: 'Trailing bytes found in binary envelope' }],
296
+ envelope: null,
297
+ }
298
+ }
299
+
300
+ return {
301
+ ok: true,
302
+ diagnostics: [],
303
+ envelope,
304
+ }
305
+ } catch (error: unknown) {
306
+ return {
307
+ ok: false,
308
+ diagnostics: [{ level: 'error', message: error instanceof Error ? error.message : 'Invalid binary envelope' }],
309
+ envelope: null,
310
+ }
311
+ }
312
+ }
@@ -0,0 +1,70 @@
1
+ import type { WireFormat } from './protocolTransport'
2
+
3
+ export type AckMode = 'fast' | 'receipt'
4
+
5
+ export interface AipCapabilities {
6
+ agent: string
7
+ capabilities: string[]
8
+ wireFormats: WireFormat[]
9
+ batchMax: number
10
+ ackModes: AckMode[]
11
+ }
12
+
13
+ export interface NegotiatedAipCapabilities {
14
+ wireFormat: WireFormat
15
+ batchMax: number
16
+ ackMode: AckMode
17
+ }
18
+
19
+ const WIRE_FORMAT_ORDER: WireFormat[] = ['binary', 'compact', 'json']
20
+ const ACK_MODE_ORDER: AckMode[] = ['fast', 'receipt']
21
+
22
+ export function createAipCapabilities(input: {
23
+ agent: string
24
+ capabilities?: string[]
25
+ wireFormats?: WireFormat[]
26
+ batchMax?: number
27
+ ackModes?: AckMode[]
28
+ }): AipCapabilities {
29
+ return {
30
+ agent: input.agent,
31
+ capabilities: input.capabilities ?? [],
32
+ wireFormats: input.wireFormats ?? ['compact', 'json'],
33
+ batchMax: input.batchMax ?? 1,
34
+ ackModes: input.ackModes ?? ['receipt'],
35
+ }
36
+ }
37
+
38
+ export function encodeAipCapabilities(capabilities: AipCapabilities): string {
39
+ return JSON.stringify(capabilities)
40
+ }
41
+
42
+ export function parseAipCapabilities(raw: string): AipCapabilities | null {
43
+ try {
44
+ const parsed = JSON.parse(raw) as Partial<AipCapabilities>
45
+ if (typeof parsed.agent !== 'string') return null
46
+ if (!Array.isArray(parsed.capabilities)) return null
47
+ if (!Array.isArray(parsed.wireFormats)) return null
48
+ if (!Array.isArray(parsed.ackModes)) return null
49
+ if (typeof parsed.batchMax !== 'number' || parsed.batchMax < 1) return null
50
+ return {
51
+ agent: parsed.agent,
52
+ capabilities: parsed.capabilities.filter((item): item is string => typeof item === 'string'),
53
+ wireFormats: parsed.wireFormats.filter((item): item is WireFormat => item === 'json' || item === 'compact' || item === 'binary'),
54
+ batchMax: Math.floor(parsed.batchMax),
55
+ ackModes: parsed.ackModes.filter((item): item is AckMode => item === 'fast' || item === 'receipt'),
56
+ }
57
+ } catch {
58
+ return null
59
+ }
60
+ }
61
+
62
+ export function negotiateAipCapabilities(local: AipCapabilities, remote: AipCapabilities): NegotiatedAipCapabilities {
63
+ const wireFormat = WIRE_FORMAT_ORDER.find((format) => local.wireFormats.includes(format) && remote.wireFormats.includes(format)) ?? 'compact'
64
+ const ackMode = ACK_MODE_ORDER.find((mode) => local.ackModes.includes(mode) && remote.ackModes.includes(mode)) ?? 'receipt'
65
+ return {
66
+ wireFormat,
67
+ batchMax: Math.max(1, Math.min(local.batchMax, remote.batchMax)),
68
+ ackMode,
69
+ }
70
+ }