@stage-labs/metro 0.1.0-beta.5 → 0.1.0-beta.6

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,184 @@
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 maskToken = (t) => !t ? '' : t.length <= 8 ? '••••' : `${t.slice(0, 6)}…${t.slice(-2)}`;
14
+ /** Apply token across CONFIG_ENV_FILE (always set/cleared) AND cwd/.env (only if it exists). */
15
+ function applyToken(key, value) {
16
+ const out = [];
17
+ for (const path of [CONFIG_ENV_FILE, join(process.cwd(), '.env')]) {
18
+ if (path !== CONFIG_ENV_FILE && !existsSync(path))
19
+ continue;
20
+ const env = readDotenv(path);
21
+ if (value === null) {
22
+ if (!(key in env))
23
+ continue;
24
+ delete env[key];
25
+ }
26
+ else
27
+ env[key] = value;
28
+ writeDotenv(path, env);
29
+ out.push(path);
30
+ }
31
+ return out;
32
+ }
33
+ async function cmdSetupStatus(f) {
34
+ loadMetroEnv();
35
+ const tg = process.env.TELEGRAM_BOT_TOKEN ?? '', dc = process.env.DISCORD_BOT_TOKEN ?? '';
36
+ if (isJson(f))
37
+ return writeJson({
38
+ version: pkg.version, config_env_file: CONFIG_ENV_FILE,
39
+ tokens: { telegram: { set: !!tg, masked: maskToken(tg) }, discord: { set: !!dc, masked: maskToken(dc) } },
40
+ });
41
+ const cfgState = existsSync(CONFIG_ENV_FILE) ? '' : ' (not yet written)';
42
+ const getStarted = !tg && !dc
43
+ ? 'Get started:\n 1. metro setup telegram <token> # https://t.me/BotFather'
44
+ + '\n metro setup discord <token> # https://discord.com/developers/applications'
45
+ + '\n 2. metro doctor\n 3. metro\n'
46
+ : 'Run `metro` to start the dispatcher, or `metro doctor` to verify.\n';
47
+ process.stdout.write(`metro ${pkg.version}\n\nconfig: ${CONFIG_ENV_FILE}${cfgState}\n\n`
48
+ + ` TELEGRAM_BOT_TOKEN ${tg ? `set (${maskToken(tg)})` : 'not set'}\n`
49
+ + ` DISCORD_BOT_TOKEN ${dc ? `set (${maskToken(dc)})` : 'not set'}\n\n${getStarted}`);
50
+ }
51
+ export async function cmdSetup(p, f) {
52
+ const [sub, value] = p;
53
+ if (!sub)
54
+ return cmdSetupStatus(f);
55
+ if (sub === 'skill')
56
+ return cmdSetupSkill(p.slice(1), f);
57
+ if (sub === 'telegram' || sub === 'discord') {
58
+ if (!value)
59
+ throw new Error(`metro setup ${sub} <token> — token is required`);
60
+ const trimmed = value.trim();
61
+ let identity;
62
+ if (!f['no-validate']) {
63
+ process.env[TOKEN_KEYS[sub]] = trimmed;
64
+ try {
65
+ const me = await (sub === 'telegram' ? new TelegramStation() : new DiscordStation()).getMe();
66
+ identity = sub === 'telegram' ? `@${me.username}` : me.username;
67
+ }
68
+ catch (err) {
69
+ delete process.env[TOKEN_KEYS[sub]];
70
+ throw exitErr(`token rejected by ${sub}: ${errMsg(err)} (use --no-validate to save anyway)`, 3);
71
+ }
72
+ }
73
+ const paths = applyToken(TOKEN_KEYS[sub], trimmed);
74
+ const verified = identity ? ` (verified as ${identity})` : '';
75
+ 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 });
76
+ return;
77
+ }
78
+ if (sub === 'clear') {
79
+ const target = value ?? 'all';
80
+ if (target !== 'all' && target !== 'telegram' && target !== 'discord')
81
+ throw new Error(`metro setup clear <telegram|discord|all> — got '${target}'`);
82
+ const keys = target === 'all' ? Object.values(TOKEN_KEYS) : [TOKEN_KEYS[target]];
83
+ const paths = new Set();
84
+ for (const k of keys)
85
+ for (const path of applyToken(k, null))
86
+ paths.add(path);
87
+ const label = target === 'all' ? 'all metro tokens' : TOKEN_KEYS[target];
88
+ emit(f, `cleared ${label} from ${[...paths].join(', ') || '(no files had it)'}\nrestart metro for changes to take effect.`, { ok: true, cleared: target, paths: [...paths] });
89
+ return;
90
+ }
91
+ throw new Error(`unknown setup subcommand '${sub}' (try: telegram, discord, clear, skill)`);
92
+ }
93
+ function tokenSource(key) {
94
+ const val = process.env[key];
95
+ if (!val)
96
+ return '';
97
+ for (const path of [join(process.cwd(), '.env'), CONFIG_ENV_FILE]) {
98
+ if (existsSync(path) && readDotenv(path)[key] === val)
99
+ return path;
100
+ }
101
+ return 'process env';
102
+ }
103
+ export async function cmdDoctor(_, f) {
104
+ loadMetroEnv();
105
+ const cfg = configuredPlatforms();
106
+ const sources = [['telegram', 'TELEGRAM_BOT_TOKEN'], ['discord', 'DISCORD_BOT_TOKEN']]
107
+ .filter(([p]) => cfg[p]).map(([p, k]) => `${p}←${tokenSource(k)}`).join(', ');
108
+ const checks = [{
109
+ name: 'tokens', ok: cfg.telegram || cfg.discord,
110
+ detail: cfg.telegram || cfg.discord ? sources
111
+ : 'no platform configured — run `metro setup telegram|discord <token>`',
112
+ }];
113
+ for (const p of ['telegram', 'discord']) {
114
+ if (!cfg[p]) {
115
+ checks.push({ name: p, ok: null, detail: 'not configured' });
116
+ continue;
117
+ }
118
+ try {
119
+ const me = await (p === 'telegram' ? new TelegramStation() : new DiscordStation()).getMe();
120
+ checks.push({ name: p, ok: true, detail: `getMe → ${p === 'telegram' ? '@' : ''}${me.username}` });
121
+ }
122
+ catch (err) {
123
+ checks.push({ name: p, ok: false, detail: errMsg(err) });
124
+ }
125
+ }
126
+ const lockFile = join(STATE_DIR, '.tail-lock');
127
+ if (!existsSync(lockFile))
128
+ checks.push({ name: 'dispatcher', ok: null, detail: 'not running' });
129
+ else
130
+ try {
131
+ const pid = Number(readFileSync(lockFile, 'utf8').trim());
132
+ if (!Number.isInteger(pid) || pid <= 0)
133
+ throw new Error('invalid pid');
134
+ process.kill(pid, 0);
135
+ checks.push({ name: 'dispatcher', ok: true, detail: `running (pid ${pid})` });
136
+ }
137
+ catch {
138
+ checks.push({ name: 'dispatcher', ok: null, detail: 'stale lockfile (auto-reclaims)' });
139
+ }
140
+ checks.push({
141
+ name: 'codex-rc', ok: null,
142
+ detail: process.env.METRO_CODEX_RC
143
+ ? `push enabled → ${process.env.METRO_CODEX_RC}`
144
+ : 'not configured (set METRO_CODEX_RC=ws://… to enable Codex push)',
145
+ });
146
+ const sk = skillStatus();
147
+ const installed = Object.entries(sk).filter(([, ok]) => ok).map(([r]) => r);
148
+ checks.push({
149
+ name: 'skill', ok: installed.length ? true : null,
150
+ detail: installed.length ? `installed for ${installed.join(', ')}` : 'not installed (run `metro setup skill`)',
151
+ });
152
+ if (isJson(f))
153
+ return writeJson({ checks });
154
+ process.stdout.write('metro doctor\n\n');
155
+ for (const c of checks) {
156
+ const mark = c.ok === true ? '✓' : c.ok === false ? '✗' : '–';
157
+ process.stdout.write(` ${mark} ${c.name.padEnd(15)} ${c.detail}\n`);
158
+ }
159
+ process.stdout.write('\n');
160
+ if (checks.some(c => c.ok === false))
161
+ throw exitErr('one or more checks failed', 3);
162
+ }
163
+ export async function cmdUpdate(_, f) {
164
+ const tag = pkg.version.includes('-') ? 'beta' : 'latest';
165
+ const res = await fetch('https://registry.npmjs.org/@stage-labs/metro', { signal: AbortSignal.timeout(15_000) });
166
+ if (!res.ok)
167
+ throw new Error(`npm registry: ${res.status}`);
168
+ const latest = (await res.json())['dist-tags']?.[tag];
169
+ if (!latest)
170
+ throw new Error(`no '${tag}' dist-tag for @stage-labs/metro`);
171
+ if (latest === pkg.version) {
172
+ return emit(f, `already on ${pkg.version} (latest ${tag})`, { ok: true, current: pkg.version, latest, upgraded: false });
173
+ }
174
+ const argv1 = process.argv[1] ?? '', spec = `@stage-labs/metro@${tag}`;
175
+ const argv = argv1.includes('/.bun/') || argv1.includes('\\bun\\') ? ['bun', 'add', '-g', spec]
176
+ : argv1.includes('/pnpm/') || argv1.includes('\\pnpm\\') ? ['pnpm', 'add', '-g', spec]
177
+ : ['npm', 'install', '-g', spec];
178
+ emit(f, `metro ${pkg.version} → ${latest}\n$ ${argv.join(' ')}`, { ok: true, current: pkg.version, latest, command: argv.join(' ') });
179
+ await new Promise((resolve, reject) => {
180
+ const child = spawn(argv[0], argv.slice(1), { stdio: isJson(f) ? 'ignore' : 'inherit' });
181
+ child.on('exit', code => code === 0 ? resolve() : reject(new Error(`${argv[0]} exited ${code}`)));
182
+ child.on('error', reject);
183
+ });
184
+ }
package/dist/cli/index.js CHANGED
@@ -1,209 +1,135 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, readFileSync } from 'node:fs';
3
- import { join } from 'node:path';
2
+ /** Metro CLI entry: parses argv, dispatches to subcommands, owns action + info commands. */
4
3
  import pkg from '../../package.json' with { type: 'json' };
