@needmoretruth/nmts-cli 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +41 -0
  3. package/README.ko.md +8 -2
  4. package/README.md +8 -2
  5. package/dist/account.d.ts +7 -3
  6. package/dist/account.js +46 -19
  7. package/dist/arg-options.d.ts +16 -0
  8. package/dist/args.js +5 -2
  9. package/dist/artifact-about.d.ts +1 -1
  10. package/dist/commands/ai-account.d.ts +34 -0
  11. package/dist/commands/ai-account.js +260 -0
  12. package/dist/commands/balance.d.ts +68 -0
  13. package/dist/commands/balance.js +11 -1
  14. package/dist/commands/extend.d.ts +3 -0
  15. package/dist/commands/extend.js +1 -0
  16. package/dist/commands/login.js +2 -2
  17. package/dist/commands/push-wallet.js +4 -1
  18. package/dist/commands/push.d.ts +3 -0
  19. package/dist/commands/put-payer.d.ts +3 -1
  20. package/dist/commands/put-payer.js +13 -1
  21. package/dist/commands/put-wallet.d.ts +31 -0
  22. package/dist/commands/put-wallet.js +84 -10
  23. package/dist/commands/put.d.ts +5 -0
  24. package/dist/commands/whoami.d.ts +4 -0
  25. package/dist/commands/whoami.js +14 -1
  26. package/dist/crypto-surface.d.ts +11 -0
  27. package/dist/crypto-surface.js +6 -0
  28. package/dist/drive-edit/tree.d.ts +12 -0
  29. package/dist/drive-edit/tree.js +25 -4
  30. package/dist/drive-erase.d.ts +5 -3
  31. package/dist/drive-erase.js +7 -2
  32. package/dist/help-options.d.ts +2 -0
  33. package/dist/help-options.js +142 -0
  34. package/dist/help.js +10 -123
  35. package/dist/main.js +14 -19
  36. package/dist/mcp-tools/reads.js +4 -3
  37. package/dist/portable.d.ts +1 -1
  38. package/dist/portable.js +1 -1
  39. package/dist/product.d.ts +1 -1
  40. package/dist/product.js +1 -1
  41. package/dist/refill-source.d.ts +69 -0
  42. package/dist/refill-source.js +143 -0
  43. package/dist/risk.d.ts +12 -0
  44. package/dist/risk.js +16 -0
  45. package/dist/shared/lib/wallet/activity.js +23 -1
  46. package/dist/standing-tip.d.ts +26 -0
  47. package/dist/standing-tip.js +31 -0
  48. package/dist/storage-control/extend.d.ts +10 -0
  49. package/dist/storage-control/extend.js +1 -1
  50. package/dist/upload-store.d.ts +10 -0
  51. package/dist/upload-wallet-plan.d.ts +8 -0
  52. package/dist/upload-wallet-plan.js +12 -3
  53. package/dist/upload-wallet-put.d.ts +16 -0
  54. package/dist/upload-wallet-put.js +4 -2
  55. package/dist/upload-wallet.d.ts +11 -0
  56. package/dist/upload-wallet.js +14 -0
  57. package/dist/wallet-sign-external.d.ts +120 -0
  58. package/dist/wallet-sign-external.js +221 -0
  59. package/dist/wallet-sign.js +3 -1
  60. package/dist/walrus.d.ts +9 -1
  61. package/dist/walrus.js +17 -3
  62. package/docs/commands/ai-account.md +25 -0
  63. package/docs/commands/login.md +4 -3
  64. package/docs/commands/verify.md +1 -1
  65. package/docs/commands/whoami.md +4 -0
  66. package/examples/podman.sh +48 -0
  67. package/package.json +6 -1
  68. package/server.json +2 -2
  69. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +42 -6
  70. package/vendor/nmts-crypto/nmts_crypto_wasm.js +105 -2
  71. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  72. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +9 -4
package/AGENTS.md CHANGED
@@ -57,7 +57,7 @@ Four things need a person, all at the beginning. If you are being set up, hand t
57
57
  |---|---|---|---|
58
58
  | 1. Make the account | a person | nmts.me, or `nmts create` at a terminal (it makes the NMTS key on that machine and hands the person a one-time link to finish in a browser) | once |
59
59
  | 2. Make an API key for you | a person | the account screen at nmts.me, or `nmts key new` on a machine that holds the NMTS key (`key list` and `key revoke` live there too) | once, and again if it is revoked |
60
- | 3. Pass the check that says a person is here | a person | nmts.me, one short code | **every four weeks**, and only for step 1, step 4 and sharing |
60
+ | 3. Pass the check that says a person is here | a person | nmts.me, one short code | **every twelve weeks**, and only for step 1, step 4 and sharing |
61
61
  | 4. Get credits into the account | you, for the free trial (`nmts trial apply`, while step 3 is live) — a person, for a funded wallet | a terminal, or nmts.me | once, then as they run out |
62
62
 
