@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.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 (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 +34 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +66 -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 +107 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3034 -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 +115 -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 +61 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2715 -0
  181. package/src/cli/commands/list.ts +117 -0
  182. package/src/cli/commands/providers.ts +16 -0
  183. package/src/cli/commands/settings.ts +197 -0
  184. package/src/cli/commands/status.ts +170 -0
  185. package/src/cli/commands/update.ts +86 -0
  186. package/src/cli/config.ts +225 -0
  187. package/src/cli/env.ts +90 -0
  188. package/src/cli/envelope.ts +57 -0
  189. package/src/cli/errors.ts +114 -0
  190. package/src/cli/inference.ts +57 -0
  191. package/src/cli/logo.ts +125 -0
  192. package/src/cli/main.ts +235 -0
  193. package/src/cli/proofs.ts +160 -0
  194. package/src/cli/ref.ts +58 -0
  195. package/src/cli/sdk.ts +65 -0
  196. package/src/cli/settings.ts +153 -0
  197. package/src/cli/tokenize.ts +131 -0
  198. package/src/cli/types.ts +27 -0
  199. package/src/constants.ts +106 -0
  200. package/src/context.ts +161 -0
  201. package/src/index.ts +129 -0
  202. package/src/provider-catalog.json +23 -0
  203. package/src/seal.ts +163 -0
  204. package/src/secretEnv.ts +250 -0
  205. package/src/taskHash.ts +100 -0
  206. package/src/types.ts +357 -0
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @file tokenize.ts
3
+ * @description Splitting a REPL line into arguments, the way a shell does.
4
+ *
5
+ * Outside the REPL the user's shell does this and the CLI never sees quotes.
6
+ * Inside it, a bare `line.split(/\s+/)` made every value containing a space
7
+ * unreachable — `others={"tools": {"bash": true}}` arrived as four
8
+ * arguments, and the error message helpfully suggested quoting, which the
9
+ * splitter then handed through as literal `'` characters. Quoting has to
10
+ * actually work, or the advice is a dead end.
11
+ *
12
+ * The grammar is the small familiar one, and deliberately no larger:
13
+ *
14
+ * 'single' everything literal up to the next single quote
15
+ * "double" literal too, except `\"` and `\\`
16
+ * \x outside quotes, the next character verbatim (so `\ ` is a space)
17
+ * {…} […] a JSON literal WHERE A VALUE STARTS — copied through exactly as
18
+ * typed, to its matching close: spaces, nesting and quotes alike
19
+ *
20
+ * That last rule is what keeps a shell splitter honest about JSON. Quote
21
+ * characters are how a shell protects a value, but they are also what JSON is
22
+ * MADE of, so stripping them turns `others={"a":1}` — the unquoted form the
23
+ * help and the GUIDE print — into `others={a:1}`, which parses as nothing.
24
+ * A literal opening where a value begins (the start of a token, or right after
25
+ * an `=`) is therefore data: copied, not interpreted. Elsewhere a bracket is
26
+ * an ordinary character, so `/api/x[0]` is still one plain token.
27
+ *
28
+ * No variable expansion, no globbing, no operators — a REPL argument is data,
29
+ * and a splitter that interprets it would be a surprise, not a convenience.
30
+ * Adjacent pieces join into one token (`others='{"a": 1}'` is one word),
31
+ * which is the whole point.
32
+ *
33
+ * A command whose LAST argument is free-form text rather than a value in a
34
+ * list — `call <id> <path> <json-body>` — should not be run through this at
35
+ * all: see {@link splitHead}.
36
+ */
37
+
38
+ /**
39
+ * Split a command line into tokens. An unterminated quote is NOT an error:
40
+ * the user is mid-thought at an interactive prompt, so the run of text is
41
+ * taken as written and the caller's own grammar check reports whatever is
42
+ * wrong with it — a parse error about quoting would just be noise on top.
43
+ */
44
+ export function tokenize(line: string): string[] {
45
+ return scan(line, Infinity).head;
46
+ }
47
+
48
+ /**
49
+ * Split off the first `n` tokens and hand the REST OF THE LINE back verbatim.
50
+ *
51
+ * The shell-style splitter is the wrong tool for an argument that is free-form
52
+ * text. `call 42 /api/x {"a": 1}` has a fixed head — command, agent, path —
53
+ * and then a body that is whatever the user typed, quotes and inner spacing
54
+ * included, on its way to an agent that will parse it. Tokenizing that and
55
+ * re-joining the pieces with a single space is a guess about what was typed;
56
+ * taking the remainder of the line is not a guess.
57
+ *
58
+ * `rest` has no leading whitespace, and is '' when the line holds no more
59
+ * than `n` tokens.
60
+ */
61
+ export function splitHead(line: string, n: number): { head: string[]; rest: string } {
62
+ return scan(line, n);
63
+ }
64
+
65
+ /** The one scanner behind both entry points: it stops after `limit` tokens
66
+ * and reports whatever is left of the line untouched. */
67
+ function scan(line: string, limit: number): { head: string[]; rest: string } {
68
+ const head: string[] = [];
69
+ let cur = '';
70
+ let started = false; // distinguishes '' (a real empty token) from no token
71
+ let quote: '"' | "'" | null = null;
72
+
73
+ for (let i = 0; i < line.length; i++) {
74
+ const c = line[i];
75
+ if (quote === "'") {
76
+ if (c === "'") quote = null;
77
+ else cur += c;
78
+ continue;
79
+ }
80
+ if (quote === '"') {
81
+ if (c === '"') quote = null;
82
+ else if (c === '\\' && (line[i + 1] === '"' || line[i + 1] === '\\')) cur += line[++i];
83
+ else cur += c;
84
+ continue;
85
+ }
86
+ // The head the caller asked for is complete: everything from the next
87
+ // non-space character on belongs to it verbatim.
88
+ if (!started && head.length >= limit) {
89
+ if (/\s/.test(c)) continue;
90
+ return { head, rest: line.slice(i) };
91
+ }
92
+ if (c === "'" || c === '"') { quote = c; started = true; continue; }
93
+ if ((c === '{' || c === '[') && (!started || line[i - 1] === '=')) {
94
+ const end = literalEnd(line, i);
95
+ cur += line.slice(i, end);
96
+ i = end - 1;
97
+ started = true;
98
+ continue;
99
+ }
100
+ if (c === '\\' && i + 1 < line.length) { cur += line[++i]; started = true; continue; }
101
+ if (/\s/.test(c)) {
102
+ if (started) { head.push(cur); cur = ''; started = false; }
103
+ continue;
104
+ }
105
+ cur += c;
106
+ started = true;
107
+ }
108
+ if (started) head.push(cur);
109
+ return { head, rest: '' };
110
+ }
111
+
112
+ /** Index just past the `}`/`]` closing the literal that opens at `start`.
113
+ * Brackets inside a JSON string don't count. An unbalanced literal runs to
114
+ * the end of the line — the same "taken as written" treatment an
115
+ * unterminated quote gets, leaving the grammar check to report it. */
116
+ function literalEnd(line: string, start: number): number {
117
+ let depth = 0;
118
+ let inString = false;
119
+ for (let i = start; i < line.length; i++) {
120
+ const c = line[i];
121
+ if (inString) {
122
+ if (c === '\\') i++;
123
+ else if (c === '"') inString = false;
124
+ continue;
125
+ }
126
+ if (c === '"') { inString = true; continue; }
127
+ if (c === '{' || c === '[') depth++;
128
+ else if ((c === '}' || c === ']') && --depth === 0) return i + 1;
129
+ }
130
+ return line.length;
131
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @file types.ts
3
+ * @description Shared shapes between the CLI router (main.ts) and the
4
+ * command modules under commands/.
5
+ */
6
+
7
+ import type { CliEnv } from './env';
8
+
9
+ /** Everything a command receives — commands never touch process.argv/env. */
10
+ export interface CommandContext {
11
+ /** Resolved environment variables (spec v0.03 §2.1). */
12
+ env: CliEnv;
13
+ /** True when `--json` was passed — envelope output, stdout data-only. */
14
+ json: boolean;
15
+ /** Positional args AFTER the command name (e.g. `status 33` → `['33']`). */
16
+ positionals: string[];
17
+ /** Parsed option flags relevant to stage-0 commands. */
18
+ flags: {
19
+ /** `list --mine` — owner-signed listing (needs AGENTIC_PRIVATE_KEY). */
20
+ mine: boolean;
21
+ /** `list --phase <p>` — client-side phase filter. */
22
+ phase?: string;
23
+ };
24
+ }
25
+
26
+ /** A command module: one async run(), throws CliError on failure. */
27
+ export type CommandRun = (ctx: CommandContext) => Promise<void>;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * @file constants.ts
3
+ * @description Contract addresses, chain configuration, and ABI hashes for the 0G AgenticID protocol.
4
+ */
5
+
6
+ /**
7
+ * 0G testnet (Galileo) chain definition — a viem `Chain` (network metadata:
8
+ * chainId, native currency, RPC, explorer), not a contract address.
9
+ */
10
+ export const ZERO_G_TESTNET = {
11
+ id: 16602,
12
+ name: '0G Galileo Testnet',
13
+ nativeCurrency: { name: '0G', symbol: '0G', decimals: 18 },
14
+ rpcUrls: {
15
+ default: { http: ['https://evmrpc-testnet.0g.ai'] },
16
+ },
17
+ blockExplorers: {
18
+ default: { name: '0G Scan', url: 'https://chainscan.0g.ai' },
19
+ },
20
+ } as const;
21
+
22
+ /**
23
+ * 0G mainnet chain definition — a viem `Chain` (values match viem's
24
+ * `zeroGMainnet`). AgenticID is now deployed on mainnet too (chain 16661);
25
+ * fromAttestor selects this automatically from /config.chain_id.
26
+ */
27
+ export const ZERO_G_MAINNET = {
28
+ id: 16661,
29
+ name: '0G Mainnet',
30
+ nativeCurrency: { name: '0G', symbol: '0G', decimals: 18 },
31
+ rpcUrls: {
32
+ default: { http: ['https://evmrpc.0g.ai'] },
33
+ },
34
+ blockExplorers: {
35
+ default: { name: '0G BlockChain Explorer', url: 'https://chainscan.0g.ai' },
36
+ },
37
+ } as const;
38
+
39
+ /**
40
+ * Contract address set — pass one explicitly to `new AgenticID({ addresses })`.
41
+ *
42
+ * Addresses are a deployment artifact, NOT baked into the SDK: an RPC + these
43
+ * addresses fully determine the target contracts, and keeping them out of the
44
+ * library means it can't drift from what's actually deployed (a proxy upgrade or
45
+ * redeploy would silently stale a bundled constant). Copy the set you target
46
+ * from contracts/DEPLOYMENT.md §6, or load it from your own config/env.
47
+ */
48
+ export interface ContractAddresses {
49
+ /** AgenticID proxy contract address */
50
+ agenticID: `0x${string}`;
51
+ /** TEEDataVerifier proxy contract address */
52
+ teeDataVerifier: `0x${string}`;
53
+ /** VerifiedFeedbackRegistry proxy — TEE marks over the canonical 8004 reputation registry (which is discovered FROM this contract via getCanonicalReputation) */
54
+ verifiedFeedback: `0x${string}`;
55
+ /** FeedbackBatcher — EIP-7702 delegate making giveFeedback+attest atomic.
56
+ * Optional: only advertised on 7702-enabled chains; absent/zero → the SDK
57
+ * uses the sequential two-tx flow. */
58
+ feedbackBatcher?: `0x${string}`;
59
+ /** CloneGate — policy-mode cloning satellite (issue #133). Optional:
60
+ * absent/zero → setCloneAuthorizer/contract-mode clone are unavailable
61
+ * in this environment. */
62
+ cloneGate?: `0x${string}`;
63
+ /** TappRegistry — trust-root acknowledgement (ack) */
64
+ tappRegistry: `0x${string}`;
65
+ /** SandboxServing — prepaid sandbox balance (deposit) */
66
+ sandboxServing: `0x${string}`;
67
+ }
68
+
69
+ /**
70
+ * Default RPC URL for the 0G Galileo Testnet (override via `AgenticID({ rpcUrl })`).
71
+ */
72
+ export const RPC_URL = 'https://evmrpc-testnet.0g.ai';
73
+
74
+ /**
75
+ * Chain ID for the 0G Galileo Testnet.
76
+ */
77
+ export const CHAIN_ID = 16602;
78
+
79
+ /**
80
+ * `waitForTransactionReceipt` options tuned for 0G: receipt availability can lag
81
+ * a few blocks after a tx lands, and the RPC occasionally 404s the tx before it
82
+ * propagates. A generous timeout + retries avoids spurious
83
+ * "transaction receipt could not be found" failures on txs that actually landed.
84
+ */
85
+ export const RECEIPT_WAIT = {
86
+ timeout: 120_000,
87
+ pollingInterval: 2_000,
88
+ // 0G's load-balanced RPC serves not-found for already-mined txs from
89
+ // lagging nodes. viem's replacement-detection branch is the real hazard:
90
+ // once `getTransaction` succeeds, a later not-found `getTransactionReceipt`
91
+ // no longer takes the retry-tolerant path — it treats the original tx as
92
+ // its own "replacement" and re-fetches the receipt WITH NO RETRY WRAPPER,
93
+ // so a single lagging node rejects the whole wait with a raw
94
+ // TransactionReceiptNotFoundError (retryCount never applies). We don't rely
95
+ // on repriced/cancelled detection, so turn the branch off: a not-found
96
+ // receipt then just waits for the next poll tick until `timeout`.
97
+ checkReplacement: false,
98
+ // Backstop for the plain not-found path (retryCount × retryDelay tolerance),
99
+ // aligned with the overall timeout (60 × 2s = 120s).
100
+ retryCount: 60,
101
+ retryDelay: 2_000,
102
+ } as const;
103
+
104
+ /** This SDK's own version. Kept in lockstep with package.json by a test —
105
+ * a runtime package.json read would break browser bundles, so a constant. */
106
+ export const SDK_VERSION = '0.2.0';
package/src/context.ts ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * @file context.ts
3
+ * @description Shared config + runtime context for the AgenticID facade and its
4
+ * internal per-contract clients. Constructed once; passed to each sub-client.
5
+ */
6
+
7
+ import {
8
+ createPublicClient,
9
+ createWalletClient,
10
+ http,
11
+ type Account,
12
+ type Chain,
13
+ type PublicClient,
14
+ type WalletClient,
15
+ } from 'viem';
16
+ import { privateKeyToAccount } from 'viem/accounts';
17
+ import { ZERO_G_TESTNET, RPC_URL, type ContractAddresses } from './constants';
18
+
19
+ /** Public config for `new AgenticID(config)`. */
20
+ export interface AgenticIDConfig {
21
+ /** RPC endpoint. Defaults to the 0G Galileo testnet RPC. */
22
+ rpcUrl?: string;
23
+ /** viem chain. Defaults to 0G Galileo (chainId 16602). */
24
+ chain?: Chain;
25
+ /** Contract addresses — required; passed explicitly (from DEPLOYMENT.md §6 / your config). */
26
+ addresses: ContractAddresses;
27
+ /** Attestor base URL — required for agent.deploy / agent.clone. */
28
+ attestorUrl?: string;
29
+ /**
30
+ * Signer for writes. A private key (`0x…`) or a viem `Account`. When set, the
31
+ * SDK builds the wallet client for you from the rpcUrl + chain — you don't
32
+ * need to construct one. Omit for a read-only client.
33
+ */
34
+ account?: Account | `0x${string}`;
35
+ /**
36
+ * Bring-your-own wallet client (e.g. an injected browser wallet). Optional —
37
+ * usually you just pass `account`. When set, its account is used for writes.
38
+ */
39
+ walletClient?: WalletClient;
40
+ /**
41
+ * Trust-root component appIds acknowledged by `sandbox.ack()`. Defaults to
42
+ * the standard set (attestor / kms / sandbox provider).
43
+ */
44
+ componentAppIds?: string[];
45
+ /**
46
+ * Sticky memory for the secret-env scheme (issue #166): once an attestor
47
+ * has advertised `secret_env_scheme`, its later absence is treated as
48
+ * tampering and refused (`scheme_withdrawn`) rather than silently falling
49
+ * back to a clear-text key. Every client remembers within its own
50
+ * lifetime; supply this store to remember across processes (the CLI backs
51
+ * it with a file). `seen` answers whether the URL ever advertised the
52
+ * scheme; `record` is called when it does.
53
+ */
54
+ secretEnvPin?: {
55
+ seen(attestorUrl: string): boolean | Promise<boolean>;
56
+ record(attestorUrl: string): void | Promise<void>;
57
+ };
58
+ }
59
+
60
+ /** The slice of the attestor's GET /config the SDK auto-configures from. */
61
+ export interface AttestorPublicConfig {
62
+ attestor_app_id?: string;
63
+ kms_app_id?: string;
64
+ sandbox_app_id?: string;
65
+ sandbox_endpoint?: string;
66
+ sandbox_provider_addr?: `0x${string}`;
67
+ sandbox_serving_addr?: `0x${string}`;
68
+ /** Default sealed image when a framework declares none. */
69
+ sandbox_snapshot?: string;
70
+ /** Selectable frameworks + the sealed image each needs (`image` omitted →
71
+ * `sandbox_snapshot`). The SDK resolves a deploy's image from here. */
72
+ frameworks?: Array<{ name: string; image?: string }>;
73
+ /** Present when this attestor's sealed images open a sealed secret env
74
+ * (`'agent-seal-ecies-v1'`, issue #166): start/reset/retry then seal the
75
+ * inference key to the agent instead of signing it in clear. */
76
+ secret_env_scheme?: string;
77
+ inference_capabilities?: Array<{ image: string; providers: string[]; secret_env_versions: number[]; formats?: string[] }>;
78
+ provider_registry_schema?: number;
79
+ provider_registry_version?: number;
80
+ provider_registry_digest?: string;
81
+ }
82
+
83
+ /** Resolved context shared by the internal clients. */
84
+ export interface Ctx {
85
+ publicClient: PublicClient;
86
+ walletClient?: WalletClient;
87
+ account?: Account;
88
+ chain: Chain;
89
+ addresses: ContractAddresses;
90
+ attestorUrl?: string;
91
+ componentAppIds: string[];
92
+ /** True when the caller passed componentAppIds explicitly — explicit
93
+ * config always beats the attestor /config auto-discovery. */
94
+ componentAppIdsExplicit: boolean;
95
+ /** Lazy, cached fetch of the attestor's GET /config (null when no
96
+ * attestorUrl is configured or the fetch fails). Environment-specific
97
+ * values (component appIds, sandbox provider) default from here so
98
+ * callers don't hand-copy them per deployment — the hardcoded-default
99
+ * footgun that made ack() revert "app not found" on non-prod envs. */
100
+ attestorConfig: () => Promise<AttestorPublicConfig | null>;
101
+ /** See {@link AgenticIDConfig.secretEnvPin}. */
102
+ secretEnvPin?: {
103
+ seen(attestorUrl: string): boolean | Promise<boolean>;
104
+ record(attestorUrl: string): void | Promise<void>;
105
+ };
106
+ }
107
+
108
+ const DEFAULT_COMPONENT_APP_IDS = ['0g-attestor', '0g-kms', '0g-sandbox-provider'];
109
+
110
+ export function buildCtx(config: AgenticIDConfig): Ctx {
111
+ const chain = (config.chain ?? ZERO_G_TESTNET) as Chain;
112
+ const rpcUrl = config.rpcUrl ?? RPC_URL;
113
+
114
+ // Resolve the signer + wallet client. A bring-your-own walletClient wins; else
115
+ // build one from `account` (a private key string or a viem Account) — so the
116
+ // caller only needs to supply an RPC + a key, not a hand-built viem client.
117
+ let account: Account | undefined;
118
+ let walletClient: WalletClient | undefined;
119
+ if (config.walletClient) {
120
+ walletClient = config.walletClient;
121
+ account =
122
+ config.walletClient.account ??
123
+ (typeof config.account === 'string' ? privateKeyToAccount(config.account) : config.account);
124
+ } else if (config.account) {
125
+ account = typeof config.account === 'string' ? privateKeyToAccount(config.account) : config.account;
126
+ walletClient = createWalletClient({ account, chain, transport: http(rpcUrl) });
127
+ }
128
+
129
+ // One shared, memoized /config fetch per Ctx. Failure memoizes null —
130
+ // callers fall back to explicit config / built-in defaults.
131
+ let cfgPromise: Promise<AttestorPublicConfig | null> | undefined;
132
+ const attestorUrl = config.attestorUrl?.replace(/\/$/, '');
133
+ const attestorConfig = () => {
134
+ if (!attestorUrl) return Promise.resolve(null);
135
+ cfgPromise ??= fetch(`${attestorUrl}/config`)
136
+ .then((r) => (r.ok ? (r.json() as Promise<AttestorPublicConfig>) : null))
137
+ .catch(() => null);
138
+ return cfgPromise;
139
+ };
140
+
141
+ return {
142
+ chain,
143
+ addresses: config.addresses,
144
+ attestorUrl: config.attestorUrl,
145
+ walletClient,
146
+ account,
147
+ componentAppIds: config.componentAppIds ?? DEFAULT_COMPONENT_APP_IDS,
148
+ componentAppIdsExplicit: config.componentAppIds !== undefined,
149
+ attestorConfig,
150
+ secretEnvPin: config.secretEnvPin,
151
+ publicClient: createPublicClient({ chain, transport: http(rpcUrl) }),
152
+ };
153
+ }
154
+
155
+ /** Guard used by write methods. */
156
+ export function requireWallet(ctx: Ctx): { walletClient: WalletClient; account: Account } {
157
+ if (!ctx.walletClient || !ctx.account) {
158
+ throw new Error('a walletClient + account are required for write operations');
159
+ }
160
+ return { walletClient: ctx.walletClient, account: ctx.account };
161
+ }
package/src/index.ts ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * @file index.ts
3
+ * @description Entry point for 0g-agentdna.
4
+ *
5
+ * One facade (`AgentDNA`; legacy alias `AgenticID`): intent namespaces — `agent` (lifecycle:
6
+ * deploy/clone/transfer + reads + agent-seal gas) and `reputation` (serve-proof
7
+ * + feedback), and `admin` (attestor-wide provider publication) — plus top-level `ack`/`ackStatus` (trust roots) and
8
+ * `deposit`/`getBalance` (sandbox balance). Construct once with rpc + addresses.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { AgentDNA } from '@0gfoundation/0g-agentdna';
13
+ * const ag = new AgentDNA({ addresses, account }); // addresses from DEPLOYMENT.md §6 / your config
14
+ * ```
15
+ */
16
+
17
+ // Node < 18 has no global fetch; without this guard the first bootstrap
18
+ // (fromAttestor) or chain read fails with a bare "fetch is not defined" from
19
+ // deep in the call stack. package.json `engines` isn't enforced by npm by
20
+ // default, so turn the miss into an actionable message at import time.
21
+ if (typeof (globalThis as { fetch?: unknown }).fetch !== 'function') {
22
+ throw new Error(
23
+ '0g-agentdna requires a global fetch (Node >= 18). ' +
24
+ 'On Node < 18 either upgrade Node or polyfill globalThis.fetch.',
25
+ );
26
+ }
27
+
28
+ // ── Facade + namespaces ──
29
+ export { AgenticID as AgentDNA, AgenticID, AgentApi, AdminApi, ReputationApi } from './AgenticID';
30
+ export type { DeployAccepted, WaitLevel } from './AgenticID';
31
+ export { makeAgentClient } from './AgentClient';
32
+ export type { AgentClient, AgentServiceEntry, AgentRoute, ChatMessage, ChatCompletion, AgentTask } from './AgentClient';
33
+ export { mcpServices } from './AgentClient';
34
+ export { defaultIData } from './AttestorClient';
35
+ export type { DefaultIDataParams } from './AttestorClient';
36
+ export type { AgenticIDConfig as AgentDNAConfig, AgenticIDConfig } from './context';
37
+
38
+ // ── Namespace implementation classes (advanced / typing) ──
39
+ export { SandboxClient } from './SandboxClient';
40
+ export { AgenticIDClient } from './AgenticIDClient';
41
+ export type { IntelligentDataResult } from './AgenticIDClient';
42
+ export { ReputationClient, MAX_ABS_FEEDBACK_VALUE } from './ReputationClient';
43
+ export { AttestorClient, CLONE_DOMAIN, CLONE_CONTRACT_DOMAIN, DEPLOY_DOMAIN, b64encode } from './AttestorClient';
44
+ export type { CloneParams, DeployParams, IDataInput, DeployCloneResponse } from './AttestorClient';
45
+ // Sealed secret env (issue #166): the inference key sealed to the agent's
46
+ // agentSeal key instead of riding the signed envelope in clear.
47
+ export { SECRET_ENV_SCHEME, SECRET_ENV_VAR, SecretEnvRefusedError, sealSecretEnv } from './secretEnv';
48
+ export type { SecretEnvMode, SecretEnvRefusalCode } from './secretEnv';
49
+
50
+ // ── Owner settings (the opaque-to-attestor configuration document) ──
51
+ export {
52
+ SETTINGS_DOMAIN,
53
+ THINKING_LEVELS,
54
+ SETTINGS_FIELDS,
55
+ ZG_COMPUTE_PROVIDER,
56
+ ROUTER_MODELS_URL,
57
+ canonicalSettings,
58
+ settingsAuthMessage,
59
+ SettingsConflictError,
60
+ sha256Hex,
61
+ modelAdvisory,
62
+ fetchRouterModelIds,
63
+ } from './Settings';
64
+ export type { SettingsDoc, ThinkingLevel } from './Settings';
65
+
66
+ // ── Reputation: serve-proof transport + verification ──
67
+ export {
68
+ ServeSession,
69
+ SERVE_PROOF_HEADER,
70
+ parseServeProofHeader,
71
+ proofFromResponse,
72
+ captureProof,
73
+ taskRevealOf,
74
+ proofRecordingFetch,
75
+ } from './ServeSession';
76
+ export type { ServeSessionOptions, ProofVerification, TaskExchange } from './ServeSession';
77
+
78
+ // ── ServeProof utilities ──
79
+ export {
80
+ buildServeProofMessageHash,
81
+ buildServeProofSigningHash,
82
+ buildServeProof,
83
+ signServeProof,
84
+ verifyServeProofSignature,
85
+ } from './ServeProof';
86
+ export type { BuildServeProofHashParams, BuildServeProofSigningHashParams } from './ServeProof';
87
+ export { taskHashOf, requestUriOf, requestUriCandidates } from './taskHash';
88
+
89
+ // ── Types ──
90
+ export type {
91
+ IntelligentData,
92
+ ServeProof,
93
+ Feedback,
94
+ FeedbackSummary,
95
+ ServeData,
96
+ GiveFeedbackParams,
97
+ GiveFeedbackResult,
98
+ TaskReveal,
99
+ AppendResponseParams,
100
+ ReadAllFeedbackParams,
101
+ GetSummaryParams,
102
+ } from './types';
103
+
104
+ // ── Constants ──
105
+ // Protocol-level, stable. Contract addresses are NOT exported — they're a
106
+ // deployment artifact (see contracts/DEPLOYMENT.md §6); pass them explicitly.
107
+ export {
108
+ ZERO_G_TESTNET,
109
+ ZERO_G_MAINNET,
110
+ RPC_URL,
111
+ CHAIN_ID,
112
+ RECEIPT_WAIT,
113
+ } from './constants';
114
+ export type { ContractAddresses } from './constants';
115
+
116
+ // ── ABIs (advanced usage) ──
117
+ export {
118
+ agenticIDAbi,
119
+ cloneGateAbi,
120
+ standardCloneAuthorizerAbi,
121
+ canonicalReputationAbi,
122
+ verifiedFeedbackAbi,
123
+ feedbackBatcherAbi,
124
+ tappRegistryAbi,
125
+ sandboxServingAbi,
126
+ } from './abi';
127
+
128
+ export { listInferenceProviders, inferenceProvider, routeHash } from './Providers';
129
+ export type { InferenceProvider, InferenceFormat, InferenceModel, ProviderRegistrySnapshot, ProviderRegistryPin } from './Providers';
@@ -0,0 +1,23 @@
1
+ [
2
+ {
3
+ "id": "0g-compute",
4
+ "name": "0G Compute",
5
+ "formats": ["openai", "anthropic"],
6
+ "defaultFormat": "openai",
7
+ "endpoints": {
8
+ "openai": "https://router-api.0g.ai/v1",
9
+ "anthropic": "https://router-api.0g.ai"
10
+ },
11
+ "modelCatalog": "https://router-api.0g.ai/v1/models",
12
+ "compatibility": {
13
+ "requiresStringContent": true,
14
+ "supportsStore": false,
15
+ "supportsDeveloperRole": false,
16
+ "supportsUsageInStreaming": false,
17
+ "supportsStrictMode": false,
18
+ "maxTokensField": "max_tokens"
19
+ }
20
+ },
21
+ { "id": "openai", "name": "OpenAI", "native": true, "formats": ["openai"] },
22
+ { "id": "anthropic", "name": "Anthropic", "native": true, "formats": ["anthropic"] }
23
+ ]