@stage-labs/metro 0.1.0-beta.191 → 0.1.0-beta.193

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.191",
3
+ "version": "0.1.0-beta.193",
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.191",
3
+ "version": "0.1.0-beta.193",
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, and the standing rules loaded at each session start. No vendor credential ever sits in a config file.",
5
5
  "author": {
6
6
  "name": "Bonustrack",
@@ -0,0 +1,107 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
3
+ import { ApiError } from '@metro-labs/http/api-error';
4
+ import { log } from '@metro-labs/core/log';
5
+ import { listSchedules, realRunner, showProps, type Runner, type ScheduledJob } from './schedules.js';
6
+ import { asUser, type AgentUser } from './user.js';
7
+
8
+ const LOG_LINES = 80;
9
+ const TAIL_BYTES = 64 * 1024;
10
+
11
+ export interface JobDetail extends ScheduledJob {
12
+ definition: string;
13
+ logs: string;
14
+ logSource: string | null;
15
+ script: { path: string; text: string } | null;
16
+ }
17
+
18
+ const SCRIPT_MAX = 64 * 1024;
19
+
20
+ function textFile(path: string): string | null {
21
+ try {
22
+ const st = statSync(path);
23
+ if (!st.isFile() || st.size > SCRIPT_MAX) return null;
24
+ const text = readFileSync(path, 'utf8');
25
+ return text.includes('\u0000') ? null : text;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ export function scriptOf(command: string): { path: string; text: string } | null {
32
+ const words = command.split(/\s+/).filter((w) => w.startsWith('/') && !w.includes('>'));
33
+ for (const path of words.slice(0, 3)) {
34
+ const text = textFile(path);
35
+ if (text !== null) return { path, text };
36
+ }
37
+ return null;
38
+ }
39
+
40
+ function findJob(id: string, user: AgentUser | null, runner: Runner): ScheduledJob {
41
+ const job = listSchedules(user, runner).find((j) => j.id === id);
42
+ if (job === undefined) throw new ApiError('no such scheduled job', 404);
43
+ return job;
44
+ }
45
+
46
+ const serviceOf = (unit: string, runner: Runner): string => showProps(runner, unit, ['Unit']).Unit ?? unit.replace(/\.timer$/, '.service');
47
+
48
+ export function logFileOf(command: string): string | null {
49
+ const m = /(?:^|\s)(?:>>|>)\s*(\/\S+)/.exec(command);
50
+ return m?.[1] ?? null;
51
+ }
52
+
53
+ function tail(path: string): string {
54
+ const size = statSync(path).size;
55
+ const start = Math.max(0, size - TAIL_BYTES);
56
+ const fd = openSync(path, 'r');
57
+ try {
58
+ const buffer = Buffer.alloc(size - start);
59
+ readSync(fd, buffer, 0, buffer.length, start);
60
+ return buffer.toString('utf8').split('\n').slice(-LOG_LINES).join('\n');
61
+ } finally {
62
+ closeSync(fd);
63
+ }
64
+ }
65
+
66
+ function timerDetail(job: ScheduledJob, runner: Runner): JobDetail {
67
+ const unit = job.id.slice('timer:'.length);
68
+ const service = serviceOf(unit, runner);
69
+ return {
70
+ ...job,
71
+ definition: runner.run('systemctl', ['cat', unit, service, '--no-pager']).stdout,
72
+ logs: runner.run('journalctl', ['-u', service, '-n', String(LOG_LINES), '--no-pager', '-o', 'short-iso']).stdout,
73
+ logSource: `journalctl -u ${service}`,
74
+ script: scriptOf(job.command),
75
+ };
76
+ }
77
+
78
+ function cronDetail(job: ScheduledJob): JobDetail {
79
+ const file = logFileOf(job.command);
80
+ const readable = file !== null && existsSync(file) && statSync(file).isFile();
81
+ return {
82
+ ...job,
83
+ definition: `${job.schedule} ${job.command}`,
84
+ logs: readable ? tail(file) : '',
85
+ logSource: file,
86
+ script: scriptOf(job.command),
87
+ };
88
+ }
89
+
90
+ export function scheduleDetail(id: string, user: AgentUser | null, runner: Runner = realRunner): JobDetail {
91
+ const job = findJob(id, user, runner);
92
+ return job.kind === 'timer' ? timerDetail(job, runner) : cronDetail(job);
93
+ }
94
+
95
+ export function runNow(id: string, user: AgentUser | null, runner: Runner = realRunner): JobDetail {
96
+ const job = findJob(id, user, runner);
97
+ if (job.runsAs === 'root') throw new ApiError('this job still runs as root; switch it to the agent first', 409);
98
+ if (job.kind === 'timer') runner.run('systemctl', ['start', '--no-block', serviceOf(job.id.slice('timer:'.length), runner)]);
99
+ else {
100
+ if (user === null) throw new ApiError('Claude Code does not run as its own user on this machine', 409);
101
+ const [file, args] = asUser(user, 'sh', ['-c', job.command]);
102
+ const child = spawn(file, args, { detached: true, stdio: 'ignore', cwd: user.home });
103
+ child.unref();
104
+ }
105
+ log.info({ job: job.name }, 'schedules: run now, from the page');
106
+ return scheduleDetail(id, user, runner);
107
+ }
@@ -2,16 +2,23 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { ApiError } from '@metro-labs/http/api-error';
3
3
  import { bodyField, readJsonBody, sessionRoute } from '@metro-labs/http/api-http';
4
4
  import { listSchedules, retrySchedule } from './schedules.js';
5
+ import { runNow, scheduleDetail } from './schedule-detail.js';
5
6
  import { agentUser } from './user.js';
6
7
 
7
8
  const PATH = '/api/schedules';
8
9
 
10
+ const queryId = (req: IncomingMessage): string | null => new URLSearchParams((req.url ?? '').split('?')[1] ?? '').get('id');
11
+
9
12
  async function answer(req: IncomingMessage): Promise<unknown> {
10
13
  const user = agentUser();
11
- if (req.method === 'GET') return { agentUser: user?.name ?? null, jobs: listSchedules(user) };
14
+ if (req.method === 'GET') {
15
+ const id = queryId(req);
16
+ return id === null ? { agentUser: user?.name ?? null, jobs: listSchedules(user) } : { job: scheduleDetail(id, user) };
17
+ }
12
18
  const body = await readJsonBody(req);
13
19
  const id = bodyField(body, 'id');
14
20
  if (typeof id !== 'string' || id === '') throw new ApiError('id is required', 400);
21
+ if (bodyField(body, 'action') === 'run') return { job: runNow(id, user) };
15
22
  return { agentUser: user?.name ?? null, jobs: retrySchedule(id, user) };
16
23
  }
17
24
 
@@ -34,7 +34,7 @@ export interface Runner {
34
34
  run: (file: string, args: string[], input?: string) => { status: number | null; stdout: string };
35
35
  }
36
36
 
37
- const realRunner: Runner = {
37
+ export const realRunner: Runner = {
38
38
  run: (file, args, input) => {
39
39
  const done = spawnSync(file, args, { encoding: 'utf8', input, stdio: ['pipe', 'pipe', 'ignore'], timeout: 20_000 });
40
40
  return { status: done.error === undefined ? done.status : null, stdout: done.stdout ?? '' };
@@ -48,7 +48,7 @@ export const rehome = (text: string, home: string): string => text.replace(/(^|[
48
48
  const stamp = (micros: unknown): string | null =>
49
49
  typeof micros === 'number' && micros > 0 ? new Date(micros / 1000).toISOString() : null;
50
50
 
51
- function showProps(runner: Runner, unit: string, props: string[]): Record<string, string> {
51
+ export function showProps(runner: Runner, unit: string, props: string[]): Record<string, string> {
52
52
  const out = runner.run('systemctl', ['show', unit, '--no-pager', ...props.map((p) => `-p${p}`)]).stdout;
53
53
  const found: Record<string, string> = {};
54
54
  for (const line of out.split('\n')) {
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.191"
2
+ "version": "0.1.0-beta.193"
3
3
  }