@degenly/agent 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,780 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DGAJD1: `degenly` CLI + the shared command layer (`createOps`) the MCP server (./mcp.ts) also uses.
4
+ *
5
+ * Built for an agent in a terminal:
6
+ * - one command, never a prompt, never a browser;
7
+ * - `--json` → ONE line, stable field names; every answer has `mode: "demo"` and `note`;
8
+ * - error → non-zero exit + `{"ok":false,"error":"CODE","hint":"..."}`;
9
+ * - buy / sell / quote / token take a MINT ADDRESS only (no names: a copycat coin can share a name);
10
+ * - coin names / symbols come back as `{ "untrusted": "..." }`.
11
+ *
12
+ * DEMO: no wallet, no key, no signature, no real trade. The demo record lives in `~/.degenly/demo.json` and is
13
+ * never sent anywhere. Network = Degenly's public read endpoints (./api.ts). Every demo answer: `mode: "demo"`.
14
+ *
15
+ * LIVE (DGAJ15, core only): `setup` / `pair` / `login` / `whoami`. The agent wallet is created on this computer
16
+ * (./keys.ts), requests are signed (./sign.ts) and sent to `/v1/*` (./client.ts). Every live answer:
17
+ * `mode: "live"`. No live trade command exists yet (DGAJ16). Demo and live never share a code path or a file.
18
+ */
19
+ import { readFileSync, realpathSync } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { pathToFileURL } from "node:url";
22
+ import { CREDENTIALS_PATH_TEXT, API_KEY_DISPLAY_CHARS, KEY_INPUT_MAX_BYTES, LIVE_NOT_AVAILABLE, createLiveClient, liveHint, loadCredentials, plausibleApiKey, resolveApiBase, saveCredentials } from "./client.js";
23
+ import { AGENT_WALLET_WARNING, WALLET_PATH_TEXT, createWallet, loadWallet, resolveHome } from "./keys.js";
24
+ import { API_PAIR_TS_SKEW_MS, createPairingCode, isSolanaAddress } from "./sign.js";
25
+ import { QUOTE_DAILY_MAX, QUOTE_MIN_GAP_MS, TOP_WINDOWS, checkQuoteLimit, createClient, list, parseQuote, parseSearchHit, parseTokenRow, parseTopRow, recordQuote, } from "./api.js";
26
+ import { SOL_DECIMALS, SOL_MINT, demoFill, demoNetworkLamports, formatUnits, parseSol, parseUnits } from "./demo/fill.js";
27
+ import { DEMO_START_LAMPORTS, loadDemo, resetDemo, saveDemo } from "./demo/store.js";
28
+ import { SYMBOL_MAX_CHARS, cleanText, isMint, showUntrusted, untrustedName, untrustedSymbol } from "./sanitize.js";
29
+ import { createLiveRead } from "./tools/live-read.js";
30
+ export const VERSION = "0.1.1";
31
+ export const DEMO_NOTE = "Demo trade. No real funds moved.";
32
+ export const LIVE_NOTICE = "Demo mode: 10 demo SOL, live prices, record kept only on this computer (~/.degenly/demo.json). For live mode the human runs: degenly setup --owner <main wallet address>";
33
+ export const RECORD_PATH_TEXT = "~/.degenly/demo.json";
34
+ export const TRADES_DEFAULT = 20;
35
+ export const TRADES_MAX = 200;
36
+ export const TRENDING_DEFAULT = 10;
37
+ export const TRENDING_MAX = 50;
38
+ /** Same bounds as the site's search (`SEARCH_QUERY_MIN_LEN` / `SEARCH_QUERY_MAX_LEN`, degenly/src/edge/dataApi.ts). */
39
+ export const SEARCH_MIN_CHARS = 2;
40
+ export const SEARCH_MAX_CHARS = 40;
41
+ const BPS_FULL = 10000n;
42
+ // ---- errors ----------------------------------------------------------------------------------
43
+ const HINTS = {
44
+ MINT_REQUIRED: "Pass the token's mint address (base58, 32-44 chars). Names and symbols are not accepted. Find mints with: search <text>.",
45
+ BAD_AMOUNT: "SOL amount as a decimal string, e.g. 0.1 (more than 0, at most 9 decimals).",
46
+ BAD_PERCENT: "Use all, or a percent above 0 and up to 100, e.g. 50 or 50%.",
47
+ TOO_SMALL: "The amount rounds to 0 raw units. Use a larger amount.",
48
+ BAD_ARGS: "Wrong arguments. Run: degenly help",
49
+ UNKNOWN_COMMAND: "Unknown command. Run: degenly help",
50
+ LOW_SOL: "Not enough demo SOL. Check: demo status. Start over with: demo reset (10 demo SOL).",
51
+ NO_HOLD: "No demo position in this mint, or less than requested. Check: demo status.",
52
+ STALE_QUOTE: "The price quote was older than 15 s when it was applied. Retry.",
53
+ BAD_QUOTE: "Degenly sent a quote this package cannot use. Retry later.",
54
+ RATE_LIMITED: `Wait retryAfterMs, then retry. Local cap: 1 quote per ${QUOTE_MIN_GAP_MS / 1000} s, ${QUOTE_DAILY_MAX} quotes per day.`,
55
+ TOKEN_NOT_FOUND: "Degenly has no Solana token with this mint.",
56
+ NO_ROUTE: "No route for this token and amount right now. Try a different amount later.",
57
+ TOO_SMALL_UPSTREAM: "Amount too small to quote. Use a larger amount.",
58
+ NETWORK: "Could not reach degenly.app. Check the connection and retry.",
59
+ BAD_RESPONSE: "degenly.app answered something unexpected. Retry later.",
60
+ SAVE_FAILED: `Could not write ${RECORD_PATH_TEXT}. Check disk space and permissions.`,
61
+ NOT_AVAILABLE_IN_DEMO: "Live commands do not run here. Demo commands (demo ...) use demo SOL only: no real funds.",
62
+ };
63
+ /** 0 ok · 2 usage · 3 rate limited · 4 network / Degenly side · 1 any other refusal. */
64
+ export function exitCodeFor(error) {
65
+ if (error === undefined)
66
+ return 0;
67
+ if (["BAD_ARGS", "UNKNOWN_COMMAND", "MINT_REQUIRED", "BAD_AMOUNT", "BAD_PERCENT", "TOO_SMALL", "BAD_OWNER", "KEY_ARG_REFUSED", "NO_KEY_INPUT", "KEY_FORMAT", "BAD_API_BASE", "BAD_DEGENLY_HOME"].includes(error))
68
+ return 2;
69
+ if (error === "RATE_LIMITED")
70
+ return 3;
71
+ if (["NETWORK", "BAD_RESPONSE", "UPSTREAM", "MISSING_KEY", "NOT_CONFIGURED", "CROSS_SITE"].includes(error) || error.startsWith("HTTP_"))
72
+ return 4;
73
+ return 1;
74
+ }
75
+ function okAnswer(fields) {
76
+ return { ok: true, mode: "demo", note: DEMO_NOTE, ...fields };
77
+ }
78
+ function fail(error, extra = {}) {
79
+ const hint = HINTS[error === "TOO_SMALL" && extra.upstream === true ? "TOO_SMALL_UPSTREAM" : error] ?? `Degenly answered ${error}. Retry later.`;
80
+ const rest = { ...extra };
81
+ delete rest.upstream;
82
+ return { ok: false, mode: "demo", note: DEMO_NOTE, error, hint, ...rest };
83
+ }
84
+ function fromApi(r) {
85
+ return fail(r.error, { ...(r.retryAfterMs !== undefined ? { retryAfterMs: r.retryAfterMs } : {}), ...(r.error === "TOO_SMALL" ? { upstream: true } : {}) });
86
+ }
87
+ // ---- small parsers ---------------------------------------------------------------------------
88
+ const PERCENT = /^(\d{1,3})(?:\.(\d{1,2}))?%?$/;
89
+ /** "all" → 10000; "50" / "50%" / "12.5%" → basis points of the position; anything else / 0 / > 100 → undefined. */
90
+ export function parsePercent(v) {
91
+ const s = v.trim().toLowerCase();
92
+ if (s === "all" || s === "max")
93
+ return BPS_FULL;
94
+ const m = PERCENT.exec(s);
95
+ if (!m)
96
+ return undefined;
97
+ const bps = BigInt(m[1] ?? "0") * 100n + BigInt((m[2] ?? "").padEnd(2, "0") || "0");
98
+ return bps > 0n && bps <= BPS_FULL ? bps : undefined;
99
+ }
100
+ function sol(lamports) {
101
+ return formatUnits(lamports, SOL_DECIMALS);
102
+ }
103
+ export function createOps(deps) {
104
+ const api = createClient(deps.fetch);
105
+ // one operation at a time (an MCP client may send calls in parallel; the record is read-modify-write)
106
+ let chain = Promise.resolve();
107
+ const serial = (f) => {
108
+ const run = chain.then(f, f);
109
+ chain = run.catch(() => undefined);
110
+ return run;
111
+ };
112
+ const load = () => {
113
+ const r = loadDemo(deps.home, deps.now());
114
+ const extra = {};
115
+ if (r.created)
116
+ extra.notice = LIVE_NOTICE;
117
+ if (r.recoveredFrom !== undefined)
118
+ extra.recoveredFrom = r.recoveredFrom;
119
+ return { state: r.state, extra };
120
+ };
121
+ const tokenInfo = async (mint) => {
122
+ const r = await api.tokens([mint]);
123
+ if (!r.ok)
124
+ return { ok: false, answer: fromApi(r) };
125
+ const token = list(r.data, parseTokenRow).find((t) => t.mint === mint);
126
+ return token ? { ok: true, token } : { ok: false, answer: fail("TOKEN_NOT_FOUND", { mint }) };
127
+ };
128
+ /** Decimals + display symbol of a mint: the demo position if held (no network), else `/api/data/tokens`. */
129
+ const metaFor = async (s, mint) => {
130
+ const p = s.positions[mint];
131
+ if (p)
132
+ return { ok: true, decimals: p.decimals, symbol: p.symbol };
133
+ const t = await tokenInfo(mint);
134
+ return t.ok ? { ok: true, decimals: t.token.decimals, symbol: cleanText(t.token.symbol, SYMBOL_MAX_CHARS) } : t;
135
+ };
136
+ /** One live price-only quote through the local limiter. */
137
+ const liveQuote = async (mint, side, amount, decimals) => {
138
+ const lim = checkQuoteLimit(deps.home, deps.now());
139
+ if (!lim.ok)
140
+ return { ok: false, answer: fail("RATE_LIMITED", { retryAfterMs: lim.retryAfterMs }) };
141
+ recordQuote(deps.home, deps.now());
142
+ const r = await api.quote({ mint, side, amount, decimals });
143
+ const receivedAt = deps.now();
144
+ if (!r.ok)
145
+ return { ok: false, answer: fromApi(r) };
146
+ const q = parseQuote(r.data);
147
+ const expected = side === "buy" ? { i: SOL_MINT, o: mint } : { i: mint, o: SOL_MINT };
148
+ if (!q || q.side !== side || q.inputMint !== expected.i || q.outputMint !== expected.o || q.inAmount !== amount.toString())
149
+ return { ok: false, answer: fail("BAD_QUOTE") };
150
+ return { ok: true, q, receivedAt };
151
+ };
152
+ /** Raw token units to sell: "all" / percent of the position, or (quote only) a token amount. */
153
+ const sellRaw = (s, mint, amount, decimals, allowTokenAmount) => {
154
+ const held = s.positions[mint] ? BigInt(s.positions[mint].raw) : 0n;
155
+ const bps = parsePercent(amount);
156
+ if (bps !== undefined && (amount.trim().endsWith("%") || ["all", "max"].includes(amount.trim().toLowerCase()) || !allowTokenAmount)) {
157
+ if (held <= 0n)
158
+ return { ok: false, answer: fail("NO_HOLD", { mint }) };
159
+ const raw = (held * bps) / BPS_FULL;
160
+ return raw > 0n ? { ok: true, raw } : { ok: false, answer: fail("TOO_SMALL") };
161
+ }
162
+ if (!allowTokenAmount)
163
+ return { ok: false, answer: fail("BAD_PERCENT") };
164
+ const raw = parseUnits(amount, decimals);
165
+ return raw !== undefined ? { ok: true, raw } : { ok: false, answer: fail("BAD_AMOUNT", { hint: `Token amount as a decimal string (at most ${decimals} decimals), or all, or a percent like 50%.` }) };
166
+ };
167
+ const positionsOf = (s) => Object.values(s.positions)
168
+ .sort((a, b) => a.openedAt - b.openedAt)
169
+ .map((p) => ({
170
+ mint: p.mint,
171
+ symbol: untrustedSymbol(p.symbol),
172
+ amount: formatUnits(p.raw, p.decimals),
173
+ raw: p.raw,
174
+ decimals: p.decimals,
175
+ costSol: sol(p.costLamports),
176
+ openedAt: new Date(p.openedAt).toISOString(),
177
+ }));
178
+ const trade = async (mint, side, amountArg) => {
179
+ if (!isMint(mint))
180
+ return fail("MINT_REQUIRED");
181
+ if (mint === SOL_MINT)
182
+ return fail("BAD_ARGS", { hint: "SOL is the demo balance itself; pass a token mint." });
183
+ let lamports;
184
+ if (side === "buy") {
185
+ lamports = parseSol(amountArg);
186
+ if (lamports === undefined)
187
+ return fail("BAD_AMOUNT");
188
+ }
189
+ else if (parsePercent(amountArg) === undefined) {
190
+ return fail("BAD_PERCENT");
191
+ }
192
+ const { state, extra } = load();
193
+ if (side === "buy" && lamports !== undefined && lamports > BigInt(state.balanceLamports)) {
194
+ return fail("LOW_SOL", { balanceSol: sol(state.balanceLamports), ...extra });
195
+ }
196
+ let raw;
197
+ let decimals;
198
+ let symbol;
199
+ if (side === "sell") {
200
+ const p = state.positions[mint];
201
+ if (!p)
202
+ return fail("NO_HOLD", { mint, ...extra });
203
+ const r = sellRaw(state, mint, amountArg, p.decimals, false);
204
+ if (!r.ok)
205
+ return { ...r.answer, ...extra };
206
+ raw = r.raw;
207
+ decimals = p.decimals;
208
+ symbol = p.symbol;
209
+ }
210
+ else {
211
+ const lim = checkQuoteLimit(deps.home, deps.now());
212
+ if (!lim.ok)
213
+ return fail("RATE_LIMITED", { retryAfterMs: lim.retryAfterMs, ...extra });
214
+ const m = await metaFor(state, mint);
215
+ if (!m.ok)
216
+ return { ...m.answer, ...extra };
217
+ raw = lamports ?? 0n;
218
+ decimals = m.decimals;
219
+ symbol = m.symbol;
220
+ }
221
+ const lq = await liveQuote(mint, side, raw, decimals);
222
+ if (!lq.ok)
223
+ return { ...lq.answer, ...extra };
224
+ const now = deps.now();
225
+ const r = demoFill(state, { ...lq.q, receivedAt: lq.receivedAt }, { symbol, decimals }, now);
226
+ if (!r.ok)
227
+ return fail(r.error, { mint, ...extra });
228
+ if (!saveDemo(deps.home, r.state))
229
+ return fail("SAVE_FAILED", extra);
230
+ const t = r.trade;
231
+ const net = BigInt(t.networkLamports);
232
+ const common = { side, mint, symbol: untrustedSymbol(t.symbol), tradeId: t.id, feeBps: t.feeBps, networkSol: sol(net), balanceSol: sol(r.state.balanceLamports) };
233
+ if (side === "buy") {
234
+ return okAnswer({ ...common, spentSol: sol(BigInt(t.inAmount) + net), received: formatUnits(t.outAmount, decimals), receivedRaw: t.outAmount, ...extra });
235
+ }
236
+ const left = r.state.positions[mint];
237
+ const proceeds = BigInt(t.outAmount) - net;
238
+ return okAnswer({
239
+ ...common,
240
+ sold: formatUnits(t.inAmount, decimals),
241
+ soldRaw: t.inAmount,
242
+ receivedSol: sol(proceeds > 0n ? proceeds : 0n),
243
+ realizedSol: sol(t.realizedLamports ?? "0"),
244
+ left: left ? formatUnits(left.raw, left.decimals) : "0",
245
+ ...extra,
246
+ });
247
+ };
248
+ return {
249
+ status: () => serial(async () => {
250
+ const { state, extra } = load();
251
+ return okAnswer({
252
+ balanceSol: sol(state.balanceLamports),
253
+ balanceLamports: state.balanceLamports,
254
+ startSol: sol(DEMO_START_LAMPORTS),
255
+ realizedSol: sol(state.realizedLamports),
256
+ positions: positionsOf(state),
257
+ tradeCount: state.trades.length,
258
+ record: RECORD_PATH_TEXT,
259
+ ...extra,
260
+ });
261
+ }),
262
+ quote: (mint, side, amount) => serial(async () => {
263
+ if (!isMint(mint))
264
+ return fail("MINT_REQUIRED");
265
+ if (mint === SOL_MINT)
266
+ return fail("BAD_ARGS", { hint: "SOL is the demo balance itself; pass a token mint." });
267
+ if (side !== "buy" && side !== "sell")
268
+ return fail("BAD_ARGS", { hint: "Side must be buy or sell." });
269
+ const { state, extra } = load();
270
+ let raw;
271
+ if (side === "buy") {
272
+ const l = parseSol(amount);
273
+ if (l === undefined)
274
+ return fail("BAD_AMOUNT", extra);
275
+ raw = l;
276
+ }
277
+ const lim = checkQuoteLimit(deps.home, deps.now());
278
+ if (!lim.ok)
279
+ return fail("RATE_LIMITED", { retryAfterMs: lim.retryAfterMs, ...extra });
280
+ const m = await metaFor(state, mint);
281
+ if (!m.ok)
282
+ return { ...m.answer, ...extra };
283
+ if (side === "sell") {
284
+ const r = sellRaw(state, mint, amount, m.decimals, true);
285
+ if (!r.ok)
286
+ return { ...r.answer, ...extra };
287
+ raw = r.raw;
288
+ }
289
+ else {
290
+ raw = parseSol(amount) ?? 0n;
291
+ }
292
+ const lq = await liveQuote(mint, side, raw, m.decimals);
293
+ if (!lq.ok)
294
+ return { ...lq.answer, ...extra };
295
+ const q = lq.q;
296
+ const net = demoNetworkLamports(q);
297
+ return okAnswer({
298
+ quoteOnly: true,
299
+ side,
300
+ mint,
301
+ symbol: untrustedSymbol(m.symbol),
302
+ in: side === "buy" ? sol(q.inAmount) : formatUnits(q.inAmount, m.decimals),
303
+ out: side === "buy" ? formatUnits(q.outAmount, m.decimals) : sol(q.outAmount),
304
+ inRaw: q.inAmount,
305
+ outRaw: q.outAmount,
306
+ feeBps: q.cost.degenlyFeeBps,
307
+ networkSol: sol(net),
308
+ ...(q.priceImpactPct !== undefined ? { priceImpactPct: q.priceImpactPct } : {}),
309
+ validForMs: 15_000,
310
+ ...extra,
311
+ });
312
+ }),
313
+ buy: (mint, solAmount) => serial(() => trade(mint, "buy", solAmount)),
314
+ sell: (mint, amount) => serial(() => trade(mint, "sell", amount)),
315
+ trades: (limit = TRADES_DEFAULT) => serial(async () => {
316
+ if (!Number.isInteger(limit) || limit < 1 || limit > TRADES_MAX)
317
+ return fail("BAD_ARGS", { hint: `limit must be 1-${TRADES_MAX}.` });
318
+ const { state, extra } = load();
319
+ const dec = new Map();
320
+ for (const t of state.trades)
321
+ if (t.side === "buy")
322
+ dec.set(t.mint, t.outDecimals);
323
+ for (const p of Object.values(state.positions))
324
+ dec.set(p.mint, p.decimals);
325
+ const rows = state.trades.slice(0, limit).map((t) => {
326
+ const d = dec.get(t.mint);
327
+ const net = BigInt(t.networkLamports);
328
+ const tokenRaw = t.side === "buy" ? t.outAmount : t.inAmount;
329
+ const solMoved = t.side === "buy" ? BigInt(t.inAmount) + net : BigInt(t.outAmount) - net;
330
+ return {
331
+ id: t.id,
332
+ at: new Date(t.at).toISOString(),
333
+ side: t.side,
334
+ mint: t.mint,
335
+ symbol: untrustedSymbol(t.symbol),
336
+ tokenAmount: d !== undefined ? formatUnits(tokenRaw, d) : undefined,
337
+ tokenRaw,
338
+ sol: sol(solMoved > 0n ? solMoved : 0n),
339
+ feeBps: t.feeBps,
340
+ ...(t.realizedLamports !== undefined ? { realizedSol: sol(t.realizedLamports) } : {}),
341
+ };
342
+ });
343
+ return okAnswer({ count: rows.length, total: state.trades.length, trades: rows, ...extra });
344
+ }),
345
+ reset: () => serial(async () => {
346
+ const { state, extra } = load();
347
+ const next = resetDemo(state, deps.now());
348
+ if (!saveDemo(deps.home, next))
349
+ return fail("SAVE_FAILED", extra);
350
+ return okAnswer({ balanceSol: sol(next.balanceLamports), positions: [], ...extra });
351
+ }),
352
+ token: (mint) => serial(async () => {
353
+ if (!isMint(mint))
354
+ return fail("MINT_REQUIRED");
355
+ const t = await tokenInfo(mint);
356
+ if (!t.ok)
357
+ return t.answer;
358
+ const k = t.token;
359
+ const warnings = [];
360
+ if (k.freezeAuthorityDisabled === false)
361
+ warnings.push("Freeze authority is enabled: this token can be frozen and may not be sellable.");
362
+ if (k.mintAuthorityDisabled === false)
363
+ warnings.push("Mint authority is enabled: more of this token can be created.");
364
+ return okAnswer({
365
+ mint: k.mint,
366
+ name: untrustedName(k.name),
367
+ symbol: untrustedSymbol(k.symbol),
368
+ decimals: k.decimals,
369
+ usdPrice: k.usdPrice,
370
+ mcapUsd: k.mcapUsd,
371
+ liquidityUsd: k.liquidityUsd,
372
+ volume24hUsd: k.volume24hUsd,
373
+ priceChange24hPct: k.priceChange24hPct,
374
+ holderCount: k.holderCount,
375
+ mintAuthorityDisabled: k.mintAuthorityDisabled,
376
+ freezeAuthorityDisabled: k.freezeAuthorityDisabled,
377
+ warnings,
378
+ });
379
+ }),
380
+ search: (query) => serial(async () => {
381
+ const q = query.trim();
382
+ if (q.length < SEARCH_MIN_CHARS || q.length > SEARCH_MAX_CHARS)
383
+ return fail("BAD_ARGS", { hint: `Search text must be ${SEARCH_MIN_CHARS}-${SEARCH_MAX_CHARS} characters.` });
384
+ const r = await api.search(q);
385
+ if (!r.ok)
386
+ return fromApi(r);
387
+ const results = list(r.data, parseSearchHit).map((h) => ({
388
+ mint: h.mint,
389
+ name: untrustedName(h.name),
390
+ symbol: untrustedSymbol(h.symbol),
391
+ mcapUsd: h.mcapUsd,
392
+ isVerified: h.isVerified,
393
+ isSus: h.isSus,
394
+ launchpad: h.launchpad !== undefined ? cleanText(h.launchpad, 24) : undefined,
395
+ }));
396
+ return okAnswer({ query: q, count: results.length, results, caution: "Many tokens share names. Pick by mint and check it with: token <mint>." });
397
+ }),
398
+ trending: (window = "1h", limit = TRENDING_DEFAULT) => serial(async () => {
399
+ if (!TOP_WINDOWS.includes(window))
400
+ return fail("BAD_ARGS", { hint: `window must be one of ${TOP_WINDOWS.join(", ")}.` });
401
+ if (!Number.isInteger(limit) || limit < 1 || limit > TRENDING_MAX)
402
+ return fail("BAD_ARGS", { hint: `limit must be 1-${TRENDING_MAX}.` });
403
+ const r = await api.top(window);
404
+ if (!r.ok)
405
+ return fromApi(r);
406
+ const tokens = list(r.data, parseTopRow)
407
+ .slice(0, limit)
408
+ .map((t) => ({
409
+ mint: t.mint,
410
+ name: untrustedName(t.name),
411
+ symbol: untrustedSymbol(t.symbol),
412
+ decimals: t.decimals,
413
+ usdPrice: t.usdPrice,
414
+ mcapUsd: t.mcapUsd,
415
+ volume24hUsd: t.volume24hUsd,
416
+ priceChange24hPct: t.priceChange24hPct,
417
+ }));
418
+ return okAnswer({ window, count: tokens.length, tokens });
419
+ }),
420
+ };
421
+ }
422
+ // ---- CLI -------------------------------------------------------------------------------------
423
+ export const USAGE = [
424
+ "degenly - Degenly for AI agents (demo mode: 10 demo SOL, live prices, no wallet, no real funds)",
425
+ "",
426
+ " degenly demo status demo balance + positions",
427
+ " degenly demo quote <mint> buy <sol> live price only, nothing traded",
428
+ " degenly demo quote <mint> sell <amount|N%|all>",
429
+ " degenly demo buy <mint> <sol> demo buy at the live price",
430
+ " degenly demo sell <mint> <N%|all> demo sell at the live price",
431
+ " degenly demo trades [--limit N] demo trade history (newest first)",
432
+ " degenly demo reset back to 10 demo SOL",
433
+ " degenly token <mint> name, decimals, price, audit",
434
+ " degenly search <text> find mints by name / symbol",
435
+ " degenly trending [5m|1h|6h|24h] [--limit N]",
436
+ " degenly mcp MCP stdio server (also: no arguments)",
437
+ "",
438
+ "Agent wallet (kept on this computer, ~/.degenly/agent-wallet.json):",
439
+ " degenly setup --owner <main wallet> create the agent wallet + print a pairing code",
440
+ " degenly pair --owner <main wallet> new pairing code for the existing agent wallet",
441
+ " degenly login [--key-file <path>] store the API key from stdin or a file (never an argument)",
442
+ " degenly whoami check the API key + agent wallet with Degenly",
443
+ " degenly live holdings real balances of the agent wallet",
444
+ " degenly live ledger [--limit N] confirmed Degenly trades of the agent wallet",
445
+ " degenly live quote <mint> buy <sol> real quote, nothing signed or sent",
446
+ " degenly live quote <mint> sell <N%|all>",
447
+ "",
448
+ "Add --json for one-line JSON. Mint addresses only; coin names are untrusted text.",
449
+ "Live buy / sell: MCP tools degenly_live_buy / degenly_live_sell only (the human confirms each trade).",
450
+ ].join("\n");
451
+ /** Value of a flag that takes one; the next word only if it is not itself a flag. */
452
+ function flagValue(argv, i) {
453
+ const v = argv[i + 1];
454
+ return v !== undefined && !v.startsWith("--") ? v : undefined;
455
+ }
456
+ function parseArgs(argv) {
457
+ const out = { json: false, keyArg: false, rest: [] };
458
+ for (let i = 0; i < argv.length; i++) {
459
+ const a = argv[i] ?? "";
460
+ if (a === "--json")
461
+ out.json = true;
462
+ else if (a === "--limit") {
463
+ const v = Number(argv[++i]);
464
+ if (!Number.isInteger(v))
465
+ out.bad = "--limit needs a whole number.";
466
+ else
467
+ out.limit = v;
468
+ }
469
+ else if (a.startsWith("--limit=")) {
470
+ const v = Number(a.slice("--limit=".length));
471
+ if (!Number.isInteger(v))
472
+ out.bad = "--limit needs a whole number.";
473
+ else
474
+ out.limit = v;
475
+ }
476
+ else if (a === "--owner" || a === "--key-file") {
477
+ const v = flagValue(argv, i);
478
+ if (v !== undefined)
479
+ i++;
480
+ if (a === "--owner")
481
+ out.owner = v ?? "";
482
+ else
483
+ out.keyFile = v ?? "";
484
+ }
485
+ else if (a.startsWith("--owner="))
486
+ out.owner = a.slice("--owner=".length);
487
+ else if (a.startsWith("--key-file="))
488
+ out.keyFile = a.slice("--key-file=".length);
489
+ else if (/^--(api-?)?key(=|$)/.test(a)) {
490
+ out.keyArg = true;
491
+ if (!a.includes("=") && flagValue(argv, i) !== undefined)
492
+ i++;
493
+ }
494
+ else
495
+ out.rest.push(a);
496
+ }
497
+ return out;
498
+ }
499
+ function humanValue(v) {
500
+ if (typeof v === "object" && v !== null && !Array.isArray(v) && typeof v.untrusted === "string" && Object.keys(v).length === 1) {
501
+ return showUntrusted(v);
502
+ }
503
+ if (typeof v === "object" && v !== null) {
504
+ return Object.entries(v)
505
+ .filter(([, x]) => x !== undefined)
506
+ .map(([k, x]) => `${k}=${humanValue(x)}`)
507
+ .join(" ");
508
+ }
509
+ return String(v);
510
+ }
511
+ /** Short human output: no JSON, one fact per line. */
512
+ export function humanize(title, a) {
513
+ const head = a.ok ? `${a.mode === "live" ? "LIVE" : "DEMO"} ${title}: ok (${a.note})` : `${a.mode === "live" ? "LIVE" : "DEMO"} ${title}: ${a.error ?? "ERROR"} - ${a.hint ?? ""}`;
514
+ const lines = [head];
515
+ for (const [k, v] of Object.entries(a)) {
516
+ if (["ok", "mode", "note", "error", "hint"].includes(k) || v === undefined)
517
+ continue;
518
+ if (Array.isArray(v)) {
519
+ lines.push(`${k}: ${v.length === 0 ? "none" : ""}`);
520
+ for (const item of v)
521
+ lines.push(` - ${humanValue(item)}`);
522
+ }
523
+ else
524
+ lines.push(`${k}: ${humanValue(v)}`);
525
+ }
526
+ return lines.join("\n");
527
+ }
528
+ const args = (n, r) => r.length === n;
529
+ // ---- live (DGAJ15 core: no trade command yet) --------------------------------------------------
530
+ export const LIVE_NOTE = "Live mode. The agent wallet key stays on this computer and is never sent.";
531
+ export const PAIR_NEXT_STEP = 'Next: open https://degenly.app/bot, sign in with your main wallet, choose "Pair agent" and paste the pairing code. Then run login with the API key the site shows once. Fund the agent wallet with SOL only with what you can afford to lose.';
532
+ /** Max wait for piped stdin at `login` (never a prompt: a terminal stdin is not read at all). */
533
+ export const STDIN_WAIT_MS = 5_000;
534
+ function liveOk(fields) {
535
+ return { ok: true, mode: "live", note: LIVE_NOTE, ...fields };
536
+ }
537
+ function liveFail(error, extra = {}) {
538
+ return { ok: false, mode: "live", note: LIVE_NOTE, error, hint: liveHint(error), ...extra };
539
+ }
540
+ function pairingAnswer(wallet, owner, now, created) {
541
+ const { code } = createPairingCode(wallet, owner, now);
542
+ return liveOk({
543
+ created,
544
+ address: wallet.address,
545
+ ownerWallet: owner,
546
+ pairingCode: code,
547
+ pairingCodeValidMs: API_PAIR_TS_SKEW_MS,
548
+ walletFile: WALLET_PATH_TEXT,
549
+ warning: AGENT_WALLET_WARNING,
550
+ next: PAIR_NEXT_STEP,
551
+ });
552
+ }
553
+ function ownerError(owner, agent) {
554
+ if (owner === undefined || !isSolanaAddress(owner) || owner === agent)
555
+ return liveFail("BAD_OWNER");
556
+ return undefined;
557
+ }
558
+ async function liveSetup(d, owner) {
559
+ if (d.homeError)
560
+ return liveFail(d.homeError);
561
+ const bad = ownerError(owner);
562
+ if (bad || owner === undefined)
563
+ return bad ?? liveFail("BAD_OWNER");
564
+ const c = createWallet(d.home);
565
+ if (!c.ok) {
566
+ if (c.error !== "WALLET_EXISTS")
567
+ return liveFail(c.error);
568
+ const l = loadWallet(d.home);
569
+ return liveFail("WALLET_EXISTS", l.ok ? { address: l.wallet.address } : {});
570
+ }
571
+ return pairingAnswer(c.wallet, owner, d.now(), true);
572
+ }
573
+ async function livePair(d, owner) {
574
+ if (d.homeError)
575
+ return liveFail(d.homeError);
576
+ const l = loadWallet(d.home);
577
+ if (!l.ok)
578
+ return liveFail(l.error);
579
+ const bad = ownerError(owner, l.wallet.address);
580
+ if (bad || owner === undefined)
581
+ return bad ?? liveFail("BAD_OWNER");
582
+ return pairingAnswer(l.wallet, owner, d.now(), false);
583
+ }
584
+ async function liveLogin(d, p) {
585
+ // the key is never taken from argv (shell history): any extra word or a --key flag is refused, stdin unread
586
+ if (p.keyArg || p.rest.length !== 1)
587
+ return liveFail("KEY_ARG_REFUSED");
588
+ if (d.homeError)
589
+ return liveFail(d.homeError);
590
+ const l = loadWallet(d.home);
591
+ if (!l.ok)
592
+ return liveFail(l.error);
593
+ let input;
594
+ if (p.keyFile !== undefined) {
595
+ try {
596
+ const buf = readFileSync(p.keyFile);
597
+ if (buf.length > KEY_INPUT_MAX_BYTES)
598
+ return liveFail("KEY_FORMAT");
599
+ input = buf.toString("utf8");
600
+ }
601
+ catch {
602
+ return liveFail("KEY_FILE_UNREADABLE");
603
+ }
604
+ }
605
+ else {
606
+ input = await d.readStdin();
607
+ }
608
+ const key = input.trim();
609
+ if (key === "")
610
+ return liveFail("NO_KEY_INPUT");
611
+ if (!plausibleApiKey(key))
612
+ return liveFail("KEY_FORMAT");
613
+ if (!saveCredentials(d.home, key))
614
+ return liveFail("CREDENTIALS_WRITE_FAILED");
615
+ return liveOk({ address: l.wallet.address, keyPrefix: key.slice(0, API_KEY_DISPLAY_CHARS), credentialsFile: CREDENTIALS_PATH_TEXT, next: "Check it with: degenly whoami" });
616
+ }
617
+ async function liveWhoami(d) {
618
+ if (d.homeError)
619
+ return liveFail(d.homeError);
620
+ const l = loadWallet(d.home);
621
+ if (!l.ok)
622
+ return liveFail(l.error);
623
+ const c = loadCredentials(d.home);
624
+ if (!c.ok)
625
+ return liveFail(c.error, { address: l.wallet.address });
626
+ const b = resolveApiBase(d.env);
627
+ if (!b.ok)
628
+ return liveFail(b.error);
629
+ const client = createLiveClient({ fetch: d.fetch, base: b.base, apiKey: c.apiKey, signer: l.wallet, now: d.now });
630
+ const r = await client.request("GET", "/v1/whoami");
631
+ if (!r.ok) {
632
+ const extra = { ...r.fields, status: r.status, ...(r.retryAfterMs !== undefined ? { retryAfterMs: r.retryAfterMs } : {}) };
633
+ return liveFail(r.error, r.error === "NOT_FOUND" ? { ...extra, hint: LIVE_NOT_AVAILABLE } : extra);
634
+ }
635
+ const wallet = typeof r.data.wallet === "string" ? r.data.wallet : "";
636
+ if (wallet !== l.wallet.address)
637
+ return liveFail("KEY_WALLET_MISMATCH", { address: l.wallet.address });
638
+ return liveOk({
639
+ wallet,
640
+ keyId: typeof r.data.keyId === "string" ? cleanText(r.data.keyId, 64) : undefined,
641
+ serverTs: typeof r.data.serverTs === "number" ? r.data.serverTs : undefined,
642
+ apiBase: b.base,
643
+ });
644
+ }
645
+ /**
646
+ * Runs one CLI command (never prompts). `out` = the full text to print; `code` = the exit code.
647
+ * `live` absent (demo-only callers) → the live commands keep answering NOT_AVAILABLE_IN_DEMO.
648
+ */
649
+ export async function runCli(argv, ops, live) {
650
+ const p = parseArgs(argv);
651
+ const r = p.rest;
652
+ const done = (title, a) => ({ code: a.ok ? 0 : exitCodeFor(a.error), out: p.json ? JSON.stringify(a) : humanize(title, a) });
653
+ if (p.bad !== undefined)
654
+ return done("error", fail("BAD_ARGS", { hint: p.bad }));
655
+ const [c0, c1, c2, c3, c4] = r;
656
+ if (c0 === "help" || c0 === "--help" || c0 === "-h")
657
+ return { code: 0, out: p.json ? JSON.stringify(okAnswer({ usage: USAGE })) : USAGE };
658
+ if (c0 === "version" || c0 === "--version")
659
+ return { code: 0, out: p.json ? JSON.stringify(okAnswer({ version: VERSION })) : VERSION };
660
+ if (p.keyArg)
661
+ return done("login", liveFail("KEY_ARG_REFUSED"));
662
+ if (live && (c0 === "setup" || c0 === "pair")) {
663
+ if (!args(1, r))
664
+ return done(c0, liveFail("BAD_ARGS", { hint: `Usage: degenly ${c0} --owner <main wallet address>` }));
665
+ return done(c0, c0 === "setup" ? await liveSetup(live, p.owner) : await livePair(live, p.owner));
666
+ }
667
+ if (live && c0 === "login")
668
+ return done("login", await liveLogin(live, p));
669
+ if (live && c0 === "whoami")
670
+ return done("whoami", args(1, r) ? await liveWhoami(live) : liveFail("BAD_ARGS", { hint: "Usage: degenly whoami" }));
671
+ // DGAJ16: live READ commands only (a live buy / sell needs the human confirmation form: MCP only)
672
+ if (live && c0 === "live") {
673
+ const read = createLiveRead(live);
674
+ if (c1 === "holdings" && args(2, r))
675
+ return done("live holdings", await read.holdings());
676
+ if (c1 === "ledger" && args(2, r))
677
+ return done("live ledger", await read.ledger(p.limit));
678
+ if (c1 === "quote" && args(5, r))
679
+ return done("live quote", await read.quote(c2 ?? "", c3 ?? "", c4 ?? ""));
680
+ return done("live", liveFail("BAD_ARGS", { hint: "Usage: degenly live holdings | live ledger [--limit N] | live quote <mint> buy <sol> | live quote <mint> sell <N%|all>" }));
681
+ }
682
+ if (c0 === "setup" || c0 === "login" || c0 === "live" || c0 === "pair" || c0 === "whoami")
683
+ return done(c0, fail("NOT_AVAILABLE_IN_DEMO"));
684
+ if (c0 === "demo") {
685
+ if (c1 === "status" && args(2, r))
686
+ return done("status", await ops.status());
687
+ if (c1 === "quote" && args(5, r))
688
+ return done("quote", await ops.quote(c2 ?? "", c3 ?? "", c4 ?? ""));
689
+ if (c1 === "buy" && args(4, r))
690
+ return done("buy", await ops.buy(c2 ?? "", c3 ?? ""));
691
+ if (c1 === "sell" && args(4, r))
692
+ return done("sell", await ops.sell(c2 ?? "", c3 ?? ""));
693
+ if (c1 === "trades" && args(2, r))
694
+ return done("trades", await ops.trades(p.limit));
695
+ if (c1 === "reset" && args(2, r))
696
+ return done("reset", await ops.reset());
697
+ return done("demo", fail(c1 && ["status", "quote", "buy", "sell", "trades", "reset"].includes(c1) ? "BAD_ARGS" : "UNKNOWN_COMMAND"));
698
+ }
699
+ if (c0 === "token" && args(2, r))
700
+ return done("token", await ops.token(c1 ?? ""));
701
+ if (c0 === "search" && r.length >= 2)
702
+ return done("search", await ops.search(r.slice(1).join(" ")));
703
+ if (c0 === "trending" && r.length <= 2)
704
+ return done("trending", await ops.trending(c1 ?? "1h", p.limit));
705
+ if (c0 === "token" || c0 === "search" || c0 === "trending")
706
+ return done(c0, fail("BAD_ARGS"));
707
+ return done("error", fail("UNKNOWN_COMMAND"));
708
+ }
709
+ export function defaultOps() {
710
+ return createOps({ home: homedir(), fetch: (url, init) => fetch(url, init), now: () => Date.now() });
711
+ }
712
+ /** Whole piped stdin, capped; a terminal is never read (no prompt), a silent pipe ends after STDIN_WAIT_MS. */
713
+ async function readPipedStdin() {
714
+ if (process.stdin.isTTY)
715
+ return "";
716
+ return new Promise((resolveText) => {
717
+ const chunks = [];
718
+ let size = 0;
719
+ let settled = false;
720
+ const finish = () => {
721
+ if (settled)
722
+ return;
723
+ settled = true;
724
+ clearTimeout(timer);
725
+ process.stdin.removeAllListeners("data");
726
+ process.stdin.pause();
727
+ resolveText(Buffer.concat(chunks).toString("utf8"));
728
+ };
729
+ const timer = setTimeout(finish, STDIN_WAIT_MS);
730
+ process.stdin.on("data", (c) => {
731
+ const b = typeof c === "string" ? Buffer.from(c) : c;
732
+ size += b.length;
733
+ // larger than any key: keep a marker over the cap so the format check refuses it
734
+ chunks.push(size > KEY_INPUT_MAX_BYTES ? Buffer.from("x".repeat(KEY_INPUT_MAX_BYTES + 1)) : b);
735
+ if (size > KEY_INPUT_MAX_BYTES)
736
+ finish();
737
+ });
738
+ process.stdin.once("end", finish);
739
+ process.stdin.once("error", finish);
740
+ });
741
+ }
742
+ export function defaultLive() {
743
+ const h = resolveHome(process.env, homedir(), process.cwd());
744
+ return {
745
+ home: h.ok ? h.home : "",
746
+ ...(h.ok ? {} : { homeError: h.error }),
747
+ env: process.env,
748
+ fetch: (url, init) => fetch(url, init),
749
+ now: () => Date.now(),
750
+ readStdin: readPipedStdin,
751
+ };
752
+ }
753
+ async function main(argv) {
754
+ const ops = defaultOps();
755
+ if (argv.length === 0 || (argv.length === 1 && argv[0] === "mcp")) {
756
+ const { startMcpStdio } = await import("./mcp.js");
757
+ await startMcpStdio(ops, defaultLive());
758
+ return;
759
+ }
760
+ const r = await runCli(argv, ops, defaultLive());
761
+ process.stdout.write(`${r.out}\n`);
762
+ process.exitCode = r.code;
763
+ }
764
+ function isEntry() {
765
+ const a = process.argv[1];
766
+ if (a === undefined)
767
+ return false;
768
+ try {
769
+ return import.meta.url === pathToFileURL(realpathSync(a)).href;
770
+ }
771
+ catch {
772
+ return false;
773
+ }
774
+ }
775
+ if (isEntry()) {
776
+ main(process.argv.slice(2)).catch(() => {
777
+ process.stdout.write(`${JSON.stringify(fail("INTERNAL", { hint: "Unexpected failure. Retry; if it repeats, run: degenly demo reset" }))}\n`);
778
+ process.exitCode = 1;
779
+ });
780
+ }