63
63
  **Step 3 does not gate the work.** Reading, writing, listing, folders, the trash, the recovery files and the
package/CHANGELOG.md CHANGED
@@ -3,6 +3,47 @@
3
3
  Each version's entry is what changed for the person or the program using `nmts`. The product's own
4
4
  update history, which covers the site and the server too, is at https://nmts.me/updates.
5
5
 
6
+ ## 0.44.0 — 2026-09-23
7
+
8
+ - **Recovery phrase.** An NMTS key can be written as 15 words from the BIP-39 English or Korean word
9
+ list. `nmts whoami --reveal --phrase` prints them (`--lang ko` for Korean), and every place that
10
+ takes an NMTS key takes the phrase too. The phrase is the key in another form: it opens the
11
+ account exactly as the key does. For programs, `phraseOf` in `@needmoretruth/nmts-cli/portable`.
12
+ - **AI accounts from the terminal.** `nmts ai-account list`, `nmts ai-account create` and
13
+ `nmts ai-account delete` run on the NMTS key's proof; an API key cannot call them. Deleting asks
14
+ you to type the confirmation back, and `--yes` answers it for an agent.
15
+ - `nmts put --pay wallet --from <path>` takes a file that credits paid for, downloads and decrypts
16
+ it into this tool's own directory, encrypts and uploads it again paid from your wallet, and moves
17
+ the old file to the trash. Storage the treasury bought cannot be handed to a wallet, so this is a
18
+ new upload, not a transfer.
19
+ - The standing gift address is fixed per network in the tool. A self-hosted server that names a
20
+ different one is followed only with `--trust-server-tip-address`; without it, `nmts` stops before
21
+ signing.
22
+ - The upload review tells an account that asked for the recovery list's storage-network copy that
23
+ this upload does not carry it, and how to write the list out as a file instead.
24
+ - Erasing a folder completely also removes the empty folders under it, which used to stay behind
25
+ in the list with nothing able to open them.
26
+ - Reads try a second aggregator on each network when the first cannot be reached.
27
+ - `examples/podman.sh` runs the tool in rootless Podman with the key handed in as a secret.
28
+
29
+ ## 0.43.0 — 2026-09-20
30
+
31
+ - Nothing changes for the `nmts` command: it signs with the wallet this NMTS key derives, as it
32
+ always has, and a terminal has no browser extension to offer instead.
33
+ - The library surface has a new entry, `@needmoretruth/nmts-cli/wallet-sign-external`: a program can
34
+ pay for an upload, an extension or a change to a storage resource with a wallet it holds no key to
35
+ — a browser extension, a hardware wallet, a remote signer — by handing over the payer's address and
36
+ a function that signs transaction bytes. The transactions are the same builders the key's own
37
+ signers use, this package submits them and reads the effects rather than trusting a digest, and a
38
+ wallet that declines is `WALLET_REFUSED`.
39
+ - A wallet-paid upload and an extension take that payer before they read a balance
40
+ (`WalletPutContext.payer`, `ExtendPlanSeams.payer`), so the quote, both balances, the measured
41
+ chain fee, the review and the sentence saying where to send coins all name the wallet that will
42
+ sign. Without a payer every one of them is the wallet this key derives, unchanged.
43
+ - An unfinished wallet-paid upload records which wallet paid, and a later run that would pay from a
44
+ different one is refused before it signs: what a registration creates belongs to the address that
45
+ signed for it.
46
+
6
47
  ## 0.42.0 — 2026-09-20
7
48
 
8
49
  - Nothing changes for the `nmts` command. The library surface gains one seam for programs built on
package/README.ko.md CHANGED
@@ -50,7 +50,7 @@ nmts --help
50
50
 
51
51
  ```sh
52
52
  npm install -g github:needmoretruth/nmts-cli # 기본 브랜치
53
- npm install -g github:needmoretruth/nmts-cli#v0.42.0 # 버전을 고정할 때
53
+ npm install -g github:needmoretruth/nmts-cli#v0.44.0 # 버전을 고정할 때
54
54
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
55
55
  ```
56
56
 
@@ -103,7 +103,9 @@ nmts get x # 파일 하나 다운로드
103
103
  것을 지웁니다.
104
104
 
105
105
  `nmts whoami --reveal`은 NMTS 키 자체를 찍습니다. `nmts unlock reveal`로 한 번 열기 전에는 잠겨
106
- 있고 실행마다 다시 묻습니다. 터미널을 기록하는 무엇이든 그때부터 NMTS 키를 갖게 됩니다.
106
+ 있고 실행마다 다시 묻습니다. 터미널을 기록하는 무엇이든 그때부터 NMTS 키를 갖게 됩니다. `--phrase`를
107
+ 붙이면 같은 키를 단어 15개의 복구 구문으로 찍습니다(`--lang ko`면 한국어 단어). `nmts login`은 둘 중 어느
108
+ 쪽도 받습니다.
107
109
 
