@stage-labs/metro 0.1.0-beta.4 → 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.
- package/README.md +138 -63
- package/dist/cache.js +74 -0
- package/dist/cli/actions.js +156 -0
- package/dist/cli/config.js +184 -0
- package/dist/cli/index.js +162 -0
- package/dist/cli/skill.js +62 -0
- package/dist/cli/util.js +72 -0
- package/dist/codex-rc.js +236 -0
- package/dist/dispatcher.js +112 -0
- package/dist/history.js +84 -0
- package/dist/ipc.js +71 -0
- package/dist/log.js +7 -2
- package/dist/stations/discord.js +198 -0
- package/dist/stations/index.js +73 -0
- package/dist/{helpers/telegram-format.js → stations/telegram-md.js} +9 -14
- package/dist/stations/telegram-upload.js +113 -0
- package/dist/stations/telegram.js +235 -0
- package/docs/agents.md +168 -0
- package/docs/uri-scheme.md +71 -0
- package/package.json +6 -3
- package/skills/metro/SKILL.md +220 -0
- package/dist/agents/claude.js +0 -207
- package/dist/agents/codex.js +0 -207
- package/dist/agents/types.js +0 -2
- package/dist/channels/discord.js +0 -104
- package/dist/channels/telegram.js +0 -189
- package/dist/cli.js +0 -221
- package/dist/helpers/scope-cache.js +0 -65
- package/dist/helpers/streaming.js +0 -209
- package/dist/helpers/turn.js +0 -40
- package/dist/orchestrator.js +0 -208
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
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 { 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
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
metro Run the dispatcher (emits JSON events on stdout).
|
|
16
|
+
metro setup [telegram|discord <token>] Save token, or show status with no args.
|
|
17
|
+
metro setup clear [telegram|discord|all] Remove tokens.
|
|
18
|
+
metro setup skill [clear] Install the metro skill into ~/.claude / ~/.codex.
|
|
19
|
+
metro doctor Health check.
|
|
20
|
+
metro stations List stations + capabilities.
|
|
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).
|
|
35
|
+
metro update Upgrade in place.
|
|
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.
|
|
40
|
+
Exit codes: 0 success · 1 usage · 2 config · 3 upstream
|
|
41
|
+
`;
|
|
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`);
|
|
51
|
+
}
|
|
52
|
+
process.stdout.write('\n');
|
|
53
|
+
}
|
|
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');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
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`);
|
|
71
|
+
}
|
|
72
|
+
process.stdout.write('\n');
|
|
73
|
+
}
|
|
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`;
|
|
83
|
+
}
|
|
84
|
+
async function cmdHistory(_, f) {
|
|
85
|
+
loadMetroEnv();
|
|
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;
|
|
101
|
+
}
|
|
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`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
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;
|
|
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));
|
|
128
|
+
const COMMANDS = {
|
|
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,
|
|
133
|
+
};
|
|
134
|
+
async function main() {
|
|
135
|
+
const cmd = process.argv[2];
|
|
136
|
+
if (cmd === '--version' || cmd === '-v')
|
|
137
|
+
return void process.stdout.write(`${pkg.version}\n`);
|
|
138
|
+
if (cmd === '--help' || cmd === '-h')
|
|
139
|
+
return void process.stdout.write(USAGE);
|
|
140
|
+
if (!cmd) {
|
|
141
|
+
await import('../dispatcher.js');
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const handler = COMMANDS[cmd];
|
|
145
|
+
if (!handler) {
|
|
146
|
+
process.stderr.write(`unknown command '${cmd}'\n\n${USAGE}`);
|
|
147
|
+
process.exit(1);
|
|
148
|
+
}
|
|
149
|
+
const { positional, flags } = parseArgs(process.argv.slice(3));
|
|
150
|
+
try {
|
|
151
|
+
await handler(positional, flags);
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
const code = err.code;
|
|
155
|
+
if (isJson(flags))
|
|
156
|
+
writeJson({ ok: false, error: errMsg(err), code: code ?? 1 });
|
|
157
|
+
else
|
|
158
|
+
process.stderr.write(`error: ${errMsg(err)}\n`);
|
|
159
|
+
process.exit(typeof code === 'number' ? code : 1);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
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
|
+
}
|
package/dist/cli/util.js
ADDED
|
@@ -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
|
+
}
|