@stage-labs/metro 0.1.0-beta.105 → 0.1.0-beta.107

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/dist/claude.js CHANGED
@@ -6,10 +6,12 @@ import { localAgents, pickLocalAgent } from './local.js';
6
6
  import { PROVIDER_FLAGS } from './provider-flags.js';
7
7
  import { localPort, localUrl } from './runtime.js';
8
8
  const CHANNEL_FLAGS = ['--dangerously-load-development-channels', 'server:metro'];
9
+ const PERMISSION_FLAGS = ['--permission-mode', 'auto'];
9
10
  const KEY_HEADER = 'x-metro-key';
10
11
  const PROBE_MS = 3_000;
11
12
  export const claudeArgs = (extra, mcpConfig) => [
12
13
  ...CHANNEL_FLAGS,
14
+ ...PERMISSION_FLAGS,
13
15
  ...(mcpConfig === undefined ? [] : ['--mcp-config', mcpConfig]),
14
16
  ...extra,
15
17
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stage-labs/metro",
3
- "version": "0.1.0-beta.105",
3
+ "version": "0.1.0-beta.107",
4
4
  "description": "The metro command line. Sign in once per machine, then hand your MCP connector list to Claude Code without the credentials touching disk, argv or shell history.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metro",
3
- "version": "0.1.0-beta.105",
3
+ "version": "0.1.0-beta.107",
4
4
  "description": "Metro for Claude Code, installed by the metro daemon on this machine: every connector the agent holds as its own MCP server relayed through the daemon, the orchestrator-only guard on the main thread, the standing rules loaded at each session start, and a refresh skill for when the daemon could not keep the server list current. No vendor credential ever sits in a config file.",
5
5
  "author": {
6
6
  "name": "Bonustrack",
@@ -4,6 +4,7 @@ import { join } from 'node:path';
4
4
  import { errMsg, log } from '@metro-labs/core/log';
5
5
  import { isRecord } from '@metro-labs/core/is-record';
6
6
  import { readJson, writeJson } from '@metro-labs/core/secure-fs';
7
+ import { METRO_VERSION } from '@metro-labs/core/version';
7
8
  import { agentsDir, listAgentFiles } from '../agents/files.js';
8
9
  import { notReady, readModelConfig } from '../gateway/model-config.js';
9
10
  import { claudeAccount, claudeInstalled } from './login.js';
@@ -26,6 +27,7 @@ export interface SessionDeps {
26
27
  agents?: string;
27
28
  signedIn?: () => boolean;
28
29
  now?: () => number;
30
+ version?: string;
29
31
  }
30
32
 
31
33
  export interface SessionStatus {
@@ -48,13 +50,24 @@ const memory: Memory = { lastStartedAt: null, lastError: null, strikes: 0, pause
48
50
 
49
51
  const statePath = (agents: string): string => join(agents, STATE_FILE);
50
52
 
51
- export function autostartEnabled(agents = agentsDir()): boolean {
53
+ function readState(agents: string): Record<string, unknown> {
52
54
  const raw = readJson<unknown>(statePath(agents), null);
53
- return !isRecord(raw) || raw.autostart !== false;
55
+ return isRecord(raw) ? raw : {};
54
56
  }
55
57
 
58
+ const writeState = (agents: string, patch: Record<string, unknown>): void => {
59
+ writeJson(statePath(agents), { ...readState(agents), ...patch });
60
+ };
61
+
62
+ export const autostartEnabled = (agents = agentsDir()): boolean => readState(agents).autostart !== false;
63
+
56
64
  export function setAutostart(enabled: boolean, agents = agentsDir()): void {
57
- writeJson(statePath(agents), { autostart: enabled });
65
+ writeState(agents, { autostart: enabled });
66
+ }
67
+
68
+ export function startedVersion(agents = agentsDir()): string | null {
69
+ const version = readState(agents).version;
70
+ return typeof version === 'string' ? version : null;
58
71
  }
59
72
 
60
73
  function tmuxOk(tmux: string, args: string[]): boolean {
@@ -108,6 +121,18 @@ function confirmChannels(tmux: string, until: number): void {
108
121
  setTimeout(tick, CONFIRM_POLL_MS).unref();
109
122
  }
110
123
 
124
+ function recordStart(deps: SessionDeps, tmux: string, now: number, run: { error?: Error; status: number | null; stderr: string }): void {
125
+ memory.lastStartedAt = now;
126
+ if (run.error !== undefined || run.status !== 0) {
127
+ memory.lastError = run.error === undefined ? `tmux new-session exited ${String(run.status)}: ${run.stderr.trim()}` : errMsg(run.error);
128
+ log.warn({ err: memory.lastError }, 'claude-session: tmux could not start');
129
+ return;
130
+ }
131
+ memory.lastError = null;
132
+ writeState(deps.agents ?? agentsDir(), { version: deps.version ?? METRO_VERSION });
133
+ confirmChannels(tmux, now + CONFIRM_WAIT_MS);
134
+ }
135
+
111
136
  export function startSession(deps: SessionDeps = {}): SessionStatus {
112
137
  const tmux = deps.tmux ?? 'tmux';
113
138
  const home = deps.home ?? homedir();
@@ -115,15 +140,8 @@ export function startSession(deps: SessionDeps = {}): SessionStatus {
115
140
  const trusted = trustFolder(home);
116
141
  const [command = 'metro', ...args] = metroCommand(deps);
117
142
  const run = spawnSync(tmux, ['new-session', '-d', '-s', SESSION_NAME, '-c', home, '-x', '200', '-y', '50', command, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], cwd: home });
118
- memory.lastStartedAt = now;
119
- if (run.error !== undefined || run.status !== 0) {
120
- memory.lastError = run.error === undefined ? `tmux new-session exited ${String(run.status)}: ${run.stderr.trim()}` : errMsg(run.error);
121
- log.warn({ err: memory.lastError }, 'claude-session: tmux could not start');
122
- } else {
123
- memory.lastError = null;
124
- log.info({ home, trusted, command: [command, ...args].join(' ') }, 'claude-session: started Claude Code in tmux');
125
- confirmChannels(tmux, now + CONFIRM_WAIT_MS);
126
- }
143
+ recordStart(deps, tmux, now, run);
144
+ if (memory.lastError === null) log.info({ home, trusted, command: [command, ...args].join(' ') }, 'claude-session: started Claude Code in tmux');
127
145
  return sessionStatus(deps);
128
146
  }
129
147
 
@@ -153,15 +171,46 @@ function strike(now: number): boolean {
153
171
  return true;
154
172
  }
155
173
 
156
- export function ensureSession(deps: SessionDeps = {}): 'started' | 'running' | 'blocked' | 'off' | 'paused' {
157
- const now = (deps.now ?? Date.now)();
158
- if (!autostartEnabled(deps.agents ?? agentsDir())) return 'off';
159
- if (sessionRunning(deps.tmux ?? 'tmux')) return 'running';
174
+ export type Ensured = 'started' | 'restarted' | 'running' | 'blocked' | 'off' | 'paused';
175
+
176
+ function holdsBack(deps: SessionDeps, now: number): Ensured | null {
160
177
  if (now < memory.pausedUntil) return 'paused';
161
178
  if (sessionBlocked(deps) !== null) return 'blocked';
162
- if (strike(now)) return 'paused';
179
+ return strike(now) ? 'paused' : null;
180
+ }
181
+
182
+ interface Resolved {
183
+ now: number;
184
+ agents: string;
185
+ version: string;
186
+ tmux: string;
187
+ }
188
+
189
+ const resolved = (deps: SessionDeps): Resolved => ({
190
+ now: (deps.now ?? Date.now)(),
191
+ agents: deps.agents ?? agentsDir(),
192
+ version: deps.version ?? METRO_VERSION,
193
+ tmux: deps.tmux ?? 'tmux',
194
+ });
195
+
196
+ function situation(r: Resolved): 'running' | 'stale' | 'absent' {
197
+ if (!sessionRunning(r.tmux)) return 'absent';
198
+ return startedVersion(r.agents) === r.version ? 'running' : 'stale';
199
+ }
200
+
201
+ export function ensureSession(deps: SessionDeps = {}): Ensured {
202
+ const r = resolved(deps);
203
+ if (!autostartEnabled(r.agents)) return 'off';
204
+ const found = situation(r);
205
+ if (found === 'running') return 'running';
206
+ const held = holdsBack(deps, r.now);
207
+ if (held !== null) return held;
208
+ if (found === 'stale') {
209
+ log.info({ was: startedVersion(r.agents), now: r.version }, 'claude-session: restarting the session an older metro started, so the new plugin and flags load');
210
+ stopSession(deps);
211
+ }
163
212
  startSession(deps);
164
- return 'started';
213
+ return found === 'stale' ? 'restarted' : 'started';
165
214
  }
166
215
 
167
216
  let watcher: ReturnType<typeof setInterval> | null = null;
@@ -171,7 +220,7 @@ export function watchSession(deps: SessionDeps = {}, everyMs = WATCH_MS): void {
171
220
  const tick = (): void => {
172
221
  try {
173
222
  const outcome = ensureSession(deps);
174
- if (outcome === 'started') log.info('claude-session: started');
223
+ if (outcome === 'started' || outcome === 'restarted') log.info({ outcome }, 'claude-session: Claude Code is up');
175
224
  } catch (err) {
176
225
  log.warn({ err: errMsg(err) }, 'claude-session: check failed');
177
226
  }
@@ -13,6 +13,7 @@ import { anthropicHeaders, forwardedHeaders, GatewayError, parseJson, pipeRespon
13
13
  import { notReady, readModelConfig, resolveRoute, routeLabel, setCodexAuth, writeModelConfig, type ModelConfig, type Route } from './model-config.js';
14
14
  import { codexCount, codexMessages, freshCodexState, type CodexDeps } from './codex.js';
15
15
  import { OPENROUTER_BASE } from './openrouter.js';
16
+ import { isRecord } from '@metro-labs/core/is-record';
16
17
  import { forgetServed, noteServed } from './served.js';
17
18
  import type { CodexTokens } from './codex-auth.js';
18
19
 
@@ -128,13 +129,19 @@ async function toOpenRouter(
128
129
  const upstream = await fetch(`${deps.openrouterBase ?? OPENROUTER_BASE}${MESSAGES}`, {
129
130
  method: 'POST',
130
131
  headers,
131
- body: JSON.stringify({ ...body, model: route.model }),
132
+ body: JSON.stringify(openrouterBody(body, route.model, cfg.openrouter.zdr)),
132
133
  signal: watch.signal,
133
134
  redirect: 'manual',
134
135
  });
135
136
  await pipeResponse(upstream, res, watch, { keepalive: true, ownCredential: true });
136
137
  }
137
138
 
139
+ export function openrouterBody(body: Record<string, unknown>, model: string, zdr: boolean): Record<string, unknown> {
140
+ if (!zdr) return { ...body, model };
141
+ const provider = isRecord(body.provider) ? body.provider : {};
142
+ return { ...body, model, provider: { ...provider, zdr: true } };
143
+ }
144
+
138
145
  async function dispatch(req: IncomingMessage, res: ServerResponse, path: string, deps: GatewayDeps): Promise<void> {
139
146
  const cfg = deps.config();
140
147
  const raw = await readBody(req);
@@ -6,7 +6,7 @@ import { log } from '@metro-labs/core/log';
6
6
  import { beginLogin, CodexAuthError, finishLogin, readCodexCliAuth } from './codex-auth.js';
7
7
  import { beginDeviceLogin, pollDeviceLogin } from './codex-device.js';
8
8
  import { codexModels, currentTokens, freshCodexState } from './codex.js';
9
- import { openrouterModels } from './openrouter.js';
9
+ import { openrouterModels, openrouterZdrModels } from './openrouter.js';
10
10
  import { lastServed } from './served.js';
11
11
  import type { CodexTokens } from './codex-auth.js';
12
12
  import { GatewayError } from './forward.js';
@@ -140,6 +140,10 @@ const OPENROUTER_ROUTES: Record<string, Route> = {
140
140
  method: 'GET',
141
141
  run: async (_req, deps) => ({ models: await openrouterModels(deps.openrouterBase, deps.fetchImpl).catch(asApiError) }),
142
142
  },
143
+ zdr: {
144
+ method: 'GET',
145
+ run: async (_req, deps) => ({ models: await openrouterZdrModels(deps.openrouterBase, deps.fetchImpl).catch(asApiError) }),
146
+ },
143
147
  };
144
148
 
145
149
  const named = (table: Record<string, Route>, name: string, method: string | undefined): Route | number => {
@@ -21,6 +21,7 @@ export interface BedrockSettings {
21
21
  export interface OpenRouterSettings {
22
22
  apiKey: string;
23
23
  model: string;
24
+ zdr: boolean;
24
25
  }
25
26
 
26
27
  export interface CodexSettings {
@@ -54,7 +55,7 @@ const empty = (): ModelConfig => ({
54
55
  provider: 'anthropic',
55
56
  anthropic: { apiKey: '', model: '' },
56
57
  bedrock: { region: '', apiKey: '', model: '' },
57
- openrouter: { apiKey: '', model: '' },
58
+ openrouter: { apiKey: '', model: '', zdr: false },
58
59
  codex: { model: '', auth: null },
59
60
  });
60
61
 
@@ -93,7 +94,7 @@ function fromDisk(raw: unknown): ModelConfig {
93
94
  provider: isProvider(raw.provider) ? raw.provider : 'anthropic',
94
95
  anthropic: { apiKey: text(anthropic.apiKey), model: text(anthropic.model) },
95
96
  bedrock: { region: text(bedrock.region), apiKey: text(bedrock.apiKey), model: text(bedrock.model) },
96
- openrouter: { apiKey: text(openrouter.apiKey), model: text(openrouter.model) },
97
+ openrouter: { apiKey: text(openrouter.apiKey), model: text(openrouter.model), zdr: openrouter.zdr === true },
97
98
  codex: { model: text(codex.model), auth: tokensFromDisk(codex.auth) },
98
99
  };
99
100
  }
@@ -106,6 +107,13 @@ export function writeModelConfig(cfg: ModelConfig, dir = agentsDir()): void {
106
107
  writeSecure(join(dir, MODEL_FILE), JSON.stringify(cfg, null, 2));
107
108
  }
108
109
 
110
+ function flag(patch: Record<string, unknown>, key: string, current: boolean, what: string): boolean {
111
+ if (!(key in patch)) return current;
112
+ const value = patch[key];
113
+ if (typeof value !== 'boolean') throw new ModelConfigError(`${what} must be true or false`);
114
+ return value;
115
+ }
116
+
109
117
  function field(patch: Record<string, unknown>, key: string, current: string, what: string): string {
110
118
  if (!(key in patch)) return current;
111
119
  const value = patch[key];
@@ -137,6 +145,7 @@ export function applyModelUpdate(cfg: ModelConfig, patch: unknown): ModelConfig
137
145
  openrouter: {
138
146
  apiKey: field(openrouter, 'apiKey', cfg.openrouter.apiKey, 'OpenRouter API key'),
139
147
  model: field(openrouter, 'model', cfg.openrouter.model, 'OpenRouter model'),
148
+ zdr: flag(openrouter, 'zdr', cfg.openrouter.zdr, 'OpenRouter zero data retention'),
140
149
  },
141
150
  codex: { model: field(codex, 'model', cfg.codex.model, 'Codex model'), auth: cfg.codex.auth },
142
151
  };
@@ -172,7 +181,7 @@ export function publicModelConfig(cfg: ModelConfig): Record<string, unknown> {
172
181
  reason: notReady(cfg),
173
182
  anthropic: { model: cfg.anthropic.model, hasKey: cfg.anthropic.apiKey !== '' },
174
183
  bedrock: { region: cfg.bedrock.region, model: cfg.bedrock.model, hasKey: cfg.bedrock.apiKey !== '' },
175
- openrouter: { model: cfg.openrouter.model, hasKey: cfg.openrouter.apiKey !== '' },
184
+ openrouter: { model: cfg.openrouter.model, hasKey: cfg.openrouter.apiKey !== '', zdr: cfg.openrouter.zdr },
176
185
  codex: { model: cfg.codex.model, signedIn: auth !== null, account: auth?.email ?? null, plan: auth?.plan ?? null },
177
186
  };
178
187
  }
@@ -38,3 +38,14 @@ export async function openrouterModels(base = OPENROUTER_BASE, fetchImpl: typeof
38
38
  .slice(0, MODELS_MAX)
39
39
  .sort((a, b) => a.id.localeCompare(b.id));
40
40
  }
41
+
42
+ export async function openrouterZdrModels(base = OPENROUTER_BASE, fetchImpl: typeof fetch = fetch): Promise<string[]> {
43
+ const res = await fetchImpl(`${base}/v1/endpoints/zdr`, { headers: { accept: 'application/json' }, redirect: 'manual' });
44
+ if (!res.ok) throw new GatewayError(res.status, 'api_error', `OpenRouter would not list its zero data retention endpoints (${String(res.status)})`);
45
+ const body: unknown = await res.json();
46
+ const data = typeof body === 'object' && body !== null ? (body as { data?: unknown }).data : undefined;
47
+ if (!Array.isArray(data)) throw new GatewayError(502, 'api_error', 'OpenRouter answered with no endpoint list');
48
+ const ids = new Set<string>();
49
+ for (const entry of data) if (isRecord(entry) && str(entry.model_id) !== '') ids.add(str(entry.model_id));
50
+ return [...ids].sort();
51
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.105"
2
+ "version": "0.1.0-beta.107"
3
3
  }