@stage-labs/metro 0.1.0-beta.125 → 0.1.0-beta.127

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.125",
3
+ "version": "0.1.0-beta.127",
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.125",
3
+ "version": "0.1.0-beta.127",
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",
@@ -32,7 +32,9 @@ import {
32
32
  type SessionDeps,
33
33
  } from './session.js';
34
34
  import { claudeVersion, updateClaude, type VersionDeps } from './version.js';
35
- import { readSessionFile, SESSION_FILE_MAX, writeSessionFile } from './session-files.js';
35
+ import { readSessionFile, receiveSessionFile, SESSION_FILE_MAX, sessionFilePath, writeSessionFile } from './session-files.js';
36
+ import { createReadStream } from 'node:fs';
37
+ import { pipeline } from 'node:stream/promises';
36
38
  import {
37
39
  claudeDir,
38
40
  deleteClaudeSession,
@@ -246,6 +248,27 @@ function routed(req: IncomingMessage, path: string, search: string, deps: Claude
246
248
  return answer(req.method ?? 'GET', path, new URLSearchParams(search), dir);
247
249
  }
248
250
 
251
+ const TEXT = 'text/plain; charset=utf-8';
252
+
253
+ async function streamed(req: IncomingMessage, res: ServerResponse, path: string, search: string, dir: string): Promise<boolean> {
254
+ const [head = '', item = ''] = parts(path);
255
+ if (head !== 'sessions' || item === '') return false;
256
+ const query = new URLSearchParams(search);
257
+ if (req.method === 'GET' && query.get('raw') === '1') {
258
+ const file = sessionFilePath(projectOf(query), item, dir);
259
+ res.writeHead(200, { 'content-type': TEXT, 'cache-control': 'no-store', ...cors(req) });
260
+ await pipeline(createReadStream(file), res).catch(() => {
261
+ res.destroy();
262
+ });
263
+ return true;
264
+ }
265
+ if (req.method === 'PUT' && !(req.headers['content-type'] ?? '').includes('json')) {
266
+ sendJson(req, res, 200, await receiveSessionFile(projectOf(query), item, req, dir));
267
+ return true;
268
+ }
269
+ return false;
270
+ }
271
+
249
272
  export function handleClaudeRequest(
250
273
  req: IncomingMessage,
251
274
  res: ServerResponse,
@@ -262,13 +285,11 @@ export function handleClaudeRequest(
262
285
  return true;
263
286
  }
264
287
  apiSession(req)
265
- .then((session) => {
288
+ .then(async (session) => {
266
289
  if (!session) throw new ApiError('unauthorized', 401);
267
290
  deps.authorize(session.subject);
268
- return routed(req, path, search, deps);
269
- })
270
- .then((body) => {
271
- sendJson(req, res, 200, body);
291
+ if (await streamed(req, res, path, search, (deps.dir ?? claudeDir)())) return;
292
+ sendJson(req, res, 200, await routed(req, path, search, deps));
272
293
  })
273
294
  .catch((err: unknown) => {
274
295
  if (err instanceof ApiError) apiFailure(req, res, err, 'claude-api');
@@ -1,10 +1,11 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
1
+ import { createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import type { Readable } from 'node:stream';
2
3
  import { join } from 'node:path';
3
4
  import { ApiError } from '@metro-labs/http/api-error';
4
5
  import { isRecord } from '@metro-labs/core/is-record';
5
6
  import { claudeDir, PROJECT_RE, safeName, SESSION_RE } from './files.js';
6
7
 
7
- export const SESSION_FILE_MAX = 64 * 1024 * 1024;
8
+ export const SESSION_FILE_MAX = 512 * 1024 * 1024;
8
9
  const FILE_MODE = 0o644;
9
10
 
10
11
  export interface SessionFile {
@@ -15,11 +16,56 @@ export interface SessionFile {
15
16
  const transcriptPath = (project: string, session: string, dir: string): string =>
16
17
  join(dir, 'projects', safeName(project, PROJECT_RE, 'Claude project id'), `${safeName(session, SESSION_RE, 'session id')}.jsonl`);
17
18
 
18
- export function readSessionFile(project: string, session: string, dir = claudeDir()): string {
19
+ export function sessionFilePath(project: string, session: string, dir = claudeDir()): string {
19
20
  const path = transcriptPath(project, session, dir);
20
21
  if (!existsSync(path)) throw new ApiError('no such session', 404);
21
22
  if (statSync(path).size > SESSION_FILE_MAX) throw new ApiError(`a session file is at most ${String(SESSION_FILE_MAX)} bytes`, 400);
22
- return readFileSync(path, 'utf8');
23
+ return path;
24
+ }
25
+
26
+ export function readSessionFile(project: string, session: string, dir = claudeDir()): string {
27
+ return readFileSync(sessionFilePath(project, session, dir), 'utf8');
28
+ }
29
+
30
+ const HEAD_BYTES = 64 * 1024;
31
+
32
+ async function spool(body: Readable, tmp: string): Promise<string> {
33
+ const out = createWriteStream(tmp, { mode: FILE_MODE });
34
+ const head: Buffer[] = [];
35
+ let total = 0;
36
+ let kept = 0;
37
+ for await (const chunk of body) {
38
+ const buf = chunk as Buffer;
39
+ total += buf.length;
40
+ if (total > SESSION_FILE_MAX) {
41
+ out.destroy();
42
+ rmSync(tmp, { force: true });
43
+ throw new ApiError(`a session file is at most ${String(SESSION_FILE_MAX)} bytes`, 413);
44
+ }
45
+ if (kept < HEAD_BYTES) {
46
+ head.push(buf.subarray(0, HEAD_BYTES - kept));
47
+ kept += buf.length;
48
+ }
49
+ if (!out.write(buf)) await new Promise<void>((r) => out.once('drain', r));
50
+ }
51
+ await new Promise<void>((resolve, reject) => {
52
+ out.once('error', reject);
53
+ out.end(resolve);
54
+ });
55
+ return Buffer.concat(head).toString('utf8');
56
+ }
57
+
58
+ export async function receiveSessionFile(project: string, session: string, body: Readable, dir = claudeDir()): Promise<SessionFile> {
59
+ const path = transcriptPath(project, session, dir);
60
+ mkdirSync(join(path, '..'), { recursive: true });
61
+ const tmp = `${path}.metro-${String(process.pid)}`;
62
+ const head = await spool(body, tmp);
63
+ if (!firstLineIsJson(head)) {
64
+ rmSync(tmp, { force: true });
65
+ throw new ApiError('a session file is JSON lines, one Claude Code entry per line', 400);
66
+ }
67
+ renameSync(tmp, path);
68
+ return { id: safeName(session, SESSION_RE, 'session id'), bytes: statSync(path).size };
23
69
  }
24
70
 
25
71
  function firstLineIsJson(text: string): boolean {
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.125"
2
+ "version": "0.1.0-beta.127"
3
3
  }