@0gfoundation/0g-agentdna 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/GUIDE.md +190 -40
  2. package/OPERATORS.md +164 -0
  3. package/OPERATORS.zh.md +141 -0
  4. package/PROVIDERS.md +6 -0
  5. package/PROVIDERS.zh.md +3 -1
  6. package/README.md +84 -11
  7. package/dist/AgentClient.d.ts +374 -26
  8. package/dist/AgentClient.d.ts.map +1 -1
  9. package/dist/AgentClient.js +323 -40
  10. package/dist/AgentClient.js.map +1 -1
  11. package/dist/AgenticID.d.ts +170 -80
  12. package/dist/AgenticID.d.ts.map +1 -1
  13. package/dist/AgenticID.js +300 -42
  14. package/dist/AgenticID.js.map +1 -1
  15. package/dist/AttestorClient.d.ts +115 -31
  16. package/dist/AttestorClient.d.ts.map +1 -1
  17. package/dist/AttestorClient.js +276 -56
  18. package/dist/AttestorClient.js.map +1 -1
  19. package/dist/Credentials.d.ts +574 -0
  20. package/dist/Credentials.d.ts.map +1 -0
  21. package/dist/Credentials.js +838 -0
  22. package/dist/Credentials.js.map +1 -0
  23. package/dist/Operators.d.ts +60 -0
  24. package/dist/Operators.d.ts.map +1 -0
  25. package/dist/Operators.js +38 -0
  26. package/dist/Operators.js.map +1 -0
  27. package/dist/Providers.d.ts +13 -0
  28. package/dist/Providers.d.ts.map +1 -1
  29. package/dist/Providers.js +20 -1
  30. package/dist/Providers.js.map +1 -1
  31. package/dist/Releases.d.ts +51 -0
  32. package/dist/Releases.d.ts.map +1 -0
  33. package/dist/Releases.js +72 -0
  34. package/dist/Releases.js.map +1 -0
  35. package/dist/ReputationClient.d.ts +47 -3
  36. package/dist/ReputationClient.d.ts.map +1 -1
  37. package/dist/ReputationClient.js +204 -78
  38. package/dist/ReputationClient.js.map +1 -1
  39. package/dist/ServeProof.d.ts +70 -23
  40. package/dist/ServeProof.d.ts.map +1 -1
  41. package/dist/ServeProof.js +94 -35
  42. package/dist/ServeProof.js.map +1 -1
  43. package/dist/ServeSession.d.ts +17 -2
  44. package/dist/ServeSession.d.ts.map +1 -1
  45. package/dist/ServeSession.js +77 -9
  46. package/dist/ServeSession.js.map +1 -1
  47. package/dist/Settings.d.ts +25 -1
  48. package/dist/Settings.d.ts.map +1 -1
  49. package/dist/Settings.js +53 -1
  50. package/dist/Settings.js.map +1 -1
  51. package/dist/TrustRegistry.d.ts +28 -0
  52. package/dist/TrustRegistry.d.ts.map +1 -0
  53. package/dist/TrustRegistry.js +67 -0
  54. package/dist/TrustRegistry.js.map +1 -0
  55. package/dist/abi.d.ts +346 -34
  56. package/dist/abi.d.ts.map +1 -1
  57. package/dist/abi.js +150 -30
  58. package/dist/abi.js.map +1 -1
  59. package/dist/cli/attach.d.ts +79 -0
  60. package/dist/cli/attach.d.ts.map +1 -0
  61. package/dist/cli/attach.js +253 -0
  62. package/dist/cli/attach.js.map +1 -0
  63. package/dist/cli/commands/cells.d.ts +45 -0
  64. package/dist/cli/commands/cells.d.ts.map +1 -1
  65. package/dist/cli/commands/cells.js +77 -0
  66. package/dist/cli/commands/cells.js.map +1 -1
  67. package/dist/cli/commands/cred.d.ts +12 -0
  68. package/dist/cli/commands/cred.d.ts.map +1 -0
  69. package/dist/cli/commands/cred.js +43 -0
  70. package/dist/cli/commands/cred.js.map +1 -0
  71. package/dist/cli/commands/doctor.d.ts.map +1 -1
  72. package/dist/cli/commands/doctor.js +44 -35
  73. package/dist/cli/commands/doctor.js.map +1 -1
  74. package/dist/cli/commands/interactive.d.ts +597 -21
  75. package/dist/cli/commands/interactive.d.ts.map +1 -1
  76. package/dist/cli/commands/interactive.js +5082 -1323
  77. package/dist/cli/commands/interactive.js.map +1 -1
  78. package/dist/cli/commands/list.d.ts +5 -5
  79. package/dist/cli/commands/list.d.ts.map +1 -1
  80. package/dist/cli/commands/list.js +21 -26
  81. package/dist/cli/commands/list.js.map +1 -1
  82. package/dist/cli/commands/providers.d.ts +4 -0
  83. package/dist/cli/commands/providers.d.ts.map +1 -1
  84. package/dist/cli/commands/providers.js +19 -5
  85. package/dist/cli/commands/providers.js.map +1 -1
  86. package/dist/cli/commands/releases.d.ts +13 -0
  87. package/dist/cli/commands/releases.d.ts.map +1 -0
  88. package/dist/cli/commands/releases.js +65 -0
  89. package/dist/cli/commands/releases.js.map +1 -0
  90. package/dist/cli/commands/settings.d.ts +5 -0
  91. package/dist/cli/commands/settings.d.ts.map +1 -1
  92. package/dist/cli/commands/settings.js +70 -24
  93. package/dist/cli/commands/settings.js.map +1 -1
  94. package/dist/cli/commands/status.d.ts +2 -1
  95. package/dist/cli/commands/status.d.ts.map +1 -1
  96. package/dist/cli/commands/status.js +22 -19
  97. package/dist/cli/commands/status.js.map +1 -1
  98. package/dist/cli/config.d.ts +48 -1
  99. package/dist/cli/config.d.ts.map +1 -1
  100. package/dist/cli/config.js +114 -5
  101. package/dist/cli/config.js.map +1 -1
  102. package/dist/cli/credentials.d.ts +179 -0
  103. package/dist/cli/credentials.d.ts.map +1 -0
  104. package/dist/cli/credentials.js +1443 -0
  105. package/dist/cli/credentials.js.map +1 -0
  106. package/dist/cli/download.d.ts +21 -0
  107. package/dist/cli/download.d.ts.map +1 -0
  108. package/dist/cli/download.js +89 -0
  109. package/dist/cli/download.js.map +1 -0
  110. package/dist/cli/env.d.ts +6 -0
  111. package/dist/cli/env.d.ts.map +1 -1
  112. package/dist/cli/env.js +18 -6
  113. package/dist/cli/env.js.map +1 -1
  114. package/dist/cli/envelope.d.ts +4 -2
  115. package/dist/cli/envelope.d.ts.map +1 -1
  116. package/dist/cli/envelope.js +10 -6
  117. package/dist/cli/envelope.js.map +1 -1
  118. package/dist/cli/errors.d.ts +45 -1
  119. package/dist/cli/errors.d.ts.map +1 -1
  120. package/dist/cli/errors.js +77 -0
  121. package/dist/cli/errors.js.map +1 -1
  122. package/dist/cli/inference.d.ts.map +1 -1
  123. package/dist/cli/inference.js +7 -0
  124. package/dist/cli/inference.js.map +1 -1
  125. package/dist/cli/inkView.d.ts +341 -0
  126. package/dist/cli/inkView.d.ts.map +1 -0
  127. package/dist/cli/inkView.js +1019 -0
  128. package/dist/cli/inkView.js.map +1 -0
  129. package/dist/cli/legacy/modelKey.d.ts +24 -0
  130. package/dist/cli/legacy/modelKey.d.ts.map +1 -0
  131. package/dist/cli/legacy/modelKey.js +32 -0
  132. package/dist/cli/legacy/modelKey.js.map +1 -0
  133. package/dist/cli/livePrompt.d.ts +212 -0
  134. package/dist/cli/livePrompt.d.ts.map +1 -0
  135. package/dist/cli/livePrompt.js +576 -0
  136. package/dist/cli/livePrompt.js.map +1 -0
  137. package/dist/cli/main.js +206 -72
  138. package/dist/cli/main.js.map +1 -1
  139. package/dist/cli/modelkey.d.ts +64 -0
  140. package/dist/cli/modelkey.d.ts.map +1 -0
  141. package/dist/cli/modelkey.js +113 -0
  142. package/dist/cli/modelkey.js.map +1 -0
  143. package/dist/cli/outboxSync.d.ts +51 -0
  144. package/dist/cli/outboxSync.d.ts.map +1 -0
  145. package/dist/cli/outboxSync.js +210 -0
  146. package/dist/cli/outboxSync.js.map +1 -0
  147. package/dist/cli/plain.d.ts +46 -0
  148. package/dist/cli/plain.d.ts.map +1 -0
  149. package/dist/cli/plain.js +260 -0
  150. package/dist/cli/plain.js.map +1 -0
  151. package/dist/cli/proofs.d.ts +5 -0
  152. package/dist/cli/proofs.d.ts.map +1 -1
  153. package/dist/cli/proofs.js +20 -0
  154. package/dist/cli/proofs.js.map +1 -1
  155. package/dist/cli/ref.d.ts.map +1 -1
  156. package/dist/cli/ref.js +3 -2
  157. package/dist/cli/ref.js.map +1 -1
  158. package/dist/cli/releaseNotice.d.ts +64 -0
  159. package/dist/cli/releaseNotice.d.ts.map +1 -0
  160. package/dist/cli/releaseNotice.js +194 -0
  161. package/dist/cli/releaseNotice.js.map +1 -0
  162. package/dist/cli/sdk.d.ts +18 -0
  163. package/dist/cli/sdk.d.ts.map +1 -1
  164. package/dist/cli/sdk.js +99 -1
  165. package/dist/cli/sdk.js.map +1 -1
  166. package/dist/cli/settings.d.ts +87 -6
  167. package/dist/cli/settings.d.ts.map +1 -1
  168. package/dist/cli/settings.js +270 -18
  169. package/dist/cli/settings.js.map +1 -1
  170. package/dist/cli/textfit.d.ts +28 -0
  171. package/dist/cli/textfit.d.ts.map +1 -0
  172. package/dist/cli/textfit.js +111 -0
  173. package/dist/cli/textfit.js.map +1 -0
  174. package/dist/constants.d.ts +1 -1
  175. package/dist/constants.js +1 -1
  176. package/dist/context.d.ts +26 -0
  177. package/dist/context.d.ts.map +1 -1
  178. package/dist/context.js +1 -0
  179. package/dist/context.js.map +1 -1
  180. package/dist/index.d.ts +19 -11
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +35 -2
  183. package/dist/index.js.map +1 -1
  184. package/dist/legacy/modelKey.d.ts +67 -0
  185. package/dist/legacy/modelKey.d.ts.map +1 -0
  186. package/dist/legacy/modelKey.js +80 -0
  187. package/dist/legacy/modelKey.js.map +1 -0
  188. package/dist/legacy/serveProofV1.d.ts +56 -0
  189. package/dist/legacy/serveProofV1.d.ts.map +1 -0
  190. package/dist/legacy/serveProofV1.js +91 -0
  191. package/dist/legacy/serveProofV1.js.map +1 -0
  192. package/dist/provider-catalog.json +3 -2
  193. package/dist/secretEnv.d.ts +18 -3
  194. package/dist/secretEnv.d.ts.map +1 -1
  195. package/dist/secretEnv.js +16 -2
  196. package/dist/secretEnv.js.map +1 -1
  197. package/dist/types.d.ts +63 -1
  198. package/dist/types.d.ts.map +1 -1
  199. package/dist/viemErrors.d.ts +30 -0
  200. package/dist/viemErrors.d.ts.map +1 -0
  201. package/dist/viemErrors.js +36 -0
  202. package/dist/viemErrors.js.map +1 -0
  203. package/package.json +5 -1
  204. package/src/AgentClient.ts +622 -68
  205. package/src/AgenticID.ts +345 -56
  206. package/src/AttestorClient.ts +330 -83
  207. package/src/Credentials.ts +1027 -0
  208. package/src/Operators.ts +71 -0
  209. package/src/Providers.ts +20 -0
  210. package/src/Releases.ts +95 -0
  211. package/src/ReputationClient.ts +231 -79
  212. package/src/ServeProof.ts +123 -39
  213. package/src/ServeSession.ts +91 -9
  214. package/src/Settings.ts +61 -1
  215. package/src/TrustRegistry.ts +75 -0
  216. package/src/abi.ts +153 -30
  217. package/src/cli/attach.ts +257 -0
  218. package/src/cli/commands/cells.ts +104 -0
  219. package/src/cli/commands/cred.ts +44 -0
  220. package/src/cli/commands/doctor.ts +45 -37
  221. package/src/cli/commands/interactive.ts +4120 -664
  222. package/src/cli/commands/list.ts +21 -30
  223. package/src/cli/commands/providers.ts +17 -4
  224. package/src/cli/commands/releases.ts +60 -0
  225. package/src/cli/commands/settings.ts +75 -28
  226. package/src/cli/commands/status.ts +24 -21
  227. package/src/cli/config.ts +119 -4
  228. package/src/cli/credentials.ts +1379 -0
  229. package/src/cli/download.ts +80 -0
  230. package/src/cli/env.ts +22 -7
  231. package/src/cli/envelope.ts +10 -6
  232. package/src/cli/errors.ts +92 -0
  233. package/src/cli/inference.ts +8 -1
  234. package/src/cli/inkView.ts +969 -0
  235. package/src/cli/legacy/modelKey.ts +35 -0
  236. package/src/cli/livePrompt.ts +615 -0
  237. package/src/cli/main.ts +206 -76
  238. package/src/cli/modelkey.ts +124 -0
  239. package/src/cli/outboxSync.ts +231 -0
  240. package/src/cli/plain.ts +260 -0
  241. package/src/cli/proofs.ts +27 -0
  242. package/src/cli/ref.ts +5 -4
  243. package/src/cli/releaseNotice.ts +200 -0
  244. package/src/cli/sdk.ts +87 -7
  245. package/src/cli/settings.ts +272 -22
  246. package/src/cli/textfit.ts +95 -0
  247. package/src/constants.ts +1 -1
  248. package/src/context.ts +28 -0
  249. package/src/index.ts +50 -7
  250. package/src/legacy/modelKey.ts +80 -0
  251. package/src/legacy/serveProofV1.ts +124 -0
  252. package/src/provider-catalog.json +3 -2
  253. package/src/secretEnv.ts +18 -3
  254. package/src/types.ts +60 -1
  255. package/src/viemErrors.ts +39 -0
