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