@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.
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 +34 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +66 -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 +107 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3034 -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 +115 -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 +61 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2715 -0
  181. package/src/cli/commands/list.ts +117 -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,1382 @@
1
+ import { modelsForProvider, type InferenceProvider } from './Providers';
2
+ /**
3
+ * @file AgenticID.ts
4
+ * @description The single entry point. Construct once with rpc + addresses (+
5
+ * attestorUrl + signer), then use the agent/reputation namespaces and admin operations:
6
+ * - `agent` — lifecycle (deploy / clone / transfer), reads, agent-seal gas top-up
7
+ * - `reputation` — serve-proof capture/verify + on-chain feedback
8
+ * - `admin` — attestor-wide provider publication, authorized by its Tapp owner
9
+ *
10
+ * plus top-level ops that don't belong to a single agent: `ack` / `ackStatus`
11
+ * (acknowledge the TEE trust-root component set) and `deposit` / `getBalance`
12
+ * (prepaid sandbox balance).
13
+ *
14
+ * Backends (AgenticID / Reputation / TappRegistry / SandboxServing contracts +
15
+ * attestor HTTP) are hidden behind the facade.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { AgentDNA } from '@0gfoundation/0g-agentdna';
20
+ * const ag = new AgentDNA({ addresses, account }); // addresses from DEPLOYMENT.md §6 / your config
21
+ * await ag.agent.transferFrom(from, to, 33n);
22
+ * const { proof } = await ag.reputation.capture(() => fetch(`${url}/chat`, ...));
23
+ * await ag.ack();
24
+ * ```
25
+ */
26
+
27
+ import type { Address, Hash, TransactionReceipt, WriteContractReturnType } from 'viem';
28
+ import { encodeFunctionData } from 'viem';
29
+ import { RECEIPT_WAIT, ZERO_G_TESTNET, ZERO_G_MAINNET } from './constants';
30
+ import { AgenticIDClient, type IntelligentDataResult } from './AgenticIDClient';
31
+ import { ReputationClient } from './ReputationClient';
32
+ import { SandboxClient } from './SandboxClient';
33
+ import { AttestorClient, type CloneParams, type DeployParams, type DeployCloneResponse } from './AttestorClient';
34
+ import { sha256Hex, type SettingsDoc } from './Settings';
35
+ import type { SecretEnvMode } from './secretEnv';
36
+ import { ServeSession, captureProof, proofFromResponse, parseServeProofHeader, type TaskExchange } from './ServeSession';
37
+ import { buildCtx, requireWallet, type AgenticIDConfig, type Ctx } from './context';
38
+ import { makeAgentClient, type AgentClient, type AgentServiceEntry, type AgentRoute } from './AgentClient';
39
+ import type {
40
+ ServeProof, GiveFeedbackParams, GiveFeedbackResult, AppendResponseParams,
41
+ ReadAllFeedbackParams, GetSummaryParams, Feedback, FeedbackSummary, ServeData,
42
+ TaskReveal,
43
+ } from './types';
44
+
45
+ const ZERO = '0x0000000000000000000000000000000000000000';
46
+
47
+ /**
48
+ * The agentId for a URL-form handle (`client` / `authenticate`): the one
49
+ * `/hello`'s X-Agent-Proof envelope carries, or the caller's hint when the
50
+ * envelope is absent. A hint that contradicts a signed `/hello` is refused.
51
+ * The caller still binds the result to the URL on chain (#62).
52
+ */
53
+ function urlAgentId(op: string, base: string, discovered: bigint | undefined, hint: bigint | undefined): bigint | undefined {
54
+ if (hint === undefined) return discovered;
55
+ if (discovered !== undefined && discovered !== hint) {
56
+ throw new Error(`${op}: ${base}/hello is signed as agent ${discovered}, not the expected agent ${hint} — refusing to connect`);
57
+ }
58
+ return hint;
59
+ }
60
+
61
+ function assertSealBound(seal: Address, op: string): void {
62
+ if (seal === ZERO) {
63
+ throw new Error(`${op}: non-seal-bound agents are not supported yet (would go through iTransferFrom/iCloneFrom)`);
64
+ }
65
+ }
66
+
67
+ /** waitForMint tuning shared by the deploy/clone `wait` option. */
68
+ type WaitMintOpts = { timeoutMs?: number; pollIntervalMs?: number; preflight?: boolean };
69
+
70
+ /** 0.1 OG — the sandbox-balance floor deploys are gated on (attestor + console use the same). */
71
+ export const MIN_SANDBOX_BALANCE_WEI = 10n ** 17n;
72
+ /**
73
+ * How long `deploy()` / `clone()` blocks before returning, in phase order:
74
+ * - omit → return on **acceptance** ({@link DeployAccepted});
75
+ * - `'minted'` → also block on the on-chain **mint** (adds `agentId`);
76
+ * - `'running'`→ also block on **provision** (adds the reachable `url`).
77
+ */
78
+ export type WaitLevel = 'minted' | 'running';
79
+
80
+ /**
81
+ * Facade-normalized deploy/clone acceptance — camelCase like every other
82
+ * SDK return (the attestor's wire JSON speaks snake_case; the mapping
83
+ * happens here so callers never see mixed casing).
84
+ */
85
+ export interface DeployAccepted {
86
+ sealId: Hash;
87
+ agentSealAddr: Address;
88
+ }
89
+ /** deploy/clone result once the background mint is awaited (`wait: 'minted'`). */
90
+ type MintedResponse = DeployAccepted & { agentId: bigint };
91
+ /** deploy/clone result once the container is up (`wait: 'running'`) — adds the
92
+ * reachable base url, which `wait: 'minted'` (mint-only) does not have yet. */
93
+ type RunningResponse = MintedResponse & { url: string };
94
+
95
+ function acceptedOf(res: DeployCloneResponse): DeployAccepted {
96
+ return { sealId: res.seal_id, agentSealAddr: res.agent_seal_addr };
97
+ }
98
+
99
+ /** Agent lifecycle (deploy / clone / transfer) + reads. Seal-bound today; the
100
+ * seal branch is reserved for non-seal agents. */
101
+ export class AgentApi {
102
+ private readonly id: AgenticIDClient;
103
+ private readonly attestor: AttestorClient;
104
+ private readonly infra: SandboxClient;
105
+ private readonly ctx: Ctx;
106
+ constructor(ctx: Ctx, initialConfig?: import('./context').AttestorPublicConfig) {
107
+ this.ctx = ctx;
108
+ this.id = new AgenticIDClient(ctx);
109
+ this.attestor = new AttestorClient(ctx, initialConfig);
110
+ this.infra = new SandboxClient(ctx);
111
+ }
112
+
113
+ /**
114
+ * Deploy/clone preflight: fail HERE, synchronously and with the fix
115
+ * named, instead of the request being accepted and dying minutes later
116
+ * as an async worker 402 with no context. Each check self-disables when
117
+ * its surface isn't configured (zero address / unknown provider), and
118
+ * read errors fail open — the attestor re-checks at accept anyway.
119
+ * Opt out per call with `{ preflight: false }`.
120
+ */
121
+ private async preflightOwnerReady(): Promise<void> {
122
+ const who = this.ctx.account?.address;
123
+ if (!who) return; // browser-wallet flows preflight in their own UI
124
+ if (this.ctx.addresses.tappRegistry !== ZERO) {
125
+ try {
126
+ const { allAcked, missing } = await this.infra.ackStatus(who);
127
+ if (!allAcked) {
128
+ throw new Error(
129
+ `trust roots not acknowledged for ${who}: ${missing.join(', ')} — call ack() once, then retry`,
130
+ );
131
+ }
132
+ } catch (e) {
133
+ if (e instanceof Error && e.message.includes('trust roots')) throw e;
134
+ // chain read failed — fail open, attestor re-checks at accept
135
+ }
136
+ }
137
+ if (this.ctx.addresses.sandboxServing !== ZERO) {
138
+ try {
139
+ // Prefer the provider's EFFECTIVE balance (on-chain minus reservations
140
+ // minus outstanding off-chain debt) — the number its create/start
141
+ // gates actually enforce. The raw chain read is the fallback and can
142
+ // be optimistic: debt accrues off-chain between settlements.
143
+ let bal: bigint;
144
+ let effective = true;
145
+ try {
146
+ bal = (await this.attestor.getEffectiveBalance()).availableWei;
147
+ } catch {
148
+ effective = false;
149
+ bal = await this.infra.getBalance(who);
150
+ }
151
+ if (bal < MIN_SANDBOX_BALANCE_WEI) {
152
+ throw new Error(
153
+ effective
154
+ ? `effective sandbox balance is ${bal} wei (on-chain minus outstanding off-chain debt), below the 0.1 OG minimum — call deposit({ amountWei }) to cover the debt plus headroom, then retry`
155
+ : `prepaid sandbox balance is ${bal} wei, below the 0.1 OG minimum — call deposit({ amountWei }) once, then retry`,
156
+ );
157
+ }
158
+ } catch (e) {
159
+ if (e instanceof Error && e.message.includes('sandbox balance')) throw e;
160
+ // provider unknown or read failed — fail open (same backstop)
161
+ }
162
+ }
163
+ await this.preflightCanReceiveNfts(who);
164
+ }
165
+
166
+ /**
167
+ * A wallet carrying an EIP-7702 delegation is code-bearing, so every
168
+ * safeMint/safeTransfer to it PROBES `onERC721Received` — a delegate that
169
+ * doesn't answer (the pre-v4 FeedbackBatcher, or any third-party delegate)
170
+ * makes the mint revert `ERC721InvalidReceiver` minutes later in the
171
+ * worker, gas spent, with no in-CLI way back. Probe HERE, name the fix.
172
+ * (feedback.md F13)
173
+ */
174
+ private async preflightCanReceiveNfts(who: Address): Promise<void> {
175
+ let code: string | undefined;
176
+ try {
177
+ code = await this.ctx.publicClient.getCode({ address: who });
178
+ } catch {
179
+ return; // read failed — fail open, the mint is the backstop
180
+ }
181
+ if (!code || code === '0x') return; // plain EOA — always receives
182
+
183
+ const SELECTOR_OK = '0x150b7a02'; // onERC721Received magic value
184
+ let accepts: boolean;
185
+ try {
186
+ const res = await this.ctx.publicClient.call({
187
+ to: who,
188
+ data: encodeFunctionData({
189
+ abi: [{
190
+ type: 'function', name: 'onERC721Received', stateMutability: 'nonpayable',
191
+ inputs: [
192
+ { name: 'operator', type: 'address' }, { name: 'from', type: 'address' },
193
+ { name: 'tokenId', type: 'uint256' }, { name: 'data', type: 'bytes' },
194
+ ],
195
+ outputs: [{ name: '', type: 'bytes4' }],
196
+ }],
197
+ functionName: 'onERC721Received',
198
+ args: [who, who, 0n, '0x'],
199
+ }),
200
+ });
201
+ accepts = !!res.data?.startsWith(SELECTOR_OK);
202
+ } catch (e) {
203
+ // A REVERT here is exactly what the mint would hit (delegate without
204
+ // the hook, e.g. the pre-v4 batcher). Transport errors fail open.
205
+ const s = `${(e as { name?: string }).name ?? ''} ${(e as Error).message ?? ''}`;
206
+ if (!/revert|CallExecutionError/i.test(s)) return;
207
+ accepts = false;
208
+ }
209
+ if (!accepts) {
210
+ throw new Error(
211
+ `wallet ${who} carries a 7702 delegation that rejects NFTs — the mint would revert ERC721InvalidReceiver. ` +
212
+ 'Fix: rate any agent once (the SDK re-delegates to the current batcher, which accepts NFTs), ' +
213
+ 'or clear the delegation with a type-4 tx to the zero address, then retry',
214
+ );
215
+ }
216
+ }
217
+
218
+ // — lifecycle —
219
+ /**
220
+ * Deploy a new agent. Async: returns `{ sealId, agentSealAddr }` once the
221
+ * attestor accepts the job. Pass `wait: 'minted'` to also block on the
222
+ * background mint (adds `agentId`) or `wait: 'running'` to also block on
223
+ * provision (adds the reachable `url`). See {@link WaitLevel}.
224
+ */
225
+ deploy(params: DeployParams, opts: { wait: 'running' } & WaitMintOpts): Promise<RunningResponse>;
226
+ deploy(params: DeployParams, opts: { wait: 'minted' } & WaitMintOpts): Promise<MintedResponse>;
227
+ deploy(params: DeployParams, opts?: { wait?: undefined } & WaitMintOpts): Promise<DeployAccepted>;
228
+ async deploy(params: DeployParams, opts?: { wait?: WaitLevel } & WaitMintOpts): Promise<DeployAccepted | MintedResponse | RunningResponse> {
229
+ if (opts?.wait === 'running' && !params.sandbox) {
230
+ throw new Error(
231
+ "deploy: wait:'running' needs a sandbox to provision — a mint-only deploy (no sandbox) has no container to wait on; use wait:'minted'",
232
+ );
233
+ }
234
+ if (opts?.preflight !== false) await this.preflightOwnerReady();
235
+ const accepted = acceptedOf(await this.attestor.deploy(params));
236
+ if (!opts?.wait) return accepted;
237
+ // 'minted' → block on the on-chain mint only (agentId, no url yet).
238
+ // 'running' → also block on provision (container up + reachable url).
239
+ if (opts.wait === 'running') return { ...accepted, ...(await this.waitForRunning(accepted.sealId, opts)) };
240
+ const agentId = await this.waitForMint(accepted.sealId, opts);
241
+ return { ...accepted, agentId };
242
+ }
243
+
244
+ /**
245
+ * Clone `sourceAgentId` to a new owner. Async like {@link deploy}: returns
246
+ * `{ sealId, agentSealAddr }` on acceptance; `wait: 'minted'` also blocks on
247
+ * the mint (adds `agentId`), `wait: 'running'` also blocks on provision.
248
+ *
249
+ * Two modes (issue #133): omit `authorization` for owner mode (the
250
+ * connected wallet must be the source's current owner); pass
251
+ * `authorization: { authData }` for contract mode — the marketplace fork
252
+ * flow, where the connected wallet IS the buyer and the source owner's
253
+ * on-chain `ICloneAuthorizer` (see {@link setCloneAuthorizer}) decides.
254
+ */
255
+ clone(params: CloneParams, opts: { wait: 'running' } & WaitMintOpts): Promise<RunningResponse>;
256
+ clone(params: CloneParams, opts: { wait: 'minted' } & WaitMintOpts): Promise<MintedResponse>;
257
+ clone(params: CloneParams, opts?: { wait?: undefined } & WaitMintOpts): Promise<DeployAccepted>;
258
+ async clone(params: CloneParams, opts?: { wait?: WaitLevel } & WaitMintOpts): Promise<DeployAccepted | MintedResponse | RunningResponse> {
259
+ if (opts?.preflight !== false) await this.preflightOwnerReady();
260
+ assertSealBound(await this.id.getAgentSeal(params.sourceAgentId), 'clone');
261
+ const accepted = acceptedOf(await this.attestor.clone(params));
262
+ if (!opts?.wait) return accepted;
263
+ if (opts.wait === 'running') return { ...accepted, ...(await this.waitForRunning(accepted.sealId, opts)) };
264
+ const agentId = await this.waitForMint(accepted.sealId, opts);
265
+ return { ...accepted, agentId };
266
+ }
267
+ // ── Policy-mode cloning (issue #133) ──────────────────────────────────────
268
+
269
+ /**
270
+ * Configure (or clear, with the zero address) a token's clone authorizer —
271
+ * the `ICloneAuthorizer` contract deciding which contract-mode clones may
272
+ * mint. The publisher's one-time opt-in to marketplace forks; owner-only.
273
+ * Cleared automatically when the token changes owner.
274
+ */
275
+ async setCloneAuthorizer(tokenId: bigint, authorizer: Address): Promise<WriteContractReturnType> {
276
+ return this.id.setCloneAuthorizer(tokenId, authorizer);
277
+ }
278
+
279
+ /** The configured clone authorizer (`0x0` = none → contract-mode clones fail closed). */
280
+ async cloneAuthorizerOf(tokenId: bigint): Promise<Address> {
281
+ return this.id.cloneAuthorizerOf(tokenId);
282
+ }
283
+
284
+ /** For a clone, the agentId it was forked from (0n = not a clone; survives transfers). */
285
+ async cloneSourceOf(agentId: bigint): Promise<bigint> {
286
+ return this.id.cloneSourceOf(agentId);
287
+ }
288
+
289
+ // Standard-policy purchase helpers — resolve the token's configured
290
+ // authorizer live and speak the OFFICIAL StandardCloneAuthorizer ABI to it.
291
+ // Against a custom policy these revert; use that policy's own surface.
292
+
293
+ /** Seller: allow `buyer` to fork this agent — a permission switch (standard policy only). */
294
+ async grantClone(sourceAgentId: bigint, buyer: Address): Promise<WriteContractReturnType> {
295
+ return this.id.grantClone(sourceAgentId, buyer);
296
+ }
297
+
298
+ /** Seller: close the door for `buyer` — refund or manual one-shot consumption (standard policy only). */
299
+ async revokeClone(sourceAgentId: bigint, buyer: Address): Promise<WriteContractReturnType> {
300
+ return this.id.revokeClone(sourceAgentId, buyer);
301
+ }
302
+
303
+ /** A grant's seller + whether it is currently effective (standard policy only). */
304
+ async cloneGrantOf(sourceAgentId: bigint, buyer: Address): Promise<{ grantor: Address; effective: boolean }> {
305
+ return this.id.cloneGrantOf(sourceAgentId, buyer);
306
+ }
307
+
308
+ async transferFrom(from: Address, to: Address, tokenId: bigint): Promise<WriteContractReturnType> {
309
+ assertSealBound(await this.id.getAgentSeal(tokenId), 'transferFrom');
310
+ return this.id.transferFrom(from, to, tokenId);
311
+ }
312
+ async safeTransferFrom(from: Address, to: Address, tokenId: bigint, data: `0x${string}` = '0x'): Promise<WriteContractReturnType> {
313
+ assertSealBound(await this.id.getAgentSeal(tokenId), 'safeTransferFrom');
314
+ return this.id.safeTransferFrom(from, to, tokenId, data);
315
+ }
316
+ /** Send native gas to an agent's agentSeal so it can self-fund on-chain writes. */
317
+ topUpAgentSeal(agentSeal: Address, amountWei: bigint): Promise<`0x${string}`> {
318
+ const { walletClient, account } = requireWallet(this.ctx);
319
+ return walletClient.sendTransaction({ to: agentSeal, value: amountWei, account, chain: this.ctx.chain });
320
+ }
321
+
322
+ /**
323
+ * What this agent costs to keep running, from on-chain data alone:
324
+ * the owner's prepaid balance, the provider's price schedule, the
325
+ * agent's evolution-gas balance, and the runway those imply. `spec`
326
+ * defaults to the standard sealed container (2 CPU / 4 GB) — pass the
327
+ * actual shape if yours differs. Per-agent metered spend needs
328
+ * provider-side usage records and is not available on chain yet.
329
+ */
330
+ /**
331
+ * What WOULD an agent cost — no agent needed (pre-deploy planning).
332
+ * Provider pricing + cost/min for the spec (default 2C/4GB), plus the
333
+ * caller's prepaid balance and implied runway when an account is set.
334
+ */
335
+ async estimateCosts(spec?: { cpu?: number; memGb?: number }): Promise<{
336
+ prepaidBalanceWei: bigint | null;
337
+ pricing: { pricePerCPUPerMin: bigint; pricePerMemGBPerMin: bigint; createFee: bigint };
338
+ costPerMinWei: bigint;
339
+ estimatedRunwayMinutes: number | null;
340
+ }> {
341
+ const cpu = BigInt(spec?.cpu ?? 2);
342
+ const memGb = BigInt(spec?.memGb ?? 4);
343
+ const svc = await this.infra.services();
344
+ const costPerMinWei = cpu * svc.pricePerCPUPerMin + memGb * svc.pricePerMemGBPerMin;
345
+ let prepaidBalanceWei: bigint | null = null;
346
+ if (this.ctx.account) {
347
+ try { prepaidBalanceWei = await this.infra.getBalance(); } catch { /* stays null */ }
348
+ }
349
+ return {
350
+ prepaidBalanceWei,
351
+ pricing: { pricePerCPUPerMin: svc.pricePerCPUPerMin, pricePerMemGBPerMin: svc.pricePerMemGBPerMin, createFee: svc.createFee },
352
+ costPerMinWei,
353
+ estimatedRunwayMinutes:
354
+ prepaidBalanceWei !== null && costPerMinWei > 0n ? Number(prepaidBalanceWei / costPerMinWei) : null,
355
+ };
356
+ }
357
+
358
+ /** estimateCosts() plus the given agent's evolution-gas balance. */
359
+ async runtimeCosts(agentId: bigint, spec?: { cpu?: number; memGb?: number }): Promise<{
360
+ prepaidBalanceWei: bigint | null;
361
+ sealGasWei: bigint;
362
+ pricing: { pricePerCPUPerMin: bigint; pricePerMemGBPerMin: bigint; createFee: bigint };
363
+ costPerMinWei: bigint;
364
+ estimatedRunwayMinutes: number | null;
365
+ }> {
366
+ const [est, sealAddr] = await Promise.all([this.estimateCosts(spec), this.id.getAgentSeal(agentId)]);
367
+ const sealGasWei = await this.ctx.publicClient.getBalance({ address: sealAddr });
368
+ return { ...est, sealGasWei };
369
+ }
370
+
371
+ /**
372
+ * Model catalog of the 0g-compute router (the `provider: '0g-compute'`
373
+ * inference path). Public endpoint, no key needed — use it to populate
374
+ * a model picker before deploy.
375
+ */
376
+ listProviders(): InferenceProvider[] { return this.attestor.listProviders(); }
377
+
378
+ async refreshProviders(): Promise<InferenceProvider[]> { return (await this.attestor.getProviderRegistry()).providers; }
379
+
380
+ getProviderRegistry() { return this.attestor.getProviderRegistry(); }
381
+
382
+ assertProviderSupported(provider: string, options: { sealId?: Hash; framework?: string; sealedImage?: string } = {}): Promise<void> {
383
+ return this.attestor.assertProviderSupported(provider, options);
384
+ }
385
+
386
+ async listModels(opts: { provider?: string } = {}): Promise<string[]> {
387
+ return (await this.listModelCaps(opts)).map((model) => model.id);
388
+ }
389
+
390
+ async listModelCaps(opts: { provider?: string } = {}): Promise<Array<{ id: string; chat: boolean; tools: boolean; formats: string[] }>> {
391
+ return (await modelsForProvider(await this.attestor.providerDefinition(opts.provider ?? '0g-compute'))).map((model) => ({
392
+ id: model.id,
393
+ chat: (model.type ?? 'chatbot') === 'chatbot',
394
+ tools: (model.supported_parameters ?? []).includes('tools'),
395
+ formats: model.supported_formats ?? [],
396
+ }));
397
+ }
398
+
399
+ /**
400
+ * Get an {@link AgentClient} for a running agent — one handle for every
401
+ * caller, one argument: an `agentId` OR an `agentUrl` (whichever you have).
402
+ * The SDK fills in the other half:
403
+ * - `agentId` → on-chain `tokenURI` → the AgentCard's serve URL;
404
+ * - `agentUrl` → the agent's **signed** `/hello`, whose `X-Agent-Proof`
405
+ * envelope carries the numeric agentId (so a URL alone is enough).
406
+ *
407
+ * Whether it can do owner ops is inherited from THIS `ag`, exactly like
408
+ * {@link AgenticID}'s account gates chain writes: an `ag` with an owner key
409
+ * gets `chat`/`chatStream` (the owner token is minted on first use and
410
+ * re-minted on rotation, e.g. after a `reset` — you never pass or refresh a
411
+ * token); a read-only `ag` gets a public client (`fetch`/`fetchWithProof`
412
+ * against `/api/*`). Being the ACTUAL owner is verified only when an owner op
413
+ * runs (chat throws for a non-owner); `/hello` and `/api/*` work regardless.
414
+ *
415
+ * With an `agentUrl`, the agentId comes from `/hello`'s proof envelope — which
416
+ * is absent when the runtime signs nothing (no `VERIFIED_FEEDBACK_ADDR`).
417
+ * Callers that already know the id pass it as `opts.agentId`: it is used when
418
+ * `/hello` carries no proof, must equal the envelope's id when it does, and
419
+ * is bound to the URL on chain like a discovered id. An `ag` with a key that
420
+ * still ends up with no agentId gets a public handle and a console warning —
421
+ * never a silent downgrade.
422
+ */
423
+ async client(idOrUrl: bigint | string, opts?: { instanceId?: string; agentId?: bigint }): Promise<AgentClient> {
424
+ const base = await this.resolveBase(idOrUrl);
425
+ const disc = await this.discoverSurface(base);
426
+ const fromUrl = typeof idOrUrl === 'string';
427
+ const agentId = fromUrl ? urlAgentId('client', base, disc.agentId, opts?.agentId) : idOrUrl;
428
+ // #62: when the agentId came from the agent's (untrusted) /hello — or from
429
+ // the caller's hint — bind it to this URL via chain before this handle
430
+ // could ever sign for it.
431
+ if (fromUrl && agentId !== undefined && this.hasAccount()) {
432
+ await this.assertAgentIdBoundToUrl(agentId, base);
433
+ }
434
+ if (agentId === undefined && this.hasAccount()) {
435
+ console.warn(
436
+ `[agentic-sdk] client(${base}): /hello carried no X-Agent-Proof, so the agentId is unknown — ` +
437
+ 'this handle has NO owner ops (chat/logs) although this AgenticID holds a key. ' +
438
+ 'Pass { agentId } (or call client(agentId)) to connect as the owner.',
439
+ );
440
+ }
441
+ const owner = agentId !== undefined && this.hasAccount();
442
+ const reauth = owner ? () => this.mintToken(base, agentId!) : undefined;
443
+ const logAuth = owner ? () => this.signOwner('0GSealLog', base, agentId!) : undefined;
444
+ return makeAgentClient({ base, services: disc.services, routes: disc.routes, reauth, logAuth, clientAddress: this.ctx.account?.address, instanceId: opts?.instanceId });
445
+ }
446
+
447
+ /**
448
+ * Owner handshake, eager: like {@link client} on an `ag` with a key, but
449
+ * mints the token up front so a non-owner fails HERE, not at first chat.
450
+ * Kept for that fail-fast semantics and back-compat; requires a wallet.
451
+ *
452
+ * With an `agentUrl`, `opts.agentId` works as in {@link client}: used when
453
+ * `/hello` carries no proof (runtime without `VERIFIED_FEEDBACK_ADDR`),
454
+ * must equal the envelope's id when it does, and is bound to the URL on
455
+ * chain before anything is signed.
456
+ */
457
+ async authenticate(idOrUrl: bigint | string, opts?: { agentId?: bigint }): Promise<AgentClient> {
458
+ requireWallet(this.ctx);
459
+ const base = await this.resolveBase(idOrUrl);
460
+ const disc = await this.discoverSurface(base);
461
+ const fromUrl = typeof idOrUrl === 'string';
462
+ const agentId = fromUrl ? urlAgentId('authenticate', base, disc.agentId, opts?.agentId) : idOrUrl;
463
+ if (agentId === undefined) {
464
+ throw new Error(
465
+ `authenticate: ${base}/hello carried no X-Agent-Proof (the runtime has no VERIFIED_FEEDBACK_ADDR, ` +
466
+ 'or the agent is not provisioned yet), so its agentId is unknown — pass { agentId } or call authenticate(agentId)',
467
+ );
468
+ }
469
+ // #62: reject a lying /hello (URL claims someone else's agentId) before signing.
470
+ if (fromUrl) await this.assertAgentIdBoundToUrl(agentId, base);
471
+ const token = await this.mintToken(base, agentId); // eager → throws if not owner
472
+ return makeAgentClient({
473
+ base, services: disc.services, routes: disc.routes, token,
474
+ reauth: () => this.mintToken(base, agentId),
475
+ logAuth: () => this.signOwner('0GSealLog', base, agentId),
476
+ clientAddress: this.ctx.account?.address,
477
+ });
478
+ }
479
+
480
+ /**
481
+ * Explicit public handle — never attaches a token even if this `ag` holds a
482
+ * key. For a third party calling the agent's `/api/*` services and capturing
483
+ * the serve-proof (`client.fetchWithProof('/api/…')` → `{ response, proof }`).
484
+ */
485
+ async connect(idOrUrl: bigint | string): Promise<AgentClient> {
486
+ const base = await this.resolveBase(idOrUrl);
487
+ const disc = await this.discoverSurface(base);
488
+ // Public handle (no token), but still declare the caller as redeemer so a
489
+ // captured serve-proof is bound to and redeemable by them.
490
+ return makeAgentClient({ base, services: disc.services, routes: disc.routes, clientAddress: this.ctx.account?.address });
491
+ }
492
+
493
+ /**
494
+ * Sign an owner control message `<tag>:<sealId>:<ts>:<audience>` (EIP-191).
495
+ * `audience` is the agent's serve base — issue #62 binds the signature to the
496
+ * endpoint it's meant for, so it can't be relayed to a different agent that
497
+ * happens to share the owner. Shared by {@link mintToken} (tag `0GSealAuth`)
498
+ * and the `/log/agent` reader (tag `0GSealLog`).
499
+ */
500
+ private async signOwner(tag: string, base: string, agentId: bigint): Promise<{ message: string; signature: string }> {
501
+ const { walletClient, account } = requireWallet(this.ctx);
502
+ const sealId = await this.id.getSealId(agentId);
503
+ // Audience is the origin (scheme://host[:port]) — that's what the runtime
504
+ // composes as its own public URL, so a base carrying a path still matches.
505
+ const audience = new URL(base).origin;
506
+ const message = `${tag}:${sealId}:${Math.floor(Date.now() / 1000)}:${audience}`;
507
+ const signature = await walletClient.signMessage({ account, message });
508
+ return { message, signature };
509
+ }
510
+
511
+ /**
512
+ * Push a settings document into a RUNNING container, so a change takes
513
+ * effect without rebuilding it.
514
+ *
515
+ * This is the second half of a settings write and it is deliberately
516
+ * separate from the first. {@link AttestorClient.setSettings} stores the
517
+ * document — that is the authoritative act, and it is what a future boot
518
+ * reads. This call only makes the change visible NOW. If it fails, the
519
+ * document is still stored and the next boot picks it up, which is why the
520
+ * caller treats a failure here as a warning rather than an error.
521
+ *
522
+ * The signed message carries a field the other owner tags do not: the
523
+ * sha256 of the body, placed before the audience (see the comment on the
524
+ * message below for why the order is forced). Without it the signature attests only to who is
525
+ * calling, and anything able to alter the request in flight could keep a
526
+ * valid signature while substituting a different document — harmless on the
527
+ * read-only routes the tag scheme started with, not harmless on one that
528
+ * accepts a payload.
529
+ *
530
+ * Applying it restarts the framework process, so whatever the agent was
531
+ * doing is interrupted. The container says so in its response and callers
532
+ * should pass that on rather than reporting a silent success.
533
+ */
534
+ async pushSettingsToContainer(base: string, agentId: bigint, doc: unknown): Promise<{ note?: string }> {
535
+ const { walletClient, account } = requireWallet(this.ctx);
536
+ const sealId = await this.id.getSealId(agentId);
537
+ const body = JSON.stringify(doc);
538
+ const digest = await sha256Hex(body);
539
+ const audience = new URL(base).origin;
540
+ // Digest BEFORE audience. An audience is a URL and carries its own colons,
541
+ // so the container can only keep it whole as the final field of a limited
542
+ // split; a digest appended after it lands in the digest's slot as
543
+ // "//host:port:<digest>" and every request 401s — a signature-shaped
544
+ // failure that is not a signature problem.
545
+ const message = `0GSealSettings:${sealId}:${Math.floor(Date.now() / 1000)}:${digest}:${audience}`;
546
+ const signature = await walletClient.signMessage({ account, message });
547
+
548
+ const r = await fetch(`${base}/_seal/settings`, {
549
+ method: 'POST',
550
+ headers: {
551
+ 'X-Auth-Message': message,
552
+ 'X-Auth-Signature': signature,
553
+ 'content-type': 'application/json',
554
+ },
555
+ body,
556
+ });
557
+ if (!r.ok) throw new Error(`pushSettingsToContainer: HTTP ${r.status}: ${await r.text()}`);
558
+ return (await r.json().catch(() => ({}))) as { note?: string };
559
+ }
560
+
561
+ /**
562
+ * Take the agent's single-driver seat, WeChat-style: the claim always wins
563
+ * and whoever held the seat learns via 409 the next time they speak. Call it
564
+ * on entering a session; re-entering after being displaced claims the seat
565
+ * back. Owner-signed with the body digest bound in (tag `0GSealClaim`).
566
+ *
567
+ * Best-effort by contract: a container from before the seat existed 404s —
568
+ * callers should treat any failure as "no occupancy on this agent".
569
+ */
570
+ async claimAgent(base: string, agentId: bigint, instanceId: string): Promise<{ displaced?: boolean }> {
571
+ const { walletClient, account } = requireWallet(this.ctx);
572
+ const sealId = await this.id.getSealId(agentId);
573
+ const body = JSON.stringify({ instance: instanceId });
574
+ const digest = await sha256Hex(body);
575
+ const audience = new URL(base).origin;
576
+ const message = `0GSealClaim:${sealId}:${Math.floor(Date.now() / 1000)}:${digest}:${audience}`;
577
+ const signature = await walletClient.signMessage({ account, message });
578
+ const r = await fetch(`${base}/_seal/claim`, {
579
+ method: 'POST',
580
+ headers: { 'X-Auth-Message': message, 'X-Auth-Signature': signature, 'content-type': 'application/json' },
581
+ body,
582
+ });
583
+ if (!r.ok) throw new Error(`claimAgent: HTTP ${r.status}: ${await r.text()}`);
584
+ return (await r.json().catch(() => ({}))) as { displaced?: boolean };
585
+ }
586
+
587
+ /**
588
+ * Wipe the agent's ONE persisted conversation and restart its framework so
589
+ * a fresh one is presented immediately. Clears WORKING CONTEXT only — the
590
+ * chain-tracked memory (what the agent chose to keep) is untouched; that is
591
+ * the difference between /clear and a container reset. Owner-signed (tag
592
+ * `0GSealClear`, the settings-push grammar); a framework whose history is
593
+ * client-held answers 501 — there is nothing server-side to clear. Pass
594
+ * `instanceId` when the caller participates in the single-driver seat: a
595
+ * clear is a driving action and is refused (409) from a displaced window.
596
+ */
597
+ async clearConversation(base: string, agentId: bigint, instanceId?: string): Promise<{ note?: string }> {
598
+ const { walletClient, account } = requireWallet(this.ctx);
599
+ const sealId = await this.id.getSealId(agentId);
600
+ const body = '{}';
601
+ const digest = await sha256Hex(body);
602
+ const audience = new URL(base).origin;
603
+ const message = `0GSealClear:${sealId}:${Math.floor(Date.now() / 1000)}:${digest}:${audience}`;
604
+ const signature = await walletClient.signMessage({ account, message });
605
+ const r = await fetch(`${base}/_seal/clear`, {
606
+ method: 'POST',
607
+ headers: {
608
+ 'X-Auth-Message': message,
609
+ 'X-Auth-Signature': signature,
610
+ 'content-type': 'application/json',
611
+ ...(instanceId ? { 'X-Client-Instance': instanceId } : {}),
612
+ },
613
+ body,
614
+ });
615
+ if (!r.ok) throw new Error(`clearConversation: HTTP ${r.status}: ${await r.text()}`);
616
+ return (await r.json().catch(() => ({}))) as { note?: string };
617
+ }
618
+
619
+ /**
620
+ * Compact the agent's ONE persisted conversation in place: the framework's
621
+ * own compaction replaces the older history with a summary and keeps the
622
+ * newest part verbatim (how much is the framework's: openclaw ~20K tokens,
623
+ * dsh only its newest item), so later requests carry less of it while the
624
+ * conversation goes on — the middle ground between doing nothing and
625
+ * {@link clearConversation}. No restart. The summary takes one or more
626
+ * model calls, so this can take minutes — longer than Node's fetch waits
627
+ * for an answer (300s). A connection dropped or timed out meanwhile does not
628
+ * abort it; the outcome is in the runtime log. Nothing to compact —
629
+ * including nothing said since the last compaction — is a 200 whose note
630
+ * says so. Owner-signed (tag `0GSealCompact`, the clear grammar). A
631
+ * framework, or a framework version, that cannot compact on demand answers
632
+ * 501: openclaw before 2026.7.1 has no `sessions compact` CLI command, which
633
+ * the adapter drives. A second compaction while one runs, a replayed
634
+ * signature, or a framework declining for now (busy) answers 409. Pass
635
+ * `instanceId` when the caller participates in the single-driver seat:
636
+ * compaction is a driving action and is refused (409) from a displaced
637
+ * window.
638
+ */
639
+ async compactConversation(base: string, agentId: bigint, instanceId?: string): Promise<{ note?: string }> {
640
+ const { walletClient, account } = requireWallet(this.ctx);
641
+ const sealId = await this.id.getSealId(agentId);
642
+ const body = '{}';
643
+ const digest = await sha256Hex(body);
644
+ const audience = new URL(base).origin;
645
+ const message = `0GSealCompact:${sealId}:${Math.floor(Date.now() / 1000)}:${digest}:${audience}`;
646
+ const signature = await walletClient.signMessage({ account, message });
647
+ const r = await fetch(`${base}/_seal/compact`, {
648
+ method: 'POST',
649
+ headers: {
650
+ 'X-Auth-Message': message,
651
+ 'X-Auth-Signature': signature,
652
+ 'content-type': 'application/json',
653
+ ...(instanceId ? { 'X-Client-Instance': instanceId } : {}),
654
+ },
655
+ body,
656
+ });
657
+ if (!r.ok) throw new Error(`compactConversation: HTTP ${r.status}: ${await r.text()}`);
658
+ return (await r.json().catch(() => ({}))) as { note?: string };
659
+ }
660
+
661
+ /** Sign `0GSealAuth` (audience-bound) and exchange it at `{base}/_seal/auth` for a token. */
662
+ private async mintToken(base: string, agentId: bigint): Promise<string> {
663
+ const { message, signature } = await this.signOwner('0GSealAuth', base, agentId);
664
+ const r = await fetch(`${base}/_seal/auth`, {
665
+ method: 'POST',
666
+ headers: { 'X-Auth-Message': message, 'X-Auth-Signature': signature },
667
+ });
668
+ if (!r.ok) throw new Error(`authenticate: HTTP ${r.status}: ${await r.text()}`);
669
+ return ((await r.json()) as { token: string }).token;
670
+ }
671
+
672
+ /**
673
+ * #62 defense-in-depth: verify a URL-derived agentId actually belongs to the
674
+ * URL we're talking to. Resolves the agent's canonical serve origin from chain
675
+ * (`tokenURI` → AgentCard `url`) and compares to `base`'s origin. A phishing
676
+ * endpoint whose `/hello` claims someone else's agentId is rejected here,
677
+ * before we sign anything for it. (The audience-bound signature also makes the
678
+ * real agent reject a relayed signature server-side — this just fails fast
679
+ * with a clear reason.)
680
+ */
681
+ private async assertAgentIdBoundToUrl(agentId: bigint, base: string): Promise<void> {
682
+ const chainOrigin = await this.resolveAgentUrl(agentId); // already an origin
683
+ const gotOrigin = new URL(base).origin;
684
+ if (chainOrigin.toLowerCase() !== gotOrigin.toLowerCase()) {
685
+ throw new Error(
686
+ `agentId/URL mismatch (possible phishing, issue #62): the endpoint at ${gotOrigin} ` +
687
+ `claims to be agent ${agentId}, but chain says agent ${agentId} serves at ${chainOrigin}. ` +
688
+ `Refusing to sign an owner message.`,
689
+ );
690
+ }
691
+ }
692
+
693
+ /** Resolve the serve base URL: a bigint agentId via on-chain tokenURI; a string URL as-is. */
694
+ private async resolveBase(idOrUrl: bigint | string): Promise<string> {
695
+ return typeof idOrUrl === 'bigint' ? this.resolveAgentUrl(idOrUrl) : idOrUrl.replace(/\/$/, '');
696
+ }
697
+
698
+ /** Whether this `ag` holds a signer — so the clients it builds can do owner ops. */
699
+ private hasAccount(): boolean {
700
+ return !!(this.ctx.walletClient && this.ctx.account);
701
+ }
702
+
703
+ /**
704
+ * Resolve an agent's live serve base URL from its on-chain identity — no
705
+ * attestor. Reads `tokenURI(agentId)` (the canonical AgentCard pointer on 0G
706
+ * storage), fetches the card, and returns the origin of its `url` (the serve
707
+ * endpoint, refreshed on storage as the container is (re)created). Throws if
708
+ * the agent isn't provisioned yet (no URI, or a card with no url).
709
+ */
710
+ private async resolveAgentUrl(agentId: bigint): Promise<string> {
711
+ const uri = await this.id.tokenURI(agentId);
712
+ if (!uri) throw new Error(`agent ${agentId}: no on-chain URI yet (not provisioned)`);
713
+ let card: Record<string, unknown>;
714
+ try {
715
+ card = (await (await fetch(uri)).json()) as Record<string, unknown>;
716
+ } catch (e) {
717
+ throw new Error(`agent ${agentId}: fetch AgentCard (${uri}) failed: ${(e as Error).message}`);
718
+ }
719
+ const cardUrl = typeof card.url === 'string' ? card.url : '';
720
+ if (!cardUrl) throw new Error(`agent ${agentId}: AgentCard has no serve url (not running)`);
721
+ return new URL(cardUrl).origin;
722
+ }
723
+
724
+ /**
725
+ * Read the agent's signed `/hello` to learn its declared surface AND its
726
+ * numeric agentId — the latter from the response's `X-Agent-Proof` envelope,
727
+ * so a caller who has only the URL still gets the id needed to authenticate.
728
+ * Absent on pre-route / unprovisioned builds → empty surface + undefined id
729
+ * (fetch/fetchWithProof still work; owner ops just aren't offered).
730
+ */
731
+ private async discoverSurface(base: string): Promise<{ services: AgentServiceEntry[]; routes: AgentRoute[]; agentId?: bigint }> {
732
+ try {
733
+ const res = await fetch(`${base}/hello`);
734
+ const hello = (await res.json()) as { services?: AgentServiceEntry[]; routes?: AgentRoute[] };
735
+ const agentId = proofFromResponse(res)?.agentId; // /hello is signed; its envelope carries agent_id
736
+ return { services: hello.services ?? [], routes: hello.routes ?? [], agentId };
737
+ } catch {
738
+ return { services: [], routes: [] }; // best-effort; fetch/fetchWithProof still work
739
+ }
740
+ }
741
+
742
+ // — runtime: interacting with a live agent —
743
+
744
+ /**
745
+ * Greet a running agent and verify it in one call: GET {agentUrl}/hello,
746
+ * capture the X-Agent-Proof header, and check the proof against chain
747
+ * (signer == on-chain agentSeal, deadline, declared data hashes all on
748
+ * chain — via {@link ServeSession}). Returns the agent's self-report
749
+ * plus a structured verification. The whole "is this agent who it
750
+ * claims, running what chain says" check, without hand-rolling the
751
+ * fetch + parse + verify.
752
+ *
753
+ * The proof signature is bound to the VerifiedFeedbackRegistry, so the
754
+ * check needs `addresses.verifiedFeedback` (fromAttestor fills it from
755
+ * /config). Without it `verification.signerMatches` is false with the
756
+ * reason 'no VerifiedFeedbackRegistry configured — cannot verify
757
+ * serve-proof'.
758
+ */
759
+ async sayHi(agentUrl: string): Promise<{
760
+ hello: {
761
+ agent: Address; owner: Address; public_url: string; message: string;
762
+ services: AgentServiceEntry[]; routes: AgentRoute[];
763
+ };
764
+ proof: ServeProof | null;
765
+ verification: import('./ServeSession').ProofVerification | null;
766
+ }> {
767
+ const base = agentUrl.replace(/\/$/, '');
768
+ const { response, proof } = await captureProof(() => fetch(`${base}/hello`));
769
+ if (!response.ok) throw new Error(`sayHi: /hello returned HTTP ${response.status}`);
770
+ const rawText = await response.text();
771
+ const raw = JSON.parse(rawText) as {
772
+ agent: Address; owner: Address; public_url: string; message: string;
773
+ services?: AgentServiceEntry[]; routes?: AgentRoute[];
774
+ };
775
+ const hello = { ...raw, services: raw.services ?? [], routes: raw.routes ?? [] };
776
+ // Per-exchange binding: the verification verdict is computed against the
777
+ // exact /hello bytes received, so `services` (including `transport`) is
778
+ // bound to this content, not only attributed to the signer.
779
+ const task: TaskExchange = {
780
+ method: 'GET', url: `${base}/hello`, requestBytes: '',
781
+ responseBytes: rawText, status: response.status,
782
+ };
783
+ const verification = proof ? await new ServeSession(this.ctx).verifyProof(proof, { task }) : null;
784
+ return { hello, proof, verification };
785
+ }
786
+
787
+ private attestorBase(): string {
788
+ if (!this.ctx.attestorUrl) throw new Error('attestorUrl is required for listDeployments');
789
+ return this.ctx.attestorUrl.replace(/\/$/, '');
790
+ }
791
+
792
+ /**
793
+ * Normalized view of the attestor's /deployments listing. The raw rows
794
+ * speak hex ("agent_id": "0x77") and snake_case; this returns bigint
795
+ * agentIds and camelCase so they compose with every other SDK call.
796
+ *
797
+ * `url` is the agent's public base URL (feed it to sayHi/authenticate/
798
+ * the /v1 chat API) — null until the container is provisioned.
799
+ * `lastProvisionError` is WHY a deployment is stuck (e.g. "image_hash
800
+ * not in validFrameworkHashes") — always check it before debugging a
801
+ * deployment that never reaches `running`. It is non-null only when the
802
+ * row is currently failed (any pipeline stage) or offline due to a
803
+ * genuine container failure; recovered rows report null.
804
+ *
805
+ * When `phase` is `"failed"`, try {@link AgentApi.retry} FIRST — it resumes
806
+ * the failed stages on the same identity. Redeploying instead orphans the
807
+ * already-minted agent; reset only helps once the container stage is
808
+ * reached.
809
+ *
810
+ * This is the PUBLIC listing: the attestor returns only non-sensitive fields
811
+ * for an unauthenticated GET (issue #64), so `sandboxId` and
812
+ * `lastProvisionError` come back **null** here. No tier carries the owner's
813
+ * settings document — read it with {@link AgentApi.getSettings}, which is
814
+ * owner-signed. `agentId`/`sealId`/`phase`/`url`/`name` are still
815
+ * present, and `owner` and `agentSeal` appear for MINTED rows (both
816
+ * chain-public once the agent exists — ownerOf /
817
+ * getAgentSeal; unminted rows keep them withheld). `agentSeal` is the
818
+ * agent's on-chain signing address: matching it against another row's
819
+ * `owner` is how client code spots agent-owned agents (delegation
820
+ * hierarchies, self-funded runs).
821
+ * Use {@link AgentApi.listMyDeployments} — owner-signed — to get the withheld
822
+ * fields for your own agents.
823
+ */
824
+ async listDeployments(): Promise<Array<{
825
+ agentId: bigint | null; sealId: Hash; phase: string; framework: string | null;
826
+ sandboxId: string | null; url: string | null; owner: Address | null; name: string | null;
827
+ agentSeal: Address | null;
828
+ createdAt: string | null; lastProvisionError: string | null;
829
+ }>> {
830
+ // slim=1 drops the embedded avatar data-URIs (~95% of the payload); servers
831
+ // predating the param ignore it.
832
+ const rows = (await (await fetch(`${this.attestorBase()}/deployments?slim=1`)).json()) as Array<Record<string, unknown>>;
833
+ return rows.map((r) => this.normalizeDeploymentRow(r));
834
+ }
835
+
836
+ /**
837
+ * Owner-scoped, authenticated listing — your own agents WITH the fields the
838
+ * public {@link AgentApi.listDeployments} withholds (`sandboxId`,
839
+ * `lastProvisionError`, stages). Signs `0GDeployments:<owner>:<ts>` with
840
+ * `ctx.account` and sends it as `X-Auth-Message`/`X-Auth-Signature`; the
841
+ * attestor verifies the signer controls `<owner>` before returning its rows.
842
+ * Requires a wallet. This is how you get a container's `sandboxId` for
843
+ * {@link AgentApi.stop}/{@link AgentApi.start}.
844
+ */
845
+ async listMyDeployments(): Promise<Awaited<ReturnType<AgentApi['listDeployments']>>> {
846
+ const { walletClient, account } = requireWallet(this.ctx);
847
+ const owner = account.address;
848
+ const message = `0GDeployments:${owner}:${Math.floor(Date.now() / 1000)}`;
849
+ const signature = await walletClient.signMessage({ account, message });
850
+ const res = await fetch(`${this.attestorBase()}/deployments?owner=${owner}&slim=1`, {
851
+ headers: { 'X-Auth-Message': message, 'X-Auth-Signature': signature },
852
+ });
853
+ if (!res.ok) throw new Error(`listMyDeployments: HTTP ${res.status}: ${await res.text()}`);
854
+ const rows = (await res.json()) as Array<Record<string, unknown>>;
855
+ return rows.map((r) => this.normalizeDeploymentRow(r));
856
+ }
857
+
858
+ /** Map one raw attestor deployment row to the normalized SDK shape. Shared
859
+ * by the public {@link AgentApi.listDeployments} and the owner-scoped
860
+ * {@link AgentApi.listMyDeployments}; whatever the tier omits simply
861
+ * comes through as null — public tier: owner/agentSeal only on minted
862
+ * rows (agentSeal only from attestors carrying the field),
863
+ * sandboxId/lastProvisionError never; owner tier: everything present
864
+ * for your own rows, including unminted ones. */
865
+ private normalizeDeploymentRow(r: Record<string, unknown>): {
866
+ agentId: bigint | null; sealId: Hash; phase: string; framework: string | null;
867
+ sandboxId: string | null; url: string | null; owner: Address | null; name: string | null;
868
+ agentSeal: Address | null;
869
+ createdAt: string | null; lastProvisionError: string | null;
870
+ } {
871
+ const card = (r.agent_card as Record<string, unknown>) ?? {};
872
+ // The card's url points at the /hello card endpoint; the base (origin)
873
+ // is what every other interaction wants.
874
+ let url: string | null = null;
875
+ try { url = card.url ? new URL(card.url as string).origin : null; } catch { /* malformed → null */ }
876
+ // Failure reasons live on the per-track stage objects
877
+ // (storage/mint/container_stage.reason); last_provision_error is a
878
+ // sticky DB column (only set, never cleared) so it is only consulted
879
+ // for phase=failed, as a backstop — same gating and priority as the
880
+ // attestor console's failureReason(). phase=offline surfaces only a
881
+ // genuine container failure (a clean owner stop carries no reason);
882
+ // recovered rows report null rather than a stale sticky error. (These
883
+ // stage fields are owner-tier only — on the public listing they are
884
+ // absent, so failureReason naturally degrades to null.)
885
+ const stageReason = (stage: unknown): string | null => {
886
+ const s = stage as { state?: string; reason?: string } | null;
887
+ return s?.state === 'failed' && s.reason ? s.reason : null;
888
+ };
889
+ const phase = (r.phase as string) ?? 'unknown';
890
+ const failureReason =
891
+ phase === 'failed'
892
+ ? stageReason(r.storage_stage) ??
893
+ stageReason(r.mint_stage) ??
894
+ stageReason(r.container_stage) ??
895
+ ((r.last_provision_error as string) ?? null)
896
+ : phase === 'offline'
897
+ ? stageReason(r.container_stage)
898
+ : null;
899
+ return {
900
+ agentId: r.agent_id ? BigInt(r.agent_id as string) : null,
901
+ agentSeal: (r.agent_seal_addr as Address) ?? null,
902
+ sealId: r.seal_id as Hash,
903
+ phase,
904
+ framework: (r.framework as string) ?? null,
905
+ sandboxId: (r.sandbox_id as string) ?? null,
906
+ url,
907
+ owner: (r.owner as Address) ?? null,
908
+ name: (card.name as string) ?? null,
909
+ createdAt: (r.created_at as string) ?? null,
910
+ lastProvisionError: failureReason,
911
+ // No `settings`: the owner's configuration document is owner-gated on
912
+ // READ as well as write and is served only by {@link getSettings}. No
913
+ // listing tier carries it, so advertising it here would have meant a
914
+ // field that is null even for a configured agent.
915
+ };
916
+ }
917
+
918
+ /** Stop a running agent's sandbox (owner-signed). Identity is preserved. */
919
+ stop(sealId: Hash, sandboxId: string): Promise<void> {
920
+ return this.attestor.lifecycle('stop', { sealId, sandboxId });
921
+ }
922
+ /**
923
+ * Bring an agent's container online (owner-signed). Two shapes:
924
+ * - `start(sealId, sandboxId)` — resume a STOPPED container.
925
+ * - `start(sealId, { apiKey, sealedImage? })` — FIRST provision of a
926
+ * mint-only / never-provisioned agent (no sandbox yet): spins a fresh
927
+ * container. `apiKey` is required in practice (the fresh container needs
928
+ * the LLM key). The semantic counterpart to a sandbox-less `deploy` —
929
+ * use this, not `reset` (which means "recreate an existing container").
930
+ * The key is sealed to the agent when the attestor supports it, so the
931
+ * wallet prompt shows ciphertext, not the key (`secretEnv`, default
932
+ * `'auto'`; `'sealed'` refuses to send it in clear). When a server
933
+ * supplies the key, pass its {@link sealApiKey} output as
934
+ * `sealedSecretEnv` instead of `apiKey`, so the key never reaches the
935
+ * signer at all.
936
+ */
937
+ start(sealId: Hash, sandboxId: string): Promise<void>;
938
+ start(sealId: Hash, opts?: { provider?: string; framework?: string; sealedImage?: string; apiKey?: string; sealedSecretEnv?: string; secretEnv?: SecretEnvMode }): Promise<void>;
939
+ start(sealId: Hash, arg?: string | { provider?: string; framework?: string; sealedImage?: string; apiKey?: string; sealedSecretEnv?: string; secretEnv?: SecretEnvMode }): Promise<void> {
940
+ if (typeof arg === 'string') return this.attestor.lifecycle('start', { sealId, sandboxId: arg });
941
+ // `framework` resolves the right sealed image for a first provision (a
942
+ // mint-only hermes/prime agent otherwise boots the default snapshot) —
943
+ // same resolution deploy/reset use. (review #154 opportunity)
944
+ return this.attestor.lifecycle('start', { sealId, provider: arg?.provider, framework: arg?.framework, sealedImage: arg?.sealedImage, apiKey: arg?.apiKey, sealedSecretEnv: arg?.sealedSecretEnv, secretEnv: arg?.secretEnv });
945
+ }
946
+ /**
947
+ * Reset (recreate) an agent's container, preserving its on-chain
948
+ * identity — a fresh boot that re-reads iData from chain and reselects
949
+ * the framework adapter from the binding. Owner-signed. `apiKey` is
950
+ * required in practice: without it the agent boots but cannot call
951
+ * its model. When the attestor advertises `secret_env_scheme`, the
952
+ * SDK seals the key to the agent's agentSeal key (only the TEE opens
953
+ * it) and the owner signs that ciphertext; otherwise it rides the
954
+ * signed envelope in clear (`secretEnv`, default `'auto'`; `'sealed'`
955
+ * refuses the clear path). The attestor keeps no reusable copy, which
956
+ * is WHY it must be passed again on every recreate.
957
+ */
958
+ reset(sealId: Hash, opts?: { provider?: string; framework?: string; sealedImage?: string; apiKey?: string; sealedSecretEnv?: string; secretEnv?: SecretEnvMode }): Promise<void> {
959
+ return this.attestor.lifecycle('reset', { sealId, provider: opts?.provider, framework: opts?.framework, sealedImage: opts?.sealedImage, apiKey: opts?.apiKey, sealedSecretEnv: opts?.sealedSecretEnv, secretEnv: opts?.secretEnv });
960
+ }
961
+
962
+ /**
963
+ * The agent's current settings document — which model it thinks with, and
964
+ * how hard — with the version to write it back against. `settings: null`
965
+ * means it has never been configured; `version: 0` then, which is exactly
966
+ * the `baseVersion` a first write takes.
967
+ *
968
+ * OWNER-SIGNED: the document is the owner's, not public, so this needs a
969
+ * wallet and the attestor checks it against the LIVE on-chain owner. It is
970
+ * not carried on {@link listDeployments} rows or anywhere else.
971
+ *
972
+ * Configuration deliberately does NOT live on chain: it is re-suppliable
973
+ * (an owner re-picks a model in ten seconds), where the agent's memory is
974
+ * not. The attestor holds this blob opaquely and hands it to the container
975
+ * on every boot.
976
+ */
977
+ async getSettings(sealId: Hash): Promise<{ settings: SettingsDoc | null; version: number }> {
978
+ return this.attestor.getSettings(sealId);
979
+ }
980
+
981
+ /**
982
+ * Replace the agent's settings document (owner-signed; the attestor
983
+ * verifies the signer against the LIVE on-chain owner). Returns the new
984
+ * version.
985
+ *
986
+ * WHOLE-DOCUMENT, COMPARE-AND-SWAP write — what you pass becomes the
987
+ * document, and `baseVersion` is the version you read before editing:
988
+ *
989
+ * ```typescript
990
+ * const { settings, version } = await ag.agent.getSettings(sealId);
991
+ * await ag.agent.setSettings(
992
+ * sealId,
993
+ * { ...(settings ?? {}), model: '0gm-1.0-35b-a3b' },
994
+ * { baseVersion: version },
995
+ * );
996
+ * ```
997
+ *
998
+ * If the stored version has moved on — another client, another device — the
999
+ * write is refused with {@link SettingsConflictError}, which carries the
1000
+ * document that is actually there. Show it and let a human decide; do not
1001
+ * loop on it, or the other writer's change is what disappears.
1002
+ *
1003
+ * The container applies it on its next boot and reports back, which
1004
+ * promotes it to last-known-good; a container that keeps coming back
1005
+ * without ever confirming one is handed the last document a boot did
1006
+ * confirm, so a document that prevents boot costs a boot, not the agent.
1007
+ *
1008
+ * Pass `onWarn` for the advisory model check before signing (a model
1009
+ * missing from the 0G router catalog is reported, never blocked).
1010
+ */
1011
+ async setSettings(
1012
+ sealId: Hash,
1013
+ settings: SettingsDoc,
1014
+ opts: { baseVersion: number; onWarn?: (warning: string) => void },
1015
+ ): Promise<{ version: number }> {
1016
+ return this.attestor.setSettings({
1017
+ sealId,
1018
+ settings,
1019
+ baseVersion: opts.baseVersion,
1020
+ onWarn: opts.onWarn,
1021
+ });
1022
+ }
1023
+
1024
+ /**
1025
+ * Seal an inference key to one agent WITHOUT signing anything — for the
1026
+ * integrator whose server supplies the key while the agent's owner signs
1027
+ * in a browser. The server calls this (a read-only client is enough: no
1028
+ * wallet), hands the browser only the returned ciphertext, and the browser
1029
+ * calls `start` / `reset` / `retry` with `{ sealedSecretEnv }`. The key
1030
+ * never reaches the browser, and the wallet prompt shows only ciphertext.
1031
+ *
1032
+ * `owner` must be the address that will sign; the agent's container
1033
+ * applies the secret only while that address owns the agent on chain.
1034
+ * Requires the attestor to advertise `secret_env_scheme`. Refusals throw
1035
+ * {@link SecretEnvRefusedError}.
1036
+ */
1037
+ sealApiKey(sealId: Hash, opts: { owner: Address; apiKey: string; provider?: string; framework?: string; sealedImage?: string }): Promise<string> {
1038
+ return this.attestor.sealApiKey({ sealId, ...opts });
1039
+ }
1040
+
1041
+ /**
1042
+ * Soft-retry a stuck deployment (owner-signed), preserving its identity.
1043
+ * This is the FIRST recovery step for a `phase: "failed"` row (see
1044
+ * {@link listDeployments}) — it re-runs the failed idempotent stages
1045
+ * (storage upload, mint re-fetch, setAgentURI, …) against the same sealId,
1046
+ * where redeploying would orphan an already-minted agent.
1047
+ *
1048
+ * Without opts it does idempotent stages only. Pass `apiKey` (and
1049
+ * optionally `sealedImage`) to let it continue past those into container
1050
+ * creation — like {@link reset}, the LLM key must be re-supplied (and is
1051
+ * sealed the same way, see `secretEnv`).
1052
+ */
1053
+ retry(sealId: Hash, opts?: { provider?: string; framework?: string; sealedImage?: string; apiKey?: string; sealedSecretEnv?: string; secretEnv?: SecretEnvMode }): Promise<void> {
1054
+ return this.attestor.retry({ sealId, provider: opts?.provider, framework: opts?.framework, sealedImage: opts?.sealedImage, apiKey: opts?.apiKey, sealedSecretEnv: opts?.sealedSecretEnv, secretEnv: opts?.secretEnv });
1055
+ }
1056
+
1057
+ /**
1058
+ * Wait for a deploy OR clone to mint on-chain, returning the new agent's
1059
+ * tokenId (agentId). Both are async and return only a `seal_id` up front — the
1060
+ * tokenId doesn't exist until the background mint. This polls
1061
+ * `getAgentIdBySealId(sealId)` (0 until minted), no WebSocket. Throws on
1062
+ * `phase: "failed"` — surfacing the owner-scoped failure reason so a pre-mint
1063
+ * failure (e.g. the storage stage) reports why instead of a blank timeout —
1064
+ * or on timeout.
1065
+ *
1066
+ * @example
1067
+ * const cl = await ag.agent.clone({ sourceAgentId, targetOwner });
1068
+ * const tokenId = await ag.agent.waitForMint(cl.seal_id); // → 34n once minted
1069
+ */
1070
+ async waitForMint(
1071
+ sealId: Hash,
1072
+ opts: { timeoutMs?: number; pollIntervalMs?: number } = {},
1073
+ ): Promise<bigint> {
1074
+ const timeoutMs = opts.timeoutMs ?? 180_000;
1075
+ const pollIntervalMs = opts.pollIntervalMs ?? 3_000;
1076
+ const deadline = Date.now() + timeoutMs;
1077
+ for (;;) {
1078
+ let agentId = 0n;
1079
+ try {
1080
+ agentId = await this.id.getAgentIdBySealId(sealId);
1081
+ } catch {
1082
+ // transient RPC hiccup — treat as "not ready yet" and keep polling
1083
+ }
1084
+ if (agentId !== 0n) return agentId;
1085
+ // A pre-mint failure (e.g. the storage stage) never advances agentId, so
1086
+ // without this the loop just times out with no reason. Mirror
1087
+ // waitForRunning: detect phase="failed" and surface the owner-scoped
1088
+ // reason (the public listing withholds it since #64, so fall back to the
1089
+ // signed listMyDeployments once, only on failure).
1090
+ let row: Awaited<ReturnType<AgentApi['listDeployments']>>[number] | undefined;
1091
+ try {
1092
+ row = (await this.listDeployments()).find((r) => r.sealId === sealId);
1093
+ } catch {
1094
+ // transient attestor hiccup — treat as "not ready yet" and keep polling
1095
+ }
1096
+ if (row?.phase === 'failed') {
1097
+ let reason = row.lastProvisionError ?? null;
1098
+ if (reason == null) {
1099
+ // Pre-mint failures live in the per-stage reasons of the PUBLIC
1100
+ // detail endpoint (e.g. mint_stage.reason = the revert data), not
1101
+ // in lastProvisionError — read them before giving up on a cause.
1102
+ try {
1103
+ const d = (await (await fetch(
1104
+ `${this.ctx.attestorUrl?.replace(/\/$/, '')}/deployment/${sealId}`,
1105
+ )).json()) as { mint_stage?: { reason?: string }; storage_stage?: { reason?: string }; container_stage?: { reason?: string } };
1106
+ reason = d.mint_stage?.reason ?? d.storage_stage?.reason ?? d.container_stage?.reason ?? null;
1107
+ } catch { /* detail unreachable — try the owner-scoped fallback */ }
1108
+ }
1109
+ if (reason == null) {
1110
+ try {
1111
+ const mine = (await this.listMyDeployments()).find((r) => r.sealId === sealId);
1112
+ reason = mine?.lastProvisionError ?? null;
1113
+ } catch { /* no wallet / auth failed — keep null */ }
1114
+ }
1115
+ throw new Error(`waitForMint: seal ${sealId} failed — ${reason ?? 'unknown'}`);
1116
+ }
1117
+ if (Date.now() >= deadline) {
1118
+ throw new Error(`waitForMint: seal ${sealId} not minted within ${timeoutMs}ms`);
1119
+ }
1120
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
1121
+ }
1122
+ }
1123
+
1124
+ /**
1125
+ * Wait for a freshly-deployed/cloned agent's CONTAINER to come up, returning
1126
+ * its agentId + reachable base url. {@link deploy}/{@link clone} with
1127
+ * `wait: 'minted'` only block on the on-chain mint — the agentId exists but
1128
+ * the container (and its url) is still 1–2 min out; `wait: 'running'`
1129
+ * routes here to also block on provision. Polls {@link listDeployments};
1130
+ * throws on `phase: "failed"` or timeout (default 300s, longer than mint
1131
+ * because provision includes container start).
1132
+ */
1133
+ async waitForRunning(
1134
+ sealId: Hash,
1135
+ opts: { timeoutMs?: number; pollIntervalMs?: number } = {},
1136
+ ): Promise<{ agentId: bigint; url: string }> {
1137
+ const timeoutMs = opts.timeoutMs ?? 300_000;
1138
+ const pollIntervalMs = opts.pollIntervalMs ?? 5_000;
1139
+ const deadline = Date.now() + timeoutMs;
1140
+ for (;;) {
1141
+ let row: Awaited<ReturnType<AgentApi['listDeployments']>>[number] | undefined;
1142
+ try {
1143
+ row = (await this.listDeployments()).find((r) => r.sealId === sealId);
1144
+ } catch {
1145
+ // transient attestor hiccup — treat as "not ready yet" and keep polling
1146
+ }
1147
+ if (row?.phase === 'running' && row.url && row.agentId != null) {
1148
+ return { agentId: row.agentId, url: row.url };
1149
+ }
1150
+ if (row?.phase === 'failed') {
1151
+ // The public listing withholds the failure reason (owner-only since
1152
+ // #64), so `row.lastProvisionError` is null here — which would report
1153
+ // an unhelpful "failed — unknown" to the very owner who deployed. If a
1154
+ // wallet is available, fetch the owner-scoped reason once (only on
1155
+ // failure, not every poll). Best-effort: read-only clients or an auth
1156
+ // failure fall back to 'unknown'.
1157
+ let reason = row.lastProvisionError ?? null;
1158
+ if (reason == null) {
1159
+ try {
1160
+ const mine = (await this.listMyDeployments()).find((r) => r.sealId === sealId);
1161
+ reason = mine?.lastProvisionError ?? null;
1162
+ } catch { /* no wallet / auth failed — keep null */ }
1163
+ }
1164
+ throw new Error(`waitForRunning: seal ${sealId} failed — ${reason ?? 'unknown'}`);
1165
+ }
1166
+ if (Date.now() >= deadline) {
1167
+ throw new Error(`waitForRunning: seal ${sealId} not running within ${timeoutMs}ms (phase=${row?.phase ?? '?'})`);
1168
+ }
1169
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
1170
+ }
1171
+ }
1172
+
1173
+ // — reads —
1174
+ getAgentSeal(agentId: bigint): Promise<Address> { return this.id.getAgentSeal(agentId); }
1175
+ getSealId(agentId: bigint): Promise<Hash> { return this.id.getSealId(agentId); }
1176
+ getAgentIdBySealId(sealId: Hash): Promise<bigint> { return this.id.getAgentIdBySealId(sealId); }
1177
+ isSealIdBound(sealId: Hash): Promise<boolean> { return this.id.isSealIdBound(sealId); }
1178
+ intelligentDatasOf(tokenId: bigint): Promise<IntelligentDataResult[]> { return this.id.intelligentDatasOf(tokenId); }
1179
+ sealedKeysOf(tokenId: bigint): Promise<`0x${string}`[]> { return this.id.sealedKeysOf(tokenId); }
1180
+ ownerOf(tokenId: bigint): Promise<Address> { return this.id.ownerOf(tokenId); }
1181
+ balanceOf(owner: Address): Promise<bigint> { return this.id.balanceOf(owner); }
1182
+ waitForTransaction(txHash: Hash): Promise<TransactionReceipt> { return this.id.waitForTransaction(txHash); }
1183
+ }
1184
+
1185
+ /** Reputation: serve-proof transport/verify + on-chain feedback. */
1186
+ export class ReputationApi {
1187
+ private readonly rep: ReputationClient;
1188
+ private readonly session: ServeSession;
1189
+ constructor(ctx: Ctx) {
1190
+ this.rep = new ReputationClient(ctx);
1191
+ this.session = new ServeSession(ctx);
1192
+ }
1193
+
1194
+ // — serve-proof transport (framework-agnostic; captures X-Agent-Proof) —
1195
+ capture(call: () => Promise<Response>) { return captureProof(call); }
1196
+ proofFromResponse(res: Response): ServeProof | null { return proofFromResponse(res); }
1197
+ parseServeProofHeader(value: string): ServeProof { return parseServeProofHeader(value); }
1198
+ /** Verify a serve-proof. Without `opts.task`: signer attribution only.
1199
+ * With a task (a TaskReveal, the TaskExchange a recorder returned, or
1200
+ * null for "not recorded") the verdict additionally binds the proof to
1201
+ * that exchange's bytes — see ServeSession.verifyProof. */
1202
+ verifyProof(proof: ServeProof, opts?: { task?: TaskReveal | TaskExchange | null }) {
1203
+ return this.session.verifyProof(proof, opts);
1204
+ }
1205
+
1206
+ // — feedback (canonical write + TEE verification mark, bundled) —
1207
+ giveFeedback(params: GiveFeedbackParams): Promise<GiveFeedbackResult> { return this.rep.giveFeedback(params); }
1208
+ attestFeedback(agentId: bigint, feedbackIndex: bigint, proof: ServeProof): Promise<WriteContractReturnType> { return this.rep.attestFeedback(agentId, feedbackIndex, proof); }
1209
+ attestFeedbackWithTask(agentId: bigint, feedbackIndex: bigint, proof: ServeProof, task: TaskReveal): Promise<WriteContractReturnType> { return this.rep.attestFeedbackWithTask(agentId, feedbackIndex, proof, task); }
1210
+ revokeFeedback(agentId: bigint, feedbackIndex: bigint): Promise<WriteContractReturnType> { return this.rep.revokeFeedback(agentId, feedbackIndex); }
1211
+ appendResponse(params: AppendResponseParams): Promise<WriteContractReturnType> { return this.rep.appendResponse(params); }
1212
+ // — canonical reads (raw feedback, verified or not) —
1213
+ readFeedback(agentId: bigint, client: Address, feedbackIndex: bigint): Promise<Feedback> { return this.rep.readFeedback(agentId, client, feedbackIndex); }
1214
+ readAllFeedback(params: ReadAllFeedbackParams): Promise<Feedback[]> { return this.rep.readAllFeedback(params); }
1215
+ getSummary(params: GetSummaryParams): Promise<FeedbackSummary> { return this.rep.getSummary(params); }
1216
+ getClients(agentId: bigint): Promise<Address[]> { return this.rep.getClients(agentId); }
1217
+ getLastIndex(agentId: bigint, client: Address): Promise<bigint> { return this.rep.getLastIndex(agentId, client); }
1218
+ getResponseCount(agentId: bigint, client: Address, feedbackIndex: bigint, responders: Address[]): Promise<bigint> { return this.rep.getResponseCount(agentId, client, feedbackIndex, responders); }
1219
+ // — verified reads (TEE marks) —
1220
+ isVerified(agentId: bigint, client: Address, feedbackIndex: bigint): Promise<boolean> { return this.rep.isVerified(agentId, client, feedbackIndex); }
1221
+ getVerifiedIndexes(agentId: bigint, client: Address): Promise<bigint[]> { return this.rep.getVerifiedIndexes(agentId, client); }
1222
+ getVerifiedClients(agentId: bigint): Promise<Address[]> { return this.rep.getVerifiedClients(agentId); }
1223
+ getVerifiedSummary(params: GetSummaryParams): Promise<FeedbackSummary> { return this.rep.getVerifiedSummary(params); }
1224
+ getVerifiedEndpoint(agentId: bigint, client: Address, feedbackIndex: bigint): Promise<string> { return this.rep.getVerifiedEndpoint(agentId, client, feedbackIndex); }
1225
+ getVerifiedSummaryForEndpoint(agentId: bigint, uri: string, clients?: Address[]): Promise<FeedbackSummary> { return this.rep.getVerifiedSummaryForEndpoint(agentId, uri, clients); }
1226
+ getServeData(agentId: bigint, client: Address, feedbackIndex: bigint): Promise<ServeData> { return this.rep.getServeData(agentId, client, feedbackIndex); }
1227
+ waitForTransaction(txHash: Hash): Promise<TransactionReceipt> { return this.rep.waitForTransaction(txHash); }
1228
+ }
1229
+
1230
+ /** The AgenticID SDK entry point. */
1231
+ /** Attestor-wide operations, authorized by its current Tapp owner. */
1232
+ export class AdminApi {
1233
+ constructor(private readonly attestor: AttestorClient) {}
1234
+
1235
+ updateProviders(providers: InferenceProvider[], opts: { baseVersion: number }) { return this.attestor.updateProviders(providers, opts.baseVersion); }
1236
+
1237
+ prepareProviderUpdate(providers: InferenceProvider[], opts: { baseVersion: number }) { return this.attestor.prepareProviderUpdate(providers, opts.baseVersion); }
1238
+
1239
+ publishSignedProviders(update: { document: string; signature: `0x${string}` }) { return this.attestor.publishSignedProviders(update); }
1240
+ }
1241
+
1242
+ export class AgenticID {
1243
+ readonly agent: AgentApi;
1244
+ readonly admin: AdminApi;
1245
+ readonly reputation: ReputationApi;
1246
+ private readonly infra: SandboxClient;
1247
+ /** Long-lived so its instance caches (/config: provider address, sandbox
1248
+ * endpoint) are paid once per session, not per call. */
1249
+ private readonly attestor: AttestorClient;
1250
+ private readonly ctx: Ctx;
1251
+
1252
+ constructor(config: AgenticIDConfig, initialConfig?: import('./context').AttestorPublicConfig) {
1253
+ const ctx = buildCtx(config);
1254
+ this.ctx = ctx;
1255
+ this.agent = new AgentApi(ctx, initialConfig);
1256
+ this.reputation = new ReputationApi(ctx);
1257
+ this.infra = new SandboxClient(ctx);
1258
+ this.attestor = new AttestorClient(ctx, initialConfig);
1259
+ this.admin = new AdminApi(this.attestor);
1260
+ }
1261
+
1262
+ /**
1263
+ * Block until a top-level tx (ack/deposit) is mined. `ack()`/`deposit()`
1264
+ * return the hash immediately, like any writeContract — reading state
1265
+ * right after (ackStatus/getBalance) can race the still-pending tx and
1266
+ * see the old value. `ag.agent`/`ag.reputation` have their own
1267
+ * equivalents for txs made through those namespaces.
1268
+ */
1269
+ waitForTransaction(txHash: Hash): Promise<TransactionReceipt> {
1270
+ return this.ctx.publicClient.waitForTransactionReceipt({ hash: txHash, ...RECEIPT_WAIT });
1271
+ }
1272
+
1273
+ /**
1274
+ * Bootstrap a client from ONE URL: the attestor's GET /config is the
1275
+ * environment's self-description (contract set, chain RPC, component
1276
+ * appIds), so `attestorUrl` alone fully determines an environment —
1277
+ * switching environments is switching URLs, with no hand-copied
1278
+ * address set to go stale. Explicit `overrides` win over /config for
1279
+ * callers who verify addresses out-of-band rather than trusting the
1280
+ * attestor. Addresses absent from /config resolve to the zero address
1281
+ * (their module reads as "not deployed here").
1282
+ */
1283
+ static async fromAttestor(
1284
+ attestorUrl: string,
1285
+ opts?: Omit<AgenticIDConfig, 'addresses' | 'attestorUrl'> & { overrides?: Partial<import('./constants').ContractAddresses> },
1286
+ ): Promise<AgenticID> {
1287
+ const base = attestorUrl.replace(/\/$/, '');
1288
+ const r = await fetch(`${base}/config`);
1289
+ if (!r.ok) throw new Error(`fromAttestor: GET ${base}/config returned HTTP ${r.status}`);
1290
+ const cfg = (await r.json()) as Record<string, string | undefined>;
1291
+ const Z = '0x0000000000000000000000000000000000000000' as Address;
1292
+ const addr = (v: string | undefined): Address => (v && v.length === 42 ? (v as Address) : Z);
1293
+ const { overrides, ...rest } = opts ?? {};
1294
+ // The signing chain MUST match what the attestor targets, or every tx is
1295
+ // signed with the wrong chainId and the node rejects it ("have X want Y").
1296
+ // Derive the viem chain from /config.chain_id — without this the SDK fell
1297
+ // back to the hardcoded testnet default (16602), so a mainnet attestor's
1298
+ // RPC got testnet-signed txs.
1299
+ const cfgChainId = cfg.chain_id ? Number(cfg.chain_id) : undefined;
1300
+ const chainFromCfg = rest.chain
1301
+ ?? (cfgChainId === ZERO_G_MAINNET.id ? (ZERO_G_MAINNET as unknown as import('viem').Chain)
1302
+ : cfgChainId === ZERO_G_TESTNET.id ? (ZERO_G_TESTNET as unknown as import('viem').Chain)
1303
+ : cfgChainId != null
1304
+ ? ({ id: cfgChainId, name: `chain-${cfgChainId}`, nativeCurrency: { name: '0G', symbol: '0G', decimals: 18 }, rpcUrls: { default: { http: [cfg.chain_rpc ?? ''] } } } as unknown as import('viem').Chain)
1305
+ : undefined);
1306
+ const client = new AgenticID({
1307
+ ...rest,
1308
+ attestorUrl: base,
1309
+ rpcUrl: rest.rpcUrl ?? cfg.chain_rpc,
1310
+ ...(chainFromCfg ? { chain: chainFromCfg } : {}),
1311
+ addresses: {
1312
+ agenticID: addr(cfg.agentic_id_addr),
1313
+ verifiedFeedback: addr(cfg.verified_feedback_addr),
1314
+ feedbackBatcher: addr(cfg.feedback_batcher_addr),
1315
+ cloneGate: addr(cfg.clone_gate_addr),
1316
+ teeDataVerifier: addr(cfg.tee_data_verifier_addr),
1317
+ tappRegistry: addr(cfg.tapp_registry_addr),
1318
+ sandboxServing: addr(cfg.sandbox_serving_addr),
1319
+ ...overrides,
1320
+ },
1321
+ }, cfg as unknown as import('./context').AttestorPublicConfig);
1322
+ if (Number(cfg.provider_registry_schema) === 1) await client.agent.refreshProviders();
1323
+ return client;
1324
+ }
1325
+
1326
+ // — trust-root acknowledgment (spans attestor + kms + sandbox-provider) —
1327
+ /** Acknowledge the TEE trust-root component set in one batched tx; null if already done. */
1328
+ ack(): Promise<WriteContractReturnType | null> { return this.infra.ack(); }
1329
+ /** TappRegistry details for every trust-root component (code hashes, ackVersion, nodes) — the data ack() signs off on. */
1330
+ components(user?: Address) { return this.infra.components(user); }
1331
+ /** Which configured components `user` (or the connected account) still needs to acknowledge. */
1332
+ ackStatus(user?: Address): Promise<{ allAcked: boolean; missing: string[] }> { return this.infra.ackStatus(user); }
1333
+
1334
+ // — prepaid sandbox balance —
1335
+ /** Fund a prepaid sandbox balance (payable). Recipient defaults to the caller; provider to the attestor /config's. */
1336
+ deposit(params: { amountWei: bigint; provider?: Address; recipient?: Address }): Promise<WriteContractReturnType> { return this.infra.deposit(params); }
1337
+ /**
1338
+ * Read a prepaid sandbox balance (wei). User defaults to the account;
1339
+ * provider to the attestor /config's. Takes an options object like
1340
+ * {@link deposit} (`getBalance({ user, provider })`); the positional form
1341
+ * `getBalance(user, provider)` also works.
1342
+ */
1343
+ getBalance(opts?: { user?: Address; provider?: Address }): Promise<bigint>;
1344
+ getBalance(user?: Address, provider?: Address): Promise<bigint>;
1345
+ getBalance(userOrOpts?: Address | { user?: Address; provider?: Address }, provider?: Address): Promise<bigint> {
1346
+ if (userOrOpts && typeof userOrOpts === 'object') {
1347
+ return this.infra.getBalance(userOrOpts.user, userOrOpts.provider);
1348
+ }
1349
+ return this.infra.getBalance(userOrOpts, provider);
1350
+ }
1351
+ /**
1352
+ * Full prepaid-account view: spendable `balance`, plus `pendingRefund` and
1353
+ * `refundUnlockAt` (funds mid-refund and when they unlock — invisible to
1354
+ * {@link getBalance}, which returns only the spendable part).
1355
+ */
1356
+ getBalanceDetail(opts?: { user?: Address; provider?: Address }): Promise<{ balance: bigint; pendingRefund: bigint; refundUnlockAt: bigint }> {
1357
+ return this.infra.getBalanceDetail(opts?.user, opts?.provider);
1358
+ }
1359
+ /** The caller wallet's NATIVE gas balance (wei) — the funds that pay tx
1360
+ * fees AND back a deposit's principal. A prepaid top-up can't exceed it. */
1361
+ async nativeBalance(address?: Address): Promise<bigint> {
1362
+ const who = address ?? this.ctx.account?.address;
1363
+ if (!who) throw new Error('nativeBalance: no address and no connected account');
1364
+ return this.ctx.publicClient.getBalance({ address: who });
1365
+ }
1366
+ /**
1367
+ * The EFFECTIVE spendable balance from the sandbox provider (owner-signed):
1368
+ * on-chain balance minus in-flight reservations minus outstanding off-chain
1369
+ * debt — the number the provider's create/start gates actually enforce.
1370
+ * {@link getBalance} (raw chain read) can be optimistic between settlements.
1371
+ * Needs a wallet and an attestor /config that advertises `sandbox_endpoint`.
1372
+ */
1373
+ getEffectiveBalance(): Promise<{ balanceWei: bigint; reservedWei: bigint; outstandingDebtWei: bigint; pendingSettlementWei: bigint; availableWei: bigint }> {
1374
+ // Reuse the facade's long-lived AttestorClient — its instance caches
1375
+ // (config/provider address) pay the /config round-trips once, not per call.
1376
+ return this.attestor.getEffectiveBalance();
1377
+ }
1378
+ /** Start withdrawing prepaid funds: moves `amountWei` into `pendingRefund` (time-locked). REPLACES any existing pending refund and restarts its lock (`amountWei` = new total). Claim with {@link withdrawRefund}. */
1379
+ requestRefund(params: { amountWei: bigint; provider?: Address }): Promise<WriteContractReturnType> { return this.infra.requestRefund(params); }
1380
+ /** Claim the pending refund once `refundUnlockAt` has passed (reverts earlier); pays out to the caller's wallet. */
1381
+ withdrawRefund(opts?: { provider?: Address }): Promise<WriteContractReturnType> { return this.infra.withdrawRefund(opts?.provider); }
1382
+ }