@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.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 (206) hide show
  1. package/GUIDE.md +975 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION.md +84 -0
  4. package/MIGRATION.zh.md +70 -0
  5. package/PROVIDERS.md +273 -0
  6. package/PROVIDERS.zh.md +234 -0
  7. package/README.md +334 -2
  8. package/dist/AgentClient.d.ts +312 -0
  9. package/dist/AgentClient.d.ts.map +1 -0
  10. package/dist/AgentClient.js +715 -0
  11. package/dist/AgentClient.js.map +1 -0
  12. package/dist/AgenticID.d.ts +823 -0
  13. package/dist/AgenticID.d.ts.map +1 -0
  14. package/dist/AgenticID.js +1188 -0
  15. package/dist/AgenticID.js.map +1 -0
  16. package/dist/AgenticIDClient.d.ts +68 -0
  17. package/dist/AgenticIDClient.d.ts.map +1 -0
  18. package/dist/AgenticIDClient.js +198 -0
  19. package/dist/AgenticIDClient.js.map +1 -0
  20. package/dist/AttestorClient.d.ts +465 -0
  21. package/dist/AttestorClient.d.ts.map +1 -0
  22. package/dist/AttestorClient.js +1030 -0
  23. package/dist/AttestorClient.js.map +1 -0
  24. package/dist/Providers.d.ts +72 -0
  25. package/dist/Providers.d.ts.map +1 -0
  26. package/dist/Providers.js +182 -0
  27. package/dist/Providers.js.map +1 -0
  28. package/dist/ReputationClient.d.ts +213 -0
  29. package/dist/ReputationClient.d.ts.map +1 -0
  30. package/dist/ReputationClient.js +708 -0
  31. package/dist/ReputationClient.js.map +1 -0
  32. package/dist/SandboxClient.d.ts +107 -0
  33. package/dist/SandboxClient.d.ts.map +1 -0
  34. package/dist/SandboxClient.js +200 -0
  35. package/dist/SandboxClient.js.map +1 -0
  36. package/dist/ServeProof.d.ts +161 -0
  37. package/dist/ServeProof.d.ts.map +1 -0
  38. package/dist/ServeProof.js +230 -0
  39. package/dist/ServeProof.js.map +1 -0
  40. package/dist/ServeSession.d.ts +180 -0
  41. package/dist/ServeSession.d.ts.map +1 -0
  42. package/dist/ServeSession.js +336 -0
  43. package/dist/ServeSession.js.map +1 -0
  44. package/dist/Settings.d.ts +179 -0
  45. package/dist/Settings.d.ts.map +1 -0
  46. package/dist/Settings.js +247 -0
  47. package/dist/Settings.js.map +1 -0
  48. package/dist/abi.d.ts +2216 -0
  49. package/dist/abi.d.ts.map +1 -0
  50. package/dist/abi.js +1248 -0
  51. package/dist/abi.js.map +1 -0
  52. package/dist/cli/commands/cells.d.ts +62 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +113 -0
  55. package/dist/cli/commands/cells.js.map +1 -0
  56. package/dist/cli/commands/doctor.d.ts +15 -0
  57. package/dist/cli/commands/doctor.d.ts.map +1 -0
  58. package/dist/cli/commands/doctor.js +236 -0
  59. package/dist/cli/commands/doctor.js.map +1 -0
  60. package/dist/cli/commands/interactive.d.ts +115 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3052 -0
  63. package/dist/cli/commands/interactive.js.map +1 -0
  64. package/dist/cli/commands/list.d.ts +31 -0
  65. package/dist/cli/commands/list.d.ts.map +1 -0
  66. package/dist/cli/commands/list.js +91 -0
  67. package/dist/cli/commands/list.js.map +1 -0
  68. package/dist/cli/commands/providers.d.ts +3 -0
  69. package/dist/cli/commands/providers.d.ts.map +1 -0
  70. package/dist/cli/commands/providers.js +21 -0
  71. package/dist/cli/commands/providers.js.map +1 -0
  72. package/dist/cli/commands/settings.d.ts +22 -0
  73. package/dist/cli/commands/settings.d.ts.map +1 -0
  74. package/dist/cli/commands/settings.js +188 -0
  75. package/dist/cli/commands/settings.js.map +1 -0
  76. package/dist/cli/commands/status.d.ts +16 -0
  77. package/dist/cli/commands/status.d.ts.map +1 -0
  78. package/dist/cli/commands/status.js +148 -0
  79. package/dist/cli/commands/status.js.map +1 -0
  80. package/dist/cli/commands/update.d.ts +21 -0
  81. package/dist/cli/commands/update.d.ts.map +1 -0
  82. package/dist/cli/commands/update.js +95 -0
  83. package/dist/cli/commands/update.js.map +1 -0
  84. package/dist/cli/config.d.ts +73 -0
  85. package/dist/cli/config.d.ts.map +1 -0
  86. package/dist/cli/config.js +239 -0
  87. package/dist/cli/config.js.map +1 -0
  88. package/dist/cli/env.d.ts +36 -0
  89. package/dist/cli/env.d.ts.map +1 -0
  90. package/dist/cli/env.js +74 -0
  91. package/dist/cli/env.js.map +1 -0
  92. package/dist/cli/envelope.d.ts +33 -0
  93. package/dist/cli/envelope.d.ts.map +1 -0
  94. package/dist/cli/envelope.js +62 -0
  95. package/dist/cli/envelope.js.map +1 -0
  96. package/dist/cli/errors.d.ts +48 -0
  97. package/dist/cli/errors.d.ts.map +1 -0
  98. package/dist/cli/errors.js +81 -0
  99. package/dist/cli/errors.js.map +1 -0
  100. package/dist/cli/inference.d.ts +21 -0
  101. package/dist/cli/inference.d.ts.map +1 -0
  102. package/dist/cli/inference.js +60 -0
  103. package/dist/cli/inference.js.map +1 -0
  104. package/dist/cli/logo.d.ts +21 -0
  105. package/dist/cli/logo.d.ts.map +1 -0
  106. package/dist/cli/logo.js +131 -0
  107. package/dist/cli/logo.js.map +1 -0
  108. package/dist/cli/main.d.ts +14 -0
  109. package/dist/cli/main.d.ts.map +1 -0
  110. package/dist/cli/main.js +223 -0
  111. package/dist/cli/main.js.map +1 -0
  112. package/dist/cli/proofs.d.ts +67 -0
  113. package/dist/cli/proofs.d.ts.map +1 -0
  114. package/dist/cli/proofs.js +133 -0
  115. package/dist/cli/proofs.js.map +1 -0
  116. package/dist/cli/ref.d.ts +39 -0
  117. package/dist/cli/ref.d.ts.map +1 -0
  118. package/dist/cli/ref.js +48 -0
  119. package/dist/cli/ref.js.map +1 -0
  120. package/dist/cli/sdk.d.ts +24 -0
  121. package/dist/cli/sdk.d.ts.map +1 -0
  122. package/dist/cli/sdk.js +65 -0
  123. package/dist/cli/sdk.js.map +1 -0
  124. package/dist/cli/settings.d.ts +66 -0
  125. package/dist/cli/settings.d.ts.map +1 -0
  126. package/dist/cli/settings.js +137 -0
  127. package/dist/cli/settings.js.map +1 -0
  128. package/dist/cli/tokenize.d.ts +61 -0
  129. package/dist/cli/tokenize.d.ts.map +1 -0
  130. package/dist/cli/tokenize.js +157 -0
  131. package/dist/cli/tokenize.js.map +1 -0
  132. package/dist/cli/types.d.ts +25 -0
  133. package/dist/cli/types.d.ts.map +1 -0
  134. package/dist/cli/types.js +8 -0
  135. package/dist/cli/types.js.map +1 -0
  136. package/dist/constants.d.ts +107 -0
  137. package/dist/constants.d.ts.map +1 -0
  138. package/dist/constants.js +74 -0
  139. package/dist/constants.js.map +1 -0
  140. package/dist/context.d.ts +108 -0
  141. package/dist/context.d.ts.map +1 -0
  142. package/dist/context.js +64 -0
  143. package/dist/context.js.map +1 -0
  144. package/dist/index.d.ts +45 -0
  145. package/dist/index.d.ts.map +1 -0
  146. package/dist/index.js +118 -0
  147. package/dist/index.js.map +1 -0
  148. package/dist/provider-catalog.json +23 -0
  149. package/dist/seal.d.ts +47 -0
  150. package/dist/seal.d.ts.map +1 -0
  151. package/dist/seal.js +145 -0
  152. package/dist/seal.js.map +1 -0
  153. package/dist/secretEnv.d.ts +119 -0
  154. package/dist/secretEnv.d.ts.map +1 -0
  155. package/dist/secretEnv.js +199 -0
  156. package/dist/secretEnv.js.map +1 -0
  157. package/dist/taskHash.d.ts +39 -0
  158. package/dist/taskHash.d.ts.map +1 -0
  159. package/dist/taskHash.js +119 -0
  160. package/dist/taskHash.js.map +1 -0
  161. package/dist/types.d.ts +336 -0
  162. package/dist/types.d.ts.map +1 -0
  163. package/dist/types.js +19 -0
  164. package/dist/types.js.map +1 -0
  165. package/package.json +75 -4
  166. package/scripts/sync-providers.cjs +8 -0
  167. package/src/AgentClient.ts +897 -0
  168. package/src/AgenticID.ts +1382 -0
  169. package/src/AgenticIDClient.ts +238 -0
  170. package/src/AttestorClient.ts +1306 -0
  171. package/src/Providers.ts +176 -0
  172. package/src/ReputationClient.ts +821 -0
  173. package/src/SandboxClient.ts +227 -0
  174. package/src/ServeProof.ts +290 -0
  175. package/src/ServeSession.ts +421 -0
  176. package/src/Settings.ts +296 -0
  177. package/src/abi.ts +1282 -0
  178. package/src/cli/commands/cells.ts +107 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2738 -0
  181. package/src/cli/commands/list.ts +95 -0
  182. package/src/cli/commands/providers.ts +16 -0
  183. package/src/cli/commands/settings.ts +197 -0
  184. package/src/cli/commands/status.ts +170 -0
  185. package/src/cli/commands/update.ts +86 -0
  186. package/src/cli/config.ts +225 -0
  187. package/src/cli/env.ts +90 -0
  188. package/src/cli/envelope.ts +57 -0
  189. package/src/cli/errors.ts +114 -0
  190. package/src/cli/inference.ts +57 -0
  191. package/src/cli/logo.ts +125 -0
  192. package/src/cli/main.ts +235 -0
  193. package/src/cli/proofs.ts +160 -0
  194. package/src/cli/ref.ts +58 -0
  195. package/src/cli/sdk.ts +65 -0
  196. package/src/cli/settings.ts +153 -0
  197. package/src/cli/tokenize.ts +131 -0
  198. package/src/cli/types.ts +27 -0
  199. package/src/constants.ts +106 -0
  200. package/src/context.ts +161 -0
  201. package/src/index.ts +129 -0
  202. package/src/provider-catalog.json +23 -0
  203. package/src/seal.ts +163 -0
  204. package/src/secretEnv.ts +250 -0
  205. package/src/taskHash.ts +100 -0
  206. package/src/types.ts +357 -0
