@degenly/agent 0.1.1 → 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/README.md +56 -9
- package/SKILL.md +16 -3
- package/dist/bip39-words.js +263 -0
- package/dist/cli.js +181 -9
- package/dist/client.js +22 -0
- package/dist/keys.js +200 -20
- package/dist/mcp.js +38 -5
- package/dist/mnemonic.js +165 -0
- package/dist/tools/live-withdraw.js +217 -0
- package/dist/tx.js +56 -0
- package/docs/clients.md +5 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -18,16 +18,19 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { readFileSync, realpathSync } from "node:fs";
|
|
20
20
|
import { homedir } from "node:os";
|
|
21
|
+
import { createInterface } from "node:readline/promises";
|
|
21
22
|
import { pathToFileURL } from "node:url";
|
|
22
23
|
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 { AGENT_WALLET_WARNING, RECOVERY_PATH_TEXT, RECOVERY_SETUP_TEXT, WALLET_PATH_TEXT, createWallet, deleteRecoveryFile, loadWallet, recoveryDeletedFor, recoveryWords, resolveHome, restoreWallet } from "./keys.js";
|
|
25
|
+
import { RECOVERY_WORD_COUNT, splitPhrase, wordsToEntropy } from "./mnemonic.js";
|
|
24
26
|
import { API_PAIR_TS_SKEW_MS, createPairingCode, isSolanaAddress } from "./sign.js";
|
|
25
27
|
import { QUOTE_DAILY_MAX, QUOTE_MIN_GAP_MS, TOP_WINDOWS, checkQuoteLimit, createClient, list, parseQuote, parseSearchHit, parseTokenRow, parseTopRow, recordQuote, } from "./api.js";
|
|
26
28
|
import { SOL_DECIMALS, SOL_MINT, demoFill, demoNetworkLamports, formatUnits, parseSol, parseUnits } from "./demo/fill.js";
|
|
27
29
|
import { DEMO_START_LAMPORTS, loadDemo, resetDemo, saveDemo } from "./demo/store.js";
|
|
28
30
|
import { SYMBOL_MAX_CHARS, cleanText, isMint, showUntrusted, untrustedName, untrustedSymbol } from "./sanitize.js";
|
|
29
31
|
import { createLiveRead } from "./tools/live-read.js";
|
|
30
|
-
|
|
32
|
+
import { OWNER_PATH_TEXT, createLiveWithdraw, saveOwner, terminalConfirm } from "./tools/live-withdraw.js";
|
|
33
|
+
export const VERSION = "0.2.0";
|
|
31
34
|
export const DEMO_NOTE = "Demo trade. No real funds moved.";
|
|
32
35
|
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
36
|
export const RECORD_PATH_TEXT = "~/.degenly/demo.json";
|
|
@@ -64,7 +67,7 @@ const HINTS = {
|
|
|
64
67
|
export function exitCodeFor(error) {
|
|
65
68
|
if (error === undefined)
|
|
66
69
|
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))
|
|
70
|
+
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", "PHRASE_ARG_REFUSED", "NO_PHRASE_INPUT"].includes(error))
|
|
68
71
|
return 2;
|
|
69
72
|
if (error === "RATE_LIMITED")
|
|
70
73
|
return 3;
|
|
@@ -444,6 +447,13 @@ export const USAGE = [
|
|
|
444
447
|
" degenly live ledger [--limit N] confirmed Degenly trades of the agent wallet",
|
|
445
448
|
" degenly live quote <mint> buy <sol> real quote, nothing signed or sent",
|
|
446
449
|
" degenly live quote <mint> sell <N%|all>",
|
|
450
|
+
" degenly withdraw <sol|all> send SOL from the agent wallet back to your paired main wallet (you type YES)",
|
|
451
|
+
" Funds can only go back to your paired main wallet. Tokens are not withdrawn: sell first; only SOL is withdrawn.",
|
|
452
|
+
"",
|
|
453
|
+
"Recovery phrase (12 words, made and kept only on this computer; Degenly never sees or stores your recovery phrase):",
|
|
454
|
+
" degenly recovery-phrase show the 12 words: only you, in your own terminal (never for an agent)",
|
|
455
|
+
" degenly recover [--phrase-file <path>] rebuild the agent wallet from the 12 words on stdin or a file",
|
|
456
|
+
" Anyone with the phrase can take the agent wallet's funds; never paste it into a chat or give it to an agent.",
|
|
447
457
|
"",
|
|
448
458
|
"Add --json for one-line JSON. Mint addresses only; coin names are untrusted text.",
|
|
449
459
|
"Live buy / sell: MCP tools degenly_live_buy / degenly_live_sell only (the human confirms each trade).",
|
|
@@ -454,7 +464,7 @@ function flagValue(argv, i) {
|
|
|
454
464
|
return v !== undefined && !v.startsWith("--") ? v : undefined;
|
|
455
465
|
}
|
|
456
466
|
function parseArgs(argv) {
|
|
457
|
-
const out = { json: false, keyArg: false, rest: [] };
|
|
467
|
+
const out = { json: false, keyArg: false, phraseArg: false, rest: [] };
|
|
458
468
|
for (let i = 0; i < argv.length; i++) {
|
|
459
469
|
const a = argv[i] ?? "";
|
|
460
470
|
if (a === "--json")
|
|
@@ -486,6 +496,19 @@ function parseArgs(argv) {
|
|
|
486
496
|
out.owner = a.slice("--owner=".length);
|
|
487
497
|
else if (a.startsWith("--key-file="))
|
|
488
498
|
out.keyFile = a.slice("--key-file=".length);
|
|
499
|
+
else if (a === "--phrase-file") {
|
|
500
|
+
const v = flagValue(argv, i);
|
|
501
|
+
if (v !== undefined)
|
|
502
|
+
i++;
|
|
503
|
+
out.phraseFile = v ?? "";
|
|
504
|
+
}
|
|
505
|
+
else if (a.startsWith("--phrase-file="))
|
|
506
|
+
out.phraseFile = a.slice("--phrase-file=".length);
|
|
507
|
+
else if (/^--(phrase|mnemonic|words|seed|recovery-phrase|secret)(=|$)/.test(a)) {
|
|
508
|
+
out.phraseArg = true;
|
|
509
|
+
if (!a.includes("=") && flagValue(argv, i) !== undefined)
|
|
510
|
+
i++;
|
|
511
|
+
}
|
|
489
512
|
else if (/^--(api-?)?key(=|$)/.test(a)) {
|
|
490
513
|
out.keyArg = true;
|
|
491
514
|
if (!a.includes("=") && flagValue(argv, i) !== undefined)
|
|
@@ -537,15 +560,18 @@ function liveOk(fields) {
|
|
|
537
560
|
function liveFail(error, extra = {}) {
|
|
538
561
|
return { ok: false, mode: "live", note: LIVE_NOTE, error, hint: liveHint(error), ...extra };
|
|
539
562
|
}
|
|
540
|
-
function pairingAnswer(wallet, owner, now, created) {
|
|
563
|
+
function pairingAnswer(wallet, owner, now, created, ownerRecorded) {
|
|
541
564
|
const { code } = createPairingCode(wallet, owner, now);
|
|
542
565
|
return liveOk({
|
|
543
566
|
created,
|
|
544
567
|
address: wallet.address,
|
|
545
568
|
ownerWallet: owner,
|
|
569
|
+
// DGAJ30: the only place a withdrawal may go (`degenly withdraw` / degenly_live_withdraw read it)
|
|
570
|
+
...(ownerRecorded ? { ownerFile: OWNER_PATH_TEXT } : { ownerFile: "not written", ownerWarning: `Could not write ${OWNER_PATH_TEXT}; withdrawals answer OWNER_UNKNOWN until pair --owner succeeds.` }),
|
|
546
571
|
pairingCode: code,
|
|
547
572
|
pairingCodeValidMs: API_PAIR_TS_SKEW_MS,
|
|
548
573
|
walletFile: WALLET_PATH_TEXT,
|
|
574
|
+
...(created ? { recovery: RECOVERY_SETUP_TEXT } : {}),
|
|
549
575
|
warning: AGENT_WALLET_WARNING,
|
|
550
576
|
next: PAIR_NEXT_STEP,
|
|
551
577
|
});
|
|
@@ -568,7 +594,7 @@ async function liveSetup(d, owner) {
|
|
|
568
594
|
const l = loadWallet(d.home);
|
|
569
595
|
return liveFail("WALLET_EXISTS", l.ok ? { address: l.wallet.address } : {});
|
|
570
596
|
}
|
|
571
|
-
return pairingAnswer(c.wallet, owner, d.now(), true);
|
|
597
|
+
return pairingAnswer(c.wallet, owner, d.now(), true, saveOwner(d.home, owner));
|
|
572
598
|
}
|
|
573
599
|
async function livePair(d, owner) {
|
|
574
600
|
if (d.homeError)
|
|
@@ -579,7 +605,7 @@ async function livePair(d, owner) {
|
|
|
579
605
|
const bad = ownerError(owner, l.wallet.address);
|
|
580
606
|
if (bad || owner === undefined)
|
|
581
607
|
return bad ?? liveFail("BAD_OWNER");
|
|
582
|
-
return pairingAnswer(l.wallet, owner, d.now(), false);
|
|
608
|
+
return pairingAnswer(l.wallet, owner, d.now(), false, saveOwner(d.home, owner));
|
|
583
609
|
}
|
|
584
610
|
async function liveLogin(d, p) {
|
|
585
611
|
// the key is never taken from argv (shell history): any extra word or a --key flag is refused, stdin unread
|
|
@@ -642,6 +668,115 @@ async function liveWhoami(d) {
|
|
|
642
668
|
apiBase: b.base,
|
|
643
669
|
});
|
|
644
670
|
}
|
|
671
|
+
// ---- recovery phrase (DGAJ29) ------------------------------------------------------------------
|
|
672
|
+
export const RECOVERY_NEEDS_TERMINAL_TEXT = "Run this yourself in your own terminal. It is never shown to an agent.";
|
|
673
|
+
export const PHRASE_SAFETY = "Degenly never sees or stores your recovery phrase. Anyone with the phrase can take the agent wallet's funds; never paste it into a chat or give it to an agent.";
|
|
674
|
+
/** DGAJ34 (DGAJ31 G-1): the SAME sentence in 3 places (`recovery-phrase` output under the words, README, SKILL.md). Do not reword. */
|
|
675
|
+
export const PHRASE_SCOPE_WARNING = "Use this phrase only for the agent wallet. Do not add accounts to it or use it as your main wallet: anyone who reads ~/.degenly/recovery.json gets every account of this phrase.";
|
|
676
|
+
/** DGAJ34: asked after the words, in the interactive terminal only. Only an exact DELETE (trimmed) deletes. */
|
|
677
|
+
export const RECOVERY_DELETE_QUESTION = "Type DELETE to remove recovery.json from this computer now that you wrote the words down:";
|
|
678
|
+
export const RECOVERY_KEPT_TEXT = "recovery.json kept. Run `degenly recovery-phrase` again when you are ready to delete it.";
|
|
679
|
+
/** DGAJ34: after the delete (and on every later `recovery-phrase` for that wallet): information, exit code 0. */
|
|
680
|
+
export const RECOVERY_GONE_TEXT = "The recovery phrase is no longer stored on this computer. Your written copy is the only one.";
|
|
681
|
+
/** DGAJ34: the delete reminder (README + `recover` output). */
|
|
682
|
+
export const RECOVERY_DELETE_REMINDER = "After you wrote the words down, delete recovery.json with `degenly recovery-phrase` (type DELETE).";
|
|
683
|
+
export const RECOVERY_DELETE_FAILED_TEXT = "RECOVERY_DELETE_FAILED: recovery.json could not be deleted and is still on this computer. Run `degenly recovery-phrase` again to retry.";
|
|
684
|
+
/**
|
|
685
|
+
* `degenly recovery-phrase`: the ONLY path that shows the words. Refused unless an interactive terminal
|
|
686
|
+
* (stdout AND stdin are a TTY) and no `--json`. On success the words come back as plain text, never as an Answer
|
|
687
|
+
* (so no JSON / MCP serializer ever holds them).
|
|
688
|
+
* DGAJ34: with a terminal prompt (`promptLine`), the words are shown as part of the prompt, followed by
|
|
689
|
+
* RECOVERY_DELETE_QUESTION; only an exact `DELETE` removes recovery.json (deleteRecoveryFile: that file only).
|
|
690
|
+
* Anything else, an empty line, EOF or a prompt error keeps it. Without `promptLine`: words only, no question.
|
|
691
|
+
*/
|
|
692
|
+
async function liveRecoveryPhrase(d, p) {
|
|
693
|
+
if (p.json || p.rest.length !== 1 || d.interactive?.() !== true)
|
|
694
|
+
return { ok: false, answer: liveFail("RECOVERY_NEEDS_TERMINAL") };
|
|
695
|
+
if (d.homeError)
|
|
696
|
+
return { ok: false, answer: liveFail(d.homeError) };
|
|
697
|
+
const r = recoveryWords(d.home);
|
|
698
|
+
if (!r.ok) {
|
|
699
|
+
if (r.error === "NO_RECOVERY_PHRASE") {
|
|
700
|
+
const w = loadWallet(d.home);
|
|
701
|
+
if (w.ok && recoveryDeletedFor(d.home, w.wallet.address))
|
|
702
|
+
return { ok: true, text: RECOVERY_GONE_TEXT };
|
|
703
|
+
}
|
|
704
|
+
return { ok: false, answer: liveFail(r.error) };
|
|
705
|
+
}
|
|
706
|
+
const numbered = r.words.map((w, i) => `${String(i + 1).padStart(2, " ")}. ${w}`);
|
|
707
|
+
r.words.fill("");
|
|
708
|
+
const text = [
|
|
709
|
+
`Agent wallet: ${r.address}`,
|
|
710
|
+
`Recovery phrase (${RECOVERY_WORD_COUNT} words, path m/44'/501'/0'/0', the Phantom / Solflare default):`,
|
|
711
|
+
"",
|
|
712
|
+
...numbered,
|
|
713
|
+
"",
|
|
714
|
+
PHRASE_SCOPE_WARNING,
|
|
715
|
+
"Write the words down on paper, in this order. " + PHRASE_SAFETY,
|
|
716
|
+
"Clear this terminal window when you are done.",
|
|
717
|
+
].join("\n");
|
|
718
|
+
numbered.fill("");
|
|
719
|
+
if (d.promptLine === undefined)
|
|
720
|
+
return { ok: true, text };
|
|
721
|
+
let answer = "";
|
|
722
|
+
try {
|
|
723
|
+
answer = await d.promptLine(`${text}\n\n${RECOVERY_DELETE_QUESTION} `);
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
answer = "";
|
|
727
|
+
}
|
|
728
|
+
if (answer.trim() !== "DELETE")
|
|
729
|
+
return { ok: true, text: RECOVERY_KEPT_TEXT };
|
|
730
|
+
const del = deleteRecoveryFile(d.home);
|
|
731
|
+
return del.ok ? { ok: true, text: RECOVERY_GONE_TEXT } : { ok: true, text: RECOVERY_DELETE_FAILED_TEXT, code: 1 };
|
|
732
|
+
}
|
|
733
|
+
/** Reads the phrase text from --phrase-file or piped stdin (never an argument). Error codes only, never a word. */
|
|
734
|
+
async function phraseInput(d, p) {
|
|
735
|
+
if (p.phraseFile !== undefined) {
|
|
736
|
+
try {
|
|
737
|
+
const buf = readFileSync(p.phraseFile);
|
|
738
|
+
if (buf.length > KEY_INPUT_MAX_BYTES)
|
|
739
|
+
return { ok: false, error: "PHRASE_WORD_COUNT" };
|
|
740
|
+
const text = buf.toString("utf8");
|
|
741
|
+
buf.fill(0);
|
|
742
|
+
return { ok: true, text };
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
return { ok: false, error: "PHRASE_FILE_UNREADABLE" };
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
return { ok: true, text: await d.readStdin() };
|
|
749
|
+
}
|
|
750
|
+
/** `degenly recover`: phrase from stdin / --phrase-file → wallet + recovery.json. Output: the address only. */
|
|
751
|
+
async function liveRecover(d, p) {
|
|
752
|
+
// like login: any extra word or a --phrase style flag is refused, stdin not read, nothing echoed
|
|
753
|
+
if (p.phraseArg || p.keyArg || p.rest.length !== 1 || p.phraseFile === "")
|
|
754
|
+
return liveFail("PHRASE_ARG_REFUSED");
|
|
755
|
+
if (d.homeError)
|
|
756
|
+
return liveFail(d.homeError);
|
|
757
|
+
const before = loadWallet(d.home);
|
|
758
|
+
if (before.ok || before.error === "WALLET_CORRUPT")
|
|
759
|
+
return liveFail("WALLET_EXISTS", before.ok ? { address: before.wallet.address } : {});
|
|
760
|
+
const input = await phraseInput(d, p);
|
|
761
|
+
if (!input.ok)
|
|
762
|
+
return liveFail(input.error);
|
|
763
|
+
const words = splitPhrase(input.text);
|
|
764
|
+
if (words.length === 0)
|
|
765
|
+
return liveFail("NO_PHRASE_INPUT");
|
|
766
|
+
const e = wordsToEntropy(words);
|
|
767
|
+
words.fill("");
|
|
768
|
+
if (!e.ok)
|
|
769
|
+
return liveFail(e.error);
|
|
770
|
+
try {
|
|
771
|
+
const r = restoreWallet(d.home, e.entropy);
|
|
772
|
+
if (!r.ok)
|
|
773
|
+
return liveFail(r.error);
|
|
774
|
+
return liveOk({ address: r.wallet.address, walletFile: WALLET_PATH_TEXT, recoveryFile: RECOVERY_PATH_TEXT, recoveryReminder: RECOVERY_DELETE_REMINDER, next: "Check it with: degenly whoami (pair again on degenly.app/bot if this computer has no API key)." });
|
|
775
|
+
}
|
|
776
|
+
finally {
|
|
777
|
+
e.entropy.fill(0);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
645
780
|
/**
|
|
646
781
|
* Runs one CLI command (never prompts). `out` = the full text to print; `code` = the exit code.
|
|
647
782
|
* `live` absent (demo-only callers) → the live commands keep answering NOT_AVAILABLE_IN_DEMO.
|
|
@@ -659,6 +794,9 @@ export async function runCli(argv, ops, live) {
|
|
|
659
794
|
return { code: 0, out: p.json ? JSON.stringify(okAnswer({ version: VERSION })) : VERSION };
|
|
660
795
|
if (p.keyArg)
|
|
661
796
|
return done("login", liveFail("KEY_ARG_REFUSED"));
|
|
797
|
+
// DGAJ29: a recovery phrase is never an argument, for any command (shell history); the value is never echoed
|
|
798
|
+
if (p.phraseArg)
|
|
799
|
+
return done(c0 ?? "error", liveFail("PHRASE_ARG_REFUSED"));
|
|
662
800
|
if (live && (c0 === "setup" || c0 === "pair")) {
|
|
663
801
|
if (!args(1, r))
|
|
664
802
|
return done(c0, liveFail("BAD_ARGS", { hint: `Usage: degenly ${c0} --owner <main wallet address>` }));
|
|
@@ -666,6 +804,20 @@ export async function runCli(argv, ops, live) {
|
|
|
666
804
|
}
|
|
667
805
|
if (live && c0 === "login")
|
|
668
806
|
return done("login", await liveLogin(live, p));
|
|
807
|
+
if (live && c0 === "recovery-phrase") {
|
|
808
|
+
const rp = await liveRecoveryPhrase(live, p);
|
|
809
|
+
return rp.ok ? { code: rp.code ?? 0, out: rp.text } : done("recovery-phrase", rp.answer);
|
|
810
|
+
}
|
|
811
|
+
if (live && c0 === "recover")
|
|
812
|
+
return done("recover", await liveRecover(live, p));
|
|
813
|
+
// DGAJ30: SOL back to the paired main wallet; the human types YES in their own terminal (never --json / an agent shell)
|
|
814
|
+
if (live && c0 === "withdraw") {
|
|
815
|
+
if (!args(2, r))
|
|
816
|
+
return done("withdraw", liveFail("BAD_ARGS", { hint: "Usage: degenly withdraw <sol|all>" }));
|
|
817
|
+
if (p.json || live.interactive?.() !== true || live.promptLine === undefined)
|
|
818
|
+
return done("withdraw", liveFail("WITHDRAW_NEEDS_TERMINAL"));
|
|
819
|
+
return done("withdraw", await createLiveWithdraw(live).withdraw(c1 ?? "", terminalConfirm(live.promptLine)));
|
|
820
|
+
}
|
|
669
821
|
if (live && c0 === "whoami")
|
|
670
822
|
return done("whoami", args(1, r) ? await liveWhoami(live) : liveFail("BAD_ARGS", { hint: "Usage: degenly whoami" }));
|
|
671
823
|
// DGAJ16: live READ commands only (a live buy / sell needs the human confirmation form: MCP only)
|
|
@@ -679,7 +831,7 @@ export async function runCli(argv, ops, live) {
|
|
|
679
831
|
return done("live quote", await read.quote(c2 ?? "", c3 ?? "", c4 ?? ""));
|
|
680
832
|
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
833
|
}
|
|
682
|
-
if (c0 === "setup" || c0 === "login" || c0 === "live" || c0 === "pair" || c0 === "whoami")
|
|
834
|
+
if (c0 === "setup" || c0 === "login" || c0 === "live" || c0 === "pair" || c0 === "whoami" || c0 === "recover" || c0 === "recovery-phrase" || c0 === "withdraw")
|
|
683
835
|
return done(c0, fail("NOT_AVAILABLE_IN_DEMO"));
|
|
684
836
|
if (c0 === "demo") {
|
|
685
837
|
if (c1 === "status" && args(2, r))
|
|
@@ -748,13 +900,33 @@ export function defaultLive() {
|
|
|
748
900
|
fetch: (url, init) => fetch(url, init),
|
|
749
901
|
now: () => Date.now(),
|
|
750
902
|
readStdin: readPipedStdin,
|
|
903
|
+
interactive: () => process.stdout.isTTY === true && process.stdin.isTTY === true,
|
|
904
|
+
promptLine: promptTerminalLine,
|
|
751
905
|
};
|
|
752
906
|
}
|
|
907
|
+
/**
|
|
908
|
+
* DGAJ30: one line typed in the interactive terminal (`degenly withdraw`; DGAJ34: the DELETE question of
|
|
909
|
+
* `degenly recovery-phrase`; never used to read a secret). EOF (Ctrl+D / closed stdin) answers "".
|
|
910
|
+
*/
|
|
911
|
+
async function promptTerminalLine(question) {
|
|
912
|
+
if (process.stdin.isTTY !== true || process.stdout.isTTY !== true)
|
|
913
|
+
return "";
|
|
914
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
915
|
+
try {
|
|
916
|
+
const closed = new Promise((resolveLine) => rl.once("close", () => resolveLine("")));
|
|
917
|
+
return await Promise.race([rl.question(question).catch(() => ""), closed]);
|
|
918
|
+
}
|
|
919
|
+
finally {
|
|
920
|
+
rl.close();
|
|
921
|
+
}
|
|
922
|
+
}
|
|
753
923
|
async function main(argv) {
|
|
754
924
|
const ops = defaultOps();
|
|
755
925
|
if (argv.length === 0 || (argv.length === 1 && argv[0] === "mcp")) {
|
|
756
926
|
const { startMcpStdio } = await import("./mcp.js");
|
|
757
|
-
|
|
927
|
+
// DGAJ29: inside MCP the recovery phrase is never shown (no tool exists for it; the flag closes the CLI path too)
|
|
928
|
+
// DGAJ30: no terminal prompt inside MCP (a withdrawal there goes through the confirmation form only)
|
|
929
|
+
await startMcpStdio(ops, { ...defaultLive(), interactive: () => false, promptLine: undefined });
|
|
758
930
|
return;
|
|
759
931
|
}
|
|
760
932
|
const r = await runCli(argv, ops, defaultLive());
|
package/dist/client.js
CHANGED
|
@@ -207,6 +207,28 @@ export const LIVE_HINTS = {
|
|
|
207
207
|
REPLAY: "This exact signed request was already used. Retry (a new signature is made each time).",
|
|
208
208
|
API_TERMS_REQUIRED: "The API Terms changed. Pair again on degenly.app/bot to accept the current version.",
|
|
209
209
|
RATE_LIMITED: "Wait retryAfterMs, then retry.",
|
|
210
|
+
// DGAJ29: recovery phrase (hints never carry a word of it)
|
|
211
|
+
RECOVERY_NEEDS_TERMINAL: "Run this yourself in your own terminal. It is never shown to an agent.",
|
|
212
|
+
NO_RECOVERY_PHRASE: "This agent wallet was created before recovery phrases existed. Back up ~/.degenly/agent-wallet.json, or withdraw and run setup again.",
|
|
213
|
+
RECOVERY_CORRUPT: "~/.degenly/recovery.json is not a valid recovery file. It was left as is. Your agent wallet file still works; back it up.",
|
|
214
|
+
RECOVERY_MISMATCH: "~/.degenly/recovery.json does not belong to the agent wallet on this computer, so no words are shown. Both files were left as is. Back up ~/.degenly/agent-wallet.json.",
|
|
215
|
+
RECOVERY_EXISTS: "~/.degenly/recovery.json already exists (it may be the only copy of a wallet's phrase) and is never overwritten. Move it somewhere safe first if you really want a new wallet.",
|
|
216
|
+
PHRASE_ARG_REFUSED: "The recovery phrase is never taken as a command argument (it would stay in shell history). Pipe it on stdin: degenly recover < phrase.txt, or use: degenly recover --phrase-file <path>",
|
|
217
|
+
NO_PHRASE_INPUT: "No recovery phrase on stdin. Pipe it in (degenly recover < phrase.txt) or use: degenly recover --phrase-file <path>. Delete that file afterwards.",
|
|
218
|
+
PHRASE_FILE_UNREADABLE: "Could not read the --phrase-file path.",
|
|
219
|
+
PHRASE_WORD_COUNT: "A Degenly agent wallet recovery phrase has exactly 12 words, separated by spaces.",
|
|
220
|
+
PHRASE_UNKNOWN_WORD: "One of the words is not in the BIP39 English word list. Check the spelling against what you wrote down; nothing is guessed.",
|
|
221
|
+
PHRASE_CHECKSUM: "The 12 words are valid words but not a valid recovery phrase (checksum). Check the order and spelling; nothing is guessed.",
|
|
222
|
+
// DGAJ30: withdraw (funds can only go back to the paired main wallet)
|
|
223
|
+
OWNER_UNKNOWN: "This computer has no record of your paired main wallet, so nothing can be withdrawn. Run: degenly pair --owner <main wallet address> (no new pairing is needed just to record it)",
|
|
224
|
+
WITHDRAW_NOT_AVAILABLE: "Withdrawals are not switched on yet on this server.",
|
|
225
|
+
WITHDRAW_NEEDS_TERMINAL: "degenly withdraw runs only in your own interactive terminal (no --json) and asks you to type YES. An agent uses the MCP tool degenly_live_withdraw instead, which shows you a confirmation form.",
|
|
226
|
+
NOTHING_TO_WITHDRAW: "The agent wallet has no SOL left to withdraw after the network fee.",
|
|
227
|
+
INSUFFICIENT_BALANCE: "The agent wallet does not hold that much SOL plus the network fee (see balanceLamports, feeLamports).",
|
|
228
|
+
DESTINATION_NOT_ALLOWED: "A withdrawal never names a destination: funds can only go back to your paired main wallet.",
|
|
229
|
+
OWNER_IS_AGENT: "The paired main wallet is the agent wallet itself. Pair again with your main wallet.",
|
|
230
|
+
NOT_AN_AGENT_KEY: "This API key is not a paired agent key. Pair the agent on degenly.app/bot and run degenly login.",
|
|
231
|
+
SIMULATION_FAILED: "The network simulation of the withdrawal failed. Nothing was signed or sent. Check the balance and retry later.",
|
|
210
232
|
};
|
|
211
233
|
export function liveHint(code) {
|
|
212
234
|
return LIVE_HINTS[code] ?? `Degenly answered ${code}. Retry later.`;
|
package/dist/keys.js
CHANGED
|
@@ -12,13 +12,22 @@
|
|
|
12
12
|
* public address and a `sign` function only.
|
|
13
13
|
* - `--keychain` (OS credential store) is NOT offered: not measured on the three OSes (DGAJ-S A4 madde 3).
|
|
14
14
|
*/
|
|
15
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
|
-
import { createPrivateKey, createPublicKey,
|
|
15
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { createPrivateKey, createPublicKey, randomBytes, sign as edSign } from "node:crypto";
|
|
17
17
|
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
18
|
+
import { RECOVERY_ENTROPY_BYTES, entropyToSolanaSeed, entropyToWords } from "./mnemonic.js";
|
|
18
19
|
import { base58Encode } from "./sign.js";
|
|
19
20
|
export const DEGENLY_DIR_NAME = ".degenly";
|
|
20
21
|
export const WALLET_FILE_NAME = "agent-wallet.json";
|
|
21
22
|
export const WALLET_PATH_TEXT = "~/.degenly/agent-wallet.json";
|
|
23
|
+
/**
|
|
24
|
+
* DGAJ29: the recovery entropy of a wallet made by `setup` / `recover` (`{"v":1,"entropyHex":"..."}`), next to the
|
|
25
|
+
* wallet file, same protection (0600, never overwritten). Wallets made before DGAJ29 have none and keep working.
|
|
26
|
+
*/
|
|
27
|
+
export const RECOVERY_FILE_NAME = "recovery.json";
|
|
28
|
+
export const RECOVERY_PATH_TEXT = "~/.degenly/recovery.json";
|
|
29
|
+
/** DGAJ29: the `setup` line about the phrase (the words themselves are never in `setup` output). Do not reword. */
|
|
30
|
+
export const RECOVERY_SETUP_TEXT = "Recovery phrase: run `degenly recovery-phrase` yourself in your own terminal and write the 12 words down. Degenly never sees or stores them.";
|
|
22
31
|
/**
|
|
23
32
|
* DGAJ-S A4 madde 1: the SAME sentence in 3 places (`setup` output, `/bot` safety note, README).
|
|
24
33
|
* DGAJ17 README uses this constant. Do not reword.
|
|
@@ -70,38 +79,209 @@ export function signerFromSeed(seed) {
|
|
|
70
79
|
const key = privateKeyFromSeed(seed);
|
|
71
80
|
return signerOf(key, publicKeyOf(key));
|
|
72
81
|
}
|
|
73
|
-
function seedOf(key) {
|
|
74
|
-
const der = key.export({ format: "der", type: "pkcs8" });
|
|
75
|
-
return new Uint8Array(der.subarray(der.length - 32));
|
|
76
|
-
}
|
|
77
82
|
function ensureDir(home) {
|
|
78
83
|
const dir = degenlyDir(home);
|
|
79
84
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
80
85
|
if (POSIX)
|
|
81
86
|
chmodSync(dir, 0o700);
|
|
82
87
|
}
|
|
83
|
-
|
|
84
|
-
|
|
88
|
+
export function recoveryPath(home) {
|
|
89
|
+
return join(degenlyDir(home), RECOVERY_FILE_NAME);
|
|
90
|
+
}
|
|
91
|
+
function isEexist(e) {
|
|
92
|
+
return typeof e === "object" && e !== null && e.code === "EEXIST";
|
|
93
|
+
}
|
|
94
|
+
/** Writes a new file 0600 with `wx` (never over an existing one). */
|
|
95
|
+
function writeNew(file, content) {
|
|
96
|
+
writeFileSync(file, content, { mode: 0o600, flag: "wx" });
|
|
97
|
+
if (POSIX)
|
|
98
|
+
chmodSync(file, 0o600);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Wallet file + (optionally) recovery file from 16 bytes of entropy. The recovery file is written first, then the
|
|
102
|
+
* wallet; a wallet write that fails removes the recovery file it just made (that wallet never existed).
|
|
103
|
+
* Every secret buffer is zeroed before returning.
|
|
104
|
+
*/
|
|
105
|
+
function writeFromEntropy(home, entropy, writeRecovery) {
|
|
85
106
|
const file = walletPath(home);
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
const pub = publicKeyOf(
|
|
90
|
-
const seed = seedOf(privateKey);
|
|
107
|
+
const rfile = recoveryPath(home);
|
|
108
|
+
const seed = entropyToSolanaSeed(entropy);
|
|
109
|
+
const key = privateKeyFromSeed(seed);
|
|
110
|
+
const pub = publicKeyOf(key);
|
|
91
111
|
const content = JSON.stringify([...seed, ...pub]);
|
|
92
112
|
seed.fill(0);
|
|
113
|
+
const recovery = writeRecovery ? JSON.stringify({ v: 1, entropyHex: Buffer.from(entropy).toString("hex") }) : "";
|
|
93
114
|
try {
|
|
94
115
|
ensureDir(home);
|
|
95
|
-
writeFileSync(file, content, { mode: 0o600, flag: "wx" });
|
|
96
|
-
if (POSIX)
|
|
97
|
-
chmodSync(file, 0o600);
|
|
98
116
|
}
|
|
99
|
-
catch
|
|
100
|
-
if (typeof e === "object" && e !== null && e.code === "EEXIST")
|
|
101
|
-
return { ok: false, error: "WALLET_EXISTS" };
|
|
117
|
+
catch {
|
|
102
118
|
return { ok: false, error: "WALLET_WRITE_FAILED" };
|
|
103
119
|
}
|
|
104
|
-
|
|
120
|
+
if (writeRecovery) {
|
|
121
|
+
try {
|
|
122
|
+
writeNew(rfile, recovery);
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
return { ok: false, error: isEexist(e) ? "RECOVERY_EXISTS" : "WALLET_WRITE_FAILED" };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
writeNew(file, content);
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
if (writeRecovery) {
|
|
133
|
+
try {
|
|
134
|
+
unlinkSync(rfile);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// left in place: it belongs to a wallet that was never written
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { ok: false, error: isEexist(e) ? "WALLET_EXISTS" : "WALLET_WRITE_FAILED" };
|
|
141
|
+
}
|
|
142
|
+
return { ok: true, wallet: signerOf(key, pub), path: file };
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* `setup`: a NEW wallet, only if no wallet file exists. Never overwrites (flag `wx`).
|
|
146
|
+
* DGAJ29: the key comes from 16 random bytes of entropy (BIP39 12 words -> SLIP-0010 m/44'/501'/0'/0'); the entropy
|
|
147
|
+
* goes to `recovery.json`. A `recovery.json` left without a wallet is never overwritten (RECOVERY_EXISTS: it may be
|
|
148
|
+
* the only copy of a funded wallet's phrase).
|
|
149
|
+
*/
|
|
150
|
+
export function createWallet(home) {
|
|
151
|
+
if (existsSync(walletPath(home)))
|
|
152
|
+
return { ok: false, error: "WALLET_EXISTS" };
|
|
153
|
+
if (existsSync(recoveryPath(home)))
|
|
154
|
+
return { ok: false, error: "RECOVERY_EXISTS" };
|
|
155
|
+
const entropy = randomBytes(RECOVERY_ENTROPY_BYTES);
|
|
156
|
+
try {
|
|
157
|
+
return writeFromEntropy(home, entropy, true);
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
entropy.fill(0);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* `recover`: rebuilds the wallet file (and `recovery.json`) from the entropy of a checked phrase.
|
|
165
|
+
* A wallet file that exists is never overwritten (WALLET_EXISTS). An existing `recovery.json` is kept if it holds
|
|
166
|
+
* the same entropy, refused otherwise (RECOVERY_EXISTS).
|
|
167
|
+
*/
|
|
168
|
+
export function restoreWallet(home, entropy) {
|
|
169
|
+
if (existsSync(walletPath(home)))
|
|
170
|
+
return { ok: false, error: "WALLET_EXISTS" };
|
|
171
|
+
let writeRecovery = true;
|
|
172
|
+
if (existsSync(recoveryPath(home))) {
|
|
173
|
+
const r = loadRecoveryEntropy(home);
|
|
174
|
+
if (!r.ok)
|
|
175
|
+
return { ok: false, error: r.error === "NO_RECOVERY_PHRASE" ? "WALLET_WRITE_FAILED" : r.error };
|
|
176
|
+
const same = Buffer.compare(r.entropy, Buffer.from(entropy)) === 0;
|
|
177
|
+
r.entropy.fill(0);
|
|
178
|
+
if (!same)
|
|
179
|
+
return { ok: false, error: "RECOVERY_EXISTS" };
|
|
180
|
+
writeRecovery = false;
|
|
181
|
+
}
|
|
182
|
+
return writeFromEntropy(home, entropy, writeRecovery);
|
|
183
|
+
}
|
|
184
|
+
/** The entropy in `recovery.json`. Missing → NO_RECOVERY_PHRASE; anything but `{v:1, entropyHex: 32 hex}` → RECOVERY_CORRUPT. */
|
|
185
|
+
export function loadRecoveryEntropy(home) {
|
|
186
|
+
const file = recoveryPath(home);
|
|
187
|
+
if (!existsSync(file))
|
|
188
|
+
return { ok: false, error: "NO_RECOVERY_PHRASE" };
|
|
189
|
+
let v;
|
|
190
|
+
try {
|
|
191
|
+
v = JSON.parse(readFileSync(file, "utf8"));
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return { ok: false, error: "RECOVERY_CORRUPT" };
|
|
195
|
+
}
|
|
196
|
+
const o = typeof v === "object" && v !== null ? v : {};
|
|
197
|
+
if (o.v !== 1 || typeof o.entropyHex !== "string" || !/^[0-9a-f]{32}$/.test(o.entropyHex))
|
|
198
|
+
return { ok: false, error: "RECOVERY_CORRUPT" };
|
|
199
|
+
return { ok: true, entropy: Buffer.from(o.entropyHex, "hex") };
|
|
200
|
+
}
|
|
201
|
+
/** Address the recovery entropy opens (m/44'/501'/0'/0'). */
|
|
202
|
+
function addressOfEntropy(entropy) {
|
|
203
|
+
const seed = entropyToSolanaSeed(entropy);
|
|
204
|
+
try {
|
|
205
|
+
return base58Encode(publicKeyOf(privateKeyFromSeed(seed)));
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
seed.fill(0);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The 12 words for `degenly recovery-phrase` (the CLI shows them only in an interactive terminal).
|
|
213
|
+
* If a wallet file exists, the words must open THAT address (RECOVERY_MISMATCH otherwise: wrong words are never shown).
|
|
214
|
+
*/
|
|
215
|
+
export function recoveryWords(home) {
|
|
216
|
+
const r = loadRecoveryEntropy(home);
|
|
217
|
+
if (!r.ok)
|
|
218
|
+
return r;
|
|
219
|
+
try {
|
|
220
|
+
const address = addressOfEntropy(r.entropy);
|
|
221
|
+
const hasWallet = existsSync(walletPath(home));
|
|
222
|
+
if (hasWallet) {
|
|
223
|
+
const w = loadWallet(home);
|
|
224
|
+
if (!w.ok)
|
|
225
|
+
return { ok: false, error: w.error === "NO_WALLET" ? "WALLET_CORRUPT" : w.error };
|
|
226
|
+
if (w.wallet.address !== address)
|
|
227
|
+
return { ok: false, error: "RECOVERY_MISMATCH" };
|
|
228
|
+
}
|
|
229
|
+
return { ok: true, words: entropyToWords(r.entropy), address, walletFile: hasWallet };
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
r.entropy.fill(0);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* DGAJ34 (DGAJ31 G-1): after the human wrote the 12 words down, `recovery.json` can be removed so no file on this
|
|
237
|
+
* computer holds the phrase any more. Next to it, `recovery-deleted.json` records ONLY the public address whose
|
|
238
|
+
* phrase was removed (`{"v":1,"address":"..."}`), so `degenly recovery-phrase` can tell "deleted by you" apart
|
|
239
|
+
* from "wallet older than recovery phrases". It holds no secret.
|
|
240
|
+
*/
|
|
241
|
+
export const RECOVERY_DELETED_FILE_NAME = "recovery-deleted.json";
|
|
242
|
+
/** The marker path (see RECOVERY_DELETED_FILE_NAME). */
|
|
243
|
+
export function recoveryDeletedPath(home) {
|
|
244
|
+
return join(degenlyDir(home), RECOVERY_DELETED_FILE_NAME);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* DGAJ34: deletes `~/.degenly/recovery.json` and nothing else. The path comes from the constant (no path argument);
|
|
248
|
+
* `agent-wallet.json`, `owner.json`, `credentials.json` and every other file stay. The wallet keeps working (its key
|
|
249
|
+
* is in `agent-wallet.json`). Before the delete, the marker gets the wallet's public address (best effort: a marker
|
|
250
|
+
* that cannot be written never stops the delete). Called by the CLI only after the human typed DELETE in a TTY.
|
|
251
|
+
*/
|
|
252
|
+
export function deleteRecoveryFile(home) {
|
|
253
|
+
const file = recoveryPath(home);
|
|
254
|
+
if (!existsSync(file))
|
|
255
|
+
return { ok: false, error: "NO_RECOVERY_PHRASE" };
|
|
256
|
+
const w = loadWallet(home);
|
|
257
|
+
if (w.ok) {
|
|
258
|
+
try {
|
|
259
|
+
writeFileSync(recoveryDeletedPath(home), JSON.stringify({ v: 1, address: w.wallet.address }), { mode: 0o600 });
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
// the marker only picks the message `recovery-phrase` shows later
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
unlinkSync(file);
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
return { ok: false, error: "RECOVERY_DELETE_FAILED" };
|
|
270
|
+
}
|
|
271
|
+
return existsSync(file) ? { ok: false, error: "RECOVERY_DELETE_FAILED" } : { ok: true };
|
|
272
|
+
}
|
|
273
|
+
/** DGAJ34: true when `recovery.json` is gone because the human deleted it for THIS wallet (the marker's address). */
|
|
274
|
+
export function recoveryDeletedFor(home, address) {
|
|
275
|
+
if (existsSync(recoveryPath(home)))
|
|
276
|
+
return false;
|
|
277
|
+
try {
|
|
278
|
+
const v = JSON.parse(readFileSync(recoveryDeletedPath(home), "utf8"));
|
|
279
|
+
const o = typeof v === "object" && v !== null ? v : {};
|
|
280
|
+
return o.v === 1 && o.address === address;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
105
285
|
}
|
|
106
286
|
/** Reads the wallet. Missing → NO_WALLET; anything else than a valid 64-byte keypair → WALLET_CORRUPT (file untouched). */
|
|
107
287
|
export function loadWallet(home) {
|