@stage-labs/metro 0.1.0-beta.1 → 0.1.0-beta.11

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 CHANGED
@@ -1,55 +1,252 @@
1
1
  # Metro
2
2
 
3
- Chat with your Claude Code or Codex agent over Telegram and Discord.
3
+ [![npm](https://img.shields.io/npm/v/@stage-labs/metro/beta?label=npm&color=cb3837)](https://www.npmjs.com/package/@stage-labs/metro)
4
+ [![lines of code](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.codetabs.com%2Fv1%2Floc%2F%3Fgithub%3Dbonustrack%2Fmetro&query=%24%5B0%5D.linesOfCode&label=lines%20of%20TypeScript&color=blue)](https://github.com/bonustrack/metro)
4
5
 
5
- ## Quickstart
6
+ > **A live JSON stream of Telegram, Discord, webhooks, and cross-user messages for your local Claude Code / Codex session.**
7
+
8
+ Metro is a small daemon you launch from inside your session. It connects to Discord, Telegram, and any third-party service that can POST a webhook (GitHub, Intercom, Fireflies, …), emits each inbound as one JSON line on stdout (which Claude Code's `Monitor` consumes natively, and Codex picks up via an app-server WebSocket push), and exposes a tiny CLI — `metro reply`, `metro send`, `metro edit`, `metro react`, `metro download`, `metro fetch` — for posting back. Cross-user: any user can ping any other via `metro send metro://claude/<user-id>/<session-id>` and the daemon re-emits it on the stream.
9
+
10
+ ```
11
+ [Claude Code session]
12
+
13
+ $ metro & # backgrounded
14
+ $ Monitor( … metro's stdout … )
15
+
16
+ >>> {"kind":"inbound","station":"discord","line":"metro://discord/123…","messageId":"9876",
17
+ "text":"@metro we got a 5xx spike from /v1/sync. Look?",
18
+ "payload":{"channelId":"123…","guildId":"456…","content":"<@…> we got a 5xx spike…",
19
+ "mentions":{"users":["<bot-id>"],"roles":[],"everyone":false},…}}
20
+
21
+ [I'd run git log + read services/sync.ts, then…]
22
+ Bash: metro reply metro://discord/123… 9876 "three deploys in the last 24h…"
23
+ ```
6
24
 
7
- In your shell:
25
+ You own your own streaming, tool calls, and reply timing. Metro is the wire.
26
+
27
+ ---
28
+
29
+ ## Quickstart
8
30
 
9
31
  ```bash
10
32
  npm install -g @stage-labs/metro@beta # or: bun add -g @stage-labs/metro@beta
11
33
 
34
+ metro setup discord <token> # https://discord.com/developers/applications
12
35
  metro setup telegram <token> # https://t.me/BotFather
13
- metro setup discord <token> # https://discord.com/developers/applications
14
-
15
- metro setup skill # writes SKILL.md so Claude Code + Codex auto-onboard
16
36
  metro doctor # verify
37
+ metro # run the daemon
38
+ ```
39
+
40
+ Requires **Node ≥ 22 or Bun ≥ 1.3**. Metro doesn't launch Claude or Codex — you do, and the user launches metro. See [`docs/users.md`](docs/users.md).
41
+
42
+ In **Discord**: DM the bot, or `@<bot>` in any channel. In **Telegram**: DM, or `@<bot>` in a forum supergroup. Every inbound becomes one JSON line on `metro`'s stdout.
43
+
44
+ ---
45
+
46
+ ## Architecture
47
+
17
48
  ```
49
+ Discord gateway ──┐
50
+ Telegram poller ──┤
51
+ Cloudflare tunnel ──┤ ── HTTP webhooks (GitHub, Intercom, …)
52
+
53
+ ├─▶ metro daemon ───▶ stdout (JSON events; Claude Code's Monitor reads here)
54
+ │ ───▶ codex-rc WebSocket (Codex turn/start; opt-in)
55
+ │ ◀── IPC Unix socket (metro send to Claude / Codex lines)
56
+
57
+ local CLI calls ────┴── REST → Discord / Telegram (metro reply / send / edit / react / download / fetch)
58
+ ```
59
+
60
+ - **Inversion of control.** Claude Code / Codex launches `metro`, not the other way around. Metro never spawns a Claude / Codex process.
61
+ - **Single daemon per machine.** Lockfile at `$METRO_STATE_DIR/.tail-lock` enforces singleton.
62
+ - **Account-tied identity.** `to` on inbound and `from` on outbound resolve to a stable account-scoped URI per runtime: `metro://claude/user/<orgId>` (from `claude auth status --json`) or `metro://codex/user/<accountId>` (from `$CODEX_HOME/auth.json`). Same on any device for the same logged-in account.
63
+ - **Codex push (opt-in).** Set `METRO_CODEX_RC=ws://127.0.0.1:8421` and metro pushes each event via JSON-RPC `turn/start` to the Codex app-server. Codex's TUI must be attached with `--remote` to the same URL.
64
+ - **Cross-user notification.** `metro send metro://claude/<user-id>/<session-id>` (or `metro://codex/<user-id>/<session-id>`) routes through the daemon's IPC socket; the daemon re-emits on its stdout (and pushes to codex-rc), so the peer sees it. Discover reachable users/sessions via `metro stations` or `$METRO_STATE_DIR/user-registry.json`.
65
+ - **Webhooks (opt-in).** `metro webhook add <label>` registers an HTTP receive endpoint; the daemon binds `127.0.0.1:8420` (override with `$METRO_WEBHOOK_PORT`). If you've run `metro tunnel setup`, a Cloudflare named tunnel exposes it publicly. Each POST is re-emitted on stdout as an inbound event.
66
+
67
+ ---
68
+
69
+ ## Stations
70
+
71
+ Each endpoint is a **station** with declared capabilities:
72
+
73
+ | Station | Modalities | Features | Config |
74
+ |------------|---------------|-------------------------------------------------------|-----------------------------------------------------------------------------------------|
75
+ | `discord` | text + image | reply, send, edit, react, download, fetch | `DISCORD_BOT_TOKEN` + Message Content Intent |
76
+ | `telegram` | text + image | reply, send, edit, react, download | `TELEGRAM_BOT_TOKEN` |
77
+ | `claude` | text | send | auto-detected from `$CLAUDECODE`; identity via `claude auth status --json` |
78
+ | `codex` | text | send | auto-detected from `$METRO_CODEX_RC` / `$CODEX_HOME`; identity via `$CODEX_HOME/auth.json` |
79
+ | `webhook` | text | (receive-only; optional HMAC verify) | `metro webhook add <label>` + `metro tunnel setup` (Cloudflare named tunnel) |
18
80
 
19
- > **Discord setup:** toggle **Message Content Intent** in Developer Portal Bot Privileged Gateway Intents.
81
+ Run `metro stations` to see live config status (`✓` configured, `✗` not, `·` informational).
20
82
 
21
- Open Claude Code (`claude`) or Codex (`codex`), and tell it:
83
+ Behaviors worth knowing:
84
+ - **No streaming / no edit machinery in metro.** The local CLI runs the show; metro is one-shot REST.
85
+ - **No link previews.** Outgoing messages set `link_preview_options.is_disabled` on Telegram and `SUPPRESS_EMBEDS` on Discord.
86
+ - **Image attachments inbound** — `[image]` placeholders surface inline in `text`; the user calls `metro download` to materialize them. 20 MB cap.
87
+ - **Rich content outbound.** `metro send` / `reply` accept `--image=<path>` (repeatable: albums of up to 10), `--document=<path>` (repeatable), `--voice=<path>` (single voice message — Telegram renders the voice bubble), and `--buttons='[[{"text":"…","url":"…"}]]'` for inline URL-button keyboards. `metro edit` accepts `--buttons` (pass `'[]'` to clear). 20 MB / file. URL buttons only for now — no callback/interactive components.
88
+ - **Telegram non-forum groups are skipped.** No thread boundary to scope on.
89
+ - **Webhook signature verification.** Pass `--secret=<shared-secret>` to `metro webhook add` and the daemon verifies `X-Hub-Signature-256` (GitHub/Intercom format) on every POST. Mismatches return 401 and never reach the stream.
90
+
91
+ ---
92
+
93
+ ## Webhooks
94
+
95
+ Receive HTTP events from third parties (GitHub, Intercom, Fireflies, anything that POSTs) as standard metro inbound events. Each registered endpoint is one Line.
96
+
97
+ ```bash
98
+ # One-time per machine — bring your own Cloudflare domain (free Registrar at-cost):
99
+ brew install cloudflared
100
+ cloudflared tunnel login # browser OAuth, pick your domain
101
+ metro tunnel setup metro webhook.example.com # creates tunnel + DNS CNAME
102
+
103
+ # Per endpoint — repeat for each provider:
104
+ metro webhook add github --secret=$(openssl rand -hex 32)
105
+ # → https://webhook.example.com/wh/<id>
106
+ # (without `metro tunnel setup`, falls back to http://127.0.0.1:8420/wh/<id> — local-only)
107
+
108
+ metro # daemon binds 8420 + spawns cloudflared automatically
109
+ ```
22
110
 
23
- > Run `metro` in the background.
111
+ Paste the URL into the provider's webhook settings (for GitHub: **Content type must be `application/json`** — form-encoded won't parse). Every POST becomes an inbound event with `station: "webhook"`, `line: metro://webhook/<id>`, `payload: { headers, body }`. If you set `--secret`, metro verifies the `X-Hub-Signature-256` header (GitHub/Intercom format) and rejects mismatches with 401.
24
112
 
25
- DM your bot. The agent picks up the next inbound and replies — the bundled skill handles launching, stdout watching, reactions, and replies.
113
+ | Action | Command |
114
+ |---|---|
115
+ | Register an endpoint | `metro webhook add <label> [--secret=<shared-secret>]` |
116
+ | List endpoints + URLs | `metro webhook list` |
117
+ | Remove an endpoint | `metro webhook remove <id>` |
118
+ | One-time tunnel setup | `metro tunnel setup <tunnel-name> <hostname>` |
119
+ | Tunnel status | `metro tunnel status` |
26
120
 
27
- ## Config
121
+ The tunnel is optional — without it the listener binds `127.0.0.1:8420` only (good for local testing or your own loopback tools). With Cloudflare named tunnels, the URL stays stable across daemon restarts and machines. See [docs/uri-scheme.md](docs/uri-scheme.md) and [docs/users.md](docs/users.md) for the full event shape.
122
+
123
+ ---
124
+
125
+ ## Lines
126
+
127
+ Every conversational scope is identified by a **Line** — a URI in the form `metro://<station>/<path>`:
128
+
129
+ ```
130
+ metro://discord/1234567890123456789
131
+ metro://telegram/-1001234567890 # main chat / DM
132
+ metro://telegram/-1001234567890/42 # forum topic 42
133
+ metro://claude/9bfc7af0-…/50b00d11-… # claude user session
134
+ metro://codex/8119ecb1-…/01997d4b-… # codex user session
135
+ metro://webhook/fwaCgTKJuLAjS2K0 # HTTP webhook endpoint
136
+ ```
137
+
138
+ Anyone can post to a line via [`metro send`](#cli) — daemon required only for Claude / Codex lines. Full grammar in [`docs/uri-scheme.md`](docs/uri-scheme.md).
139
+
140
+ ---
141
+
142
+ ## CLI
143
+
144
+ ```
145
+ metro Run the daemon (emits JSON events on stdout).
146
+ metro setup [telegram|discord <token>] Save token, or show status.
147
+ metro setup clear [telegram|discord|all] Remove tokens.
148
+ metro doctor Health check.
149
+ metro stations List stations + capabilities.
150
+ metro lines List recently-seen conversations.
151
+ metro send <line> <text> [--image=…]… [--document=…]… [--voice=…] [--buttons=…]
152
+ Post a fresh message; --image/--document repeat for albums.
153
+ metro reply <line> <message_id> <text> [--image|--document|--voice|--buttons]
154
+ Threaded reply (same flags as send).
155
+ metro edit <line> <message_id> <text> [--buttons=<json>]
156
+ Edit a previously-sent message (text + URL-button keyboard).
157
+ metro react <line> <message_id> <emoji> Set or clear ('') a reaction.
158
+ metro download <line> <message_id> [--out=<dir>]
159
+ Download image attachments to disk.
160
+ metro fetch <line> [--limit=N] Recent-message lookback (Discord only).
161
+ metro history [--limit=N] [--line=…] [--station=…] [--kind=…] [--from=…] [--text=…] [--since=…]
162
+ Universal message log (every inbound + outbound), newest first.
163
+ metro webhook add <label> [--secret=…] Register an HTTP receive endpoint (GitHub, Intercom, …).
164
+ metro webhook list | remove <id> List or remove webhook endpoints.
165
+ metro tunnel setup <name> <hostname> Configure a Cloudflare named tunnel for public webhook URLs.
166
+ metro tunnel status Show current tunnel config.
167
+ metro update Upgrade in place.
168
+ ```
169
+
170
+ All commands accept `--json`. `reply` / `send` / `edit` read multi-line `<text>` from stdin if no positional is given.
171
+
172
+ **State files** in `$METRO_STATE_DIR` (default `~/.cache/metro`):
173
+ - `USERS.md` — user skill copied from the package on every start (so the path is stable across upgrades)
174
+ - `history.jsonl` — universal message log (one JSON object per line; append-only). Read with `metro history`. Each entry carries `from` and `to` as universal participant URIs (`metro://<station>/user/<id>`, `metro://claude/user/<orgId>`, `metro://codex/user/<accountId>`) plus a `fromName` display field. The dispatcher auto-detects the local user for `to` on inbound (`$CLAUDECODE` → `metro://claude/user/<orgId>` from `claude auth status --json`; `$METRO_CODEX_RC`/`$CODEX_HOME` → `metro://codex/user/<accountId>` from `$CODEX_HOME/auth.json`).
175
+ - `bot-ids.json` — `{discord: "<botUserId>", telegram: "<botUserId>"}` written by the daemon on startup (cached for the few historical lookups that still need a platform-side bot identity).
176
+ - `lines.json` — line → last-seen / name cache (read by `metro lines`)
177
+ - `user-registry.json` — every `(station, user-id, sessions[])` tuple metro has seen; surfaced under each Claude / Codex row in `metro stations`
178
+ - `stations/codex/session-id` — current codex-rc thread id (daemon writes on handshake; CLI processes read for `metro://codex/<user-id>/<session>`)
179
+ - `webhooks.json` — registered HTTP receive endpoints (id, label, optional shared secret)
180
+ - `tunnel.json` — Cloudflare named-tunnel config (`{name, hostname}`); when present, the daemon spawns `cloudflared tunnel run`. The token is resolved via `cloudflared tunnel token <name>` and passed through as `TUNNEL_TOKEN`, so the per-tunnel credentials JSON at `~/.cloudflared/<id>.json` is not required (the named-form spawn is the fallback when the token call fails)
181
+ - `.tail-lock` — dispatcher pid
182
+ - `metro.sock` — daemon IPC socket
183
+ - `telegram-offset.json` — last processed update id
184
+
185
+ ---
186
+
187
+ ## Configuration
28
188
 
29
189
  | Variable | Default | Description |
30
190
  |---|---|---|
31
191
  | `TELEGRAM_BOT_TOKEN`, `DISCORD_BOT_TOKEN` | — | Bot tokens. `metro setup` writes them here. |
192
+ | `METRO_CODEX_RC` | — | Codex app-server URL (`ws://…`, `wss://…`, `unix:///…`). When set, the daemon pushes each event via JSON-RPC `turn/start`. |
193
+ | `METRO_WEBHOOK_PORT` | `8420` | Local port the HTTP webhook listener binds to (always `127.0.0.1`; expose publicly via Cloudflare tunnel). |
194
+ | `METRO_USER_ID` | — | Override the resolved user id (orgId / accountId) used in `metro://<station>/user/<id>` and `metro://<station>/<id>/<session>`. Useful for testing. |
195
+ | `METRO_USER_SESSION_ID` | — | Override the resolved session id (Claude session / Codex thread). |
196
+ | `METRO_FROM` | — | Pin a custom `from` URI for all writes (overrides runtime detection). |
32
197
  | `METRO_CONFIG_DIR` | `~/.config/metro` | Where the global `.env` lives. |
33
- | `METRO_STATE_DIR` | `~/.cache/metro` | Lockfile, attachment cache, default download dir. |
198
+ | `METRO_STATE_DIR` | `~/.cache/metro` | Lockfile, line cache, IPC socket, telegram offset, registries, tunnel config. |
34
199
  | `METRO_LOG_LEVEL` | `info` | `trace` / `debug` / `info` / `warn` / `error` / `fatal`. |
35
200
 
36
- Token precedence: process env → `./.env` → `$METRO_CONFIG_DIR/.env`. Logs to stderr.
201
+ Precedence: process env → `./.env` → `$METRO_CONFIG_DIR/.env`. Logs go to stderr.
37
202
 
38
- ## Reference
203
+ ---
39
204
 
40
- - `metro --help` — command surface
41
- - `metro doctor` — health check
42
- - [SKILL.md](skills/metro/SKILL.md) — agent-facing flow
43
-
44
- ## Uninstall
205
+ ## Develop
45
206
 
46
207
  ```bash
47
- metro setup clear; metro setup skill --clear
48
- rm -rf ~/.cache/metro/
49
- npm uninstall -g @stage-labs/metro
208
+ git clone https://github.com/bonustrack/metro && cd metro
209
+ bun install && bun run build
210
+ bun link # makes `metro` resolve to this checkout
211
+ METRO_LOG_LEVEL=debug metro
212
+
213
+ bun run typecheck # ts
214
+ bun run lint # eslint
50
215
  ```
51
216
 
217
+ Source map:
218
+
219
+ - [`src/cli/`](src/cli/) — `metro` binary entry ([`index.ts`](src/cli/index.ts)) + admin commands ([`config.ts`](src/cli/config.ts): setup/doctor/update), action handlers ([`actions.ts`](src/cli/actions.ts): send/reply/edit/react/download/fetch), webhook + tunnel commands ([`webhook.ts`](src/cli/webhook.ts)), and shared CLI primitives ([`util.ts`](src/cli/util.ts)).
220
+ - [`src/dispatcher.ts`](src/dispatcher.ts) — the daemon: starts each station, emits events on stdout, listens on the IPC socket, optionally pushes to codex-rc, supervises the Cloudflare tunnel.
221
+ - [`src/stations/`](src/stations/) — Line URI scheme + ChatStation interface + listing ([`index.ts`](src/stations/index.ts)). Chat impls: [`discord.ts`](src/stations/discord.ts), [`telegram.ts`](src/stations/telegram.ts) (+ [`telegram-md.ts`](src/stations/telegram-md.ts) markdown helper). User identity resolvers: [`claude.ts`](src/stations/claude.ts) (orgId via `claude auth status --json`), [`codex.ts`](src/stations/codex.ts) (account_id via `auth.json`). HTTP receive: [`webhook.ts`](src/stations/webhook.ts).
222
+ - [`src/codex-rc.ts`](src/codex-rc.ts) — Codex app-server WebSocket push client (also exposes the rc thread id used as Codex session-id).
223
+ - [`src/tunnel.ts`](src/tunnel.ts) — Cloudflared named-tunnel supervisor.
224
+ - [`src/webhooks.ts`](src/webhooks.ts) — webhook endpoint store (`webhooks.json` CRUD).
225
+ - [`src/registry.ts`](src/registry.ts) — user registry: `(station, user-id, sessions[])` tracking.
226
+ - [`src/history.ts`](src/history.ts) — universal message log + `userSelf()` / `selfLine()` identity helpers.
227
+ - [`src/ipc.ts`](src/ipc.ts) — Unix-socket IPC between the daemon and one-shot CLI commands.
228
+ - [`src/cache.ts`](src/cache.ts) — in-memory line cache with debounced flush to `lines.json`, plus bot-id cache.
229
+ - [`docs/uri-scheme.md`](docs/uri-scheme.md) specs the Line format; [`docs/users.md`](docs/users.md) is the in-context skill for users.
230
+
231
+ CI runs typecheck + lint + build on every PR via [`.github/workflows/ci.yml`](.github/workflows/ci.yml).
232
+
233
+ ---
234
+
52
235
  ## Caveats
53
236
 
54
- - **No allowlist.** Anyone who can DM your bot or @-mention it can talk to your session. Run against bots you own.
55
- - **Latency.** Inbounds surface at the next agent decision boundary sub-second on Claude Code, longer on Codex turns.
237
+ - **No allowlist on chat stations.** Anyone who can DM/`@`-mention your bot can produce events. Run against bots you own.
238
+ - **Webhook secrets are optional but recommended.** Without `--secret`, anyone who learns the endpoint URL can POST events. With it, metro verifies `X-Hub-Signature-256` and rejects mismatches.
239
+ - **Telegram bot privacy is on by default**, which can block `@`-mentions in groups. Disable via [@BotFather](https://t.me/BotFather) → Bot Settings → Group Privacy, then kick + re-invite.
240
+ - **Telegram non-forum groups are skipped.** No thread boundary to scope on. DMs and forum topics work normally.
241
+ - **Telegram fetch isn't supported** (bot API doesn't expose history); `metro fetch` returns `[]` on Telegram lines.
242
+ - **Cloudflared is your responsibility.** `metro tunnel setup` records the named tunnel; you still install `cloudflared` (`brew install cloudflared`) and run `cloudflared tunnel login` once.
243
+
244
+ ---
245
+
246
+ ## Uninstall
247
+
248
+ ```bash
249
+ metro setup clear
250
+ rm -rf ~/.cache/metro
251
+ npm uninstall -g @stage-labs/metro
252
+ ```
package/dist/cache.js ADDED
@@ -0,0 +1,69 @@
1
+ /** Per-machine caches: seen lines (lines.json) + bot ids (bot-ids.json). */
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { errMsg, log } from './log.js';
5
+ import { STATE_DIR } from './paths.js';
6
+ const cacheFile = join(STATE_DIR, 'lines.json');
7
+ const FLUSH_DELAY_MS = 5_000;
8
+ let cache = null;
9
+ let dirty = false;
10
+ let flushTimer = null;
11
+ function read() {
12
+ if (cache)
13
+ return cache;
14
+ if (!existsSync(cacheFile))
15
+ return cache = {};
16
+ try {
17
+ cache = JSON.parse(readFileSync(cacheFile, 'utf8'));
18
+ }
19
+ catch (err) {
20
+ log.warn({ err: errMsg(err), path: cacheFile }, 'lines cache read failed; treating as empty');
21
+ cache = {};
22
+ }
23
+ return cache;
24
+ }
25
+ function flush() {
26
+ if (!dirty || !cache)
27
+ return;
28
+ try {
29
+ writeFileSync(cacheFile, JSON.stringify(cache, null, 2));
30
+ dirty = false;
31
+ }
32
+ catch (err) {
33
+ log.warn({ err: errMsg(err), path: cacheFile }, 'lines cache write failed');
34
+ }
35
+ }
36
+ process.on('exit', flush);
37
+ export function noteSeen(line, name) {
38
+ const c = read();
39
+ const entry = c[line] ??= { createdAt: new Date().toISOString() };
40
+ entry.lastSeenAt = new Date().toISOString();
41
+ if (name && entry.name !== name)
42
+ entry.name = name;
43
+ dirty = true;
44
+ if (!flushTimer)
45
+ flushTimer = setTimeout(() => { flushTimer = null; flush(); }, FLUSH_DELAY_MS);
46
+ }
47
+ export const listLines = () => Object.entries(read()).map(([line, entry]) => ({ line: line, entry }));
48
+ /** Bot identity cache: `{discord: "<userId>", telegram: "<userId>"}`. Daemon writes after getMe(). */
49
+ const botIdsFile = join(STATE_DIR, 'bot-ids.json');
50
+ const readBotIds = () => {
51
+ try {
52
+ return existsSync(botIdsFile) ? JSON.parse(readFileSync(botIdsFile, 'utf8')) : {};
53
+ }
54
+ catch {
55
+ return {};
56
+ }
57
+ };
58
+ export function saveBotId(station, id) {
59
+ const cur = readBotIds();
60
+ if (cur[station] === id)
61
+ return;
62
+ cur[station] = id;
63
+ try {
64
+ writeFileSync(botIdsFile, JSON.stringify(cur, null, 2));
65
+ }
66
+ catch (err) {
67
+ log.warn({ err: errMsg(err) }, 'bot-ids cache write failed');
68
+ }
69
+ }
@@ -0,0 +1,147 @@
1
+ /** CLI action handlers: send/reply/edit/react/download/fetch + helpers. */
2
+ import { mkdirSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { errMsg } from '../log.js';
6
+ import { DiscordStation } from '../stations/discord.js';
7
+ import { TelegramStation } from '../stations/telegram.js';
8
+ import { ipcCall } from '../ipc.js';
9
+ import { userSelf, appendHistory, lookupEntry, mintId, readHistory, resolvePlatformId, } from '../history.js';
10
+ import { asLine, Line } from '../stations/index.js';
11
+ import { loadMetroEnv } from '../paths.js';
12
+ import { emit, flagList, flagOne, isJson, need, resolveText, writeJson, } from './util.js';
13
+ export function chatStationOf(line) {
14
+ const s = Line.station(line);
15
+ if (s === 'discord')
16
+ return new DiscordStation();
17
+ if (s === 'telegram')
18
+ return new TelegramStation();
19
+ throw new Error(`no chat station for line "${line}" (try metro://{discord|telegram}/...)`);
20
+ }
21
+ function parseButtons(f) {
22
+ const raw = flagOne(f, 'buttons');
23
+ if (raw === undefined)
24
+ return undefined;
25
+ try {
26
+ return JSON.parse(raw);
27
+ }
28
+ catch (err) {
29
+ throw new Error(`--buttons must be JSON like '[[{"text":"…","url":"…"}]]': ${errMsg(err)}`);
30
+ }
31
+ }
32
+ function richOpts(f) {
33
+ const opts = {};
34
+ const images = flagList(f, 'image');
35
+ if (images.length)
36
+ opts.images = images;
37
+ const documents = flagList(f, 'document');
38
+ if (documents.length)
39
+ opts.documents = documents;
40
+ const voice = flagOne(f, 'voice');
41
+ if (voice)
42
+ opts.voice = voice;
43
+ const buttons = parseButtons(f);
44
+ if (buttons)
45
+ opts.buttons = buttons;
46
+ return opts;
47
+ }
48
+ /** Mirror the original entry's destination: group → `line`; DM → the other-party user URI. */
49
+ function destinationFor(orig, line) {
50
+ if (!orig || !orig.to || orig.to === orig.line)
51
+ return line;
52
+ return orig.from;
53
+ }
54
+ /** Append an outbound action to history.jsonl; `to` mirrors the destination per `destinationFor`. */
55
+ function logOutbound(f, e) {
56
+ const id = mintId();
57
+ const fromOverride = flagOne(f, 'from');
58
+ appendHistory({
59
+ id, ts: new Date().toISOString(), station: Line.station(e.line) ?? '?',
60
+ from: fromOverride ? asLine(fromOverride) : userSelf(), to: e.to ?? e.line, ...e,
61
+ });
62
+ return id;
63
+ }
64
+ export async function cmdSend(p, f) {
65
+ need(p, 1, 'metro send <line> <text> [--image=<path>]… [--document=<path>]… [--voice=<path>] [--buttons=<json>]');
66
+ loadMetroEnv();
67
+ const text = await resolveText(p, 1), line = asLine(p[0]);
68
+ if (Line.isLocal(line)) {
69
+ const from = flagOne(f, 'from');
70
+ const resp = await ipcCall({ op: 'notify', line, from, text });
71
+ if (!resp.ok)
72
+ throw new Error(resp.error);
73
+ return emit(f, `notified ${line}`, { ok: true, line, id: null, messageId: null });
74
+ }
75
+ const messageId = await chatStationOf(line).send(line, text, richOpts(f));
76
+ /** Inherit destination from the most recent inbound on this line so DM sends address the user. */
77
+ const to = destinationFor(readHistory({ line, kind: 'inbound', limit: 1 })[0], line);
78
+ const id = logOutbound(f, { kind: 'outbound', line, text, messageId, to });
79
+ emit(f, `sent ${id} (${messageId}) to ${line}`, { ok: true, line, id, messageId });
80
+ }
81
+ export async function cmdReply(p, f) {
82
+ need(p, 2, 'metro reply <line> <message_id> <text> [--image=… --document=… --voice=… --buttons=…]');
83
+ loadMetroEnv();
84
+ const [to, replyToArg] = p, text = await resolveText(p, 2), line = asLine(to);
85
+ const replyTo = resolvePlatformId(replyToArg);
86
+ const messageId = await chatStationOf(line).send(line, text, { ...richOpts(f), replyTo });
87
+ const id = logOutbound(f, { kind: 'outbound', line, text, messageId, replyTo: replyToArg, to: destinationFor(lookupEntry(replyToArg), line) });
88
+ emit(f, `replied ${id} (${messageId}) to ${line}#${replyTo}`, { ok: true, line, id, replyTo: replyToArg, messageId });
89
+ }
90
+ export async function cmdEdit(p, f) {
91
+ need(p, 2, 'metro edit <line> <message_id> <text> [--buttons=<json>]');
92
+ loadMetroEnv();
93
+ const [to, msgArg] = p, text = await resolveText(p, 2), line = asLine(to);
94
+ const platformId = resolvePlatformId(msgArg);
95
+ const buttons = parseButtons(f);
96
+ await chatStationOf(line).edit(line, platformId, text, buttons ? { buttons } : undefined);
97
+ /** Carry forward the original recipient if we have a row for this message. */
98
+ const id = logOutbound(f, { kind: 'edit', line, text, messageId: platformId, replyTo: msgArg, to: lookupEntry(msgArg)?.to });
99
+ emit(f, `edited ${line}#${platformId} (${id})`, { ok: true, line, id, messageId: platformId });
100
+ }
101
+ export async function cmdReact(p, f) {
102
+ need(p, 2, 'metro react <line> <message_id> <emoji> (empty emoji clears)');
103
+ loadMetroEnv();
104
+ const [to, msgArg, emoji = ''] = p, line = asLine(to);
105
+ const platformId = resolvePlatformId(msgArg);
106
+ await chatStationOf(line).react(line, platformId, emoji);
107
+ const id = logOutbound(f, { kind: 'react', line, messageId: platformId, emoji, to: destinationFor(lookupEntry(msgArg), line) });
108
+ const human = emoji ? `reacted ${emoji} on ${line}#${platformId}` : `cleared reaction on ${line}#${platformId}`;
109
+ emit(f, human, { ok: true, line, id, messageId: platformId, emoji });
110
+ }
111
+ export async function cmdDownload(p, f) {
112
+ need(p, 2, 'metro download <line> <message_id> [--out=<dir>]');
113
+ loadMetroEnv();
114
+ const [to, msgArg] = p, line = asLine(to);
115
+ const messageId = resolvePlatformId(msgArg);
116
+ const outDir = typeof f.out === 'string' ? f.out : join(tmpdir(), 'metro-downloads');
117
+ mkdirSync(outDir, { recursive: true });
118
+ /** Telegram has no get-message-by-id REST endpoint — daemon holds the in-memory snapshot. */
119
+ let files;
120
+ if (Line.station(line) === 'telegram') {
121
+ const resp = await ipcCall({ op: 'download', line, messageId, outDir });
122
+ if (!resp.ok)
123
+ throw new Error(resp.error);
124
+ files = 'files' in resp ? resp.files : [];
125
+ }
126
+ else {
127
+ files = await chatStationOf(line).download(line, messageId, outDir);
128
+ }
129
+ if (isJson(f))
130
+ return writeJson({ ok: true, line, files });
131
+ if (!files.length)
132
+ process.stdout.write(`(no image attachments on ${line}#${messageId})\n`);
133
+ for (const file of files)
134
+ process.stdout.write(file.path + '\n');
135
+ }
136
+ export async function cmdFetch(p, f) {
137
+ need(p, 1, 'metro fetch <line> [--limit=N]');
138
+ loadMetroEnv();
139
+ const line = asLine(p[0]);
140
+ const messages = await chatStationOf(line).fetch(line, Number(flagOne(f, 'limit')) || 20);
141
+ if (isJson(f))
142
+ return writeJson({ ok: true, line, messages });
143
+ if (!messages.length)
144
+ process.stdout.write(`(no messages on ${line})\n`);
145
+ for (const m of messages)
146
+ process.stdout.write(`${m.timestamp} ${m.author}: ${m.text}\n`);
147
+ }