@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,1306 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file AttestorClient.ts
|
|
3
|
+
* @description Internal client for attestor HTTP endpoints: seal-bound deploy +
|
|
4
|
+
* clone. Consumers use the `AgenticID` facade's `agent` namespace.
|
|
5
|
+
*
|
|
6
|
+
* Neither is an on-chain call. The owner signs a canonical envelope (EIP-191) and
|
|
7
|
+
* POSTs it; the attestor verifies the signer and drives the mint. Deploy also
|
|
8
|
+
* carries a sandbox "create" envelope the attestor relays to the sandbox provider.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Address } from 'viem';
|
|
12
|
+
import { getAddress, hexToBytes, isAddress, keccak256 } from 'viem';
|
|
13
|
+
import { requireWallet, type Ctx, type AttestorPublicConfig } from './context';
|
|
14
|
+
import { listInferenceProviders, ProviderRegistryClient, routeHash, registrySigningMessage, acceptedRegistryDigest, validateProvider, type InferenceProvider, type ProviderRegistrySnapshot } from './Providers';
|
|
15
|
+
import { SDK_VERSION } from './constants';
|
|
16
|
+
import { agenticIDAbi, cloneGateAbi, tappRegistryAbi } from './abi';
|
|
17
|
+
import {
|
|
18
|
+
canonicalSettings, modelAdvisory, settingsAuthMessage, SettingsConflictError, sha256Hex,
|
|
19
|
+
type SettingsDoc,
|
|
20
|
+
} from './Settings';
|
|
21
|
+
import {
|
|
22
|
+
SECRET_ENV_SCHEME,
|
|
23
|
+
SECRET_ENV_VAR,
|
|
24
|
+
SecretEnvRefusedError,
|
|
25
|
+
checkSealedSecretEnv,
|
|
26
|
+
parseAgentSealPubkey,
|
|
27
|
+
publicKeyToAddress,
|
|
28
|
+
randomBytes,
|
|
29
|
+
sealSecretEnv,
|
|
30
|
+
type SecretEnvMode,
|
|
31
|
+
} from './secretEnv';
|
|
32
|
+
|
|
33
|
+
export const CLONE_DOMAIN = 'AgenticID.Clone.v1';
|
|
34
|
+
export const CLONE_CONTRACT_DOMAIN = 'AgenticID.CloneContract.v1';
|
|
35
|
+
export const DEPLOY_DOMAIN = 'AgenticID.Deploy.v1';
|
|
36
|
+
|
|
37
|
+
export interface CloneParams {
|
|
38
|
+
sourceAgentId: bigint;
|
|
39
|
+
targetOwner: Address;
|
|
40
|
+
/**
|
|
41
|
+
* Idempotency key. Optional — the SDK generates a random one per call. Pass
|
|
42
|
+
* your own stable key to make a retry dedupe server-side (same key → returns
|
|
43
|
+
* the existing clone instead of minting a duplicate).
|
|
44
|
+
*/
|
|
45
|
+
idempotencyKey?: string;
|
|
46
|
+
/**
|
|
47
|
+
* Contract-mode credentials (issue #133 marketplace fork flow). Omit for the
|
|
48
|
+
* original owner mode — the connected wallet must then be the source's
|
|
49
|
+
* current on-chain owner.
|
|
50
|
+
*
|
|
51
|
+
* In contract mode the connected wallet is the BUYER (`targetOwner`): it
|
|
52
|
+
* signs a clone-intent (domain `AgenticID.CloneContract.v1`), and the
|
|
53
|
+
* source owner's on-chain `ICloneAuthorizer` decides whether the clone may
|
|
54
|
+
* mint. `authData` is opaque bytes forwarded to the authorizer — the
|
|
55
|
+
* marketplace defines its shape (e.g. abi-encoded purchase id).
|
|
56
|
+
*
|
|
57
|
+
* The intent binds the FULL policy context: `keccak256(authData)` and the
|
|
58
|
+
* authorizer address are signed alongside the operation fields, so a
|
|
59
|
+
* relayer can transport the request but cannot resubmit it under
|
|
60
|
+
* different auth data (each variant would be a fresh, buyer-billed clone)
|
|
61
|
+
* or carry it across a policy rotation. `authorizer` is optional here —
|
|
62
|
+
* omitted, the SDK reads it live via `cloneAuthorizerOf`; pass it
|
|
63
|
+
* explicitly to stay offline or pin the read.
|
|
64
|
+
*/
|
|
65
|
+
authorization?: {
|
|
66
|
+
/** Opaque bytes forwarded to the source's `ICloneAuthorizer.canClone`. */
|
|
67
|
+
authData: `0x${string}`;
|
|
68
|
+
/**
|
|
69
|
+
* The authorizer the intent will be signed under. Optional — read live
|
|
70
|
+
* from `cloneAuthorizerOf(sourceAgentId)` when omitted. Must be
|
|
71
|
+
* non-zero; the attestor cross-checks it against its own live read.
|
|
72
|
+
*/
|
|
73
|
+
authorizer?: Address;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** One intelligent-data input (role + opaque JSON plaintext + extra description fields). */
|
|
78
|
+
export interface IDataInput {
|
|
79
|
+
role: string;
|
|
80
|
+
plaintext: unknown;
|
|
81
|
+
extra?: Record<string, unknown>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Inputs for {@link defaultIData}. */
|
|
85
|
+
export interface DefaultIDataParams {
|
|
86
|
+
/** Framework name for the binding; default "openclaw". */
|
|
87
|
+
framework?: string;
|
|
88
|
+
name: string;
|
|
89
|
+
description: string;
|
|
90
|
+
/** Persona inference pin; default 0g-compute/0gm-1.0-35b-a3b (the 0G router's own model). */
|
|
91
|
+
inference?: { provider: string; model: string };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The canonical two-entry default iData — the same shape the attestor
|
|
96
|
+
* used to synthesize server-side before the WYSIWYS API change:
|
|
97
|
+
*
|
|
98
|
+
* - a VERSION-LESS framework binding `{name, schema_version}` (the
|
|
99
|
+
* sealed adapter resolves the missing version to its validated
|
|
100
|
+
* whitelistMax), and
|
|
101
|
+
* - the `persona` protocol seed `{system_prompt, inference}` that every
|
|
102
|
+
* adapter translates into its own config (FRAMEWORK_ADAPTER.md §5.4).
|
|
103
|
+
*
|
|
104
|
+
* Owners sign these exact bytes: defaults are now part of the signed
|
|
105
|
+
* content rather than a server-side template.
|
|
106
|
+
*/
|
|
107
|
+
export function defaultIData(p: DefaultIDataParams): IDataInput[] {
|
|
108
|
+
return [
|
|
109
|
+
{
|
|
110
|
+
role: 'framework',
|
|
111
|
+
plaintext: { name: p.framework ?? 'openclaw', schema_version: 1 },
|
|
112
|
+
extra: {},
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
role: 'persona',
|
|
116
|
+
plaintext: {
|
|
117
|
+
system_prompt: `You are ${p.name}. ${p.description}\n`,
|
|
118
|
+
inference: p.inference ?? { provider: '0g-compute', model: '0gm-1.0-35b-a3b' },
|
|
119
|
+
},
|
|
120
|
+
extra: {},
|
|
121
|
+
},
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface DeployParams {
|
|
126
|
+
/**
|
|
127
|
+
* Idempotency key. Optional — the SDK generates a random one per call. Pass
|
|
128
|
+
* your own stable key to make a retry dedupe server-side (same key → returns
|
|
129
|
+
* the existing deploy instead of minting a duplicate).
|
|
130
|
+
*/
|
|
131
|
+
idempotencyKey?: string;
|
|
132
|
+
name: string;
|
|
133
|
+
description: string;
|
|
134
|
+
image?: string;
|
|
135
|
+
/**
|
|
136
|
+
* The agent's complete iData, exactly as it will be encrypted and
|
|
137
|
+
* minted — WYSIWYS: the bytes you sign here are the bytes that get
|
|
138
|
+
* sealed; the attestor synthesizes nothing. Must include a
|
|
139
|
+
* `role="framework"` binding (`{name, schema_version}`). Omit (or pass
|
|
140
|
+
* empty) and the SDK builds `defaultIData()` for you from
|
|
141
|
+
* name/description/framework/inference below.
|
|
142
|
+
*/
|
|
143
|
+
iData?: IDataInput[];
|
|
144
|
+
/**
|
|
145
|
+
* Agent-framework name for the SDK-built default iData ("openclaw"
|
|
146
|
+
* default). Must be one of the names your attestor's `GET /config`
|
|
147
|
+
* advertises in `frameworks[]` — the attestor rejects unsupported names
|
|
148
|
+
* pre-mint. The SDK also resolves this framework's sealed image from
|
|
149
|
+
* `frameworks[]` when you don't pass `sandbox.sealedImage`, so you never
|
|
150
|
+
* need to know a framework's image. CLIENT-SIDE for the binding: it feeds
|
|
151
|
+
* `defaultIData()` when `iData` is omitted — the on-chain binding inside
|
|
152
|
+
* i_data is the single source of truth (validated against `GET /config`'s
|
|
153
|
+
* `frameworks[]` before mint). Ignored when you pass your own `iData`.
|
|
154
|
+
*/
|
|
155
|
+
framework?: string;
|
|
156
|
+
/** Inference pin for the SDK-built default persona (defaults to
|
|
157
|
+
* 0g-compute/0gm-1.0-35b-a3b). Ignored when you pass your own `iData`. */
|
|
158
|
+
inference?: { provider: string; model: string };
|
|
159
|
+
/** Sandbox "create" payload the attestor relays to the provider. OPTIONAL:
|
|
160
|
+
* omit it entirely to MINT WITHOUT provisioning a container — the agent
|
|
161
|
+
* lands Offline (minted, no runtime), brought online later via start().
|
|
162
|
+
* The "mint-only" deploy. */
|
|
163
|
+
sandbox?: {
|
|
164
|
+
/** The sealed runtime image name (0g-sandbox's own field is called
|
|
165
|
+
* `snapshot`; the SDK sends it verbatim under that wire name).
|
|
166
|
+
* Omit (or pass '') to use the attestor /config's current image —
|
|
167
|
+
* the operator-maintained default. */
|
|
168
|
+
sealedImage?: string;
|
|
169
|
+
/** Inference API key. On this one-shot path the create envelope is
|
|
170
|
+
* signed before the agent (and its agentSeal key) exists, so the key
|
|
171
|
+
* cannot be sealed and rides the envelope in clear: the wallet prompt
|
|
172
|
+
* shows it. To keep it out of the prompt, deploy without `sandbox`,
|
|
173
|
+
* wait for the mint, then `start(sealId, { apiKey })`. */
|
|
174
|
+
apiKey: string;
|
|
175
|
+
/** See {@link SecretEnvMode}. `'sealed'` makes this call throw before
|
|
176
|
+
* anything is signed, because a one-shot deploy cannot seal the key. */
|
|
177
|
+
secretEnv?: SecretEnvMode;
|
|
178
|
+
sealed?: boolean;
|
|
179
|
+
resourceId?: string;
|
|
180
|
+
};
|
|
181
|
+
/** Seconds the sandbox envelope stays valid. Default 180. */
|
|
182
|
+
envelopeTtlSec?: number;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface DeployCloneResponse {
|
|
186
|
+
seal_id: `0x${string}`;
|
|
187
|
+
agent_seal_addr: Address;
|
|
188
|
+
}
|
|
189
|
+
// NOTE: the attestor's JSON also carries `subscribe_url` (a ws:// progress feed
|
|
190
|
+
// its own frontend renders). It's omitted here — programmatic callers track
|
|
191
|
+
// completion by polling instead (getAgentIdBySealId(seal_id) / GET /deployment).
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* base64 of a string's UTF-8 bytes — on every runtime.
|
|
195
|
+
*
|
|
196
|
+
* The global `btoa` is LATIN-1: it takes a binary string, one byte per code
|
|
197
|
+
* unit. Handing it a JS string directly throws `InvalidCharacterError` on
|
|
198
|
+
* anything above U+00FF (so any CJK payload died outright), and silently
|
|
199
|
+
* encodes the WRONG bytes for U+0080..U+00FF — "café" shipped `Y2Fm6Q==`
|
|
200
|
+
* where the signature covered the UTF-8 `Y2Fmw6k=`. The attestor then
|
|
201
|
+
* recovered a different signer and reported the misleading
|
|
202
|
+
* "signer mismatch". So encode to UTF-8 first and feed btoa the bytes, the
|
|
203
|
+
* same form the attestor's own console uses (attestor/crates/api/web/index.html).
|
|
204
|
+
*/
|
|
205
|
+
export function b64encode(s: string): string {
|
|
206
|
+
const bytes = new TextEncoder().encode(s);
|
|
207
|
+
const g = globalThis as { btoa?: (d: string) => string };
|
|
208
|
+
if (typeof g.btoa === 'function') {
|
|
209
|
+
// Chunked: `String.fromCharCode(...bytes)` overflows the argument stack
|
|
210
|
+
// on a large iData payload.
|
|
211
|
+
let binary = '';
|
|
212
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
213
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
214
|
+
}
|
|
215
|
+
return g.btoa(binary);
|
|
216
|
+
}
|
|
217
|
+
return Buffer.from(bytes).toString('base64');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function randHex(bytes: number): string {
|
|
221
|
+
// randomBytes carries the Node 18 node:crypto fallback — without it the
|
|
222
|
+
// unguarded WebCrypto access crashed deploy() before any request was sent.
|
|
223
|
+
return Array.from(randomBytes(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** `GET /settings`'s body → the pair every caller wants. An unset document is
|
|
227
|
+
* `{settings: null, version: 0}`, and 0 is exactly the `baseVersion` a first
|
|
228
|
+
* write takes, so "never configured" needs no special case anywhere above.
|
|
229
|
+
* `settings_version` is accepted alongside `version` because that is the
|
|
230
|
+
* column's name on the attestor's own row shape. */
|
|
231
|
+
function parseSettingsBody(body: unknown): { settings: SettingsDoc | null; version: number } {
|
|
232
|
+
const b = (body ?? {}) as {
|
|
233
|
+
settings?: SettingsDoc | null;
|
|
234
|
+
version?: number | string | null;
|
|
235
|
+
settings_version?: number | string | null;
|
|
236
|
+
};
|
|
237
|
+
const raw = b.version ?? b.settings_version;
|
|
238
|
+
return { settings: b.settings ?? null, version: raw == null ? 0 : Number(raw) };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Best-effort version out of a 409 body — used only when the re-read that
|
|
242
|
+
* follows a conflict ALSO fails, so a number is better than nothing and a
|
|
243
|
+
* wrong guess is never acted on (the error is reported, never retried). */
|
|
244
|
+
function versionInBody(text: string): number {
|
|
245
|
+
try {
|
|
246
|
+
const v = parseSettingsBody(JSON.parse(text)).version;
|
|
247
|
+
if (v) return v;
|
|
248
|
+
} catch { /* not JSON — fall through to the text scan */ }
|
|
249
|
+
const m = text.match(/version[^0-9]{0,20}(\d+)/i);
|
|
250
|
+
return m ? Number(m[1]) : 0;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const SEALED_NEEDS_AGENT =
|
|
254
|
+
"secretEnv 'sealed': a deploy with `sandbox` signs its create envelope before the agent " +
|
|
255
|
+
'(and its agentSeal key) exists, so the key cannot be sealed. Deploy without `sandbox`, ' +
|
|
256
|
+
'wait for the mint, then call start(sealId, { apiKey }).';
|
|
257
|
+
|
|
258
|
+
function errMsg(e: unknown): string {
|
|
259
|
+
return e instanceof Error ? e.message : String(e);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Throws unless `mode` is a known {@link SecretEnvMode} (undefined = 'auto'). */
|
|
263
|
+
function assertSecretEnvMode(mode: unknown): asserts mode is SecretEnvMode | undefined {
|
|
264
|
+
if (mode !== undefined && mode !== 'auto' && mode !== 'sealed' && mode !== 'plaintext') {
|
|
265
|
+
throw new SecretEnvRefusedError(
|
|
266
|
+
'invalid_mode',
|
|
267
|
+
`secretEnv must be 'auto', 'sealed' or 'plaintext', got ${JSON.stringify(mode)}`,
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function schemeUnsupported(what: string): SecretEnvRefusedError {
|
|
273
|
+
return new SecretEnvRefusedError(
|
|
274
|
+
'scheme_unsupported',
|
|
275
|
+
`${what}: this attestor does not advertise secret_env_scheme=${SECRET_ENV_SCHEME} ` +
|
|
276
|
+
'in GET /config, so its sealed images cannot open a sealed key',
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export class AttestorClient {
|
|
281
|
+
/** In-memory half of the secret-env sticky pin (see secretEnvScheme). */
|
|
282
|
+
private schemeSeen = false;
|
|
283
|
+
|
|
284
|
+
constructor(private readonly ctx: Ctx, initialConfig?: AttestorPublicConfig) {
|
|
285
|
+
this.remoteRegistrySeen = initialConfig?.provider_registry_schema === 1;
|
|
286
|
+
this.schemeSeen = initialConfig?.secret_env_scheme === SECRET_ENV_SCHEME;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private baseUrl(): string {
|
|
290
|
+
if (!this.ctx.attestorUrl) throw new Error('attestorUrl is required for deploy/clone');
|
|
291
|
+
return this.ctx.attestorUrl.replace(/\/$/, '');
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* The EFFECTIVE spendable balance, from the sandbox provider's
|
|
296
|
+
* owner-signed `GET /api/balance`: on-chain balance minus in-flight
|
|
297
|
+
* reservations minus outstanding off-chain debt (accrued fees not yet
|
|
298
|
+
* settled). This is the number the provider's create/start gates actually
|
|
299
|
+
* enforce — the on-chain `getBalance` alone can be wildly optimistic
|
|
300
|
+
* (observed live: 3.6 OG on chain, 25 OG outstanding debt, available 0).
|
|
301
|
+
* Requires the attestor /config to advertise `sandbox_endpoint`.
|
|
302
|
+
*/
|
|
303
|
+
async getEffectiveBalance(): Promise<{
|
|
304
|
+
balanceWei: bigint; reservedWei: bigint; outstandingDebtWei: bigint; pendingSettlementWei: bigint; availableWei: bigint;
|
|
305
|
+
}> {
|
|
306
|
+
const cfg = (await this.attestorConfig()) as { sandbox_endpoint?: string };
|
|
307
|
+
if (!cfg.sandbox_endpoint) {
|
|
308
|
+
throw new Error('getEffectiveBalance: this attestor does not advertise sandbox_endpoint');
|
|
309
|
+
}
|
|
310
|
+
const env = await this.signEnvelope('balance', '', {}, 180);
|
|
311
|
+
const r = await fetch(`${cfg.sandbox_endpoint.replace(/\/$/, '')}/api/balance`, {
|
|
312
|
+
headers: {
|
|
313
|
+
'X-Wallet-Address': env.wallet_address,
|
|
314
|
+
'X-Signed-Message': env.signed_message_b64,
|
|
315
|
+
'X-Wallet-Signature': env.wallet_signature,
|
|
316
|
+
},
|
|
317
|
+
signal: AbortSignal.timeout(10_000),
|
|
318
|
+
});
|
|
319
|
+
if (!r.ok) throw new Error(`provider /api/balance: HTTP ${r.status} ${await r.text().catch(() => '')}`);
|
|
320
|
+
const b = (await r.json()) as { balance?: string; reserved?: string; outstanding_debt?: string; pending_settlement?: string; available?: string };
|
|
321
|
+
return {
|
|
322
|
+
balanceWei: BigInt(b.balance ?? '0'),
|
|
323
|
+
reservedWei: BigInt(b.reserved ?? '0'),
|
|
324
|
+
outstandingDebtWei: BigInt(b.outstanding_debt ?? '0'),
|
|
325
|
+
// queued-but-unsettled vouchers (0g-sandbox#89) — as committed as debt
|
|
326
|
+
pendingSettlementWei: BigInt(b.pending_settlement ?? '0'),
|
|
327
|
+
availableWei: BigInt(b.available ?? '0'),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Owner-signed sandbox action envelope. The sandbox runtime verifies
|
|
333
|
+
* every lifecycle action against the owner wallet; field order must
|
|
334
|
+
* match its `signedRequest` struct exactly
|
|
335
|
+
* ({action, expires_at, nonce, payload, resource_id}) or the recovered
|
|
336
|
+
* signer won't match.
|
|
337
|
+
*/
|
|
338
|
+
/** One cached /config fetch per client instance — the provider address
|
|
339
|
+
* (0g-sandbox#93 envelope binding), sandbox endpoint (effective balance),
|
|
340
|
+
* and future needs ride the same round-trip. {} on failure: every
|
|
341
|
+
* consumer already degrades on missing fields. */
|
|
342
|
+
private cfgPromise: Promise<AttestorPublicConfig> | undefined;
|
|
343
|
+
private attestorConfig(opts?: { fresh?: boolean }): Promise<AttestorPublicConfig> {
|
|
344
|
+
// `fresh` re-reads (and re-memoizes) /config: the secret-env decision
|
|
345
|
+
// must see an operator's flag change on a long-lived client.
|
|
346
|
+
if (opts?.fresh) this.cfgPromise = undefined;
|
|
347
|
+
// Memoize SUCCESS only: a transient /config failure at session start must
|
|
348
|
+
// not go sticky for the instance's lifetime (review #154 N3b) — clear the
|
|
349
|
+
// memo on failure so the next caller retries.
|
|
350
|
+
this.cfgPromise ??= fetch(`${this.baseUrl()}/config`, { signal: AbortSignal.timeout(10_000) })
|
|
351
|
+
.then((r) => {
|
|
352
|
+
// An error page is not a config: treat a non-2xx like a network
|
|
353
|
+
// failure (consumers degrade on {}, and the memo is cleared).
|
|
354
|
+
if (!r.ok) throw new Error(`GET /config: HTTP ${r.status}`);
|
|
355
|
+
return r.json() as Promise<AttestorPublicConfig>;
|
|
356
|
+
})
|
|
357
|
+
.catch(() => { this.cfgPromise = undefined; return {}; });
|
|
358
|
+
return this.cfgPromise;
|
|
359
|
+
}
|
|
360
|
+
private async resolveProviderAddr(): Promise<string> {
|
|
361
|
+
return (await this.attestorConfig()).sandbox_provider_addr ?? '';
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private async signEnvelope(
|
|
365
|
+
action: string,
|
|
366
|
+
resourceId: string,
|
|
367
|
+
payload: Record<string, unknown>,
|
|
368
|
+
ttlSec: number,
|
|
369
|
+
) {
|
|
370
|
+
const { walletClient, account } = requireWallet(this.ctx);
|
|
371
|
+
// Provider binding (0g-sandbox#93, anti cross-provider replay): inserted
|
|
372
|
+
// between payload and resource_id (alphabetical), omitted when unknown —
|
|
373
|
+
// the omitted form keeps the legacy byte layout.
|
|
374
|
+
const provider = await this.resolveProviderAddr();
|
|
375
|
+
const canonical = JSON.stringify({
|
|
376
|
+
action,
|
|
377
|
+
expires_at: Math.floor(Date.now() / 1000) + ttlSec,
|
|
378
|
+
nonce: randHex(16),
|
|
379
|
+
payload,
|
|
380
|
+
...(provider ? { provider } : {}),
|
|
381
|
+
resource_id: resourceId,
|
|
382
|
+
});
|
|
383
|
+
const signature = await walletClient.signMessage({ account, message: canonical });
|
|
384
|
+
return {
|
|
385
|
+
wallet_address: account.address,
|
|
386
|
+
signed_message_b64: b64encode(canonical),
|
|
387
|
+
wallet_signature: signature,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Resolve the sealed image name: an explicit value wins; otherwise the
|
|
393
|
+
* image `GET /config` declares for `framework` (frameworks whose runtime
|
|
394
|
+
* isn't in the default snapshot — hermes etc. — carry their own image);
|
|
395
|
+
* failing that, the default `sandbox_snapshot`. So a caller who passes a
|
|
396
|
+
* `framework` never needs to know its image. An empty snapshot in the
|
|
397
|
+
* create envelope makes the provider fail ("sealed containers require an
|
|
398
|
+
* image or snapshot"), so /config is the source of truth.
|
|
399
|
+
*/
|
|
400
|
+
private async resolveSealedImage(explicit?: string, framework?: string, sealId?: `0x${string}`): Promise<string> {
|
|
401
|
+
if (explicit) return explicit;
|
|
402
|
+
let fw = framework;
|
|
403
|
+
// An existing agent already knows what it is: its deployment row records
|
|
404
|
+
// the framework. Without this read, a bare reset/start/retry of a
|
|
405
|
+
// hermes/prime/dsh agent fell back to the DEFAULT (openclaw) image and
|
|
406
|
+
// booted a container without its framework installed (observed live,
|
|
407
|
+
// agent 452) — the CLI wizard papered over it by asking; the SDK is the
|
|
408
|
+
// right place for the lookup. An UNREADABLE row refuses rather than
|
|
409
|
+
// falling through: silently choosing the default image re-creates the
|
|
410
|
+
// exact bug this lookup exists to prevent, and the subsequent POST goes
|
|
411
|
+
// to the same attestor anyway. A row without a framework (a legacy or
|
|
412
|
+
// never-provisioned agent) still gets the default — that is data, not a
|
|
413
|
+
// failed read.
|
|
414
|
+
if (!fw && sealId) {
|
|
415
|
+
let row: { framework?: string | null };
|
|
416
|
+
try {
|
|
417
|
+
const r = await fetch(`${this.baseUrl()}/deployment/${sealId}`, {
|
|
418
|
+
signal: AbortSignal.timeout(10_000),
|
|
419
|
+
});
|
|
420
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
421
|
+
row = (await r.json()) as { framework?: string | null };
|
|
422
|
+
} catch (e) {
|
|
423
|
+
throw new Error(
|
|
424
|
+
`cannot read /deployment/${sealId} to pick the sealed image (${errMsg(e)}); ` +
|
|
425
|
+
"retry, or pass `framework` (or `sealedImage`) explicitly",
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
fw = row.framework ?? undefined;
|
|
429
|
+
}
|
|
430
|
+
// Rides the instance's memoized /config (review #154 N3a) — this was the
|
|
431
|
+
// one remaining uncached fetch on the deploy/reset/first-start path.
|
|
432
|
+
const cfg: any = await this.attestorConfig();
|
|
433
|
+
if (fw && Array.isArray(cfg?.frameworks)) {
|
|
434
|
+
const entry = cfg.frameworks.find((f: any) => f?.name === fw);
|
|
435
|
+
if (entry?.image) return entry.image;
|
|
436
|
+
}
|
|
437
|
+
return (cfg && cfg.sandbox_snapshot) || '';
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
private providerRegistry?: ProviderRegistryClient;
|
|
442
|
+
private remoteRegistrySeen = false;
|
|
443
|
+
|
|
444
|
+
listProviders(): InferenceProvider[] { return this.providerRegistry?.list() ?? listInferenceProviders(); }
|
|
445
|
+
|
|
446
|
+
async getProviderRegistry(): Promise<ProviderRegistrySnapshot> {
|
|
447
|
+
if (!this.ctx.attestorUrl) return { version: 0, providers: listInferenceProviders() };
|
|
448
|
+
const cfg = await this.attestorConfig({ fresh: true });
|
|
449
|
+
this.providerRegistry ??= new ProviderRegistryClient(this.ctx.attestorUrl);
|
|
450
|
+
if (Object.keys(cfg).length === 0) throw new SecretEnvRefusedError('config_unreadable', 'cannot read GET /config to resolve inference providers');
|
|
451
|
+
if (cfg.provider_registry_schema !== 1) {
|
|
452
|
+
if (this.remoteRegistrySeen) throw new Error('provider registry capability was withdrawn');
|
|
453
|
+
return { version: 0, providers: this.listProviders() };
|
|
454
|
+
}
|
|
455
|
+
this.remoteRegistrySeen = true;
|
|
456
|
+
return this.providerRegistry.refresh({ chainId: this.ctx.chain?.id,
|
|
457
|
+
contract: this.ctx.addresses?.agenticID, appId: cfg.attestor_app_id, tappRegistry: this.ctx.addresses?.tappRegistry, version: cfg.provider_registry_version, digest: cfg.provider_registry_digest });
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async providerDefinition(id: string): Promise<InferenceProvider> {
|
|
461
|
+
const provider = (await this.getProviderRegistry()).providers.find((entry) => entry.id === id);
|
|
462
|
+
if (!provider) throw new Error(`UNSUPPORTED_INFERENCE_PROVIDER: ${id}`);
|
|
463
|
+
return provider;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** Build an owner-authorized publication request. Contract-wallet owners
|
|
467
|
+
* can obtain their signature externally and call publishSignedProviders. */
|
|
468
|
+
async prepareProviderUpdate(providers: InferenceProvider[], baseVersion: number): Promise<{ document: string; message: string; owner: Address }> {
|
|
469
|
+
if (!Number.isSafeInteger(baseVersion) || baseVersion < 0) throw new Error('invalid provider base version');
|
|
470
|
+
providers.forEach(validateProvider);
|
|
471
|
+
if (!providers.length || providers.length > 128 || new Set(providers.map((p) => p.id)).size !== providers.length || !providers.some((p) => p.id === '0g-compute')) throw new Error('invalid provider registry');
|
|
472
|
+
const cfg = await this.attestorConfig({ fresh: true });
|
|
473
|
+
const registry = this.ctx.addresses.tappRegistry;
|
|
474
|
+
if (!registry || /^0x0{40}$/i.test(registry) || !cfg.attestor_app_id) throw new Error('attestor TappRegistry/app ID is not configured');
|
|
475
|
+
const info = await this.ctx.publicClient.readContract({ address: registry, abi: tappRegistryAbi,
|
|
476
|
+
functionName: 'getAppInfo', args: [cfg.attestor_app_id] });
|
|
477
|
+
const owner = info.owner;
|
|
478
|
+
if (/^0x0{40}$/i.test(owner)) throw new Error('attestor Tapp has no owner');
|
|
479
|
+
if (!this.ctx.addresses.agenticID) throw new Error('provider update requires an AgenticID contract');
|
|
480
|
+
const document = JSON.stringify({ schema: 1, chain_id: this.ctx.chain.id, agentic_id_addr: this.ctx.addresses.agenticID,
|
|
481
|
+
tapp_registry_addr: registry, attestor_app_id: cfg.attestor_app_id, base_version: baseVersion, expires_at: Math.floor(Date.now() / 1000) + 180, providers });
|
|
482
|
+
if (new TextEncoder().encode(document).length > 256 * 1024) throw new Error('provider document too large');
|
|
483
|
+
return { document, message: registrySigningMessage(document), owner };
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async publishSignedProviders(update: { document: string; signature: `0x${string}` }): Promise<{ version: number }> {
|
|
487
|
+
const response = await fetch(`${this.baseUrl()}/admin/inference/providers`, { method: 'PUT',
|
|
488
|
+
headers: { 'content-type': 'application/json' }, body: JSON.stringify(update), signal: AbortSignal.timeout(15_000) });
|
|
489
|
+
if (!response.ok) throw new Error(`provider update: HTTP ${response.status} ${await response.text()}`);
|
|
490
|
+
return response.json() as Promise<{ version: number }>;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
async updateProviders(providers: InferenceProvider[], baseVersion: number): Promise<{ version: number }> {
|
|
494
|
+
const { account, walletClient } = requireWallet(this.ctx);
|
|
495
|
+
const prepared = await this.prepareProviderUpdate(providers, baseVersion);
|
|
496
|
+
if (prepared.owner.toLowerCase() !== account.address.toLowerCase()) throw new Error('wallet is not the current attestor Tapp owner; contract wallets can use prepareProviderUpdate/publishSignedProviders');
|
|
497
|
+
const signature = await walletClient.signMessage({ account, message: prepared.message });
|
|
498
|
+
return this.publishSignedProviders({ document: prepared.document, signature });
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private async credentialRoute(provider: string, image: string | undefined, sealId: `0x${string}` | undefined): Promise<{ hash: string; registry: import('./Providers').ProviderRegistryPin } | undefined> {
|
|
502
|
+
const accepted = await this.getProviderRegistry();
|
|
503
|
+
const definition = accepted.providers.find((p) => p.id === provider);
|
|
504
|
+
if (!definition) throw new Error(`UNSUPPORTED_INFERENCE_PROVIDER: ${provider}`);
|
|
505
|
+
const builtin = listInferenceProviders().find((entry) => entry.id === provider);
|
|
506
|
+
const changed = !builtin || routeHash(builtin) !== routeHash(definition);
|
|
507
|
+
if (changed && !sealId) throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
|
|
508
|
+
const cfg = await this.attestorConfig();
|
|
509
|
+
const snapshot = image ?? (sealId ? await this.resolveSealedImage(undefined, undefined, sealId) : undefined);
|
|
510
|
+
const capable = cfg.inference_capabilities?.some((entry) => entry.image === snapshot && entry.secret_env_versions.includes(3)
|
|
511
|
+
&& (definition.native ? entry.providers.includes(provider) : definition.formats.every((format) => entry.formats?.includes(format))));
|
|
512
|
+
if (changed && !capable) throw new SecretEnvRefusedError('provider_binding_unsupported', `image ${snapshot || '(unknown)'} does not support dynamic provider routes for ${provider}`);
|
|
513
|
+
return capable && sealId ? { hash: routeHash(definition), registry: { version: accepted.version,
|
|
514
|
+
...(accepted.version > 0 ? { digest: acceptedRegistryDigest(accepted.document!, accepted.signature!) } : {}) } } : undefined;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Verify support for an exact runtime image before signing an owner action. */
|
|
518
|
+
async assertProviderSupported(provider: string, options: { sealId?: `0x${string}`; framework?: string; sealedImage?: string } = {}): Promise<void> {
|
|
519
|
+
const definition = await this.providerDefinition(provider);
|
|
520
|
+
const builtin = listInferenceProviders().find((entry) => entry.id === provider);
|
|
521
|
+
const changed = !builtin || routeHash(builtin) !== routeHash(definition);
|
|
522
|
+
if (provider === '0g-compute' && !changed) return;
|
|
523
|
+
const cfg = await this.attestorConfig({ fresh: true });
|
|
524
|
+
const image = await this.resolveSealedImage(options.sealedImage, options.framework, options.sealId);
|
|
525
|
+
const capabilities = Array.isArray(cfg.inference_capabilities) ? cfg.inference_capabilities : [];
|
|
526
|
+
const supported = !!image && cfg.secret_env_scheme === SECRET_ENV_SCHEME && capabilities.some((entry) =>
|
|
527
|
+
entry.image === image && (
|
|
528
|
+
(!changed && entry.providers.includes(provider) && entry.secret_env_versions.includes(2)) ||
|
|
529
|
+
(entry.secret_env_versions.includes(3) && (definition.native ? entry.providers.includes(provider) : definition.formats.every((format) => entry.formats?.includes(format))))));
|
|
530
|
+
if (!supported) throw new SecretEnvRefusedError('provider_binding_unsupported',
|
|
531
|
+
`image ${image || '(unknown)'} does not advertise provider-bound credentials for ${provider}; upgrade the sealed image and its attestor capabilities first`);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* The agent's agentSeal public key (compressed hex), verified before
|
|
536
|
+
* anything is sealed to it: the answer must be for `sealId`, the key must
|
|
537
|
+
* hash to the `agent_seal_addr` the attestor reports and, once the agent is
|
|
538
|
+
* minted, to the agentSeal on chain (`getAgentSeal`), so a relaying proxy
|
|
539
|
+
* cannot substitute its own key. Throws {@link SecretEnvRefusedError}.
|
|
540
|
+
*/
|
|
541
|
+
async agentSealPubkey(sealId: `0x${string}`): Promise<`0x${string}`> {
|
|
542
|
+
return (await this.verifiedAgentSeal(sealId)).pubkey;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
private async verifiedAgentSeal(
|
|
546
|
+
sealId: `0x${string}`,
|
|
547
|
+
): Promise<{ pubkey: `0x${string}`; onChain: { agentId: bigint; agentSeal: Address } | null }> {
|
|
548
|
+
let body: { seal_id?: string; agent_seal_addr?: string; agent_seal_pubkey?: string };
|
|
549
|
+
try {
|
|
550
|
+
const res = await fetch(`${this.baseUrl()}/agent-seal-pubkey?seal_id=${encodeURIComponent(sealId)}`, {
|
|
551
|
+
signal: AbortSignal.timeout(10_000),
|
|
552
|
+
});
|
|
553
|
+
if (!res.ok) {
|
|
554
|
+
throw new Error(`HTTP ${res.status} ${await res.text().catch(() => '')}`.trim());
|
|
555
|
+
}
|
|
556
|
+
body = (await res.json()) as typeof body;
|
|
557
|
+
} catch (e) {
|
|
558
|
+
throw new SecretEnvRefusedError('pubkey_unavailable', `/agent-seal-pubkey failed: ${errMsg(e)}`, { cause: e });
|
|
559
|
+
}
|
|
560
|
+
if (String(body.seal_id ?? '').toLowerCase() !== sealId.toLowerCase()) {
|
|
561
|
+
throw new SecretEnvRefusedError(
|
|
562
|
+
'pubkey_mismatch',
|
|
563
|
+
'/agent-seal-pubkey answered for another seal_id — refusing to seal to it',
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
const pubkey = parseAgentSealPubkey(String(body.agent_seal_pubkey ?? ''));
|
|
567
|
+
const derived = publicKeyToAddress(hexToBytes(pubkey));
|
|
568
|
+
if (!body.agent_seal_addr || !isAddress(body.agent_seal_addr) || getAddress(body.agent_seal_addr) !== derived) {
|
|
569
|
+
throw new SecretEnvRefusedError(
|
|
570
|
+
'pubkey_mismatch',
|
|
571
|
+
'/agent-seal-pubkey: the key does not belong to agent_seal_addr — refusing to seal to it',
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
const onChain = await this.onChainAgent(sealId);
|
|
575
|
+
if (onChain && getAddress(onChain.agentSeal) !== derived) {
|
|
576
|
+
throw new SecretEnvRefusedError(
|
|
577
|
+
'pubkey_mismatch',
|
|
578
|
+
`/agent-seal-pubkey: the key does not belong to the on-chain agentSeal ${onChain.agentSeal} — refusing to seal to it`,
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
return { pubkey, onChain };
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Seal an inference key for one agent without signing anything, for the
|
|
586
|
+
* integrator whose server supplies the key while a user's wallet signs
|
|
587
|
+
* (issue #166): the server calls this and hands the browser only the
|
|
588
|
+
* returned ciphertext, which the browser passes to `start` / `reset` /
|
|
589
|
+
* `retry` as `sealedSecretEnv`. The key never reaches the browser, and the
|
|
590
|
+
* wallet prompt shows only ciphertext.
|
|
591
|
+
*
|
|
592
|
+
* Needs no wallet: a read-only client (`attestorUrl`, `addresses`, RPC) is
|
|
593
|
+
* enough. `owner` is the address that will sign the envelope; the agent's
|
|
594
|
+
* container applies the secret only while that address is its on-chain
|
|
595
|
+
* owner, so once the agent is minted this checks `ownerOf` first. It also
|
|
596
|
+
* requires the attestor to advertise `secret_env_scheme` (a fresh read of
|
|
597
|
+
* `GET /config`) and verifies the agentSeal key as {@link agentSealPubkey}
|
|
598
|
+
* does. Throws {@link SecretEnvRefusedError}; returns the base64 value for
|
|
599
|
+
* `env.SEAL_SECRET_ENV`.
|
|
600
|
+
*/
|
|
601
|
+
async sealApiKey(params: { sealId: `0x${string}`; owner: Address; apiKey: string; provider?: string; framework?: string; sealedImage?: string }): Promise<string> {
|
|
602
|
+
if (!params.apiKey) throw new SecretEnvRefusedError('invalid_input', 'sealApiKey: apiKey is required');
|
|
603
|
+
if (!isAddress(params.owner)) throw new SecretEnvRefusedError('invalid_input', 'sealApiKey: owner is not an address');
|
|
604
|
+
await this.requireSecretEnvScheme('sealApiKey');
|
|
605
|
+
const provider = params.provider ?? '0g-compute';
|
|
606
|
+
await this.assertProviderSupported(provider, params);
|
|
607
|
+
const image = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId);
|
|
608
|
+
const boundRoute = await this.credentialRoute(provider, image, params.sealId);
|
|
609
|
+
const { pubkey, onChain } = await this.verifiedAgentSeal(params.sealId);
|
|
610
|
+
if (onChain) {
|
|
611
|
+
let chainOwner: Address;
|
|
612
|
+
try {
|
|
613
|
+
chainOwner = (await this.ctx.publicClient.readContract({
|
|
614
|
+
address: this.ctx.addresses.agenticID,
|
|
615
|
+
abi: agenticIDAbi,
|
|
616
|
+
functionName: 'ownerOf',
|
|
617
|
+
args: [onChain.agentId],
|
|
618
|
+
})) as Address;
|
|
619
|
+
} catch (e) {
|
|
620
|
+
throw new SecretEnvRefusedError('chain_read_failed', `sealApiKey: ownerOf failed: ${errMsg(e)}`, { cause: e });
|
|
621
|
+
}
|
|
622
|
+
if (getAddress(chainOwner) !== getAddress(params.owner)) {
|
|
623
|
+
throw new SecretEnvRefusedError(
|
|
624
|
+
'owner_mismatch',
|
|
625
|
+
`sealApiKey: ${getAddress(params.owner)} is not the agent's on-chain owner (${getAddress(chainOwner)}); ` +
|
|
626
|
+
'its container would refuse the secret',
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return sealSecretEnv(pubkey, params.owner, { API_KEY: params.apiKey }, boundRoute || provider !== '0g-compute' ? provider : undefined, boundRoute?.hash, boundRoute?.registry);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** On-chain agentId + agentSeal of a minted agent; null before the mint
|
|
634
|
+
* (or when this client has no chain context, e.g. a bare AttestorClient
|
|
635
|
+
* in tests). A failed read throws: an unanswered check is not a pass. */
|
|
636
|
+
private async onChainAgent(sealId: `0x${string}`): Promise<{ agentId: bigint; agentSeal: Address } | null> {
|
|
637
|
+
const registry = this.ctx.addresses?.agenticID;
|
|
638
|
+
if (!registry || !this.ctx.publicClient) return null;
|
|
639
|
+
try {
|
|
640
|
+
const agentId = (await this.ctx.publicClient.readContract({
|
|
641
|
+
address: registry,
|
|
642
|
+
abi: agenticIDAbi,
|
|
643
|
+
functionName: 'getAgentIdBySealId',
|
|
644
|
+
args: [sealId],
|
|
645
|
+
})) as bigint;
|
|
646
|
+
// 0 means "not minted" OR agent #0 (a valid canonical id): disambiguate.
|
|
647
|
+
if (agentId === 0n) {
|
|
648
|
+
const bound = (await this.ctx.publicClient.readContract({
|
|
649
|
+
address: registry,
|
|
650
|
+
abi: agenticIDAbi,
|
|
651
|
+
functionName: 'isSealIdBound',
|
|
652
|
+
args: [sealId],
|
|
653
|
+
})) as boolean;
|
|
654
|
+
if (!bound) return null;
|
|
655
|
+
}
|
|
656
|
+
const agentSeal = (await this.ctx.publicClient.readContract({
|
|
657
|
+
address: registry,
|
|
658
|
+
abi: agenticIDAbi,
|
|
659
|
+
functionName: 'getAgentSeal',
|
|
660
|
+
args: [agentId],
|
|
661
|
+
})) as Address;
|
|
662
|
+
return { agentId, agentSeal };
|
|
663
|
+
} catch (e) {
|
|
664
|
+
throw new SecretEnvRefusedError('chain_read_failed', `agentSeal chain check failed: ${errMsg(e)}`, { cause: e });
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* A FRESH read of `GET /config` for the seal-or-not decision, so turning
|
|
670
|
+
* the flag ON reaches long-lived clients on their next call. The other
|
|
671
|
+
* direction is deliberately NOT symmetric: after this client (or machine)
|
|
672
|
+
* has seen the scheme once, its absence throws `scheme_withdrawn` — see
|
|
673
|
+
* the sticky pin below. Returns the scheme ('' when never seen and not
|
|
674
|
+
* advertised); throws when /config cannot be read at all.
|
|
675
|
+
*/
|
|
676
|
+
private async secretEnvScheme(): Promise<string> {
|
|
677
|
+
const cfg = await this.attestorConfig({ fresh: true });
|
|
678
|
+
// attestorConfig() answers {} when /config is unreachable. Reading that
|
|
679
|
+
// as "unsupported" would put the key in clear in front of the wallet on
|
|
680
|
+
// a transient error, so stop instead.
|
|
681
|
+
if (Object.keys(cfg).length === 0) {
|
|
682
|
+
throw new SecretEnvRefusedError(
|
|
683
|
+
'config_unreadable',
|
|
684
|
+
"cannot read the attestor's GET /config to decide how to deliver the key; retry, or pass secretEnv: 'plaintext' explicitly",
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
const advertised = cfg.secret_env_scheme === SECRET_ENV_SCHEME;
|
|
688
|
+
// Sticky pin: the seal-or-not decision rides an answer a relaying proxy
|
|
689
|
+
// can edit, and for 'auto' a stripped `secret_env_scheme` is
|
|
690
|
+
// indistinguishable from an old attestor — the one downgrade the sealing
|
|
691
|
+
// is meant to prevent. So the scheme can appear but never disappear:
|
|
692
|
+
// once this client (or, through `secretEnvPin`, this machine) has seen
|
|
693
|
+
// it, its absence is a refusal, not a clear-text fallback. A deliberate
|
|
694
|
+
// operator rollback is expressed by the caller as secretEnv: 'plaintext'.
|
|
695
|
+
const url = this.baseUrl();
|
|
696
|
+
if (advertised) {
|
|
697
|
+
this.schemeSeen = true;
|
|
698
|
+
await this.ctx.secretEnvPin?.record(url);
|
|
699
|
+
return SECRET_ENV_SCHEME;
|
|
700
|
+
}
|
|
701
|
+
if (this.schemeSeen || (await this.ctx.secretEnvPin?.seen(url))) {
|
|
702
|
+
throw new SecretEnvRefusedError(
|
|
703
|
+
'scheme_withdrawn',
|
|
704
|
+
`this attestor advertised secret_env_scheme=${SECRET_ENV_SCHEME} before but no longer does — ` +
|
|
705
|
+
"a relaying proxy may be stripping it to force a clear-text key. Refusing to downgrade; " +
|
|
706
|
+
"if the attestor really rolled the flag back, pass secretEnv: 'plaintext' explicitly",
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
return '';
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
private async requireSecretEnvScheme(what: string): Promise<void> {
|
|
713
|
+
if (!(await this.secretEnvScheme())) throw schemeUnsupported(what);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** env block for a sandbox create payload: the inference key (sealed or in
|
|
717
|
+
* clear, see {@link keyEnv}), and nothing else. Reasoning depth used to
|
|
718
|
+
* ride here as `SEAL_OWNER_THINKING`; it does not any more — the container
|
|
719
|
+
* reads `thinking` from the owner's settings document, which reaches it on
|
|
720
|
+
* EVERY boot (including a resume, which a create-time variable misses) and
|
|
721
|
+
* can be changed without a recreate. See {@link SettingsDoc}. */
|
|
722
|
+
private async sandboxEnv(p: {
|
|
723
|
+
image?: string;
|
|
724
|
+
sealId?: `0x${string}`;
|
|
725
|
+
apiKey?: string;
|
|
726
|
+
provider?: string;
|
|
727
|
+
sealedSecretEnv?: string;
|
|
728
|
+
mode?: SecretEnvMode;
|
|
729
|
+
}): Promise<Record<string, string>> {
|
|
730
|
+
const env: Record<string, string> = {};
|
|
731
|
+
if (p.apiKey || p.sealedSecretEnv !== undefined) {
|
|
732
|
+
Object.assign(env, await this.keyEnv(p.apiKey, p.sealedSecretEnv, p.mode ?? 'auto', p.sealId, p.provider, p.image));
|
|
733
|
+
}
|
|
734
|
+
return env;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* How the inference key rides the create payload (issue #166):
|
|
739
|
+
* - `sealedSecretEnv` (sealed elsewhere, e.g. by an integrator's server
|
|
740
|
+
* with {@link sealApiKey}): placed verbatim as `SEAL_SECRET_ENV`, only
|
|
741
|
+
* when the attestor advertises `secret_env_scheme`; there is no clear
|
|
742
|
+
* fallback, because there is no key here to fall back to;
|
|
743
|
+
* - `apiKey`, sealed here to the agent as `SEAL_SECRET_ENV` (see
|
|
744
|
+
* secretEnv.ts) when the agent already exists (`sealId`) and the
|
|
745
|
+
* attestor advertises `secret_env_scheme`, so the wallet prompt shows
|
|
746
|
+
* ciphertext only;
|
|
747
|
+
* - otherwise `apiKey` in clear as `API_KEY` (older attestors and images,
|
|
748
|
+
* and a one-shot `deploy`, whose agent does not exist when it signs),
|
|
749
|
+
* unless `mode` is `'sealed'`, which throws instead.
|
|
750
|
+
* Once sealing is chosen, every error throws: nothing falls back to clear
|
|
751
|
+
* text after the fact. Every throw is a {@link SecretEnvRefusedError}
|
|
752
|
+
* raised before anything is signed.
|
|
753
|
+
*/
|
|
754
|
+
private async keyEnv(
|
|
755
|
+
apiKey: string | undefined,
|
|
756
|
+
sealedSecretEnv: string | undefined,
|
|
757
|
+
mode: SecretEnvMode,
|
|
758
|
+
sealId?: `0x${string}`,
|
|
759
|
+
provider = '0g-compute',
|
|
760
|
+
image?: string,
|
|
761
|
+
): Promise<Record<string, string>> {
|
|
762
|
+
assertSecretEnvMode(mode);
|
|
763
|
+
const boundRoute = await this.credentialRoute(provider, image, sealId);
|
|
764
|
+
if (boundRoute) {
|
|
765
|
+
if (mode === 'plaintext') throw new SecretEnvRefusedError('provider_binding_unsupported', 'dynamic routes require sealed credentials');
|
|
766
|
+
mode = 'sealed';
|
|
767
|
+
}
|
|
768
|
+
if (provider !== '0g-compute') {
|
|
769
|
+
if (!sealId) throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
|
|
770
|
+
if (mode === 'plaintext') throw new SecretEnvRefusedError('provider_binding_unsupported', 'non-compute providers require a provider-bound sealed key');
|
|
771
|
+
await this.assertProviderSupported(provider, { sealId, sealedImage: image });
|
|
772
|
+
mode = 'sealed';
|
|
773
|
+
}
|
|
774
|
+
if (sealedSecretEnv !== undefined) {
|
|
775
|
+
if (apiKey) {
|
|
776
|
+
throw new SecretEnvRefusedError('conflicting_inputs', 'pass apiKey or sealedSecretEnv, not both');
|
|
777
|
+
}
|
|
778
|
+
if (mode === 'plaintext') {
|
|
779
|
+
throw new SecretEnvRefusedError('conflicting_inputs', "sealedSecretEnv cannot be sent with secretEnv: 'plaintext'");
|
|
780
|
+
}
|
|
781
|
+
if (!sealId) throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
|
|
782
|
+
const value = checkSealedSecretEnv(sealedSecretEnv);
|
|
783
|
+
await this.requireSecretEnvScheme('sealedSecretEnv');
|
|
784
|
+
return { [SECRET_ENV_VAR]: value };
|
|
785
|
+
}
|
|
786
|
+
if (!apiKey) return {};
|
|
787
|
+
if (mode === 'plaintext') return { API_KEY: apiKey };
|
|
788
|
+
if (!sealId) {
|
|
789
|
+
if (mode === 'sealed') throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
|
|
790
|
+
return { API_KEY: apiKey };
|
|
791
|
+
}
|
|
792
|
+
if (!(await this.secretEnvScheme())) {
|
|
793
|
+
if (mode === 'sealed') throw schemeUnsupported("secretEnv 'sealed'");
|
|
794
|
+
return { API_KEY: apiKey };
|
|
795
|
+
}
|
|
796
|
+
const { account } = requireWallet(this.ctx);
|
|
797
|
+
const pubkey = await this.agentSealPubkey(sealId);
|
|
798
|
+
return { [SECRET_ENV_VAR]: sealSecretEnv(pubkey, account.address, { API_KEY: apiKey }, boundRoute || provider !== '0g-compute' ? provider : undefined, boundRoute?.hash, boundRoute?.registry) };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** Sandbox "create" envelope for deploy (relayed to the provider). */
|
|
802
|
+
private async sandboxEnvelope(sandbox: NonNullable<DeployParams['sandbox']>, ttlSec: number, framework?: string) {
|
|
803
|
+
const snapshot = await this.resolveSealedImage(sandbox.sealedImage, framework);
|
|
804
|
+
return this.signEnvelope(
|
|
805
|
+
'create',
|
|
806
|
+
sandbox.resourceId ?? '',
|
|
807
|
+
{
|
|
808
|
+
snapshot,
|
|
809
|
+
sealed: sandbox.sealed ?? true,
|
|
810
|
+
// No sealId: the agent does not exist until /deploy answers.
|
|
811
|
+
env: await this.sandboxEnv({ apiKey: sandbox.apiKey, mode: sandbox.secretEnv }),
|
|
812
|
+
},
|
|
813
|
+
ttlSec,
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* Lifecycle op on a deployed agent's sandbox. `stop`/`start` act on the
|
|
819
|
+
* existing container (resourceId = sandbox_id); `reset` is an
|
|
820
|
+
* unconditional recreate (action="create", empty resource_id) that
|
|
821
|
+
* preserves the on-chain identity and replaces only the container —
|
|
822
|
+
* the way to force a fresh boot (e.g. after a new sealed image, or
|
|
823
|
+
* stuck-state recovery). All are owner-signed; the attestor + sandbox
|
|
824
|
+
* both re-verify.
|
|
825
|
+
*/
|
|
826
|
+
async lifecycle(
|
|
827
|
+
op: 'stop' | 'start' | 'reset',
|
|
828
|
+
params: {
|
|
829
|
+
sealId: `0x${string}`;
|
|
830
|
+
sandboxId?: string;
|
|
831
|
+
/** Framework name for `reset`/first `start` — the SDK resolves its
|
|
832
|
+
* sealed image from GET /config's frameworks[] (same as deploy), so a
|
|
833
|
+
* non-default framework doesn't need `sealedImage` passed. */
|
|
834
|
+
framework?: string;
|
|
835
|
+
/** The sealed runtime image name (0g-sandbox's own field is called
|
|
836
|
+
* `snapshot`; only relevant for `reset`). Explicit wins over the
|
|
837
|
+
* framework-resolved image. */
|
|
838
|
+
sealedImage?: string;
|
|
839
|
+
/** Inference API key for `reset` — the fresh container needs a fresh
|
|
840
|
+
* env (the attestor doesn't cache the LLM key). Without it the agent
|
|
841
|
+
* comes back alive but can't call its model. Sealed to the agent when
|
|
842
|
+
* the attestor supports it (see `secretEnv`). */
|
|
843
|
+
apiKey?: string;
|
|
844
|
+
/** Credential provider; defaults to legacy compute. */
|
|
845
|
+
provider?: string;
|
|
846
|
+
/** The key already sealed to this agent (the value {@link sealApiKey}
|
|
847
|
+
* returned, e.g. on an integrator's server), in place of `apiKey`:
|
|
848
|
+
* signed verbatim as `SEAL_SECRET_ENV`, so the key never has to reach
|
|
849
|
+
* the signer. Requires the attestor to advertise `secret_env_scheme`. */
|
|
850
|
+
sealedSecretEnv?: string;
|
|
851
|
+
/** How `apiKey` travels; see {@link SecretEnvMode}. Default `'auto'`. */
|
|
852
|
+
secretEnv?: SecretEnvMode;
|
|
853
|
+
envelopeTtlSec?: number;
|
|
854
|
+
},
|
|
855
|
+
): Promise<void> {
|
|
856
|
+
const { account } = requireWallet(this.ctx);
|
|
857
|
+
const ttl = params.envelopeTtlSec ?? 180;
|
|
858
|
+
let envelope;
|
|
859
|
+
// `reset`, OR a first-time `start` of a never-provisioned (mint-only)
|
|
860
|
+
// agent: both spin a FRESH container via the `create` envelope. A `start`
|
|
861
|
+
// WITH a sandboxId resumes an existing (stopped) container instead.
|
|
862
|
+
if (op === 'reset' || (op === 'start' && !params.sandboxId)) {
|
|
863
|
+
if (params.provider && params.provider !== '0g-compute' && !params.apiKey && params.sealedSecretEnv === undefined) {
|
|
864
|
+
throw new SecretEnvRefusedError('invalid_input', `reset/start for ${params.provider} requires its API key`);
|
|
865
|
+
}
|
|
866
|
+
const snapshot = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId);
|
|
867
|
+
envelope = await this.signEnvelope(
|
|
868
|
+
'create',
|
|
869
|
+
'',
|
|
870
|
+
{
|
|
871
|
+
snapshot,
|
|
872
|
+
sealed: true,
|
|
873
|
+
...(params.apiKey || params.sealedSecretEnv !== undefined
|
|
874
|
+
? {
|
|
875
|
+
env: await this.sandboxEnv({
|
|
876
|
+
sealId: params.sealId,
|
|
877
|
+
provider: params.provider,
|
|
878
|
+
image: snapshot,
|
|
879
|
+
apiKey: params.apiKey,
|
|
880
|
+
sealedSecretEnv: params.sealedSecretEnv,
|
|
881
|
+
mode: params.secretEnv,
|
|
882
|
+
}),
|
|
883
|
+
}
|
|
884
|
+
: {}),
|
|
885
|
+
},
|
|
886
|
+
ttl,
|
|
887
|
+
);
|
|
888
|
+
} else {
|
|
889
|
+
if (!params.sandboxId) throw new Error(`${op}: sandboxId is required`);
|
|
890
|
+
envelope = await this.signEnvelope(op, params.sandboxId, {}, ttl);
|
|
891
|
+
}
|
|
892
|
+
// A no-sandboxId `start` still POSTs /start; the attestor dispatches on the
|
|
893
|
+
// envelope action (create → fresh provision, start → resume).
|
|
894
|
+
const path = op === 'reset' ? '/reset' : `/${op}`;
|
|
895
|
+
const res = await fetch(`${this.baseUrl()}${path}`, {
|
|
896
|
+
method: 'POST',
|
|
897
|
+
headers: { 'content-type': 'application/json' },
|
|
898
|
+
// `framework` rides along so the attestor can keep the row's recorded
|
|
899
|
+
// framework in sync when a reset switches harness (review #154 F1) —
|
|
900
|
+
// optional; old attestors ignore unknown fields.
|
|
901
|
+
body: JSON.stringify({ seal_id: params.sealId, owner: account.address, sandbox_envelope: envelope, ...(params.framework ? { framework: params.framework } : {}) }),
|
|
902
|
+
});
|
|
903
|
+
if (!res.ok) {
|
|
904
|
+
const text = await res.text().catch(() => '');
|
|
905
|
+
throw new Error(`${path} failed: HTTP ${res.status} ${text}`);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// ── owner settings ──────────────────────────────────────────────────────
|
|
910
|
+
// One document per agent, stored by the attestor as an OPAQUE blob and
|
|
911
|
+
// applied by the container. Its rule, in BOTH directions, is "signed by the
|
|
912
|
+
// agent's current ON-CHAIN owner" (read live at request time, the way
|
|
913
|
+
// lifecycle_auth.rs does — an indexed column that lags would let a seller
|
|
914
|
+
// keep reading and configuring an agent they already sold), and a write
|
|
915
|
+
// additionally has to name the version it is replacing.
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* The agent's current settings document, as the attestor is holding it, plus
|
|
919
|
+
* the version to write it back against. `settings: null` means the agent has
|
|
920
|
+
* never been configured — not an error — and `version: 0` is exactly the
|
|
921
|
+
* `baseVersion` such a first write takes.
|
|
922
|
+
*
|
|
923
|
+
* OWNER-SIGNED, like the write, and against the same LIVE on-chain owner:
|
|
924
|
+
* the document is the owner's, it can name a private endpoint or a paid
|
|
925
|
+
* model, and it is no more public than the wallet that authored it. It is
|
|
926
|
+
* therefore NOT on the deployment row and NOT in any listing —
|
|
927
|
+
* `GET /settings?seal_id=…` with an owner signature is the only way to read
|
|
928
|
+
* it. The message is the write's minus the digest (there is no body), so it
|
|
929
|
+
* ends at the base version, which a reader sends as 0.
|
|
930
|
+
*
|
|
931
|
+
* Requires a wallet.
|
|
932
|
+
*/
|
|
933
|
+
async getSettings(sealId: `0x${string}`): Promise<{ settings: SettingsDoc | null; version: number }> {
|
|
934
|
+
const { walletClient, account } = requireWallet(this.ctx);
|
|
935
|
+
const seal = sealId.toLowerCase() as `0x${string}`;
|
|
936
|
+
const message = settingsAuthMessage(seal, Math.floor(Date.now() / 1000), 0);
|
|
937
|
+
const signature = await walletClient.signMessage({ account, message });
|
|
938
|
+
const res = await fetch(`${this.baseUrl()}/settings?seal_id=${seal}`, {
|
|
939
|
+
headers: { 'X-Auth-Message': message, 'X-Auth-Signature': signature },
|
|
940
|
+
signal: AbortSignal.timeout(10_000),
|
|
941
|
+
});
|
|
942
|
+
if (!res.ok) {
|
|
943
|
+
const text = await res.text().catch(() => '');
|
|
944
|
+
if (res.status === 401) {
|
|
945
|
+
throw new Error(
|
|
946
|
+
`getSettings: rejected (HTTP 401) — ${account.address} is not agent ${seal}'s current on-chain owner. ${text}`,
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
throw new Error(`getSettings: /settings HTTP ${res.status} ${text}`);
|
|
950
|
+
}
|
|
951
|
+
return parseSettingsBody(await res.json());
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/**
|
|
955
|
+
* Write a new settings document (owner-signed, compare-and-swap).
|
|
956
|
+
*
|
|
957
|
+
* The wire contract, exactly:
|
|
958
|
+
* - body `{"seal_id": "0x…", "base_version": <n>, "settings": <the document>}`
|
|
959
|
+
* - header `X-Auth-Message: AgenticID.Settings.v1:0x<sealId>:<ts>:<base_version>:<sha256-hex>`
|
|
960
|
+
* - header `X-Auth-Signature: 0x<65-byte EIP-191 signature over that message>`
|
|
961
|
+
*
|
|
962
|
+
* `baseVersion` is the version {@link getSettings} returned before the edit
|
|
963
|
+
* (0 = "there is no document yet"). The attestor refuses with HTTP 409 when
|
|
964
|
+
* it no longer matches, which this method surfaces as
|
|
965
|
+
* {@link SettingsConflictError} carrying the re-read document. It never
|
|
966
|
+
* retries: a silent retry is precisely how the other writer's change
|
|
967
|
+
* vanishes.
|
|
968
|
+
*
|
|
969
|
+
* The signature covers a DIGEST of the document rather than the document
|
|
970
|
+
* itself — the signed statement rides a header, so it has to stay short and
|
|
971
|
+
* ASCII. The digest and the body are produced from ONE serialization
|
|
972
|
+
* ({@link canonicalSettings}, spliced into the body verbatim below): hashing
|
|
973
|
+
* one string and sending another is how a correct signature turns into a
|
|
974
|
+
* phantom "signer mismatch". The server side has to match that: hash the
|
|
975
|
+
* RAW `settings` slice of the body it received (serde_json's `&RawValue`),
|
|
976
|
+
* never a re-serialization of the parsed value — which is also the form
|
|
977
|
+
* that keeps the blob opaque to it.
|
|
978
|
+
*
|
|
979
|
+
* Pass `onWarn` to run the advisory model check BEFORE signing — a model
|
|
980
|
+
* absent from the 0G router catalog is reported, never blocked (a framework
|
|
981
|
+
* built-in is legitimately absent, and the container is the real gate). Omit
|
|
982
|
+
* it and no catalog request is made at all.
|
|
983
|
+
*/
|
|
984
|
+
async setSettings(params: {
|
|
985
|
+
sealId: `0x${string}`;
|
|
986
|
+
settings: SettingsDoc;
|
|
987
|
+
/** The version {@link getSettings} returned before this edit; 0 for a
|
|
988
|
+
* first write. A mismatch is an HTTP 409 → {@link SettingsConflictError}. */
|
|
989
|
+
baseVersion: number;
|
|
990
|
+
onWarn?: (warning: string) => void;
|
|
991
|
+
}): Promise<{ version: number }> {
|
|
992
|
+
const { walletClient, account } = requireWallet(this.ctx);
|
|
993
|
+
if (params.settings.provider) await this.assertProviderSupported(params.settings.provider, { sealId: params.sealId });
|
|
994
|
+
if (params.onWarn) {
|
|
995
|
+
for (const w of await modelAdvisory(params.settings, await this.providerDefinition(params.settings.provider ?? '0g-compute'))) params.onWarn(w);
|
|
996
|
+
}
|
|
997
|
+
// ONE serialization: hashed here, spliced into the body below.
|
|
998
|
+
const canonical = canonicalSettings(params.settings);
|
|
999
|
+
const sealId = params.sealId.toLowerCase() as `0x${string}`;
|
|
1000
|
+
// The body below is assembled by hand, so anything that is not a plain
|
|
1001
|
+
// integer here (undefined from a JS caller, a NaN from a bad parse) would
|
|
1002
|
+
// ship as invalid JSON under a signature that still verified. Refuse now.
|
|
1003
|
+
const base = Number(params.baseVersion);
|
|
1004
|
+
if (!Number.isSafeInteger(base) || base < 0) {
|
|
1005
|
+
throw new Error(
|
|
1006
|
+
`setSettings: baseVersion must be a non-negative integer (read it from getSettings), got ${String(params.baseVersion)}`,
|
|
1007
|
+
);
|
|
1008
|
+
}
|
|
1009
|
+
const message = settingsAuthMessage(
|
|
1010
|
+
sealId,
|
|
1011
|
+
Math.floor(Date.now() / 1000),
|
|
1012
|
+
base,
|
|
1013
|
+
await sha256Hex(canonical),
|
|
1014
|
+
);
|
|
1015
|
+
const signature = await walletClient.signMessage({ account, message });
|
|
1016
|
+
const res = await fetch(`${this.baseUrl()}/settings`, {
|
|
1017
|
+
method: 'POST',
|
|
1018
|
+
headers: {
|
|
1019
|
+
'content-type': 'application/json',
|
|
1020
|
+
'X-Auth-Message': message,
|
|
1021
|
+
'X-Auth-Signature': signature,
|
|
1022
|
+
},
|
|
1023
|
+
// Hand-assembled so the `settings` member is byte-for-byte the string
|
|
1024
|
+
// that was hashed. `JSON.stringify({seal_id, settings})` would re-encode
|
|
1025
|
+
// the document and put the digest one serializer quirk away from wrong.
|
|
1026
|
+
body: `{"seal_id":${JSON.stringify(sealId)},"base_version":${base},"settings":${canonical}}`,
|
|
1027
|
+
});
|
|
1028
|
+
if (!res.ok) {
|
|
1029
|
+
const text = await res.text().catch(() => '');
|
|
1030
|
+
if (res.status === 401) {
|
|
1031
|
+
throw new Error(
|
|
1032
|
+
`setSettings: rejected (HTTP 401) — ${account.address} is not agent ${sealId}'s current on-chain owner. ${text}`,
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
1035
|
+
if (res.status === 409) {
|
|
1036
|
+
// Re-read so the caller can SEE what it would have overwritten. The
|
|
1037
|
+
// read is the same owner-signed call, so it can fail on its own (a
|
|
1038
|
+
// transferred agent, a flaky attestor) — in that case fall back to the
|
|
1039
|
+
// version the refusal named, and say the document could not be read
|
|
1040
|
+
// rather than inventing one.
|
|
1041
|
+
const live = await this.getSettings(sealId).catch(() => null);
|
|
1042
|
+
throw new SettingsConflictError({
|
|
1043
|
+
sealId,
|
|
1044
|
+
baseVersion: base,
|
|
1045
|
+
currentVersion: live?.version ?? versionInBody(text),
|
|
1046
|
+
current: live?.settings ?? null,
|
|
1047
|
+
detail: live ? undefined : `could not re-read the current document: ${text.slice(0, 200)}`,
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
throw new Error(`/settings failed: HTTP ${res.status} ${text}`);
|
|
1051
|
+
}
|
|
1052
|
+
const body = (await res.json()) as { version?: number | string };
|
|
1053
|
+
return { version: Number(body.version ?? 0) };
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
/**
|
|
1057
|
+
* Soft-retry a stuck deployment (owner-signed) instead of redeploying —
|
|
1058
|
+
* which would orphan an already-minted identity. The attestor re-runs every
|
|
1059
|
+
* failed idempotent stage (storage upload from persisted ciphertext, mint
|
|
1060
|
+
* receipt re-fetch, setAgentURI, …) against the SAME seal_id.
|
|
1061
|
+
*
|
|
1062
|
+
* Without `apiKey`: posts `{ seal_id, owner }` — idempotent stages only, no
|
|
1063
|
+
* container work (the cheap owner-field auth path). With `apiKey` or
|
|
1064
|
+
* `sealedSecretEnv` (and optionally `sealedImage`): attaches the same
|
|
1065
|
+
* owner-signed "create" envelope reset uses (the key sealed to the agent when the attestor
|
|
1066
|
+
* supports it, see `secretEnv`), so the worker may continue past the
|
|
1067
|
+
* idempotent stages into container creation. The attestor keeps no copy of
|
|
1068
|
+
* the key outside that job, so — as with reset — continuing into a
|
|
1069
|
+
* container needs it re-supplied.
|
|
1070
|
+
*/
|
|
1071
|
+
async retry(params: {
|
|
1072
|
+
sealId: `0x${string}`;
|
|
1073
|
+
/** Framework name — resolves the sealed image from /config's frameworks[]
|
|
1074
|
+
* (same as deploy) when `sealedImage` isn't given. */
|
|
1075
|
+
framework?: string;
|
|
1076
|
+
sealedImage?: string;
|
|
1077
|
+
apiKey?: string;
|
|
1078
|
+
provider?: string;
|
|
1079
|
+
/** In place of `apiKey`: the key already sealed to this agent; see
|
|
1080
|
+
* {@link lifecycle}'s `sealedSecretEnv`. */
|
|
1081
|
+
sealedSecretEnv?: string;
|
|
1082
|
+
/** How `apiKey` travels; see {@link SecretEnvMode}. Default `'auto'`. */
|
|
1083
|
+
secretEnv?: SecretEnvMode;
|
|
1084
|
+
envelopeTtlSec?: number;
|
|
1085
|
+
}): Promise<void> {
|
|
1086
|
+
if (params.provider && params.provider !== '0g-compute' && !params.apiKey && params.sealedSecretEnv === undefined) {
|
|
1087
|
+
throw new SecretEnvRefusedError('invalid_input', `retry for ${params.provider} requires its API key`);
|
|
1088
|
+
}
|
|
1089
|
+
const { account } = requireWallet(this.ctx);
|
|
1090
|
+
const body: Record<string, unknown> = { seal_id: params.sealId, owner: account.address };
|
|
1091
|
+
if (params.apiKey || params.sealedSecretEnv !== undefined) {
|
|
1092
|
+
const snapshot = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId);
|
|
1093
|
+
body.sandbox_envelope = await this.signEnvelope(
|
|
1094
|
+
'create',
|
|
1095
|
+
'',
|
|
1096
|
+
{
|
|
1097
|
+
snapshot,
|
|
1098
|
+
sealed: true,
|
|
1099
|
+
env: await this.sandboxEnv({
|
|
1100
|
+
sealId: params.sealId,
|
|
1101
|
+
provider: params.provider,
|
|
1102
|
+
image: snapshot,
|
|
1103
|
+
apiKey: params.apiKey,
|
|
1104
|
+
sealedSecretEnv: params.sealedSecretEnv,
|
|
1105
|
+
mode: params.secretEnv,
|
|
1106
|
+
}),
|
|
1107
|
+
},
|
|
1108
|
+
params.envelopeTtlSec ?? 180,
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
const res = await fetch(`${this.baseUrl()}/retry`, {
|
|
1112
|
+
method: 'POST',
|
|
1113
|
+
headers: { 'content-type': 'application/json' },
|
|
1114
|
+
body: JSON.stringify(body),
|
|
1115
|
+
});
|
|
1116
|
+
if (!res.ok) {
|
|
1117
|
+
const text = await res.text().catch(() => '');
|
|
1118
|
+
throw new Error(`/retry failed: HTTP ${res.status} ${text}`);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/**
|
|
1123
|
+
* Deploy a new agent. The connected wallet is the owner. Returns the new
|
|
1124
|
+
* agent's identity; it drives storage → mint → setAgentURI and (given the
|
|
1125
|
+
* sandbox envelope) brings a container online.
|
|
1126
|
+
*/
|
|
1127
|
+
async deploy(params: DeployParams): Promise<DeployCloneResponse> {
|
|
1128
|
+
const { walletClient, account } = requireWallet(this.ctx);
|
|
1129
|
+
// Fail before the first signature: a one-shot deploy signs its create
|
|
1130
|
+
// envelope before the agent exists, so it can never seal the key.
|
|
1131
|
+
assertSecretEnvMode(params.sandbox?.secretEnv);
|
|
1132
|
+
const seed = params.iData?.find((entry) => entry.role === 'persona')?.plaintext as { inference?: { provider?: string } } | undefined;
|
|
1133
|
+
const provider = seed?.inference?.provider ?? params.inference?.provider ?? '0g-compute';
|
|
1134
|
+
await this.providerDefinition(provider);
|
|
1135
|
+
if (params.sandbox && provider !== '0g-compute') throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
|
|
1136
|
+
if (params.sandbox?.apiKey && params.sandbox.secretEnv === 'sealed') {
|
|
1137
|
+
throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
|
|
1138
|
+
}
|
|
1139
|
+
const owner = account.address;
|
|
1140
|
+
const idempotencyKey = params.idempotencyKey ?? `sdk-${randHex(16)}`;
|
|
1141
|
+
const source = params.iData?.length
|
|
1142
|
+
? params.iData
|
|
1143
|
+
: defaultIData({
|
|
1144
|
+
framework: params.framework,
|
|
1145
|
+
name: params.name,
|
|
1146
|
+
description: params.description,
|
|
1147
|
+
inference: params.inference,
|
|
1148
|
+
});
|
|
1149
|
+
const iData = source.map((d) => ({ role: d.role, plaintext: d.plaintext, extra: d.extra ?? {} }));
|
|
1150
|
+
|
|
1151
|
+
// Owner canonical — must match CanonicalDeploy (order is irrelevant; the
|
|
1152
|
+
// attestor deserializes then re-checks each field).
|
|
1153
|
+
const canonical = JSON.stringify({
|
|
1154
|
+
domain: DEPLOY_DOMAIN,
|
|
1155
|
+
idempotency_key: idempotencyKey,
|
|
1156
|
+
owner,
|
|
1157
|
+
name: params.name,
|
|
1158
|
+
description: params.description,
|
|
1159
|
+
image: params.image ?? null,
|
|
1160
|
+
i_data: iData,
|
|
1161
|
+
});
|
|
1162
|
+
const ownerSig = await walletClient.signMessage({ account, message: canonical });
|
|
1163
|
+
// Provision only when a sandbox is given; omit it → mint-only deploy
|
|
1164
|
+
// (attestor mints, no container — the agent lands Offline).
|
|
1165
|
+
const sandbox_envelope = params.sandbox
|
|
1166
|
+
? await this.sandboxEnvelope(params.sandbox, params.envelopeTtlSec ?? 180, params.framework)
|
|
1167
|
+
: undefined;
|
|
1168
|
+
|
|
1169
|
+
return this.post('/deploy', {
|
|
1170
|
+
idempotency_key: idempotencyKey,
|
|
1171
|
+
owner,
|
|
1172
|
+
owner_signature: ownerSig,
|
|
1173
|
+
owner_signed_message_b64: b64encode(canonical),
|
|
1174
|
+
name: params.name,
|
|
1175
|
+
description: params.description,
|
|
1176
|
+
image: params.image ?? null,
|
|
1177
|
+
i_data: iData,
|
|
1178
|
+
...(sandbox_envelope ? { sandbox_envelope } : {}),
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/**
|
|
1183
|
+
* Clone `sourceAgentId` to `targetOwner`. Lands Offline for the target owner.
|
|
1184
|
+
*
|
|
1185
|
+
* Owner mode (default): the connected wallet must be the current on-chain
|
|
1186
|
+
* owner of the source. Contract mode (`authorization`): the connected
|
|
1187
|
+
* wallet is the BUYER — it signs a `AgenticID.CloneContract.v1` intent, and
|
|
1188
|
+
* the source owner's on-chain authorizer decides. The intent signature is
|
|
1189
|
+
* transported by the marketplace backend verbatim (relayer can submit, not
|
|
1190
|
+
* alter).
|
|
1191
|
+
*/
|
|
1192
|
+
/** CloneGate address, required for contract-mode clones. */
|
|
1193
|
+
private cloneGateAddr(): `0x${string}` {
|
|
1194
|
+
const a = this.ctx.addresses.cloneGate;
|
|
1195
|
+
if (!a || a === '0x0000000000000000000000000000000000000000') {
|
|
1196
|
+
throw new Error(
|
|
1197
|
+
'contract-mode clone requires a CloneGate in this environment ' +
|
|
1198
|
+
'(the attestor /config reports no clone_gate_addr)',
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
return a;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
async clone(params: CloneParams): Promise<DeployCloneResponse> {
|
|
1205
|
+
const { walletClient, account } = requireWallet(this.ctx);
|
|
1206
|
+
if (params.sourceAgentId > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
1207
|
+
throw new Error('sourceAgentId too large for JSON number encoding');
|
|
1208
|
+
}
|
|
1209
|
+
if (params.authorization && params.targetOwner.toLowerCase() !== account.address.toLowerCase()) {
|
|
1210
|
+
throw new Error(
|
|
1211
|
+
'contract mode requires the connected wallet to be targetOwner ' +
|
|
1212
|
+
'(the buyer signs the intent)',
|
|
1213
|
+
);
|
|
1214
|
+
}
|
|
1215
|
+
const idempotencyKey = params.idempotencyKey ?? `sdk-${randHex(16)}`;
|
|
1216
|
+
// Contract mode: the intent signs the full policy context — the auth
|
|
1217
|
+
// data hash and the authorizer it will be evaluated under (review #145:
|
|
1218
|
+
// otherwise one signed intent replayable under N auth-data variants, or
|
|
1219
|
+
// across a policy rotation, each a fresh buyer-billed clone).
|
|
1220
|
+
let authDataKeccak: `0x${string}` | undefined;
|
|
1221
|
+
let authorizer: Address | undefined;
|
|
1222
|
+
if (params.authorization) {
|
|
1223
|
+
authDataKeccak = keccak256(params.authorization.authData);
|
|
1224
|
+
authorizer = params.authorization.authorizer
|
|
1225
|
+
?? (await this.ctx.publicClient.readContract({
|
|
1226
|
+
address: this.cloneGateAddr(),
|
|
1227
|
+
abi: cloneGateAbi,
|
|
1228
|
+
functionName: 'cloneAuthorizerOf',
|
|
1229
|
+
args: [params.sourceAgentId],
|
|
1230
|
+
}) as Address);
|
|
1231
|
+
if (authorizer === '0x0000000000000000000000000000000000000000') {
|
|
1232
|
+
throw new Error(
|
|
1233
|
+
'contract mode requires the source to have a clone authorizer configured ' +
|
|
1234
|
+
'(owner must call setCloneAuthorizer)',
|
|
1235
|
+
);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
const domain = params.authorization ? CLONE_CONTRACT_DOMAIN : CLONE_DOMAIN;
|
|
1239
|
+
const canonical = JSON.stringify({
|
|
1240
|
+
domain,
|
|
1241
|
+
idempotency_key: idempotencyKey,
|
|
1242
|
+
source_agent_id: Number(params.sourceAgentId),
|
|
1243
|
+
target_owner: params.targetOwner,
|
|
1244
|
+
...(params.authorization
|
|
1245
|
+
? { auth_data_keccak: authDataKeccak, authorizer }
|
|
1246
|
+
: {}),
|
|
1247
|
+
});
|
|
1248
|
+
const signature = await walletClient.signMessage({ account, message: canonical });
|
|
1249
|
+
const common = {
|
|
1250
|
+
idempotency_key: idempotencyKey,
|
|
1251
|
+
source_agent_id: Number(params.sourceAgentId),
|
|
1252
|
+
target_owner: params.targetOwner,
|
|
1253
|
+
};
|
|
1254
|
+
if (params.authorization) {
|
|
1255
|
+
return this.post('/clone', {
|
|
1256
|
+
...common,
|
|
1257
|
+
authorization: {
|
|
1258
|
+
mode: 'contract',
|
|
1259
|
+
intent_signature: signature,
|
|
1260
|
+
intent_signed_message_b64: b64encode(canonical),
|
|
1261
|
+
auth_data: params.authorization.authData,
|
|
1262
|
+
},
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
return this.post('/clone', {
|
|
1266
|
+
...common,
|
|
1267
|
+
owner_signature: signature,
|
|
1268
|
+
owner_signed_message_b64: b64encode(canonical),
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// Transient-retry wrapper for the mint-driving POSTs (/deploy, /clone).
|
|
1273
|
+
// Safe to retry because the SAME body carries the SAME idempotency_key, so
|
|
1274
|
+
// the attestor dedupes server-side (a retry after a dropped response returns
|
|
1275
|
+
// the existing agent, never a duplicate). We retry connection-level failures
|
|
1276
|
+
// (reset / timeout — fetch rejects) and 5xx; a 4xx is a client/business
|
|
1277
|
+
// rejection where retrying can't help, so it throws immediately.
|
|
1278
|
+
private async post(path: string, body: unknown): Promise<DeployCloneResponse> {
|
|
1279
|
+
const payload = JSON.stringify(body);
|
|
1280
|
+
const ATTEMPTS = 3;
|
|
1281
|
+
let lastErr: unknown;
|
|
1282
|
+
for (let i = 0; i < ATTEMPTS; i++) {
|
|
1283
|
+
if (i > 0) await new Promise((r) => setTimeout(r, 500 * 2 ** (i - 1))); // 0.5s, 1s
|
|
1284
|
+
let res: Response;
|
|
1285
|
+
try {
|
|
1286
|
+
res = await fetch(`${this.baseUrl()}${path}`, {
|
|
1287
|
+
method: 'POST',
|
|
1288
|
+
// X-Agentic-Client: the caller SDK/CLI version - lets the
|
|
1289
|
+
// attestor request logs show the client-version spread, pairing
|
|
1290
|
+
// with /config cli_latest on the advertise side.
|
|
1291
|
+
headers: { 'content-type': 'application/json', 'x-agentic-client': `sdk/${SDK_VERSION}` },
|
|
1292
|
+
body: payload,
|
|
1293
|
+
});
|
|
1294
|
+
} catch (e) {
|
|
1295
|
+
lastErr = e; // connection-level failure — transient, retry
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
if (res.ok) return (await res.json()) as DeployCloneResponse;
|
|
1299
|
+
const text = await res.text().catch(() => '');
|
|
1300
|
+
const err = new Error(`${path} failed: HTTP ${res.status} ${text}`);
|
|
1301
|
+
if (res.status < 500) throw err; // 4xx — client/business error, retry won't help
|
|
1302
|
+
lastErr = err; // 5xx — server transient, retry
|
|
1303
|
+
}
|
|
1304
|
+
throw lastErr;
|
|
1305
|
+
}
|
|
1306
|
+
}
|