@0gfoundation/0g-agentdna 0.2.3 → 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 +90 -9
  167. package/dist/cli/settings.d.ts.map +1 -1
  168. package/dist/cli/settings.js +273 -21
  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 +275 -25
  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
@@ -0,0 +1,1027 @@
1
+ /**
2
+ * Owner credentials for an agent's sealed credential proxy.
3
+ *
4
+ * The owner keeps third-party keys (API keys, tokens, refresh tokens) in the
5
+ * agent's sealed runtime, never in the framework the model drives. The agent
6
+ * writes a placeholder such as `[[credential:github]]` where a key belongs;
7
+ * sealed fills it in on the way out, only for the hosts and request positions
8
+ * the owner allowed, and redacts the value from responses.
9
+ *
10
+ * What this module signs and sends:
11
+ *
12
+ * - each value is sealed (ECIES) to the agent's agentSeal key in this client,
13
+ * bound to the owner, the seal, the chain and the entry name;
14
+ * - each entry's definition (hosts, positions, use, token request template,
15
+ * whether it may be revealed) is serialized once, and its keccak goes into
16
+ * an EIP-712 `CredentialSet` the owner signs once for all entries;
17
+ * - the set is stored at the attestor (which hands it to every boot) and
18
+ * pushed to the running container (which applies it at once).
19
+ *
20
+ * The attestor never sees a value. The container checks everything again,
21
+ * including that the signer is the agent's current on-chain owner.
22
+ */
23
+ import { plainText } from './AgentClient';
24
+ import { getAddress, hashTypedData, hexToBytes, isAddress, keccak256, recoverAddress, toBytes, type Address, type Hash, type Hex } from 'viem';
25
+ import type { Ctx } from './context';
26
+ import { requireWallet } from './context';
27
+ import { eciesEncrypt, publicKeyToAddress } from './secretEnv';
28
+ import { sha256Hex } from './Settings';
29
+ import type { AttestorClient } from './AttestorClient';
30
+ import { requestSecretEnv } from './legacy/modelKey';
31
+
32
+ /** EIP-712 domain name and version shared with sealed and the attestor. */
33
+ export const CREDENTIALS_DOMAIN_NAME = 'AgentDNA Credentials';
34
+ export const CREDENTIALS_DOMAIN_VERSION = '1';
35
+
36
+ export const credentialSetTypes = {
37
+ CredentialSet: [
38
+ { name: 'sealId', type: 'bytes32' },
39
+ { name: 'ownerEpoch', type: 'uint64' },
40
+ { name: 'version', type: 'uint64' },
41
+ { name: 'entries', type: 'Entry[]' },
42
+ ],
43
+ Entry: [
44
+ { name: 'name', type: 'string' },
45
+ { name: 'defHash', type: 'bytes32' },
46
+ ],
47
+ } as const;
48
+
49
+ export const approvalTypes = {
50
+ Approval: [
51
+ { name: 'sealId', type: 'bytes32' },
52
+ { name: 'bootId', type: 'bytes32' },
53
+ { name: 'authReqId', type: 'bytes32' },
54
+ { name: 'requestDigest', type: 'bytes32' },
55
+ { name: 'expiresAt', type: 'uint64' },
56
+ ],
57
+ } as const;
58
+
59
+ /** Where a placeholder may stand in a request. */
60
+ export type CredentialPosition =
61
+ | { kind: 'header'; name: string; template: string }
62
+ | { kind: 'basic'; username: string }
63
+ | { kind: 'query'; param: string }
64
+ | { kind: 'path' }
65
+ | { kind: 'body'; field: string };
66
+
67
+ /** Template sealed follows to call a token endpoint (RFC 6749 §3.2). */
68
+ export interface TokenRequestTemplate {
69
+ url: string;
70
+ encoding?: 'form' | 'json';
71
+ /** Field → template: `{v}` is this entry's value, `{cred:<name>}` another entry's. */
72
+ fields: Record<string, string>;
73
+ basic_auth?: { username_entry: string; password_entry: string };
74
+ /** Parameters the agent may add (e.g. `scope`). */
75
+ params?: string[];
76
+ /** Response fields kept as derived entries the agent uses by placeholder. */
77
+ take: Array<{ field: string; name?: string; hosts: string[]; positions: CredentialPosition[]; expires_in_field?: string }>;
78
+ /** e.g. `refresh_token`: a new value in the response replaces this entry. */
79
+ rotate_field?: string;
80
+ }
81
+
82
+ /**
83
+ * How a signing entry (`use: 'sign'`) uses its key, which is never written
84
+ * into a request: sealed signs AWS requests (sigv4) or HMAC-signed ones on
85
+ * their way out, mints a JWT where the entry's placeholder stands, or signs
86
+ * with a wallet through the agent's credential socket.
87
+ */
88
+ export type CredentialSigner =
89
+ | { method: 'sigv4'; access_key_id: string; region: string; service: string; session_token_entry?: string }
90
+ | {
91
+ method: 'hmac';
92
+ /** Template over {method} {path} {query} {body} {timestamp} {header:<name>}. */
93
+ message: string;
94
+ header?: string;
95
+ param?: string;
96
+ algorithm?: 'sha256' | 'sha512' | 'sha1';
97
+ encoding?: 'hex' | 'base64';
98
+ prefix?: string;
99
+ timestamp_header?: string;
100
+ }
101
+ | { method: 'jwt'; alg: 'RS256' | 'ES256' | 'HS256'; kid?: string; claims?: Record<string, unknown>; ttl?: number }
102
+ | { method: 'wallet' };
103
+
104
+ /**
105
+ * A login entry: the owner logs the agent in to the MCP server at `url`
106
+ * (OAuth with PKCE, run by sealed); sealed keeps and refreshes the tokens.
107
+ */
108
+ export interface CredentialMCP {
109
+ url: string;
110
+ /** For a server that does not register clients itself. */
111
+ client_id?: string;
112
+ /** The entry holding that client's secret. */
113
+ client_secret_entry?: string;
114
+ scopes?: string[];
115
+ }
116
+
117
+ /**
118
+ * Makes an entry the agent's model (inference) key for one provider of the
119
+ * platform's provider registry: sealed hands it to the framework for that
120
+ * provider's model calls and nothing else. Without `route_hash` the image's
121
+ * built-in route; with it, the provider's route in that accepted registry
122
+ * version (see {@link CredentialsApi.setModelKey}).
123
+ */
124
+ export interface CredentialInference {
125
+ provider: string;
126
+ route_hash?: string;
127
+ registry?: { version: number; digest?: string };
128
+ }
129
+
130
+ /** One credential as the owner sets it. */
131
+ export interface CredentialInput {
132
+ name: string;
133
+ /** The secret. Omit to keep the value already stored for this name. */
134
+ value?: string;
135
+ hosts: string[];
136
+ positions: CredentialPosition[];
137
+ /** `inject` (default), `token_only` (only feeds a token request), `sign`; `model` for a model key. */
138
+ use?: 'inject' | 'token_only' | 'sign' | 'model';
139
+ /** Required with `use: 'sign'`. */
140
+ signer?: CredentialSigner;
141
+ /** A login entry; it takes no value (see {@link CredentialsApi.login}). */
142
+ mcp?: CredentialMCP;
143
+ description?: string;
144
+ /** Unix seconds. */
145
+ expiresAt?: number;
146
+ /** Let the agent have the value itself without asking each time. */
147
+ allowReveal?: boolean;
148
+ /** Let sealed store a rotated refresh token back for the next boot. */
149
+ writeback?: boolean;
150
+ tokenRequest?: TokenRequestTemplate;
151
+ /** A model key: no hosts, positions or other options (see {@link CredentialInference}). */
152
+ inference?: CredentialInference;
153
+ }
154
+
155
+ /** A stored credential, as the owner reads it back (never the value). */
156
+ export interface CredentialDefinition {
157
+ v: 1;
158
+ name: string;
159
+ hosts: string[];
160
+ positions: CredentialPosition[];
161
+ /** `model` marks a model key: an image from before model keys skips the entry. */
162
+ use: 'inject' | 'token_only' | 'sign' | 'model';
163
+ value_hash: string;
164
+ description?: string;
165
+ expires_at?: number;
166
+ allow_reveal?: boolean;
167
+ writeback?: boolean;
168
+ token_request?: TokenRequestTemplate;
169
+ signer?: CredentialSigner;
170
+ mcp?: CredentialMCP;
171
+ inference?: CredentialInference;
172
+ }
173
+
174
+ /** Model key entries are named `model.<provider>`. */
175
+ export const MODEL_KEY_PREFIX = 'model.';
176
+
177
+ export function modelKeyName(provider: string): string {
178
+ return `${MODEL_KEY_PREFIX}${provider}`;
179
+ }
180
+
181
+ /**
182
+ * A model key sealed to one agent for its owner by whoever holds the key
183
+ * (an integrator's server, {@link CredentialsApi.sealModelKey}). The owner
184
+ * stores it as it is ({@link CredentialsApi.setModelKey}) and never sees the
185
+ * key.
186
+ */
187
+ export interface SealedModelKey {
188
+ v: 1;
189
+ sealId: Hash;
190
+ owner: Address;
191
+ provider: string;
192
+ /** The value as the credential set stores it: ECIES to the agent's agentSeal key, base64. */
193
+ value: string;
194
+ /** LEGACY(model-key): the same key as an older image reads it with the request (`SEAL_SECRET_ENV`); absent when the attestor does not seal request keys. */
195
+ secretEnv?: string;
196
+ }
197
+
198
+ /** Which model key the running agent's framework uses (`GET /_seal/credentials`). */
199
+ export interface ModelKeyInUse {
200
+ provider?: string;
201
+ /** `credentials`: an entry of the set; `deploy` (LEGACY(model-key)): the key given with the create/reset request. */
202
+ source: 'credentials' | 'deploy' | 'none';
203
+ /** The entry's value hash, when `source` is `credentials`. */
204
+ value_hash?: string;
205
+ /** Why the key the settings choose is not the one in use. */
206
+ issue?: string;
207
+ /** LEGACY(model-key): the provider of the key given with the create/reset request, when it is usable: a switch to it needs no key in the set. */
208
+ deploy_provider?: string;
209
+ }
210
+
211
+ /** {@link CredentialsApi.modelKeys}. */
212
+ export interface ModelKeysView {
213
+ /** The providers the credential set holds a key for. */
214
+ stored: Array<{ provider: string; valueHash: string }>;
215
+ /** The key the running agent uses; null: not running; `unsupported`: an image from before model keys in the set. */
216
+ inUse: ModelKeyInUse | null | 'unsupported';
217
+ }
218
+
219
+ /**
220
+ * What the running agent has loaded: the entries the agent may use (names and
221
+ * where they may go, never values) and, from an image that takes model keys
222
+ * from the set, which model key is in use (absent from an older image).
223
+ */
224
+ export interface LoadedCredentials {
225
+ version: number;
226
+ entries: Array<{ name: string; source: string; use: string; hosts: string[]; expires_at?: number; logged_in_at?: number; status?: string }>;
227
+ model?: ModelKeyInUse;
228
+ }
229
+
230
+ /** The signed document, as sealed and the attestor read it. */
231
+ export interface CredentialDocument {
232
+ set: { seal_id: string; owner_epoch: number; version: number; entries: Array<{ name: string; def_hash: string }> };
233
+ signature: string;
234
+ defs: Record<string, string>;
235
+ values: Record<string, string>;
236
+ writebacks?: Record<string, unknown>;
237
+ }
238
+
239
+ /** A request waiting for the owner (sealed's /_seal/credentials/pending). */
240
+ export interface PendingCredentialRequest {
241
+ auth_req_id: string;
242
+ op: 'reveal' | 'add' | 'login';
243
+ name: string;
244
+ params?: Record<string, string>;
245
+ /** What sealed knows (source, hosts, expiry). */
246
+ facts: Record<string, unknown>;
247
+ /** What the agent said; shown apart from the facts. */
248
+ reason?: string;
249
+ request_digest: string;
250
+ boot_id: string;
251
+ created_at: number;
252
+ expires_at: number;
253
+ status: 'pending' | 'approved' | 'denied';
254
+ }
255
+
256
+ /** The largest value sealed holds (credproxy.MaxValueLen). */
257
+ export const MAX_VALUE_BYTES = 16 * 1024;
258
+
259
+ /**
260
+ * Thrown when the stored set is not one this wallet signed: the attestor, or
261
+ * the connection to it, returned something else. Nothing is signed on top
262
+ * of it.
263
+ */
264
+ export class CredentialsUnverifiedError extends Error {
265
+ constructor(readonly why: string) {
266
+ super(`the stored credential set cannot be used (${why}); nothing was signed`);
267
+ this.name = 'CredentialsUnverifiedError';
268
+ }
269
+ }
270
+
271
+ /** Thrown when the stored set moved on since it was read. */
272
+ export class CredentialsConflictError extends Error {
273
+ constructor(readonly currentVersion: number, readonly ownerEpoch: number) {
274
+ super(`credentials have moved on: the current version is ${currentVersion}; re-read and retry`);
275
+ this.name = 'CredentialsConflictError';
276
+ }
277
+ }
278
+
279
+ // Base64 without Node's Buffer, so the module runs in browsers too.
280
+ function b64(bytes: Uint8Array): string {
281
+ let bin = '';
282
+ for (const c of bytes) bin += String.fromCharCode(c);
283
+ return btoa(bin);
284
+ }
285
+ function fromB64(s: string): Uint8Array {
286
+ const bin = atob(s);
287
+ const out = new Uint8Array(bin.length);
288
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
289
+ return out;
290
+ }
291
+
292
+ /** The plaintext a value's ciphertext holds (sealed/internal/credentials). */
293
+ export function credentialPlaintext(p: { owner: Address; sealId: Hash; chainId: number; name: string; value: string }): string {
294
+ return JSON.stringify({ v: 1, type: 'credential', owner: getAddress(p.owner), seal_id: p.sealId.toLowerCase(), chain_id: p.chainId, name: p.name, value: p.value });
295
+ }
296
+
297
+ /**
298
+ * Build a definition from an input and the ciphertext hash of its value.
299
+ * The bytes depend only on the definition, never on how the input was built
300
+ * (keys in one fixed order), so an entry stored again unchanged keeps its
301
+ * hash, and with it what sealed wrote back for it.
302
+ */
303
+ export function definitionOf(c: CredentialInput, valueHash: Hash): CredentialDefinition {
304
+ const d: CredentialDefinition = { v: 1, name: c.name, hosts: c.hosts, positions: c.positions, use: c.use ?? 'inject', value_hash: valueHash };
305
+ if (c.description) d.description = c.description;
306
+ if (c.expiresAt) d.expires_at = c.expiresAt;
307
+ if (c.allowReveal) d.allow_reveal = true;
308
+ // A login lives in writebacks.
309
+ if (c.writeback || c.mcp) d.writeback = true;
310
+ if (c.tokenRequest) d.token_request = c.tokenRequest;
311
+ if (c.signer) d.signer = c.signer;
312
+ if (c.mcp) d.mcp = c.mcp;
313
+ if (c.inference) d.inference = c.inference;
314
+ return d;
315
+ }
316
+
317
+ /** A stored definition as an input that keeps its stored value. */
318
+ export function inputOf(d: CredentialDefinition): CredentialInput {
319
+ return {
320
+ name: d.name, hosts: d.hosts, positions: d.positions, use: d.use, description: d.description,
321
+ expiresAt: d.expires_at, allowReveal: d.allow_reveal, writeback: d.writeback, tokenRequest: d.token_request,
322
+ signer: d.signer, mcp: d.mcp, inference: d.inference,
323
+ };
324
+ }
325
+
326
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
327
+ const PROVIDER_RE = /^[a-z0-9][a-z0-9-]*$/;
328
+
329
+ /** An entry to store: its value, or one sealed elsewhere (base64 ciphertext). */
330
+ type EntryInput = CredentialInput & { sealedValue?: string };
331
+
332
+ /** `model.<provider>`, for a provider id. */
333
+ function modelKeyNameOf(provider: string): string {
334
+ const name = modelKeyName(provider);
335
+ if (!PROVIDER_RE.test(provider) || !NAME_RE.test(name)) throw new Error(`credentials: not a provider id: ${JSON.stringify(provider)}`);
336
+ return name;
337
+ }
338
+
339
+ /** A model key: one line of printable characters (sealed sends it in a header or writes it into the framework's config). */
340
+ function checkModelKey(value: string): string {
341
+ if (!value || /[\u0000-\u001f\u007f]/.test(value)) throw new Error('credentials: a model key is one line of printable characters');
342
+ if (toBytes(value).length > MAX_VALUE_BYTES) throw new Error(`credentials: a model key is at most ${MAX_VALUE_BYTES} bytes`);
343
+ return value;
344
+ }
345
+
346
+ /**
347
+ * The checks {@link CredentialsApi.setModelKey} makes of a key and its
348
+ * provider before it reads or sends anything: a caller that stores a key
349
+ * after a request (`AgentApi.deploy`) runs them before the request. Throws.
350
+ */
351
+ export function checkModelKeyInput(provider: string, value: string): void {
352
+ modelKeyNameOf(provider);
353
+ checkModelKey(value);
354
+ }
355
+
356
+ /** A sealed model key for this agent, provider and signer; its ciphertext. */
357
+ function checkSealedModelKey(k: SealedModelKey, seal: Hash, provider: string, signer: Address): string {
358
+ if (k?.v !== 1 || typeof k.value !== 'string') throw new Error('credentials: not a sealed model key (sealModelKey)');
359
+ if (typeof k.sealId !== 'string' || k.sealId.toLowerCase() !== seal) throw new Error(`credentials: the sealed model key is for agent ${k.sealId}, not ${seal}`);
360
+ if (k.provider !== provider) throw new Error(`credentials: the sealed model key is for ${k.provider}, not ${provider}`);
361
+ if (!isAddress(k.owner) || getAddress(k.owner) !== getAddress(signer)) {
362
+ throw new Error(`credentials: the model key is sealed for ${k.owner}, not ${getAddress(signer)}; the agent would refuse it`);
363
+ }
364
+ let bytes: Uint8Array;
365
+ try {
366
+ bytes = fromB64(k.value);
367
+ } catch {
368
+ throw new Error('credentials: the sealed model key is not base64');
369
+ }
370
+ // Ciphertext of a value sealed holds (MAX_VALUE_BYTES) and its binding.
371
+ if (bytes.length === 0 || bytes.length > MAX_VALUE_BYTES + 1024) throw new Error('credentials: the sealed model key has no value or is too long');
372
+ return k.value;
373
+ }
374
+
375
+ /**
376
+ * A stored set's place in order (ownership epoch, then version) and its
377
+ * EIP-712 digest: of two sets the owner signed at one place (one the
378
+ * attestor refused, say), only the one seen first is taken.
379
+ */
380
+ interface Mark {
381
+ epoch: number;
382
+ version: number;
383
+ digest?: string;
384
+ }
385
+ const older = (a: Mark, b: Mark): boolean => a.epoch < b.epoch || (a.epoch === b.epoch && a.version < b.version);
386
+ const same = (a: Mark, b: Mark): boolean => a.epoch === b.epoch && a.version === b.version;
387
+ /** m replaces o: it is later, or at o's place with a digest o lacks. */
388
+ const newer = (m: Mark, o: Mark): boolean => older(o, m) || (same(o, m) && !o.digest && !!m.digest);
389
+ const isMark = (m: unknown): m is Mark =>
390
+ !!m && typeof m === 'object' && Number.isSafeInteger((m as Mark).epoch) && Number.isSafeInteger((m as Mark).version)
391
+ && ((m as Mark).digest === undefined || typeof (m as Mark).digest === 'string');
392
+ /** A hook's answer, or undefined when it throws or rejects. */
393
+ async function safely<T>(f: () => T | Promise<T>): Promise<T | undefined> {
394
+ try {
395
+ return await f();
396
+ } catch {
397
+ return undefined;
398
+ }
399
+ }
400
+
401
+ export class CredentialsApi {
402
+ /** The newest set seen per agent (see markKey), within this client's life. */
403
+ private readonly marks = new Map<string, Mark>();
404
+ /** Per agent, the check against the newest set seen and its raise run one at a time. */
405
+ private readonly markTurns = new Map<string, Promise<unknown>>();
406
+
407
+ constructor(
408
+ private readonly ctx: Ctx,
409
+ private readonly attestor: AttestorClient,
410
+ ) {}
411
+
412
+ private markKey(seal: Hash): string {
413
+ return `${this.ctx.chain.id}:${this.ctx.addresses.agenticID.toLowerCase()}:${seal}`;
414
+ }
415
+
416
+ /** The newest set this client (or, through credentialMarks, this machine) has seen. */
417
+ private async markOf(seal: Hash): Promise<Mark | undefined> {
418
+ const key = this.markKey(seal);
419
+ const answer = await safely(() => this.ctx.credentialMarks?.seen(key));
420
+ const kept = isMark(answer) ? answer : undefined;
421
+ const mine = this.marks.get(key);
422
+ if (!mine) return kept;
423
+ return kept && newer(kept, mine) ? kept : mine;
424
+ }
425
+
426
+ private inTurn<T>(seal: Hash, f: () => Promise<T>): Promise<T> {
427
+ const key = this.markKey(seal);
428
+ const run = (this.markTurns.get(key) ?? Promise.resolve()).then(f);
429
+ this.markTurns.set(key, run.catch(() => undefined));
430
+ return run;
431
+ }
432
+
433
+ private async raiseMark(seal: Hash, m: Mark): Promise<void> {
434
+ const key = this.markKey(seal);
435
+ const cur = await this.markOf(seal);
436
+ // Read again after the wait: another raise may have run meanwhile.
437
+ const mine = this.marks.get(key);
438
+ if ((cur && !newer(m, cur)) || (mine && !newer(m, mine))) return;
439
+ this.marks.set(key, m);
440
+ await safely(() => this.ctx.credentialMarks?.record(key, m));
441
+ }
442
+
443
+ /** Why a stored set at `at` is not taken, given the newest seen, or undefined. */
444
+ private staleness(at: Mark, seen: Mark | undefined): string | undefined {
445
+ if (!seen) return undefined;
446
+ let why: string | undefined;
447
+ if (older(at, seen)) why = `it is older than the newest set this client has seen, version ${seen.version} of ownership ${seen.epoch}`;
448
+ else if (same(at, seen) && seen.digest && at.digest && at.digest.toLowerCase() !== seen.digest.toLowerCase()) why = `it is not the version ${seen.version} this client has seen`;
449
+ if (!why) return undefined;
450
+ const marks = this.ctx.credentialMarks;
451
+ const clear = marks?.where
452
+ ? `remove this agent's record from ${marks.where}`
453
+ : marks
454
+ ? "remove this agent's record from the client's credentialMarks store"
455
+ : 'start a new client';
456
+ return `${why}. If the attestor's data was reset on purpose, ${clear} and read again`;
457
+ }
458
+
459
+ /** The EIP-712 digest of a set, as the owner signs it. */
460
+ private setDigest(seal: Hash, set: CredentialDocument['set']): Hash {
461
+ return hashTypedData({
462
+ domain: this.domain(),
463
+ types: credentialSetTypes,
464
+ primaryType: 'CredentialSet',
465
+ message: { sealId: seal, ownerEpoch: BigInt(set.owner_epoch), version: BigInt(set.version), entries: set.entries.map((x) => ({ name: x.name, defHash: x.def_hash as Hash })) },
466
+ });
467
+ }
468
+
469
+ private attestorUrl(): string {
470
+ if (!this.ctx.attestorUrl) throw new Error('credentials: attestorUrl is required');
471
+ return this.ctx.attestorUrl.replace(/\/$/, '');
472
+ }
473
+
474
+ private domain() {
475
+ return {
476
+ name: CREDENTIALS_DOMAIN_NAME,
477
+ version: CREDENTIALS_DOMAIN_VERSION,
478
+ chainId: this.ctx.chain.id,
479
+ verifyingContract: this.ctx.addresses.agenticID,
480
+ } as const;
481
+ }
482
+
483
+ private async ownerHeaders(message: string): Promise<Record<string, string>> {
484
+ const { walletClient, account } = requireWallet(this.ctx);
485
+ const signature = await walletClient.signMessage({ account, message });
486
+ return { 'X-Auth-Message': message, 'X-Auth-Signature': signature };
487
+ }
488
+
489
+ /**
490
+ * The agent's public URL, for the container routes: the deployment row's
491
+ * `url`, else its AgentCard's (without the `/hello` path), as the CLI
492
+ * resolves it. The public row carries only the AgentCard's.
493
+ */
494
+ async agentUrl(sealId: Hash): Promise<string> {
495
+ const r = await fetch(`${this.attestorUrl()}/deployment/${sealId}`, { signal: AbortSignal.timeout(10_000) });
496
+ if (!r.ok) throw new Error(`credentials: cannot read /deployment/${sealId}: HTTP ${r.status}`);
497
+ const row = (await r.json()) as { url?: string; agent_card?: { url?: string } };
498
+ const url = row.url ?? row.agent_card?.url?.replace(/\/hello$/, '');
499
+ if (!url) throw new Error('credentials: the agent has no public URL yet (not running?)');
500
+ return url.replace(/\/$/, '');
501
+ }
502
+
503
+ /**
504
+ * Owner-signed read of the stored set (no values). The set is checked to be
505
+ * one this wallet signed, down to each definition and stored value, and no
506
+ * older than the newest this client has seen, since every change signs the
507
+ * other entries again from it; one that is not throws
508
+ * {@link CredentialsUnverifiedError}.
509
+ */
510
+ async get(sealId: Hash): Promise<{ version: number; ownerEpoch: number; document: CredentialDocument | null; definitions: CredentialDefinition[] }> {
511
+ const seal = sealId.toLowerCase() as Hash;
512
+ const message = `AgenticID.Credentials.v1:${seal}:${Math.floor(Date.now() / 1000)}:0`;
513
+ const r = await fetch(`${this.attestorUrl()}/credentials?seal_id=${seal}`, { headers: await this.ownerHeaders(message), signal: AbortSignal.timeout(10_000) });
514
+ if (!r.ok) throw new Error(`credentials.get: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
515
+ const body = (await r.json()) as { version: number; owner_epoch: number; document: CredentialDocument | null };
516
+ // A number this client cannot hold exactly could not be kept as the
517
+ // newest seen either.
518
+ if (![body.version, body.owner_epoch].every((n) => Number.isSafeInteger(n) && n >= 0)) {
519
+ throw new CredentialsUnverifiedError('its version or ownership epoch is not a number this client can hold');
520
+ }
521
+ if (!body.document && body.version !== 0) throw new CredentialsUnverifiedError(`version ${body.version} comes with no signed set`);
522
+ const v = body.document ? await this.verified(seal, body.version, body.owner_epoch, body.document) : { definitions: [], digest: undefined };
523
+ const definitions = v.definitions;
524
+ // An older set the owner did sign, or another at the same version,
525
+ // served again, would bring back what the owner changed or removed since.
526
+ const at: Mark = { epoch: body.owner_epoch, version: body.version, digest: v.digest };
527
+ // Checked and raised in one turn: two reads in flight take one set at a version.
528
+ await this.inTurn(seal, async () => {
529
+ const stale = this.staleness(at, await this.markOf(seal));
530
+ if (stale) throw new CredentialsUnverifiedError(stale);
531
+ if (body.document) await this.raiseMark(seal, at);
532
+ });
533
+ return { version: body.version, ownerEpoch: body.owner_epoch, document: body.document, definitions };
534
+ }
535
+
536
+ /** The definitions of a stored document this wallet signed for this agent, or throws. */
537
+ private async verified(seal: Hash, version: number, ownerEpoch: number, doc: CredentialDocument): Promise<{ definitions: CredentialDefinition[]; digest: Hash }> {
538
+ const fail = (why: string): never => {
539
+ throw new CredentialsUnverifiedError(why);
540
+ };
541
+ const set = doc.set;
542
+ if (!set || !Array.isArray(set.entries)) fail('no signed set');
543
+ if (String(set.seal_id).toLowerCase() !== seal) fail('it is for another agent');
544
+ if (set.version !== version || set.owner_epoch !== ownerEpoch) fail(`it is signed as version ${set.version}, stored as ${version}`);
545
+ let digest: Hash | undefined;
546
+ let signer: Address | undefined;
547
+ try {
548
+ digest = this.setDigest(seal, set);
549
+ signer = await recoverAddress({ hash: digest, signature: doc.signature as Hex });
550
+ } catch {
551
+ signer = undefined;
552
+ }
553
+ const { account } = requireWallet(this.ctx);
554
+ if (!signer || getAddress(signer) !== getAddress(account.address)) fail('its signature is not this wallet\'s');
555
+ const names = new Set<string>();
556
+ const definitions = set.entries.map((e) => {
557
+ if (names.has(e.name)) fail(`${e.name} is listed twice`);
558
+ names.add(e.name);
559
+ const raw = doc.defs?.[e.name];
560
+ if (typeof raw !== 'string') fail(`${e.name} has no definition`);
561
+ const bytes = fromB64(raw);
562
+ if (keccak256(bytes) !== e.def_hash) fail(`${e.name}'s definition is not the signed one`);
563
+ const def = JSON.parse(new TextDecoder().decode(bytes)) as CredentialDefinition;
564
+ if (def.name !== e.name) fail(`${e.name}'s definition names ${def.name}`);
565
+ // The stored value is the one the definition (so the signature) binds.
566
+ if (!def.mcp) {
567
+ const v = doc.values?.[e.name];
568
+ if (typeof v !== 'string' || keccak256(fromB64(v)) !== def.value_hash) fail(`${e.name}'s stored value is not the signed one`);
569
+ }
570
+ return def;
571
+ });
572
+ return { definitions, digest: digest! };
573
+ }
574
+
575
+ /**
576
+ * Replace the agent's whole credential set (compare-and-swap on the version
577
+ * {@link get} returned). Entries without `value` keep their stored value.
578
+ * Stores the set at the attestor, then pushes it to the running container;
579
+ * a push failure is returned as a warning (the next boot applies it).
580
+ */
581
+ async put(sealId: Hash, entries: CredentialInput[], opts: { baseVersion: number; agentUrl?: string }): Promise<{ version: number; pushWarning?: string }> {
582
+ const doc = await this.buildDocument(sealId, entries, opts.baseVersion);
583
+ const version = await this.store(sealId, doc, opts.baseVersion);
584
+ const pushWarning = await this.push(sealId, doc, opts.agentUrl).then(() => undefined, (e: unknown) => String(e instanceof Error ? e.message : e));
585
+ return { version, pushWarning };
586
+ }
587
+
588
+ /**
589
+ * Remove one entry. The attestor stores the new set, then the container
590
+ * gets it, so the entry stops working at once; pushWarning says why the
591
+ * running container did not take it (it then applies at the next boot).
592
+ * Revoke the key at its provider as well: removing it here does not.
593
+ */
594
+ async remove(sealId: Hash, name: string, opts?: { agentUrl?: string }): Promise<{ version: number; pushWarning?: string }> {
595
+ const current = await this.get(sealId);
596
+ const keep = current.definitions.filter((d) => d.name !== name).map((d) => inputOf(d));
597
+ const doc = await this.buildDocument(sealId, keep, current.version, current);
598
+ // Stored first, as put does: a container that took a version the
599
+ // attestor never stored would refuse the attestor's set at its next boot.
600
+ const version = await this.store(sealId, doc, current.version);
601
+ const pushWarning = await this.push(sealId, doc, opts?.agentUrl).then(() => undefined, (e: unknown) => String(e instanceof Error ? e.message : e));
602
+ return { version, pushWarning };
603
+ }
604
+
605
+ /** Turn advance permission to reveal one entry on or off. */
606
+ async setAllowReveal(sealId: Hash, name: string, allow: boolean, opts?: { agentUrl?: string }): Promise<{ version: number; pushWarning?: string }> {
607
+ const current = await this.get(sealId);
608
+ const def = current.definitions.find((d) => d.name === name);
609
+ if (!def) throw new Error(`credentials: no entry named ${name}`);
610
+ // A signing key signs and is never revealed (sealed refuses it). A value
611
+ // sealed obtained for the entry (a login, a rotated token) is bound to
612
+ // that value or login, not to this setting, so it is kept.
613
+ if (allow && def.inference) {
614
+ throw new Error(`credentials: ${name} is a model key: sealed hands it to the framework and never reveals it`);
615
+ }
616
+ if (allow && def.use === 'sign') {
617
+ throw new Error(`credentials: ${name} is a signing key: it signs and is never revealed`);
618
+ }
619
+ const next = current.definitions.map((d) => (d.name === name ? { ...inputOf(d), allowReveal: allow } : inputOf(d)));
620
+ return this.put(sealId, next, { baseVersion: current.version, agentUrl: opts?.agentUrl });
621
+ }
622
+
623
+ /**
624
+ * Set the agent's model key for one provider (the entry `model.<provider>`),
625
+ * then push it to the running agent. The agent's settings choose which
626
+ * provider it uses: a key for that provider takes effect at once (sealed
627
+ * swaps it in, or restarts the framework with it); one for another provider
628
+ * is kept until the settings switch to it. The key is bound to the provider's
629
+ * route in the registry version the attestor serves now, checked against
630
+ * this agent's image first.
631
+ *
632
+ * `value` is the key, or the key sealed for this owner elsewhere
633
+ * ({@link sealModelKey}), stored as it is: the owner signs its ciphertext's
634
+ * hash and never has the key.
635
+ *
636
+ * The owner signs the read of the stored set, the new set and the write:
637
+ * three signatures, and a fourth for the push. `newAgent`: the agent was
638
+ * created a moment ago by this wallet (`AgentApi.deploy`) and has no set
639
+ * yet, so the read is skipped (two signatures); should one be stored by
640
+ * then, the write is refused as a conflict and made again after a read.
641
+ * `sealedTo`: the agentSeal address a key given in clear was sealed to.
642
+ */
643
+ async setModelKey(
644
+ sealId: Hash,
645
+ provider: string,
646
+ value: string | SealedModelKey,
647
+ opts?: { agentUrl?: string; push?: boolean; newAgent?: boolean },
648
+ ): Promise<{ version: number; valueHash: Hash; pushWarning?: string; sealedTo?: Address }> {
649
+ const seal = sealId.toLowerCase() as Hash;
650
+ const name = modelKeyNameOf(provider);
651
+ const given = typeof value === 'string'
652
+ ? { value: checkModelKey(value) }
653
+ : { sealedValue: checkSealedModelKey(value, seal, provider, requireWallet(this.ctx).account.address) };
654
+ const binding = await this.attestor.modelKeyBinding(provider, seal);
655
+ const entry: EntryInput = { name, ...given, hosts: [], positions: [], use: 'model', inference: { provider, ...binding } };
656
+ // A key given in clear is sealed here, to the key the attestor names
657
+ // (checked against the chain once the agent is minted).
658
+ const sealing = given.value !== undefined ? await this.sealingKey(seal) : undefined;
659
+ const write = async (cur: Awaited<ReturnType<CredentialsApi['get']>>) => {
660
+ const others = cur.definitions.filter((d) => d.name !== name).map(inputOf);
661
+ const doc = await this.buildDocument(seal, [...others, entry], cur.version, cur, sealing);
662
+ return { doc, version: await this.store(seal, doc, cur.version) };
663
+ };
664
+ let written: Awaited<ReturnType<typeof write>>;
665
+ if (opts?.newAgent) {
666
+ try {
667
+ written = await write({ version: 0, ownerEpoch: 0, document: null, definitions: [] });
668
+ } catch (e) {
669
+ if (!(e instanceof CredentialsConflictError)) throw e;
670
+ written = await write(await this.get(seal));
671
+ }
672
+ } else {
673
+ written = await write(await this.get(seal));
674
+ }
675
+ const { doc, version } = written;
676
+ // `push: false`: a container about to be recreated takes it at its boot.
677
+ const pushWarning = opts?.push === false ? undefined
678
+ : await this.push(seal, doc, opts?.agentUrl).then(() => undefined, (e: unknown) => String(e instanceof Error ? e.message : e));
679
+ return { version, valueHash: keccak256(fromB64(doc.values[name])), pushWarning, ...(sealing ? { sealedTo: sealing.address } : {}) };
680
+ }
681
+
682
+ /**
683
+ * Seal a model key to one agent for its owner, signing nothing: for the
684
+ * integrator whose server holds the key while the owner signs in a browser
685
+ * (issue #166). The server calls this (a read-only client is enough: no
686
+ * wallet) and hands the owner only the result, which the owner stores with
687
+ * {@link setModelKey} or passes to `start` / `reset` / `retry` as
688
+ * `sealedModelKey`. The key never reaches the owner.
689
+ *
690
+ * The value is bound, as every value in the set, to `owner`, the agent, the
691
+ * chain and the entry `model.<provider>`; once the agent is minted, `owner`
692
+ * must be its on-chain owner (a {@link SecretEnvRefusedError} otherwise).
693
+ * LEGACY(model-key): `framework` / `sealedImage` matter only for the
694
+ * request copy older images read (`secretEnv`), and go with it.
695
+ */
696
+ async sealModelKey(
697
+ sealId: Hash,
698
+ opts: { owner: Address; apiKey: string; provider?: string; framework?: string; sealedImage?: string },
699
+ ): Promise<SealedModelKey> {
700
+ const seal = sealId.toLowerCase() as Hash;
701
+ const provider = opts.provider ?? '0g-compute';
702
+ const name = modelKeyNameOf(provider);
703
+ const apiKey = checkModelKey(opts.apiKey);
704
+ if (!isAddress(opts.owner)) throw new Error('credentials: sealModelKey: owner is not an address');
705
+ const owner = getAddress(opts.owner);
706
+ const pubkey = hexToBytes(await this.attestor.agentSealPubkeyFor(seal, owner, 'sealModelKey'));
707
+ const value = b64(eciesEncrypt(pubkey, toBytes(credentialPlaintext({ owner, sealId: seal, chainId: this.ctx.chain.id, name, value: apiKey }))));
708
+ const secretEnv = await requestSecretEnv(this.attestor, { sealId: seal, owner, apiKey, provider, framework: opts.framework, sealedImage: opts.sealedImage });
709
+ return { v: 1, sealId: seal, owner, provider, value, ...(secretEnv ? { secretEnv } : {}) };
710
+ }
711
+
712
+ /** Remove the agent's model key for one provider (see {@link setModelKey}). */
713
+ async removeModelKey(sealId: Hash, provider: string, opts?: { agentUrl?: string }): Promise<{ version: number; pushWarning?: string }> {
714
+ return this.remove(sealId, modelKeyName(provider), opts);
715
+ }
716
+
717
+ /**
718
+ * The agent's model keys: the providers its credential set holds a key for,
719
+ * and which key the running agent uses. `inUse` is null when the agent
720
+ * cannot be asked (not running), `unsupported` when its image predates
721
+ * model keys in the set.
722
+ */
723
+ async modelKeys(sealId: Hash, opts?: { agentUrl?: string }): Promise<ModelKeysView> {
724
+ const cur = await this.get(sealId);
725
+ const stored = cur.definitions.filter((d) => d.inference).map((d) => ({ provider: d.inference!.provider, valueHash: d.value_hash }));
726
+ const loaded = await this.loaded(sealId, opts).catch(() => undefined);
727
+ return { stored, inUse: !loaded ? null : loaded.model ?? 'unsupported' };
728
+ }
729
+
730
+ /**
731
+ * Whether the agent has a model key for `provider`: one in its credential
732
+ * set, or (asked of the running agent; LEGACY(model-key)) the key handed
733
+ * over with the create/reset request being for that provider.
734
+ */
735
+ async hasModelKey(sealId: Hash, provider: string, opts?: { agentUrl?: string }): Promise<boolean> {
736
+ const view = await this.modelKeys(sealId, opts);
737
+ return view.stored.some((k) => k.provider === provider)
738
+ // LEGACY(model-key): the request copy the running container got.
739
+ || (!!view.inUse && view.inUse !== 'unsupported' && view.inUse.deploy_provider === provider);
740
+ }
741
+
742
+ /**
743
+ * After a boot: when the credential set holds a key for the provider the
744
+ * running agent uses and the agent does not run on it (it booted before the
745
+ * key was stored, or did not get the set at its boot), push the set again.
746
+ */
747
+ async resyncModelKey(sealId: Hash, opts?: { agentUrl?: string }): Promise<'in_sync' | 'pushed' | 'not_running' | 'unsupported'> {
748
+ const view = await this.modelKeys(sealId, opts);
749
+ if (view.inUse === null) return 'not_running';
750
+ if (view.inUse === 'unsupported') return 'unsupported';
751
+ const provider = view.inUse.provider;
752
+ if (!provider || !view.stored.some((k) => k.provider === provider) || view.inUse.source === 'credentials') return 'in_sync';
753
+ const cur = await this.get(sealId);
754
+ if (!cur.document) return 'in_sync';
755
+ await this.push(sealId.toLowerCase() as Hash, cur.document, opts?.agentUrl);
756
+ return 'pushed';
757
+ }
758
+
759
+ /** The agent's agentSeal key values are sealed to, checked as
760
+ * `agentSealPubkey` checks it, with its address. */
761
+ private async sealingKey(seal: Hash): Promise<{ bytes: Uint8Array; address: Address }> {
762
+ const bytes = hexToBytes(await this.attestor.agentSealPubkey(seal));
763
+ return { bytes, address: publicKeyToAddress(bytes) };
764
+ }
765
+
766
+ private async buildDocument(
767
+ sealId: Hash,
768
+ entries: EntryInput[],
769
+ baseVersion: number,
770
+ current?: Awaited<ReturnType<CredentialsApi['get']>>,
771
+ sealing?: { bytes: Uint8Array; address: Address },
772
+ ): Promise<CredentialDocument> {
773
+ const { walletClient, account } = requireWallet(this.ctx);
774
+ const seal = sealId.toLowerCase() as Hash;
775
+ const cur = current ?? (await this.get(seal));
776
+ if (cur.version !== baseVersion) throw new CredentialsConflictError(cur.version, cur.ownerEpoch);
777
+ const names = new Set<string>();
778
+ const needsSealing = entries.some((e) => e.value !== undefined);
779
+ const pubkey = needsSealing ? (sealing ?? (await this.sealingKey(seal))).bytes : undefined;
780
+ const doc: CredentialDocument = {
781
+ set: { seal_id: seal, owner_epoch: cur.ownerEpoch, version: baseVersion + 1, entries: [] },
782
+ signature: '',
783
+ defs: {},
784
+ values: {},
785
+ };
786
+ for (const e of entries) {
787
+ if (!NAME_RE.test(e.name)) throw new Error(`credentials: invalid name ${JSON.stringify(e.name)}`);
788
+ if (names.has(e.name)) throw new Error(`credentials: ${e.name} listed twice`);
789
+ names.add(e.name);
790
+ if (e.mcp) {
791
+ // A login entry has no value of the owner's: sealed logs in and
792
+ // keeps the tokens.
793
+ if (e.value !== undefined) throw new Error(`credentials: ${e.name} is a login entry and takes no value`);
794
+ const defBytes = toBytes(JSON.stringify(definitionOf(e, '' as Hash)));
795
+ doc.defs[e.name] = b64(defBytes);
796
+ doc.set.entries.push({ name: e.name, def_hash: keccak256(defBytes) });
797
+ continue;
798
+ }
799
+ let ciphertext: Uint8Array;
800
+ // sealed holds values of up to 16 KiB; a longer one would be skipped.
801
+ if (e.value !== undefined && toBytes(e.value).length > MAX_VALUE_BYTES) {
802
+ throw new Error(`credentials: ${e.name}'s value is over ${MAX_VALUE_BYTES} bytes, the most sealed holds`);
803
+ }
804
+ if (e.value !== undefined) {
805
+ ciphertext = eciesEncrypt(pubkey!, toBytes(credentialPlaintext({ owner: account.address, sealId: seal, chainId: this.ctx.chain.id, name: e.name, value: e.value })));
806
+ } else if (e.sealedValue !== undefined) {
807
+ // Sealed elsewhere for this owner (sealModelKey): stored as it is.
808
+ ciphertext = fromB64(e.sealedValue);
809
+ } else {
810
+ const stored = cur.document?.values[e.name];
811
+ if (!stored) throw new Error(`credentials: ${e.name} has no stored value; pass value`);
812
+ ciphertext = fromB64(stored);
813
+ }
814
+ const defBytes = toBytes(JSON.stringify(definitionOf(e, keccak256(ciphertext))));
815
+ doc.defs[e.name] = b64(defBytes);
816
+ doc.values[e.name] = b64(ciphertext);
817
+ doc.set.entries.push({ name: e.name, def_hash: keccak256(defBytes) });
818
+ }
819
+ doc.signature = await walletClient.signTypedData({
820
+ account,
821
+ domain: this.domain(),
822
+ types: credentialSetTypes,
823
+ primaryType: 'CredentialSet',
824
+ message: {
825
+ sealId: seal,
826
+ ownerEpoch: BigInt(doc.set.owner_epoch),
827
+ version: BigInt(doc.set.version),
828
+ entries: doc.set.entries.map((x) => ({ name: x.name, defHash: x.def_hash as Hash })),
829
+ },
830
+ });
831
+ return doc;
832
+ }
833
+
834
+ private async store(sealId: Hash, doc: CredentialDocument, baseVersion: number): Promise<number> {
835
+ const seal = sealId.toLowerCase() as Hash;
836
+ const body = JSON.stringify({ seal_id: seal, base_version: baseVersion, document: doc });
837
+ const message = `AgenticID.Credentials.v1:${seal}:${Math.floor(Date.now() / 1000)}:${baseVersion}:${await sha256Hex(body)}`;
838
+ const r = await fetch(`${this.attestorUrl()}/credentials`, {
839
+ method: 'POST',
840
+ headers: { ...(await this.ownerHeaders(message)), 'content-type': 'application/json' },
841
+ body,
842
+ signal: AbortSignal.timeout(20_000),
843
+ });
844
+ if (r.status === 409) {
845
+ const j = (await r.json().catch(() => ({}))) as { details?: { version?: number; owner_epoch?: number } };
846
+ throw new CredentialsConflictError(j.details?.version ?? -1, j.details?.owner_epoch ?? -1);
847
+ }
848
+ if (!r.ok) throw new Error(`credentials: store failed: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
849
+ const version = ((await r.json()) as { version: number }).version;
850
+ await this.inTurn(seal, () => this.raiseMark(seal, { epoch: doc.set.owner_epoch, version: doc.set.version, digest: this.setDigest(seal, doc.set) }));
851
+ return version;
852
+ }
853
+
854
+ /** Owner-signed request to the running container (`/_seal/...`). */
855
+ private async sealRequest(sealId: Hash, base: string, tag: string, path: string, body?: string): Promise<Response> {
856
+ const audience = new URL(base).origin;
857
+ const ts = Math.floor(Date.now() / 1000);
858
+ // Digest before audience: the audience carries colons and must stay last.
859
+ const message = body !== undefined ? `${tag}:${sealId.toLowerCase()}:${ts}:${await sha256Hex(body)}:${audience}` : `${tag}:${sealId.toLowerCase()}:${ts}:${audience}`;
860
+ return fetch(`${base}${path}`, {
861
+ method: body !== undefined ? 'POST' : 'GET',
862
+ headers: { ...(await this.ownerHeaders(message)), ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
863
+ body,
864
+ signal: AbortSignal.timeout(20_000),
865
+ });
866
+ }
867
+
868
+ private async push(sealId: Hash, doc: CredentialDocument, agentUrl?: string): Promise<void> {
869
+ const base = agentUrl ?? (await this.agentUrl(sealId));
870
+ const r = await this.sealRequest(sealId, base, '0GSealCredentials', '/_seal/credentials', JSON.stringify(doc));
871
+ if (!r.ok) throw new Error(`push to the running agent failed: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
872
+ }
873
+
874
+ /**
875
+ * Connect a login entry's MCP server: start the owner's OAuth login and
876
+ * return the link the owner opens to consent (valid 10 minutes); the
877
+ * authorization server returns the browser to the agent, which completes
878
+ * the login itself and keeps the tokens.
879
+ */
880
+ async connect(sealId: Hash, name: string, opts?: { agentUrl?: string }): Promise<{ authorizeUrl: string }> {
881
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
882
+ const r = await this.sealRequest(sealId, base, '0GSealCredLogin', '/_seal/credentials/login', JSON.stringify({ name }));
883
+ if (!r.ok) throw new Error(`credentials.connect: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
884
+ return { authorizeUrl: ((await r.json()) as { authorize_url: string }).authorize_url };
885
+ }
886
+
887
+ /**
888
+ * Disconnect a login entry: the running agent asks the authorization
889
+ * server to revoke its tokens (RFC 7009) when the server offers that, and
890
+ * forgets them; then the entry is removed. `revoked` says whether the
891
+ * server confirmed; `note` says why not (no revocation endpoint, the agent
892
+ * not running, …), in which case revoke the app's access at the service.
893
+ */
894
+ async disconnect(sealId: Hash, name: string, opts?: { agentUrl?: string }): Promise<{ version: number; revoked: boolean; forgotten: boolean; changed?: boolean; note?: string; pushWarning?: string }> {
895
+ let revoked = false;
896
+ let changed = false; // the entry changed while the agent disconnected it
897
+ let forgotten = false; // the running agent took the disconnect and forgot the tokens
898
+ let note: string | undefined;
899
+ try {
900
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
901
+ const r = await this.sealRequest(sealId, base, '0GSealCredDisconnect', '/_seal/credentials/disconnect', JSON.stringify({ name }));
902
+ if (r.ok) {
903
+ const b = (await r.json()) as { revoked: boolean; note?: string };
904
+ revoked = b.revoked;
905
+ forgotten = true;
906
+ note = b.note || undefined;
907
+ } else if (r.status === 409) {
908
+ // A new set redefined or removed the entry, or the owner changed,
909
+ // while the agent disconnected it: it forgot nothing, and what the
910
+ // server revoked may not be all the entry held. The removal below
911
+ // makes the agent forget it.
912
+ const b = (await r.json().catch(() => ({}))) as { revoked?: boolean; note?: string };
913
+ changed = true;
914
+ note = b.revoked
915
+ ? "the entry changed while the agent disconnected it: the tokens it held when the disconnect began are revoked; to be sure no other is left, revoke the app's access at the service"
916
+ : `the entry changed while the agent disconnected it and nothing was revoked${b.note ? ` (${plainText(b.note)})` : ''}: revoke the app's access at the service`;
917
+ } else note = `the agent refused: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`.trim();
918
+ } catch (e) {
919
+ note = `the agent could not be reached (${e instanceof Error ? e.message : String(e)}): revoke the app's access at the service`;
920
+ }
921
+ const { version, pushWarning } = await this.remove(sealId, name, opts);
922
+ return { version, revoked, forgotten, ...(changed ? { changed } : {}), note, pushWarning };
923
+ }
924
+
925
+ /**
926
+ * The entries the running agent has loaded (names and where they may go,
927
+ * never values). A login entry is listed with `status: 'awaiting_login'`
928
+ * until its login is done, then with `logged_in_at`.
929
+ */
930
+ async loaded(sealId: Hash, opts?: { agentUrl?: string }): Promise<LoadedCredentials> {
931
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
932
+ const r = await this.sealRequest(sealId, base, '0GSealCredentials', '/_seal/credentials');
933
+ if (!r.ok) throw new Error(`credentials.loaded: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
934
+ return (await r.json()) as LoadedCredentials;
935
+ }
936
+
937
+ /** Requests waiting for the owner on this agent, with sealed's facts and the agent's reason. */
938
+ async pending(sealId: Hash, opts?: { agentUrl?: string }): Promise<PendingCredentialRequest[]> {
939
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
940
+ const r = await this.sealRequest(sealId, base, '0GSealCredPending', '/_seal/credentials/pending');
941
+ if (!r.ok) throw new Error(`credentials.pending: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
942
+ return (await r.json()) as PendingCredentialRequest[];
943
+ }
944
+
945
+ /** Pending counts across every agent the wallet owns (from the attestor). */
946
+ async pendingCounts(): Promise<Array<{ seal_id: string; agent_id: string | null; pending: number; updated_at: number }>> {
947
+ const { account } = requireWallet(this.ctx);
948
+ const message = `AgenticID.CredentialsPending.v1:${account.address.toLowerCase()}:${Math.floor(Date.now() / 1000)}`;
949
+ const r = await fetch(`${this.attestorUrl()}/credentials/pending`, { headers: await this.ownerHeaders(message), signal: AbortSignal.timeout(10_000) });
950
+ if (!r.ok) throw new Error(`credentials.pendingCounts: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
951
+ return (await r.json()) as Array<{ seal_id: string; agent_id: string | null; pending: number; updated_at: number }>;
952
+ }
953
+
954
+ /** Where the attestor emails this wallet about pending requests, and whether it sends any. */
955
+ async notifyAddress(): Promise<{ email: string | null; enabled: boolean }> {
956
+ const { account } = requireWallet(this.ctx);
957
+ const message = `AgenticID.CredentialsNotify.v1:${account.address.toLowerCase()}:${Math.floor(Date.now() / 1000)}`;
958
+ const r = await fetch(`${this.attestorUrl()}/credentials/notify`, { headers: await this.ownerHeaders(message), signal: AbortSignal.timeout(10_000) });
959
+ if (!r.ok) throw new Error(`credentials.notifyAddress: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
960
+ return (await r.json()) as { email: string | null; enabled: boolean };
961
+ }
962
+
963
+ /** Set (an address) or stop (null) email about pending requests on any agent this wallet owns. */
964
+ async setNotifyAddress(email: string | null): Promise<{ email: string | null; enabled: boolean }> {
965
+ const { account } = requireWallet(this.ctx);
966
+ const body = JSON.stringify({ email });
967
+ const message = `AgenticID.CredentialsNotify.v1:${account.address.toLowerCase()}:${Math.floor(Date.now() / 1000)}:${await sha256Hex(body)}`;
968
+ const r = await fetch(`${this.attestorUrl()}/credentials/notify`, {
969
+ method: 'POST',
970
+ headers: { ...(await this.ownerHeaders(message)), 'content-type': 'application/json' },
971
+ body,
972
+ signal: AbortSignal.timeout(10_000),
973
+ });
974
+ if (!r.ok) throw new Error(`credentials.setNotifyAddress: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
975
+ return (await r.json()) as { email: string | null; enabled: boolean };
976
+ }
977
+
978
+ /**
979
+ * Approve one pending request once: an EIP-712 Approval bound to this boot,
980
+ * this request id and its digest, valid for `ttlSeconds` (default 1 h, never
981
+ * past the request's own expiry). The agent sends the same request again
982
+ * and gets its answer; the approval is then spent.
983
+ */
984
+ async approveOnce(sealId: Hash, authReqId: string, opts?: { agentUrl?: string; ttlSeconds?: number }): Promise<void> {
985
+ const { walletClient, account } = requireWallet(this.ctx);
986
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
987
+ const item = (await this.pending(sealId, { agentUrl: base })).find((p) => p.auth_req_id.toLowerCase() === authReqId.toLowerCase());
988
+ if (!item) throw new Error(`credentials: no pending request ${authReqId}`);
989
+ const expiresAt = Math.min(Math.floor(Date.now() / 1000) + (opts?.ttlSeconds ?? 3600), item.expires_at);
990
+ const approval = { seal_id: sealId.toLowerCase(), boot_id: item.boot_id, auth_req_id: item.auth_req_id, request_digest: item.request_digest, expires_at: expiresAt };
991
+ const signature = await walletClient.signTypedData({
992
+ account,
993
+ domain: this.domain(),
994
+ types: approvalTypes,
995
+ primaryType: 'Approval',
996
+ message: {
997
+ sealId: approval.seal_id as Hash, bootId: approval.boot_id as Hash, authReqId: approval.auth_req_id as Hash,
998
+ requestDigest: approval.request_digest as Hash, expiresAt: BigInt(expiresAt),
999
+ },
1000
+ });
1001
+ await this.decide(sealId, base, { auth_req_id: item.auth_req_id, decision: 'once', approval, signature });
1002
+ }
1003
+
1004
+ /** Refuse one pending request. */
1005
+ async deny(sealId: Hash, authReqId: string, opts?: { agentUrl?: string }): Promise<void> {
1006
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
1007
+ await this.decide(sealId, base, { auth_req_id: authReqId, decision: 'deny' });
1008
+ }
1009
+
1010
+ private async decide(sealId: Hash, base: string, body: Record<string, unknown>): Promise<void> {
1011
+ const r = await this.sealRequest(sealId, base, '0GSealCredDecide', '/_seal/credentials/decide', JSON.stringify(body));
1012
+ if (!r.ok) throw new Error(`credentials: decision refused: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
1013
+ }
1014
+
1015
+ /**
1016
+ * What the agent did with its credentials (never values), oldest first.
1017
+ * `after` is Unix seconds. A record with `count` stands for that many
1018
+ * successful uses of a value sealed supplies itself (its inference key),
1019
+ * from `first` to `ts`.
1020
+ */
1021
+ async audit(sealId: Hash, opts?: { after?: number; agentUrl?: string }): Promise<Array<{ ts: string; op: string; names: string[]; host?: string; method?: string; result: string; count?: number; first?: string }>> {
1022
+ const base = opts?.agentUrl ?? (await this.agentUrl(sealId));
1023
+ const r = await this.sealRequest(sealId, base, '0GSealCredAudit', `/_seal/credentials/audit?after=${opts?.after ?? 0}`);
1024
+ if (!r.ok) throw new Error(`credentials.audit: HTTP ${r.status} ${plainText(await r.text().catch(() => ''))}`);
1025
+ return (await r.json()) as Array<{ ts: string; op: string; names: string[]; host?: string; method?: string; result: string; count?: number; first?: string }>;
1026
+ }
1027
+ }