@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,235 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file main.ts
4
+ * @description Entry point of `0g-agentdna` — the diagnostics CLI that ships
5
+ * inside @0gfoundation/0g-agentdna (`bin` in package.json; no extra install,
6
+ * no extra deps — arg parsing is node:util's parseArgs).
7
+ *
8
+ * This file owns: argv parsing, command routing, `--help`/`--version`, and
9
+ * the single error boundary that turns any thrown CliError into the
10
+ * envelope/exit-code contract (spec v0.03 §2.2–2.3). Commands own everything
11
+ * else and never touch process.argv or process.exit.
12
+ */
13
+
14
+ import { parseArgs } from 'node:util';
15
+ import { readFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { CliError, toCliError, EXIT } from './errors';
18
+ import { emitError, print } from './envelope';
19
+ import { readEnv } from './env';
20
+ import type { CommandContext, CommandRun } from './types';
21
+ import { run as doctor } from './commands/doctor';
22
+ import { run as status } from './commands/status';
23
+ import { run as list } from './commands/list';
24
+ import { run as update } from './commands/update';
25
+ import { run as settings } from './commands/settings';
26
+ import { run as providers } from './commands/providers';
27
+ import { run as interactive } from './commands/interactive';
28
+
29
+ /** Diagnostics subcommands. Anything else (bare, or a leading agent ref)
30
+ * routes to the default interactive shell. */
31
+ const COMMANDS: Record<string, CommandRun> = { doctor, status, list, update, settings, providers };
32
+
33
+ // Help is written for LLM consumption as much as for humans: exact syntax,
34
+ // env contract, exit-code semantics, runnable examples — it is the ground
35
+ // truth an agent plans against (spec v0.03 §2.4).
36
+ const HELP = `0g-agentdna — 0G AgentDNA CLI for the AgenticID protocol
37
+ (ships with @0gfoundation/0g-agentdna; no separate install)
38
+
39
+ USAGE
40
+ 0g-agentdna [agent] [options] interactive chat (default)
41
+ 0g-agentdna <command> [options] diagnostics
42
+
43
+ INTERACTIVE (default — no command)
44
+ 0g-agentdna Open the manager REPL. Its commands:
45
+ list agents on this attestor (* = yours)
46
+ use <agentId|seal> enter YOUR agent's session, in
47
+ ANY phase (lifecycle is inside)
48
+ hello <agentId|seal> any agent's public /hello
49
+ (identity + services + proof;
50
+ banks a rating ticket if a
51
+ wallet is configured)
52
+ call <id> [path] use an agent's service (banks
53
+ a rating ticket)
54
+ rate <id> [score] rate an agent on-chain, spending
55
+ a ticket from call/hello (<1h)
56
+ deploy new-agent wizard, then chat
57
+ start/stop/reset <id> lifecycle without entering
58
+ the session (reset asks the
59
+ framework + key)
60
+ settings <id> [k=v] show/change the agent's
61
+ configuration document
62
+ balance prepaid balance + burn rate
63
+ deposit [og] fund the prepaid balance
64
+ withdraw [og] refund prepaid funds (time-
65
+ locked; bare claims)
66
+ ack acknowledge the TEE trust
67
+ root (implicit in deploy/
68
+ start/reset)
69
+ login guided setup: attestor URL,
70
+ owner key, provider, inference key (Enter
71
+ keeps current; keys echo *)
72
+ whoami · help · quit
73
+ 0g-agentdna <agent> Shortcut: use that agent directly, then drop to
74
+ the manager REPL on /back.
75
+
76
+ In a session: type to talk; Esc / Ctrl-C interrupts
77
+ the turn in flight (and cancels a /start or /reset
78
+ wait). Slash: /hello /balance /topup [og] /stop
79
+ /start /reset /settings [k=v] /agentlog [n]
80
+ /startuplog [n] /back (or /unuse) /quit. The framework (for /reset
81
+ and the chat model selector) is picked by you, never
82
+ guessed. Config persists to ~/.config/0g-agentdna
83
+ (config.json + credentials at 0600); AGENTIC_* env
84
+ vars always override the files.
85
+
86
+ COMMANDS
87
+ doctor Check every deploy prerequisite (attestor reachable, RPC,
88
+ wallet, gas, trust-root ack, sandbox balance). Each failing
89
+ item prints a remedy. Exit 0 all green; exit 3 otherwise,
90
+ carrying the FIRST failing check's code. Diagnostics only:
91
+ the ack/deposit remedies are transactions (they need gas)
92
+ executed via the deploy console or the SDK, not this CLI.
93
+ status <agent> One agent's full picture: phase, agentId/sealId/agentSeal,
94
+ url, failure reason. <agent> is a decimal agentId (33) or a
95
+ 0x… sealId — the CLI converts between them for you.
96
+ list List deployments. --mine (owner-signed, needs
97
+ AGENTIC_PRIVATE_KEY) adds owner-only fields such as the
98
+ failure reason and sandboxId.
99
+ settings <agent> [k=v …]
100
+ Show the agent's configuration document (which model it
101
+ thinks with, and how hard); with key=value assignments,
102
+ change it. Keys: provider, model, thinking (low|high|max),
103
+ others (opaque JSON for that framework's own knobs —
104
+ quote it: others='{"a": 1}'). Assignments merge into the
105
+ stored document; an empty value (thinking=) clears a field.
106
+ The document is the owner's, so BOTH reading and writing
107
+ are owner-signed and need AGENTIC_PRIVATE_KEY. A write is a
108
+ compare-and-swap against the version just read: if another
109
+ client changed the document meanwhile, it is refused (exit
110
+ 3, SETTINGS_CONFLICT) rather than overwriting them. The
111
+ model advisory uses its provider catalog. Provider changes
112
+ need a matching key and image support, then require reset.
113
+ providers Read the platform provider registry (--json for export).
114
+ update Self-update: compare against the npm registry and
115
+ npm install -g the latest (a git-checkout/npm-link copy
116
+ is reported, not overwritten). --json only reports.
117
+
118
+ OPTIONS
119
+ --json Machine output: stdout carries exactly one
120
+ {ok, data | error} envelope; all progress goes to stderr.
121
+ error = {code, message, remedy?, details?}. Bigints are
122
+ decimal strings; absent values are null, not omitted.
123
+ doctor packs its per-check results (status pass|fail|skip)
124
+ under (data|error.details).checks.
125
+ --mine (list) only deployments owned by AGENTIC_PRIVATE_KEY.
126
+ --phase <p> (list) filter: deploying|running|stopped|offline|failed.
127
+ --help Show this help.
128
+ --version Print the package version (identical to the SDK's).
129
+
130
+ ENVIRONMENT
131
+ AGENTIC_ATTESTOR_URL required. Attestor base URL — one URL selects the
132
+ whole environment (contracts, RPC, appIds).
133
+ AGENTIC_PRIVATE_KEY optional. Owner key (0x… hex). Env only — there is
134
+ deliberately no flag for it.
135
+ AGENTIC_RPC_URL optional. Overrides the RPC the attestor advertises.
136
+ AGENTIC_API_KEY optional. Inference key for deploy/reset; overrides
137
+ the one stored by login.
138
+ AGENTIC_VERIFIED_FEEDBACK_ADDR / AGENTIC_FEEDBACK_BATCHER_ADDR
139
+ optional. Reputation-pair address overrides for
140
+ attestors whose /config doesn't advertise them yet.
141
+ The registry must be the one the agents' sealed
142
+ proxy signs serve-proofs for, or every proof fails
143
+ verification.
144
+
145
+ EXIT CODES
146
+ 0 success · 1 unknown · 2 usage error (incl. unknown command/agent — branch
147
+ on error.code to tell them apart) · 3 fixable precondition (run the error's
148
+ remedy, then retry) · 4 timeout (check again later) · 5 auth (stop)
149
+
150
+ EXAMPLES
151
+ 0g-agentdna # deploy a new agent and chat
152
+ 0g-agentdna 286 # attach to agent 286 and chat
153
+ 0g-agentdna doctor
154
+ 0g-agentdna status 33
155
+ 0g-agentdna settings 286
156
+ 0g-agentdna settings 286 model=0gm-1.0-35b-a3b thinking=high
157
+ 0g-agentdna list --mine --phase failed --json | jq -r '.data[].sealId'`;
158
+
159
+ /** Package version, read at runtime from the SDK's own package.json
160
+ * (dist/cli/main.js → ../../package.json). */
161
+ function packageVersion(): string {
162
+ const raw = readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8');
163
+ return (JSON.parse(raw) as { version: string }).version;
164
+ }
165
+
166
+ async function main(): Promise<number> {
167
+ // parseArgs throws on unknown/malformed flags — surfaced as exit 2 below.
168
+ const { values, positionals } = parseArgs({
169
+ args: process.argv.slice(2),
170
+ allowPositionals: true,
171
+ strict: true,
172
+ options: {
173
+ json: { type: 'boolean', default: false },
174
+ help: { type: 'boolean', default: false },
175
+ version: { type: 'boolean', default: false },
176
+ mine: { type: 'boolean', default: false },
177
+ phase: { type: 'string' },
178
+ },
179
+ });
180
+
181
+ if (values.version) {
182
+ print(packageVersion());
183
+ return EXIT.OK;
184
+ }
185
+ if (values.help) {
186
+ print(HELP);
187
+ return EXIT.OK;
188
+ }
189
+
190
+ // Claude-Code-style default: bare `0g-agentdna` (or with just an agent
191
+ // ref, e.g. `0g-agentdna 286`) enters the interactive chat. The
192
+ // diagnostics commands (doctor/status/list) are the only reserved words;
193
+ // an agentId is decimal and a sealId is 0x…, so neither collides with a
194
+ // command name — anything that isn't a known command routes to chat.
195
+ const [first, ...rest] = positionals;
196
+ const isCommand = !!first && first in COMMANDS;
197
+ const run = isCommand ? COMMANDS[first] : interactive;
198
+
199
+ const ctx: CommandContext = {
200
+ env: readEnv(),
201
+ json: values.json,
202
+ positionals: isCommand ? rest : positionals,
203
+ flags: { mine: values.mine, phase: values.phase },
204
+ };
205
+ await run(ctx);
206
+ return EXIT.OK;
207
+ }
208
+
209
+ // Single error boundary. `--json` is detected from raw argv so the envelope
210
+ // contract holds even when parseArgs itself is what threw.
211
+ // `process.exitCode` (not `process.exit()`): exit() can truncate stdout when
212
+ // it's a pipe — a natural exit drains the write buffers first, which the
213
+ // envelope contract depends on.
214
+ const wantJson = process.argv.includes('--json');
215
+ main()
216
+ .then((code) => {
217
+ process.exitCode = code;
218
+ })
219
+ .catch((e: unknown) => {
220
+ // node:util's parseArgs errors carry ERR_PARSE_ARGS_* codes — usage, exit 2.
221
+ const nodeCode = (e as { code?: string }).code ?? '';
222
+ // Own wording, not node:util's raw parseArgs prose (its "place it at the
223
+ // end of the command after '--'" advice means nothing to end users).
224
+ const err =
225
+ nodeCode.startsWith('ERR_PARSE_ARGS')
226
+ ? new CliError(
227
+ 'BAD_FLAG',
228
+ nodeCode === 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
229
+ ? `unknown flag: ${((e as Error).message.match(/'(--?[^']+)'/) ?? [])[1] ?? '(see --help)'}`
230
+ : 'malformed command-line arguments',
231
+ { remedy: '0g-agentdna --help' },
232
+ )
233
+ : toCliError(e);
234
+ process.exitCode = emitError(err, wantJson);
235
+ });
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @file proofs.ts
3
+ * @description The proof jar: locally saved serve-proofs ("tickets") captured
4
+ * from agent interactions, so `rate` can spend a ticket from an interaction
5
+ * that already happened — including rating an agent that has since gone
6
+ * offline. Physics of a ticket: expires one hour after issuance (the sealed
7
+ * proxy sets the deadline; the chain enforces it), single-use (signature is
8
+ * the nonce), and redeemable ONLY by the wallet named in `submitter` — so a
9
+ * jar entry leaking is harmless to anyone else.
10
+ *
11
+ * Stored next to the CLI config (`proofs.json`, 0600 out of caution). Each
12
+ * entry carries the proof AND the task-receipt materials (method/uri/body
13
+ * hashes/status) captured from the same interaction, so submission can open
14
+ * the taskHash commitment on-chain (TEE-verified endpoint).
15
+ */
16
+
17
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import type { ServeProof, TaskReveal } from '../types';
20
+ import type { ProofVerification } from '../ServeSession';
21
+ import { configPaths } from './config';
22
+
23
+ /** A saved ticket: the proof plus its receipt materials and provenance. */
24
+ export interface SavedProof {
25
+ agentId: string; // decimal string (JSON-safe bigint)
26
+ submitter: `0x${string}`; // the only wallet that can redeem it
27
+ endpoint: string; // full URL the interaction hit (for the feedback `endpoint` field)
28
+ capturedAt: number; // unix seconds
29
+ deadline: number; // unix seconds — from the proof
30
+ proof: {
31
+ agentId: string; submitter: `0x${string}`; timestamp: string; deadline: string;
32
+ taskHash: `0x${string}`; dataHashes: `0x${string}`[]; frameworkHash: `0x${string}`;
33
+ signature: `0x${string}`;
34
+ validator?: `0x${string}`; // envelope diagnostics: lets `rate` tell a registry mismatch from a bad ticket
35
+ };
36
+ task: TaskReveal;
37
+ }
38
+
39
+ function jarPath(): string {
40
+ return join(configPaths().dir, 'proofs.json');
41
+ }
42
+
43
+ function loadJar(): SavedProof[] {
44
+ const p = jarPath();
45
+ if (!existsSync(p)) return [];
46
+ try {
47
+ const all = JSON.parse(readFileSync(p, 'utf8')) as SavedProof[];
48
+ const now = Math.floor(Date.now() / 1000);
49
+ return all.filter((e) => e.deadline > now); // prune expired on load
50
+ } catch {
51
+ return [];
52
+ }
53
+ }
54
+
55
+ function writeJar(entries: SavedProof[]): void {
56
+ mkdirSync(configPaths().dir, { recursive: true });
57
+ writeFileSync(jarPath(), `${JSON.stringify(entries, null, 2)}\n`, { mode: 0o600 });
58
+ }
59
+
60
+ /** Tickets kept per (agentId, submitter). Proofs expire in ~1h anyway, so
61
+ * the cap only bounds the file against pathological call loops. */
62
+ const MAX_TICKETS_PER_PAIR = 5;
63
+
64
+ /** Bank a ticket (append — one proof backs one rating, several interactions
65
+ * with one agent yield several independently spendable tickets). */
66
+ export function saveProof(proof: ServeProof, task: TaskReveal, endpoint: string): void {
67
+ const entry: SavedProof = {
68
+ agentId: proof.agentId.toString(),
69
+ submitter: proof.submitter,
70
+ endpoint,
71
+ capturedAt: Math.floor(Date.now() / 1000),
72
+ deadline: Number(proof.deadline),
73
+ proof: {
74
+ agentId: proof.agentId.toString(),
75
+ submitter: proof.submitter,
76
+ timestamp: proof.timestamp.toString(),
77
+ deadline: proof.deadline.toString(),
78
+ taskHash: proof.taskHash,
79
+ dataHashes: proof.dataHashes,
80
+ frameworkHash: proof.frameworkHash,
81
+ signature: proof.signature,
82
+ ...(proof.validator ? { validator: proof.validator } : {}),
83
+ },
84
+ task,
85
+ };
86
+ const all = loadJar();
87
+ const mine = all.filter(
88
+ (e) => e.agentId === entry.agentId && e.submitter.toLowerCase() === entry.submitter.toLowerCase(),
89
+ );
90
+ const others = all.filter((e) => !mine.includes(e));
91
+ // newest kept; oldest dropped past the cap
92
+ const kept = [...mine, entry]
93
+ .sort((a, b) => b.capturedAt - a.capturedAt)
94
+ .slice(0, MAX_TICKETS_PER_PAIR);
95
+ writeJar([...others, ...kept]);
96
+ }
97
+
98
+ /** All unexpired tickets for (agentId, wallet), newest first — with a
99
+ * mining-time margin so a ticket seconds from expiry isn't offered. */
100
+ export function listProofs(agentId: bigint, wallet: `0x${string}`, marginSeconds = 120): SavedProof[] {
101
+ const now = Math.floor(Date.now() / 1000);
102
+ return loadJar()
103
+ .filter(
104
+ (e) =>
105
+ e.agentId === agentId.toString() &&
106
+ e.submitter.toLowerCase() === wallet.toLowerCase() &&
107
+ e.deadline > now + marginSeconds,
108
+ )
109
+ .sort((a, b) => b.capturedAt - a.capturedAt);
110
+ }
111
+
112
+ /** Burn ONE spent (or refused) ticket, identified by its unique signature. */
113
+ export function removeProof(signature: `0x${string}`): void {
114
+ writeJar(loadJar().filter((e) => e.proof.signature !== signature));
115
+ }
116
+
117
+ /**
118
+ * Whether the registry would redeem this ticket, judged on exactly what
119
+ * VerifiedFeedbackRegistry checks: not expired, and a signature that verifies
120
+ * against the registry configured here. `dataOnChain` is NOT one of them —
121
+ * the registry never compares a proof's dataHashes with the agent's current
122
+ * iData (it records them as the version that served), so a ticket whose
123
+ * agent has since committed new state still redeems. `rate` shows that case
124
+ * as an informational note, not a failure.
125
+ */
126
+ export function ticketRedeemable(
127
+ v: Pick<ProofVerification, 'notExpired' | 'registryMatches' | 'signerMatches'>,
128
+ ): boolean {
129
+ return v.notExpired && v.registryMatches && v.signerMatches;
130
+ }
131
+
132
+ /**
133
+ * What `rate` does with a ticket that is not `ticketRedeemable`.
134
+ * `'burn'` only on a defect of the ticket itself — expired, or a signature
135
+ * that does not verify against the registry it names. `'keep'` when the
136
+ * failure is this side's configuration (no registry configured, or the
137
+ * ticket names a different one): the ticket may still redeem once that is
138
+ * fixed. `dataOnChain` never burns a ticket (see `ticketRedeemable`).
139
+ */
140
+ export function ticketDisposition(
141
+ v: Pick<ProofVerification, 'notExpired' | 'registryMatches' | 'signerMatches'>,
142
+ ): 'burn' | 'keep' {
143
+ const defect = !v.notExpired || (v.registryMatches && !v.signerMatches);
144
+ return defect ? 'burn' : 'keep';
145
+ }
146
+
147
+ /** Rehydrate the bigint fields for SDK submission. */
148
+ export function toServeProof(e: SavedProof): ServeProof {
149
+ return {
150
+ agentId: BigInt(e.proof.agentId),
151
+ submitter: e.proof.submitter,
152
+ timestamp: BigInt(e.proof.timestamp),
153
+ deadline: BigInt(e.proof.deadline),
154
+ taskHash: e.proof.taskHash,
155
+ dataHashes: e.proof.dataHashes,
156
+ frameworkHash: e.proof.frameworkHash,
157
+ signature: e.proof.signature,
158
+ ...(e.proof.validator ? { validator: e.proof.validator } : {}),
159
+ };
160
+ }
package/src/cli/ref.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @file ref.ts
3
+ * @description The unified `<agent>` reference parser — a pure function, no
4
+ * I/O — shared by every command that takes an agent argument (spec v0.03
5
+ * §3.2). One positional accepts either coordinate; the CLI converts between
6
+ * them so callers never juggle the protocol's ID system:
7
+ *
8
+ * - decimal string → agentId (ERC-721 tokenId, exists only after mint)
9
+ * - 0x + 64 hex → sealId (attestor deployment key, exists from accept)
10
+ *
11
+ * Chain resolution (agentId ⇄ sealId) lives in the commands — this module
12
+ * only classifies the input, so it is trivially unit-testable.
13
+ */
14
+
15
+ import { CliError } from './errors';
16
+
17
+ /** A classified agent reference. */
18
+ export type AgentRef =
19
+ | { kind: 'agentId'; agentId: bigint }
20
+ | { kind: 'sealId'; sealId: `0x${string}` }
21
+ /** A truncated sealId (0x + 8..63 hex) — resolved against a listing by
22
+ * unique prefix. Lets the abbreviated ids shown by `list` be pasted back
23
+ * into commands (unminted rows have no agentId, so their sealId is the
24
+ * only handle). */
25
+ | { kind: 'sealPrefix'; prefix: string };
26
+
27
+ /**
28
+ * Classify a raw `<agent>` argument. Throws `BAD_AGENT_REF` (exit 2) for
29
+ * anything that is neither a decimal agentId nor a 0x… (8..64)-hex sealId
30
+ * (shorter than 64 = prefix, matched uniquely against the listing).
31
+ */
32
+ export function parseAgentRef(input: string | undefined): AgentRef {
33
+ if (input && /^\d+$/.test(input)) {
34
+ return { kind: 'agentId', agentId: BigInt(input) };
35
+ }
36
+ if (input && /^0x[0-9a-fA-F]{64}$/.test(input)) {
37
+ return { kind: 'sealId', sealId: input as `0x${string}` };
38
+ }
39
+ if (input && /^0x[0-9a-fA-F]{8,63}$/.test(input)) {
40
+ return { kind: 'sealPrefix', prefix: input.toLowerCase() };
41
+ }
42
+ throw new CliError(
43
+ 'BAD_AGENT_REF',
44
+ input
45
+ ? `not an agent reference: "${input}" (expected a decimal agentId or a 0x… 64-hex sealId; ≥8 hex chars work as a unique prefix)`
46
+ : 'missing <agent> argument (a decimal agentId or a 0x… 64-hex sealId)',
47
+ { remedy: '0g-agentdna status 33 | 0g-agentdna status 0x<64-hex sealId>' },
48
+ );
49
+ }
50
+
51
+ /** Does `sealId` match this ref? (exact id or unique-prefix candidates —
52
+ * prefix uniqueness is the caller's job, this is the per-row predicate.) */
53
+ export function refMatchesSeal(ref: AgentRef, sealId: string): boolean {
54
+ const s = sealId.toLowerCase();
55
+ if (ref.kind === 'sealId') return s === ref.sealId.toLowerCase();
56
+ if (ref.kind === 'sealPrefix') return s.startsWith(ref.prefix);
57
+ return false;
58
+ }
package/src/cli/sdk.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @file sdk.ts
3
+ * @description Shared bootstrap: CliEnv → AgenticID facade. The single place
4
+ * the CLI constructs the SDK client — doctor/status/list all reuse it, so the
5
+ * env→client semantics can never drift between commands (this is the shared
6
+ * artifact that made B/C/D "parallel with a hidden shared piece"; it lands in
7
+ * B and the others consume it).
8
+ */
9
+
10
+ import { AgenticID } from '../AgenticID';
11
+ import { CliError } from './errors';
12
+ import { loadSecretEnvPins, recordSecretEnvPin } from './config';
13
+ import { requireAttestorUrl, requirePrivateKey, type CliEnv } from './env';
14
+
15
+ /**
16
+ * Build an SDK facade from the CLI environment.
17
+ *
18
+ * - Attestor URL is always required (one URL selects the environment).
19
+ * - The private key is strictly validated when the caller REQUIRES a wallet
20
+ * (`withWallet` — owner-signed surfaces fail loudly with exit 3 + remedy).
21
+ * Read-only callers proceed walletless on a malformed key (the caller is
22
+ * expected to warn) — public surfaces must not be hostage to a bad env var.
23
+ * - `AGENTIC_RPC_URL` overrides the attestor-advertised RPC (explicit-wins).
24
+ */
25
+ export async function buildClient(env: CliEnv, opts: { withWallet?: boolean } = {}): Promise<AgenticID> {
26
+ const attestorUrl = requireAttestorUrl(env);
27
+ // Wallet-requiring callers get the strict check (named error + remedy).
28
+ // Read-only callers proceed WALLETLESS on a malformed key instead of dying —
29
+ // public surfaces like `list`/`hello` must not be hostage to a bad env var.
30
+ const account = opts.withWallet
31
+ ? requirePrivateKey(env)
32
+ : env.privateKey && /^0x[0-9a-fA-F]{64}$/.test(env.privateKey)
33
+ ? env.privateKey
34
+ : undefined;
35
+ try {
36
+ // Address overrides for environments whose attestor /config doesn't (yet)
37
+ // advertise the reputation pair — explicit env wins over discovery. The
38
+ // registry must equal the one the sealed proxy signs serve-proofs for
39
+ // (EIP-191 v0x00 intended validator), or every proof fails verification.
40
+ const vf = process.env.AGENTIC_VERIFIED_FEEDBACK_ADDR?.trim();
41
+ const fbb = process.env.AGENTIC_FEEDBACK_BATCHER_ADDR?.trim();
42
+ const overrides = {
43
+ ...(vf ? { verifiedFeedback: vf as `0x${string}` } : {}),
44
+ ...(fbb ? { feedbackBatcher: fbb as `0x${string}` } : {}),
45
+ };
46
+ return await AgenticID.fromAttestor(attestorUrl, {
47
+ ...(account ? { account } : {}),
48
+ ...(env.rpcUrl ? { rpcUrl: env.rpcUrl } : {}),
49
+ ...(Object.keys(overrides).length ? { overrides } : {}),
50
+ // Once this machine has seen an attestor advertise secret_env_scheme,
51
+ // its absence is tampering, not a downgrade (issue #166).
52
+ secretEnvPin: {
53
+ seen: (url) => !!loadSecretEnvPins()[url],
54
+ record: (url) => recordSecretEnvPin(url),
55
+ },
56
+ });
57
+ } catch (e) {
58
+ if (e instanceof CliError) throw e;
59
+ throw new CliError(
60
+ 'ATTESTOR_UNREACHABLE',
61
+ `could not bootstrap from ${attestorUrl}/config: ${(e as Error).message}`,
62
+ { remedy: 'verify AGENTIC_ATTESTOR_URL points at a reachable attestor, then retry' },
63
+ );
64
+ }
65
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * @file settings.ts
3
+ * @description Shared pieces of the CLI's settings surface — the `key=value`
4
+ * grammar, the merge, and the rendering. Used by the `settings` command and
5
+ * by both REPL levels, so the three can never drift apart.
6
+ *
7
+ * The grammar is deliberately tiny, because the document is:
8
+ *
9
+ * settings <agent> show the current document
10
+ * settings <agent> model=0gm-1.0-35b-a3b change one field
11
+ * settings <agent> thinking= clear one field
12
+ * settings <agent> others='{"a": 1}' the framework's own opaque knobs
13
+ *
14
+ * Assignments MERGE into the stored document — the owner is editing one
15
+ * field, not re-authoring the whole thing. The wire write is still a whole
16
+ * document; the merge happens here.
17
+ *
18
+ * Quoting works at both layers: a shell hands `others='{"a": 1}'` over as
19
+ * one argument, and the REPL's own splitter (`cli/tokenize.ts`) honours the
20
+ * same quotes rather than breaking the JSON on its spaces.
21
+ */
22
+
23
+ import { CliError } from './errors';
24
+ import { SETTINGS_FIELDS, THINKING_LEVELS, type SettingsDoc, type ThinkingLevel } from '../Settings';
25
+
26
+ /** The document's named fields. `others` is opaque JSON; the rest are
27
+ * strings. Anything else a container understands is writable through the
28
+ * SDK, but not through this grammar — the CLI refuses keys it cannot
29
+ * describe, so a typo can never become a stored field. */
30
+ export const SETTINGS_KEYS = SETTINGS_FIELDS;
31
+ export type SettingsKey = (typeof SETTINGS_KEYS)[number];
32
+
33
+ /** One `key=value`. `value === undefined` means "clear this field". */
34
+ export interface Assignment {
35
+ key: SettingsKey;
36
+ value: string | ThinkingLevel | unknown | undefined;
37
+ }
38
+
39
+ const USAGE = '0g-agentdna settings <agent> [provider=… model=… thinking=low|high|max others=<json>]';
40
+
41
+ /** How to quote a JSON value, in either place it can be typed. */
42
+ const FRAMEWORK_QUOTING =
43
+ `settings <agent> others='{"key": "value"}' # quote it — inside the REPL too`;
44
+
45
+ /**
46
+ * Parse `key=value` positionals. Throws `BAD_FLAG` (exit 2) on an unknown
47
+ * key, a bad thinking level, or an `others=` value that is not JSON — all
48
+ * usage errors worth failing on before any network work.
49
+ */
50
+ export function parseAssignments(args: string[]): Assignment[] {
51
+ const out: Assignment[] = [];
52
+ for (const arg of args) {
53
+ const eq = arg.indexOf('=');
54
+ if (eq < 1) {
55
+ throw new CliError('BAD_FLAG', `not a setting assignment: "${arg}" (expected key=value)`, { remedy: USAGE });
56
+ }
57
+ const key = arg.slice(0, eq);
58
+ const raw = arg.slice(eq + 1);
59
+ if (!(SETTINGS_KEYS as readonly string[]).includes(key)) {
60
+ throw new CliError(
61
+ 'BAD_FLAG',
62
+ `unknown setting "${key}" — the platform's named fields are ${SETTINGS_KEYS.join(', ')} ` +
63
+ '(anything framework-specific goes inside others=<json>)',
64
+ { remedy: USAGE },
65
+ );
66
+ }
67
+ if (raw === '') {
68
+ out.push({ key: key as SettingsKey, value: undefined });
69
+ continue;
70
+ }
71
+ if (key === 'thinking' && !(THINKING_LEVELS as readonly string[]).includes(raw)) {
72
+ throw new CliError('BAD_FLAG', `thinking must be one of ${THINKING_LEVELS.join('|')}, got "${raw}"`, {
73
+ remedy: USAGE,
74
+ });
75
+ }
76
+ if (key === 'others') {
77
+ let parsed: unknown;
78
+ try {
79
+ parsed = JSON.parse(raw);
80
+ } catch (e) {
81
+ throw new CliError('BAD_FLAG', `others= must be JSON: ${(e as Error).message}`, {
82
+ remedy: FRAMEWORK_QUOTING,
83
+ });
84
+ }
85
+ out.push({ key, value: parsed });
86
+ continue;
87
+ }
88
+ out.push({ key: key as SettingsKey, value: raw });
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** Merge assignments onto the stored document, producing the document to write. */
94
+ export function applyAssignments(base: SettingsDoc | null, assignments: Assignment[]): SettingsDoc {
95
+ const doc: SettingsDoc = { ...(base ?? {}) };
96
+ for (const a of assignments) {
97
+ if (a.value === undefined) delete doc[a.key];
98
+ else if (a.key === 'others') doc.others = a.value;
99
+ else doc[a.key] = a.value as string & ThinkingLevel;
100
+ }
101
+ return doc;
102
+ }
103
+
104
+ /**
105
+ * Refuse a document with no model, before anything is signed.
106
+ *
107
+ * A blank model is the ONE state the container treats as fatal (two adapters
108
+ * hard-fail Start without a pin), and it is also the one state the
109
+ * last-known-good fallback cannot rescue: an agent that predates this channel
110
+ * has no stored document and no confirmed one, so a first partial edit
111
+ * (`settings 286 thinking=high`) would merge onto nothing, write
112
+ * `{"thinking":"high"}`, and take the agent down on its next boot with
113
+ * nothing to fall back to. That is a foot-gun, not a choice worth honouring —
114
+ * so name the missing field and the fix.
115
+ *
116
+ * `hadStored` distinguishes the two ways to get here, because the fix differs:
117
+ * with no stored document the user has to say which model to pin, while
118
+ * clearing `model=` out of an existing one is simply not a thing to do.
119
+ */
120
+ export function assertModelPresent(next: SettingsDoc, hadStored: boolean): void {
121
+ if (next.model?.trim()) return;
122
+ throw new CliError(
123
+ 'BAD_FLAG',
124
+ hadStored
125
+ ? 'refusing to write a document with no model — two framework adapters hard-fail startup without a model pin'
126
+ : 'this agent has no stored settings document yet, so a partial edit would write one with no model — ' +
127
+ 'and two framework adapters hard-fail startup without a model pin',
128
+ {
129
+ remedy:
130
+ 'include the model in the same command, e.g. ' +
131
+ '`settings <agent> model=0gm-1.0-35b-a3b thinking=high` (the agent\'s current model is whatever its ' +
132
+ 'image was built or last configured with — `hello <agent>` and `/agentlog` show what it is running)',
133
+ },
134
+ );
135
+ }
136
+
137
+ /**
138
+ * Human rendering: aligned `field value` lines. Named fields first, then any
139
+ * field this build does not know about — showing them is the point, since
140
+ * the container owns the vocabulary and the CLI must not pretend a newer
141
+ * setting is not there.
142
+ */
143
+ export function renderSettings(doc: SettingsDoc | null): string[] {
144
+ if (!doc || Object.keys(doc).length === 0) return ['(not configured — the agent boots on its framework defaults)'];
145
+ const show = (v: unknown): string =>
146
+ v === undefined || v === null ? '—' : typeof v === 'string' ? v : JSON.stringify(v);
147
+ const extra = Object.keys(doc).filter(
148
+ (k) => !(SETTINGS_KEYS as readonly string[]).includes(k) && doc[k] !== undefined,
149
+ );
150
+ return [...SETTINGS_KEYS.filter((k) => doc[k] !== undefined), ...extra].map(
151
+ (k) => `${k.padEnd(11)}${show(doc[k])}`,
152
+ );
153
+ }