@@ -13,10 +13,11 @@ import { getAddress, hexToBytes, isAddress, keccak256 } from 'viem';
13
13
  import { requireWallet, type Ctx, type AttestorPublicConfig } from './context';
14
14
  import { listInferenceProviders, ProviderRegistryClient, routeHash, registrySigningMessage, acceptedRegistryDigest, validateProvider, type InferenceProvider, type ProviderRegistrySnapshot } from './Providers';
15
15
  import { SDK_VERSION } from './constants';
16
+ import { OPERATOR_DOMAIN, OperatorConflictError, OperatorCheckpointSupersededError, assertOperatorComputeOptions, type OperatorOptions, type OperatorState, type RuntimeBinding } from './Operators';
16
17
  import { agenticIDAbi, cloneGateAbi, tappRegistryAbi } from './abi';
17
18
  import {
18
19
  canonicalSettings, modelAdvisory, settingsAuthMessage, SettingsConflictError, sha256Hex,
19
- THINKING_LEVELS, type SettingsDoc,
20
+ THINKING_LEVELS, versionPicksProblem, type SettingsDoc,
20
21
  } from './Settings';
21
22
  import {
22
23
  SECRET_ENV_SCHEME,
@@ -29,6 +30,7 @@ import {
29
30
  sealSecretEnv,
30
31
  type SecretEnvMode,
31
32
  } from './secretEnv';
33
+ import { carriesRequestKey, deployRequestKey } from './legacy/modelKey';
32
34
 
33
35
  export const CLONE_DOMAIN = 'AgenticID.Clone.v1';
34
36
  export const CLONE_CONTRACT_DOMAIN = 'AgenticID.CloneContract.v1';
@@ -228,13 +230,18 @@ export interface DeployParams {
228
230
  * Omit (or pass '') to use the attestor /config's current image —
229
231
  * the operator-maintained default. */
230
232
  sealedImage?: string;
231
- /** Inference API key. On this one-shot path the create envelope is
232
- * signed before the agent (and its agentSeal key) exists, so the key
233
- * cannot be sealed and rides the envelope in clear: the wallet prompt
234
- * shows it. To keep it out of the prompt, deploy without `sandbox`,
235
- * wait for the mint, then `start(sealId, { apiKey })`. */
236
- apiKey: string;
237
- /** See {@link SecretEnvMode}. `'sealed'` makes this call throw before
233
+ /** Inference API key. `AgentApi.deploy` stores it in the agent's
234
+ * credential set as the agent is created. LEGACY(model-key): it also
235
+ * rides the create envelope, for older images. On this one-shot path the
236
+ * envelope is signed before the agent (and its agentSeal key) exists, so
237
+ * the key cannot be sealed and rides the envelope in clear: the wallet
238
+ * prompt shows it. To keep it out of the prompt, deploy without `sandbox`,
239
+ * wait for the mint, then `start(sealId, { apiKey })`. Omit it to
240
+ * start without a model key (an agent that cannot call its model until
241
+ * one is set with `credentials.setModelKey`). */
242
+ apiKey?: string;
243
+ /** LEGACY(model-key): how `apiKey` rides the create envelope; see
244
+ * {@link SecretEnvMode}. `'sealed'` makes this call throw before
238
245
  * anything is signed, because a one-shot deploy cannot seal the key. */
239
246
  secretEnv?: SecretEnvMode;
240
247
  sealed?: boolean;
@@ -242,6 +249,20 @@ export interface DeployParams {
242
249
  };
243
250
  /** Seconds the sandbox envelope stays valid. Default 180. */
244
251
  envelopeTtlSec?: number;
252
+ /** The caller stores the agent's credential set right after the attestor
253
+ * accepts the deploy (`AgentApi.deploy` does with a model key): the
254
+ * attestor creates the container once the set is stored, shortly after
255
+ * the mint without one, or after a minute at the latest, so its first
256
+ * boot gets the set. Signed with the deploy; an attestor from before
257
+ * ignores it. Only with `sandbox`. */
258
+ awaitCredentials?: boolean;
259
+ }
260
+
261
+ /** The provider a deploy's model key is for: the persona's (the caller's own
262
+ * `iData`), else the SDK-built persona's (`inference`), else 0g-compute. */
263
+ export function deployProvider(params: Pick<DeployParams, 'iData' | 'inference'>): string {
264
+ const seed = params.iData?.find((entry) => entry.role === 'persona')?.plaintext as { inference?: { provider?: string } } | undefined;
265
+ return seed?.inference?.provider ?? params.inference?.provider ?? '0g-compute';
245
266
  }
246
267
 
247
268
  export interface DeployCloneResponse {
@@ -317,6 +338,16 @@ const SEALED_NEEDS_AGENT =
317
338
  '(and its agentSeal key) exists, so the key cannot be sealed. Deploy without `sandbox`, ' +
318
339
  'wait for the mint, then call start(sealId, { apiKey }).';
319
340
 
341
+ /**
342
+ * An HTTP refusal from the attestor or the sandbox provider. The message is
343
+ * `<what>[ failed]: HTTP <status> <body>` as before; the answer is also kept
344
+ * apart (`httpStatus`, `httpWhat`, `httpBody`), so a caller that shows it to
345
+ * a person (the CLI) can say what the server said instead of its raw body.
346
+ */
347
+ function httpRefusal(what: string, status: number, body: string, failed = true): Error & { httpStatus: number; httpWhat: string; httpBody: string } {
348
+ return Object.assign(new Error(`${what}${failed ? ' failed' : ''}: HTTP ${status} ${body}`), { httpStatus: status, httpWhat: what, httpBody: body });
349
+ }
350
+
320
351
  function errMsg(e: unknown): string {
321
352
  return e instanceof Error ? e.message : String(e);
322
353
  }
@@ -340,7 +371,7 @@ function schemeUnsupported(what: string): SecretEnvRefusedError {
340
371
  }
341
372
 
342
373
  export class AttestorClient {
343
- /** In-memory half of the secret-env sticky pin (see secretEnvScheme). */
374
+ /** LEGACY(model-key): in-memory half of the secret-env sticky pin (see secretEnvScheme). */
344
375
  private schemeSeen = false;
345
376
 
346
377
  constructor(private readonly ctx: Ctx, initialConfig?: AttestorPublicConfig) {
@@ -378,7 +409,7 @@ export class AttestorClient {
378
409
  },
379
410
  signal: AbortSignal.timeout(10_000),
380
411
  });
381
- if (!r.ok) throw new Error(`provider /api/balance: HTTP ${r.status} ${await r.text().catch(() => '')}`);
412
+ if (!r.ok) throw httpRefusal('provider /api/balance', r.status, await r.text().catch(() => ''), false);
382
413
  const b = (await r.json()) as { balance?: string; reserved?: string; outstanding_debt?: string; pending_settlement?: string; available?: string };
383
414
  return {
384
415
  balanceWei: BigInt(b.balance ?? '0'),
@@ -428,6 +459,7 @@ export class AttestorClient {
428
459
  resourceId: string,
429
460
  payload: Record<string, unknown>,
430
461
  ttlSec: number,
462
+ agenticBinding?: RuntimeBinding,
431
463
  ) {
432
464
  const { walletClient, account } = requireWallet(this.ctx);
433
465
  // Provider binding (0g-sandbox#93, anti cross-provider replay): inserted
@@ -436,6 +468,7 @@ export class AttestorClient {
436
468
  const provider = await this.resolveProviderAddr();
437
469
  const canonical = JSON.stringify({
438
470
  action,
471
+ ...(agenticBinding ? { agentic_id: agenticBinding } : {}),
439
472
  expires_at: Math.floor(Date.now() / 1000) + ttlSec,
440
473
  nonce: randHex(16),
441
474
  payload,
@@ -450,6 +483,143 @@ export class AttestorClient {
450
483
  };
451
484
  }
452
485
 
486
+ /** Public routing metadata; runtime requests are independently authorized by the attestor. */
487
+ async getOperator(sealId: `0x${string}`): Promise<OperatorState> {
488
+ return this.fetchOperator(sealId);
489
+ }
490
+
491
+ private async fetchOperator(sealId: `0x${string}`, checkpoint = false): Promise<OperatorState> {
492
+ const res = await fetch(`${this.baseUrl()}/operator?seal_id=${encodeURIComponent(sealId)}${checkpoint ? '&checkpoint=true' : ''}`, {
493
+ signal: AbortSignal.timeout(10_000),
494
+ });
495
+ if (!res.ok) {
496
+ const error = httpRefusal('/operator', res.status, await res.text().catch(() => ''));
497
+ Object.assign(error, { status: res.status });
498
+ throw error;
499
+ }
500
+ const body = await res.json() as {
501
+ owner: Address; operator: Address | null; version: number; allow_recreate: boolean;
502
+ expires_at: number;
503
+ checkpoint?: { number?: unknown; hash?: unknown } | null;
504
+ };
505
+ const anchor = body.checkpoint;
506
+ if (!isAddress(body.owner) || (body.operator !== null && !isAddress(body.operator)) ||
507
+ !Number.isSafeInteger(body.version) || body.version < 0 ||
508
+ !Number.isSafeInteger(body.expires_at) || body.expires_at < 0 ||
509
+ typeof body.allow_recreate !== 'boolean' ||
510
+ (anchor != null && (!Number.isSafeInteger(anchor.number) || Number(anchor.number) < 0 ||
511
+ typeof anchor.hash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(anchor.hash)))) {
512
+ throw new Error('/operator returned an invalid authorization summary');
513
+ }
514
+ return {
515
+ sealId, owner: getAddress(body.owner), operator: body.operator === null ? null : getAddress(body.operator),
516
+ version: body.version, allowRecreate: body.allow_recreate, expiresAt: body.expires_at,
517
+ checkpoint: anchor == null ? null : {
518
+ number: anchor.number as number, hash: anchor.hash as `0x${string}`,
519
+ },
520
+ };
521
+ }
522
+
523
+ /** Owner-only. A successful grant update retires the current runtime; provision again with its controller wallet. */
524
+ async setOperator(sealId: `0x${string}`, operator: Address, opts: OperatorOptions = {}): Promise<OperatorState> {
525
+ if (!isAddress(operator) || /^0x0{40}$/i.test(operator)) throw new Error('setOperator: operator must be a nonzero wallet address');
526
+ return this.writeOperator(sealId, getAddress(operator), opts);
527
+ }
528
+
529
+ /** Owner-only. Revokes future operations and retires the current runtime. */
530
+ async revokeOperator(sealId: `0x${string}`, opts: { baseVersion?: number } = {}): Promise<OperatorState> {
531
+ return this.writeOperator(sealId, null, opts);
532
+ }
533
+
534
+ private async writeOperator(sealId: `0x${string}`, operator: Address | null, opts: OperatorOptions): Promise<OperatorState> {
535
+ const { account, walletClient } = requireWallet(this.ctx);
536
+ const current = await this.fetchOperator(sealId, operator !== null);
537
+ if (getAddress(account.address) !== current.owner) throw new Error('operator authorization requires the current NFT owner');
538
+ if (operator !== null && !current.checkpoint) {
539
+ throw new Error('operator authorization requires a minted agent and an ownership checkpoint from the attestor');
540
+ }
541
+ const base = opts.baseVersion ?? current.version;
542
+ const expiry = operator === null ? 0 : opts.expiresAt ?? 0;
543
+ if (!Number.isSafeInteger(base) || base < 0) throw new Error('operator baseVersion must be a nonnegative safe integer');
544
+ if (!Number.isSafeInteger(expiry) || expiry < 0 || (expiry !== 0 && expiry <= Math.floor(Date.now() / 1000))) {
545
+ throw new Error('operator expiresAt must be 0 or a future Unix timestamp');
546
+ }
547
+ if (opts.allowRecreate !== undefined && typeof opts.allowRecreate !== 'boolean') {
548
+ throw new Error('operator allowRecreate must be a boolean');
549
+ }
550
+ const contract = this.ctx.addresses?.agenticID;
551
+ const chainId = this.ctx.chain?.id;
552
+ if (!contract || !isAddress(contract) || !Number.isSafeInteger(chainId) || chainId <= 0) {
553
+ throw new Error('operator authorization requires an AgenticID contract and chain');
554
+ }
555
+ const canonical = JSON.stringify({
556
+ domain: OPERATOR_DOMAIN, chain_id: chainId, contract, seal_id: sealId,
557
+ owner: account.address, base_version: base, operator,
558
+ allow_recreate: operator === null ? false : opts.allowRecreate ?? false,
559
+ expires_at: expiry, issued_at: Math.floor(Date.now() / 1000),
560
+ checkpoint: operator === null ? null : current.checkpoint,
561
+ });
562
+ const signature = await walletClient.signMessage({ account, message: canonical });
563
+ const res = await fetch(`${this.baseUrl()}/operator`, {
564
+ method: 'PUT', headers: { 'content-type': 'application/json' },
565
+ body: JSON.stringify({ seal_id: sealId, signed_message_b64: b64encode(canonical), signature }),
566
+ });
567
+ if (!res.ok) {
568
+ const text = await res.text().catch(() => '');
569
+ if (res.status === 409) {
570
+ let body: { error?: { code?: unknown }; minimum_block?: unknown } | undefined;
571
+ try { body = JSON.parse(text); } catch { /* Preserve the ordinary conflict for non-JSON responses. */ }
572
+ if (body?.error?.code === 'operator_checkpoint_superseded') {
573
+ const minimum = body.minimum_block;
574
+ throw new OperatorCheckpointSupersededError(sealId, base, text,
575
+ Number.isSafeInteger(minimum) && Number(minimum) >= 0 ? minimum as number : undefined);
576
+ }
577
+ throw new OperatorConflictError(sealId, base, text);
578
+ }
579
+ throw httpRefusal('/operator', res.status, text);
580
+ }
581
+ // Re-read public routing metadata after the write.
582
+ return this.getOperator(sealId);
583
+ }
584
+
585
+ private async runtimeAuthority(sealId: `0x${string}`): Promise<{ owner: Address; binding?: RuntimeBinding }> {
586
+ const { account } = requireWallet(this.ctx);
587
+ let state: OperatorState;
588
+ try {
589
+ state = await this.getOperator(sealId);
590
+ } catch (e) {
591
+ // Older attestors have no operator route and remain owner-only. Other
592
+ // failures must not produce an unbound operator envelope.
593
+ if ((e as { status?: number }).status === 404) return { owner: account.address };
594
+ throw e;
595
+ }
596
+ if (state.owner === getAddress(account.address)) return { owner: state.owner };
597
+ if (state.operator !== getAddress(account.address) || (state.expiresAt !== 0 && state.expiresAt <= Math.floor(Date.now() / 1000))) {
598
+ throw new Error('connected wallet is neither the current NFT owner nor its active operator');
599
+ }
600
+ const contract = this.ctx.addresses?.agenticID;
601
+ const chainId = this.ctx.chain?.id;
602
+ if (!contract || !isAddress(contract) || !Number.isSafeInteger(chainId) || chainId <= 0) {
603
+ throw new Error('operator lifecycle requires an AgenticID contract and chain');
604
+ }
605
+ return { owner: state.owner, binding: {
606
+ chain_id: chainId, contract, seal_id: sealId, operator_version: state.version,
607
+ } };
608
+ }
609
+
610
+ /** Whether the connected wallet is this agent's effective, paying operator. */
611
+ async isRuntimeOperator(sealId: `0x${string}`): Promise<boolean> {
612
+ return !!(await this.runtimeAuthority(sealId)).binding;
613
+ }
614
+
615
+ /** Public deployment routing, for callers that only retain the agent's seal. */
616
+ async currentSandboxId(sealId: `0x${string}`): Promise<string | null> {
617
+ const res = await fetch(`${this.baseUrl()}/deployment/${sealId}`, { signal: AbortSignal.timeout(10_000) });
618
+ if (!res.ok) throw new Error(`/deployment/${sealId} failed: HTTP ${res.status}`);
619
+ const row = await res.json() as { sandbox_id?: string | null };
620
+ return row.sandbox_id || null;
621
+ }
622
+
453
623
  /**
454
624
  * The agent's public deployment row (`GET /deployment/:sealId`). An
455
625
  * unreadable row refuses, naming `purpose`: the call that needs it posts to
@@ -598,6 +768,8 @@ export class AttestorClient {
598
768
  return this.publishSignedProviders({ document: prepared.document, signature });
599
769
  }
600
770
 
771
+ /** LEGACY(model-key): the route a request key is bound to (`keyEnv`,
772
+ * `sealApiKey`); a key in the set is bound by {@link modelKeyBinding}. */
601
773
  private async credentialRoute(provider: string, image: string | undefined, sealId: `0x${string}` | undefined): Promise<{ hash: string; registry: import('./Providers').ProviderRegistryPin } | undefined> {
602
774
  const accepted = await this.getProviderRegistry();
603
775
  const definition = accepted.providers.find((p) => p.id === provider);
@@ -614,7 +786,26 @@ export class AttestorClient {
614
786
  ...(accepted.version > 0 ? { digest: acceptedRegistryDigest(accepted.document!, accepted.signature!) } : {}) } } : undefined;
615
787
  }
616
788
 
617
- /** Verify support for an exact runtime image before signing an owner action. */
789
+ /**
790
+ * Where a model key set through the credential set may go
791
+ * (Credentials.setModelKey): the provider's route in the registry version
792
+ * the attestor serves now, which sealed reads back and checks before it uses
793
+ * the key; with no registry published, the image's built-in route (nothing
794
+ * to bind). The agent's image must support the provider.
795
+ */
796
+ async modelKeyBinding(provider: string, sealId: `0x${string}`): Promise<{ route_hash?: string; registry?: import('./Providers').ProviderRegistryPin }> {
797
+ await this.assertProviderSupported(provider, { sealId });
798
+ const accepted = await this.getProviderRegistry();
799
+ const definition = accepted.providers.find((p) => p.id === provider);
800
+ if (!definition) throw new Error(`UNSUPPORTED_INFERENCE_PROVIDER: ${provider}`);
801
+ if (accepted.version === 0) return {};
802
+ return { route_hash: routeHash(definition), registry: { version: accepted.version, digest: acceptedRegistryDigest(accepted.document!, accepted.signature!) } };
803
+ }
804
+
805
+ /** Verify support for an exact runtime image before signing an owner
806
+ * action: the image's capabilities the attestor advertises. Whether the
807
+ * request copy of a key can be sealed (`secret_env_scheme`) is not part of
808
+ * it; {@link keyEnv} checks that for the copy it builds. */
618
809
  async assertProviderSupported(provider: string, options: { sealId?: `0x${string}`; framework?: string; sealedImage?: string } = {}): Promise<void> {
619
810
  const definition = await this.providerDefinition(provider);
620
811
  const builtin = listInferenceProviders().find((entry) => entry.id === provider);
@@ -623,7 +814,7 @@ export class AttestorClient {
623
814
  const cfg = await this.attestorConfig({ fresh: true });
624
815
  const image = await this.resolveSealedImage(options.sealedImage, options.framework, options.sealId);
625
816
  const capabilities = Array.isArray(cfg.inference_capabilities) ? cfg.inference_capabilities : [];
626
- const supported = !!image && cfg.secret_env_scheme === SECRET_ENV_SCHEME && capabilities.some((entry) =>
817
+ const supported = !!image && capabilities.some((entry) =>
627
818
  entry.image === image && (
628
819
  (!changed && entry.providers.includes(provider) && entry.secret_env_versions.includes(2)) ||
629
820
  (entry.secret_env_versions.includes(3) && (definition.native ? entry.providers.includes(provider) : definition.formats.every((format) => entry.formats?.includes(format))))));
@@ -682,6 +873,8 @@ export class AttestorClient {
682
873
  }
683
874
 
684
875
  /**
876
+ * LEGACY(model-key): the request-only form of `credentials.sealModelKey`.
877
+ *
685
878
  * Seal an inference key for one agent without signing anything, for the
686
879
  * integrator whose server supplies the key while a user's wallet signs
687
880
  * (issue #166): the server calls this and hands the browser only the
@@ -706,7 +899,19 @@ export class AttestorClient {
706
899
  await this.assertProviderSupported(provider, params);
707
900
  const image = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId);
708
901
  const boundRoute = await this.credentialRoute(provider, image, params.sealId);
709
- const { pubkey, onChain } = await this.verifiedAgentSeal(params.sealId);
902
+ const pubkey = await this.agentSealPubkeyFor(params.sealId, params.owner, 'sealApiKey');
903
+ return sealSecretEnv(pubkey, params.owner, { API_KEY: params.apiKey }, boundRoute || provider !== '0g-compute' ? provider : undefined, boundRoute?.hash, boundRoute?.registry);
904
+ }
905
+
906
+ /**
907
+ * The agent's agentSeal public key, verified as {@link agentSealPubkey}
908
+ * does, for a value sealed on behalf of `owner` without its wallet. The
909
+ * container takes such a value only while `owner` owns the agent, so once
910
+ * the agent is minted `owner` must be its on-chain owner. `what` names the
911
+ * caller in a refusal. Throws {@link SecretEnvRefusedError}.
912
+ */
913
+ async agentSealPubkeyFor(sealId: `0x${string}`, owner: Address, what: string): Promise<`0x${string}`> {
914
+ const { pubkey, onChain } = await this.verifiedAgentSeal(sealId);
710
915
  if (onChain) {
711
916
  let chainOwner: Address;
712
917
  try {
@@ -717,17 +922,17 @@ export class AttestorClient {
717
922
  args: [onChain.agentId],
718
923
  })) as Address;
719
924
  } catch (e) {
720
- throw new SecretEnvRefusedError('chain_read_failed', `sealApiKey: ownerOf failed: ${errMsg(e)}`, { cause: e });
925
+ throw new SecretEnvRefusedError('chain_read_failed', `${what}: ownerOf failed: ${errMsg(e)}`, { cause: e });
721
926
  }
722
- if (getAddress(chainOwner) !== getAddress(params.owner)) {
927
+ if (getAddress(chainOwner) !== getAddress(owner)) {
723
928
  throw new SecretEnvRefusedError(
724
929
  'owner_mismatch',
725
- `sealApiKey: ${getAddress(params.owner)} is not the agent's on-chain owner (${getAddress(chainOwner)}); ` +
930
+ `${what}: ${getAddress(owner)} is not the agent's on-chain owner (${getAddress(chainOwner)}); ` +
726
931
  'its container would refuse the secret',
727
932
  );
728
933
  }
729
934
  }
730
- return sealSecretEnv(pubkey, params.owner, { API_KEY: params.apiKey }, boundRoute || provider !== '0g-compute' ? provider : undefined, boundRoute?.hash, boundRoute?.registry);
935
+ return pubkey;
731
936
  }
732
937
 
733
938
  /** On-chain agentId + agentSeal of a minted agent; null before the mint
@@ -766,6 +971,8 @@ export class AttestorClient {
766
971
  }
767
972
 
768
973
  /**
974
+ * LEGACY(model-key): only the request copy of a key is sealed this way.
975
+ *
769
976
  * A FRESH read of `GET /config` for the seal-or-not decision, so turning
770
977
  * the flag ON reaches long-lived clients on their next call. The other
771
978
  * direction is deliberately NOT symmetric: after this client (or machine)
@@ -809,12 +1016,14 @@ export class AttestorClient {
809
1016
  return '';
810
1017
  }
811
1018
 
1019
+ /** LEGACY(model-key): the scheme the request copy of a key needs. */
812
1020
  private async requireSecretEnvScheme(what: string): Promise<void> {
813
1021
  if (!(await this.secretEnvScheme())) throw schemeUnsupported(what);
814
1022
  }
815
1023
 
816
- /** env block for a sandbox create payload: the inference key (sealed or in
817
- * clear, see {@link keyEnv}), and nothing else. Reasoning depth used to
1024
+ /** LEGACY(model-key): env block for a sandbox create payload: the
1025
+ * inference key (sealed or in clear, see {@link keyEnv}), and nothing
1026
+ * else; without the request copy a create carries no env. Reasoning depth used to
818
1027
  * ride here as `SEAL_OWNER_THINKING`; it does not any more — the container
819
1028
  * reads `thinking` from the owner's settings document, which reaches it on
820
1029
  * EVERY boot (including a resume, which a create-time variable misses) and
@@ -835,6 +1044,9 @@ export class AttestorClient {
835
1044
  }
836
1045
 
837
1046
  /**
1047
+ * LEGACY(model-key): the key sent with the request, for images that read
1048
+ * only that (the credential set is the main path; legacy/modelKey.ts).
1049
+ *
838
1050
  * How the inference key rides the create payload (issue #166):
839
1051
  * - `sealedSecretEnv` (sealed elsewhere, e.g. by an integrator's server
840
1052
  * with {@link sealApiKey}): placed verbatim as `SEAL_SECRET_ENV`, only
@@ -908,7 +1120,7 @@ export class AttestorClient {
908
1120
  snapshot,
909
1121
  sealed: sandbox.sealed ?? true,
910
1122
  // No sealId: the agent does not exist until /deploy answers.
911
- env: await this.sandboxEnv({ apiKey: sandbox.apiKey, mode: sandbox.secretEnv }),
1123
+ env: await this.sandboxEnv(deployRequestKey(sandbox)),
912
1124
  },
913
1125
  ttlSec,
914
1126
  );
@@ -938,6 +1150,8 @@ export class AttestorClient {
938
1150
  params: {
939
1151
  sealId: `0x${string}`;
940
1152
  sandboxId?: string;
1153
+ /** Resolve the current mapping inside this request, without a second deployment read. */
1154
+ resolveSandbox?: boolean;
941
1155
  /** Framework name for `reset`/first `start` — the SDK resolves its
942
1156
  * sealed image from GET /config's frameworks[] (same as deploy), so a
943
1157
  * non-default framework doesn't need `sealedImage` passed. */
@@ -946,31 +1160,60 @@ export class AttestorClient {
946
1160
  * `snapshot`; only relevant for `reset`). Explicit wins over the
947
1161
  * framework-resolved image. */
948
1162
  sealedImage?: string;
949
- /** Inference API key for `reset` — the fresh container needs a fresh
950
- * env (the attestor doesn't cache the LLM key). Without it the agent
951
- * comes back alive but can't call its model. Sealed to the agent when
952
- * the attestor supports it (see `secretEnv`). */
1163
+ /** LEGACY(model-key): the model key sent with the request, for images
1164
+ * that read only that (`AgentApi` stores it in the credential set).
1165
+ * Sealed to the agent when the attestor supports it (see `secretEnv`). */
953
1166
  apiKey?: string;
954
1167
  /** Credential provider; defaults to legacy compute. */
955
1168
  provider?: string;
956
- /** The key already sealed to this agent (the value {@link sealApiKey}
957
- * returned, e.g. on an integrator's server), in place of `apiKey`:
958
- * signed verbatim as `SEAL_SECRET_ENV`, so the key never has to reach
959
- * the signer. Requires the attestor to advertise `secret_env_scheme`. */
1169
+ /** The agent's credential set holds a model key for `provider`: a
1170
+ * create without a key is not refused for it. */
1171
+ keyInCredentials?: boolean;
1172
+ /** Run once every check that can refuse has passed, before the first
1173
+ * write or signature (the model key going into the credential set). */
1174
+ beforeWrite?: () => Promise<void>;
1175
+ /** SDK owner-only model-key planning after runtime identity has been resolved. Never run for an operator. */
1176
+ prepareModelKey?: () => Promise<{ keyInCredentials: boolean; beforeWrite?: () => Promise<void> }>;
1177
+ /** Original facade options, checked without running owner callbacks for an operator. */
1178
+ operatorOptions?: Parameters<typeof assertOperatorComputeOptions>[0];
1179
+ /** LEGACY(model-key): the key already sealed to this agent (the value
1180
+ * {@link sealApiKey} returned, e.g. on an integrator's server), in place
1181
+ * of `apiKey`: signed verbatim as `SEAL_SECRET_ENV`, so the key never
1182
+ * has to reach the signer. Requires the attestor to advertise
1183
+ * `secret_env_scheme`. */
960
1184
  sealedSecretEnv?: string;
961
- /** How `apiKey` travels; see {@link SecretEnvMode}. Default `'auto'`. */
1185
+ /** LEGACY(model-key): how `apiKey` travels; see {@link SecretEnvMode}. Default `'auto'`. */
962
1186
  secretEnv?: SecretEnvMode;
963
1187
  envelopeTtlSec?: number;
964
1188
  },
965
1189
  ): Promise<void> {
966
- const { account } = requireWallet(this.ctx);
1190
+ // Resolve identity and deployment once for this call. Never reuse a grant
1191
+ // across calls; API and worker still revalidate at their own boundaries.
1192
+ const deploymentPurpose = op === 'stop' ? 'resolve the sandbox'
1193
+ : (op === 'reset' || !params.sandboxId) && !params.sealedImage && !params.framework
1194
+ ? "pick the sealed image and check the agent's settings" : "check the agent's settings";
1195
+ const [authority, row] = await Promise.all([
1196
+ this.runtimeAuthority(params.sealId),
1197
+ op !== 'stop' || (params.resolveSandbox && !params.sandboxId)
1198
+ ? this.deploymentRow(params.sealId, deploymentPurpose)
1199
+ : Promise.resolve(undefined),
1200
+ ]);
1201
+ const operator = !!authority.binding;
1202
+ if (operator) {
1203
+ assertOperatorComputeOptions(params);
1204
+ assertOperatorComputeOptions(params.operatorOptions ?? {});
1205
+ }
1206
+ const keyPlan = operator ? undefined : await params.prepareModelKey?.();
1207
+ const keyInCredentials = keyPlan?.keyInCredentials ?? params.keyInCredentials;
1208
+ const sandboxId = params.sandboxId ?? (params.resolveSandbox ? row?.sandbox_id as string | undefined : undefined);
967
1209
  const ttl = params.envelopeTtlSec ?? 180;
968
1210
  // `reset`, OR a first-time `start` of a never-provisioned (mint-only)
969
1211
  // agent: both spin a FRESH container via the `create` envelope. A `start`
970
1212
  // WITH a sandboxId resumes an existing (stopped) container instead.
971
- const create = op === 'reset' || (op === 'start' && !params.sandboxId);
972
- if (!create && !params.sandboxId) throw new Error(`${op}: sandboxId is required`);
973
- if (create && params.provider && params.provider !== '0g-compute' && !params.apiKey && params.sealedSecretEnv === undefined) {
1213
+ const create = op === 'reset' || (op === 'start' && !sandboxId);
1214
+ if (!create && !sandboxId) throw new Error(`${op}: sandboxId is required`);
1215
+ const requestKey = carriesRequestKey(params);
1216
+ if (create && !operator && params.provider && params.provider !== '0g-compute' && !requestKey && !keyInCredentials) {
974
1217
  throw new SecretEnvRefusedError('invalid_input', `reset/start for ${params.provider} requires its API key`);
975
1218
  }
976
1219
  // Every boot a start or reset brings about is served the agent's settings
@@ -978,15 +1221,8 @@ export class AttestorClient {
978
1221
  // one stored first (see needsDefaultSettings). The row is read, and every
979
1222
  // check below that can refuse runs, before anything is written or signed.
980
1223
  let seed: { provider: string; model: string } | null = null;
981
- let row: Record<string, unknown> | undefined;
982
1224
  if (op !== 'stop') {
983
- row = await this.deploymentRow(
984
- params.sealId,
985
- create && !params.sealedImage && !params.framework
986
- ? "pick the sealed image and check the agent's settings"
987
- : "check the agent's settings",
988
- );
989
- seed = this.defaultSettingsFor(row);
1225
+ seed = operator ? null : this.defaultSettingsFor(row!);
990
1226
  if (seed && params.provider && params.provider !== seed.provider) {
991
1227
  throw new Error(
992
1228
  `${op}: agent ${params.sealId} has no settings document and could boot with no model; ` +
@@ -995,7 +1231,7 @@ export class AttestorClient {
995
1231
  }
996
1232
  }
997
1233
  let action: string = op;
998
- let resourceId = params.sandboxId ?? '';
1234
+ let resourceId = sandboxId ?? '';
999
1235
  let payload: Record<string, unknown> = {};
1000
1236
  if (create) {
1001
1237
  const snapshot = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId, row);
@@ -1004,7 +1240,9 @@ export class AttestorClient {
1004
1240
  payload = {
1005
1241
  snapshot,
1006
1242
  sealed: true,
1007
- ...(params.apiKey || params.sealedSecretEnv !== undefined
1243
+ // LEGACY(model-key): the request copy; a key in the set reaches the
1244
+ // container through /provision.
1245
+ ...(requestKey
1008
1246
  ? {
1009
1247
  env: await this.sandboxEnv({
1010
1248
  sealId: params.sealId,
@@ -1018,13 +1256,17 @@ export class AttestorClient {
1018
1256
  : {}),
1019
1257
  };
1020
1258
  }
1259
+ if (!operator) {
1260
+ await params.beforeWrite?.();
1261
+ await keyPlan?.beforeWrite?.();
1262
+ }
1021
1263
  if (seed) {
1022
1264
  await storeDefaultSettings(
1023
1265
  { setSettings: (sealId, settings, opts) => this.setSettings({ sealId, settings, baseVersion: opts.baseVersion }) },
1024
1266
  params.sealId,
1025
1267
  );
1026
1268
  }
1027
- const envelope = await this.signEnvelope(action, resourceId, payload, ttl);
1269
+ const envelope = await this.signEnvelope(action, resourceId, payload, ttl, authority.binding);
1028
1270
  // A no-sandboxId `start` still POSTs /start; the attestor dispatches on the
1029
1271
  // envelope action (create → fresh provision, start → resume).
1030
1272
  const path = op === 'reset' ? '/reset' : `/${op}`;
@@ -1034,11 +1276,11 @@ export class AttestorClient {
1034
1276
  // `framework` rides along so the attestor can keep the row's recorded
1035
1277
  // framework in sync when a reset switches harness (review #154 F1) —
1036
1278
  // optional; old attestors ignore unknown fields.
1037
- body: JSON.stringify({ seal_id: params.sealId, owner: account.address, sandbox_envelope: envelope, ...(params.framework ? { framework: params.framework } : {}) }),
1279
+ body: JSON.stringify({ seal_id: params.sealId, owner: authority.owner, sandbox_envelope: envelope, ...(params.framework ? { framework: params.framework } : {}) }),
1038
1280
  });
1039
1281
  if (!res.ok) {
1040
1282
  const text = await res.text().catch(() => '');
1041
- throw new Error(`${path} failed: HTTP ${res.status} ${text}`);
1283
+ throw httpRefusal(path, res.status, text);
1042
1284
  }
1043
1285
  }
1044
1286
 
@@ -1134,6 +1376,8 @@ export class AttestorClient {
1134
1376
  && !(THINKING_LEVELS as readonly string[]).includes(thinking.trim().toLowerCase())) {
1135
1377
  throw new Error(`setSettings: thinking must be one of ${THINKING_LEVELS.join('|')}, got "${thinking}"`);
1136
1378
  }
1379
+ const versionsProblem = versionPicksProblem(params.settings.versions);
1380
+ if (versionsProblem) throw new Error(`setSettings: ${versionsProblem}`);
1137
1381
  if (params.settings.provider) await this.assertProviderSupported(params.settings.provider, { sealId: params.sealId });
1138
1382
  if (params.onWarn) {
1139
1383
  for (const w of await modelAdvisory(params.settings, await this.providerDefinition(params.settings.provider ?? '0g-compute'))) params.onWarn(w);
@@ -1191,7 +1435,7 @@ export class AttestorClient {
1191
1435
  detail: live ? undefined : `could not re-read the current document: ${text.slice(0, 200)}`,
1192
1436
  });
1193
1437
  }
1194
- throw new Error(`/settings failed: HTTP ${res.status} ${text}`);
1438
+ throw httpRefusal('/settings', res.status, text);
1195
1439
  }
1196
1440
  const body = (await res.json()) as { version?: number | string };
1197
1441
  return { version: Number(body.version ?? 0) };
@@ -1203,14 +1447,12 @@ export class AttestorClient {
1203
1447
  * failed idempotent stage (storage upload from persisted ciphertext, mint
1204
1448
  * receipt re-fetch, setAgentURI, …) against the SAME seal_id.
1205
1449
  *
1206
- * Without `apiKey`: posts `{ seal_id, owner }` — idempotent stages only, no
1207
- * container work (the cheap owner-field auth path). With `apiKey` or
1208
- * `sealedSecretEnv` (and optionally `sealedImage`): attaches the same
1209
- * owner-signed "create" envelope reset uses (the key sealed to the agent when the attestor
1210
- * supports it, see `secretEnv`), so the worker may continue past the
1211
- * idempotent stages into container creation. The attestor keeps no copy of
1212
- * the key outside that job, so — as with reset — continuing into a
1213
- * container needs it re-supplied.
1450
+ * Every retry carries the same owner-signed "create" envelope reset uses
1451
+ * (optionally with `sealedImage`); the attestor refuses a retry without
1452
+ * it. When the container failed or was stopped, the worker continues past
1453
+ * the idempotent stages into container creation with that envelope; the
1454
+ * container takes the model key from the credential set at its boot.
1455
+ * LEGACY(model-key): `apiKey` / `sealedSecretEnv` also ride the request.
1214
1456
  */
1215
1457
  async retry(params: {
1216
1458
  sealId: `0x${string}`;
@@ -1218,40 +1460,43 @@ export class AttestorClient {
1218
1460
  * (same as deploy) when `sealedImage` isn't given. */
1219
1461
  framework?: string;
1220
1462
  sealedImage?: string;
1463
+ /** LEGACY(model-key): the model key sent with the request; see
1464
+ * {@link lifecycle}'s `apiKey`. */
1221
1465
  apiKey?: string;
1222
1466
  provider?: string;
1223
- /** In place of `apiKey`: the key already sealed to this agent; see
1224
- * {@link lifecycle}'s `sealedSecretEnv`. */
1467
+ /** LEGACY(model-key): in place of `apiKey`, the key already sealed to
1468
+ * this agent; see {@link lifecycle}'s `sealedSecretEnv`. */
1225
1469
  sealedSecretEnv?: string;
1226
- /** How `apiKey` travels; see {@link SecretEnvMode}. Default `'auto'`. */
1470
+ /** LEGACY(model-key): how `apiKey` travels; see {@link SecretEnvMode}. Default `'auto'`. */
1227
1471
  secretEnv?: SecretEnvMode;
1472
+ /** As for {@link lifecycle}: the credential set holds the provider's
1473
+ * model key, so a provider other than 0g-compute needs no `apiKey`. */
1474
+ keyInCredentials?: boolean;
1475
+ /** As for {@link lifecycle}: run before the first write or signature. */
1476
+ beforeWrite?: () => Promise<void>;
1228
1477
  envelopeTtlSec?: number;
1229
1478
  }): Promise<void> {
1230
- if (params.provider && params.provider !== '0g-compute' && !params.apiKey && params.sealedSecretEnv === undefined) {
1479
+ const requestKey = carriesRequestKey(params);
1480
+ if (params.provider && params.provider !== '0g-compute' && !requestKey && !params.keyInCredentials) {
1231
1481
  throw new SecretEnvRefusedError('invalid_input', `retry for ${params.provider} requires its API key`);
1232
1482
  }
1233
1483
  const { account } = requireWallet(this.ctx);
1234
1484
  const body: Record<string, unknown> = { seal_id: params.sealId, owner: account.address };
1235
- if (params.apiKey || params.sealedSecretEnv !== undefined) {
1236
- const snapshot = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId);
1237
- body.sandbox_envelope = await this.signEnvelope(
1238
- 'create',
1239
- '',
1240
- {
1241
- snapshot,
1242
- sealed: true,
1243
- env: await this.sandboxEnv({
1244
- sealId: params.sealId,
1245
- provider: params.provider,
1246
- image: snapshot,
1247
- apiKey: params.apiKey,
1248
- sealedSecretEnv: params.sealedSecretEnv,
1249
- mode: params.secretEnv,
1250
- }),
1251
- },
1252
- params.envelopeTtlSec ?? 180,
1253
- );
1254
- }
1485
+ const snapshot = await this.resolveSealedImage(params.sealedImage, params.framework, params.sealId);
1486
+ // LEGACY(model-key): the request copy; a key in the set reaches the
1487
+ // container through /provision.
1488
+ const env = requestKey
1489
+ ? await this.sandboxEnv({
1490
+ sealId: params.sealId,
1491
+ provider: params.provider,
1492
+ image: snapshot,
1493
+ apiKey: params.apiKey,
1494
+ sealedSecretEnv: params.sealedSecretEnv,
1495
+ mode: params.secretEnv,
1496
+ })
1497
+ : undefined;
1498
+ await params.beforeWrite?.();
1499
+ body.sandbox_envelope = await this.signEnvelope('create', '', { snapshot, sealed: true, ...(env ? { env } : {}) }, params.envelopeTtlSec ?? 180);
1255
1500
  const res = await fetch(`${this.baseUrl()}/retry`, {
1256
1501
  method: 'POST',
1257
1502
  headers: { 'content-type': 'application/json' },
@@ -1259,7 +1504,7 @@ export class AttestorClient {
1259
1504
  });
1260
1505
  if (!res.ok) {
1261
1506
  const text = await res.text().catch(() => '');
1262
- throw new Error(`/retry failed: HTTP ${res.status} ${text}`);
1507
+ throw httpRefusal('/retry', res.status, text);
1263
1508
  }
1264
1509
  }
1265
1510
 
@@ -1273,8 +1518,7 @@ export class AttestorClient {
1273
1518
  // Fail before the first signature: a one-shot deploy signs its create
1274
1519
  // envelope before the agent exists, so it can never seal the key.
1275
1520
  assertSecretEnvMode(params.sandbox?.secretEnv);
1276
- const seed = params.iData?.find((entry) => entry.role === 'persona')?.plaintext as { inference?: { provider?: string } } | undefined;
1277
- const provider = seed?.inference?.provider ?? params.inference?.provider ?? '0g-compute';
1521
+ const provider = deployProvider(params);
1278
1522
  await this.providerDefinition(provider);
1279
1523
  if (params.sandbox && provider !== '0g-compute') throw new SecretEnvRefusedError('sealed_needs_agent', SEALED_NEEDS_AGENT);
1280
1524
  if (params.sandbox?.apiKey && params.sandbox.secretEnv === 'sealed') {
@@ -1306,6 +1550,7 @@ export class AttestorClient {
1306
1550
 
1307
1551
  // Owner canonical — must match CanonicalDeploy (order is irrelevant; the
1308
1552
  // attestor deserializes then re-checks each field).
1553
+ const awaitCredentials = !!(params.awaitCredentials && params.sandbox);
1309
1554
  const canonical = JSON.stringify({
1310
1555
  domain: DEPLOY_DOMAIN,
1311
1556
  idempotency_key: idempotencyKey,
@@ -1314,6 +1559,7 @@ export class AttestorClient {
1314
1559
  description: params.description,
1315
1560
  image: params.image ?? null,
1316
1561
  i_data: iData,
1562
+ ...(awaitCredentials ? { await_credentials: true } : {}),
1317
1563
  });
1318
1564
  const ownerSig = await walletClient.signMessage({ account, message: canonical });
1319
1565
  // Provision only when a sandbox is given; omit it → mint-only deploy
@@ -1332,6 +1578,7 @@ export class AttestorClient {
1332
1578
  image: params.image ?? null,
1333
1579
  i_data: iData,
1334
1580
  ...(sandbox_envelope ? { sandbox_envelope } : {}),
1581
+ ...(awaitCredentials ? { await_credentials: true } : {}),
1335
1582
  });
1336
1583
  }
1337
1584
 
@@ -1453,7 +1700,7 @@ export class AttestorClient {
1453
1700
  }
1454
1701
  if (res.ok) return (await res.json()) as DeployCloneResponse;
1455
1702
  const text = await res.text().catch(() => '');
1456
- const err = new Error(`${path} failed: HTTP ${res.status} ${text}`);
1703
+ const err = httpRefusal(path, res.status, text);
1457
1704
  if (res.status < 500) throw err; // 4xx — client/business error, retry won't help
1458
1705
  lastErr = err; // 5xx — server transient, retry
1459
1706
  }