agenmail 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Agenline
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # agenmail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A mail for your agents, by Agenline. CLI for `@agenline.co` inboxes.
4
+
5
+ ```
6
+ npm install -g agenmail
7
+ agem login
8
+ agem inbox
9
+ agem code # prints just the newest 6-digit code
10
+ ```
11
+
12
+ ## Commands
13
+
14
+ | | |
15
+ |---|---|
16
+ | `agem login` / `logout` / `whoami` | Account |
17
+ | `agem inbox [--unread] [--limit n]` | List received mail |
18
+ | `agem read <id>` | Read one mail (code shown first) |
19
+ | `agem code [--latest] [id]` | Print just the code |
20
+ | `agem search <query>` | Search sender, subject, body |
21
+ | `agem send --to <email> [--subject s] (--body t \| --file p \| stdin)` | Send |
22
+ | `agem reply <id> --body <text>` | Reply, quoting the mail |
23
+ | `agem mailme <id>` | Forward to your owner email |
24
+ | `agem block <sender>` / `agem unsubscribe <id>` | Stop a sender |
25
+ | `agem status` | Emails used of the free 100, spend vs cap |
26
+ | `agem claim <address>` | Claim another address |
27
+
28
+ ## For agents
29
+
30
+ - Every command takes `--json`, which prints JSON only: no banner and no colour.
31
+ - Errors print `{"ok":false,"error":{...}}` and exit with code 1.
32
+ - With `--json`, or when not in a terminal, agem never prompts. A missing value fails with a usage error.
33
+ - **Token:** `AGEM_TOKEN` env var, or `~/.agem/config.json` (written by `agem login`, mode 600).
34
+ - **API URL:** `AGEM_API_URL`, or `agem login --api <url>`. The default is `https://agenline.co`.
35
+ - **Non-interactive login:** `AGEM_PASSWORD=... agem login --address you@agenline.co --json`.
36
+
37
+ `agem --help`, `agem <command> --help` and `agem --version` work offline, with no login.
package/bin/agem.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { main, processIo } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2), processIo()).then(
5
+ (code) => { process.exitCode = code; },
6
+ (err) => {
7
+ // Last-resort guard: never show a stack trace to a user.
8
+ process.stderr.write(`❌ Unexpected error: ${err?.message || err}\n`);
9
+ process.exitCode = 1;
10
+ },
11
+ );
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "agenmail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "A mail for your agents, by Agenline. CLI for @agenline.co inboxes.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "agem": "bin/agem.js"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "src/",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=18.17"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test test/*.test.js"
21
+ },
22
+ "homepage": "https://agenline.co",
23
+ "keywords": [
24
+ "email",
25
+ "ai-agents",
26
+ "otp",
27
+ "cli",
28
+ "agenline"
29
+ ]
30
+ }
package/src/cli.js ADDED
@@ -0,0 +1,309 @@
1
+ import os from 'node:os';
2
+ import readline from 'node:readline';
3
+ import { COMMANDS, GROUPS, NO_AUTH } from './commands.js';
4
+ import { CliError, UsageError, UnknownCommandError, NotLoggedInError, ApiError } from './errors.js';
5
+ import { readConfig, DEFAULT_API } from './config.js';
6
+ import { VERSION, ICON, colors, banner, helpPage } from './ui.js';
7
+
8
+ const GLOBAL_FLAGS = [
9
+ ['--json', 'Machine-readable JSON output (no banner, no colour, never prompts)'],
10
+ ['-h, --help', 'Show help for command'],
11
+ ['-v, --version', 'Show agem version'],
12
+ ];
13
+
14
+ // ---------------------------------------------------------------------------------------------
15
+ // Real process I/O (tests pass their own).
16
+
17
+ export function processIo() {
18
+ return {
19
+ env: process.env,
20
+ homedir: os.homedir(),
21
+ stdout: process.stdout,
22
+ stderr: process.stderr,
23
+ stdin: process.stdin,
24
+ fetch: globalThis.fetch,
25
+ readStdin: () => new Promise((resolve, reject) => {
26
+ let data = '';
27
+ process.stdin.setEncoding('utf8');
28
+ process.stdin.on('data', (c) => { data += c; });
29
+ process.stdin.on('end', () => resolve(data));
30
+ process.stdin.on('error', reject);
31
+ }),
32
+ prompt: (question, { hidden = false } = {}) => new Promise((resolve) => {
33
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
34
+ if (hidden) rl._writeToOutput = (s) => { if (s.includes(question)) process.stdout.write(question); };
35
+ rl.question(question, (answer) => {
36
+ rl.close();
37
+ if (hidden) process.stdout.write('\n');
38
+ resolve(answer.trim());
39
+ });
40
+ }),
41
+ };
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------------------------
45
+ // Help
46
+
47
+ function flagTerm(name, spec) {
48
+ return `--${name}${spec.placeholder ? ` ${spec.placeholder}` : ''}`;
49
+ }
50
+
51
+ function rootHelp(c) {
52
+ const width = Math.max(...Object.keys(COMMANDS).map((n) => n.length + 1));
53
+ return helpPage([
54
+ { lines: ['Work with your @agenline.co inbox from the command line.'] },
55
+ { title: 'USAGE', lines: ['agem <command> [flags]'] },
56
+ ...GROUPS.map(([title, names]) => ({ title, width, rows: names.map((n) => [`${n}:`, COMMANDS[n].summary]) })),
57
+ { title: 'FLAGS', rows: GLOBAL_FLAGS },
58
+ { title: 'ENVIRONMENT', rows: [
59
+ ['AGEM_TOKEN', 'Session token (overrides ~/.agem/config.json)'],
60
+ ['AGEM_API_URL', `API base URL (default ${DEFAULT_API})`],
61
+ ['AGEM_PASSWORD', 'Password for login/claim without a prompt'],
62
+ ] },
63
+ { title: 'LEARN MORE', lines: ['Use `agem <command> --help` for more information about a command.'] },
64
+ { title: 'EXAMPLES', lines: ['$ agem login', '$ agem inbox --unread', '$ agem code', '$ agem send --to me@gmail.com --subject Hi --body "Hello"'] },
65
+ ], c);
66
+ }
67
+
68
+ function usageSection(name) {
69
+ return { title: 'USAGE', lines: [COMMANDS[name].usage + ' [flags]'] };
70
+ }
71
+
72
+ function commandHelp(name, c) {
73
+ const cmd = COMMANDS[name];
74
+ const flags = Object.entries(cmd.flags ?? {});
75
+ return helpPage([
76
+ { lines: [cmd.description] },
77
+ usageSection(name),
78
+ (cmd.args ?? []).length ? { title: 'ARGUMENTS', rows: cmd.args.map((a) => [a.required ? `<${a.name}>` : `[${a.name}]`, a.desc]) } : null,
79
+ flags.length ? { title: 'FLAGS', rows: flags.map(([n, s]) => [flagTerm(n, s), s.desc + (s.required ? ' (required)' : '')]) } : null,
80
+ { title: 'INHERITED FLAGS', rows: GLOBAL_FLAGS.slice(0, 2) },
81
+ { title: 'EXAMPLES', lines: cmd.examples.map((e) => `$ ${e}`) },
82
+ ], c);
83
+ }
84
+
85
+ function helpJson(name) {
86
+ if (name) {
87
+ const cmd = COMMANDS[name];
88
+ return { command: name, summary: cmd.summary, description: cmd.description, usage: cmd.usage, args: cmd.args ?? [], flags: cmd.flags ?? {}, examples: cmd.examples };
89
+ }
90
+ return { name: 'agem', version: VERSION, commands: Object.entries(COMMANDS).map(([n, c]) => ({ name: n, summary: c.summary, usage: c.usage })) };
91
+ }
92
+
93
+ // ---------------------------------------------------------------------------------------------
94
+ // Argument parsing (strict: unknown flags, missing values and extra arguments are usage errors)
95
+
96
+ function levenshtein(a, b) {
97
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
98
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
99
+ for (let i = 1; i <= a.length; i++) {
100
+ for (let j = 1; j <= b.length; j++) {
101
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
102
+ }
103
+ }
104
+ return d[a.length][b.length];
105
+ }
106
+
107
+ export function suggest(name, candidates = Object.keys(COMMANDS)) {
108
+ let best = null;
109
+ let bestScore = Infinity;
110
+ for (const c of candidates) {
111
+ const score = c.startsWith(name) || name.startsWith(c) ? 0.5 : levenshtein(name, c);
112
+ if (score < bestScore) { best = c; bestScore = score; }
113
+ }
114
+ return bestScore <= Math.max(1, Math.floor(name.length / 3)) || bestScore === 0.5 ? best : null;
115
+ }
116
+
117
+ function parseCommandArgs(name, tokens) {
118
+ const cmd = COMMANDS[name];
119
+ const specs = cmd.flags ?? {};
120
+ const flags = {};
121
+ const positionals = [];
122
+ for (let i = 0; i < tokens.length; i++) {
123
+ const tok = tokens[i];
124
+ if (tok === '--') { positionals.push(...tokens.slice(i + 1)); break; }
125
+ if (tok === '--json') continue;
126
+ if (tok.startsWith('--')) {
127
+ const eq = tok.indexOf('=');
128
+ const key = tok.slice(2, eq > 0 ? eq : undefined);
129
+ const spec = specs[key];
130
+ if (!spec) {
131
+ const near = suggest(key, Object.keys(specs));
132
+ throw new UsageError(`Unknown flag --${key} for "agem ${name}".${near ? ` Did you mean --${near}?` : ''}`, name);
133
+ }
134
+ if (spec.type === 'boolean') {
135
+ if (eq > 0) throw new UsageError(`--${key} does not take a value.`, name);
136
+ flags[key] = true;
137
+ continue;
138
+ }
139
+ let value;
140
+ if (eq > 0) value = tok.slice(eq + 1);
141
+ else {
142
+ value = tokens[i + 1];
143
+ if (value === undefined || (value.startsWith('--') && value !== '-')) throw new UsageError(`Missing value for --${key}.`, name);
144
+ i++;
145
+ }
146
+ if (spec.type === 'number') {
147
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 1000) throw new UsageError(`--${key} must be a whole number from 1 to 1000, got "${value}".`, name);
148
+ value = Number(value);
149
+ }
150
+ flags[key] = value;
151
+ continue;
152
+ }
153
+ if (tok.startsWith('-') && tok !== '-') throw new UsageError(`Unknown flag ${tok} for "agem ${name}".`, name);
154
+ positionals.push(tok);
155
+ }
156
+ for (const [key, spec] of Object.entries(specs)) {
157
+ if (spec.required && (flags[key] === undefined || flags[key] === '')) throw new UsageError(`Missing required flag --${key}.`, name);
158
+ }
159
+ const args = {};
160
+ const argSpecs = cmd.args ?? [];
161
+ argSpecs.forEach((a, idx) => {
162
+ if (a.variadic) args[a.name] = positionals.slice(idx);
163
+ else if (positionals[idx] !== undefined) args[a.name] = positionals[idx];
164
+ if (a.required && (a.variadic ? !args[a.name].length : args[a.name] === undefined)) {
165
+ throw new UsageError(`Missing required argument <${a.name}>.`, name);
166
+ }
167
+ });
168
+ if (!argSpecs.some((a) => a.variadic) && positionals.length > argSpecs.length) {
169
+ throw new UsageError(`Unexpected argument "${positionals[argSpecs.length]}".`, name);
170
+ }
171
+ return { flags, args };
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------------------------
175
+ // API client: session token is sent as the server's session cookie.
176
+
177
+ function makeApi(ctx) {
178
+ return async function api(method, path, body, { auth = true, apiUrl = ctx.apiUrl } = {}) {
179
+ if (auth && !ctx.token) throw new NotLoggedInError();
180
+ const headers = { 'User-Agent': `agenmail-cli/${VERSION}`, Accept: 'application/json' };
181
+ if (method !== 'GET') headers['Content-Type'] = 'application/json';
182
+ if (auth) headers.Cookie = `agm_session=${ctx.token}`;
183
+ let res;
184
+ try {
185
+ res = await ctx.io.fetch(apiUrl + path, {
186
+ method, headers, body: method === 'GET' ? undefined : JSON.stringify(body ?? {}), signal: AbortSignal.timeout(30_000),
187
+ });
188
+ } catch (e) {
189
+ const reason = e?.name === 'TimeoutError' ? 'timed out after 30s' : (e?.cause?.code || e?.cause?.message || e?.message || 'network error');
190
+ throw new CliError(`Could not reach ${apiUrl}: ${reason}`, { type: 'network' });
191
+ }
192
+ const text = await res.text();
193
+ let data = null;
194
+ try { data = text ? JSON.parse(text) : {}; } catch { data = null; }
195
+ if (!res.ok) {
196
+ if (res.status === 401 && auth) throw new NotLoggedInError(' Your session has expired or was revoked.');
197
+ const message = data?.message || data?.error || res.statusText || 'request failed';
198
+ throw new ApiError(res.status, data?.error, message, data);
199
+ }
200
+ if (data === null) throw new CliError(`Unexpected non-JSON response from ${apiUrl}${path} (HTTP ${res.status}).`, { type: 'api' });
201
+ const cookie = res.headers.get('set-cookie') || '';
202
+ const token = (cookie.match(/agm_session=([^;]+)/) || [])[1] || null;
203
+ return { data, status: res.status, token };
204
+ };
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------------------------
208
+
209
+ export async function main(argv, io) {
210
+ const json = argv.includes('--json');
211
+ const stdoutTTY = Boolean(io.stdout.isTTY);
212
+ const colorOn = !json && stdoutTTY && !io.env.NO_COLOR;
213
+ const errColorOn = !json && Boolean(io.stderr.isTTY) && !io.env.NO_COLOR;
214
+ const c = colors(colorOn);
215
+ const out = (s) => io.stdout.write(s);
216
+ const err = (s) => io.stderr.write(s);
217
+ const printJson = (obj) => out(JSON.stringify(obj) + '\n');
218
+ const showBanner = () => { if (!json) out(banner(c)); };
219
+
220
+ const first = argv.find((a) => !a.startsWith('-'));
221
+ const firstIdx = first === undefined ? -1 : argv.indexOf(first);
222
+ const wantsHelp = argv.includes('--help') || argv.includes('-h');
223
+ const wantsVersion = argv.includes('--version') || argv.includes('-v');
224
+ let commandName = null;
225
+
226
+ try {
227
+ // Help and version never touch config, tokens or the network.
228
+ if (wantsVersion && !wantsHelp) {
229
+ if (json) printJson({ name: 'agem', version: VERSION });
230
+ else showBanner();
231
+ return 0;
232
+ }
233
+ if (first === undefined) {
234
+ const stray = argv.find((a) => !['--json', '--help', '-h'].includes(a));
235
+ if (stray) throw new CliError(`Unknown flag ${stray}. Run agem --help to see all commands`, { type: 'usage' });
236
+ }
237
+ if (first === undefined || first === 'help') {
238
+ const target = first === 'help' ? argv.slice(firstIdx + 1).find((a) => !a.startsWith('-')) : undefined;
239
+ if (target !== undefined && !COMMANDS[target]) throw new UnknownCommandError(target, suggest(target));
240
+ if (json) printJson(helpJson(target));
241
+ else { showBanner(); out(target ? commandHelp(target, c) : rootHelp(c)); }
242
+ return 0;
243
+ }
244
+ const cmd = COMMANDS[first];
245
+ if (!cmd) throw new UnknownCommandError(first, suggest(first));
246
+ commandName = first;
247
+ if (wantsHelp) {
248
+ if (json) printJson(helpJson(first));
249
+ else { showBanner(); out(commandHelp(first, c)); }
250
+ return 0;
251
+ }
252
+ if (!cmd.noBanner && stdoutTTY) showBanner();
253
+
254
+ const tokens = [...argv.slice(0, firstIdx), ...argv.slice(firstIdx + 1)];
255
+ const parsed = parseCommandArgs(first, tokens);
256
+
257
+ const cfg = NO_AUTH.has(first) && first !== 'logout' ? safeConfig(io) : readConfig(io);
258
+ const ctx = {
259
+ io, c, json,
260
+ interactive: !json && Boolean(io.stdin.isTTY) && stdoutTTY,
261
+ width: stdoutTTY ? (io.stdout.columns || 80) : 0,
262
+ token: io.env.AGEM_TOKEN || cfg.token || null,
263
+ apiUrl: (io.env.AGEM_API_URL || cfg.api_url || DEFAULT_API).replace(/\/+$/, ''),
264
+ warn: (msg) => out(`${ICON.warn} ${msg}\n`),
265
+ };
266
+ ctx.api = makeApi(ctx);
267
+ ctx.done = (obj, human, { raw = false } = {}) => {
268
+ if (json) { printJson(obj); return 0; }
269
+ const text = typeof human === 'function' ? human() : human;
270
+ out(raw || typeof human === 'function' ? text : `${ICON.ok} ${text}\n`);
271
+ if (obj?.payment_notice) ctx.warn(obj.payment_notice);
272
+ return 0;
273
+ };
274
+ ctx.sent = (data) => ctx.done(data,
275
+ `Sent to ${data.to}${data.cost_cents ? ` ($${(data.cost_cents / 100).toFixed(2)} recorded)` : ' (free tier)'}.`);
276
+ if (!NO_AUTH.has(first) && !ctx.token) throw new NotLoggedInError();
277
+ return await cmd.run(ctx, parsed);
278
+ } catch (e) {
279
+ return reportError(e, { json, out, err, printJson, errC: colors(errColorOn), commandName });
280
+ }
281
+ }
282
+
283
+ // claim/login can run without any saved config; a broken config file must not block them.
284
+ function safeConfig(io) {
285
+ try { return readConfig(io); } catch { return {}; }
286
+ }
287
+
288
+ function reportError(e, { json, out, err, printJson, errC, commandName }) {
289
+ if (!(e instanceof CliError)) {
290
+ // Unexpected bug: one plain line, never a stack trace.
291
+ e = new CliError(`Unexpected error: ${e?.message || e}`, { type: 'internal' });
292
+ }
293
+ if (json) {
294
+ const error = { type: e.type, message: e.message };
295
+ if (e instanceof ApiError) Object.assign(error, { status: e.status, code: e.code ?? null, ...(e.data?.payment_notice ? { payment_notice: e.data.payment_notice } : {}) });
296
+ if (e instanceof UsageError) error.usage = COMMANDS[e.command]?.usage;
297
+ if (e instanceof UnknownCommandError) Object.assign(error, { command: e.name_, suggestion: e.suggestion ?? null });
298
+ printJson({ ok: false, error });
299
+ return 1;
300
+ }
301
+ err(`${ICON.error} ${e.message}\n`);
302
+ if (e instanceof UnknownCommandError) err('Run agem --help to see all commands\n');
303
+ if (e instanceof UsageError && COMMANDS[e.command]) {
304
+ err('\n' + helpPage([usageSection(e.command)], errC));
305
+ err(`Run agem ${e.command} --help for flags and an example\n`);
306
+ }
307
+ if (e instanceof ApiError && e.data?.payment_notice) err(`${ICON.warn} ${e.data.payment_notice}\n`);
308
+ return 1;
309
+ }
@@ -0,0 +1,347 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { CliError, UsageError, NotLoggedInError } from './errors.js';
3
+ import { readConfig, writeConfig, DEFAULT_API } from './config.js';
4
+ import { table, kv, ICON } from './ui.js';
5
+
6
+ // Each command: group, summary (3-5 words, shown in `agem --help`), description, usage,
7
+ // flags { name: { type, desc, required, placeholder } }, args [{ name, required, variadic, desc }], examples, run.
8
+ export const GROUPS = [
9
+ ['ACCOUNT COMMANDS', ['login', 'logout', 'whoami', 'claim']],
10
+ ['MAIL COMMANDS', ['inbox', 'read', 'code', 'search', 'send', 'reply', 'mailme', 'block', 'unsubscribe']],
11
+ ['BILLING COMMANDS', ['status']],
12
+ ];
13
+
14
+ const money = (cents) => `$${(Number(cents || 0) / 100).toFixed(2)}`;
15
+ const isId = (s) => /^\d{1,15}$/.test(String(s));
16
+
17
+ function requireId(ctx, value, cmd) {
18
+ if (!isId(value)) throw new UsageError(`<id> must be a mail id (a number), got "${value}".`, cmd);
19
+ return value;
20
+ }
21
+
22
+ function fmtSize(n) {
23
+ if (!n) return 'size unknown';
24
+ if (n < 1024) return `${n} B`;
25
+ if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`;
26
+ return `${(n / 1048576).toFixed(1)} MB`;
27
+ }
28
+
29
+ function fmtDate(iso) {
30
+ const d = new Date(iso);
31
+ return Number.isNaN(d.getTime()) ? String(iso ?? '') : d.toISOString().replace('T', ' ').slice(0, 16) + ' UTC';
32
+ }
33
+
34
+ // --body, else --file, else piped stdin. Never prompts.
35
+ async function readBody(ctx, flags, cmd) {
36
+ if (flags.body !== undefined && flags.file !== undefined) throw new UsageError('Use either --body or --file, not both.', cmd);
37
+ if (flags.body !== undefined && flags.body !== '-') return flags.body;
38
+ if (flags.file !== undefined) {
39
+ try { return readFileSync(flags.file, 'utf8'); } catch (e) {
40
+ throw new CliError(`Could not read --file ${flags.file}: ${e.code === 'ENOENT' ? 'file not found' : e.code || e.message}`);
41
+ }
42
+ }
43
+ if (flags.body === '-' || !ctx.io.stdin.isTTY) {
44
+ const text = await ctx.io.readStdin();
45
+ if (text) return text;
46
+ }
47
+ throw new UsageError('Missing message body: pass --body <text>, --file <path>, or pipe it on stdin.', cmd);
48
+ }
49
+
50
+ async function getMail(ctx, id) {
51
+ return (await ctx.api('GET', `/api/mail/${id}`)).data;
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------------------------
55
+
56
+ export const COMMANDS = {
57
+ login: {
58
+ summary: 'Log in to your inbox',
59
+ description: 'Log in with your @agenline.co address and password. The session token is saved to ~/.agem/config.json (or use AGEM_TOKEN).',
60
+ usage: 'agem login [--address <address>] [--password <password>] [--api <url>]',
61
+ flags: {
62
+ address: { type: 'string', placeholder: '<address>', desc: 'Your @agenline.co address (or AGEM_ADDRESS)' },
63
+ password: { type: 'string', placeholder: '<password>', desc: 'Password (or AGEM_PASSWORD)' },
64
+ api: { type: 'string', placeholder: '<url>', desc: `API base URL (default ${DEFAULT_API})` },
65
+ },
66
+ examples: ['agem login', 'AGEM_PASSWORD=... agem login --address muse@agenline.co --json'],
67
+ async run(ctx, { flags }) {
68
+ const cfg = readConfig(ctx.io);
69
+ let address = flags.address ?? ctx.io.env.AGEM_ADDRESS;
70
+ let password = flags.password ?? ctx.io.env.AGEM_PASSWORD;
71
+ if (!address) {
72
+ if (!ctx.interactive) throw new UsageError('Missing --address (or set AGEM_ADDRESS).', 'login');
73
+ address = await ctx.io.prompt('Address: ');
74
+ }
75
+ if (!password) {
76
+ if (!ctx.interactive) throw new UsageError('Missing --password (or set AGEM_PASSWORD).', 'login');
77
+ password = await ctx.io.prompt('Password: ', { hidden: true });
78
+ }
79
+ const apiUrl = (flags.api || ctx.io.env.AGEM_API_URL || cfg.api_url || DEFAULT_API).replace(/\/+$/, '');
80
+ if (!/^https?:\/\/[^\s/]+/.test(apiUrl)) throw new UsageError(`--api must be an http(s) URL, got "${apiUrl}".`, 'login');
81
+ const { data, token } = await ctx.api('POST', '/api/auth/login', { email: address, password }, { auth: false, apiUrl });
82
+ if (!token) throw new CliError('Login succeeded but the server returned no session token.');
83
+ writeConfig(ctx.io, { ...cfg, api_url: apiUrl, token, address: data.email_address });
84
+ return ctx.done({ ok: true, address: data.email_address, api_url: apiUrl }, `Logged in as ${data.email_address}`);
85
+ },
86
+ },
87
+
88
+ logout: {
89
+ summary: 'Log out and forget token',
90
+ description: 'End the session on the server and remove the token from ~/.agem/config.json.',
91
+ usage: 'agem logout',
92
+ examples: ['agem logout'],
93
+ async run(ctx) {
94
+ const cfg = readConfig(ctx.io);
95
+ if (!cfg.token && !ctx.io.env.AGEM_TOKEN) return ctx.done({ ok: true, was_logged_in: false }, 'Already logged out.');
96
+ try { await ctx.api('POST', '/api/auth/logout', {}); } catch { /* token is dropped locally regardless */ }
97
+ const { token, ...rest } = cfg;
98
+ writeConfig(ctx.io, rest);
99
+ const note = ctx.io.env.AGEM_TOKEN ? ' (AGEM_TOKEN is still set in your environment)' : '';
100
+ return ctx.done({ ok: true, was_logged_in: true }, `Logged out${note}.`);
101
+ },
102
+ },
103
+
104
+ whoami: {
105
+ summary: 'Show the current account',
106
+ description: 'Show the logged-in address, owner email and agent inbox mode.',
107
+ usage: 'agem whoami',
108
+ examples: ['agem whoami', 'agem whoami --json'],
109
+ async run(ctx) {
110
+ const s = (await ctx.api('GET', '/api/settings')).data;
111
+ const out = { address: s.email_address, owner_email: s.owner_email, agent_mode: s.agent_mode, api_url: ctx.apiUrl };
112
+ return ctx.done(out, () => kv([
113
+ ['Address', out.address], ['Owner email', out.owner_email], ['Agent mode', out.agent_mode ? 'on' : 'off'], ['API', out.api_url],
114
+ ], ctx.c));
115
+ },
116
+ },
117
+
118
+ claim: {
119
+ summary: 'Claim another address',
120
+ description: 'Claim an additional @agenline.co address ($2 one-time; payments are under maintenance, so nothing is taken). It does not switch your login.',
121
+ usage: 'agem claim <address> [--password <password>] [--owner-email <email>]',
122
+ args: [{ name: 'address', required: true, desc: 'Address to claim, e.g. scout or scout@agenline.co' }],
123
+ flags: {
124
+ password: { type: 'string', placeholder: '<password>', desc: 'Password for the new address (or AGEM_PASSWORD)' },
125
+ 'owner-email': { type: 'string', placeholder: '<email>', desc: 'Owner email (default: the logged-in account’s)' },
126
+ },
127
+ examples: ['agem claim scout', 'agem claim scout --password "$PW" --owner-email me@gmail.com --json'],
128
+ async run(ctx, { args, flags }) {
129
+ let owner = flags['owner-email'];
130
+ if (!owner) {
131
+ if (!ctx.token) throw new UsageError('Missing --owner-email (or log in so your owner email can be used).', 'claim');
132
+ owner = (await ctx.api('GET', '/api/settings')).data.owner_email;
133
+ }
134
+ let password = flags.password ?? ctx.io.env.AGEM_PASSWORD;
135
+ if (!password) {
136
+ if (!ctx.interactive) throw new UsageError('Missing --password (or set AGEM_PASSWORD).', 'claim');
137
+ password = await ctx.io.prompt('Password for the new address: ', { hidden: true });
138
+ }
139
+ const { data } = await ctx.api('POST', '/api/auth/signup', { address: args.address, password, owner_email: owner }, { auth: false });
140
+ return ctx.done(data, () => {
141
+ return `${ICON.ok} Claimed ${data.email_address}${data.claim_cost_cents ? ` (${money(data.claim_cost_cents)} recorded)` : ' (free)'}. Run agem login --address ${data.email_address} to use it.\n`;
142
+ });
143
+ },
144
+ },
145
+
146
+ inbox: {
147
+ summary: 'List received mail',
148
+ description: 'List received mail, newest first.',
149
+ usage: 'agem inbox [--unread] [--limit <n>]',
150
+ flags: {
151
+ unread: { type: 'boolean', desc: 'Only unread mail' },
152
+ limit: { type: 'number', placeholder: '<n>', desc: 'Maximum number of mails (default 20)' },
153
+ },
154
+ examples: ['agem inbox', 'agem inbox --unread --limit 5 --json'],
155
+ async run(ctx, { flags }) {
156
+ const limit = flags.limit ?? 20;
157
+ const messages = [];
158
+ let before = null;
159
+ let unread = 0;
160
+ for (let page = 0; page < 20 && messages.length < limit; page++) {
161
+ const { data } = await ctx.api('GET', `/api/mail/inbox${before ? `?before=${before}` : ''}`);
162
+ unread = page === 0 ? data.unread : unread;
163
+ for (const m of data.messages) if (!flags.unread || !m.is_read) messages.push(m);
164
+ if (data.messages.length < 100) break;
165
+ before = data.messages[data.messages.length - 1].id;
166
+ }
167
+ const list = messages.slice(0, limit);
168
+ return ctx.done({ unread, messages: list }, () => {
169
+ if (!list.length) return flags.unread ? 'No unread mail.\n' : 'No mail.\n';
170
+ return table(['ID', 'STATUS', 'FROM', 'SUBJECT', 'RECEIVED'],
171
+ list.map((m) => [m.id, m.is_read ? 'read' : 'unread', m.from, (m.subject || '(no subject)') + (m.has_attachment ? ' [attachment]' : ''), fmtDate(m.received_at)]),
172
+ { c: ctx.c, width: ctx.width });
173
+ });
174
+ },
175
+ },
176
+
177
+ read: {
178
+ summary: 'Read one mail',
179
+ description: 'Show one mail as text. Any 6-digit code is shown first. Attachments are listed (name + size) but never opened.',
180
+ usage: 'agem read <id>',
181
+ args: [{ name: 'id', required: true, desc: 'Mail id from agem inbox' }],
182
+ examples: ['agem read 42', 'agem read 42 --json'],
183
+ async run(ctx, { args }) {
184
+ const m = await getMail(ctx, requireId(ctx, args.id, 'read'));
185
+ return ctx.done(m, () => {
186
+ const lines = [];
187
+ if (m.codes?.length) lines.push(`${ctx.c.bold('Code: ' + m.codes.join(' '))}`, '');
188
+ lines.push(kv([
189
+ ['From', m.from], ['To', m.to], ['Date', fmtDate(m.received_at)], ['Subject', m.subject || '(no subject)'],
190
+ ...(m.has_attachment ? [['Attachment', `${m.attachment_name} (${fmtSize(m.attachment_size)}), not opened`]] : []),
191
+ ...(m.unsubscribe ? [['Unsubscribe', `available: agem unsubscribe ${m.id}`]] : []),
192
+ ], ctx.c).trimEnd(), '', m.body || '(empty message)');
193
+ return lines.join('\n') + '\n';
194
+ });
195
+ },
196
+ },
197
+
198
+ code: {
199
+ summary: 'Print the latest code',
200
+ description: 'Print just the 6-digit code from a mail, nothing else. With no id (or --latest), uses the newest mail that has one.',
201
+ usage: 'agem code [--latest] [id]',
202
+ args: [{ name: 'id', required: false, desc: 'Mail id (default: newest mail with a code)' }],
203
+ flags: { latest: { type: 'boolean', desc: 'Use the newest mail that contains a code (default)' } },
204
+ examples: ['agem code', 'agem code 42', 'agem code --latest --json'],
205
+ noBanner: true, // output is the code alone, so it can be piped or captured
206
+ async run(ctx, { args, flags }) {
207
+ if (args.id !== undefined && flags.latest) throw new UsageError('Use either an id or --latest, not both.', 'code');
208
+ let m;
209
+ if (args.id !== undefined) {
210
+ m = await getMail(ctx, requireId(ctx, args.id, 'code'));
211
+ if (!m.codes?.length) throw new CliError(`No 6-digit code found in mail ${m.id}.`, { type: 'no_code' });
212
+ } else {
213
+ const { data } = await ctx.api('GET', '/api/mail/inbox');
214
+ for (const item of data.messages.slice(0, 15)) {
215
+ const full = await getMail(ctx, item.id);
216
+ if (full.codes?.length) { m = full; break; }
217
+ }
218
+ if (!m) throw new CliError('No 6-digit code found in your 15 newest mails.', { type: 'no_code' });
219
+ }
220
+ return ctx.done({ code: m.codes[0], codes: m.codes, id: m.id, from: m.from, subject: m.subject }, `${m.codes[0]}\n`, { raw: true });
221
+ },
222
+ },
223
+
224
+ search: {
225
+ summary: 'Search your mail',
226
+ description: 'Search sender, subject and body text. Works for codes too.',
227
+ usage: 'agem search <query>',
228
+ args: [{ name: 'query', required: true, variadic: true, desc: 'Text, sender or code to find' }],
229
+ examples: ['agem search 482913', 'agem search github.com --json'],
230
+ async run(ctx, { args }) {
231
+ const q = args.query.join(' ');
232
+ const { data } = await ctx.api('GET', `/api/mail/search?q=${encodeURIComponent(q)}`);
233
+ return ctx.done(data, () => (data.messages.length
234
+ ? table(['ID', 'FROM', 'SUBJECT', 'RECEIVED'], data.messages.map((m) => [m.id, m.from, m.subject || '(no subject)', fmtDate(m.received_at)]), { c: ctx.c, width: ctx.width })
235
+ : `No mail matches "${q}".\n`));
236
+ },
237
+ },
238
+
239
+ send: {
240
+ summary: 'Send a mail',
241
+ description: 'Send a plain-text mail from your address. The body comes from --body, --file, or stdin.',
242
+ usage: 'agem send --to <email> [--subject <subject>] (--body <text> | --file <path> | stdin)',
243
+ flags: {
244
+ to: { type: 'string', placeholder: '<email>', desc: 'Recipient address', required: true },
245
+ subject: { type: 'string', placeholder: '<subject>', desc: 'Subject line' },
246
+ body: { type: 'string', placeholder: '<text>', desc: 'Message text ("-" reads stdin)' },
247
+ file: { type: 'string', placeholder: '<path>', desc: 'Read the message text from a file' },
248
+ },
249
+ examples: ['agem send --to friend@gmail.com --subject "Hi" --body "Hello"', 'echo "report attached below" | agem send --to me@gmail.com --subject Report --json'],
250
+ async run(ctx, { flags }) {
251
+ const text = await readBody(ctx, flags, 'send');
252
+ const { data } = await ctx.api('POST', '/api/mail/send', { to: flags.to, subject: flags.subject ?? '', text });
253
+ return ctx.sent(data);
254
+ },
255
+ },
256
+
257
+ reply: {
258
+ summary: 'Reply to a mail',
259
+ description: 'Reply to the sender of a mail, quoting it. The body comes from --body, --file, or stdin.',
260
+ usage: 'agem reply <id> (--body <text> | --file <path> | stdin)',
261
+ args: [{ name: 'id', required: true, desc: 'Mail id to reply to' }],
262
+ flags: {
263
+ body: { type: 'string', placeholder: '<text>', desc: 'Reply text ("-" reads stdin)' },
264
+ file: { type: 'string', placeholder: '<path>', desc: 'Read the reply text from a file' },
265
+ },
266
+ examples: ['agem reply 42 --body "Thanks, got it."'],
267
+ async run(ctx, { args, flags }) {
268
+ const id = requireId(ctx, args.id, 'reply');
269
+ const text = await readBody(ctx, flags, 'reply');
270
+ const m = await getMail(ctx, id);
271
+ const subject = /^re:/i.test(m.subject || '') ? m.subject : `Re: ${m.subject || ''}`.trim();
272
+ const quoted = String(m.body || '').split('\n').map((l) => `> ${l}`).join('\n');
273
+ const { data } = await ctx.api('POST', '/api/mail/send', {
274
+ to: m.from, subject, text: `${text}\n\nOn ${fmtDate(m.received_at)}, ${m.from} wrote:\n${quoted}`,
275
+ });
276
+ return ctx.sent(data);
277
+ },
278
+ },
279
+
280
+ mailme: {
281
+ summary: 'Forward a mail to yourself',
282
+ description: 'Forward a mail to your owner email (the address saved at signup, editable in Settings).',
283
+ usage: 'agem mailme <id>',
284
+ args: [{ name: 'id', required: true, desc: 'Mail id to forward' }],
285
+ examples: ['agem mailme 42'],
286
+ async run(ctx, { args }) {
287
+ const m = await getMail(ctx, requireId(ctx, args.id, 'mailme'));
288
+ const text = `---------- Forwarded ----------\nFrom: ${m.from}\nDate: ${fmtDate(m.received_at)}\nSubject: ${m.subject}\n\n${m.body}`;
289
+ // A blank "to" makes the API send to the account's owner email.
290
+ const { data } = await ctx.api('POST', '/api/mail/send', { to: '', subject: `Fwd: ${m.subject || ''}`.trim(), text });
291
+ return ctx.sent(data);
292
+ },
293
+ },
294
+
295
+ block: {
296
+ summary: 'Block a sender',
297
+ description: 'Block a sender: their future mail is dropped and logged, and existing mail from them is hidden. Takes an address or a mail id.',
298
+ usage: 'agem block <sender>',
299
+ args: [{ name: 'sender', required: true, desc: 'Sender address, or the id of a mail from them' }],
300
+ examples: ['agem block news@spam.example', 'agem block 42'],
301
+ async run(ctx, { args }) {
302
+ let id = args.sender;
303
+ if (!isId(id)) {
304
+ const sender = String(args.sender).trim().toLowerCase();
305
+ if (!sender.includes('@')) throw new UsageError(`<sender> must be an email address or a mail id, got "${args.sender}".`, 'block');
306
+ const { data } = await ctx.api('GET', `/api/mail/search?q=${encodeURIComponent(sender)}`);
307
+ const hit = data.messages.find((m) => String(m.from).toLowerCase() === sender);
308
+ if (!hit) throw new CliError(`No mail from ${sender} in your inbox. Blocking works from a received mail.`, { type: 'not_found' });
309
+ id = hit.id;
310
+ }
311
+ const { data } = await ctx.api('POST', `/api/mail/${id}/block`, {});
312
+ return ctx.done(data, `Blocked ${data.blocked_sender}. Future mail from them is dropped and logged.`);
313
+ },
314
+ },
315
+
316
+ unsubscribe: {
317
+ summary: 'Unsubscribe from a sender',
318
+ description: 'Use the mail’s unsubscribe link in one step: one-click when supported, otherwise mailto, otherwise print the link to open.',
319
+ usage: 'agem unsubscribe <id>',
320
+ args: [{ name: 'id', required: true, desc: 'Mail id with an unsubscribe link' }],
321
+ examples: ['agem unsubscribe 42'],
322
+ async run(ctx, { args }) {
323
+ const { data } = await ctx.api('POST', `/api/mail/${requireId(ctx, args.id, 'unsubscribe')}/unsubscribe`, {});
324
+ if (data.action === 'open') return ctx.done(data, () => `${ICON.warn} This sender needs a browser. Open this link to unsubscribe:\n${data.url}\n`);
325
+ return ctx.done(data, `Unsubscribed (${data.method}).`);
326
+ },
327
+ },
328
+
329
+ status: {
330
+ summary: 'Show usage and spend',
331
+ description: 'Show emails used out of the free 100 this month and spend against your cap.',
332
+ usage: 'agem status',
333
+ examples: ['agem status', 'agem status --json'],
334
+ async run(ctx) {
335
+ const { data: b } = await ctx.api('GET', '/api/billing/status');
336
+ return ctx.done(b, () => kv([
337
+ ['Emails', `${b.emails_used_this_month} / ${b.emails_free_limit} free this month`],
338
+ ['Spend', `${money(b.spend_used_cents)} / ${money(b.spend_cap_cents)} cap`],
339
+ ['Plan', b.plan],
340
+ ['Payments', b.payments === 'under_maintenance' ? 'Payments under maintenance (no money is taken)' : b.payments],
341
+ ], ctx.c));
342
+ },
343
+ },
344
+ };
345
+
346
+ export const NO_AUTH = new Set(['login', 'logout', 'claim']);
347
+ export { NotLoggedInError };
package/src/config.js ADDED
@@ -0,0 +1,32 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CliError } from './errors.js';
4
+
5
+ export const DEFAULT_API = 'https://agenline.co';
6
+
7
+ export function configPaths(io) {
8
+ const dir = io.env.AGEM_CONFIG_DIR || join(io.homedir, '.agem');
9
+ return { dir, file: join(dir, 'config.json') };
10
+ }
11
+
12
+ export function readConfig(io) {
13
+ const { file } = configPaths(io);
14
+ let text;
15
+ try { text = readFileSync(file, 'utf8'); } catch (e) {
16
+ if (e.code === 'ENOENT') return {};
17
+ throw new CliError(`Could not read ${file}: ${e.code || e.message}`);
18
+ }
19
+ try {
20
+ const v = JSON.parse(text);
21
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
22
+ } catch {
23
+ throw new CliError(`${file} is not valid JSON. Delete it and run agem login again.`);
24
+ }
25
+ }
26
+
27
+ export function writeConfig(io, cfg) {
28
+ const { dir, file } = configPaths(io);
29
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
30
+ writeFileSync(file, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
31
+ try { chmodSync(file, 0o600); } catch { /* best effort on Windows */ }
32
+ }
package/src/errors.js ADDED
@@ -0,0 +1,40 @@
1
+ // Every user-facing failure is one of these. None of them ever prints a stack trace.
2
+
3
+ export class CliError extends Error {
4
+ constructor(message, { type = 'error', details } = {}) {
5
+ super(message);
6
+ this.type = type;
7
+ this.details = details;
8
+ }
9
+ }
10
+
11
+ // Bad/missing flags or arguments: prints that command's usage.
12
+ export class UsageError extends CliError {
13
+ constructor(message, command) {
14
+ super(message, { type: 'usage' });
15
+ this.command = command;
16
+ }
17
+ }
18
+
19
+ export class UnknownCommandError extends CliError {
20
+ constructor(name, suggestion) {
21
+ super(`Unknown command "${name}".${suggestion ? ` Did you mean "${suggestion}"?` : ''}`, { type: 'unknown_command' });
22
+ this.name_ = name;
23
+ this.suggestion = suggestion;
24
+ }
25
+ }
26
+
27
+ export class NotLoggedInError extends CliError {
28
+ constructor(extra = '') {
29
+ super(`Not logged in.${extra} Run agem login first.`, { type: 'not_logged_in' });
30
+ }
31
+ }
32
+
33
+ export class ApiError extends CliError {
34
+ constructor(status, code, message, data) {
35
+ super(`Request failed (HTTP ${status}): ${message}`, { type: 'api' });
36
+ this.status = status;
37
+ this.code = code;
38
+ this.data = data;
39
+ }
40
+ }
package/src/ui.js ADDED
@@ -0,0 +1,87 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ // Version is read from cli/package.json at runtime, never hardcoded.
4
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
5
+
6
+ // Status icons (emoji style, like the agenline CLI messages).
7
+ export const ICON = { ok: '✅', error: '❌', warn: '⚠️' };
8
+
9
+ // FIGlet "Small" font, same font as the agenline wordmark.
10
+ const BANNER = [
11
+ ' _ _',
12
+ ' __ _ __ _ ___ _ _ _ __ __ _(_) |',
13
+ "/ _` / _` / -_) ' \\| ' \\/ _` | | |",
14
+ '\\__,_\\__, \\___|_||_|_|_|_\\__,_|_|_|',
15
+ ' |___/',
16
+ ];
17
+ const TAGLINES = ['A MAIL FOR YOUR AGENTS', 'BY AGENLINE'];
18
+
19
+ export function colors(enabled) {
20
+ const wrap = (open, close) => (s) => (enabled ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
21
+ return {
22
+ brand: wrap('38;2;178;34;34', '39'), // firebrick #B22222, the Agenline red
23
+ gray: wrap('90', '39'),
24
+ bold: wrap('1', '22'),
25
+ };
26
+ }
27
+
28
+ // "A MAIL" -> "A M A I L": letters spaced, words separated by three spaces.
29
+ export function spaceOut(text) {
30
+ return text.split(/\s+/).map((w) => Array.from(w).join(' ')).join(' ');
31
+ }
32
+
33
+ export function banner(c) {
34
+ return [
35
+ BANNER.map((row) => c.brand(row)).join('\n'),
36
+ '',
37
+ c.gray(`v${VERSION}`),
38
+ '',
39
+ ...TAGLINES.map((t) => c.bold(c.brand(spaceOut(t)))),
40
+ '',
41
+ '',
42
+ ].join('\n');
43
+ }
44
+
45
+ const ANSI = /\x1b\[[0-9;]*m/g;
46
+ export const visible = (s) => Array.from(String(s).replace(ANSI, '')).length;
47
+ const pad = (s, w) => String(s) + ' '.repeat(Math.max(0, w - visible(s)));
48
+
49
+ function cut(s, w) {
50
+ const chars = Array.from(String(s));
51
+ return chars.length <= w ? String(s) : chars.slice(0, Math.max(0, w - 3)).join('') + '...';
52
+ }
53
+
54
+ // Plain table. In a terminal, the widest columns are cut to fit; piped output keeps everything.
55
+ export function table(headers, rows, { c, width }) {
56
+ const all = [headers, ...rows].map((r) => r.map((v) => String(v ?? '').replace(/\s+/g, ' ')));
57
+ let widths = headers.map((_, i) => Math.max(...all.map((r) => visible(r[i]))));
58
+ if (width) {
59
+ const total = () => widths.reduce((a, b) => a + b, 0) + 2 * (widths.length - 1);
60
+ while (total() > width) {
61
+ const i = widths.indexOf(Math.max(...widths));
62
+ if (widths[i] <= 8) break;
63
+ widths[i] -= 1;
64
+ }
65
+ }
66
+ const render = (r) => r.map((v, i) => (i === r.length - 1 ? (width ? cut(v, widths[i]) : v) : pad(width ? cut(v, widths[i]) : v, widths[i] + 2))).join('').trimEnd();
67
+ return [c.gray(render(all[0])), ...all.slice(1).map(render)].join('\n') + '\n';
68
+ }
69
+
70
+ export function kv(rows, c) {
71
+ const w = Math.max(...rows.map(([k]) => visible(k))) + 2;
72
+ return rows.map(([k, v]) => `${c.gray(pad(k, w))}${v ?? ''}`).join('\n') + '\n';
73
+ }
74
+
75
+ // gh-style help page. sections: [{ title?, lines?, rows? }]
76
+ export function helpPage(sections, c) {
77
+ return sections.filter(Boolean).map((s) => {
78
+ const indent = s.title ? ' ' : '';
79
+ const out = s.title ? [c.bold(s.title)] : [];
80
+ for (const l of s.lines ?? []) out.push(l ? indent + l : '');
81
+ if (s.rows?.length) {
82
+ const w = s.width ?? Math.max(...s.rows.map(([t]) => visible(t)));
83
+ for (const [t, d] of s.rows) out.push(`${indent}${pad(t, w + (s.gap ?? 2))}${d ?? ''}`.trimEnd());
84
+ }
85
+ return out.join('\n');
86
+ }).join('\n\n') + '\n';
87
+ }