108
110
  **어느 자격도 명령행 인자로는 받지 않습니다.** 어떤 프로세스든 다른 프로세스의 명령행 인자를 읽을 수
109
111
  있고, 셸은 그것을 기록에 남깁니다. 둘 다 그런 옵션이 없습니다.
@@ -435,6 +437,10 @@ docker run --rm \
435
437
 
436
438
  이름은 댔는데 없는 자격 파일은 어떤 요청보다 먼저 멈춥니다(종료 코드 3).
437
439
 
440
+ rootless Podman에서는 `examples/podman.sh`가 같은 일을 Podman 시크릿으로 합니다. 키는 컨테이너 안에
441
+ `/run/secrets/nmts-key` 파일로 들어가고, `podman inspect`에는 그 경로만 보입니다. `NMTS_ACCOUNT_CODE`와
442
+ `NMTS_ACCOUNT_CODE_FILE`이 둘 다 있으면 `NMTS_ACCOUNT_CODE`가 이기므로, 컨테이너 안에서는 그것을 비워 두십시오.
443
+
438
444
  잠금 상태와 모드는 설정 디렉터리에 있고, 지워진 컨테이너는 그것을 함께 가져갑니다. 새 컨테이너는 목록과
439
445
  다운로드는 그냥 되고, 업로드는 물으므로 스크립트는 `--yes`를 넘기며, 잠긴 것(지갑·공유)은 사람이 한 번 연
440
446
  설정 디렉터리를 컨테이너 밖에 두어야 합니다(`-v nmts-config:/config`). 직접 만든 이미지에서는
package/README.md CHANGED
@@ -51,7 +51,7 @@ default branch, from a pinned version, or from the tarball attached to the
51
51
 
52
52
  ```sh
53
53
  npm install -g github:needmoretruth/nmts-cli # the default branch
54
- npm install -g github:needmoretruth/nmts-cli#v0.42.0 # a pinned version
54
+ npm install -g github:needmoretruth/nmts-cli#v0.44.0 # a pinned version
55
55
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
56
56
  ```
57
57
 
@@ -106,7 +106,8 @@ handle and never the key itself, and does not replace a stored API key unless th
106
106
 
107
107
  `nmts whoami --reveal` prints your NMTS key itself. It is locked until you run `nmts unlock
108
108
  reveal` once, and asked about on every run; anything that logs your terminal has your NMTS key from
109
- then on.
109
+ then on. Add `--phrase` for the same key as its 15-word recovery phrase (`--lang ko` for Korean
110
+ words); `nmts login` accepts either form.
110
111
 
111
112
  **Neither credential is ever accepted as a command-line argument.** Any process can read another
112
113
  process's command line, and shells record it in history. There is no flag for either.
@@ -459,6 +460,11 @@ docker run --rm \
459
460
 
460
461
  A credential file that is named but missing is a hard stop (exit 3) before any request.
461
462
 
463
+ With rootless Podman, `examples/podman.sh` does the same through a Podman secret: the key reaches
464
+ the container as the file `/run/secrets/nmts-key`, and `podman inspect` shows only that path.
465
+ `NMTS_ACCOUNT_CODE` wins over `NMTS_ACCOUNT_CODE_FILE` when both are set, so leave it unset in a
466
+ container.
467
+
462
468
  Unlocks and the mode live in the config directory, and a container that is removed takes them
463
469
  with it. A fresh container lists and downloads freely; an upload asks, so a script passes `--yes`,
464
470
  and anything locked (the wallet, sharing) needs the config directory kept outside the container
package/dist/account.d.ts CHANGED
@@ -7,12 +7,16 @@ export interface AccountIdentity {
7
7
  displayCode: string;
8
8
  }
9
9
  /**
10
- * Check that a string is a real NMTS key.
10
+ * Check that a string is a real NMTS key — or its 15-word recovery phrase — and return the key in
11
+ * its display form, so what gets stored is the key whichever spelling was typed.
11
12
  *
12
13
  * ⛔ This is the engine's own parser, which verifies the trailing check symbol. A typo therefore
13
14
  * fails HERE, offline, instead of becoming a sign-in failure the person cannot tell apart from
14
- * a wrong password, a network problem or a suspended account.
15
+ * a wrong password, a network problem or a suspended account. The engine's own message is not
16
+ * repeated: it can contain the input.
15
17
  */
16
- export declare function assertUsableCode(code: string): Promise<void>;
18
+ export declare function assertUsableCode(code: string): Promise<string>;
17
19
  /** Derive the public facts about an account from its code. */
18
20
  export declare function identityOf(code: string): Promise<AccountIdentity>;
21
+ /** The NMTS key as its 15-word recovery phrase, in `en` (default) or `ko`. */
22
+ export declare function phraseOf(code: string, lang: string | undefined): Promise<string>;
package/dist/account.js CHANGED
@@ -22,38 +22,28 @@ import { toBase64Url } from "./bytes.js";
22
22
  import { DERIVED, loadCrypto } from "./crypto.js";