5
- import { cmdLines } from './lines.js';
6
- import { cmdUpdate } from './update.js';
7
- import { DiscordStation } from '../stations/discord/index.js';
8
- import { TelegramStation } from '../stations/telegram/index.js';
9
- import { fmtCapabilities, listStations } from '../stations/listing.js';
10
- import { sendToLine } from '../stations/send.js';
11
4
  import { errMsg } from '../log.js';
12
- import { CONFIG_ENV_FILE, configuredPlatforms, loadMetroEnv, readDotenv, STATE_DIR, writeDotenv } from '../paths.js';
13
- const USAGE = `metro Telegram + Discord bridge for your Claude Code / Codex agent
5
+ import { listLines } from '../cache.js';
6
+ import { fmtCapabilities, listStations } from '../stations/index.js';
7
+ import { loadMetroEnv } from '../paths.js';
8
+ import { readHistory } from '../history.js';
9
+ import { cmdDoctor, cmdSetup, cmdUpdate } from './config.js';
10
+ import { cmdDownload, cmdEdit, cmdFetch, cmdNotify, cmdReact, cmdReply, cmdSend, } from './actions.js';
11
+ import { flagOne, isJson, parseArgs, writeJson, } from './util.js';
12
+ const USAGE = `metro — Telegram + Discord stream for your Claude Code / Codex agent
14
13
 
