@stage-labs/metro 0.1.0-beta.6 → 0.1.0-beta.8
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 +87 -30
- package/dist/cache.js +11 -10
- package/dist/cli/actions.js +13 -30
- package/dist/cli/config.js +10 -9
- package/dist/cli/index.js +23 -8
- package/dist/cli/webhook.js +83 -0
- package/dist/codex-rc.js +14 -5
- package/dist/dispatcher.js +43 -33
- package/dist/history.js +21 -6
- package/dist/ipc.js +2 -1
- package/dist/paths.js +3 -3
- package/dist/registry.js +48 -0
- package/dist/stations/claude.js +45 -0
- package/dist/stations/codex.js +68 -0
- package/dist/stations/discord.js +17 -15
- package/dist/stations/index.js +68 -8
- package/dist/stations/telegram.js +5 -27
- package/dist/stations/webhook.js +100 -0
- package/dist/tunnel.js +49 -0
- package/dist/webhooks.js +40 -0
- package/docs/agents.md +67 -19
- package/docs/uri-scheme.md +68 -14
- package/package.json +1 -1
- package/skills/metro/SKILL.md +51 -22
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# Metro
|
|
2
2
|
|
|
3
|
-
> **A live JSON stream of Telegram
|
|
3
|
+
> **A live JSON stream of Telegram, Discord, webhooks, and cross-agent messages for your local Claude Code / Codex session.**
|
|
4
4
|
|
|
5
|
-
Metro is a small daemon you launch from inside your agent. It connects to Discord and
|
|
5
|
+
Metro is a small daemon you launch from inside your agent. 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-agent: any agent can ping any other via `metro send metro://claude/<agent-id>/<session-id>` and the daemon re-emits it on the stream.
|
|
6
6
|
|
|
7
7
|
```
|
|
8
8
|
[Claude Code session]
|
|
@@ -10,8 +10,10 @@ Metro is a small daemon you launch from inside your agent. It connects to Discor
|
|
|
10
10
|
$ metro & # backgrounded
|
|
11
11
|
$ Monitor( … metro's stdout … )
|
|
12
12
|
|
|
13
|
-
>>> {"
|
|
14
|
-
"text":"@bot we got a 5xx spike from /v1/sync. Look?",
|
|
13
|
+
>>> {"kind":"inbound","station":"discord","line":"metro://discord/123…","messageId":"9876",
|
|
14
|
+
"text":"@bot we got a 5xx spike from /v1/sync. Look?",
|
|
15
|
+
"payload":{"channelId":"123…","guildId":"456…","content":"<@…> we got a 5xx spike…",
|
|
16
|
+
"mentions":{"users":["<bot-id>"],"roles":[],"everyone":false},…}}
|
|
15
17
|
|
|
16
18
|
[I'd run git log + read services/sync.ts, then…]
|
|
17
19
|
Bash: metro reply metro://discord/123… 9876 "three deploys in the last 24h…"
|
|
@@ -41,20 +43,23 @@ In **Discord**: DM the bot, or `@<bot>` in any channel. In **Telegram**: DM, or
|
|
|
41
43
|
## Architecture
|
|
42
44
|
|
|
43
45
|
```
|
|
44
|
-
Discord gateway
|
|
45
|
-
Telegram poller
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
46
|
+
Discord gateway ──┐
|
|
47
|
+
Telegram poller ──┤
|
|
48
|
+
Cloudflare tunnel ──┤ ── HTTP webhooks (GitHub, Intercom, …)
|
|
49
|
+
│
|
|
50
|
+
├─▶ metro daemon ───▶ stdout (JSON events; Claude Code's Monitor reads here)
|
|
51
|
+
│ ───▶ codex-rc WebSocket (Codex turn/start; opt-in)
|
|
52
|
+
│ ◀── IPC Unix socket (metro send to agent lines)
|
|
53
|
+
│
|
|
54
|
+
agent CLI calls ────┴── REST → Discord / Telegram (metro reply / send / edit / react / download / fetch)
|
|
52
55
|
```
|
|
53
56
|
|
|
54
57
|
- **Inversion of control.** The agent (Claude Code, Codex) launches `metro`, not the other way around. Metro never spawns an agent process.
|
|
55
58
|
- **Single daemon per machine.** Lockfile at `$METRO_STATE_DIR/.tail-lock` enforces singleton.
|
|
59
|
+
- **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.
|
|
56
60
|
- **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.
|
|
57
|
-
- **Cross-agent notification.** `metro send metro://claude/<
|
|
61
|
+
- **Cross-agent notification.** `metro send metro://claude/<agent-id>/<session-id>` (or `metro://codex/<agent-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 agent sees it. Discover reachable agents/sessions via `metro stations` or `$METRO_STATE_DIR/agent-registry.json`.
|
|
62
|
+
- **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.
|
|
58
63
|
|
|
59
64
|
---
|
|
60
65
|
|
|
@@ -62,12 +67,13 @@ agent CLI calls ──┴── REST → Discord / Telegram (metro reply / sen
|
|
|
62
67
|
|
|
63
68
|
Each endpoint is a **station** with declared capabilities:
|
|
64
69
|
|
|
65
|
-
| Station | Kind
|
|
66
|
-
|
|
67
|
-
| `discord` | chat
|
|
68
|
-
| `telegram` | chat
|
|
69
|
-
| `claude` | agent
|
|
70
|
-
| `codex` | agent
|
|
70
|
+
| Station | Kind | Modalities | Features | Config |
|
|
71
|
+
|------------|---------|---------------|-------------------------------------------------------|-----------------------------------------------------------------------------------------|
|
|
72
|
+
| `discord` | chat | text + image | reply, send, edit, react, download, fetch | `DISCORD_BOT_TOKEN` + Message Content Intent |
|
|
73
|
+
| `telegram` | chat | text + image | reply, send, edit, react, download | `TELEGRAM_BOT_TOKEN` |
|
|
74
|
+
| `claude` | agent | text | send, notify | auto-detected from `$CLAUDECODE`; identity via `claude auth status --json` |
|
|
75
|
+
| `codex` | agent | text | send, notify | auto-detected from `$METRO_CODEX_RC` / `$CODEX_HOME`; identity via `$CODEX_HOME/auth.json` |
|
|
76
|
+
| `webhook` | service | text | (receive-only; optional HMAC verify) | `metro webhook add <label>` + `metro tunnel setup` (Cloudflare named tunnel) |
|
|
71
77
|
|
|
72
78
|
Run `metro stations` to see live config status (`✓` configured, `✗` not, `·` informational).
|
|
73
79
|
|
|
@@ -77,6 +83,39 @@ Behaviors worth knowing:
|
|
|
77
83
|
- **Image attachments inbound** — `[image]` placeholders surface inline in `text`; the agent calls `metro download` to materialize them. 20 MB cap.
|
|
78
84
|
- **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.
|
|
79
85
|
- **Telegram non-forum groups are skipped.** No thread boundary to scope on.
|
|
86
|
+
- **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.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Webhooks
|
|
91
|
+
|
|
92
|
+
Receive HTTP events from third parties (GitHub, Intercom, Fireflies, anything that POSTs) as standard metro inbound events. Each registered endpoint is one Line.
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
# One-time per machine — bring your own Cloudflare domain (free Registrar at-cost):
|
|
96
|
+
brew install cloudflared
|
|
97
|
+
cloudflared tunnel login # browser OAuth, pick your domain
|
|
98
|
+
metro tunnel setup metro webhook.example.com # creates tunnel + DNS CNAME
|
|
99
|
+
|
|
100
|
+
# Per endpoint — repeat for each provider:
|
|
101
|
+
metro webhook add github --secret=$(openssl rand -hex 32)
|
|
102
|
+
# → https://webhook.example.com/wh/<id>
|
|
103
|
+
# (without `metro tunnel setup`, falls back to http://127.0.0.1:8420/wh/<id> — local-only)
|
|
104
|
+
|
|
105
|
+
metro # daemon binds 8420 + spawns cloudflared automatically
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
| Action | Command |
|
|
111
|
+
|---|---|
|
|
112
|
+
| Register an endpoint | `metro webhook add <label> [--secret=<shared-secret>]` |
|
|
113
|
+
| List endpoints + URLs | `metro webhook list` |
|
|
114
|
+
| Remove an endpoint | `metro webhook remove <id>` |
|
|
115
|
+
| One-time tunnel setup | `metro tunnel setup <tunnel-name> <hostname>` |
|
|
116
|
+
| Tunnel status | `metro tunnel status` |
|
|
117
|
+
|
|
118
|
+
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/agents.md](docs/agents.md) for the full event shape.
|
|
80
119
|
|
|
81
120
|
---
|
|
82
121
|
|
|
@@ -88,8 +127,9 @@ Every conversational scope is identified by a **Line** — a URI in the form `me
|
|
|
88
127
|
metro://discord/1234567890123456789
|
|
89
128
|
metro://telegram/-1001234567890 # main chat / DM
|
|
90
129
|
metro://telegram/-1001234567890/42 # forum topic 42
|
|
91
|
-
metro://claude/
|
|
92
|
-
metro://codex/
|
|
130
|
+
metro://claude/9bfc7af0-…/50b00d11-… # claude agent session
|
|
131
|
+
metro://codex/8119ecb1-…/01997d4b-… # codex agent session
|
|
132
|
+
metro://webhook/fwaCgTKJuLAjS2K0 # HTTP webhook endpoint
|
|
93
133
|
```
|
|
94
134
|
|
|
95
135
|
Anyone can post to a line via [`metro send`](#cli) — daemon required only for agent lines. Full grammar in [`docs/uri-scheme.md`](docs/uri-scheme.md).
|
|
@@ -115,9 +155,12 @@ metro react <line> <message_id> <emoji> Set or clear ('') a reaction.
|
|
|
115
155
|
metro download <line> <message_id> [--out=<dir>]
|
|
116
156
|
Download image attachments to disk.
|
|
117
157
|
metro fetch <line> [--limit=N] Recent-message lookback (Discord only).
|
|
118
|
-
metro notify <line> <text> [--from=<line>] Emit a notification on the daemon's stream.
|
|
119
158
|
metro history [--limit=N] [--line=…] [--station=…] [--kind=…] [--from=…] [--text=…] [--since=…]
|
|
120
159
|
Universal message log (every inbound + outbound), newest first.
|
|
160
|
+
metro webhook add <label> [--secret=…] Register an HTTP receive endpoint (GitHub, Intercom, …).
|
|
161
|
+
metro webhook list | remove <id> List or remove webhook endpoints.
|
|
162
|
+
metro tunnel setup <name> <hostname> Configure a Cloudflare named tunnel for public webhook URLs.
|
|
163
|
+
metro tunnel status Show current tunnel config.
|
|
121
164
|
metro update Upgrade in place.
|
|
122
165
|
```
|
|
123
166
|
|
|
@@ -125,9 +168,13 @@ All commands accept `--json`. `reply` / `send` / `edit` read multi-line `<text>`
|
|
|
125
168
|
|
|
126
169
|
**State files** in `$METRO_STATE_DIR` (default `~/.cache/metro`):
|
|
127
170
|
- `AGENTS.md` — agent skill copied from the package on every start (so the path is stable across upgrades)
|
|
128
|
-
- `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/<
|
|
171
|
+
- `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 consuming agent 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`).
|
|
129
172
|
- `bot-ids.json` — `{discord: "<botUserId>", telegram: "<botUserId>"}` written by the daemon on startup (cached for the few historical lookups that still need a bot identity).
|
|
130
173
|
- `lines.json` — line → last-seen / name cache (read by `metro lines`)
|
|
174
|
+
- `agent-registry.json` — every `(station, agent-id, sessions[])` tuple metro has seen; surfaced under each agent row in `metro stations`
|
|
175
|
+
- `stations/codex/session-id` — current codex-rc thread id (daemon writes on handshake; CLI processes read for `metro://codex/<agent-id>/<session>`)
|
|
176
|
+
- `webhooks.json` — registered HTTP receive endpoints (id, label, optional shared secret)
|
|
177
|
+
- `tunnel.json` — Cloudflare named-tunnel config (`{name, hostname}`); when present, the daemon spawns `cloudflared tunnel run`
|
|
131
178
|
- `.tail-lock` — dispatcher pid
|
|
132
179
|
- `metro.sock` — daemon IPC socket
|
|
133
180
|
- `telegram-offset.json` — last processed update id
|
|
@@ -140,8 +187,12 @@ All commands accept `--json`. `reply` / `send` / `edit` read multi-line `<text>`
|
|
|
140
187
|
|---|---|---|
|
|
141
188
|
| `TELEGRAM_BOT_TOKEN`, `DISCORD_BOT_TOKEN` | — | Bot tokens. `metro setup` writes them here. |
|
|
142
189
|
| `METRO_CODEX_RC` | — | Codex app-server URL (`ws://…`, `wss://…`, `unix:///…`). When set, the daemon pushes each event via JSON-RPC `turn/start`. |
|
|
190
|
+
| `METRO_WEBHOOK_PORT` | `8420` | Local port the HTTP webhook listener binds to (always `127.0.0.1`; expose publicly via Cloudflare tunnel). |
|
|
191
|
+
| `METRO_AGENT_ID` | — | Override the resolved agent id (orgId / accountId) used in `metro://<station>/user/<id>` and `metro://<station>/<id>/<session>`. Useful for testing. |
|
|
192
|
+
| `METRO_AGENT_SESSION_ID` | — | Override the resolved session id (Claude session / Codex thread). |
|
|
193
|
+
| `METRO_FROM` | — | Pin a custom `from` URI for all writes (overrides runtime detection). |
|
|
143
194
|
| `METRO_CONFIG_DIR` | `~/.config/metro` | Where the global `.env` lives. |
|
|
144
|
-
| `METRO_STATE_DIR` | `~/.cache/metro` | Lockfile, line cache, IPC socket, telegram offset. |
|
|
195
|
+
| `METRO_STATE_DIR` | `~/.cache/metro` | Lockfile, line cache, IPC socket, telegram offset, registries, tunnel config. |
|
|
145
196
|
| `METRO_LOG_LEVEL` | `info` | `trace` / `debug` / `info` / `warn` / `error` / `fatal`. |
|
|
146
197
|
|
|
147
198
|
Precedence: process env → `./.env` → `$METRO_CONFIG_DIR/.env`. Logs go to stderr.
|
|
@@ -162,12 +213,16 @@ bun run lint # eslint
|
|
|
162
213
|
|
|
163
214
|
Source map:
|
|
164
215
|
|
|
165
|
-
- [`src/cli/`](src/cli/) — `metro` binary entry ([`index.ts`](src/cli/index.ts)) + admin commands ([`config.ts`](src/cli/config.ts): setup/doctor/update) + shared CLI primitives ([`util.ts`](src/cli/util.ts)).
|
|
166
|
-
- [`src/dispatcher.ts`](src/dispatcher.ts) — the daemon: starts each
|
|
167
|
-
- [`src/stations/`](src/stations/) — Line URI scheme + ChatStation interface + listing ([`index.ts`](src/stations/index.ts))
|
|
168
|
-
- [`src/codex-rc.ts`](src/codex-rc.ts) — Codex app-server WebSocket push client.
|
|
216
|
+
- [`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)).
|
|
217
|
+
- [`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.
|
|
218
|
+
- [`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). Agent 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).
|
|
219
|
+
- [`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).
|
|
220
|
+
- [`src/tunnel.ts`](src/tunnel.ts) — Cloudflared named-tunnel supervisor.
|
|
221
|
+
- [`src/webhooks.ts`](src/webhooks.ts) — webhook endpoint store (`webhooks.json` CRUD).
|
|
222
|
+
- [`src/registry.ts`](src/registry.ts) — agent registry: `(station, agent-id, sessions[])` tracking.
|
|
223
|
+
- [`src/history.ts`](src/history.ts) — universal message log + `agentSelf()` / `selfLine()` identity helpers.
|
|
169
224
|
- [`src/ipc.ts`](src/ipc.ts) — Unix-socket IPC between the daemon and one-shot CLI commands.
|
|
170
|
-
- [`src/cache.ts`](src/cache.ts) — in-memory line cache with debounced flush to `lines.json
|
|
225
|
+
- [`src/cache.ts`](src/cache.ts) — in-memory line cache with debounced flush to `lines.json`, plus bot-id cache.
|
|
171
226
|
- [`docs/uri-scheme.md`](docs/uri-scheme.md) specs the Line format; [`docs/agents.md`](docs/agents.md) is the in-context skill for agents.
|
|
172
227
|
|
|
173
228
|
CI runs typecheck + lint + build on every PR via [`.github/workflows/ci.yml`](.github/workflows/ci.yml).
|
|
@@ -176,10 +231,12 @@ CI runs typecheck + lint + build on every PR via [`.github/workflows/ci.yml`](.g
|
|
|
176
231
|
|
|
177
232
|
## Caveats
|
|
178
233
|
|
|
179
|
-
- **No allowlist.** Anyone who can DM/`@`-mention your bot can produce events. Run against bots you own.
|
|
234
|
+
- **No allowlist on chat stations.** Anyone who can DM/`@`-mention your bot can produce events. Run against bots you own.
|
|
235
|
+
- **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.
|
|
180
236
|
- **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.
|
|
181
237
|
- **Telegram non-forum groups are skipped.** No thread boundary to scope on. DMs and forum topics work normally.
|
|
182
238
|
- **Telegram fetch isn't supported** (bot API doesn't expose history); `metro fetch` returns `[]` on Telegram lines.
|
|
239
|
+
- **Cloudflared is your responsibility.** `metro tunnel setup` records the named tunnel; you still install `cloudflared` (`brew install cloudflared`) and run `cloudflared tunnel login` once.
|
|
183
240
|
|
|
184
241
|
---
|
|
185
242
|
|
package/dist/cache.js
CHANGED
|
@@ -48,9 +48,16 @@ export function noteSeen(line, name) {
|
|
|
48
48
|
export const listLines = () => Object.entries(read()).map(([line, entry]) => ({ line: line, entry }));
|
|
49
49
|
/** Bot identity cache: `{discord: "<userId>", telegram: "<userId>"}`. Daemon writes after getMe(). */
|
|
50
50
|
const botIdsFile = join(STATE_DIR, 'bot-ids.json');
|
|
51
|
+
const readBotIds = () => {
|
|
52
|
+
try {
|
|
53
|
+
return existsSync(botIdsFile) ? JSON.parse(readFileSync(botIdsFile, 'utf8')) : {};
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
};
|
|
51
59
|
export function saveBotId(station, id) {
|
|
52
|
-
const cur =
|
|
53
|
-
? JSON.parse(readFileSync(botIdsFile, 'utf8')) : {};
|
|
60
|
+
const cur = readBotIds();
|
|
54
61
|
if (cur[station] === id)
|
|
55
62
|
return;
|
|
56
63
|
cur[station] = id;
|
|
@@ -63,12 +70,6 @@ export function saveBotId(station, id) {
|
|
|
63
70
|
}
|
|
64
71
|
/** Resolve the bot's URI for a station. Returns `metro://<station>/bot/<id>` or the placeholder. */
|
|
65
72
|
export function botLine(station) {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
? JSON.parse(readFileSync(botIdsFile, 'utf8')) : {};
|
|
69
|
-
return ids[station] ? Line.bot(station, ids[station]) : `metro://${station}/bot`;
|
|
70
|
-
}
|
|
71
|
-
catch {
|
|
72
|
-
return `metro://${station}/bot`;
|
|
73
|
-
}
|
|
73
|
+
const id = readBotIds()[station];
|
|
74
|
+
return id ? Line.bot(station, id) : `metro://${station}/bot`;
|
|
74
75
|
}
|
package/dist/cli/actions.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** CLI action handlers: send/reply/edit/react/download/fetch
|
|
1
|
+
/** CLI action handlers: send/reply/edit/react/download/fetch + helpers. */
|
|
2
2
|
import { mkdirSync } from 'node:fs';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
@@ -45,34 +45,29 @@ function richOpts(f) {
|
|
|
45
45
|
opts.buttons = buttons;
|
|
46
46
|
return opts;
|
|
47
47
|
}
|
|
48
|
-
/** Append an outbound action to history.jsonl;
|
|
49
|
-
function logOutbound(f,
|
|
48
|
+
/** Append an outbound action to history.jsonl; `to` = the original sender when replying/reacting. */
|
|
49
|
+
function logOutbound(f, e) {
|
|
50
50
|
const id = mintId();
|
|
51
|
-
const station = Line.station(line) ?? '?';
|
|
52
51
|
const fromOverride = flagOne(f, 'from');
|
|
53
|
-
const from = fromOverride ? asLine(fromOverride) : agentSelf();
|
|
54
52
|
appendHistory({
|
|
55
|
-
id, ts: new Date().toISOString(),
|
|
56
|
-
|
|
57
|
-
attachments: [...(opts?.images ?? []), ...(opts?.documents ?? []), ...(opts?.voice ? [opts.voice] : [])],
|
|
53
|
+
id, ts: new Date().toISOString(), station: Line.station(e.line) ?? '?',
|
|
54
|
+
from: fromOverride ? asLine(fromOverride) : agentSelf(), to: e.to ?? e.line, ...e,
|
|
58
55
|
});
|
|
59
56
|
return id;
|
|
60
57
|
}
|
|
61
|
-
/** When replying/reacting/editing, the recipient is the original message's sender (if we have it). */
|
|
62
|
-
const recipientFor = (idOrPlatform) => lookupEntry(idOrPlatform)?.from;
|
|
63
58
|
export async function cmdSend(p, f) {
|
|
64
59
|
need(p, 1, 'metro send <line> <text> [--image=<path>]… [--document=<path>]… [--voice=<path>] [--buttons=<json>]');
|
|
65
60
|
loadMetroEnv();
|
|
66
61
|
const text = await resolveText(p, 1), line = asLine(p[0]);
|
|
67
62
|
if (Line.isAgent(line)) {
|
|
68
|
-
const
|
|
63
|
+
const from = flagOne(f, 'from');
|
|
64
|
+
const resp = await ipcCall({ op: 'notify', line, from, text });
|
|
69
65
|
if (!resp.ok)
|
|
70
66
|
throw new Error(resp.error);
|
|
71
67
|
return emit(f, `notified ${line}`, { ok: true, line, id: null, messageId: null });
|
|
72
68
|
}
|
|
73
|
-
const
|
|
74
|
-
const
|
|
75
|
-
const id = logOutbound(f, 'outbound', line, text, messageId, undefined, opts);
|
|
69
|
+
const messageId = await chatStationOf(line).send(line, text, richOpts(f));
|
|
70
|
+
const id = logOutbound(f, { kind: 'outbound', line, text, messageId });
|
|
76
71
|
emit(f, `sent ${id} (${messageId}) to ${line}`, { ok: true, line, id, messageId });
|
|
77
72
|
}
|
|
78
73
|
export async function cmdReply(p, f) {
|
|
@@ -80,9 +75,8 @@ export async function cmdReply(p, f) {
|
|
|
80
75
|
loadMetroEnv();
|
|
81
76
|
const [to, replyToArg] = p, text = await resolveText(p, 2), line = asLine(to);
|
|
82
77
|
const replyTo = resolvePlatformId(replyToArg);
|
|
83
|
-
const
|
|
84
|
-
const
|
|
85
|
-
const id = logOutbound(f, 'outbound', line, text, messageId, replyToArg, opts, undefined, recipientFor(replyToArg));
|
|
78
|
+
const messageId = await chatStationOf(line).send(line, text, { ...richOpts(f), replyTo });
|
|
79
|
+
const id = logOutbound(f, { kind: 'outbound', line, text, messageId, replyTo: replyToArg, to: lookupEntry(replyToArg)?.from });
|
|
86
80
|
emit(f, `replied ${id} (${messageId}) to ${line}#${replyTo}`, { ok: true, line, id, replyTo: replyToArg, messageId });
|
|
87
81
|
}
|
|
88
82
|
export async function cmdEdit(p, f) {
|
|
@@ -93,8 +87,7 @@ export async function cmdEdit(p, f) {
|
|
|
93
87
|
const buttons = parseButtons(f);
|
|
94
88
|
await chatStationOf(line).edit(line, platformId, text, buttons ? { buttons } : undefined);
|
|
95
89
|
/** Carry forward the original recipient if we have a row for this message. */
|
|
96
|
-
const
|
|
97
|
-
const id = logOutbound(f, 'edit', line, text, platformId, msgArg, undefined, undefined, original?.to);
|
|
90
|
+
const id = logOutbound(f, { kind: 'edit', line, text, messageId: platformId, replyTo: msgArg, to: lookupEntry(msgArg)?.to });
|
|
98
91
|
emit(f, `edited ${line}#${platformId} (${id})`, { ok: true, line, id, messageId: platformId });
|
|
99
92
|
}
|
|
100
93
|
export async function cmdReact(p, f) {
|
|
@@ -103,7 +96,7 @@ export async function cmdReact(p, f) {
|
|
|
103
96
|
const [to, msgArg, emoji = ''] = p, line = asLine(to);
|
|
104
97
|
const platformId = resolvePlatformId(msgArg);
|
|
105
98
|
await chatStationOf(line).react(line, platformId, emoji);
|
|
106
|
-
const id = logOutbound(f, 'react', line,
|
|
99
|
+
const id = logOutbound(f, { kind: 'react', line, messageId: platformId, emoji, to: lookupEntry(msgArg)?.from });
|
|
107
100
|
const human = emoji ? `reacted ${emoji} on ${line}#${platformId}` : `cleared reaction on ${line}#${platformId}`;
|
|
108
101
|
emit(f, human, { ok: true, line, id, messageId: platformId, emoji });
|
|
109
102
|
}
|
|
@@ -144,13 +137,3 @@ export async function cmdFetch(p, f) {
|
|
|
144
137
|
for (const m of messages)
|
|
145
138
|
process.stdout.write(`${m.timestamp} ${m.author}: ${m.text}\n`);
|
|
146
139
|
}
|
|
147
|
-
export async function cmdNotify(p, f) {
|
|
148
|
-
need(p, 1, 'metro notify <line> <text> [--from=<line>]');
|
|
149
|
-
loadMetroEnv();
|
|
150
|
-
const text = await resolveText(p, 1), line = asLine(p[0]);
|
|
151
|
-
const from = flagOne(f, 'from');
|
|
152
|
-
const resp = await ipcCall({ op: 'notify', line, from, text });
|
|
153
|
-
if (!resp.ok)
|
|
154
|
-
throw new Error(resp.error);
|
|
155
|
-
emit(f, `notified ${line}`, { ok: true, line });
|
|
156
|
-
}
|
package/dist/cli/config.js
CHANGED
|
@@ -10,6 +10,7 @@ import { CONFIG_ENV_FILE, configuredPlatforms, loadMetroEnv, readDotenv, STATE_D
|
|
|
10
10
|
import { emit, exitErr, isJson, writeJson } from './util.js';
|
|
11
11
|
import { cmdSetupSkill, skillStatus } from './skill.js';
|
|
12
12
|
const TOKEN_KEYS = { telegram: 'TELEGRAM_BOT_TOKEN', discord: 'DISCORD_BOT_TOKEN' };
|
|
13
|
+
const stationFor = (p) => p === 'telegram' ? new TelegramStation() : new DiscordStation();
|
|
13
14
|
const maskToken = (t) => !t ? '' : t.length <= 8 ? '••••' : `${t.slice(0, 6)}…${t.slice(-2)}`;
|
|
14
15
|
/** Apply token across CONFIG_ENV_FILE (always set/cleared) AND cwd/.env (only if it exists). */
|
|
15
16
|
function applyToken(key, value) {
|
|
@@ -62,7 +63,7 @@ export async function cmdSetup(p, f) {
|
|
|
62
63
|
if (!f['no-validate']) {
|
|
63
64
|
process.env[TOKEN_KEYS[sub]] = trimmed;
|
|
64
65
|
try {
|
|
65
|
-
const me = await (sub
|
|
66
|
+
const me = await stationFor(sub).getMe();
|
|
66
67
|
identity = sub === 'telegram' ? `@${me.username}` : me.username;
|
|
67
68
|
}
|
|
68
69
|
catch (err) {
|
|
@@ -103,26 +104,26 @@ function tokenSource(key) {
|
|
|
103
104
|
export async function cmdDoctor(_, f) {
|
|
104
105
|
loadMetroEnv();
|
|
105
106
|
const cfg = configuredPlatforms();
|
|
106
|
-
const
|
|
107
|
-
|
|
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
|
-
}];
|
|
107
|
+
const checks = [];
|
|
108
|
+
const sources = [];
|
|
113
109
|
for (const p of ['telegram', 'discord']) {
|
|
114
110
|
if (!cfg[p]) {
|
|
115
111
|
checks.push({ name: p, ok: null, detail: 'not configured' });
|
|
116
112
|
continue;
|
|
117
113
|
}
|
|
114
|
+
sources.push(`${p}←${tokenSource(TOKEN_KEYS[p])}`);
|
|
118
115
|
try {
|
|
119
|
-
const me = await (p
|
|
116
|
+
const me = await stationFor(p).getMe();
|
|
120
117
|
checks.push({ name: p, ok: true, detail: `getMe → ${p === 'telegram' ? '@' : ''}${me.username}` });
|
|
121
118
|
}
|
|
122
119
|
catch (err) {
|
|
123
120
|
checks.push({ name: p, ok: false, detail: errMsg(err) });
|
|
124
121
|
}
|
|
125
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
|
+
});
|
|
126
127
|
const lockFile = join(STATE_DIR, '.tail-lock');
|
|
127
128
|
if (!existsSync(lockFile))
|
|
128
129
|
checks.push({ name: 'dispatcher', ok: null, detail: 'not running' });
|
package/dist/cli/index.js
CHANGED
|
@@ -4,10 +4,12 @@ import pkg from '../../package.json' with { type: 'json' };
|
|
|
4
4
|
import { errMsg } from '../log.js';
|
|
5
5
|
import { listLines } from '../cache.js';
|
|
6
6
|
import { fmtCapabilities, listStations } from '../stations/index.js';
|
|
7
|
+
import { listAgents } from '../registry.js';
|
|
7
8
|
import { loadMetroEnv } from '../paths.js';
|
|
8
9
|
import { readHistory } from '../history.js';
|
|
9
10
|
import { cmdDoctor, cmdSetup, cmdUpdate } from './config.js';
|
|
10
|
-
import { cmdDownload, cmdEdit, cmdFetch,
|
|
11
|
+
import { cmdDownload, cmdEdit, cmdFetch, cmdReact, cmdReply, cmdSend, } from './actions.js';
|
|
12
|
+
import { cmdTunnel, cmdWebhook } from './webhook.js';
|
|
11
13
|
import { flagOne, isJson, parseArgs, writeJson, } from './util.js';
|
|
12
14
|
const USAGE = `metro — Telegram + Discord stream for your Claude Code / Codex agent
|
|
13
15
|
|
|
@@ -29,9 +31,12 @@ Usage:
|
|
|
29
31
|
metro download <line> <message_id> [--out=<dir>]
|
|
30
32
|
Download image attachments to disk.
|
|
31
33
|
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
34
|
metro history [--limit=N] [--line=…] [--station=…] [--kind=…] [--from=…] [--text=…] [--since=…]
|
|
34
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.
|
|
35
40
|
metro update Upgrade in place.
|
|
36
41
|
metro --version | --help
|
|
37
42
|
|
|
@@ -42,12 +47,23 @@ Exit codes: 0 success · 1 usage · 2 config · 3 upstream
|
|
|
42
47
|
async function cmdStations(_, f) {
|
|
43
48
|
loadMetroEnv();
|
|
44
49
|
const rows = listStations();
|
|
50
|
+
const agentsByStation = {
|
|
51
|
+
claude: listAgents('claude'),
|
|
52
|
+
codex: listAgents('codex'),
|
|
53
|
+
};
|
|
45
54
|
if (isJson(f))
|
|
46
|
-
return writeJson({ stations: rows });
|
|
55
|
+
return writeJson({ stations: rows, agents: agentsByStation });
|
|
47
56
|
process.stdout.write('metro stations\n\n');
|
|
48
57
|
for (const s of rows) {
|
|
49
58
|
const mark = s.configured === true ? '✓' : s.configured === false ? '✗' : '·';
|
|
50
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
|
+
}
|
|
51
67
|
}
|
|
52
68
|
process.stdout.write('\n');
|
|
53
69
|
}
|
|
@@ -58,10 +74,8 @@ async function cmdLines(_, f) {
|
|
|
58
74
|
.sort((a, b) => (b.lastSeenAt ?? '').localeCompare(a.lastSeenAt ?? ''));
|
|
59
75
|
if (isJson(f))
|
|
60
76
|
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
|
-
}
|
|
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');
|
|
65
79
|
const widest = Math.max(...rows.map(r => r.line.length));
|
|
66
80
|
process.stdout.write('metro lines\n\n');
|
|
67
81
|
for (const r of rows) {
|
|
@@ -128,7 +142,8 @@ const pad = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s.padEnd(n));
|
|
|
128
142
|
const COMMANDS = {
|
|
129
143
|
setup: cmdSetup, doctor: cmdDoctor, stations: cmdStations, lines: cmdLines,
|
|
130
144
|
send: cmdSend, reply: cmdReply, edit: cmdEdit, react: cmdReact,
|
|
131
|
-
download: cmdDownload, fetch: cmdFetch,
|
|
145
|
+
download: cmdDownload, fetch: cmdFetch,
|
|
146
|
+
webhook: cmdWebhook, tunnel: cmdTunnel,
|
|
132
147
|
history: cmdHistory, update: cmdUpdate,
|
|
133
148
|
};
|
|
134
149
|
async function main() {
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** CLI subcommands: `metro webhook add|list|remove` + `metro tunnel setup`. */
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { addEndpoint, listEndpoints, removeEndpoint } from '../webhooks.js';
|
|
4
|
+
import { loadTunnelConfig, saveTunnelConfig } from '../tunnel.js';
|
|
5
|
+
import { emit, exitErr, flagOne, isJson, need, writeJson } from './util.js';
|
|
6
|
+
const DEFAULT_PORT = 8420;
|
|
7
|
+
const port = () => Number(process.env.METRO_WEBHOOK_PORT) || DEFAULT_PORT;
|
|
8
|
+
function urlFor(endpointId) {
|
|
9
|
+
const t = loadTunnelConfig();
|
|
10
|
+
return t ? `https://${t.hostname}/wh/${endpointId}` : `http://127.0.0.1:${port()}/wh/${endpointId}`;
|
|
11
|
+
}
|
|
12
|
+
export async function cmdWebhook(p, f) {
|
|
13
|
+
const sub = p[0];
|
|
14
|
+
if (sub === 'add')
|
|
15
|
+
return cmdWebhookAdd(p.slice(1), f);
|
|
16
|
+
if (sub === 'list' || sub === undefined)
|
|
17
|
+
return cmdWebhookList(f);
|
|
18
|
+
if (sub === 'remove' || sub === 'rm')
|
|
19
|
+
return cmdWebhookRemove(p.slice(1), f);
|
|
20
|
+
throw exitErr('usage: metro webhook [add <label> [--secret=…] | list | remove <id>]', 1);
|
|
21
|
+
}
|
|
22
|
+
async function cmdWebhookAdd(p, f) {
|
|
23
|
+
need(p, 1, 'metro webhook add <label> [--secret=<shared-secret>]');
|
|
24
|
+
const ep = addEndpoint(p[0], flagOne(f, 'secret'));
|
|
25
|
+
const url = urlFor(ep.id);
|
|
26
|
+
emit(f, `webhook ${ep.id} (${ep.label}) → ${url}${ep.secret ? `\nshared secret: ${ep.secret}` : ''}`, { ok: true, endpoint: ep, url });
|
|
27
|
+
}
|
|
28
|
+
async function cmdWebhookList(f) {
|
|
29
|
+
const eps = listEndpoints().map(ep => ({ ...ep, url: urlFor(ep.id) }));
|
|
30
|
+
if (isJson(f))
|
|
31
|
+
return writeJson({ endpoints: eps });
|
|
32
|
+
if (!eps.length)
|
|
33
|
+
return void process.stdout.write('metro webhooks\n\n (none — run `metro webhook add <label>`)\n\n');
|
|
34
|
+
process.stdout.write('metro webhooks\n\n');
|
|
35
|
+
for (const ep of eps) {
|
|
36
|
+
process.stdout.write(` ${ep.id} ${ep.label}${ep.secret ? ' (signed)' : ''}\n ${ep.url}\n`);
|
|
37
|
+
}
|
|
38
|
+
process.stdout.write('\n');
|
|
39
|
+
}
|
|
40
|
+
async function cmdWebhookRemove(p, f) {
|
|
41
|
+
need(p, 1, 'metro webhook remove <id>');
|
|
42
|
+
const ok = removeEndpoint(p[0]);
|
|
43
|
+
if (!ok)
|
|
44
|
+
throw exitErr(`no webhook with id "${p[0]}"`, 1);
|
|
45
|
+
emit(f, `removed webhook ${p[0]}`, { ok: true, id: p[0] });
|
|
46
|
+
}
|
|
47
|
+
export async function cmdTunnel(p, f) {
|
|
48
|
+
const sub = p[0];
|
|
49
|
+
if (sub === 'setup')
|
|
50
|
+
return cmdTunnelSetup(p.slice(1), f);
|
|
51
|
+
if (sub === 'status' || sub === undefined)
|
|
52
|
+
return cmdTunnelStatus(f);
|
|
53
|
+
throw exitErr('usage: metro tunnel [setup <name> <hostname> | status]', 1);
|
|
54
|
+
}
|
|
55
|
+
async function cmdTunnelSetup(p, f) {
|
|
56
|
+
need(p, 2, 'metro tunnel setup <tunnel-name> <hostname> (e.g. `metro tunnel setup metro webhook.example.com`)');
|
|
57
|
+
const [name, hostname] = p;
|
|
58
|
+
if (!hasCloudflared()) {
|
|
59
|
+
throw exitErr('cloudflared not on PATH — install with `brew install cloudflared` (or see https://developers.cloudflare.com/cloudflared/)', 2);
|
|
60
|
+
}
|
|
61
|
+
/** Idempotent: if tunnel exists, `tunnel create` errors with "already exists" — that's fine, continue. */
|
|
62
|
+
run('cloudflared', ['tunnel', 'create', name], { allowFail: true });
|
|
63
|
+
/** DNS route is also idempotent in newer cloudflared; older versions error if the CNAME exists. Same handling. */
|
|
64
|
+
run('cloudflared', ['tunnel', 'route', 'dns', name, hostname], { allowFail: true });
|
|
65
|
+
saveTunnelConfig({ name, hostname });
|
|
66
|
+
emit(f, `tunnel saved: ${name} → ${hostname}\n` +
|
|
67
|
+
'first run: `cloudflared tunnel login` if you haven\'t (browser OAuth).\n' +
|
|
68
|
+
'then start metro — the daemon will spawn `cloudflared tunnel run` for you.', { ok: true, name, hostname });
|
|
69
|
+
}
|
|
70
|
+
async function cmdTunnelStatus(f) {
|
|
71
|
+
const cfg = loadTunnelConfig();
|
|
72
|
+
if (isJson(f))
|
|
73
|
+
return writeJson({ configured: !!cfg, tunnel: cfg });
|
|
74
|
+
if (!cfg)
|
|
75
|
+
return void process.stdout.write('metro tunnel\n\n (not configured — run `metro tunnel setup <name> <hostname>`)\n\n');
|
|
76
|
+
process.stdout.write(`metro tunnel\n\n name: ${cfg.name}\n hostname: ${cfg.hostname}\n\n`);
|
|
77
|
+
}
|
|
78
|
+
const hasCloudflared = () => spawnSync('cloudflared', ['--version'], { stdio: 'ignore' }).status === 0;
|
|
79
|
+
function run(cmd, args, opts = {}) {
|
|
80
|
+
const r = spawnSync(cmd, args, { stdio: 'inherit' });
|
|
81
|
+
if (r.status !== 0 && !opts.allowFail)
|
|
82
|
+
throw exitErr(`${cmd} ${args.join(' ')} exited ${r.status}`, 2);
|
|
83
|
+
}
|
package/dist/codex-rc.js
CHANGED
|
@@ -32,6 +32,7 @@ export class CodexRC {
|
|
|
32
32
|
nextId = 1;
|
|
33
33
|
pending = new Map();
|
|
34
34
|
threadId = null;
|
|
35
|
+
threadListener = null;
|
|
35
36
|
queue = [];
|
|
36
37
|
connected = false;
|
|
37
38
|
connecting = false;
|
|
@@ -45,6 +46,14 @@ export class CodexRC {
|
|
|
45
46
|
this.endpoint = parseUrl(url);
|
|
46
47
|
}
|
|
47
48
|
start() { void this.connect(); }
|
|
49
|
+
getThreadId() { return this.threadId; }
|
|
50
|
+
onThread(listener) { this.threadListener = listener; }
|
|
51
|
+
setThreadId(id) {
|
|
52
|
+
if (this.threadId === id)
|
|
53
|
+
return;
|
|
54
|
+
this.threadId = id;
|
|
55
|
+
this.threadListener?.(id);
|
|
56
|
+
}
|
|
48
57
|
stop() {
|
|
49
58
|
this.closed = true;
|
|
50
59
|
this.clearTurnTimeout();
|
|
@@ -75,7 +84,7 @@ export class CodexRC {
|
|
|
75
84
|
ws.on('close', () => this.onClose());
|
|
76
85
|
const clientInfo = { name: 'metro', version: this.clientVersion, title: null };
|
|
77
86
|
await this.call('initialize', { clientInfo });
|
|
78
|
-
this.
|
|
87
|
+
this.setThreadId(await this.pickOrCreateThread());
|
|
79
88
|
this.connected = true;
|
|
80
89
|
log.info({ url: this.url, thread: this.threadId ?? '(none yet)' }, 'codex-rc connected');
|
|
81
90
|
void this.drainQueue();
|
|
@@ -110,7 +119,7 @@ export class CodexRC {
|
|
|
110
119
|
case 'thread/started': {
|
|
111
120
|
const id = msg.params?.thread?.id;
|
|
112
121
|
if (id) {
|
|
113
|
-
this.
|
|
122
|
+
this.setThreadId(id);
|
|
114
123
|
log.info({ thread: id }, 'codex-rc thread started');
|
|
115
124
|
void this.drainQueue();
|
|
116
125
|
}
|
|
@@ -142,7 +151,7 @@ export class CodexRC {
|
|
|
142
151
|
case 'thread/closed':
|
|
143
152
|
case 'thread/archived':
|
|
144
153
|
log.warn({ method: msg.method }, 'codex-rc thread closed/archived');
|
|
145
|
-
this.
|
|
154
|
+
this.setThreadId(null);
|
|
146
155
|
break;
|
|
147
156
|
}
|
|
148
157
|
}
|
|
@@ -186,7 +195,7 @@ export class CodexRC {
|
|
|
186
195
|
if (!this.connected || this.turnInFlight || !this.queue.length)
|
|
187
196
|
return;
|
|
188
197
|
if (!this.threadId) {
|
|
189
|
-
this.
|
|
198
|
+
this.setThreadId(await this.pickOrCreateThread());
|
|
190
199
|
if (!this.threadId)
|
|
191
200
|
return;
|
|
192
201
|
}
|
|
@@ -204,7 +213,7 @@ export class CodexRC {
|
|
|
204
213
|
this.clearTurnTimeout();
|
|
205
214
|
this.turnInFlight = false;
|
|
206
215
|
if (dead)
|
|
207
|
-
this.
|
|
216
|
+
this.setThreadId(null);
|
|
208
217
|
setTimeout(() => void this.drainQueue(), 1_000);
|
|
209
218
|
}
|
|
210
219
|
}
|