@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.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.
- package/GUIDE.md +975 -0
- package/LICENSE +21 -0
- package/MIGRATION.md +84 -0
- package/MIGRATION.zh.md +70 -0
- package/PROVIDERS.md +273 -0
- package/PROVIDERS.zh.md +234 -0
- package/README.md +334 -2
- package/dist/AgentClient.d.ts +312 -0
- package/dist/AgentClient.d.ts.map +1 -0
- package/dist/AgentClient.js +715 -0
- package/dist/AgentClient.js.map +1 -0
- package/dist/AgenticID.d.ts +823 -0
- package/dist/AgenticID.d.ts.map +1 -0
- package/dist/AgenticID.js +1188 -0
- package/dist/AgenticID.js.map +1 -0
- package/dist/AgenticIDClient.d.ts +68 -0
- package/dist/AgenticIDClient.d.ts.map +1 -0
- package/dist/AgenticIDClient.js +198 -0
- package/dist/AgenticIDClient.js.map +1 -0
- package/dist/AttestorClient.d.ts +465 -0
- package/dist/AttestorClient.d.ts.map +1 -0
- package/dist/AttestorClient.js +1030 -0
- package/dist/AttestorClient.js.map +1 -0
- package/dist/Providers.d.ts +72 -0
- package/dist/Providers.d.ts.map +1 -0
- package/dist/Providers.js +182 -0
- package/dist/Providers.js.map +1 -0
- package/dist/ReputationClient.d.ts +213 -0
- package/dist/ReputationClient.d.ts.map +1 -0
- package/dist/ReputationClient.js +708 -0
- package/dist/ReputationClient.js.map +1 -0
- package/dist/SandboxClient.d.ts +107 -0
- package/dist/SandboxClient.d.ts.map +1 -0
- package/dist/SandboxClient.js +200 -0
- package/dist/SandboxClient.js.map +1 -0
- package/dist/ServeProof.d.ts +161 -0
- package/dist/ServeProof.d.ts.map +1 -0
- package/dist/ServeProof.js +230 -0
- package/dist/ServeProof.js.map +1 -0
- package/dist/ServeSession.d.ts +180 -0
- package/dist/ServeSession.d.ts.map +1 -0
- package/dist/ServeSession.js +336 -0
- package/dist/ServeSession.js.map +1 -0
- package/dist/Settings.d.ts +179 -0
- package/dist/Settings.d.ts.map +1 -0
- package/dist/Settings.js +247 -0
- package/dist/Settings.js.map +1 -0
- package/dist/abi.d.ts +2216 -0
- package/dist/abi.d.ts.map +1 -0
- package/dist/abi.js +1248 -0
- package/dist/abi.js.map +1 -0
- package/dist/cli/commands/cells.d.ts +34 -0
- package/dist/cli/commands/cells.d.ts.map +1 -0
- package/dist/cli/commands/cells.js +66 -0
- package/dist/cli/commands/cells.js.map +1 -0
- package/dist/cli/commands/doctor.d.ts +15 -0
- package/dist/cli/commands/doctor.d.ts.map +1 -0
- package/dist/cli/commands/doctor.js +236 -0
- package/dist/cli/commands/doctor.js.map +1 -0
- package/dist/cli/commands/interactive.d.ts +107 -0
- package/dist/cli/commands/interactive.d.ts.map +1 -0
- package/dist/cli/commands/interactive.js +3034 -0
- package/dist/cli/commands/interactive.js.map +1 -0
- package/dist/cli/commands/list.d.ts +31 -0
- package/dist/cli/commands/list.d.ts.map +1 -0
- package/dist/cli/commands/list.js +115 -0
- package/dist/cli/commands/list.js.map +1 -0
- package/dist/cli/commands/providers.d.ts +3 -0
- package/dist/cli/commands/providers.d.ts.map +1 -0
- package/dist/cli/commands/providers.js +21 -0
- package/dist/cli/commands/providers.js.map +1 -0
- package/dist/cli/commands/settings.d.ts +22 -0
- package/dist/cli/commands/settings.d.ts.map +1 -0
- package/dist/cli/commands/settings.js +188 -0
- package/dist/cli/commands/settings.js.map +1 -0
- package/dist/cli/commands/status.d.ts +16 -0
- package/dist/cli/commands/status.d.ts.map +1 -0
- package/dist/cli/commands/status.js +148 -0
- package/dist/cli/commands/status.js.map +1 -0
- package/dist/cli/commands/update.d.ts +21 -0
- package/dist/cli/commands/update.d.ts.map +1 -0
- package/dist/cli/commands/update.js +95 -0
- package/dist/cli/commands/update.js.map +1 -0
- package/dist/cli/config.d.ts +73 -0
- package/dist/cli/config.d.ts.map +1 -0
- package/dist/cli/config.js +239 -0
- package/dist/cli/config.js.map +1 -0
- package/dist/cli/env.d.ts +36 -0
- package/dist/cli/env.d.ts.map +1 -0
- package/dist/cli/env.js +74 -0
- package/dist/cli/env.js.map +1 -0
- package/dist/cli/envelope.d.ts +33 -0
- package/dist/cli/envelope.d.ts.map +1 -0
- package/dist/cli/envelope.js +62 -0
- package/dist/cli/envelope.js.map +1 -0
- package/dist/cli/errors.d.ts +48 -0
- package/dist/cli/errors.d.ts.map +1 -0
- package/dist/cli/errors.js +81 -0
- package/dist/cli/errors.js.map +1 -0
- package/dist/cli/inference.d.ts +21 -0
- package/dist/cli/inference.d.ts.map +1 -0
- package/dist/cli/inference.js +60 -0
- package/dist/cli/inference.js.map +1 -0
- package/dist/cli/logo.d.ts +21 -0
- package/dist/cli/logo.d.ts.map +1 -0
- package/dist/cli/logo.js +131 -0
- package/dist/cli/logo.js.map +1 -0
- package/dist/cli/main.d.ts +14 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +223 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/proofs.d.ts +67 -0
- package/dist/cli/proofs.d.ts.map +1 -0
- package/dist/cli/proofs.js +133 -0
- package/dist/cli/proofs.js.map +1 -0
- package/dist/cli/ref.d.ts +39 -0
- package/dist/cli/ref.d.ts.map +1 -0
- package/dist/cli/ref.js +48 -0
- package/dist/cli/ref.js.map +1 -0
- package/dist/cli/sdk.d.ts +24 -0
- package/dist/cli/sdk.d.ts.map +1 -0
- package/dist/cli/sdk.js +65 -0
- package/dist/cli/sdk.js.map +1 -0
- package/dist/cli/settings.d.ts +66 -0
- package/dist/cli/settings.d.ts.map +1 -0
- package/dist/cli/settings.js +137 -0
- package/dist/cli/settings.js.map +1 -0
- package/dist/cli/tokenize.d.ts +61 -0
- package/dist/cli/tokenize.d.ts.map +1 -0
- package/dist/cli/tokenize.js +157 -0
- package/dist/cli/tokenize.js.map +1 -0
- package/dist/cli/types.d.ts +25 -0
- package/dist/cli/types.d.ts.map +1 -0
- package/dist/cli/types.js +8 -0
- package/dist/cli/types.js.map +1 -0
- package/dist/constants.d.ts +107 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +74 -0
- package/dist/constants.js.map +1 -0
- package/dist/context.d.ts +108 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +64 -0
- package/dist/context.js.map +1 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +118 -0
- package/dist/index.js.map +1 -0
- package/dist/provider-catalog.json +23 -0
- package/dist/seal.d.ts +47 -0
- package/dist/seal.d.ts.map +1 -0
- package/dist/seal.js +145 -0
- package/dist/seal.js.map +1 -0
- package/dist/secretEnv.d.ts +119 -0
- package/dist/secretEnv.d.ts.map +1 -0
- package/dist/secretEnv.js +199 -0
- package/dist/secretEnv.js.map +1 -0
- package/dist/taskHash.d.ts +39 -0
- package/dist/taskHash.d.ts.map +1 -0
- package/dist/taskHash.js +119 -0
- package/dist/taskHash.js.map +1 -0
- package/dist/types.d.ts +336 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +19 -0
- package/dist/types.js.map +1 -0
- package/package.json +75 -4
- package/scripts/sync-providers.cjs +8 -0
- package/src/AgentClient.ts +897 -0
- package/src/AgenticID.ts +1382 -0
- package/src/AgenticIDClient.ts +238 -0
- package/src/AttestorClient.ts +1306 -0
- package/src/Providers.ts +176 -0
- package/src/ReputationClient.ts +821 -0
- package/src/SandboxClient.ts +227 -0
- package/src/ServeProof.ts +290 -0
- package/src/ServeSession.ts +421 -0
- package/src/Settings.ts +296 -0
- package/src/abi.ts +1282 -0
- package/src/cli/commands/cells.ts +61 -0
- package/src/cli/commands/doctor.ts +235 -0
- package/src/cli/commands/interactive.ts +2715 -0
- package/src/cli/commands/list.ts +117 -0
- package/src/cli/commands/providers.ts +16 -0
- package/src/cli/commands/settings.ts +197 -0
- package/src/cli/commands/status.ts +170 -0
- package/src/cli/commands/update.ts +86 -0
- package/src/cli/config.ts +225 -0
- package/src/cli/env.ts +90 -0
- package/src/cli/envelope.ts +57 -0
- package/src/cli/errors.ts +114 -0
- package/src/cli/inference.ts +57 -0
- package/src/cli/logo.ts +125 -0
- package/src/cli/main.ts +235 -0
- package/src/cli/proofs.ts +160 -0
- package/src/cli/ref.ts +58 -0
- package/src/cli/sdk.ts +65 -0
- package/src/cli/settings.ts +153 -0
- package/src/cli/tokenize.ts +131 -0
- package/src/cli/types.ts +27 -0
- package/src/constants.ts +106 -0
- package/src/context.ts +161 -0
- package/src/index.ts +129 -0
- package/src/provider-catalog.json +23 -0
- package/src/seal.ts +163 -0
- package/src/secretEnv.ts +250 -0
- package/src/taskHash.ts +100 -0
- 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
|
+
}
|