15
14
  Usage:
16
- metro Run the dispatcher daemon.
15
+ metro Run the dispatcher (emits JSON events on stdout).
17
16
  metro setup [telegram|discord <token>] Save token, or show status with no args.
18
17
  metro setup clear [telegram|discord|all] Remove tokens.
18
+ metro setup skill [clear] Install the metro skill into ~/.claude / ~/.codex.
19
19
  metro doctor Health check.
20
20
  metro stations List stations + capabilities.
21
- metro lines List active conversations (sorted by recency).
22
- metro send <line> <text> Post a message to a metro:// line.
21
+ metro lines List recently-seen conversations.
22
+ metro send <line> <text> [--image=<path>]… [--document=<path>]… [--voice=<path>] [--buttons=<json>]
23
+ Post a fresh message; repeat --image/--document for multi-file albums.
24
+ metro reply <line> <message_id> <text> [--image=… --document=… --voice=… --buttons=…]
25
+ Threaded reply (same flags as send).
26
+ metro edit <line> <message_id> <text> [--buttons=<json>]
27
+ Edit a previously-sent message (text + buttons).
28
+ metro react <line> <message_id> <emoji> Set or clear ('') a reaction.
29
+ metro download <line> <message_id> [--out=<dir>]
30
+ Download image attachments to disk.
31
+ metro fetch <line> [--limit=N] Recent-message lookback (Discord only).
32
+ metro notify <line> <text> [--from=<line>] Emit a notification on the daemon's stream.
33
+ metro history [--limit=N] [--line=…] [--station=…] [--kind=…] [--from=…] [--text=…] [--since=…]
34
+ Read the universal message log (newest first).
23
35
  metro update Upgrade in place.
