@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.1

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