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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/GUIDE.md +975 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION.md +84 -0
  4. package/MIGRATION.zh.md +70 -0
  5. package/PROVIDERS.md +273 -0
  6. package/PROVIDERS.zh.md +234 -0
  7. package/README.md +334 -2
  8. package/dist/AgentClient.d.ts +312 -0
  9. package/dist/AgentClient.d.ts.map +1 -0
  10. package/dist/AgentClient.js +715 -0
  11. package/dist/AgentClient.js.map +1 -0
  12. package/dist/AgenticID.d.ts +823 -0
  13. package/dist/AgenticID.d.ts.map +1 -0
  14. package/dist/AgenticID.js +1188 -0
  15. package/dist/AgenticID.js.map +1 -0
  16. package/dist/AgenticIDClient.d.ts +68 -0
  17. package/dist/AgenticIDClient.d.ts.map +1 -0
  18. package/dist/AgenticIDClient.js +198 -0
  19. package/dist/AgenticIDClient.js.map +1 -0
  20. package/dist/AttestorClient.d.ts +465 -0
  21. package/dist/AttestorClient.d.ts.map +1 -0
  22. package/dist/AttestorClient.js +1030 -0
  23. package/dist/AttestorClient.js.map +1 -0
  24. package/dist/Providers.d.ts +72 -0
  25. package/dist/Providers.d.ts.map +1 -0
  26. package/dist/Providers.js +182 -0
  27. package/dist/Providers.js.map +1 -0
  28. package/dist/ReputationClient.d.ts +213 -0
  29. package/dist/ReputationClient.d.ts.map +1 -0
  30. package/dist/ReputationClient.js +708 -0
  31. package/dist/ReputationClient.js.map +1 -0
  32. package/dist/SandboxClient.d.ts +107 -0
  33. package/dist/SandboxClient.d.ts.map +1 -0
  34. package/dist/SandboxClient.js +200 -0
  35. package/dist/SandboxClient.js.map +1 -0
  36. package/dist/ServeProof.d.ts +161 -0
  37. package/dist/ServeProof.d.ts.map +1 -0
  38. package/dist/ServeProof.js +230 -0
  39. package/dist/ServeProof.js.map +1 -0
  40. package/dist/ServeSession.d.ts +180 -0
  41. package/dist/ServeSession.d.ts.map +1 -0
  42. package/dist/ServeSession.js +336 -0
  43. package/dist/ServeSession.js.map +1 -0
  44. package/dist/Settings.d.ts +179 -0
  45. package/dist/Settings.d.ts.map +1 -0
  46. package/dist/Settings.js +247 -0
  47. package/dist/Settings.js.map +1 -0
  48. package/dist/abi.d.ts +2216 -0
  49. package/dist/abi.d.ts.map +1 -0
  50. package/dist/abi.js +1248 -0
  51. package/dist/abi.js.map +1 -0
  52. package/dist/cli/commands/cells.d.ts +62 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +113 -0
  55. package/dist/cli/commands/cells.js.map +1 -0
  56. package/dist/cli/commands/doctor.d.ts +15 -0
  57. package/dist/cli/commands/doctor.d.ts.map +1 -0
  58. package/dist/cli/commands/doctor.js +236 -0
  59. package/dist/cli/commands/doctor.js.map +1 -0
  60. package/dist/cli/commands/interactive.d.ts +115 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3052 -0
  63. package/dist/cli/commands/interactive.js.map +1 -0
  64. package/dist/cli/commands/list.d.ts +31 -0
  65. package/dist/cli/commands/list.d.ts.map +1 -0
  66. package/dist/cli/commands/list.js +91 -0
  67. package/dist/cli/commands/list.js.map +1 -0
  68. package/dist/cli/commands/providers.d.ts +3 -0
  69. package/dist/cli/commands/providers.d.ts.map +1 -0
  70. package/dist/cli/commands/providers.js +21 -0
  71. package/dist/cli/commands/providers.js.map +1 -0
  72. package/dist/cli/commands/settings.d.ts +22 -0
  73. package/dist/cli/commands/settings.d.ts.map +1 -0
  74. package/dist/cli/commands/settings.js +188 -0
  75. package/dist/cli/commands/settings.js.map +1 -0
  76. package/dist/cli/commands/status.d.ts +16 -0
  77. package/dist/cli/commands/status.d.ts.map +1 -0
  78. package/dist/cli/commands/status.js +148 -0
  79. package/dist/cli/commands/status.js.map +1 -0
  80. package/dist/cli/commands/update.d.ts +21 -0
  81. package/dist/cli/commands/update.d.ts.map +1 -0
  82. package/dist/cli/commands/update.js +95 -0
  83. package/dist/cli/commands/update.js.map +1 -0
  84. package/dist/cli/config.d.ts +73 -0
  85. package/dist/cli/config.d.ts.map +1 -0
  86. package/dist/cli/config.js +239 -0
  87. package/dist/cli/config.js.map +1 -0
  88. package/dist/cli/env.d.ts +36 -0
  89. package/dist/cli/env.d.ts.map +1 -0
  90. package/dist/cli/env.js +74 -0
  91. package/dist/cli/env.js.map +1 -0
  92. package/dist/cli/envelope.d.ts +33 -0
  93. package/dist/cli/envelope.d.ts.map +1 -0
  94. package/dist/cli/envelope.js +62 -0
  95. package/dist/cli/envelope.js.map +1 -0
  96. package/dist/cli/errors.d.ts +48 -0
  97. package/dist/cli/errors.d.ts.map +1 -0
  98. package/dist/cli/errors.js +81 -0
  99. package/dist/cli/errors.js.map +1 -0
  100. package/dist/cli/inference.d.ts +21 -0
  101. package/dist/cli/inference.d.ts.map +1 -0
  102. package/dist/cli/inference.js +60 -0
  103. package/dist/cli/inference.js.map +1 -0
  104. package/dist/cli/logo.d.ts +21 -0
  105. package/dist/cli/logo.d.ts.map +1 -0
  106. package/dist/cli/logo.js +131 -0
  107. package/dist/cli/logo.js.map +1 -0
  108. package/dist/cli/main.d.ts +14 -0
  109. package/dist/cli/main.d.ts.map +1 -0
  110. package/dist/cli/main.js +223 -0
  111. package/dist/cli/main.js.map +1 -0
  112. package/dist/cli/proofs.d.ts +67 -0
  113. package/dist/cli/proofs.d.ts.map +1 -0
  114. package/dist/cli/proofs.js +133 -0
  115. package/dist/cli/proofs.js.map +1 -0
  116. package/dist/cli/ref.d.ts +39 -0
  117. package/dist/cli/ref.d.ts.map +1 -0
  118. package/dist/cli/ref.js +48 -0
  119. package/dist/cli/ref.js.map +1 -0
  120. package/dist/cli/sdk.d.ts +24 -0
  121. package/dist/cli/sdk.d.ts.map +1 -0
  122. package/dist/cli/sdk.js +65 -0
  123. package/dist/cli/sdk.js.map +1 -0
  124. package/dist/cli/settings.d.ts +66 -0
  125. package/dist/cli/settings.d.ts.map +1 -0
  126. package/dist/cli/settings.js +137 -0
  127. package/dist/cli/settings.js.map +1 -0
  128. package/dist/cli/tokenize.d.ts +61 -0
  129. package/dist/cli/tokenize.d.ts.map +1 -0
  130. package/dist/cli/tokenize.js +157 -0
  131. package/dist/cli/tokenize.js.map +1 -0
  132. package/dist/cli/types.d.ts +25 -0
  133. package/dist/cli/types.d.ts.map +1 -0
  134. package/dist/cli/types.js +8 -0
  135. package/dist/cli/types.js.map +1 -0
  136. package/dist/constants.d.ts +107 -0
  137. package/dist/constants.d.ts.map +1 -0
  138. package/dist/constants.js +74 -0
  139. package/dist/constants.js.map +1 -0
  140. package/dist/context.d.ts +108 -0
  141. package/dist/context.d.ts.map +1 -0
  142. package/dist/context.js +64 -0
  143. package/dist/context.js.map +1 -0
  144. package/dist/index.d.ts +45 -0
  145. package/dist/index.d.ts.map +1 -0
  146. package/dist/index.js +118 -0
  147. package/dist/index.js.map +1 -0
  148. package/dist/provider-catalog.json +23 -0
  149. package/dist/seal.d.ts +47 -0
  150. package/dist/seal.d.ts.map +1 -0
  151. package/dist/seal.js +145 -0
  152. package/dist/seal.js.map +1 -0
  153. package/dist/secretEnv.d.ts +119 -0
  154. package/dist/secretEnv.d.ts.map +1 -0
  155. package/dist/secretEnv.js +199 -0
  156. package/dist/secretEnv.js.map +1 -0
  157. package/dist/taskHash.d.ts +39 -0
  158. package/dist/taskHash.d.ts.map +1 -0
  159. package/dist/taskHash.js +119 -0
  160. package/dist/taskHash.js.map +1 -0
  161. package/dist/types.d.ts +336 -0
  162. package/dist/types.d.ts.map +1 -0
  163. package/dist/types.js +19 -0
  164. package/dist/types.js.map +1 -0
  165. package/package.json +75 -4
  166. package/scripts/sync-providers.cjs +8 -0
  167. package/src/AgentClient.ts +897 -0
  168. package/src/AgenticID.ts +1382 -0
  169. package/src/AgenticIDClient.ts +238 -0
  170. package/src/AttestorClient.ts +1306 -0
  171. package/src/Providers.ts +176 -0
  172. package/src/ReputationClient.ts +821 -0
  173. package/src/SandboxClient.ts +227 -0
  174. package/src/ServeProof.ts +290 -0
  175. package/src/ServeSession.ts +421 -0
  176. package/src/Settings.ts +296 -0
  177. package/src/abi.ts +1282 -0
  178. package/src/cli/commands/cells.ts +107 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2738 -0
  181. package/src/cli/commands/list.ts +95 -0
  182. package/src/cli/commands/providers.ts +16 -0
  183. package/src/cli/commands/settings.ts +197 -0
  184. package/src/cli/commands/status.ts +170 -0
  185. package/src/cli/commands/update.ts +86 -0
  186. package/src/cli/config.ts +225 -0
  187. package/src/cli/env.ts +90 -0
  188. package/src/cli/envelope.ts +57 -0
  189. package/src/cli/errors.ts +114 -0
  190. package/src/cli/inference.ts +57 -0
  191. package/src/cli/logo.ts +125 -0
  192. package/src/cli/main.ts +235 -0
  193. package/src/cli/proofs.ts +160 -0
  194. package/src/cli/ref.ts +58 -0
  195. package/src/cli/sdk.ts +65 -0
  196. package/src/cli/settings.ts +153 -0
  197. package/src/cli/tokenize.ts +131 -0
  198. package/src/cli/types.ts +27 -0
  199. package/src/constants.ts +106 -0
  200. package/src/context.ts +161 -0
  201. package/src/index.ts +129 -0
  202. package/src/provider-catalog.json +23 -0
  203. package/src/seal.ts +163 -0
  204. package/src/secretEnv.ts +250 -0
  205. package/src/taskHash.ts +100 -0
  206. package/src/types.ts +357 -0
