@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.
- package/GUIDE.md +975 -0
- package/LICENSE +21 -0
- package/MIGRATION.md +84 -0
- package/MIGRATION.zh.md +70 -0
- package/PROVIDERS.md +273 -0
- package/PROVIDERS.zh.md +234 -0
- package/README.md +334 -2
- package/dist/AgentClient.d.ts +312 -0
- package/dist/AgentClient.d.ts.map +1 -0
- package/dist/AgentClient.js +715 -0
- package/dist/AgentClient.js.map +1 -0
- package/dist/AgenticID.d.ts +823 -0
- package/dist/AgenticID.d.ts.map +1 -0
- package/dist/AgenticID.js +1188 -0
- package/dist/AgenticID.js.map +1 -0
- package/dist/AgenticIDClient.d.ts +68 -0
- package/dist/AgenticIDClient.d.ts.map +1 -0
- package/dist/AgenticIDClient.js +198 -0
- package/dist/AgenticIDClient.js.map +1 -0
- package/dist/AttestorClient.d.ts +465 -0
- package/dist/AttestorClient.d.ts.map +1 -0
- package/dist/AttestorClient.js +1030 -0
- package/dist/AttestorClient.js.map +1 -0
- package/dist/Providers.d.ts +72 -0
- package/dist/Providers.d.ts.map +1 -0
- package/dist/Providers.js +182 -0
- package/dist/Providers.js.map +1 -0
- package/dist/ReputationClient.d.ts +213 -0
- package/dist/ReputationClient.d.ts.map +1 -0
- package/dist/ReputationClient.js +708 -0
- package/dist/ReputationClient.js.map +1 -0
- package/dist/SandboxClient.d.ts +107 -0
- package/dist/SandboxClient.d.ts.map +1 -0
- package/dist/SandboxClient.js +200 -0
- package/dist/SandboxClient.js.map +1 -0
- package/dist/ServeProof.d.ts +161 -0
- package/dist/ServeProof.d.ts.map +1 -0
- package/dist/ServeProof.js +230 -0
- package/dist/ServeProof.js.map +1 -0
- package/dist/ServeSession.d.ts +180 -0
- package/dist/ServeSession.d.ts.map +1 -0
- package/dist/ServeSession.js +336 -0
- package/dist/ServeSession.js.map +1 -0
- package/dist/Settings.d.ts +179 -0
- package/dist/Settings.d.ts.map +1 -0
- package/dist/Settings.js +247 -0
- package/dist/Settings.js.map +1 -0
- package/dist/abi.d.ts +2216 -0
- package/dist/abi.d.ts.map +1 -0
- package/dist/abi.js +1248 -0
- package/dist/abi.js.map +1 -0
- package/dist/cli/commands/cells.d.ts +34 -0
- package/dist/cli/commands/cells.d.ts.map +1 -0
- package/dist/cli/commands/cells.js +66 -0
- package/dist/cli/commands/cells.js.map +1 -0
- package/dist/cli/commands/doctor.d.ts +15 -0
- package/dist/cli/commands/doctor.d.ts.map +1 -0
- package/dist/cli/commands/doctor.js +236 -0
- package/dist/cli/commands/doctor.js.map +1 -0
- package/dist/cli/commands/interactive.d.ts +107 -0
- package/dist/cli/commands/interactive.d.ts.map +1 -0
- package/dist/cli/commands/interactive.js +3034 -0
- package/dist/cli/commands/interactive.js.map +1 -0
- package/dist/cli/commands/list.d.ts +31 -0
- package/dist/cli/commands/list.d.ts.map +1 -0
- package/dist/cli/commands/list.js +115 -0
- package/dist/cli/commands/list.js.map +1 -0
- package/dist/cli/commands/providers.d.ts +3 -0
- package/dist/cli/commands/providers.d.ts.map +1 -0
- package/dist/cli/commands/providers.js +21 -0
- package/dist/cli/commands/providers.js.map +1 -0
- package/dist/cli/commands/settings.d.ts +22 -0
- package/dist/cli/commands/settings.d.ts.map +1 -0
- package/dist/cli/commands/settings.js +188 -0
- package/dist/cli/commands/settings.js.map +1 -0
- package/dist/cli/commands/status.d.ts +16 -0
- package/dist/cli/commands/status.d.ts.map +1 -0
- package/dist/cli/commands/status.js +148 -0
- package/dist/cli/commands/status.js.map +1 -0
- package/dist/cli/commands/update.d.ts +21 -0
- package/dist/cli/commands/update.d.ts.map +1 -0
- package/dist/cli/commands/update.js +95 -0
- package/dist/cli/commands/update.js.map +1 -0
- package/dist/cli/config.d.ts +73 -0
- package/dist/cli/config.d.ts.map +1 -0
- package/dist/cli/config.js +239 -0
- package/dist/cli/config.js.map +1 -0
- package/dist/cli/env.d.ts +36 -0
- package/dist/cli/env.d.ts.map +1 -0
- package/dist/cli/env.js +74 -0
- package/dist/cli/env.js.map +1 -0
- package/dist/cli/envelope.d.ts +33 -0
- package/dist/cli/envelope.d.ts.map +1 -0
- package/dist/cli/envelope.js +62 -0
- package/dist/cli/envelope.js.map +1 -0
- package/dist/cli/errors.d.ts +48 -0
- package/dist/cli/errors.d.ts.map +1 -0
- package/dist/cli/errors.js +81 -0
- package/dist/cli/errors.js.map +1 -0
- package/dist/cli/inference.d.ts +21 -0
- package/dist/cli/inference.d.ts.map +1 -0
- package/dist/cli/inference.js +60 -0
- package/dist/cli/inference.js.map +1 -0
- package/dist/cli/logo.d.ts +21 -0
- package/dist/cli/logo.d.ts.map +1 -0
- package/dist/cli/logo.js +131 -0
- package/dist/cli/logo.js.map +1 -0
- package/dist/cli/main.d.ts +14 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +223 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/proofs.d.ts +67 -0
- package/dist/cli/proofs.d.ts.map +1 -0
- package/dist/cli/proofs.js +133 -0
- package/dist/cli/proofs.js.map +1 -0
- package/dist/cli/ref.d.ts +39 -0
- package/dist/cli/ref.d.ts.map +1 -0
- package/dist/cli/ref.js +48 -0
- package/dist/cli/ref.js.map +1 -0
- package/dist/cli/sdk.d.ts +24 -0
- package/dist/cli/sdk.d.ts.map +1 -0
- package/dist/cli/sdk.js +65 -0
- package/dist/cli/sdk.js.map +1 -0
- package/dist/cli/settings.d.ts +66 -0
- package/dist/cli/settings.d.ts.map +1 -0
- package/dist/cli/settings.js +137 -0
- package/dist/cli/settings.js.map +1 -0
- package/dist/cli/tokenize.d.ts +61 -0
- package/dist/cli/tokenize.d.ts.map +1 -0
- package/dist/cli/tokenize.js +157 -0
- package/dist/cli/tokenize.js.map +1 -0
- package/dist/cli/types.d.ts +25 -0
- package/dist/cli/types.d.ts.map +1 -0
- package/dist/cli/types.js +8 -0
- package/dist/cli/types.js.map +1 -0
- package/dist/constants.d.ts +107 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +74 -0
- package/dist/constants.js.map +1 -0
- package/dist/context.d.ts +108 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +64 -0
- package/dist/context.js.map +1 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +118 -0
- package/dist/index.js.map +1 -0
- package/dist/provider-catalog.json +23 -0
- package/dist/seal.d.ts +47 -0
- package/dist/seal.d.ts.map +1 -0
- package/dist/seal.js +145 -0
- package/dist/seal.js.map +1 -0
- package/dist/secretEnv.d.ts +119 -0
- package/dist/secretEnv.d.ts.map +1 -0
- package/dist/secretEnv.js +199 -0
- package/dist/secretEnv.js.map +1 -0
- package/dist/taskHash.d.ts +39 -0
- package/dist/taskHash.d.ts.map +1 -0
- package/dist/taskHash.js +119 -0
- package/dist/taskHash.js.map +1 -0
- package/dist/types.d.ts +336 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +19 -0
- package/dist/types.js.map +1 -0
- package/package.json +75 -4
- package/scripts/sync-providers.cjs +8 -0
- package/src/AgentClient.ts +897 -0
- package/src/AgenticID.ts +1382 -0
- package/src/AgenticIDClient.ts +238 -0
- package/src/AttestorClient.ts +1306 -0
- package/src/Providers.ts +176 -0
- package/src/ReputationClient.ts +821 -0
- package/src/SandboxClient.ts +227 -0
- package/src/ServeProof.ts +290 -0
- package/src/ServeSession.ts +421 -0
- package/src/Settings.ts +296 -0
- package/src/abi.ts +1282 -0
- package/src/cli/commands/cells.ts +61 -0
- package/src/cli/commands/doctor.ts +235 -0
- package/src/cli/commands/interactive.ts +2715 -0
- package/src/cli/commands/list.ts +117 -0
- package/src/cli/commands/providers.ts +16 -0
- package/src/cli/commands/settings.ts +197 -0
- package/src/cli/commands/status.ts +170 -0
- package/src/cli/commands/update.ts +86 -0
- package/src/cli/config.ts +225 -0
- package/src/cli/env.ts +90 -0
- package/src/cli/envelope.ts +57 -0
- package/src/cli/errors.ts +114 -0
- package/src/cli/inference.ts +57 -0
- package/src/cli/logo.ts +125 -0
- package/src/cli/main.ts +235 -0
- package/src/cli/proofs.ts +160 -0
- package/src/cli/ref.ts +58 -0
- package/src/cli/sdk.ts +65 -0
- package/src/cli/settings.ts +153 -0
- package/src/cli/tokenize.ts +131 -0
- package/src/cli/types.ts +27 -0
- package/src/constants.ts +106 -0
- package/src/context.ts +161 -0
- package/src/index.ts +129 -0
- package/src/provider-catalog.json +23 -0
- package/src/seal.ts +163 -0
- package/src/secretEnv.ts +250 -0
- package/src/taskHash.ts +100 -0
- package/src/types.ts +357 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file config.ts
|
|
3
|
+
* @description Persisted CLI config so you don't re-export env vars every
|
|
4
|
+
* session. Two files under the XDG config dir
|
|
5
|
+
* (`$XDG_CONFIG_HOME/0g-agentdna`, default `~/.config/0g-agentdna`):
|
|
6
|
+
*
|
|
7
|
+
* config.json { attestorUrl, rpcUrl? } — non-secret, selects the env
|
|
8
|
+
* credentials { privateKey?, inferenceKeys? } — provider keys, chmod 0600
|
|
9
|
+
*
|
|
10
|
+
* The owner key is kept in its OWN file at 0600, not in config.json — the
|
|
11
|
+
* standard split (gh / aws / docker do the same) so a shared or
|
|
12
|
+
* world-readable config never carries the key.
|
|
13
|
+
*
|
|
14
|
+
* Environment variables always WIN over the files (AGENTIC_ATTESTOR_URL /
|
|
15
|
+
* AGENTIC_PRIVATE_KEY / AGENTIC_RPC_URL) so CI and one-off overrides work
|
|
16
|
+
* without touching disk. `readEnv` (env.ts) folds these files in as the
|
|
17
|
+
* fallback layer.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync, existsSync, renameSync, unlinkSync } from 'node:fs';
|
|
21
|
+
import { randomUUID } from 'node:crypto';
|
|
22
|
+
import { homedir } from 'node:os';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
|
|
25
|
+
export interface FileConfig {
|
|
26
|
+
attestorUrl?: string;
|
|
27
|
+
rpcUrl?: string;
|
|
28
|
+
inferenceProvider?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Resolve on-disk locations and move an existing legacy directory once.
|
|
32
|
+
* Renaming preserves credentials, proof tickets, downgrade pins, and modes.
|
|
33
|
+
* An existing AgentDNA directory always wins; the two stores are never merged. */
|
|
34
|
+
export function configPaths(env: NodeJS.ProcessEnv = process.env): { dir: string; config: string; credentials: string } {
|
|
35
|
+
const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), '.config');
|
|
36
|
+
const dir = join(base, '0g-agentdna');
|
|
37
|
+
const legacy = join(base, '0g-agenticid');
|
|
38
|
+
if (!existsSync(dir) && existsSync(legacy)) {
|
|
39
|
+
try {
|
|
40
|
+
renameSync(legacy, dir);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
// Another CLI process may have completed the same migration first.
|
|
43
|
+
if (!existsSync(dir)) {
|
|
44
|
+
const code = (error as NodeJS.ErrnoException).code ?? 'unknown';
|
|
45
|
+
throw new Error(`cannot migrate CLI config from ${legacy} to ${dir} (${code}); move the directory manually and retry`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return { dir, config: join(dir, 'config.json'), credentials: join(dir, 'credentials') };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Read config.json; missing/corrupt file → empty config (never throws). */
|
|
53
|
+
export function loadConfig(env: NodeJS.ProcessEnv = process.env): FileConfig {
|
|
54
|
+
const { config } = configPaths(env);
|
|
55
|
+
if (!existsSync(config)) return {};
|
|
56
|
+
try {
|
|
57
|
+
const c = JSON.parse(readFileSync(config, 'utf8')) as FileConfig;
|
|
58
|
+
return {
|
|
59
|
+
attestorUrl: c.attestorUrl?.replace(/\/$/, ''),
|
|
60
|
+
rpcUrl: c.rpcUrl,
|
|
61
|
+
inferenceProvider: c.inferenceProvider,
|
|
62
|
+
};
|
|
63
|
+
} catch {
|
|
64
|
+
return {};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Secret-env sticky pins (issue #166): attestor URLs that have advertised
|
|
70
|
+
* `secret_env_scheme` at least once, so a later absence is refused as
|
|
71
|
+
* tampering instead of silently downgrading to a clear-text key — across
|
|
72
|
+
* CLI invocations, not just within one process. One small file so the
|
|
73
|
+
* existing config.json load/save semantics stay untouched.
|
|
74
|
+
*/
|
|
75
|
+
export function loadSecretEnvPins(env: NodeJS.ProcessEnv = process.env): Record<string, true> {
|
|
76
|
+
const file = join(configPaths(env).dir, 'secret-env-pins.json');
|
|
77
|
+
if (!existsSync(file)) return {};
|
|
78
|
+
try {
|
|
79
|
+
return JSON.parse(readFileSync(file, 'utf8')) as Record<string, true>;
|
|
80
|
+
} catch {
|
|
81
|
+
return {};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Record that `attestorUrl` advertises the scheme. Best-effort: a failed
|
|
86
|
+
* write only costs persistence, never the call. */
|
|
87
|
+
export function recordSecretEnvPin(attestorUrl: string, env: NodeJS.ProcessEnv = process.env): void {
|
|
88
|
+
try {
|
|
89
|
+
const { dir } = configPaths(env);
|
|
90
|
+
mkdirSync(dir, { recursive: true });
|
|
91
|
+
const pins = { ...loadSecretEnvPins(env), [attestorUrl]: true as const };
|
|
92
|
+
writeFileSync(join(dir, 'secret-env-pins.json'), `${JSON.stringify(pins, null, 2)}
|
|
93
|
+
`, { mode: 0o644 });
|
|
94
|
+
} catch {
|
|
95
|
+
/* best-effort */
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Merge a patch into config.json (creating the dir), 0644. */
|
|
100
|
+
export function saveConfig(patch: FileConfig, env: NodeJS.ProcessEnv = process.env): void {
|
|
101
|
+
const { dir, config } = configPaths(env);
|
|
102
|
+
mkdirSync(dir, { recursive: true });
|
|
103
|
+
const next = { ...loadConfig(env), ...patch };
|
|
104
|
+
// drop empties so the file stays clean
|
|
105
|
+
for (const k of Object.keys(next) as (keyof FileConfig)[]) if (!next[k]) delete next[k];
|
|
106
|
+
writeFileSync(config, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o644 });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Owner key and provider-scoped inference keys, stored at 0600. */
|
|
110
|
+
export interface Credentials {
|
|
111
|
+
privateKey?: `0x${string}`;
|
|
112
|
+
inferenceKeys?: Record<string, string>;
|
|
113
|
+
/** Read-only compatibility with the old compute-only credential format. */
|
|
114
|
+
apiKey?: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function writeCredentials(next: Credentials, env: NodeJS.ProcessEnv): void {
|
|
118
|
+
const { dir, credentials } = configPaths(env);
|
|
119
|
+
mkdirSync(dir, { recursive: true });
|
|
120
|
+
const temporary = `${credentials}.${process.pid}.${randomUUID()}.tmp`;
|
|
121
|
+
try {
|
|
122
|
+
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
123
|
+
renameSync(temporary, credentials);
|
|
124
|
+
chmodSync(credentials, 0o600);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
try { unlinkSync(temporary); } catch { /* nothing was written */ }
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Old single API keys are compute keys. Migrate on first read, atomically. */
|
|
132
|
+
export function loadCredentials(env: NodeJS.ProcessEnv = process.env): Credentials {
|
|
133
|
+
const { credentials } = configPaths(env);
|
|
134
|
+
if (!existsSync(credentials)) return {};
|
|
135
|
+
let parsed: Credentials;
|
|
136
|
+
try {
|
|
137
|
+
const text = readFileSync(credentials, 'utf8').trim();
|
|
138
|
+
if (!text) return {};
|
|
139
|
+
parsed = text.startsWith('{') ? JSON.parse(text) as Credentials : { privateKey: text as `0x${string}` };
|
|
140
|
+
} catch { return {}; }
|
|
141
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
|
|
142
|
+
const privateKey = typeof parsed.privateKey === 'string' ? normalizeKey(parsed.privateKey) : null;
|
|
143
|
+
const inferenceKeys: Record<string, string> = {};
|
|
144
|
+
if (parsed.inferenceKeys && typeof parsed.inferenceKeys === 'object' && !Array.isArray(parsed.inferenceKeys)) {
|
|
145
|
+
for (const [provider, value] of Object.entries(parsed.inferenceKeys)) {
|
|
146
|
+
if (/^[a-z0-9][a-z0-9-]*$/.test(provider) && typeof value === 'string' && value.trim()) {
|
|
147
|
+
inferenceKeys[provider] = value.trim();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (typeof parsed.apiKey === 'string' && parsed.apiKey.trim() && !inferenceKeys['0g-compute']) {
|
|
152
|
+
inferenceKeys['0g-compute'] = parsed.apiKey.trim();
|
|
153
|
+
}
|
|
154
|
+
const result: Credentials = {
|
|
155
|
+
...(privateKey ? { privateKey } : {}),
|
|
156
|
+
...(Object.keys(inferenceKeys).length ? { inferenceKeys } : {}),
|
|
157
|
+
};
|
|
158
|
+
// Keep corrupt/empty documents untouched. A legacy key is removed only after
|
|
159
|
+
// the complete normalized replacement has been written successfully.
|
|
160
|
+
if (typeof parsed.apiKey === 'string' && parsed.apiKey.trim()) writeCredentials(result, env);
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function saveCredentials(patch: Credentials, env: NodeJS.ProcessEnv = process.env): void {
|
|
165
|
+
const previous = loadCredentials(env);
|
|
166
|
+
const inferenceKeys = { ...previous.inferenceKeys, ...patch.inferenceKeys };
|
|
167
|
+
if (patch.apiKey) inferenceKeys['0g-compute'] = patch.apiKey;
|
|
168
|
+
const next: Credentials = { ...previous, ...patch, ...(Object.keys(inferenceKeys).length ? { inferenceKeys } : {}) };
|
|
169
|
+
delete next.apiKey;
|
|
170
|
+
writeCredentials(next, env);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The owner key, or null. Normalizes on read (old CLI builds saved login
|
|
174
|
+
* input verbatim, so a pre-normalization file may hold a 0x-less key);
|
|
175
|
+
* an un-normalizable value passes through raw so the caller can name it. */
|
|
176
|
+
export function loadKey(env: NodeJS.ProcessEnv = process.env): `0x${string}` | null {
|
|
177
|
+
const raw = loadCredentials(env).privateKey ?? null;
|
|
178
|
+
if (!raw) return null;
|
|
179
|
+
return normalizeKey(raw) ?? raw;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Normalize a pasted private key: trims, and prepends the 0x that wallet
|
|
183
|
+
* exports (MetaMask among them) commonly omit. Returns null if it isn't a
|
|
184
|
+
* 64-hex key either way. */
|
|
185
|
+
export function normalizeKey(key: string): `0x${string}` | null {
|
|
186
|
+
const k = key.trim();
|
|
187
|
+
if (/^0x[0-9a-fA-F]{64}$/.test(k)) return k as `0x${string}`;
|
|
188
|
+
if (/^[0-9a-fA-F]{64}$/.test(k)) return `0x${k}` as `0x${string}`;
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Persist the owner key (accepts 64 hex with or without the 0x prefix). */
|
|
193
|
+
export function saveKey(key: string, env: NodeJS.ProcessEnv = process.env): void {
|
|
194
|
+
const k = normalizeKey(key);
|
|
195
|
+
if (!k) throw new Error('private key must be 64 hex chars (0x prefix optional)');
|
|
196
|
+
saveCredentials({ privateKey: k }, env);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** No provider argument retains the old compute-only helper signature. */
|
|
200
|
+
export function loadApiKey(providerOrEnv: string | NodeJS.ProcessEnv = '0g-compute', env: NodeJS.ProcessEnv = process.env): string | null {
|
|
201
|
+
const provider = typeof providerOrEnv === 'string' ? providerOrEnv : '0g-compute';
|
|
202
|
+
const source = typeof providerOrEnv === 'string' ? env : providerOrEnv;
|
|
203
|
+
return loadCredentials(source).inferenceKeys?.[provider] ?? null;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function saveApiKey(apiKey: string, env?: NodeJS.ProcessEnv): void;
|
|
207
|
+
export function saveApiKey(provider: string, apiKey: string, env?: NodeJS.ProcessEnv): void;
|
|
208
|
+
export function saveApiKey(providerOrKey: string, keyOrEnv?: string | NodeJS.ProcessEnv, env: NodeJS.ProcessEnv = process.env): void {
|
|
209
|
+
const provider = typeof keyOrEnv === 'string' ? providerOrKey : '0g-compute';
|
|
210
|
+
const key = (typeof keyOrEnv === 'string' ? keyOrEnv : providerOrKey).trim();
|
|
211
|
+
const source = typeof keyOrEnv === 'string' ? env : keyOrEnv ?? env;
|
|
212
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(provider)) throw new Error('invalid inference provider');
|
|
213
|
+
if (!key) throw new Error('api key is empty');
|
|
214
|
+
saveCredentials({ inferenceKeys: { [provider]: key } }, source);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Global legacy variables only belong to compute; new overrides are bound. */
|
|
218
|
+
export function inferenceKeyFromEnv(provider: string, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
219
|
+
const key = env.AGENTDNA_API_KEY?.trim();
|
|
220
|
+
const binding = env.AGENTDNA_API_KEY_PROVIDER?.trim();
|
|
221
|
+
if (key && !binding) throw new Error('AGENTDNA_API_KEY requires AGENTDNA_API_KEY_PROVIDER');
|
|
222
|
+
if (key && binding === provider) return key;
|
|
223
|
+
if (provider === '0g-compute') return env.AGENTIC_API_KEY?.trim() || env.API_KEY?.trim() || null;
|
|
224
|
+
return null;
|
|
225
|
+
}
|
package/src/cli/env.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file env.ts
|
|
3
|
+
* @description Environment-variable resolution — the ONLY config channel in
|
|
4
|
+
* stage 0 (spec v0.03 §2.1). No config file; and deliberately no
|
|
5
|
+
* `--private-key`-style flag, ever: argv is public (shell history, `ps`,
|
|
6
|
+
* CI logs), env is not.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { CliError } from './errors';
|
|
10
|
+
import { loadConfig, loadKey, normalizeKey } from './config';
|
|
11
|
+
|
|
12
|
+
/** Resolved CLI environment. All values come from `process.env`. */
|
|
13
|
+
export interface CliEnv {
|
|
14
|
+
/** `AGENTIC_ATTESTOR_URL` — one URL selects the whole environment
|
|
15
|
+
* (contracts, chain RPC, appIds via the attestor's GET /config). */
|
|
16
|
+
attestorUrl?: string;
|
|
17
|
+
/** `AGENTIC_PRIVATE_KEY` — optional owner key. Enables `--mine`,
|
|
18
|
+
* owner-tier failure reasons, and doctor's owner checks. */
|
|
19
|
+
privateKey?: `0x${string}`;
|
|
20
|
+
/** Where `privateKey` came from — a malformed-key error must name the
|
|
21
|
+
* right place to fix (unset env vs re-run login). */
|
|
22
|
+
privateKeySource?: 'env' | 'file';
|
|
23
|
+
/** `AGENTIC_RPC_URL` — optional RPC override (explicit-wins over the
|
|
24
|
+
* attestor /config's advertised RPC). */
|
|
25
|
+
rpcUrl?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolve the CLI environment. Environment variables WIN; the persisted
|
|
30
|
+
* config files (config.ts) are the fallback layer, so `0g-agentdna` works
|
|
31
|
+
* across sessions without re-exporting, while a one-off `AGENTIC_*=… ` or CI
|
|
32
|
+
* still overrides without touching disk.
|
|
33
|
+
*/
|
|
34
|
+
export function readEnv(env: NodeJS.ProcessEnv = process.env): CliEnv {
|
|
35
|
+
const pick = (name: string): string | undefined => {
|
|
36
|
+
const v = env[name]?.trim();
|
|
37
|
+
return v ? v : undefined;
|
|
38
|
+
};
|
|
39
|
+
const file = loadConfig(env);
|
|
40
|
+
const fileKey = loadKey(env);
|
|
41
|
+
return {
|
|
42
|
+
attestorUrl: (pick('AGENTIC_ATTESTOR_URL') ?? file.attestorUrl)?.replace(/\/$/, ''),
|
|
43
|
+
// env keys are normalized like login input (0x prefix optional); a
|
|
44
|
+
// malformed value passes through so requirePrivateKey can name the problem.
|
|
45
|
+
...((): Pick<CliEnv, 'privateKey' | 'privateKeySource'> => {
|
|
46
|
+
const raw = pick('AGENTIC_PRIVATE_KEY');
|
|
47
|
+
if (raw) return { privateKey: normalizeKey(raw) ?? (raw as `0x${string}`), privateKeySource: 'env' };
|
|
48
|
+
if (fileKey) return { privateKey: fileKey, privateKeySource: 'file' };
|
|
49
|
+
return {};
|
|
50
|
+
})(),
|
|
51
|
+
rpcUrl: pick('AGENTIC_RPC_URL') ?? file.rpcUrl,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Attestor URL or a remediable failure (exit 3) naming the exact fix. */
|
|
56
|
+
export function requireAttestorUrl(env: CliEnv): string {
|
|
57
|
+
if (!env.attestorUrl) {
|
|
58
|
+
throw new CliError('MISSING_ATTESTOR_URL', 'AGENTIC_ATTESTOR_URL is not set — the CLI cannot reach an environment without it', {
|
|
59
|
+
remedy: 'export AGENTIC_ATTESTOR_URL=https://agenticid.0g.ai # or your own attestor',
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return env.attestorUrl;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Private key or a remediable failure (exit 3) — for owner-only surfaces.
|
|
66
|
+
* Validates the format here so a malformed key fails with a clear exit-3
|
|
67
|
+
* remedy instead of a deep viem stack trace later. */
|
|
68
|
+
export function requirePrivateKey(env: CliEnv): `0x${string}` {
|
|
69
|
+
if (!env.privateKey) {
|
|
70
|
+
throw new CliError('WALLET_REQUIRED', 'this operation needs the owner wallet, and AGENTIC_PRIVATE_KEY is not set', {
|
|
71
|
+
remedy: 'export AGENTIC_PRIVATE_KEY=0x… # env only — there is no flag for this, by design',
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(env.privateKey)) {
|
|
75
|
+
// Name the actual source — blaming the env var when the bad value sits in
|
|
76
|
+
// the credentials file sends the user to `unset` something that isn't set.
|
|
77
|
+
throw new CliError(
|
|
78
|
+
'WALLET_REQUIRED',
|
|
79
|
+
env.privateKeySource === 'file'
|
|
80
|
+
? 'the saved owner key (login credentials file) is malformed (expected 64 hex chars, 0x prefix optional)'
|
|
81
|
+
: 'AGENTIC_PRIVATE_KEY is set but malformed (expected 64 hex chars, 0x prefix optional)',
|
|
82
|
+
{
|
|
83
|
+
remedy: env.privateKeySource === 'file'
|
|
84
|
+
? 'run `login` and re-enter the key'
|
|
85
|
+
: 'export AGENTIC_PRIVATE_KEY=0x<64 hex chars> # or unset it to use the login-saved key',
|
|
86
|
+
},
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
return env.privateKey;
|
|
90
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file envelope.ts
|
|
3
|
+
* @description Output discipline for the `0g-agentdna` CLI — the gene-layer
|
|
4
|
+
* contract of spec v0.03 §2.2:
|
|
5
|
+
*
|
|
6
|
+
* - stdout carries DATA ONLY. With `--json` that is exactly one
|
|
7
|
+
* `{ok, data} | {ok, error}` envelope per invocation, so
|
|
8
|
+
* `0g-agentdna … --json | jq` never sees anything else.
|
|
9
|
+
* - Human-facing progress/notes go to stderr, in both modes.
|
|
10
|
+
* - bigint values serialize as strings (JSON numbers lose precision past
|
|
11
|
+
* 2^53 — agentIds are uint256 on chain).
|
|
12
|
+
*
|
|
13
|
+
* Envelope field names are append-only: adding fields is fine, renaming or
|
|
14
|
+
* removing is a breaking change (scripts and the future skill parse these).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { CliError } from './errors';
|
|
18
|
+
|
|
19
|
+
/** JSON.stringify replacer: bigint → decimal string. */
|
|
20
|
+
export function bigintReplacer(_key: string, value: unknown): unknown {
|
|
21
|
+
return typeof value === 'bigint' ? value.toString() : value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Success envelope to stdout (JSON mode). */
|
|
25
|
+
export function emitOk(data: unknown): void {
|
|
26
|
+
process.stdout.write(JSON.stringify({ ok: true, data }, bigintReplacer) + '\n');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Error → output + exit code, honoring the mode:
|
|
31
|
+
* - JSON mode: the error envelope is DATA — it goes to stdout (a pipeline
|
|
32
|
+
* reading stdout must see why the command failed), stderr stays quiet.
|
|
33
|
+
* - Human mode: everything goes to stderr; stdout stays clean.
|
|
34
|
+
* Returns the exit code for the caller to pass to `process.exit`.
|
|
35
|
+
*/
|
|
36
|
+
export function emitError(err: CliError, json: boolean): number {
|
|
37
|
+
if (json) {
|
|
38
|
+
const error: Record<string, unknown> = { code: err.code, message: err.message };
|
|
39
|
+
if (err.remedy !== undefined) error.remedy = err.remedy;
|
|
40
|
+
if (err.details !== undefined) error.details = err.details;
|
|
41
|
+
process.stdout.write(JSON.stringify({ ok: false, error }, bigintReplacer) + '\n');
|
|
42
|
+
} else {
|
|
43
|
+
process.stderr.write(`error (${err.code}): ${err.message}\n`);
|
|
44
|
+
if (err.remedy) process.stderr.write(` fix: ${err.remedy}\n`);
|
|
45
|
+
}
|
|
46
|
+
return err.exitCode;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Human-facing note/progress line — always stderr, never stdout. */
|
|
50
|
+
export function note(message: string): void {
|
|
51
|
+
process.stderr.write(message + '\n');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Human-mode data line (tables, check lists …) — stdout, non-JSON mode only. */
|
|
55
|
+
export function print(line: string): void {
|
|
56
|
+
process.stdout.write(line + '\n');
|
|
57
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file errors.ts
|
|
3
|
+
* @description Error codes + exit-code semantics for the `0g-agentdna` CLI —
|
|
4
|
+
* part of the gene-layer contract (spec v0.03 §2.3) consumed by scripts and
|
|
5
|
+
* agents. Both the code strings and the code→exit mapping are APPEND-ONLY:
|
|
6
|
+
* adding a code is fine, renaming or renumbering is a breaking change.
|
|
7
|
+
*
|
|
8
|
+
* Exit-code semantics (what a non-JSON-parsing caller should do next):
|
|
9
|
+
* 0 — success
|
|
10
|
+
* 1 — unknown/internal error: report it, retrying won't help
|
|
11
|
+
* 2 — usage error: fix the arguments and re-run
|
|
12
|
+
* 3 — fixable precondition: run `error.remedy`, then re-run
|
|
13
|
+
* 4 — timeout: the operation may still complete; check status later
|
|
14
|
+
* 5 — auth/ownership: stop; a different key is needed
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Machine-readable error codes. Append-only — never rename. */
|
|
18
|
+
export type ErrorCode =
|
|
19
|
+
// exit 1 — unknown/internal
|
|
20
|
+
| 'UNKNOWN'
|
|
21
|
+
| 'NOT_IMPLEMENTED'
|
|
22
|
+
// exit 2 — usage
|
|
23
|
+
| 'UNKNOWN_COMMAND'
|
|
24
|
+
| 'BAD_FLAG'
|
|
25
|
+
| 'BAD_AGENT_REF'
|
|
26
|
+
| 'AGENT_NOT_FOUND'
|
|
27
|
+
// exit 3 — fixable precondition (error.remedy tells the caller how)
|
|
28
|
+
| 'MISSING_ATTESTOR_URL'
|
|
29
|
+
| 'ATTESTOR_UNREACHABLE'
|
|
30
|
+
| 'RPC_UNREACHABLE'
|
|
31
|
+
| 'WALLET_REQUIRED'
|
|
32
|
+
| 'PREFLIGHT_GAS'
|
|
33
|
+
| 'PREFLIGHT_ACK'
|
|
34
|
+
| 'PREFLIGHT_BALANCE'
|
|
35
|
+
| 'SETTINGS_CONFLICT'
|
|
36
|
+
| 'INFERENCE_KEY_REQUIRED'
|
|
37
|
+
| 'INFERENCE_PROVIDER_UNSUPPORTED'
|
|
38
|
+
// exit 4 — timeout
|
|
39
|
+
| 'TIMEOUT'
|
|
40
|
+
// exit 5 — auth/ownership
|
|
41
|
+
| 'AUTH_REJECTED';
|
|
42
|
+
|
|
43
|
+
/** Semantic exit codes (see file header for caller guidance). */
|
|
44
|
+
export const EXIT = {
|
|
45
|
+
OK: 0,
|
|
46
|
+
UNKNOWN: 1,
|
|
47
|
+
USAGE: 2,
|
|
48
|
+
REMEDIABLE: 3,
|
|
49
|
+
TIMEOUT: 4,
|
|
50
|
+
AUTH: 5,
|
|
51
|
+
} as const;
|
|
52
|
+
|
|
53
|
+
const EXIT_BY_CODE: Record<ErrorCode, number> = {
|
|
54
|
+
UNKNOWN: EXIT.UNKNOWN,
|
|
55
|
+
NOT_IMPLEMENTED: EXIT.UNKNOWN,
|
|
56
|
+
UNKNOWN_COMMAND: EXIT.USAGE,
|
|
57
|
+
BAD_FLAG: EXIT.USAGE,
|
|
58
|
+
BAD_AGENT_REF: EXIT.USAGE,
|
|
59
|
+
AGENT_NOT_FOUND: EXIT.USAGE,
|
|
60
|
+
MISSING_ATTESTOR_URL: EXIT.REMEDIABLE,
|
|
61
|
+
ATTESTOR_UNREACHABLE: EXIT.REMEDIABLE,
|
|
62
|
+
RPC_UNREACHABLE: EXIT.REMEDIABLE,
|
|
63
|
+
WALLET_REQUIRED: EXIT.REMEDIABLE,
|
|
64
|
+
PREFLIGHT_GAS: EXIT.REMEDIABLE,
|
|
65
|
+
PREFLIGHT_ACK: EXIT.REMEDIABLE,
|
|
66
|
+
PREFLIGHT_BALANCE: EXIT.REMEDIABLE,
|
|
67
|
+
// Somebody else wrote the settings document between this command's read and
|
|
68
|
+
// its write. Remediable, and the remedy is a re-run — but only after the
|
|
69
|
+
// caller has looked at `details.current`, which is why this is an error and
|
|
70
|
+
// not a silent retry.
|
|
71
|
+
SETTINGS_CONFLICT: EXIT.REMEDIABLE,
|
|
72
|
+
INFERENCE_KEY_REQUIRED: EXIT.REMEDIABLE,
|
|
73
|
+
INFERENCE_PROVIDER_UNSUPPORTED: EXIT.REMEDIABLE,
|
|
74
|
+
TIMEOUT: EXIT.TIMEOUT,
|
|
75
|
+
AUTH_REJECTED: EXIT.AUTH,
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The one error type every command throws. `main.ts` is the single place that
|
|
80
|
+
* turns it into an envelope (or a stderr line) + `process.exit`.
|
|
81
|
+
*/
|
|
82
|
+
export class CliError extends Error {
|
|
83
|
+
/** Stable machine-readable code — the contract field scripts branch on. */
|
|
84
|
+
readonly code: ErrorCode;
|
|
85
|
+
/** How to fix it. For exit-3 errors this is the whole point: a command or
|
|
86
|
+
* instruction the caller (human or agent) can act on directly. */
|
|
87
|
+
readonly remedy?: string;
|
|
88
|
+
/** Structured extras (e.g. doctor's per-check results). Must survive the
|
|
89
|
+
* bigint-safe JSON serializer in envelope.ts. */
|
|
90
|
+
readonly details?: unknown;
|
|
91
|
+
|
|
92
|
+
constructor(code: ErrorCode, message: string, opts?: { remedy?: string; details?: unknown }) {
|
|
93
|
+
super(message);
|
|
94
|
+
this.name = 'CliError';
|
|
95
|
+
this.code = code;
|
|
96
|
+
this.remedy = opts?.remedy;
|
|
97
|
+
this.details = opts?.details;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
get exitCode(): number {
|
|
101
|
+
return EXIT_BY_CODE[this.code];
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Wrap any thrown value into a CliError (unknown → exit 1). */
|
|
106
|
+
export function toCliError(e: unknown): CliError {
|
|
107
|
+
if (e instanceof CliError) return e;
|
|
108
|
+
if (e instanceof Error && (e as Error & { code?: string }).code === 'provider_binding_unsupported') {
|
|
109
|
+
return new CliError('INFERENCE_PROVIDER_UNSUPPORTED', e.message, {
|
|
110
|
+
remedy: 'ask the attestor operator to enable provider-bound credentials for this runtime image, then retry',
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return new CliError('UNKNOWN', e instanceof Error ? e.message : String(e));
|
|
114
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { AgenticID } from '../AgenticID';
|
|
2
|
+
import type { Hash } from 'viem';
|
|
3
|
+
import { inferenceKeyFromEnv, loadApiKey } from './config';
|
|
4
|
+
import { CliError } from './errors';
|
|
5
|
+
import { requiresMintFirst } from '../Providers';
|
|
6
|
+
|
|
7
|
+
/** Deploy using the current registry's routing requirements. Called after
|
|
8
|
+
* the wizard's prompts/preflight so an edited compute route is rechecked. */
|
|
9
|
+
export async function deployWithInference(ag: AgenticID, params: {
|
|
10
|
+
name: string; framework: string; provider: string; model: string;
|
|
11
|
+
provision: boolean; apiKey?: string;
|
|
12
|
+
}) {
|
|
13
|
+
const definition = (await ag.agent.refreshProviders()).find((p) => p.id === params.provider);
|
|
14
|
+
if (!definition) throw new CliError('INFERENCE_PROVIDER_UNSUPPORTED', `unknown provider: ${params.provider}`);
|
|
15
|
+
const mintFirst = requiresMintFirst(definition);
|
|
16
|
+
await ag.agent.assertProviderSupported(params.provider, { framework: params.framework });
|
|
17
|
+
const deployment = await ag.agent.deploy({
|
|
18
|
+
name: params.name,
|
|
19
|
+
description: 'deployed from 0g-agentdna',
|
|
20
|
+
framework: params.framework,
|
|
21
|
+
inference: { provider: params.provider, model: params.model },
|
|
22
|
+
...(params.provision && !mintFirst ? { sandbox: { apiKey: params.apiKey! } } : {}),
|
|
23
|
+
});
|
|
24
|
+
const mint = await ag.agent.waitForMint(deployment.sealId, { timeoutMs: 180000 });
|
|
25
|
+
if (mintFirst) {
|
|
26
|
+
await ag.agent.setSettings(deployment.sealId, { provider: params.provider, model: params.model }, { baseVersion: 0 });
|
|
27
|
+
if (params.provision) await ag.agent.start(deployment.sealId, {
|
|
28
|
+
provider: params.provider, framework: params.framework, apiKey: params.apiKey, secretEnv: 'sealed',
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return { deployment, agentId: String((mint as { agentId?: unknown }).agentId ?? mint) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function configuredInferenceKey(provider: string, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
35
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(provider)) throw new CliError('BAD_FLAG', 'invalid inference provider ID');
|
|
36
|
+
return inferenceKeyFromEnv(provider, env) || loadApiKey(provider, env);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function requireConfiguredInferenceKey(provider: string, env: NodeJS.ProcessEnv = process.env): string {
|
|
40
|
+
const key = configuredInferenceKey(provider, env);
|
|
41
|
+
if (!key) throw new CliError('INFERENCE_KEY_REQUIRED', `no API key registered for ${provider}`, {
|
|
42
|
+
remedy: `run login and register the ${provider} key, then repeat the command`,
|
|
43
|
+
});
|
|
44
|
+
return key;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A failed owner settings read must not select a different provider or key. */
|
|
48
|
+
export async function agentInferenceProvider(ag: AgenticID, sealId: Hash): Promise<string> {
|
|
49
|
+
const { settings } = await ag.agent.getSettings(sealId);
|
|
50
|
+
const provider = settings?.provider ?? '0g-compute';
|
|
51
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(provider)) throw new CliError('BAD_FLAG', 'invalid inference provider ID');
|
|
52
|
+
return provider;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function requiresProviderReset(error: unknown): boolean {
|
|
56
|
+
return /CREDENTIAL_PROVIDER_MISMATCH|CREDENTIAL_ROUTE_MISMATCH|PROVIDER_BOUND_CREDENTIAL_REQUIRED/.test(error instanceof Error ? error.message : String(error));
|
|
57
|
+
}
|
package/src/cli/logo.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file logo.ts
|
|
3
|
+
* @description Splash logo for the interactive shell: the panda (with
|
|
4
|
+
* bamboo) from the deterministic avatar generator — a faithful pixel port
|
|
5
|
+
* of `gen_panda` in attestor/crates/shared/src/avatar.rs ("Pretty SHA").
|
|
6
|
+
* Fixed pixels and colors here: this is the shell's mascot, not a
|
|
7
|
+
* seed-derived identity avatar.
|
|
8
|
+
*
|
|
9
|
+
* Rendered with half-block characters (▀/▄, two pixel rows per text
|
|
10
|
+
* line) in 256-color ANSI → 16 columns × 8 lines. Callers must gate on
|
|
11
|
+
* TTY/NO_COLOR and fall back to a plain banner.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const GS = 16;
|
|
15
|
+
type Grid = (number | null)[][];
|
|
16
|
+
|
|
17
|
+
/** avatar.rs palette indexes used by the panda, mapped to ANSI-256. */
|
|
18
|
+
const ANSI256: Record<number, number> = {
|
|
19
|
+
0: 71, // bamboo (avatar.rs "body" slot; green here)
|
|
20
|
+
3: 236, // shadow — the panda's black
|
|
21
|
+
5: 231, // white
|
|
22
|
+
7: 217, // soft — cheeks / paw pads
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function pandaGrid(): Grid {
|
|
26
|
+
const g: Grid = Array.from({ length: GS }, () => Array<number | null>(GS).fill(null));
|
|
27
|
+
const sp = (c: number, r: number, v: number) => {
|
|
28
|
+
if (r >= 0 && r < GS && c >= 0 && c < GS) g[r][c] = v;
|
|
29
|
+
};
|
|
30
|
+
const fr = (c: number, r: number, w: number, h: number, v: number) => {
|
|
31
|
+
for (let i = r; i < r + h; i++) for (let j = c; j < c + w; j++) sp(j, i, v);
|
|
32
|
+
};
|
|
33
|
+
// gen_panda, verbatim (with_bamboo = true).
|
|
34
|
+
fr(3, 1, 3, 2, 3);
|
|
35
|
+
fr(10, 1, 3, 2, 3);
|
|
36
|
+
fr(2, 2, 12, 7, 5);
|
|
37
|
+
fr(4, 3, 8, 5, 7);
|
|
38
|
+
fr(3, 3, 4, 3, 3);
|
|
39
|
+
fr(9, 3, 4, 3, 3);
|
|
40
|
+
sp(5, 4, 5);
|
|
41
|
+
sp(6, 4, 3);
|
|
42
|
+
sp(9, 4, 5);
|
|
43
|
+
sp(10, 4, 3);
|
|
44
|
+
fr(6, 7, 2, 1, 3);
|
|
45
|
+
fr(7, 8, 2, 1, 3);
|
|
46
|
+
sp(6, 9, 3);
|
|
47
|
+
sp(7, 9, 3);
|
|
48
|
+
sp(8, 9, 3);
|
|
49
|
+
sp(9, 9, 3);
|
|
50
|
+
fr(2, 9, 12, 6, 5);
|
|
51
|
+
fr(2, 10, 2, 4, 3);
|
|
52
|
+
fr(12, 10, 2, 4, 3);
|
|
53
|
+
fr(3, 14, 4, 2, 3);
|
|
54
|
+
fr(9, 14, 4, 2, 3);
|
|
55
|
+
sp(3, 15, 7);
|
|
56
|
+
sp(4, 15, 7);
|
|
57
|
+
sp(9, 15, 7);
|
|
58
|
+
sp(10, 15, 7);
|
|
59
|
+
fr(0, 5, 2, 10, 0);
|
|
60
|
+
sp(0, 7, 3);
|
|
61
|
+
sp(0, 9, 3);
|
|
62
|
+
sp(0, 11, 3);
|
|
63
|
+
sp(0, 13, 3);
|
|
64
|
+
sp(2, 11, 3);
|
|
65
|
+
sp(3, 12, 3);
|
|
66
|
+
return g;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Nearest xterm-256 color-cube index for a #rrggbb hex — the same plain
|
|
70
|
+
* 256-color escapes the panda uses, so no truecolor dependency anywhere. */
|
|
71
|
+
function hexTo256(h: string): number {
|
|
72
|
+
const lvl = (v: number) => (v < 48 ? 0 : v < 115 ? 1 : Math.min(5, Math.round((v - 35) / 40)));
|
|
73
|
+
const r = lvl(parseInt(h.slice(1, 3), 16));
|
|
74
|
+
const g = lvl(parseInt(h.slice(3, 5), 16));
|
|
75
|
+
const b = lvl(parseInt(h.slice(5, 7), 16));
|
|
76
|
+
return 16 + 36 * r + 6 * g + b;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Render a Pretty-SHA avatar SVG (the attestor's /avatar/:seed.svg — a
|
|
81
|
+
* 16×16 background rect plus 1×1 pixel rects) as 8 ANSI-256 half-block
|
|
82
|
+
* lines. Returns null when the SVG doesn't look like one.
|
|
83
|
+
*/
|
|
84
|
+
export function svgPixelLines(svg: string): string[] | null {
|
|
85
|
+
const bg = svg.match(/<rect width="16" height="16" fill="(#[0-9a-fA-F]{6})"\/>/);
|
|
86
|
+
if (!bg) return null;
|
|
87
|
+
const grid: string[][] = Array.from({ length: GS }, () => Array<string>(GS).fill(bg[1]));
|
|
88
|
+
const re = /<rect x="(\d+)" y="(\d+)" width="1" height="1" fill="(#[0-9a-fA-F]{6})"\/>/g;
|
|
89
|
+
let m: RegExpExecArray | null;
|
|
90
|
+
let n = 0;
|
|
91
|
+
while ((m = re.exec(svg))) {
|
|
92
|
+
const x = Number(m[1]);
|
|
93
|
+
const y = Number(m[2]);
|
|
94
|
+
if (x < GS && y < GS) { grid[y][x] = m[3]; n++; }
|
|
95
|
+
}
|
|
96
|
+
if (!n) return null;
|
|
97
|
+
const lines: string[] = [];
|
|
98
|
+
for (let r = 0; r < GS; r += 2) {
|
|
99
|
+
let line = '';
|
|
100
|
+
for (let c = 0; c < GS; c++) line += `\x1b[38;5;${hexTo256(grid[r][c])}m\x1b[48;5;${hexTo256(grid[r + 1][c])}m▀`;
|
|
101
|
+
lines.push(`${line}\x1b[0m`);
|
|
102
|
+
}
|
|
103
|
+
return lines;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Splash background tile — the light tint a real Pretty-SHA avatar gets
|
|
107
|
+
* (make_bg lands around L=0.92), so the panda renders as the same solid
|
|
108
|
+
* 16×8 tile the agent avatars do. */
|
|
109
|
+
const SPLASH_BG = 254;
|
|
110
|
+
|
|
111
|
+
/** The panda as 8 ANSI lines (each ends reset, no trailing newline). */
|
|
112
|
+
export function pandaLines(): string[] {
|
|
113
|
+
const g = pandaGrid();
|
|
114
|
+
const lines: string[] = [];
|
|
115
|
+
for (let r = 0; r < GS; r += 2) {
|
|
116
|
+
let line = '';
|
|
117
|
+
for (let c = 0; c < GS; c++) {
|
|
118
|
+
const top = g[r][c] != null ? ANSI256[g[r][c] as number] : SPLASH_BG;
|
|
119
|
+
const bot = g[r + 1][c] != null ? ANSI256[g[r + 1][c] as number] : SPLASH_BG;
|
|
120
|
+
line += `\x1b[38;5;${top}m\x1b[48;5;${bot}m▀`;
|
|
121
|
+
}
|
|
122
|
+
lines.push(`${line}\x1b[0m`);
|
|
123
|
+
}
|
|
124
|
+
return lines;
|
|
125
|
+
}
|