@@ -0,0 +1,421 @@
1
+ /**
2
+ * @file ServeSession.ts
3
+ * @description Consumer-side transport for reputation: call an agent's serve
4
+ * endpoint (any framework, any path) and capture the TEE-signed ServeProof the
5
+ * sealed proxy stamps on every response as the `X-Agent-Proof` header.
6
+ *
7
+ * Each agent runs its own serve endpoint — whatever HTTP API it needs; the
8
+ * protocol doesn't prescribe one, so it differs per agent. The one invariant is
9
+ * the sealed proxy in front of it, which stamps `X-Agent-Proof` on every
10
+ * response. So this layer doesn't model the call — you invoke the agent however
11
+ * it expects; ServeSession only extracts the proof from the response. The proof
12
+ * is then submittable on-chain via ReputationClient.giveFeedback (attribution is
13
+ * msg.sender; only the proof's `submitter` may redeem it).
14
+ *
15
+ * Header format (from sealed/internal/proxy):
16
+ * X-Agent-Proof: 0x<65-byte sig hex>.<base64url(envelope JSON)>
17
+ * envelope JSON = { agent_id, submitter, timestamp, deadline, task_hash,
18
+ * data_hashes[], framework_hash, validator }
19
+ * `validator` (the VerifiedFeedbackRegistry the signature is bound to) is
20
+ * diagnostics only — not part of the on-chain ServeProof tuple — and absent on
21
+ * images that predate it.
22
+ */
23
+
24
+ import {
25
+ isAddress,
26
+ keccak256,
27
+ stringToBytes,
28
+ type Address,
29
+ type Hash,
30
+ type PublicClient,
31
+ } from 'viem';
32
+ import { agenticIDAbi } from './abi';
33
+ import { verifyServeProofSignature } from './ServeProof';
34
+ import { taskHashOf, requestUriCandidates } from './taskHash';
35
+ import { type Ctx } from './context';
36
+ import type { ServeProof, TaskReveal } from './types';
37
+
38
+ export const SERVE_PROOF_HEADER = 'X-Agent-Proof';
39
+
40
+ interface RawEnvelope {
41
+ agent_id: string;
42
+ submitter: `0x${string}`;
43
+ timestamp: number;
44
+ deadline: number;
45
+ task_hash: `0x${string}`;
46
+ data_hashes: `0x${string}`[];
47
+ framework_hash: `0x${string}`;
48
+ validator?: `0x${string}`;
49
+ }
50
+
51
+ const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' as const;
52
+
53
+ function b64urlDecode(s: string): string {
54
+ const b64 = s.replace(/-/g, '+').replace(/_/g, '/');
55
+ const g = globalThis as { atob?: (d: string) => string };
56
+ if (typeof g.atob === 'function') return g.atob(b64);
57
+ // Node fallback (envelope is ASCII, so binary === utf8 here).
58
+ return Buffer.from(b64, 'base64').toString('binary');
59
+ }
60
+
61
+ /**
62
+ * Parse an `X-Agent-Proof` header value into a ServeProof ready for
63
+ * ReputationClient.giveFeedback.
64
+ */
65
+ export function parseServeProofHeader(value: string): ServeProof {
66
+ const dot = value.indexOf('.');
67
+ if (dot < 0) throw new Error('malformed X-Agent-Proof header (missing ".")');
68
+ const signature = value.slice(0, dot) as `0x${string}`;
69
+ const env = JSON.parse(b64urlDecode(value.slice(dot + 1))) as RawEnvelope;
70
+ return {
71
+ agentId: BigInt(env.agent_id),
72
+ submitter: env.submitter ?? ZERO_ADDRESS,
73
+ timestamp: BigInt(env.timestamp),
74
+ deadline: BigInt(env.deadline),
75
+ taskHash: env.task_hash,
76
+ dataHashes: env.data_hashes ?? [],
77
+ frameworkHash: env.framework_hash,
78
+ signature,
79
+ // Unsigned diagnostics from an untrusted header: keep only a string.
80
+ ...(typeof env.validator === 'string' && env.validator ? { validator: env.validator } : {}),
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Extract the ServeProof from a fetch Response, or null if the agent did not
86
+ * stamp one (e.g. an unminted agent / dev mode).
87
+ */
88
+ export function proofFromResponse(res: { headers: { get(name: string): string | null } }): ServeProof | null {
89
+ const header = res.headers.get(SERVE_PROOF_HEADER);
90
+ return header ? parseServeProofHeader(header) : null;
91
+ }
92
+
93
+ /** The methods undici/fetch normalize to uppercase themselves (measured:
94
+ * get→GET … options→OPTIONS; anything else, e.g. `patch`, travels as
95
+ * written and the proxy hashes r.Method as received). Recording must
96
+ * uppercase exactly these six — more would hash a method the proxy never
97
+ * saw, fewer would record 'get' where the wire said 'GET'. */
98
+ const FETCH_NORMALIZED_METHODS = new Set(['get', 'head', 'post', 'put', 'delete', 'options']);
99
+
100
+ /** The HTTP method as it travels on the wire (see the set above). */
101
+ export function normalizedMethod(m?: string): string {
102
+ const s = m ?? 'GET';
103
+ return FETCH_NORMALIZED_METHODS.has(s.toLowerCase()) ? s.toUpperCase() : s;
104
+ }
105
+
106
+ /** The request body bytes as they traveled, for the taskHash preimage —
107
+ * or null when the shape cannot be captured faithfully (Blob/FormData
108
+ * are async, ReadableStream would block): the caller must treat the
109
+ * whole task as unrecorded, never hash a wrong '' stand-in. */
110
+ export function requestBytesOf(
111
+ body: unknown,
112
+ ): Uint8Array | string | null {
113
+ if (body == null) return '';
114
+ if (typeof body === 'string') return body;
115
+ if (body instanceof Uint8Array) return body;
116
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
117
+ if (body instanceof URLSearchParams) return body.toString(); // undici sends exactly this
118
+ if (body instanceof DataView) {
119
+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
120
+ }
121
+ return null; // Blob, FormData, ReadableStream, … — unrecordable, not wrong
122
+ }
123
+
124
+ /**
125
+ * A fetch-compatible wrapper for generic MCP clients: every SIGNED exchange
126
+ * it performs is recorded (proof + task) into `log`, and the Response is
127
+ * returned untouched, so an MCP SDK's streamable-HTTP transport accepts it
128
+ * as its custom fetch (the transport is passed to `client.connect()`).
129
+ * Unsigned responses are logged with `task: null` and their body is never
130
+ * read — a long-lived SSE listener would otherwise never resolve. After the
131
+ * session, verify each entry with `session.verifyProof(entry.proof, { task:
132
+ * entry.task })` — note `task: null` yields `ok: false` (fail closed), so
133
+ * skip entries whose task is null only when you know why it is.
134
+ *
135
+ * @example
136
+ * const log: Array<{ proof: ServeProof | null; task: TaskExchange | null }> = [];
137
+ * const client = new Client({ name: 'consumer', version: '1' });
138
+ * await client.connect(new StreamableHTTPClientTransport(url, {
139
+ * fetch: proofRecordingFetch(log),
140
+ * }));
141
+ * // … run the MCP session …
142
+ * for (const e of log) if (e.proof) {
143
+ * const v = await session.verifyProof(e.proof, { task: e.task });
144
+ * if (!v.ok || !v.taskMatches) throw new Error('unverified MCP exchange');
145
+ * }
146
+ */
147
+ export function proofRecordingFetch(
148
+ log: Array<{ proof: ServeProof | null; task: TaskExchange | null }>,
149
+ ): typeof fetch {
150
+ return (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
151
+ // A Request as input: clone it BEFORE fetch consumes its body, so the
152
+ // request bytes stay recoverable if the response turns out signed.
153
+ // init.body (when set) overrides the Request's own body on the wire —
154
+ // clone only when the Request's body is what will actually be sent.
155
+ // Per the Fetch spec, `init.body: null` falls back to the Request's
156
+ // body too, so only a non-null override defeats the clone.
157
+ const reqClone =
158
+ input instanceof Request && input.body && init?.body == null ? input.clone() : null;
159
+ const response = await fetch(input, init);
160
+ // Record the task only when the response carries X-Agent-Proof: a
161
+ // signed response is always finite (the proxy buffers it whole), so
162
+ // awaiting the clone cannot hang; an unsigned/SSE response is returned
163
+ // immediately — awaiting its body would block the caller's stream.
164
+ const proof = proofFromResponse(response);
165
+ let task: TaskExchange | null = null;
166
+ if (proof) {
167
+ try {
168
+ const url =
169
+ typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
170
+ const method =
171
+ input instanceof Request && !init?.method ? input.method : normalizedMethod(init?.method);
172
+ let reqBytes: Uint8Array | string | null;
173
+ if (reqClone) {
174
+ reqBytes = await reqClone.arrayBuffer().then((b) => new Uint8Array(b));
175
+ } else {
176
+ reqBytes = requestBytesOf(init?.body);
177
+ }
178
+ if (reqBytes !== null) {
179
+ const cloned = response.clone();
180
+ const respBytes = await cloned.arrayBuffer().then((b) => new Uint8Array(b));
181
+ task = { method, url, requestBytes: reqBytes, responseBytes: respBytes, status: response.status };
182
+ }
183
+ } catch {
184
+ task = null;
185
+ }
186
+ }
187
+ log.push({ proof, task });
188
+ return response;
189
+ }) as typeof fetch;
190
+ }
191
+
192
+ /**
193
+ * Build the TaskReveal(s) for an exchange you actually sent and received —
194
+ * the input to `verifyProof(proof, { task })`'s per-exchange binding. The
195
+ * proxy hashed one specific URI form; undici (Node fetch) and browsers
196
+ * differ on a bare trailing '?', so one reveal per requestUriCandidates
197
+ * form is returned and the comparison tries each.
198
+ *
199
+ * The bytes are hashed exactly as they traveled: pass the raw request body
200
+ * string/bytes and the raw response body (NOT a re-serialized JSON —
201
+ * key order and whitespace change the hash).
202
+ */
203
+ export function taskRevealOf(exchange: TaskExchange): TaskReveal[] {
204
+ const reqBytes = exchange.requestBytes ?? '';
205
+ const reqBodyHash = keccak256(
206
+ typeof reqBytes === 'string' ? stringToBytes(reqBytes) : reqBytes,
207
+ );
208
+ const respBodyHash = keccak256(
209
+ typeof exchange.responseBytes === 'string'
210
+ ? stringToBytes(exchange.responseBytes)
211
+ : exchange.responseBytes,
212
+ );
213
+ return requestUriCandidates(exchange.url).map((uri) => ({
214
+ method: exchange.method,
215
+ uri,
216
+ reqBodyHash,
217
+ respBodyHash,
218
+ statusCode: exchange.status,
219
+ }));
220
+ }
221
+
222
+ /**
223
+ * Run an agent call (yielding a Response) and capture its ServeProof.
224
+ * You still consume the body yourself (`response.json()` etc.).
225
+ *
226
+ * @example
227
+ * const { response, proof } = await captureProof(() =>
228
+ * fetch(`${agentUrl}/chat`, { method: 'POST', body }));
229
+ * const data = await response.json();
230
+ * if (proof) await rep.giveFeedback({ ...feedback, serveProof: proof });
231
+ */
232
+ export async function captureProof(
233
+ call: () => Promise<Response>,
234
+ ): Promise<{ response: Response; proof: ServeProof | null }> {
235
+ const response = await call();
236
+ return { response, proof: proofFromResponse(response) };
237
+ }
238
+
239
+ /** Result of a local ServeProof pre-check (before spending gas on-chain). */
240
+ export interface ProofVerification {
241
+ ok: boolean;
242
+ signerMatches: boolean;
243
+ notExpired: boolean;
244
+ dataOnChain: boolean;
245
+ /** False when no VerifiedFeedbackRegistry is configured, or the proof's
246
+ * envelope names a different one. The signature is then not checked
247
+ * (`signerMatches` is false too) — a configuration mismatch, not
248
+ * necessarily a bad proof. */
249
+ registryMatches: boolean;
250
+ /** null when no task was passed to verifyProof (the call means signer
251
+ * attribution only). With a task: whether the proof's taskHash equals
252
+ * the hash recomputed from that task — binding the proof to THIS
253
+ * exchange's method, URI, request body, response body and status, not
254
+ * just to the signer. Required for `ok` when a task is passed. */
255
+ taskMatches: boolean | null;
256
+ reasons: string[];
257
+ }
258
+
259
+ /** The exchange a proof's taskHash commits to, in caller-friendly form: what
260
+ * you actually sent and received. Turned into TaskReveal(s) by
261
+ * taskRevealOf (the URI the proxy hashed is not always knowable in
262
+ * advance, so each requestUriCandidates form gets one). */
263
+ export interface TaskExchange {
264
+ method: string;
265
+ /** The full request URL — only its path+query feed the hash, but the
266
+ * candidates are derived from the whole URL. */
267
+ url: string | URL;
268
+ /** Raw request body bytes/string as sent ('' for none). */
269
+ requestBytes?: Uint8Array | string;
270
+ /** Raw response body bytes/string as received. */
271
+ responseBytes: Uint8Array | string;
272
+ status: number;
273
+ }
274
+
275
+ export interface ServeSessionOptions {
276
+ /** Seconds of clock skew tolerated when checking the deadline. Default 0. */
277
+ clockSkew?: number;
278
+ /** Current unix time (seconds); injectable for testing. */
279
+ now?: () => number;
280
+ }
281
+
282
+ /**
283
+ * Chain-aware helper to validate a captured ServeProof before submitting — so a
284
+ * stale or mismatched proof is caught locally rather than by an on-chain revert.
285
+ */
286
+ export class ServeSession {
287
+ public readonly publicClient: PublicClient;
288
+ public readonly agenticID: Address;
289
+ /** The VerifiedFeedbackRegistry proxy — the intended validator every
290
+ * serve-proof signature is bound to. Zero = not configured. */
291
+ public readonly verifiedFeedback: Address;
292
+ private readonly clockSkew: number;
293
+ private readonly now: () => number;
294
+
295
+ constructor(ctx: Ctx, options: ServeSessionOptions = {}) {
296
+ this.agenticID = ctx.addresses.agenticID;
297
+ this.verifiedFeedback = ctx.addresses.verifiedFeedback ?? ZERO_ADDRESS;
298
+ this.publicClient = ctx.publicClient;
299
+ this.clockSkew = options.clockSkew ?? 0;
300
+ this.now = options.now ?? (() => Math.floor(Date.now() / 1000));
301
+ }
302
+
303
+ /**
304
+ * Verify a proof against chain state: signer == on-chain agentSeal (over the
305
+ * digest bound to the configured VerifiedFeedbackRegistry), deadline not
306
+ * passed, and every declared dataHash is present in the agent's on-chain
307
+ * iData (so the buyer knows what the agent was running).
308
+ *
309
+ * Needs `addresses.verifiedFeedback` (fromAttestor fills it): without it
310
+ * nothing can be verified and `signerMatches` / `registryMatches` are false.
311
+ */
312
+ /**
313
+ * Verify a proof against chain state. Without `opts.task` the verdict is
314
+ * signer attribution: the proof was signed by this agent's on-chain
315
+ * agentSeal, in time, over data the chain knows. With `opts.task` (a
316
+ * TaskReveal, or the TaskExchange you actually sent/received) the verdict
317
+ * additionally binds the proof to THAT exchange: `taskMatches` recomputes
318
+ * taskHash = keccak(method ‖ uri ‖ keccak(reqBody) ‖ keccak(respBody) ‖
319
+ * status) from your bytes and compares it to the proof's commitment — a
320
+ * genuine proof attached to a different response body yields
321
+ * `taskMatches: false` and `ok: false`. An explicit `task: null` (what
322
+ * the recorders return when the exchange wasn't captured) fails closed:
323
+ * `ok: false`, never a silent fall-back to signer-only.
324
+ */
325
+ async verifyProof(
326
+ proof: ServeProof,
327
+ opts?: { task?: TaskReveal | TaskExchange | null },
328
+ ): Promise<ProofVerification> {
329
+ const reasons: string[] = [];
330
+
331
+ const notExpired = proof.deadline > BigInt(this.now() - this.clockSkew);
332
+ if (!notExpired) reasons.push('proof deadline has passed');
333
+
334
+ // The signature is bound to the registry that redeems it (EIP-191 v0x00
335
+ // intended validator). Without one there is nothing to verify against;
336
+ // when the envelope names another one, the signature cannot match ours.
337
+ const registry = this.verifiedFeedback;
338
+ const registryConfigured =
339
+ isAddress(registry, { strict: false }) && registry.toLowerCase() !== ZERO_ADDRESS;
340
+ let registryMatches = registryConfigured;
341
+ let signerMatches = false;
342
+ if (!registryConfigured) {
343
+ reasons.push('no VerifiedFeedbackRegistry configured — cannot verify serve-proof');
344
+ } else if (proof.validator && proof.validator.toLowerCase() !== registry.toLowerCase()) {
345
+ registryMatches = false;
346
+ reasons.push(
347
+ `proof signed for a different VerifiedFeedbackRegistry (proof: ${proof.validator}, configured: ${registry})`,
348
+ );
349
+ } else {
350
+ const agentSeal = (await this.publicClient.readContract({
351
+ address: this.agenticID,
352
+ abi: agenticIDAbi,
353
+ functionName: 'getAgentSeal',
354
+ args: [proof.agentId],
355
+ })) as Address;
356
+ // The digest is domain-bound: the proof was signed against this chain,
357
+ // the identity registry the reputation contract is anchored to, and the
358
+ // reputation contract itself.
359
+ const chainId = BigInt(await this.publicClient.getChainId());
360
+ signerMatches =
361
+ agentSeal !== ZERO_ADDRESS &&
362
+ (await verifyServeProofSignature(proof, agentSeal, {
363
+ chainId,
364
+ verifyingContract: this.agenticID,
365
+ validator: registry,
366
+ }));
367
+ if (!signerMatches) {
368
+ reasons.push(
369
+ proof.validator
370
+ ? 'signature does not match the on-chain agentSeal'
371
+ : 'signature does not match the on-chain agentSeal (the proof names no validator — likely a pre-upgrade sealed image)',
372
+ );
373
+ }
374
+ }
375
+
376
+ // dataHashes ⊆ intelligentDatasOf(agentId)
377
+ let dataOnChain = true;
378
+ if (proof.dataHashes.length > 0) {
379
+ const idatas = (await this.publicClient.readContract({
380
+ address: this.agenticID,
381
+ abi: agenticIDAbi,
382
+ functionName: 'intelligentDatasOf',
383
+ args: [proof.agentId],
384
+ })) as readonly { dataHash: Hash }[];
385
+ const onChain = new Set(idatas.map((d) => d.dataHash.toLowerCase()));
386
+ dataOnChain = proof.dataHashes.every((h) => onChain.has(h.toLowerCase()));
387
+ if (!dataOnChain) reasons.push('a declared dataHash is not on chain for this agent');
388
+ }
389
+
390
+ // Optional per-exchange binding: recompute the taskHash from the
391
+ // caller's own bytes and compare against the proof's commitment. With a
392
+ // TaskExchange every URI candidate gets a reveal (undici drops a bare
393
+ // trailing '?', browsers keep it — the proxy hashed one of the two).
394
+ // An EXPLICIT null is not "no task": the caller passed
395
+ // fetchWithProof's task and it wasn't recorded — fail closed rather
396
+ // than silently degrade to the signer-only verdict.
397
+ let taskMatches: boolean | null = null;
398
+ if (opts && 'task' in opts) {
399
+ if (opts.task == null) {
400
+ taskMatches = false;
401
+ reasons.push('task was passed but not recorded — cannot bind this exchange');
402
+ } else {
403
+ const reveals = 'responseBytes' in opts.task ? taskRevealOf(opts.task) : [opts.task];
404
+ taskMatches = reveals.some((r) => taskHashOf(r) === proof.taskHash);
405
+ if (!taskMatches) {
406
+ reasons.push('taskHash does not match this exchange (method/uri/bodies/status)');
407
+ }
408
+ }
409
+ }
410
+
411
+ return {
412
+ ok: signerMatches && notExpired && dataOnChain && taskMatches !== false,
413
+ signerMatches,
414
+ notExpired,
415
+ dataOnChain,
416
+ registryMatches,
417
+ taskMatches,
418
+ reasons,
419
+ };
420
+ }
421
+ }