@stage-labs/metro 0.1.0-beta.184 → 0.1.0-beta.186

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/service.js CHANGED
@@ -35,6 +35,7 @@ export function systemdUnit(host, exec, target) {
35
35
  `ExecStart=${exec.map(unitWord).join(' ')}`,
36
36
  'Restart=always',
37
37
  'RestartSec=2',
38
+ 'OOMPolicy=continue',
38
39
  `WorkingDirectory=${unitWord(host.home)}`,
39
40
  ...env,
40
41
  '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stage-labs/metro",
3
- "version": "0.1.0-beta.184",
3
+ "version": "0.1.0-beta.186",
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.184",
3
+ "version": "0.1.0-beta.186",
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",
@@ -70,7 +70,7 @@ export function agentEnv(user: AgentUser, extra: Record<string, string> = {}): R
70
70
  export function asUser(user: AgentUser | null, file: string, args: readonly string[], extra: Record<string, string> = {}): [string, string[]] {
71
71
  if (user === null) return [file, [...args]];
72
72
  const env = Object.entries(agentEnv(user, extra)).map(([k, v]) => `${k}=${v}`);
73
- return ['runuser', ['-u', user.name, '--', 'env', '-i', ...env, file, ...args]];
73
+ return ['setpriv', [`--reuid=${String(user.uid)}`, `--regid=${String(user.gid)}`, '--init-groups', 'env', '-i', ...env, file, ...args]];
74
74
  }
75
75
 
76
76
  export const asAgent = (file: string, args: readonly string[], extra: Record<string, string> = {}): [string, string[]] =>
@@ -24,6 +24,7 @@ import { syncPluginServers } from '../connectors/plugin-sync.js';
24
24
  import { loadConnectorPolicies, readLocalConnectors } from '../connectors/store.js';
25
25
  import { ensureMetroPlugin } from '../claude/plugin-install.js';
26
26
  import { provisionAgentUser } from '../agent-user/provision.js';
27
+ import { ensureServiceOomPolicy } from '../claude/memory.js';
27
28
  import { unwatchSession, watchSession } from '../claude/session.js';
28
29
  import { tryClaudeSetup } from '../claude/setup.js';
29
30
  import { applyLocalOwner } from './local-owner.js';
@@ -154,6 +155,7 @@ installBearerSessions(agentsDir(), localOwner);
154
155
  }
155
156
 