package/src/seal.ts ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * @file seal.ts
3
+ * @description viem Account backed by the sealed container's sign socket —
4
+ * how an AGENT uses the SDK as an owner (nested agents).
5
+ *
6
+ * Inside a sealed container the agentSeal private key lives only in the
7
+ * sealed Go process; the agent reaches it through a unix-socket signer
8
+ * (`SEAL_SIGN_SOCK`, three endpoints: personal_sign / typed_data /
9
+ * transaction — see sealed/internal/proxy/sign.go). This module bridges
10
+ * that signer into a viem `Account`, so the whole SDK works unchanged:
11
+ *
12
+ * import { AgentDNA } from '@0gfoundation/0g-agentdna';
13
+ * import { sealAccount } from '@0gfoundation/0g-agentdna/seal';
14
+ * const ag = await AgentDNA.fromAttestor(url, { account: await sealAccount() });
15
+ *
16
+ * Node-only (unix sockets); import from the `/seal` subpath so browser
17
+ * bundles of the main entry stay node-free.
18
+ */
19
+
20
+ import { request as httpRequest } from 'node:http';
21
+ import { toAccount } from 'viem/accounts';
22
+ import type { Address, Hex, LocalAccount } from 'viem';
23
+
24
+ export interface SealAccountOptions {
25
+ /** Unix socket path. Default: $SEAL_SIGN_SOCK, then /run/seal-sign.sock. */
26
+ socketPath?: string;
27
+ /**
28
+ * The agentSeal address. Default: $AGENT_SEAL (exported into the agent's
29
+ * environment by the sealed runtime); as a last resort the adapter probes
30
+ * the socket with one personal_sign and uses the address it reports.
31
+ */
32
+ address?: Address;
33
+ }
34
+
35
+ /** POST a JSON body to the sign socket; JSON response or a typed error. */
36
+ function sockPost(socketPath: string, path: string, body: unknown): Promise<Record<string, any>> {
37
+ // JSON.stringify with a bigint guard — a stray bigint (e.g. a typed-data
38
+ // domain chainId) must become a number/string, not a TypeError.
39
+ const payload = JSON.stringify(body, (_k, v) => (typeof v === 'bigint' ? v.toString() : v));
40
+ return new Promise((resolve, reject) => {
41
+ const req = httpRequest(
42
+ { socketPath, path, method: 'POST', headers: { 'content-type': 'application/json' } },
43
+ (res) => {
44
+ let raw = '';
45
+ res.setEncoding('utf8');
46
+ res.on('data', (c) => (raw += c));
47
+ res.on('end', () => {
48
+ let parsed: Record<string, any> | null = null;
49
+ try { parsed = JSON.parse(raw); } catch { /* non-JSON error body */ }
50
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300 && parsed) {
51
+ resolve(parsed);
52
+ } else {
53
+ const detail = parsed?.error ?? raw.trim() ?? '';
54
+ reject(new Error(`seal sign socket ${path}: HTTP ${res.statusCode}${detail ? ` — ${detail}` : ''}`));
55
+ }
56
+ });
57
+ },
58
+ );
59
+ req.on('error', (e) =>
60
+ reject(new Error(`seal sign socket ${path}: ${e.message} (socket: ${socketPath} — are you inside a sealed container?)`)),
61
+ );
62
+ req.end(payload);
63
+ });
64
+ }
65
+
66
+ /** The EIP712Domain type entry the geth-side hasher requires inside `types`. */
67
+ function eip712DomainType(domain: Record<string, unknown>): Array<{ name: string; type: string }> {
68
+ const fields: Array<{ name: string; type: string }> = [];
69
+ if (domain.name !== undefined) fields.push({ name: 'name', type: 'string' });
70
+ if (domain.version !== undefined) fields.push({ name: 'version', type: 'string' });
71
+ if (domain.chainId !== undefined) fields.push({ name: 'chainId', type: 'uint256' });
72
+ if (domain.verifyingContract !== undefined) fields.push({ name: 'verifyingContract', type: 'address' });
73
+ if (domain.salt !== undefined) fields.push({ name: 'salt', type: 'bytes32' });
74
+ return fields;
75
+ }
76
+
77
+ const dec = (v: bigint | number | undefined): string | undefined =>
78
+ v === undefined ? undefined : v.toString(10);
79
+
80
+ /**
81
+ * A viem `LocalAccount` whose signatures come from the sealed container's
82
+ * sign socket. Pass it wherever the SDK takes `account` — the SDK's
83
+ * contract: no method ever needs a raw private key, all signing flows
84
+ * through the viem Account interface, so this account IS full ownership.
85
+ *
86
+ * Unsupported on purpose (the socket signs legacy + EIP-1559 only): tx
87
+ * types eip2930/eip4844/eip7702 and access lists — those throw an explicit
88
+ * error rather than mis-signing.
89
+ *
90
+ * Deliberately absent, and must stay so: raw-hash signing (`sign({ hash })`)
91
+ * and any EIP-191 version 0x00 path. The socket's preimages are only
92
+ * personal_sign (0x19 0x45), typed data (0x19 0x01) and transactions it
93
+ * encodes itself; ServeProofs are signed over a 0x19 0x00 digest that only
94
+ * the sealed proxy produces, so this account cannot forge one.
95
+ */
96
+ export async function sealAccount(opts?: SealAccountOptions): Promise<LocalAccount> {
97
+ const socketPath = opts?.socketPath ?? process.env.SEAL_SIGN_SOCK ?? '/run/seal-sign.sock';
98
+
99
+ let address = opts?.address ?? (process.env.AGENT_SEAL as Address | undefined);
100
+ if (!address) {
101
+ // Last resort: one probe signature — the socket reports its address.
102
+ const probe = await sockPost(socketPath, '/sign/personal_sign', { message: 'agenticid-sdk: sealAccount address probe' });
103
+ address = probe.address as Address;
104
+ }
105
+
106
+ return toAccount({
107
+ address,
108
+
109
+ async signMessage({ message }) {
110
+ // viem's two input shapes map to the socket's two body fields; mixing
111
+ // them up signs a DIFFERENT message (utf8 of "0x…" vs the raw bytes).
112
+ const body =
113
+ typeof message === 'string'
114
+ ? { message }
115
+ : { message_hex: typeof message.raw === 'string' ? message.raw : `0x${Buffer.from(message.raw).toString('hex')}` };
116
+ const res = await sockPost(socketPath, '/sign/personal_sign', body);
117
+ return res.signature as Hex;
118
+ },
119
+
120
+ async signTransaction(tx) {
121
+ const type = tx.type ?? (tx.maxFeePerGas !== undefined ? 'eip1559' : 'legacy');
122
+ if (type !== 'eip1559' && type !== 'legacy') {
123
+ throw new Error(`sealAccount: tx type "${type}" not supported by the seal sign socket (legacy + eip1559 only)`);
124
+ }
125
+ if ('accessList' in tx && tx.accessList?.length) {
126
+ throw new Error('sealAccount: accessList not supported by the seal sign socket');
127
+ }
128
+ if (tx.chainId === undefined || tx.nonce === undefined || tx.gas === undefined) {
129
+ throw new Error('sealAccount: signTransaction needs chainId, nonce and gas — prepare the request first (viem prepareTransactionRequest)');
130
+ }
131
+ const body = {
132
+ chain_id: tx.chainId.toString(10),
133
+ nonce: tx.nonce,
134
+ to: tx.to ?? '',
135
+ value: dec(tx.value) ?? '0',
136
+ data: tx.data ?? '',
137
+ gas_limit: Number(tx.gas),
138
+ type: type === 'eip1559' ? 'dynamic' : 'legacy',
139
+ ...(type === 'eip1559'
140
+ ? { max_fee_per_gas: dec(tx.maxFeePerGas), max_priority_fee_per_gas: dec(tx.maxPriorityFeePerGas) }
141
+ : { gas_price: dec(tx.gasPrice) }),
142
+ };
143
+ const res = await sockPost(socketPath, '/sign/transaction', body);
144
+ return res.raw_tx as Hex; // already the serialized signed tx
145
+ },
146
+
147
+ async signTypedData(typedData) {
148
+ const { domain = {}, types, primaryType, message } = typedData as {
149
+ domain?: Record<string, unknown>; types: Record<string, unknown>; primaryType: string; message: unknown;
150
+ };
151
+ // geth's apitypes hasher requires the EIP712Domain entry INSIDE types;
152
+ // viem convention omits it — inject one derived from the domain fields.
153
+ const body = {
154
+ domain,
155
+ primaryType,
156
+ message,
157
+ types: { EIP712Domain: eip712DomainType(domain), ...types },
158
+ };
159
+ const res = await sockPost(socketPath, '/sign/typed_data', body);
160
+ return res.signature as Hex;
161
+ },
162
+ });
163
+ }
@@ -0,0 +1,250 @@
1
+ /**
2
+ * @file secretEnv.ts
3
+ * @description Seal an owner's secret env (today: the inference API key) to an
4
+ * agent's agentSeal public key, so it never appears in clear in the envelope
5
+ * the owner's wallet signs (issue #166).
6
+ *
7
+ * The sandbox "create" envelope is signed with EIP-191 `personal_sign`, and a
8
+ * wallet shows that message verbatim. With the key in `env.API_KEY`, the
9
+ * prompt displayed it, and every hop that relays the envelope (an
10
+ * integrator's proxy, the attestor's job store, the sandbox provider) held it
11
+ * in clear. Sealed instead, the envelope carries
12
+ *
13
+ * env.SEAL_SECRET_ENV = base64( ECIES(agentSeal_pub, {"v":1,"owner",env}) )
14
+ *
15
+ * The owner still signs exactly the bytes the container receives; those bytes
16
+ * are ciphertext that only agentSeal_priv opens (the sealed container after
17
+ * `/provision`, and the attestor's KMS derivation). The container checks that
18
+ * `owner` is the agent's live on-chain owner before applying it.
19
+ *
20
+ * Who seals: the SDK seals `apiKey` itself on start/reset/retry. When an
21
+ * integrator supplies the key (its own billed account) and a user signs, the
22
+ * integrator's server seals it with `sealApiKey` and hands the browser only
23
+ * the ciphertext, which the browser passes as `sealedSecretEnv`. The key then
24
+ * never reaches the user's browser at all.
25
+ *
26
+ * ECIES is the eciesjs-compatible scheme the attestor and sealed already use
27
+ * for `sealedKeys`: secp256k1 ECDH, HKDF-SHA256 over
28
+ * `ephemeralPub(65) ‖ sharedPoint(65)` (no salt, no info), AES-256-GCM with a
29
+ * 16-byte nonce; wire format `ephemeralPub(65) ‖ nonce(16) ‖ tag(16) ‖ ct`.
30
+ */
31
+
32
+ import { secp256k1 } from '@noble/curves/secp256k1';
33
+ import { hkdf } from '@noble/hashes/hkdf';
34
+ import { sha256 } from '@noble/hashes/sha2';
35
+ import { gcm } from '@noble/ciphers/aes';
36
+ import { getAddress, hexToBytes, keccak256, toHex, type Address, type Hex } from 'viem';
37
+
38
+ /** `GET /config` value that says this attestor's sealed images open a secret env. */
39
+ export const SECRET_ENV_SCHEME = 'agent-seal-ecies-v1';
40
+ /** The container env var that carries the sealed secret env. */
41
+ export const SECRET_ENV_VAR = 'SEAL_SECRET_ENV';
42
+
43
+ /**
44
+ * How `start` / `reset` / `retry` / `deploy` deliver the inference key:
45
+ * - `'auto'` (default): sealed to the agent when the attestor advertises
46
+ * `secret_env_scheme` and the agent exists already; otherwise in clear
47
+ * (older attestors, and a one-shot `deploy` with `sandbox`, whose agent
48
+ * does not exist yet when the envelope is signed).
49
+ * - `'sealed'`: sealed or throw — the wallet prompt never shows the key.
50
+ * - `'plaintext'`: legacy `env.API_KEY` in clear, for a sealed image built
51
+ * before `SEAL_SECRET_ENV` existed.
52
+ */
53
+ export type SecretEnvMode = 'auto' | 'sealed' | 'plaintext';
54
+
55
+ /** Why a secret-env step refused. Every refusal happens before anything is
56
+ * signed or sent. */
57
+ export type SecretEnvRefusalCode =
58
+ /** `secretEnv` is not 'auto' | 'sealed' | 'plaintext'. */
59
+ | 'provider_binding_unsupported'
60
+ | 'invalid_mode'
61
+ /** Both `apiKey` and `sealedSecretEnv`, or `sealedSecretEnv` with 'plaintext'. */
62
+ | 'conflicting_inputs'
63
+ /** A required input is missing or malformed (e.g. `sealApiKey` without a key or a valid owner). */
64
+ | 'invalid_input'
65
+ /** The call signs before the agent exists (one-shot deploy), so nothing can be sealed to it. */
66
+ | 'sealed_needs_agent'
67
+ /** GET /config could not be read, so the SDK cannot tell whether sealing is supported. */
68
+ | 'config_unreadable'
69
+ /** The attestor does not advertise `secret_env_scheme`. */
70
+ | 'scheme_unsupported'
71
+ /** GET /agent-seal-pubkey failed (network error or non-2xx). */
72
+ | 'pubkey_unavailable'
73
+ /** The served agentSeal public key is not a valid secp256k1 point. */
74
+ | 'pubkey_invalid'
75
+ /** The served key belongs to another seal, another agent_seal_addr, or not to the on-chain agentSeal. */
76
+ | 'pubkey_mismatch'
77
+ /** A chain read needed for a check failed. */
78
+ | 'chain_read_failed'
79
+ /** `owner` is not the agent's on-chain owner, so its container would refuse the secret. */
80
+ | 'owner_mismatch'
81
+ /** `sealedSecretEnv` is not an ECIES ciphertext in the expected wire format. */
82
+ | 'invalid_sealed_secret_env'
83
+ /** This attestor advertised `secret_env_scheme` before and no longer does.
84
+ * For `'auto'` that is indistinguishable from a relaying proxy stripping
85
+ * the field to force a clear-text key, so the SDK refuses instead of
86
+ * downgrading (a sticky pin, per client and — via `secretEnvPin` — per
87
+ * machine). A deliberate operator rollback is expressed by the caller as
88
+ * `secretEnv: 'plaintext'`. */
89
+ | 'scheme_withdrawn';
90
+
91
+ /**
92
+ * A secret-env refusal. `signed` is always false: the SDK checks everything
93
+ * before it asks the wallet to sign and before it posts anything, so an
94
+ * integrator can treat this error as "nothing left the process".
95
+ */
96
+ export class SecretEnvRefusedError extends Error {
97
+ readonly signed = false as const;
98
+ constructor(
99
+ readonly code: SecretEnvRefusalCode,
100
+ message: string,
101
+ options?: { cause?: unknown },
102
+ ) {
103
+ super(message);
104
+ this.name = 'SecretEnvRefusedError';
105
+ if (options && 'cause' in options) (this as { cause?: unknown }).cause = options.cause;
106
+ }
107
+ }
108
+
109
+ type WebCrypto = { getRandomValues<T extends Uint8Array>(x: T): T };
110
+
111
+ /** Cryptographic random bytes: WebCrypto in browsers and Node >= 19, the
112
+ * node:crypto fallback on Node 18 (the engines floor). */
113
+ export function randomBytes(n: number): Uint8Array {
114
+ const a = new Uint8Array(n);
115
+ let cryptoObj = (globalThis as { crypto?: WebCrypto }).crypto;
116
+ if (!cryptoObj?.getRandomValues && typeof require === 'function') {
117
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
118
+ cryptoObj = (require('crypto') as { webcrypto?: WebCrypto }).webcrypto;
119
+ }
120
+ if (!cryptoObj?.getRandomValues) {
121
+ throw new Error('AgenticID SDK: no WebCrypto available (need a browser or Node >= 18 with crypto.webcrypto)');
122
+ }
123
+ cryptoObj.getRandomValues(a);
124
+ return a;
125
+ }
126
+
127
+ function base64(bytes: Uint8Array): string {
128
+ const g = globalThis as { btoa?: (d: string) => string };
129
+ if (typeof g.btoa === 'function') {
130
+ let bin = '';
131
+ for (const b of bytes) bin += String.fromCharCode(b);
132
+ return g.btoa(bin);
133
+ }
134
+ return Buffer.from(bytes).toString('base64');
135
+ }
136
+
137
+ /** Ethereum address of a secp256k1 public key (compressed or uncompressed). */
138
+ export function publicKeyToAddress(pubkey: Uint8Array): Address {
139
+ const uncompressed = secp256k1.ProjectivePoint.fromHex(pubkey).toRawBytes(false);
140
+ return getAddress(`0x${keccak256(uncompressed.slice(1)).slice(-40)}`);
141
+ }
142
+
143
+ /** eciesjs-compatible ECIES encryption to a secp256k1 public key (33 or 65 bytes). */
144
+ export function eciesEncrypt(recipientPubkey: Uint8Array, plaintext: Uint8Array): Uint8Array {
145
+ // fromHex validates the point is on the curve (throws otherwise).
146
+ const recipient = secp256k1.ProjectivePoint.fromHex(recipientPubkey);
147
+ const ephemeralPriv = randomValidPriv();
148
+ const ephemeralPub = secp256k1.getPublicKey(ephemeralPriv, false);
149
+ const shared = secp256k1.getSharedSecret(ephemeralPriv, recipient.toRawBytes(true), false);
150
+ const ikm = new Uint8Array(ephemeralPub.length + shared.length);
151
+ ikm.set(ephemeralPub, 0);
152
+ ikm.set(shared, ephemeralPub.length);
153
+ const key = hkdf(sha256, ikm, undefined, undefined, 32);
154
+ const nonce = randomBytes(16);
155
+ const sealed = gcm(key, nonce).encrypt(plaintext); // ciphertext ‖ tag(16)
156
+ const ct = sealed.subarray(0, sealed.length - 16);
157
+ const tag = sealed.subarray(sealed.length - 16);
158
+ const out = new Uint8Array(65 + 16 + 16 + ct.length);
159
+ out.set(ephemeralPub, 0);
160
+ out.set(nonce, 65);
161
+ out.set(tag, 81);
162
+ out.set(ct, 97);
163
+ return out;
164
+ }
165
+
166
+ function randomValidPriv(): Uint8Array {
167
+ // A uniformly random 32-byte string is a valid scalar with overwhelming
168
+ // probability; loop for the (~2^-128) remainder rather than bias it.
169
+ for (;;) {
170
+ const k = randomBytes(32);
171
+ if (secp256k1.utils.isValidPrivateKey(k)) return k;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Seal `env` for one agent. `agentSealPubkey` is the agent's agentSeal public
177
+ * key (hex, compressed or uncompressed); `owner` is the address that will sign
178
+ * the envelope (the container requires it to be the agent's on-chain owner).
179
+ * Returns the base64 value for `env.SEAL_SECRET_ENV`.
180
+ */
181
+ export function sealSecretEnv(agentSealPubkey: Hex, owner: Address, env: Record<string, string>, provider?: string, routeHash?: string, registry?: import('./Providers').ProviderRegistryPin): string {
182
+ if (provider !== undefined && !/^[a-z0-9][a-z0-9-]*$/.test(provider)) {
183
+ throw new SecretEnvRefusedError('invalid_input', 'invalid inference provider');
184
+ }
185
+ if (routeHash && (!provider || !/^0x[0-9a-f]{64}$/.test(routeHash))) throw new SecretEnvRefusedError('invalid_input', 'invalid credential route hash');
186
+ if (routeHash && (!registry || !Number.isSafeInteger(registry.version) || registry.version < 0 ||
187
+ (registry.version > 0 ? !/^0x[0-9a-f]{64}$/.test(registry.digest ?? '') : registry.digest !== undefined))) {
188
+ throw new SecretEnvRefusedError('invalid_input', 'v3 credentials require an accepted registry version and digest');
189
+ }
190
+ if (registry && !routeHash) throw new SecretEnvRefusedError('invalid_input', 'registry binding requires v3');
191
+ const plaintext = new TextEncoder().encode(
192
+ JSON.stringify(routeHash ? { v: 3, owner: getAddress(owner), provider, route_hash: routeHash, registry, env } : provider === undefined ? { v: 1, owner: getAddress(owner), env } : { v: 2, owner: getAddress(owner), provider, env }),
193
+ );
194
+ return base64(eciesEncrypt(hexToBytes(agentSealPubkey), plaintext));
195
+ }
196
+
197
+ /** Parse and validate an agentSeal public key served by the attestor; returns
198
+ * its canonical compressed hex. Throws on anything that is not a curve point. */
199
+ export function parseAgentSealPubkey(pubkey: string): Hex {
200
+ if (!/^0x([0-9a-fA-F]{66}|[0-9a-fA-F]{130})$/.test(pubkey)) {
201
+ throw new SecretEnvRefusedError(
202
+ 'pubkey_invalid',
203
+ 'agent_seal_pubkey must be a 33- or 65-byte hex secp256k1 public key',
204
+ );
205
+ }
206
+ try {
207
+ return toHex(secp256k1.ProjectivePoint.fromHex(hexToBytes(pubkey as Hex)).toRawBytes(true));
208
+ } catch (e) {
209
+ throw new SecretEnvRefusedError('pubkey_invalid', 'agent_seal_pubkey is not a secp256k1 curve point', {
210
+ cause: e,
211
+ });
212
+ }
213
+ }
214
+
215
+ function fromBase64(s: string): Uint8Array {
216
+ const g = globalThis as { atob?: (d: string) => string };
217
+ if (typeof g.atob === 'function') {
218
+ const bin = g.atob(s);
219
+ const out = new Uint8Array(bin.length);
220
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
221
+ return out;
222
+ }
223
+ return new Uint8Array(Buffer.from(s, 'base64'));
224
+ }
225
+
226
+ /** Smallest `{"v":1,"owner":"0x…40","env":{"API_KEY":"x"}}` plaintext, in bytes. */
227
+ const MIN_PLAINTEXT = 70;
228
+
229
+ /**
230
+ * Check that `value` has the shape `sealSecretEnv` produces (standard base64
231
+ * of `ephemeralPub(65) ‖ nonce(16) ‖ tag(16) ‖ ct`, with a valid ephemeral
232
+ * point) and return it trimmed. The SDK cannot decrypt it, so this does not
233
+ * prove which agent it was sealed to; it stops a caller from signing
234
+ * something that is plainly not a sealed secret (a raw key passed by
235
+ * mistake, say) into the envelope.
236
+ */
237
+ export function checkSealedSecretEnv(value: string): string {
238
+ const v = typeof value === 'string' ? value.trim() : '';
239
+ const refuse = (why: string) =>
240
+ new SecretEnvRefusedError('invalid_sealed_secret_env', `sealedSecretEnv ${why}; pass the value sealApiKey returned`);
241
+ if (!v || v.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(v)) throw refuse('is not standard base64');
242
+ const raw = fromBase64(v);
243
+ if (raw.length < 65 + 16 + 16 + MIN_PLAINTEXT || raw[0] !== 0x04) throw refuse('is not an ECIES ciphertext');
244
+ try {
245
+ secp256k1.ProjectivePoint.fromHex(raw.subarray(0, 65));
246
+ } catch {
247
+ throw refuse('does not start with a valid ephemeral public key');
248
+ }
249
+ return v;
250
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @file taskHash.ts
3
+ * @description The ServeProof `taskHash` preimage, recomputed client-side.
4
+ *
5
+ * The sealed proxy signs
6
+ *
7
+ * taskHash = keccak256(method ‖ uri ‖ keccak256(reqBody) ‖ keccak256(respBody) ‖ status)
8
+ *
9
+ * (a plain concatenation; `status` as decimal — 3 digits for 100..999), where
10
+ * `uri` is Go's `r.URL.RequestURI()` of the request as the proxy received it.
11
+ * VerifiedFeedbackRegistry.attestFeedbackWithTask rebuilds the same preimage
12
+ * from a {@link TaskReveal}. Consensus-critical: duplicated in the contract,
13
+ * sealed (internal/proxy) and the attestor console, all pinned to the shared
14
+ * katTaskHash vector — a change must land in every copy.
15
+ */
16
+
17
+ import { keccak256, toBytes, hexToBytes, concat, type Hash } from 'viem';
18
+ import type { TaskReveal } from './types';
19
+
20
+ /** keccak256(method ‖ uri ‖ reqBodyHash ‖ respBodyHash ‖ decimal statusCode). */
21
+ export function taskHashOf(task: TaskReveal): Hash {
22
+ return keccak256(concat([
23
+ toBytes(task.method), toBytes(task.uri),
24
+ hexToBytes(task.reqBodyHash), hexToBytes(task.respBodyHash),
25
+ toBytes(String(task.statusCode)),
26
+ ]));
27
+ }
28
+
29
+ // Go net/url shouldEscape(c, encodePath).
30
+ function goShouldEscapePath(c: number): boolean {
31
+ if ((c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) || (c >= 0x30 && c <= 0x39)) return false;
32
+ switch (String.fromCharCode(c)) {
33
+ case '-': case '_': case '.': case '~':
34
+ return false;
35
+ case '$': case '&': case '+': case ',': case '/': case ':': case ';': case '=': case '?': case '@':
36
+ return c === 0x3f; // only '?' is escaped in a path
37
+ default:
38
+ return true;
39
+ }
40
+ }
41
+
42
+ // Go net/url validEncoded(s, encodePath).
43
+ function goValidEncodedPath(s: string): boolean {
44
+ for (let i = 0; i < s.length; i++) {
45
+ const c = s.charCodeAt(i);
46
+ if ("!$&'()*+,;=:@[]%".includes(s[i])) continue;
47
+ if (c > 0x7f || goShouldEscapePath(c)) return false;
48
+ }
49
+ return true;
50
+ }
51
+
52
+ const HEX = '0123456789ABCDEF';
53
+
54
+ /**
55
+ * Go's `url.ParseRequestURI(target).RequestURI()` for an origin-form request
56
+ * target (`/path[?query]`, exactly as sent on the wire) — the `uri` the sealed
57
+ * proxy hashes. The path is kept verbatim when Go accepts its encoding;
58
+ * otherwise (a raw `|`, `^`, … that WHATWG URLs leave alone) Go decodes it and
59
+ * re-escapes every byte outside its path set as upper-case `%XX`. The query is
60
+ * kept verbatim, including a bare trailing `?`. A target Go cannot parse (bad
61
+ * `%` escape) is answered 400 by the proxy, so it is returned unchanged.
62
+ */
63
+ export function requestUriOf(target: string): string {
64
+ const q = target.indexOf('?');
65
+ const rawPath = q < 0 ? target : target.slice(0, q);
66
+ const query = q < 0 ? '' : target.slice(q); // '?' + RawQuery, or a bare '?'
67
+ if (rawPath === '' || goValidEncodedPath(rawPath)) return (rawPath || '/') + query;
68
+ // unescape(rawPath, encodePath) → bytes
69
+ const bytes: number[] = [];
70
+ for (let i = 0; i < rawPath.length; i++) {
71
+ const ch = rawPath[i];
72
+ if (ch === '%') {
73
+ const h = rawPath.slice(i + 1, i + 3);
74
+ if (!/^[0-9a-fA-F]{2}$/.test(h)) return target;
75
+ bytes.push(parseInt(h, 16));
76
+ i += 2;
77
+ } else {
78
+ for (const b of new TextEncoder().encode(ch)) bytes.push(b);
79
+ }
80
+ }
81
+ // escape(path, encodePath)
82
+ let out = '';
83
+ for (const b of bytes) out += goShouldEscapePath(b) ? `%${HEX[b >> 4]}${HEX[b & 15]}` : String.fromCharCode(b);
84
+ return (out || '/') + query;
85
+ }
86
+
87
+ /**
88
+ * The `uri` forms the proxy may have hashed for a request to `url`: Go's
89
+ * RequestURI of the request target, first as Node's fetch (undici) sends it
90
+ * — `pathname + search`, dropping a bare trailing `?` — then, when the URL
91
+ * has such an empty query, as a client that keeps the `?` sends it (the
92
+ * WHATWG fetch spec, browsers). A caller matching a signed taskHash tries
93
+ * each.
94
+ */
95
+ export function requestUriCandidates(url: string | URL): string[] {
96
+ const u = typeof url === 'string' ? new URL(url) : url;
97
+ const out = [requestUriOf(u.pathname + u.search)];
98
+ if (u.search === '' && u.href.replace(/#.*$/, '').endsWith('?')) out.push(requestUriOf(`${u.pathname}?`));
99
+ return out;
100
+ }