@stage-labs/metro 0.1.0-beta.0 → 0.1.0-beta.10

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.
@@ -0,0 +1,185 @@
1
+ /** Setup / doctor / update — config-side commands consumed by cli.ts. */
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { spawn } from 'node:child_process';
4
+ import { join } from 'node:path';
5
+ import pkg from '../../package.json' with { type: 'json' };
6
+ import { DiscordStation } from '../stations/discord.js';
7
+ import { TelegramStation } from '../stations/telegram.js';
8
+ import { errMsg } from '../log.js';
9
+ import { CONFIG_ENV_FILE, configuredPlatforms, loadMetroEnv, readDotenv, STATE_DIR, writeDotenv, } from '../paths.js';
10
+ import { emit, exitErr, isJson, writeJson } from './util.js';
11
+ import { cmdSetupSkill, skillStatus } from './skill.js';
12
+ const TOKEN_KEYS = { telegram: 'TELEGRAM_BOT_TOKEN', discord: 'DISCORD_BOT_TOKEN' };
13
+ const stationFor = (p) => p === 'telegram' ? new TelegramStation() : new DiscordStation();
14
+ const maskToken = (t) => !t ? '' : t.length <= 8 ? '••••' : `${t.slice(0, 6)}…${t.slice(-2)}`;
15
+ /** Apply token across CONFIG_ENV_FILE (always set/cleared) AND cwd/.env (only if it exists). */
16
+ function applyToken(key, value) {
17
+ const out = [];
18
+ for (const path of [CONFIG_ENV_FILE, join(process.cwd(), '.env')]) {
19
+ if (path !== CONFIG_ENV_FILE && !existsSync(path))
20
+ continue;
21
+ const env = readDotenv(path);
22
+ if (value === null) {
23
+ if (!(key in env))
24
+ continue;
25
+ delete env[key];
26
+ }
27
+ else
28
+ env[key] = value;
29
+ writeDotenv(path, env);
30
+ out.push(path);
31
+ }
32
+ return out;
33
+ }
34
+ async function cmdSetupStatus(f) {
35
+ loadMetroEnv();
36
+ const tg = process.env.TELEGRAM_BOT_TOKEN ?? '', dc = process.env.DISCORD_BOT_TOKEN ?? '';
37
+ if (isJson(f))
38
+ return writeJson({
39
+ version: pkg.version, config_env_file: CONFIG_ENV_FILE,
40
+ tokens: { telegram: { set: !!tg, masked: maskToken(tg) }, discord: { set: !!dc, masked: maskToken(dc) } },
41
+ });
42
+ const cfgState = existsSync(CONFIG_ENV_FILE) ? '' : ' (not yet written)';
43
+ const getStarted = !tg && !dc
44
+ ? 'Get started:\n 1. metro setup telegram <token> # https://t.me/BotFather'
45
+ + '\n metro setup discord <token> # https://discord.com/developers/applications'
46
+ + '\n 2. metro doctor\n 3. metro\n'
47
+ : 'Run `metro` to start the dispatcher, or `metro doctor` to verify.\n';
48
+ process.stdout.write(`metro ${pkg.version}\n\nconfig: ${CONFIG_ENV_FILE}${cfgState}\n\n`
49
+ + ` TELEGRAM_BOT_TOKEN ${tg ? `set (${maskToken(tg)})` : 'not set'}\n`
50
+ + ` DISCORD_BOT_TOKEN ${dc ? `set (${maskToken(dc)})` : 'not set'}\n\n${getStarted}`);
51
+ }
52
+ export async function cmdSetup(p, f) {
53
+ const [sub, value] = p;
54
+ if (!sub)
55
+ return cmdSetupStatus(f);
56
+ if (sub === 'skill')
57
+ return cmdSetupSkill(p.slice(1), f);
58
+ if (sub === 'telegram' || sub === 'discord') {
59
+ if (!value)
60
+ throw new Error(`metro setup ${sub} <token> — token is required`);
61
+ const trimmed = value.trim();
62
+ let identity;
63
+ if (!f['no-validate']) {
64
+ process.env[TOKEN_KEYS[sub]] = trimmed;
65
+ try {
66
+ const me = await stationFor(sub).getMe();
67
+ identity = sub === 'telegram' ? `@${me.username}` : me.username;
68
+ }
69
+ catch (err) {
70
+ delete process.env[TOKEN_KEYS[sub]];
71
+ throw exitErr(`token rejected by ${sub}: ${errMsg(err)} (use --no-validate to save anyway)`, 3);
72
+ }
73
+ }
74
+ const paths = applyToken(TOKEN_KEYS[sub], trimmed);
75
+ const verified = identity ? ` (verified as ${identity})` : '';
76
+ emit(f, `saved ${TOKEN_KEYS[sub]}${verified} to ${paths.join(', ')}\nrestart metro for the new token to take effect.`, { ok: true, saved: TOKEN_KEYS[sub], paths, verified_as: identity ?? null });
77
+ return;
78
+ }
79
+ if (sub === 'clear') {
80
+ const target = value ?? 'all';
81
+ if (target !== 'all' && target !== 'telegram' && target !== 'discord')
82
+ throw new Error(`metro setup clear <telegram|discord|all> — got '${target}'`);
83
+ const keys = target === 'all' ? Object.values(TOKEN_KEYS) : [TOKEN_KEYS[target]];
84
+ const paths = new Set();
85
+ for (const k of keys)
86
+ for (const path of applyToken(k, null))
87
+ paths.add(path);
88
+ const label = target === 'all' ? 'all metro tokens' : TOKEN_KEYS[target];
89
+ emit(f, `cleared ${label} from ${[...paths].join(', ') || '(no files had it)'}\nrestart metro for changes to take effect.`, { ok: true, cleared: target, paths: [...paths] });
90
+ return;
91
+ }
92
+ throw new Error(`unknown setup subcommand '${sub}' (try: telegram, discord, clear, skill)`);
93
+ }
94
+ function tokenSource(key) {
95
+ const val = process.env[key];
96
+ if (!val)
97
+ return '';
98
+ for (const path of [join(process.cwd(), '.env'), CONFIG_ENV_FILE]) {
99
+ if (existsSync(path) && readDotenv(path)[key] === val)
100
+ return path;
101
+ }
102
+ return 'process env';
103
+ }
104
+ export async function cmdDoctor(_, f) {
105
+ loadMetroEnv();
106
+ const cfg = configuredPlatforms();
107
+ const checks = [];
108
+ const sources = [];
109
+ for (const p of ['telegram', 'discord']) {
110
+ if (!cfg[p]) {
111
+ checks.push({ name: p, ok: null, detail: 'not configured' });
112
+ continue;
113
+ }
114
+ sources.push(`${p}←${tokenSource(TOKEN_KEYS[p])}`);
115
+ try {
116
+ const me = await stationFor(p).getMe();
117
+ checks.push({ name: p, ok: true, detail: `getMe → ${p === 'telegram' ? '@' : ''}${me.username}` });
118
+ }
119
+ catch (err) {
120
+ checks.push({ name: p, ok: false, detail: errMsg(err) });
121
+ }
122
+ }
123
+ checks.unshift({
124
+ name: 'tokens', ok: cfg.telegram || cfg.discord,
125
+ detail: sources.length ? sources.join(', ') : 'no platform configured — run `metro setup telegram|discord <token>`',
126
+ });
127
+ const lockFile = join(STATE_DIR, '.tail-lock');
128
+ if (!existsSync(lockFile))
129
+ checks.push({ name: 'dispatcher', ok: null, detail: 'not running' });
130
+ else
131
+ try {
132
+ const pid = Number(readFileSync(lockFile, 'utf8').trim());
133
+ if (!Number.isInteger(pid) || pid <= 0)
134
+ throw new Error('invalid pid');
135
+ process.kill(pid, 0);
136
+ checks.push({ name: 'dispatcher', ok: true, detail: `running (pid ${pid})` });
137
+ }
138
+ catch {
139
+ checks.push({ name: 'dispatcher', ok: null, detail: 'stale lockfile (auto-reclaims)' });
140
+ }
141
+ checks.push({
142
+ name: 'codex-rc', ok: null,
143
+ detail: process.env.METRO_CODEX_RC
144
+ ? `push enabled → ${process.env.METRO_CODEX_RC}`
145
+ : 'not configured (set METRO_CODEX_RC=ws://… to enable Codex push)',
146
+ });
147
+ const sk = skillStatus();
148
+ const installed = Object.entries(sk).filter(([, ok]) => ok).map(([r]) => r);
149
+ checks.push({
150
+ name: 'skill', ok: installed.length ? true : null,
151
+ detail: installed.length ? `installed for ${installed.join(', ')}` : 'not installed (run `metro setup skill`)',
152
+ });
153
+ if (isJson(f))
154
+ return writeJson({ checks });
155
+ process.stdout.write('metro doctor\n\n');
156
+ for (const c of checks) {
157
+ const mark = c.ok === true ? '✓' : c.ok === false ? '✗' : '–';
158
+ process.stdout.write(` ${mark} ${c.name.padEnd(15)} ${c.detail}\n`);
159
+ }
160
+ process.stdout.write('\n');
161
+ if (checks.some(c => c.ok === false))
162
+ throw exitErr('one or more checks failed', 3);
163
+ }
164
+ export async function cmdUpdate(_, f) {
165
+ const tag = pkg.version.includes('-') ? 'beta' : 'latest';
166
+ const res = await fetch('https://registry.npmjs.org/@stage-labs/metro', { signal: AbortSignal.timeout(15_000) });
167
+ if (!res.ok)
168
+ throw new Error(`npm registry: ${res.status}`);
169
+ const latest = (await res.json())['dist-tags']?.[tag];
170
+ if (!latest)
171
+ throw new Error(`no '${tag}' dist-tag for @stage-labs/metro`);
172
+ if (latest === pkg.version) {
173
+ return emit(f, `already on ${pkg.version} (latest ${tag})`, { ok: true, current: pkg.version, latest, upgraded: false });
174
+ }
175
+ const argv1 = process.argv[1] ?? '', spec = `@stage-labs/metro@${tag}`;
176
+ const argv = argv1.includes('/.bun/') || argv1.includes('\\bun\\') ? ['bun', 'add', '-g', spec]
177
+ : argv1.includes('/pnpm/') || argv1.includes('\\pnpm\\') ? ['pnpm', 'add', '-g', spec]
178
+ : ['npm', 'install', '-g', spec];
179
+ emit(f, `metro ${pkg.version} → ${latest}\n$ ${argv.join(' ')}`, { ok: true, current: pkg.version, latest, command: argv.join(' ') });
180
+ await new Promise((resolve, reject) => {
181
+ const child = spawn(argv[0], argv.slice(1), { stdio: isJson(f) ? 'ignore' : 'inherit' });
182
+ child.on('exit', code => code === 0 ? resolve() : reject(new Error(`${argv[0]} exited ${code}`)));
183
+ child.on('error', reject);
184
+ });
185
+ }
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ /** Metro CLI entry: parses argv, dispatches to subcommands, owns action + info commands. */
3
+ import pkg from '../../package.json' with { type: 'json' };
4
+ import { errMsg } from '../log.js';
5
+ import { listLines } from '../cache.js';
6
+ import { fmtCapabilities, listStations } from '../stations/index.js';
7
+ import { listAgents } from '../registry.js';
8
+ import { loadMetroEnv } from '../paths.js';
9
+ import { readHistory } from '../history.js';
10
+ import { cmdDoctor, cmdSetup, cmdUpdate } from './config.js';
11
+ import { cmdDownload, cmdEdit, cmdFetch, cmdReact, cmdReply, cmdSend, } from './actions.js';
12
+ import { cmdTunnel, cmdWebhook } from './webhook.js';
13
+ import { flagOne, isJson, parseArgs, writeJson, } from './util.js';
14
+ const USAGE = `metro — Telegram + Discord stream for your Claude Code / Codex agent
15
+
16
+ Usage:
17
+ metro Run the dispatcher (emits JSON events on stdout).
18
+ metro setup [telegram|discord <token>] Save token, or show status with no args.
19
+ metro setup clear [telegram|discord|all] Remove tokens.
20
+ metro setup skill [clear] Install the metro skill into ~/.claude / ~/.codex.
21
+ metro doctor Health check.
22
+ metro stations List stations + capabilities.
23
+ metro lines List recently-seen conversations.
24
+ metro send <line> <text> [--image=<path>]… [--document=<path>]… [--voice=<path>] [--buttons=<json>]
25
+ Post a fresh message; repeat --image/--document for multi-file albums.
26
+ metro reply <line> <message_id> <text> [--image=… --document=… --voice=… --buttons=…]
27
+ Threaded reply (same flags as send).
28
+ metro edit <line> <message_id> <text> [--buttons=<json>]
29
+ Edit a previously-sent message (text + buttons).
30
+ metro react <line> <message_id> <emoji> Set or clear ('') a reaction.
31
+ metro download <line> <message_id> [--out=<dir>]
32
+ Download image attachments to disk.
33
+ metro fetch <line> [--limit=N] Recent-message lookback (Discord only).
34
+ metro history [--limit=N] [--line=…] [--station=…] [--kind=…] [--from=…] [--text=…] [--since=…]
35
+ Read the universal message log (newest first).
36
+ metro webhook add <label> [--secret=…] Register an HTTP receive endpoint (GitHub, Intercom, …).
37
+ metro webhook list | remove <id> List or remove webhook endpoints.
38
+ metro tunnel setup <name> <hostname> Configure a Cloudflare named tunnel (run cloudflared tunnel login first).
39
+ metro tunnel status Show current tunnel config.
40
+ metro update Upgrade in place.
41
+ metro --version | --help
42
+
43
+ Lines: metro://<station>/<path>. See docs/uri-scheme.md.
44
+ Multi-line --text: pipe on stdin in place of the positional arg.
45
+ Exit codes: 0 success · 1 usage · 2 config · 3 upstream
46
+ `;
47
+ async function cmdStations(_, f) {
48
+ loadMetroEnv();
49
+ const rows = listStations();
50
+ const agentsByStation = {
51
+ claude: listAgents('claude'),
52
+ codex: listAgents('codex'),
53
+ };
54
+ if (isJson(f))
55
+ return writeJson({ stations: rows, agents: agentsByStation });
56
+ process.stdout.write('metro stations\n\n');
57
+ for (const s of rows) {
58
+ const mark = s.configured === true ? '✓' : s.configured === false ? '✗' : '·';
59
+ process.stdout.write(` ${mark} ${s.name.padEnd(10)} ${s.kind.padEnd(6)} ${fmtCapabilities(s.capabilities)}\n ${s.detail}\n`);
60
+ if (s.kind === 'agent') {
61
+ const seen = agentsByStation[s.name] ?? [];
62
+ for (const inst of seen) {
63
+ const sessionsTxt = inst.sessions.length ? ` · sessions: ${inst.sessions.length}` : '';
64
+ process.stdout.write(` seen: ${inst.agentId}${sessionsTxt}\n`);
65
+ }
66
+ }
67
+ }
68
+ process.stdout.write('\n');
69
+ }
70
+ async function cmdLines(_, f) {
71
+ loadMetroEnv();
72
+ const rows = listLines()
73
+ .map(({ line, entry }) => ({ line, name: entry.name ?? null, lastSeenAt: entry.lastSeenAt ?? null }))
74
+ .sort((a, b) => (b.lastSeenAt ?? '').localeCompare(a.lastSeenAt ?? ''));
75
+ if (isJson(f))
76
+ return writeJson({ lines: rows });
77
+ if (!rows.length)
78
+ return void process.stdout.write('metro lines\n\n (none yet — start the dispatcher and send a message)\n\n');
79
+ const widest = Math.max(...rows.map(r => r.line.length));
80
+ process.stdout.write('metro lines\n\n');
81
+ for (const r of rows) {
82
+ const when = r.lastSeenAt ? humanAgo(r.lastSeenAt) : '—';
83
+ const tag = r.name ? ` ${r.name.slice(0, 40)}${r.name.length > 40 ? '…' : ''}` : '';
84
+ process.stdout.write(` ${when.padEnd(10)} ${r.line.padEnd(widest)}${tag}\n`);
85
+ }
86
+ process.stdout.write('\n');
87
+ }
88
+ function humanAgo(iso) {
89
+ const sec = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000));
90
+ if (sec < 60)
91
+ return `${sec}s ago`;
92
+ if (sec < 3600)
93
+ return `${Math.floor(sec / 60)}m ago`;
94
+ if (sec < 86400)
95
+ return `${Math.floor(sec / 3600)}h ago`;
96
+ return `${Math.floor(sec / 86400)}d ago`;
97
+ }
98
+ async function cmdHistory(_, f) {
99
+ loadMetroEnv();
100
+ const since = flagOne(f, 'since');
101
+ const entries = readHistory({
102
+ line: flagOne(f, 'line'),
103
+ station: flagOne(f, 'station'),
104
+ kind: flagOne(f, 'kind'),
105
+ from: flagOne(f, 'from'),
106
+ textContains: flagOne(f, 'text'),
107
+ since: since ? new Date(since) : undefined,
108
+ limit: Number(flagOne(f, 'limit')) || 50,
109
+ });
110
+ if (isJson(f))
111
+ return writeJson({ entries });
112
+ if (!entries.length) {
113
+ process.stdout.write('(no matching history entries)\n');
114
+ return;
115
+ }
116
+ process.stdout.write('time id kind from → to body\n');
117
+ for (const e of entries.reverse()) {
118
+ const ts = e.ts.slice(11, 19);
119
+ const from = pad(fmtActor(e.from, e.fromName), 24);
120
+ const to = pad(fmtActor(e.to), 24);
121
+ const body = e.text ?? (e.emoji ? `[react ${e.emoji}]` : '');
122
+ const text = body.length > 60 ? body.slice(0, 59) + '…' : body;
123
+ process.stdout.write(`${ts} ${e.id.padEnd(12)} ${e.kind.padEnd(12)} ${from} → ${to} ${text}\n`);
124
+ }
125
+ }
126
+ /** Compact display: fromName if known; else `station:@<id>` (user), `station:bot`, or `station:<id>`. */
127
+ function fmtActor(uri, name) {
128
+ if (name)
129
+ return name;
130
+ const m = uri.match(/^metro:\/\/([^/]+)(?:\/(?:(user|bot)\/)?(.*))?$/);
131
+ if (!m)
132
+ return uri;
133
+ const [, station, kind, rest] = m;
134
+ if (kind === 'bot')
135
+ return `${station}:bot`;
136
+ if (kind === 'user')
137
+ return `${station}:@${shortId(rest ?? '')}`;
138
+ return rest ? `${station}:${shortId(rest)}` : station;
139
+ }
140
+ const shortId = (s) => s.length <= 12 ? s : `${s.slice(0, 5)}…${s.slice(-4)}`;
141
+ const pad = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s.padEnd(n));
142
+ const COMMANDS = {
143
+ setup: cmdSetup, doctor: cmdDoctor, stations: cmdStations, lines: cmdLines,
144
+ send: cmdSend, reply: cmdReply, edit: cmdEdit, react: cmdReact,
145
+ download: cmdDownload, fetch: cmdFetch,
146
+ webhook: cmdWebhook, tunnel: cmdTunnel,
147
+ history: cmdHistory, update: cmdUpdate,
148
+ };
149
+ async function main() {
150
+ const cmd = process.argv[2];
151
+ if (cmd === '--version' || cmd === '-v')
152
+ return void process.stdout.write(`${pkg.version}\n`);
153
+ if (cmd === '--help' || cmd === '-h')
154
+ return void process.stdout.write(USAGE);
155
+ if (!cmd) {
156
+ await import('../dispatcher.js');
157
+ return;
158
+ }
159
+ const handler = COMMANDS[cmd];
160
+ if (!handler) {
161
+ process.stderr.write(`unknown command '${cmd}'\n\n${USAGE}`);
162
+ process.exit(1);
163
+ }
164
+ const { positional, flags } = parseArgs(process.argv.slice(3));
165
+ try {
166
+ await handler(positional, flags);
167
+ }
168
+ catch (err) {
169
+ const code = err.code;
170
+ if (isJson(flags))
171
+ writeJson({ ok: false, error: errMsg(err), code: code ?? 1 });
172
+ else
173
+ process.stderr.write(`error: ${errMsg(err)}\n`);
174
+ process.exit(typeof code === 'number' ? code : 1);
175
+ }
176
+ }
177
+ await main();
@@ -0,0 +1,62 @@
1
+ /** `metro setup skill` — install the bundled SKILL.md into each detected agent runtime. */
2
+ import { copyFileSync, existsSync, mkdirSync, unlinkSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { errMsg } from '../log.js';
7
+ import { emit, exitErr } from './util.js';
8
+ const RUNTIME_DIRS = {
9
+ 'claude-code': join(homedir(), '.claude', 'skills', 'metro'),
10
+ codex: join(homedir(), '.codex', 'skills', 'metro'),
11
+ };
12
+ /** dist/cli/skill.js → <package-root>/skills/metro/SKILL.md */
13
+ const bundledPath = () => join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills', 'metro', 'SKILL.md');
14
+ const dest = (r) => join(RUNTIME_DIRS[r], 'SKILL.md');
15
+ export const skillStatus = () => ({
16
+ 'claude-code': existsSync(dest('claude-code')),
17
+ codex: existsSync(dest('codex')),
18
+ });
19
+ export async function cmdSetupSkill(p, f) {
20
+ const [sub] = p;
21
+ if (sub === 'clear')
22
+ return clear(f);
23
+ if (sub && sub !== 'install')
24
+ throw exitErr(`unknown skill subcommand '${sub}' (try: install, clear)`, 1);
25
+ return install(f);
26
+ }
27
+ function install(f) {
28
+ const src = bundledPath();
29
+ if (!existsSync(src))
30
+ throw exitErr(`bundled SKILL.md missing at ${src} (broken install?)`, 2);
31
+ const installed = [];
32
+ for (const r of Object.keys(RUNTIME_DIRS)) {
33
+ if (!existsSync(join(homedir(), r === 'claude-code' ? '.claude' : '.codex')))
34
+ continue;
35
+ try {
36
+ mkdirSync(RUNTIME_DIRS[r], { recursive: true });
37
+ copyFileSync(src, dest(r));
38
+ installed.push(dest(r));
39
+ }
40
+ catch (err) {
41
+ throw exitErr(`failed to install skill for ${r}: ${errMsg(err)}`, 2);
42
+ }
43
+ }
44
+ if (!installed.length) {
45
+ throw exitErr('no agent runtime detected (~/.claude or ~/.codex). Install one and rerun.', 2);
46
+ }
47
+ emit(f, `installed metro skill → ${installed.join(', ')}`, { ok: true, installed });
48
+ }
49
+ function clear(f) {
50
+ const removed = [];
51
+ for (const r of Object.keys(RUNTIME_DIRS)) {
52
+ const path = dest(r);
53
+ if (existsSync(path)) {
54
+ try {
55
+ unlinkSync(path);
56
+ removed.push(path);
57
+ }
58
+ catch { /* ignore */ }
59
+ }
60
+ }
61
+ emit(f, removed.length ? `removed metro skill from ${removed.join(', ')}` : 'no installed skill found', { ok: true, removed });
62
+ }
@@ -0,0 +1,72 @@
1
+ /** Shared CLI primitives consumed by index.ts + config.ts. */
2
+ export const exitErr = (msg, code) => Object.assign(new Error(msg), { code });
3
+ export const isJson = (f) => f.json === true;
4
+ export const writeJson = (obj) => void process.stdout.write(JSON.stringify(obj) + '\n');
5
+ export const emit = (f, human, structured) => isJson(f) ? writeJson(structured) : void process.stdout.write(human + '\n');
6
+ export const need = (positional, min, usage) => {
7
+ if (positional.length < min)
8
+ throw exitErr(`usage: ${usage}`, 1);
9
+ };
10
+ /** Return the last string value for `key` (or undefined). */
11
+ export function flagOne(f, key) {
12
+ const v = f[key];
13
+ if (typeof v === 'string')
14
+ return v;
15
+ if (Array.isArray(v) && v.length)
16
+ return v[v.length - 1];
17
+ return undefined;
18
+ }
19
+ /** Return all string values for `key`, also splitting comma-separated entries. */
20
+ export function flagList(f, key) {
21
+ const v = f[key];
22
+ const raw = typeof v === 'string' ? [v] : Array.isArray(v) ? v : [];
23
+ return raw.flatMap(s => s.split(',').map(p => p.trim()).filter(Boolean));
24
+ }
25
+ export function parseArgs(argv) {
26
+ const positional = [], flags = {};
27
+ const add = (k, val) => {
28
+ const cur = flags[k];
29
+ if (cur === undefined) {
30
+ flags[k] = val;
31
+ return;
32
+ }
33
+ if (typeof val === 'boolean') {
34
+ flags[k] = val;
35
+ return;
36
+ }
37
+ flags[k] = Array.isArray(cur) ? [...cur, val] : [cur, val];
38
+ };
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const a = argv[i];
41
+ if (!a.startsWith('--')) {
42
+ positional.push(a);
43
+ continue;
44
+ }
45
+ const eq = a.indexOf('=');
46
+ if (eq !== -1) {
47
+ add(a.slice(2, eq), a.slice(eq + 1));
48
+ continue;
49
+ }
50
+ const next = argv[i + 1];
51
+ if (next !== undefined && !next.startsWith('--')) {
52
+ add(a.slice(2), next);
53
+ i++;
54
+ }
55
+ else
56
+ add(a.slice(2), true);
57
+ }
58
+ return { positional, flags };
59
+ }
60
+ export async function resolveText(positional, from) {
61
+ if (positional.length > from)
62
+ return positional.slice(from).join(' ');
63
+ if (process.stdin.isTTY)
64
+ throw exitErr('text is required (or pipe text on stdin)', 1);
65
+ const chunks = [];
66
+ for await (const c of process.stdin)
67
+ chunks.push(c);
68
+ const stdin = Buffer.concat(chunks).toString('utf8').replace(/\n$/, '');
69
+ if (!stdin)
70
+ throw exitErr('text is required (or pipe text on stdin)', 1);
71
+ return stdin;
72
+ }
@@ -0,0 +1,81 @@
1
+ /** CLI subcommands: `metro webhook add|list|remove` + `metro tunnel setup`. */
2
+ import { spawnSync } from 'node:child_process';
3
+ import { addEndpoint, listEndpoints, removeEndpoint, webhookPort } from '../webhooks.js';
4
+ import { loadTunnelConfig, saveTunnelConfig } from '../tunnel.js';
5
+ import { emit, exitErr, flagOne, isJson, need, writeJson } from './util.js';
6
+ function urlFor(endpointId) {
7
+ const t = loadTunnelConfig();
8
+ return t ? `https://${t.hostname}/wh/${endpointId}` : `http://127.0.0.1:${webhookPort()}/wh/${endpointId}`;
9
+ }
10
+ export async function cmdWebhook(p, f) {
11
+ const sub = p[0];
12
+ if (sub === 'add')
13
+ return cmdWebhookAdd(p.slice(1), f);
14
+ if (sub === 'list' || sub === undefined)
15
+ return cmdWebhookList(f);
16
+ if (sub === 'remove' || sub === 'rm')
17
+ return cmdWebhookRemove(p.slice(1), f);
18
+ throw exitErr('usage: metro webhook [add <label> [--secret=…] | list | remove <id>]', 1);
19
+ }
20
+ async function cmdWebhookAdd(p, f) {
21
+ need(p, 1, 'metro webhook add <label> [--secret=<shared-secret>]');
22
+ const ep = addEndpoint(p[0], flagOne(f, 'secret'));
23
+ const url = urlFor(ep.id);
24
+ emit(f, `webhook ${ep.id} (${ep.label}) → ${url}${ep.secret ? `\nshared secret: ${ep.secret}` : ''}`, { ok: true, endpoint: ep, url });
25
+ }
26
+ async function cmdWebhookList(f) {
27
+ const eps = listEndpoints().map(ep => ({ ...ep, url: urlFor(ep.id) }));
28
+ if (isJson(f))
29
+ return writeJson({ endpoints: eps });
30
+ if (!eps.length)
31
+ return void process.stdout.write('metro webhooks\n\n (none — run `metro webhook add <label>`)\n\n');
32
+ process.stdout.write('metro webhooks\n\n');
33
+ for (const ep of eps) {
34
+ process.stdout.write(` ${ep.id} ${ep.label}${ep.secret ? ' (signed)' : ''}\n ${ep.url}\n`);
35
+ }
36
+ process.stdout.write('\n');
37
+ }
38
+ async function cmdWebhookRemove(p, f) {
39
+ need(p, 1, 'metro webhook remove <id>');
40
+ const ok = removeEndpoint(p[0]);
41
+ if (!ok)
42
+ throw exitErr(`no webhook with id "${p[0]}"`, 1);
43
+ emit(f, `removed webhook ${p[0]}`, { ok: true, id: p[0] });
44
+ }
45
+ export async function cmdTunnel(p, f) {
46
+ const sub = p[0];
47
+ if (sub === 'setup')
48
+ return cmdTunnelSetup(p.slice(1), f);
49
+ if (sub === 'status' || sub === undefined)
50
+ return cmdTunnelStatus(f);
51
+ throw exitErr('usage: metro tunnel [setup <name> <hostname> | status]', 1);
52
+ }
53
+ async function cmdTunnelSetup(p, f) {
54
+ need(p, 2, 'metro tunnel setup <tunnel-name> <hostname> (e.g. `metro tunnel setup metro webhook.example.com`)');
55
+ const [name, hostname] = p;
56
+ if (!hasCloudflared()) {
57
+ throw exitErr('cloudflared not on PATH — install with `brew install cloudflared` (or see https://developers.cloudflare.com/cloudflared/)', 2);
58
+ }
59
+ /** Idempotent: if tunnel exists, `tunnel create` errors with "already exists" — that's fine, continue. */
60
+ run('cloudflared', ['tunnel', 'create', name], { allowFail: true });
61
+ /** DNS route is also idempotent in newer cloudflared; older versions error if the CNAME exists. Same handling. */
62
+ run('cloudflared', ['tunnel', 'route', 'dns', name, hostname], { allowFail: true });
63
+ saveTunnelConfig({ name, hostname });
64
+ emit(f, `tunnel saved: ${name} → ${hostname}\n` +
65
+ 'first run: `cloudflared tunnel login` if you haven\'t (browser OAuth).\n' +
66
+ 'then start metro — the daemon will spawn `cloudflared tunnel run` for you.', { ok: true, name, hostname });
67
+ }
68
+ async function cmdTunnelStatus(f) {
69
+ const cfg = loadTunnelConfig();
70
+ if (isJson(f))
71
+ return writeJson({ configured: !!cfg, tunnel: cfg });
72
+ if (!cfg)
73
+ return void process.stdout.write('metro tunnel\n\n (not configured — run `metro tunnel setup <name> <hostname>`)\n\n');
74
+ process.stdout.write(`metro tunnel\n\n name: ${cfg.name}\n hostname: ${cfg.hostname}\n\n`);
75
+ }
76
+ const hasCloudflared = () => spawnSync('cloudflared', ['--version'], { stdio: 'ignore' }).status === 0;
77
+ function run(cmd, args, opts = {}) {
78
+ const r = spawnSync(cmd, args, { stdio: 'inherit' });
79
+ if (r.status !== 0 && !opts.allowFail)
80
+ throw exitErr(`${cmd} ${args.join(' ')} exited ${r.status}`, 2);
81
+ }