156
157
  async function startClaude(): Promise<void> {
158
+ ensureServiceOomPolicy();
157
159
  const agentUser = await provisionAgentUser();
158
160
  if (agentUser !== 'off') log.info({ agentUser }, 'agent-user: Claude Code runs as its own user');
159
161
  if (agentUser === 'failed' || agentUser === 'unsupported') return;
@@ -0,0 +1,72 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { totalmem } from 'node:os';
4
+ import { dirname } from 'node:path';
5
+ import { errMsg, log } from '@metro-labs/core/log';
6
+
7
+ const UNIT = '/etc/systemd/system/metro.service';
8
+ const DROP_IN = '/etc/systemd/system/metro.service.d/10-metro-memory.conf';
9
+ const DROP_IN_TEXT = '[Service]\nOOMPolicy=continue\n';
10
+ const GIB = 1024 ** 3;
11
+ const RESERVE = 1.5 * GIB;
12
+ const FLOOR = GIB;
13
+
14
+ export interface ScopeHost {
15
+ platform: string;
16
+ uid: number | undefined;
17
+ systemd: boolean;
18
+ total: number;
19
+ }
20
+
21
+ const realHost = (): ScopeHost => ({
22
+ platform: process.platform,
23
+ uid: process.getuid?.(),
24
+ systemd: existsSync('/run/systemd/system'),
25
+ total: totalmem(),
26
+ });
27
+
28
+ export function sessionMemoryLimit(total: number): number {
29
+ const kept = Math.min(Math.floor(total * 0.8), total - RESERVE);
30
+ return Math.max(FLOOR, Math.floor(kept / (1024 * 1024)) * 1024 * 1024);
31
+ }
32
+
33
+ const usesScopes = (host: ScopeHost): boolean => host.platform === 'linux' && host.uid === 0 && host.systemd;
34
+
35
+ export function inSessionScope(command: [string, string[]], host: ScopeHost = realHost(), now = Date.now()): [string, string[]] {
36
+ if (!usesScopes(host)) return command;
37
+ const limit = sessionMemoryLimit(host.total);
38
+ const [file, args] = command;
39
+ return [
40
+ 'systemd-run',
41
+ [
42
+ '--scope',
43
+ '--quiet',
44
+ '--collect',
45
+ `--unit=metro-claude-${String(now)}`,
46
+ '-p',
47
+ `MemoryMax=${String(limit)}`,
48
+ '-p',
49
+ `MemoryHigh=${String(Math.floor(limit * 0.9))}`,
50
+ '-p',
51
+ 'OOMPolicy=continue',
52
+ '--',
53
+ file,
54
+ ...args,
55
+ ],
56
+ ];
57
+ }
58
+
59
+ export function ensureServiceOomPolicy(host: ScopeHost = realHost(), env: NodeJS.ProcessEnv = process.env): 'written' | 'present' | 'skipped' {
60
+ if (!usesScopes(host) || (env.INVOCATION_ID ?? '') === '' || !existsSync(UNIT)) return 'skipped';
61
+ try {
62
+ if (existsSync(DROP_IN) && readFileSync(DROP_IN, 'utf8') === DROP_IN_TEXT) return 'present';
63
+ mkdirSync(dirname(DROP_IN), { recursive: true });
64
+ writeFileSync(DROP_IN, DROP_IN_TEXT, { mode: 0o644 });
65
+ const reload = spawnSync('systemctl', ['daemon-reload'], { stdio: 'ignore' });
66
+ log.info({ reloaded: reload.status === 0 }, 'claude-memory: the metro service no longer stops as a whole when the kernel kills one process for memory');
67
+ return 'written';
68
+ } catch (err) {
69
+ log.warn({ err: errMsg(err) }, 'claude-memory: could not set the service memory policy');
70
+ return 'skipped';
71
+ }
72
+ }
@@ -11,6 +11,7 @@ import { notReady, readModelConfig, routedConnection } from '../gateway/model-co
11
11
  import { claudeDir, listClaudeProjects } from './files.js';
12
12
  import { claudeAccount, claudeInstalled } from './login.js';
13
13
  import { trustFolder } from './onboarding.js';
14
+ import { inSessionScope } from './memory.js';
14
15
  import { agentUser, agentViewDir, asAgent, claudeHome, wantedAgentUser } from '../agent-user/user.js';
15
16
 
16
17
  function sessionEnv(): Record<string, string> {
@@ -88,6 +89,8 @@ function tmuxOk(tmux: string, args: string[]): boolean {
88
89
 
89
90
  export const sessionRunning = (tmux = 'tmux'): boolean => tmuxOk(tmux, ['has-session', '-t', SESSION_NAME]);
90
91
 
92
+ export const tmuxServerUp = (tmux = 'tmux'): boolean => tmuxOk(tmux, ['list-sessions']);
93
+
91
94
  function realDir(dir: string): string {
92
95
  try {
93
96
  return realpathSync(dir);
@@ -179,7 +182,8 @@ export function startSession(deps: SessionDeps = {}): SessionStatus {
179
182
  const trusted = trustFolder(home);
180
183
  const [command = 'metro', ...args] = metroCommand(deps, home);
181
184
  const tmuxArgs = ['new-session', '-d', '-s', SESSION_NAME, '-c', home, '-x', '200', '-y', '50', command, ...args];
182
- const run = spawnSync(...asAgent(tmux, tmuxArgs), { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], cwd: home });
185
+ const launch = deps.tmux === undefined && !tmuxServerUp(tmux) ? inSessionScope(asAgent(tmux, tmuxArgs)) : asAgent(tmux, tmuxArgs);
186
+ const run = spawnSync(...launch, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], cwd: home });
183
187
  recordStart(deps, tmux, now, run);
184
188
  if (memory.lastError === null) log.info({ home, trusted, command: [command, ...args].join(' ') }, 'claude-session: started Claude Code in tmux');
185
189
  return sessionStatus(deps);
@@ -5,7 +5,8 @@ import { isRecord } from '@metro-labs/core/is-record';
5
5
  import { log } from '@metro-labs/core/log';
6
6
  import { openrouterModels, openrouterZdrModels } from './openrouter.js';
7
7
  import { anthropicModels, bedrockModels } from './provider-models.js';
8
- import { syncAvailableModelsQuietly } from '../claude/setup.js';
8
+ import { routeOf, syncAvailableModelsQuietly } from '../claude/setup.js';
9
+ import { sessionRunning, stopSession } from '../claude/session.js';
9
10
  import { forgetOne } from './usage.js';
10
11
  import {
11
12
  addConnection,
@@ -35,10 +36,19 @@ const DEVICE_ID_RE = /^[A-Za-z0-9_-]{16,64}$/;
35
36
 
36
37
  export type { ModelApiDeps } from './model-store.js';
37
38
 
39
+ function restartRunningSession(): boolean {
40
+ if (!sessionRunning()) return false;
41
+ stopSession();
42
+ return true;
43
+ }
44
+
38
45
  function kept(store: Store, next: ModelConfig, deps: ModelApiDeps, note: string, fields: Record<string, unknown>): unknown {
46
+ const before = routeOf(store.read());
39
47
  store.write(next);
40
48
  syncAvailableModelsQuietly(deps.setup ?? {}, next);
41
49
  log.info(fields, note);
50
+ if (routeOf(next) !== before && (deps.restartSession ?? restartRunningSession)())
51
+ log.info({ was: before, now: routeOf(next) }, 'model-api: the model changed, so the Claude session restarts on it');
42
52
  return settingsBody(next);
43
53
  }
44
54
 
@@ -23,6 +23,7 @@ export interface ModelApiDeps {
23
23
  anthropicBase?: string;
24
24
  bedrockControlBase?: string;
25
25
  setup?: SetupDeps;
26
+ restartSession?: () => boolean;
26
27
  }
27
28
 
28
29
  export interface Store {
@@ -6,12 +6,21 @@ import { bodyField, readJsonBody, sessionRoute } from '@metro-labs/http/api-http
6
6
  import { log } from '@metro-labs/core/log';
7
7
  import { mintTerminalTicket } from './tickets.js';
8
8
  import { agentCommand, asAgent, claudeHome } from '../agent-user/user.js';
9
+ import { inSessionScope } from '../claude/memory.js';
10
+ import { tmuxServerUp } from '../claude/session.js';
9
11
 
10
12
  const PREFIX = '/api/terminal';
11
13
  const TICKETS = `${PREFIX}/tickets`;
12
14
  const SESSION_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
13
15
 
14
- export const tmuxCommand = (session: string, home = claudeHome() ?? homedir()): string[] => agentCommand([
16
+ const scoped = (command: string[]): string[] => {
17
+ if (tmuxServerUp()) return command;
18
+ const [file = '', ...args] = command;
19
+ const [bin, argv] = inSessionScope([file, args]);
20
+ return [bin, ...argv];
21
+ };
22
+
23
+ export const tmuxCommand = (session: string, home = claudeHome() ?? homedir()): string[] => scoped(agentCommand([
15
24
  'tmux',
16
25
  'new-session',
17
26
  '-A',
@@ -35,7 +44,7 @@ export const tmuxCommand = (session: string, home = claudeHome() ?? homedir()):
35
44
  '-as',
36
45
  'terminal-features',
37
46
  ',xterm-256color:clipboard',
38
- ], { TERM: 'xterm-256color', COLORTERM: 'truecolor' });
47
+ ], { TERM: 'xterm-256color', COLORTERM: 'truecolor' }));
39
48
 
40
49
  export interface TerminalApiDeps {
41
50
  command?: (session: string) => string[];
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.184"
2
+ "version": "0.1.0-beta.186"
3
3
  }