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