@stage-labs/metro 0.1.0-beta.116 → 0.1.0-beta.118

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stage-labs/metro",
3
- "version": "0.1.0-beta.116",
3
+ "version": "0.1.0-beta.118",
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.116",
3
+ "version": "0.1.0-beta.118",
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",
@@ -20,6 +20,8 @@ const ORCHESTRATION = new Set([
20
20
  'TaskUpdate',
21
21
  ]);
22
22
  const IMAGE = /\.(png|jpe?g|gif|webp|bmp)$/i;
23
+ const MCP = /^mcp__/;
24
+ const METRO_MCP = /^mcp__metro__/;
23
25
 
24
26
  function deny(reason) {
25
27
  process.stdout.write(
@@ -35,7 +37,10 @@ function verdict(payload) {
35
37
  if (typeof payload.agent_id === 'string' && payload.agent_id !== '') return null;
36
38
  if (tool === 'Agent' && input.run_in_background === false)
37
39
  return 'A foreground subagent blinds the main thread: it cannot see or acknowledge inbound metro messages until the agent finishes. Re-issue the identical Agent call with run_in_background: true, then wait for the task notification.';
38
- if (ORCHESTRATION.has(tool) || tool.startsWith('mcp__')) return null;
40
+ if (ORCHESTRATION.has(tool)) return null;
41
+ if (METRO_MCP.test(tool)) return null;
42
+ if (MCP.test(tool))
43
+ return `A connector call is work, not orchestration: ${tool} reads somebody's files, mail or records, and its answer can be long enough to crowd out the chat you are here to follow. Only metro's own tools run on this thread. Delegate it to a subagent with the Agent tool (run_in_background: true; the worker reaches every connector) and relay what it finds.`;
39
44
  if (tool === 'Read' && typeof input.file_path === 'string' && IMAGE.test(input.file_path)) return null;
40
45
  return `The main thread is orchestrator-only, so ${tool === '' ? 'this tool' : tool} is not available here. Delegate the work to a subagent with the Agent tool (run_in_background: true; the worker agent has full tool access) or to a Workflow, and report the result over metro.`;
41
46
  }
@@ -7,7 +7,7 @@ You are the main thread of a Claude Code session that is connected to chat throu
7
7
 
8
8
  **Inbound.** A message arrives as a `<channel source="metro" …>` block. Read `addressed` first: `direct`, `mention` or `reply` means it is for you; without it the message merely happened in a room you watch, so treat it as context and stay silent unless the person plainly wants you. For a message that is for you, the first tool call is `react` on it (👀, then 👍 or ✅ once done) so the person knows you saw it, and any reply goes on the same `line`, passed verbatim.
9
9
 
10
- **Delegate everything that is work.** Reading files, running commands, searching, fetching pages, editing: hand it to a subagent with the `Agent` tool, `subagent_type: "worker"`, always `run_in_background: true`, then keep answering chat while it runs and relay the result when the task notification arrives. A foreground subagent blinds you to chat and the guard refuses it. You may read image files yourself, so a screenshot someone sends is yours to look at.
10
+ **Delegate everything that is work.** Reading files, running commands, searching, fetching pages, editing, and every connector tool: hand it to a subagent with the `Agent` tool, `subagent_type: "worker"`, always `run_in_background: true`, then keep answering chat while it runs and relay the result when the task notification arrives. A foreground subagent blinds you to chat and the guard refuses it. You may read image files yourself, so a screenshot someone sends is yours to look at.
11
11
 
12
12
  **Never wait on the terminal.** `AskUserQuestion`, plan mode and anything that blocks for a person at the keyboard are denied everywhere, main thread and subagents alike. When something is ambiguous, do what does not depend on it, choose the most reasonable reading, say so in your reply, and if a real decision is needed ask over chat with `send` and carry on. Tool-approval prompts reach the chat too; the person answers `yes <id>` or `no <id>` there.
13
13
 
@@ -33,9 +33,17 @@ export interface RestoredAgent {
33
33
  connectors: number;
34
34
  }
35
35
 
36
+ export type ImportMode = 'append' | 'overwrite';
37
+
36
38
  export interface BundleApiDeps {
37
39
  bundle: (subject: string, agentId: string) => Promise<AgentBundle>;
38
- restore: (subject: string, bundle: AgentBundle) => Promise<RestoredAgent>;
40
+ restore: (subject: string, bundle: AgentBundle, mode: ImportMode) => Promise<RestoredAgent>;
41
+ }
42
+
43
+ export function parseMode(raw: unknown): ImportMode {
44
+ const mode = isRecord(raw) && typeof raw.mode === 'string' ? raw.mode : 'overwrite';
45
+ if (mode !== 'append' && mode !== 'overwrite') throw bad("mode is 'append' or 'overwrite'");
46
+ return mode;
39
47
  }
40
48
 
41
49
  const bad = (what: string): ApiError => new ApiError(`bundle: ${what}`, 400);
@@ -73,7 +81,10 @@ export function parseBundle(raw: unknown): AgentBundle {
73
81
  }
74
82
 
75
83
  async function answer(req: IncomingMessage, deps: BundleApiDeps, subject: string, path: string): Promise<unknown> {
76
- if (path === RESTORE_PATH) return deps.restore(subject, parseBundle(await readJsonBody(req, BUNDLE_MAX)));
84
+ if (path === RESTORE_PATH) {
85
+ const body: unknown = await readJsonBody(req, BUNDLE_MAX);
86
+ return deps.restore(subject, parseBundle(body), parseMode(body));
87
+ }
77
88
  const id = parseId(path.slice(AGENTS.length + 1).split('/')[0] ?? '');
78
89
  if (id === null) throw new ApiError('no such agent', 404);
79
90
  return deps.bundle(subject, id);
@@ -206,15 +206,18 @@ function importTarget(dir: string, agent: LoadedAgent & { key: string }): Import
206
206
  return { path: same?.path ?? fresh, previous: same?.file };
207
207
  }
208
208
 
209
+ export type ImportMode = 'append' | 'overwrite';
210
+
209
211
  export async function localImportAgent(
210
212
  subject: string,
211
213
  agent: LoadedAgent,
212
214
  dir = agentsDir(),
215
+ mode: ImportMode = 'overwrite',
213
216
  ): Promise<{ id: string; name: string; key: string; stations: number }> {
214
217
  assertLocalOwner(subject, dir);
215
218
  assertImportable(agent);
216
219
  const { path, previous } = importTarget(dir, agent);
217
- const file = fileFor(agent, localOwner(dir), path, previous);
220
+ const file = fileFor(agent, localOwner(dir), path, previous, mode);
218
221
  ensureSecureDir(join(path, '..'));
219
222
  save({ path, file });
220
223
  if (previous !== undefined && previous.key !== agent.key) unregisterAgentKey(agent.id);
@@ -227,11 +230,17 @@ export async function localImportAgent(
227
230
  });
228
231
  }
229
232
 
230
- function mergedStations(agent: LoadedAgent, previous: AgentFile | undefined): AgentFile['stations'] {
231
- const fromMetro = agent.accounts.map((a) => ({ ...a, allowlist: a.allowlist ?? ['*'] }));
232
- const kept = (previous?.stations ?? []).filter(
233
- (s) => !fromMetro.some((m) => m.station === s.station && m.id === s.id),
234
- );
233
+ function mergedStations(
234
+ agent: LoadedAgent,
235
+ previous: AgentFile | undefined,
236
+ mode: ImportMode,
237
+ ): AgentFile['stations'] {
238
+ const before = previous?.stations ?? [];
239
+ const here = (station: string, id: string): boolean => before.some((s) => s.station === station && s.id === id);
240
+ const fromMetro = agent.accounts
241
+ .map((a) => ({ ...a, allowlist: a.allowlist ?? ['*'] }))
242
+ .filter((m) => mode === 'overwrite' || !here(m.station, m.id));
243
+ const kept = before.filter((s) => !fromMetro.some((m) => m.station === s.station && m.id === s.id));
235
244
  return [...fromMetro, ...kept];
236
245
  }
237
246
 
@@ -239,7 +248,8 @@ function fileFor(
239
248
  agent: LoadedAgent,
240
249
  owner: string | null,
241
250
  path: string,
242
- previous?: AgentFile,
251
+ previous: AgentFile | undefined,
252
+ mode: ImportMode,
243
253
  ): AgentFile {
244
254
  try {
245
255
  return parseAgentFile(
@@ -249,7 +259,7 @@ function fileFor(
249
259
  name: previous?.name ?? agent.name,
250
260
  key: agent.key,
251
261
  owner,
252
- stations: mergedStations(agent, previous),
262
+ stations: mergedStations(agent, previous, mode),
253
263
  connectors: previous?.connectors ?? [],
254
264
  }),
255
265
  path,
@@ -39,6 +39,7 @@ import {
39
39
  listMemory,
40
40
  readMemoryFile,
41
41
  readTranscript,
42
+ writeMemoryFile,
42
43
  } from './files.js';
43
44
 
44
45
  const PREFIX = '/api/claude';
@@ -94,12 +95,16 @@ const parts = (path: string): string[] => path.slice(PREFIX.length + 1).split('/
94
95
  const seenIn = (body: Record<string, unknown>): string | null | undefined =>
95
96
  'seenAt' in body ? (typeof body.seenAt === 'string' ? body.seenAt : null) : undefined;
96
97
 
97
- async function writeAnswer(req: IncomingMessage, path: string, dir: string): Promise<unknown> {
98
+ const WRITE_HEADS = new Set(['settings', 'skills', 'memory']);
99
+
100
+ async function writeAnswer(req: IncomingMessage, path: string, search: string, dir: string): Promise<unknown> {
98
101
  const [head = '', item = ''] = parts(path);
99
- if ((head !== 'settings' && head !== 'skills') || item === '') throw new ApiError('method not allowed', 405);
102
+ if (!WRITE_HEADS.has(head) || item === '') throw new ApiError('method not allowed', 405);
100
103
  const body = await readJsonBody(req, BODY_MAX);
101
104
  if (!isRecord(body) || typeof body.text !== 'string') throw new ApiError('text is required', 400);
102
105
  if (head === 'skills') return writeClaudeSkill(decodeURIComponent(item), body.text, seenIn(body), dir);
106
+ if (head === 'memory')
107
+ return writeMemoryFile(projectOf(new URLSearchParams(search)), decodeURIComponent(item), body.text, dir);
103
108
  return writeClaudeSettings(item, body.text, seenIn(body), dir);
104
109
  }
105
110
 
@@ -217,7 +222,7 @@ function routed(req: IncomingMessage, path: string, search: string, deps: Claude
217
222
  if (head === LOGIN) return loginAnswer(req, item, deps);
218
223
  const single = item === '' ? SINGLETONS[head] : undefined;
219
224
  if (single !== undefined) return single(req, deps);
220
- if (req.method === 'PUT') return writeAnswer(req, path, dir);
225
+ if (req.method === 'PUT') return writeAnswer(req, path, search, dir);
221
226
  if (req.method === 'POST') return created(req, path, dir);
222
227
  return answer(req.method ?? 'GET', path, new URLSearchParams(search), dir);
223
228
  }
@@ -2,11 +2,14 @@ import {
2
2
  closeSync,
3
3
  createReadStream,
4
4
  existsSync,
5
+ mkdirSync,
5
6
  openSync,
6
7
  readdirSync,
7
8
  readSync,
9
+ renameSync,
8
10
  rmSync,
9
11
  statSync,
12
+ writeFileSync,
10
13
  } from 'node:fs';
11
14
  import { homedir } from 'node:os';
12
15
  import { join } from 'node:path';
@@ -22,6 +25,8 @@ const TEXT_CAP = 20_000;
22
25
  const RESULT_CAP = 8_000;
23
26
  const INPUT_CAP = 4_000;
24
27
  const FILE_CAP = 1_000_000;
28
+ const MEMORY_MAX = 256 * 1024;
29
+ const MEMORY_MODE = 0o644;
25
30
  const NOISE = ['<task-notification>', '<system-reminder>', '<local-command', '<command-name>'];
26
31
 
27
32
  export function claudeDir(): string {
@@ -322,6 +327,21 @@ export function listMemory(project: string, dir = claudeDir()): MemoryListing {
322
327
  return { files, index: existsSync(index) ? readCapped(index) : null };
323
328
  }
324
329
 
330
+ export function writeMemoryFile(project: string, name: string, text: string, dir = claudeDir()): MemoryFile {
331
+ if (text.trim() === '') throw new ApiError('a memory file cannot be empty', 400);
332
+ if (Buffer.byteLength(text, 'utf8') > MEMORY_MAX)
333
+ throw new ApiError(`a memory file is at most ${String(MEMORY_MAX)} bytes`, 400);
334
+ const folder = memoryDir(project, dir);
335
+ const file = safeName(name, MEMORY_RE, 'memory file name');
336
+ mkdirSync(folder, { recursive: true });
337
+ const path = join(folder, file);
338
+ const tmp = `${path}.metro-${String(process.pid)}`;
339
+ writeFileSync(tmp, text, { mode: MEMORY_MODE });
340
+ renameSync(tmp, path);
341
+ const stat = statSync(path);
342
+ return { name: file, bytes: stat.size, modifiedAt: stat.mtime.toISOString() };
343
+ }
344
+
325
345
  export function readMemoryFile(project: string, name: string, dir = claudeDir()): string {
326
346
  const path = join(memoryDir(project, dir), safeName(name, MEMORY_RE, 'memory file name'));
327
347
  if (!existsSync(path)) throw new ApiError('no such memory file', 404);
@@ -104,14 +104,22 @@ async function oauthCapable(url: URL, auth: ConnectorAuth): Promise<boolean> {
104
104
  return advertisesOAuth(url);
105
105
  }
106
106
 
107
- export function localImportConnectors(rows: LoadedConnector[], dir = agentsDir()): number {
107
+ export function localImportConnectors(
108
+ rows: LoadedConnector[],
109
+ dir = agentsDir(),
110
+ mode: 'append' | 'overwrite' = 'overwrite',
111
+ ): number {
108
112
  const current = readLocalConnectors(dir);
109
- for (const row of rows) {
113
+ const fresh =
114
+ mode === 'overwrite'
115
+ ? rows
116
+ : rows.filter((row) => !current.some((r) => r.id === row.id || r.name === row.name));
117
+ for (const row of fresh) {
110
118
  const other = current.find((r) => r.id !== row.id && r.name === row.name);
111
119
  if (other !== undefined)
112
120
  throw new ConnectorError(`a connector named '${row.name}' already exists on this daemon; rename it first`, 409);
113
121
  }
114
- const imported: LocalConnectorRow[] = rows.map((row) => ({
122
+ const imported: LocalConnectorRow[] = fresh.map((row) => ({
115
123
  id: row.id,
116
124
  name: row.name,
117
125
  url: row.url,
@@ -9,6 +9,7 @@ export interface OpenRouterModel {
9
9
  name: string;
10
10
  prompt: number | null;
11
11
  completion: number | null;
12
+ created: number | null;
12
13
  }
13
14
 
14
15
  const str = (value: unknown): string => (typeof value === 'string' ? value : '');
@@ -18,12 +19,27 @@ function price(raw: unknown): number | null {
18
19
  return Number.isFinite(value) && value >= 0 ? value : null;
19
20
  }
20
21
 
22
+ function released(raw: unknown): number | null {
23
+ return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : null;
24
+ }
25
+
21
26
  function modelOf(entry: unknown): OpenRouterModel | null {
22
27
  if (!isRecord(entry)) return null;
23
28
  const id = str(entry.id);
24
29
  if (id === '') return null;
25
30
  const pricing = isRecord(entry.pricing) ? entry.pricing : {};
26
- return { id, name: str(entry.name) || id, prompt: price(pricing.prompt), completion: price(pricing.completion) };
31
+ return {
32
+ id,
33
+ name: str(entry.name) || id,
34
+ prompt: price(pricing.prompt),
35
+ completion: price(pricing.completion),
36
+ created: released(entry.created),
37
+ };
38
+ }
39
+
40
+ export function newestFirst(a: OpenRouterModel, b: OpenRouterModel): number {
41
+ const when = (b.created ?? 0) - (a.created ?? 0);
42
+ return when !== 0 ? when : a.id.localeCompare(b.id);
27
43
  }
28
44
 
29
45
  export async function openrouterModels(base = OPENROUTER_BASE, fetchImpl: typeof fetch = fetch): Promise<OpenRouterModel[]> {
@@ -35,8 +51,8 @@ export async function openrouterModels(base = OPENROUTER_BASE, fetchImpl: typeof
35
51
  return data
36
52
  .map(modelOf)
37
53
  .filter((model): model is OpenRouterModel => model !== null)
38
- .slice(0, MODELS_MAX)
39
- .sort((a, b) => a.id.localeCompare(b.id));
54
+ .sort(newestFirst)
55
+ .slice(0, MODELS_MAX);
40
56
  }
41
57
 
42
58
  export async function openrouterZdrModels(base = OPENROUTER_BASE, fetchImpl: typeof fetch = fetch): Promise<string[]> {
@@ -164,10 +164,10 @@ function bundleApi(deps: LocalModeDeps): BundleApiDeps {
164
164
  if (bundle.agent.key === '') throw new ApiError(`agent '${agent.name}' has no key to bundle`, 400);
165
165
  return bundle;
166
166
  },
167
- restore: async (subject, bundle) => {
167
+ restore: async (subject, bundle, mode) => {
168
168
  assertLocalOwner(subject);
169
- const made = await localImportAgent(subject, loadedAgentOf(bundle));
170
- const connectors = localImportConnectors(bundle.connectors);
169
+ const made = await localImportAgent(subject, loadedAgentOf(bundle), undefined, mode);
170
+ const connectors = localImportConnectors(bundle.connectors, undefined, mode);
171
171
  for (const station of new Set(bundle.agent.stations.map((a) => a.station)))
172
172
  await deps.syncStations(station).catch((err: unknown) => {
173
173
  log.warn({ station, err: errMsg(err) }, 'restore: station reload failed, the change lands at the next boot');
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.116"
2
+ "version": "0.1.0-beta.118"
3
3
  }