24
36
  metro --version | --help
37
+
38
+ Lines: metro://<station>/<path>. See docs/uri-scheme.md.
39
+ Multi-line --text: pipe on stdin in place of the positional arg.
25
40
  Exit codes: 0 success · 1 usage · 2 config · 3 upstream
26
41
  `;
27
- const exitErr = (msg, code) => Object.assign(new Error(msg), { code });
28
- const isJson = (f) => f.json === true;
29
- const emit = (f, human, structured) => void process.stdout.write(isJson(f) ? JSON.stringify(structured) + '\n' : human + '\n');
30
- const maskToken = (t) => !t ? '' : t.length <= 8 ? '••••' : `${t.slice(0, 6)}…${t.slice(-2)}`;
31
- const TOKEN_KEYS = { telegram: 'TELEGRAM_BOT_TOKEN', discord: 'DISCORD_BOT_TOKEN' };
32
- function parseArgs(argv) {
33
- const positional = [], flags = {};
34
- for (let i = 0; i < argv.length; i++) {
35
- const a = argv[i];
36
- if (!a.startsWith('--')) {
37
- positional.push(a);
38
- continue;
39
- }
40
- const eq = a.indexOf('=');
41
- if (eq !== -1) {
42
- flags[a.slice(2, eq)] = a.slice(eq + 1);
43
- continue;
44
- }
45
- const key = a.slice(2), next = argv[i + 1];
46
- if (next !== undefined && !next.startsWith('--')) {
47
- flags[key] = next;
48
- i++;
49
- }
50
- else
51
- flags[key] = true;
52
- }
53
- return { positional, flags };
54
- }
55
- /** Apply a token across CONFIG_ENV_FILE (always set/cleared) AND cwd/.env (only if it exists). Returns paths touched. */
56
- function applyTokenToAllEnvs(key, value) {
57
- const out = [];
58
- for (const path of [CONFIG_ENV_FILE, join(process.cwd(), '.env')]) {
59
- if (path !== CONFIG_ENV_FILE && !existsSync(path))
60
- continue;
61
- const env = readDotenv(path);
62
- if (value === null) {
63
- if (!(key in env))
64
- continue;
65
- delete env[key];
66
- }
67
- else
68
- env[key] = value;
69
- writeDotenv(path, env);
70
- out.push(path);
42
+ async function cmdStations(_, f) {
43
+ loadMetroEnv();
44
+ const rows = listStations();
45
+ if (isJson(f))
46
+ return writeJson({ stations: rows });
47
+ process.stdout.write('metro stations\n\n');
48
+ for (const s of rows) {
49
+ const mark = s.configured === true ? '✓' : s.configured === false ? '✗' : '·';
50
+ process.stdout.write(` ${mark} ${s.name.padEnd(10)} ${s.kind.padEnd(6)} ${fmtCapabilities(s.capabilities)}\n ${s.detail}\n`);
71
51
  }
72
- return out;
52
+ process.stdout.write('\n');
73
53
  }
74
- async function cmdSetup(positional, flags) {
75
- const [sub, value] = positional;
76
- if (!sub)
77
- return cmdSetupStatus(flags);
78
- if (sub === 'telegram' || sub === 'discord') {
79
- if (!value)
80
- throw new Error(`metro setup ${sub} <token> token is required`);
81
- const trimmed = value.trim();
82
- let identity;
83
- if (!flags['no-validate']) {
84
- process.env[TOKEN_KEYS[sub]] = trimmed;
85
- try {
86
- identity = sub === 'telegram' ? `@${(await new TelegramStation().getMe()).username}` : (await new DiscordStation().getMe()).username;
87
- }
88
- catch (err) {
89
- delete process.env[TOKEN_KEYS[sub]];
90
- throw exitErr(`token rejected by ${sub}: ${errMsg(err)} (use --no-validate to save anyway)`, 3);
91
- }
92
- }
93
- const paths = applyTokenToAllEnvs(TOKEN_KEYS[sub], trimmed);
94
- emit(flags, `saved ${TOKEN_KEYS[sub]}${identity ? ` (verified as ${identity})` : ''} to ${paths.join(', ')}\nrestart metro for the new token to take effect.`, { ok: true, saved: TOKEN_KEYS[sub], paths, verified_as: identity ?? null });
54
+ async function cmdLines(_, f) {
55
+ loadMetroEnv();
56
+ const rows = listLines()
57
+ .map(({ line, entry }) => ({ line, name: entry.name ?? null, lastSeenAt: entry.lastSeenAt ?? null }))
58
+ .sort((a, b) => (b.lastSeenAt ?? '').localeCompare(a.lastSeenAt ?? ''));
59
+ if (isJson(f))
60
+ return writeJson({ lines: rows });
61
+ if (!rows.length) {
62
+ process.stdout.write('metro lines\n\n (none yet — start the dispatcher and send a message)\n\n');
95
63
  return;
96
64
  }
97
- if (sub === 'clear') {
98
- const target = value ?? 'all';
99
- if (target !== 'all' && target !== 'telegram' && target !== 'discord')
100
- throw new Error(`metro setup clear <telegram|discord|all> got '${target}'`);
101
- const keys = target === 'all' ? ['TELEGRAM_BOT_TOKEN', 'DISCORD_BOT_TOKEN'] : [TOKEN_KEYS[target]];
102
- const paths = new Set();
103
- for (const k of keys)
104
- for (const p of applyTokenToAllEnvs(k, null))
105
- paths.add(p);
106
- const label = target === 'all' ? 'all metro tokens' : TOKEN_KEYS[target];
107
- return void emit(flags, `cleared ${label} from ${[...paths].join(', ') || '(no files had it)'}\nrestart metro for changes to take effect.`, { ok: true, cleared: target, paths: [...paths] });
65
+ const widest = Math.max(...rows.map(r => r.line.length));
66
+ process.stdout.write('metro lines\n\n');
67
+ for (const r of rows) {
68
+ const when = r.lastSeenAt ? humanAgo(r.lastSeenAt) : '';
69
+ const tag = r.name ? ` ${r.name.slice(0, 40)}${r.name.length > 40 ? '' : ''}` : '';
70
+ process.stdout.write(` ${when.padEnd(10)} ${r.line.padEnd(widest)}${tag}\n`);
108
71
  }
109
- throw new Error(`unknown setup subcommand '${sub}' (try: telegram, discord, clear)`);
110
- }
111
- async function cmdSetupStatus(flags) {
112
- loadMetroEnv();
113
- const tg = process.env.TELEGRAM_BOT_TOKEN ?? '', dc = process.env.DISCORD_BOT_TOKEN ?? '';
114
- if (isJson(flags))
115
- return void process.stdout.write(JSON.stringify({ version: pkg.version, config_env_file: CONFIG_ENV_FILE,
116
- tokens: { telegram: { set: !!tg, masked: maskToken(tg) }, discord: { set: !!dc, masked: maskToken(dc) } } }) + '\n');
117
- const cfgState = existsSync(CONFIG_ENV_FILE) ? '' : ' (not yet written)';
118
- process.stdout.write(`metro ${pkg.version}\n\nconfig: ${CONFIG_ENV_FILE}${cfgState}\n\n TELEGRAM_BOT_TOKEN ${tg ? `set (${maskToken(tg)})` : 'not set'}\n DISCORD_BOT_TOKEN ${dc ? `set (${maskToken(dc)})` : 'not set'}\n\n${!tg && !dc
119
- ? 'Get started:\n 1. metro setup telegram <token> # https://t.me/BotFather\n metro setup discord <token> # https://discord.com/developers/applications\n 2. metro doctor\n 3. metro\n'
120
- : 'Run `metro` to start the dispatcher, or `metro doctor` to verify.\n'}`);
72
+ process.stdout.write('\n');
121
73
  }
122
- /** Find which file (or process env) supplied the currently-loaded token, so doctor can name the real source. */
123
- function tokenSource(key) {
124
- const val = process.env[key];
125
- if (!val)
126
- return '';
127
- for (const path of [join(process.cwd(), '.env'), CONFIG_ENV_FILE])
128
- if (existsSync(path) && readDotenv(path)[key] === val)
129
- return path;
130
- return 'process env';
74
+ function humanAgo(iso) {
75
+ const sec = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000));
76
+ if (sec < 60)
77
+ return `${sec}s ago`;
78
+ if (sec < 3600)
79
+ return `${Math.floor(sec / 60)}m ago`;
80
+ if (sec < 86400)
81
+ return `${Math.floor(sec / 3600)}h ago`;
82
+ return `${Math.floor(sec / 86400)}d ago`;
131
83
  }
132
- async function cmdDoctor(flags) {
84
+ async function cmdHistory(_, f) {
133
85
  loadMetroEnv();
134
- const cfg = configuredPlatforms();
135
- const sources = [['telegram', 'TELEGRAM_BOT_TOKEN'], ['discord', 'DISCORD_BOT_TOKEN']].filter(([p]) => cfg[p]).map(([p, k]) => `${p}←${tokenSource(k)}`).join(', ');
136
- const checks = [{ name: 'tokens', ok: cfg.telegram || cfg.discord,
137
- detail: cfg.telegram || cfg.discord ? sources : 'no platform configured — run `metro setup telegram|discord <token>`',
138
- }];
139
- const getMeFns = { telegram: () => new TelegramStation().getMe(), discord: () => new DiscordStation().getMe() };
140
- for (const p of ['telegram', 'discord']) {
141
- if (!cfg[p]) {
142
- checks.push({ name: p, ok: null, detail: 'not configured' });
143
- continue;
144
- }
145
- try {
146
- const me = await getMeFns[p]();
147
- checks.push({ name: p, ok: true, detail: `getMe → ${p === 'telegram' ? '@' : ''}${me.username}` });
148
- }
149
- catch (err) {
150
- checks.push({ name: p, ok: false, detail: errMsg(err) });
151
- }
152
- }
153
- checks.push(dispatcherCheck());
154
- if (isJson(flags))
155
- process.stdout.write(JSON.stringify({ checks }) + '\n');
156
- else {
157
- process.stdout.write('metro doctor\n\n');
158
- for (const c of checks)
159
- process.stdout.write(` ${c.ok === true ? '✓' : c.ok === false ? '✗' : '–'} ${c.name.padEnd(15)} ${c.detail}\n`);
160
- process.stdout.write('\n');
161
- }
162
- if (checks.some(c => c.ok === false))
163
- throw exitErr('one or more checks failed', 3);
164
- }
165
- function dispatcherCheck() {
166
- const lockFile = join(STATE_DIR, '.tail-lock');
167
- if (!existsSync(lockFile))
168
- return { name: 'dispatcher', ok: null, detail: 'not running' };
169
- try {
170
- const pid = Number(readFileSync(lockFile, 'utf8').trim());
171
- if (!Number.isInteger(pid) || pid <= 0)
172
- throw new Error('invalid pid');
173
- process.kill(pid, 0);
174
- return { name: 'dispatcher', ok: true, detail: `running (pid ${pid})` };
86
+ const since = flagOne(f, 'since');
87
+ const entries = readHistory({
88
+ line: flagOne(f, 'line'),
89
+ station: flagOne(f, 'station'),
90
+ kind: flagOne(f, 'kind'),
91
+ from: flagOne(f, 'from'),
92
+ textContains: flagOne(f, 'text'),
93
+ since: since ? new Date(since) : undefined,
94
+ limit: Number(flagOne(f, 'limit')) || 50,
95
+ });
96
+ if (isJson(f))
97
+ return writeJson({ entries });
98
+ if (!entries.length) {
99
+ process.stdout.write('(no matching history entries)\n');
100
+ return;
175
101
  }
176
- catch {
177
- return { name: 'dispatcher', ok: null, detail: 'stale lockfile (will auto-reclaim on next start)' };
102
+ process.stdout.write('time id kind from → to body\n');
103
+ for (const e of entries.reverse()) {
104
+ const ts = e.ts.slice(11, 19);
105
+ const from = pad(fmtActor(e.from, e.fromName), 24);
106
+ const to = pad(fmtActor(e.to), 24);
107
+ const body = e.text ?? (e.emoji ? `[react ${e.emoji}]` : '');
108
+ const text = body.length > 60 ? body.slice(0, 59) + '…' : body;
109
+ process.stdout.write(`${ts} ${e.id.padEnd(12)} ${e.kind.padEnd(12)} ${from} → ${to} ${text}\n`);
178
110
  }
179
111
  }
180
- async function cmdSend(positional, flags) {
181
- const [to, ...rest] = positional;
182
- if (!to || !rest.length)
183
- throw exitErr('usage: metro send <line> <text>', 1);
184
- loadMetroEnv();
185
- const { line, messageId } = await sendToLine(to, rest.join(' '));
186
- emit(flags, `sent ${messageId} to ${line}`, { ok: true, line, messageId });
187
- }
188
- async function cmdStations(flags) {
189
- loadMetroEnv();
190
- const rows = listStations();
191
- if (isJson(flags))
192
- return void process.stdout.write(JSON.stringify({ stations: rows }) + '\n');
193
- process.stdout.write('metro stations\n\n');
194
- for (const s of rows) {
195
- const mark = s.configured === true ? '✓' : s.configured === false ? '✗' : '·';
196
- process.stdout.write(` ${mark} ${s.name.padEnd(10)} ${s.kind.padEnd(6)} ${fmtCapabilities(s.capabilities)}\n ${s.detail}\n`);
197
- }
198
- process.stdout.write('\n');
112
+ /** Compact display: fromName if known; else `station:@<id>` (user), `station:bot`, or `station:<id>`. */
113
+ function fmtActor(uri, name) {
114
+ if (name)
115
+ return name;
116
+ const m = uri.match(/^metro:\/\/([^/]+)(?:\/(?:(user|bot)\/)?(.*))?$/);
117
+ if (!m)
118
+ return uri;
119
+ const [, station, kind, rest] = m;
120
+ if (kind === 'bot')
121
+ return `${station}:bot`;
122
+ if (kind === 'user')
123
+ return `${station}:@${shortId(rest ?? '')}`;
124
+ return rest ? `${station}:${shortId(rest)}` : station;
199
125
  }
126
+ const shortId = (s) => s.length <= 12 ? s : `${s.slice(0, 5)}…${s.slice(-4)}`;
127
+ const pad = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s.padEnd(n));
200
128
  const COMMANDS = {
201
- setup: cmdSetup,
202
- doctor: (_, f) => cmdDoctor(f),
203
- stations: (_, f) => cmdStations(f),
204
- lines: (_, f) => cmdLines(isJson(f)),
205
- send: cmdSend,
206
- update: (_, f) => cmdUpdate(isJson(f)),
129
+ setup: cmdSetup, doctor: cmdDoctor, stations: cmdStations, lines: cmdLines,
130
+ send: cmdSend, reply: cmdReply, edit: cmdEdit, react: cmdReact,
131
+ download: cmdDownload, fetch: cmdFetch, notify: cmdNotify,
132
+ history: cmdHistory, update: cmdUpdate,
207
133
  };
208
134
  async function main() {
209
135
  const cmd = process.argv[2];
@@ -227,7 +153,7 @@ async function main() {
227
153
  catch (err) {
228
154
  const code = err.code;
229
155
  if (isJson(flags))
230
- process.stdout.write(JSON.stringify({ ok: false, error: errMsg(err), code: code ?? 1 }) + '\n');
156
+ writeJson({ ok: false, error: errMsg(err), code: code ?? 1 });
231
157
  else
232
158
  process.stderr.write(`error: ${errMsg(err)}\n`);
233
159
  process.exit(typeof code === 'number' ? code : 1);
@@ -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
+ }