23
23
  import { NmtsError } from "./errors.js";
24
24
  /**
25
- * Check that a string is a real NMTS key.
25
+ * Check that a string is a real NMTS key — or its 15-word recovery phrase — and return the key in
26
+ * its display form, so what gets stored is the key whichever spelling was typed.
26
27
  *
27
28
  * ⛔ This is the engine's own parser, which verifies the trailing check symbol. A typo therefore
28
29
  * fails HERE, offline, instead of becoming a sign-in failure the person cannot tell apart from
29
- * a wrong password, a network problem or a suspended account.
30
+ * a wrong password, a network problem or a suspended account. The engine's own message is not
31
+ * repeated: it can contain the input.
30
32
  */
31
33
  export async function assertUsableCode(code) {
32
34
  const glue = await loadCrypto();
35
+ const bytes = parseKeyOrPhrase(glue, code);
33
36
  try {
34
- glue.account_code_parse(code);
37
+ return glue.account_code_display(bytes);
35
38
  }
36
- catch {
37
- // ⛔ The engine's own message is not repeated: it can contain the input.
38
- throw new NmtsError("That is not a valid NMTS key.", {
39
- exitCode: 2,
40
- nextStep: "Check for a mistyped or missing character. The last character is a check symbol.",
41
- });
39
+ finally {
40
+ bytes.fill(0);
42
41
  }
43
42
  }
44
43
  /** Derive the public facts about an account from its code. */
45
44
  export async function identityOf(code) {
46
45
  const glue = await loadCrypto();
47
- let bytes;
48
- try {
49
- bytes = glue.account_code_parse(code);
50
- }
51
- catch {
52
- throw new NmtsError("That is not a valid NMTS key.", {
53
- exitCode: 2,
54
- nextStep: "Check for a mistyped or missing character. The last character is a check symbol.",
55
- });
56
- }
46
+ const bytes = parseKeyOrPhrase(glue, code);
57
47
  // ⛔ WIPED, like every other derivation in this tool. This buffer is not an account id — it is
58
48
  // EVERY KEY IN THE ACCOUNT: the sign-in secret, the key that opens the files, the key that
59
49
  // opens the file list, and the wallet root. This one call site was leaving all of it live for
@@ -74,3 +64,40 @@ export async function identityOf(code) {
74
64
  bytes.fill(0);
75
65
  }
76
66
  }
67
+ /**
68
+ * The 20 bytes of an NMTS key or its 15-word recovery phrase. A phrase's refusal says which way it
69
+ * is wrong — a 12- or 24-word input is most likely a wallet's seed pasted into the wrong place.
70
+ */
71
+ function parseKeyOrPhrase(glue, input) {
72
+ try {
73
+ return glue.account_code_parse(input);
74
+ }
75
+ catch (e) {
76
+ const message = e instanceof Error ? e.message : String(e);
77
+ const nextStep = message.startsWith("phrase:count")
78
+ ? "An NMTS recovery phrase has 15 words. A 12- or 24-word phrase belongs to a wallet, not to NMTS."
79
+ : message.startsWith("phrase:word")
80
+ ? `Word ${message.split(":")[2] ?? "?"} is not in the recovery phrase word list. Check its spelling.`
81
+ : message.startsWith("phrase:checksum")
82
+ ? "Every word is in the list, but one is wrong or two are in the wrong order."
83
+ : "Check for a mistyped or missing character. The last character is a check symbol.";
84
+ throw new NmtsError("That is not a valid NMTS key or recovery phrase.", { exitCode: 2, nextStep });
85
+ }
86
+ }
87
+ /** The NMTS key as its 15-word recovery phrase, in `en` (default) or `ko`. */
88
+ export async function phraseOf(code, lang) {
89
+ if (lang !== undefined && lang !== "en" && lang !== "ko") {
90
+ throw new NmtsError(`There is no recovery phrase word list "${lang}".`, {
91
+ exitCode: 2,
92
+ nextStep: "--lang takes en or ko.",
93
+ });
94
+ }
95
+ const glue = await loadCrypto();
96
+ const bytes = parseKeyOrPhrase(glue, code);
97
+ try {
98
+ return glue.account_code_phrase(bytes, lang ?? "en");
99
+ }
100
+ finally {
101
+ bytes.fill(0);
102
+ }
103
+ }
@@ -52,6 +52,12 @@ export interface ParsedArgs {
52
52
  pay?: string;
53
53
  /** `put --pay wallet`: `fit`, `whole`, or a held storage resource's object id. */
54
54
  storage?: string;
55
+ /**
56
+ * `put --pay wallet --from <drive path>`: re-upload a file the account's credits paid for, this
57
+ * time on the wallet's money. The new file takes the old one's name and folder, and the old one
58
+ * goes to the trash.
59
+ */
60
+ from?: string;
55
61
  /** `consent grant wallet`: how long the grant lasts (days, at most 30), or until a date.
56
62
  * `key new`: how many days the new API key lasts. The server clamps at its own ceiling. */
57
63
  days?: string;
@@ -165,6 +171,8 @@ export interface ParsedArgs {
165
171
  * nothing and says what it does.
166
172
  */
167
173
  reveal: boolean;
174
+ /** `whoami --reveal --phrase`: the key as its 15-word recovery phrase. */
175
+ phrase: boolean;
168
176
  /**
169
177
  * `key new`: put the new key on the screen once, as well as storing it. A flag and not a value
170
178
  * for the reason above: it names no secret, it asks for the one this run was just handed.
@@ -187,4 +195,12 @@ export interface ParsedArgs {
187
195
  * copy kept here and a copy kept from the browser are the same file.
188
196
  */
189
197
  save: boolean;
198
+ /**
199
+ * `put`/`push`/`extend --pay wallet`: send the standing gift to the address THIS SERVER names,
200
+ * even when it is not the one built into this tool (`standing-tip.ts` `TIP_ADDRESS`).
201
+ *
202
+ * ⛔ FOR A SERVER YOU RUN YOURSELF AND NOTHING ELSE. Off by default: a server that can choose
203
+ * where a standing gift goes collects every one this machine sends.
204
+ */
205
+ trustServerTipAddress: boolean;
190
206
  }
package/dist/args.js CHANGED
@@ -52,6 +52,7 @@ const VALUE_OPTIONS = {
52
52
  // credential and lists this one as the exception it is: what it names is a FILE, the shape
53
53
  // this tool already recommends for every other secret (`NMTS_ACCOUNT_CODE_FILE`).
54
54
  "--sui-key-file": "suiKeyFile",
55
+ "--from": "from",
55
56
  "--account": "account",
56
57
  "--app": "app",
57
58
  };
@@ -101,6 +102,7 @@ const FLAG_OPTIONS = {
101
102
  "--desc": "desc",
102
103
  "--hidden": "hidden",
103
104
  "--reveal": "reveal",
105
+ "--phrase": "phrase",
104
106
  "--release-storage": "releaseStorage",
105
107
  "--print": "print",
106
108
  "--qr": "qr",
@@ -108,6 +110,7 @@ const FLAG_OPTIONS = {
108
110
  "--save": "save",
109
111
  "--remove": "remove",
110
112
  "--accept-extremes": "acceptExtremes",
113
+ "--trust-server-tip-address": "trustServerTipAddress",
111
114
  };
112
115
  // ⛔ Derived from the tables, not written again. A hand-kept list is how an option ends up tested
113
116
  // for one property and accepted with another. ⚠ Every option that carries a value is in here,
@@ -145,8 +148,8 @@ function append(parsed, field, value) {
145
148
  const FLAG_DEFAULTS = {
146
149
  help: false, version: false, json: false, all: false, force: false, dryRun: false, releaseStorage: false,
147
150
  yes: false, publish: false, plain: false, env: false, status: false,
148
- desc: false, hidden: false, reveal: false, print: false, qr: false, board: false,
149
- save: false, acceptExtremes: false, remove: false, noWait: false,
151
+ desc: false, hidden: false, reveal: false, phrase: false, print: false, qr: false, board: false,
152
+ save: false, acceptExtremes: false, remove: false, noWait: false, trustServerTipAddress: false,
150
153
  };
151
154
  export function parseArgs(argv) {
152
155
  const parsed = { command: null, operands: [], ...FLAG_DEFAULTS };
@@ -11,7 +11,7 @@ export declare const CRYPTO_SPEC_URL = "https://github.com/needmoretruth/nmts-re
11
11
  * is the field's own contract — what the writer says about itself — and a person holding two
12
12
  * copies of one account's artefacts can then tell which program made each.
13
13
  */
14
- export declare const WRITTEN_BY = "nmts-cli 0.42.0";
14
+ export declare const WRITTEN_BY = "nmts-cli 0.44.0";
15
15
  /** Which of the three artefacts a wrapper is. A reader holding several can sort them. */
16
16
  export type ArtifactKind = "recovery-list" | "file-list" | "recovery-kit";
17
17
  /**
@@ -0,0 +1,34 @@
1
+ import type { ParsedArgs } from "../args.ts";
2
+ export interface AiAccountOptions {
3
+ server?: string | undefined;
4
+ json?: boolean;
5
+ /** The tier gate's answer for the permanent act, or `--yes` under skip-permissions. */
6
+ yes?: boolean;
7
+ write?: (line: string) => void;
8
+ /** Injected in tests: answers the one typed line. Its presence stands in for a terminal. */
9
+ readLine?: (question: string) => Promise<string>;
10
+ }
11
+ /**
12
+ * `nmts ai-account <verb>`.
13
+ *
14
+ * ⛔ THE BARE WORD LISTS, AND THAT IS THE SAFE HALF ON PURPOSE. A command whose bare form created
15
+ * something would make `ai-account` a thing somebody runs to find out what it does.
16
+ */
17
+ export declare function aiAccount(verb: string | undefined, args: ParsedArgs): Promise<number>;
18
+ export declare function list(options?: AiAccountOptions): Promise<number>;
19
+ /**
20
+ * Make one.
21
+ *
22
+ * ⛔ THE KEY IS PRINTED ONCE AND IS NOT STORED ANYWHERE. It is what the AI is given; this machine
23
+ * goes on being the account it already was. It can be derived again from this account's key and
24
+ * the place, which is the one thing that makes printing it here safe to have missed.
25
+ */
26
+ export declare function create(asked: string | undefined, options?: AiAccountOptions): Promise<number>;
27
+ /**
28
+ * Erase one.
29
+ *
30
+ * ⛔ IT IS THE SAME ERASURE THE ACCOUNT ITSELF WOULD RUN — the row, the files, the keys, the shares
31
+ * in both directions — and nothing undoes it. The typed sentence is `delete-account`'s, because
32
+ * it is the same act aimed at a different account.
33
+ */
34
+ export declare function remove(id: string | undefined, options?: AiAccountOptions): Promise<number>;
@@ -0,0 +1,260 @@
1
+ // `nmts ai-account list|create|delete` — the accounts a person makes for an AI to work in, from a
2
+ // terminal.
3
+ //
4
+ // ⛔ WHY THEY EXIST AT ALL. Handing an AI this account's NMTS key hands it everything: the files,
5
+ // the wallet, the right to erase. An AI account is an ORDINARY account with its own key, its own
6
+ // wallet and its own empty drive, made under this one — so what is handed over is an account
7
+ // that holds nothing, and files reach it by being shared with it.
8
+ //
9
+ // ⛔ THE NMTS KEY PROVES IT, AND AN API KEY NEVER CAN. The three doors are closed to keys on
10
+ // purpose (`domain::agent_routes`): an AI that could make AI accounts is an account factory, and
11
+ // revoking its key would mean nothing once it had made three more. What travels is the derived
12
+ // proof — the same value a sign-in sends (`account-proof.ts`) — never the key.
13
+ //
14
+ // ⛔ AND THERE IS NO MCP TOOL FOR ANY OF IT, for the reason `key new` has none: the credential that
15
+ // mints credentials has to be the one a person holds.
16
+ //
17
+ // ⛔ THE NEW ACCOUNT'S KEY IS MADE HERE AND NEVER SENT. It is derived from this account's key and
18
+ // the place (NCF-3 §1.5), so the same place always gives the same account back — a key that was
19
+ // lost can be derived again, and an erased place can be re-used. What the server is told is the
20
+ // same pair a sign-in sends, exactly as the browser tells it.
21
+ import { identityOf } from "../account.js";
22
+ import { accountProof, accountProofFor } from "../account-proof.js";
23
+ import { request, ServerError } from "../api.js";
24
+ import { requireAccountCode } from "../code-access.js";
25
+ import { readCredentialsFile } from "../credentials.js";
26
+ import { DERIVED, loadCrypto } from "../crypto.js";
27
+ import { CONFIRM_SENTENCE } from "./delete-account.js";
28
+ import { NmtsError } from "../errors.js";
29
+ import { isRecord } from "../guards.js";
30
+ import { BINARY_NAME, HOME_URL } from "../product.js";
31
+ import { promptLine } from "../prompt.js";
32
+ import { resolveServer } from "../server.js";
33
+ /** How many places an account has for AI accounts of its own. The server's own ceiling. */
34
+ const PLACES = 3;
35
+ function childrenOf(answer) {
36
+ const list = isRecord(answer) ? answer["children"] : undefined;
37
+ if (!Array.isArray(list)) {
38
+ throw new NmtsError(`The server's answer did not carry a list of AI accounts.`, {
39
+ nextStep: `Nothing was changed. Report it rather than retrying — the shape, not the network, is wrong.`,
40
+ });
41
+ }
42
+ const out = [];
43
+ for (const row of list) {
44
+ if (!isRecord(row))
45
+ continue;
46
+ const id = row["account_id"];
47
+ const index = row["child_index"];
48
+ const created = row["created_at"];
49
+ const status = row["status"];
50
+ if (typeof id !== "string" || typeof index !== "number" || typeof created !== "string")
51
+ continue;
52
+ const code = row["public_code"];
53
+ out.push({
54
+ account_id: id,
55
+ child_index: index,
56
+ public_code: typeof code === "string" ? code : null,
57
+ created_at: created,
58
+ status: typeof status === "string" ? status : "active",
59
+ });
60
+ }
61
+ return out;
62
+ }
63
+ async function caller(options) {
64
+ const held = await requireAccountCode();
65
+ const stored = readCredentialsFile();
66
+ const server = resolveServer(options.server ?? stored?.server);
67
+ const identity = await identityOf(held.code);
68
+ // ⛔ BUILT FOR THIS ONE RUN AND KEPT BY NOBODY, and it asks for the agreement that covers sending
69
+ // it when the key came from an environment variable.
70
+ const authSecret = await accountProofFor({ code: held.code, source: held.source });
71
+ return { server, accountId: identity.accountId, authSecret, code: held.code };
72
+ }
73
+ async function listFor(who) {
74
+ return childrenOf(await request(who.server, "/v1/account/ai-accounts/list-by-code", {
75
+ method: "POST",
76
+ body: { account_id: who.accountId, auth_secret: who.authSecret },
77
+ }));
78
+ }
79
+ /**
80
+ * `nmts ai-account <verb>`.
81
+ *
82
+ * ⛔ THE BARE WORD LISTS, AND THAT IS THE SAFE HALF ON PURPOSE. A command whose bare form created
83
+ * something would make `ai-account` a thing somebody runs to find out what it does.
84
+ */
85
+ export async function aiAccount(verb, args) {
86
+ const options = { server: args.server, json: args.json, yes: args.yes };
87
+ if (verb === undefined || verb === "" || verb === "list")
88
+ return await list(options);
89
+ if (verb === "create")
90
+ return await create(args.operands[1], options);
91
+ if (verb === "delete")
92
+ return await remove(args.operands[1], options);
93
+ throw new NmtsError(`\`${verb}\` is not an ai-account verb.`, {
94
+ exitCode: 2,
95
+ nextStep: `The verbs are \`${BINARY_NAME} ai-account list\`, \`${BINARY_NAME} ai-account create [place]\` ` +
96
+ `and \`${BINARY_NAME} ai-account delete <account id>\`. Each needs the NMTS key on this ` +
97
+ `machine; an API key cannot reach any of them.`,
98
+ });
99
+ }
100
+ export async function list(options = {}) {
101
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
102
+ const who = await caller(options);
103
+ const children = await listFor(who);
104
+ if (options.json === true) {
105
+ say(JSON.stringify({ children }));
106
+ return 0;
107
+ }
108
+ if (children.length === 0) {
109
+ say(`This account has made no AI accounts.`);
110
+ say(`\`${BINARY_NAME} ai-account create\` makes one — an ordinary account with its own key and`);
111
+ say(`its own empty drive, so nothing of this one's is handed over.`);
112
+ return 0;
113
+ }
114
+ for (const child of children) {
115
+ say(`place ${child.child_index} ${child.account_id} ${child.status} made ${child.created_at.slice(0, 10)}`);
116
+ }
117
+ say(``);
118
+ say(`Each one's NMTS key comes from this account's key and its place, so it can be derived again`);
119
+ say(`— \`${BINARY_NAME} ai-account create <place>\` on a place that is already taken says so rather`);
120
+ say(`than printing it. \`${BINARY_NAME} ai-account delete <account id>\` erases one for good.`);
121
+ return 0;
122
+ }
123
+ /** The place this run uses: the one asked for, or the lowest that is free. */
124
+ function placeFor(asked, taken) {
125
+ if (asked !== undefined && asked !== "") {
126
+ if (!/^[0-9]+$/u.test(asked.trim())) {
127
+ throw new NmtsError(`A place is a whole number from 1 to ${PLACES}, not "${asked}".`, { exitCode: 2 });
128
+ }
129
+ const place = Number(asked.trim());
130
+ if (place < 1 || place > PLACES) {
131
+ throw new NmtsError(`This account has ${PLACES} places for AI accounts, numbered 1 to ${PLACES}.`, {
132
+ exitCode: 2,
133
+ nextStep: `Nothing was made. \`${BINARY_NAME} ai-account list\` says which are taken.`,
134
+ });
135
+ }
136
+ return place;
137
+ }
138
+ const used = new Set(taken.map((child) => child.child_index));
139
+ for (let place = 1; place <= PLACES; place += 1)
140
+ if (!used.has(place))
141
+ return place;
142
+ throw new NmtsError(`All ${PLACES} places under this account are taken.`, {
143
+ exitCode: 4,
144
+ nextStep: `Nothing was made. Erase one with \`${BINARY_NAME} ai-account delete <account id>\` — its place ` +
145
+ `comes free and re-deriving at that place later gives the same account back.`,
146
+ });
147
+ }
148
+ /**
149
+ * Make one.
150
+ *
151
+ * ⛔ THE KEY IS PRINTED ONCE AND IS NOT STORED ANYWHERE. It is what the AI is given; this machine
152
+ * goes on being the account it already was. It can be derived again from this account's key and
153
+ * the place, which is the one thing that makes printing it here safe to have missed.
154
+ */
155
+ export async function create(asked, options = {}) {
156
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
157
+ const who = await caller(options);
158
+ const place = placeFor(asked, await listFor(who));
159
+ // ⛔ DERIVED HERE AND SENT NOWHERE. What the server is told is the pair below, which is what a
160
+ // sign-in sends for any account; the key itself never leaves this process.
161
+ const glue = await loadCrypto();
162
+ const derived = glue.kdf_derive(glue.account_code_parse(who.code));
163
+ const [from, to] = DERIVED.aiAccountRoot;
164
+ let childCode;
165
+ try {
166
+ childCode = glue.derive_ai_account_code(derived.subarray(from, to), place);
167
+ }
168
+ finally {
169
+ derived.fill(0);
170
+ }
171
+ const childIdentity = await identityOf(childCode);
172
+ const childSecret = await accountProof(childCode);
173
+ try {
174
+ await request(who.server, "/v1/account/ai-accounts/by-code", {
175
+ method: "POST",
176
+ body: {
177
+ account_id: who.accountId,
178
+ auth_secret: who.authSecret,
179
+ child_account_id: childIdentity.accountId,
180
+ child_auth_secret: childSecret,
181
+ child_index: place,
182
+ },
183
+ // ⛔ NOT REPEATED ON A TIMEOUT. A request that reached the server and died on the way back has
184
+ // already spent a place and one of the day's creations; a retry would spend another.
185
+ retryBudgetMs: 0,
186
+ });
187
+ }
188
+ catch (error) {
189
+ if (error instanceof ServerError && error.code === "AI_ACCOUNTS_NEED_ENABLE") {
190
+ throw new NmtsError(`The first AI account under this account is made in a browser.`, {
191
+ exitCode: 4,
192
+ nextStep: `Nothing was made. Turning the feature on costs a human check, which no command-line tool ` +
193
+ `can pass — do it once on the account screen at ${HOME_URL}, and every one after it can be ` +
194
+ `made from here.`,
195
+ });
196
+ }
197
+ throw error;
198
+ }
199
+ if (options.json === true) {
200
+ // ⛔ THE KEY IS IN THE JSON, because there is nowhere else it could go and a caller that asked
201
+ // for a machine-readable answer is the caller that has to hand it to something.
202
+ say(JSON.stringify({ account_id: childIdentity.accountId, child_index: place, account_code: childCode }));
203
+ return 0;
204
+ }
205
+ say(`A new account for an AI exists, at place ${place}.`);
206
+ say(``);
207
+ say(` account id ${childIdentity.accountId}`);
208
+ say(``);
209
+ say(`⛔ THIS IS ITS NMTS KEY. It opens that account and nothing else — not this one.`);
210
+ say(` Hand it to the program that will use it, and keep it as carefully as your own.`);
211
+ say(``);
212
+ say(` ${childCode}`);
213
+ say(``);
214
+ say(`Nothing on this machine changed. The account is empty: it has its own wallet and no credits,`);
215
+ say(`and files reach it by being shared with it (\`${BINARY_NAME} share\`).`);
216
+ return 0;
217
+ }
218
+ /**
219
+ * Erase one.
220
+ *
221
+ * ⛔ IT IS THE SAME ERASURE THE ACCOUNT ITSELF WOULD RUN — the row, the files, the keys, the shares
222
+ * in both directions — and nothing undoes it. The typed sentence is `delete-account`'s, because
223
+ * it is the same act aimed at a different account.
224
+ */
225
+ export async function remove(id, options = {}) {
226
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
227
+ if (id === undefined || id === "") {
228
+ throw new NmtsError(`Say which AI account to erase.`, {
229
+ exitCode: 2,
230
+ nextStep: `\`${BINARY_NAME} ai-account delete <account id>\` — the id \`${BINARY_NAME} ai-account list\` prints.`,
231
+ });
232
+ }
233
+ const who = await caller(options);
234
+ say(`⛔ This erases AI account ${id} and everything in it. Nothing brings it back.`);
235
+ say(` Its place comes free: re-deriving at that place later gives the same account, empty.`);
236
+ const ask = options.readLine ?? promptLine;
237
+ const typed = options.yes === true ? CONFIRM_SENTENCE : (await ask(`Type exactly: ${CONFIRM_SENTENCE}\n> `)).trim();
238
+ if (typed !== CONFIRM_SENTENCE) {
239
+ say(`Nothing was erased.`);
240
+ return 1;
241
+ }
242
+ try {
243
+ await request(who.server, "/v1/account/ai-accounts/erase-by-code", {
244
+ method: "POST",
245
+ body: { account_id: who.accountId, auth_secret: who.authSecret, child_id: id },
246
+ retryBudgetMs: 0,
247
+ });
248
+ }
249
+ catch (error) {
250
+ if (error instanceof ServerError && error.status === 404) {
251
+ throw new NmtsError(`This account made no AI account with the id ${id}.`, {
252
+ exitCode: 4,
253
+ nextStep: `Nothing was erased. \`${BINARY_NAME} ai-account list\` says which ones exist.`,
254
+ });
255
+ }
256
+ throw error;
257
+ }
258
+ say(`Erased. The server holds nothing about that account now.`);
259
+ return 0;
260
+ }