Pace Claude's heavy work to the machine it runs on, with configurable hard caps

Paces Claude's heavy work to the machine it runs on. Unconfigured, it caps nothing and never reminds, so a VM can be saturated. On a machine shared with a person, configure it to remind the model to scale its work down as load climbs, with generous hard caps as a backstop.
Set these options under pluginConfigs in settings, keyed load@<marketplace>:
browserSessions: refuses to launch an agent-browser session while this many already run on the machine. 0 caps nothing. Each agent is held to one session regardless.caps: pool:limit:regex entries. A Bash command matching an entry's regex is refused while limit processes in its pool already run, while it starts several at once (& in a loop, xargs -P), or under critical memory pressure. Entries sharing a pool share its limit. Running jobs are counted from ps, once per process tree, so wrappers and workers don't count twice.Thresholds are load average per core, named for what the mod does at each:
remind: after any tool call, appends a reminder to the result once load reaches it or memory is under pressure. The reminder names the load, memory pressure, Claude sessions, and capped jobs running, and asks the model to weigh its next heavy step: defer it, narrow it, lower its worker and thread counts, or run it under nice. 0 turns reminders off.warn: a firmer reminder at this load, or under critical memory pressure, to start no heavy work the task doesn't need. Each agent hears each level once until the machine calms.refuse: refuses capped commands while load is above it. 0 turns it off.user/settings.json holds this repo's own values.
register.ts gates Bash calls, paces every tool call, and closes an agent's browser sessions when it ends.caps.ts parses caps, samples the machine, and judges capped commands.pace.ts grades the machine and writes the reminder.browser.ts limits agent-browser to one session per agent and, when configured, a number of sessions machine-wide.command.ts splits a command line into the simple commands both read.mod-events as browser.*, cap.*, pace, and error. session.start carries any caps that failed to parse.bun scripts/mod-test.ts load runs the mod's tests.
mod/register.ts 357 lines1import type { EngineInterface, On, PluginOptions } from "claude-code";
2import { type BrowserCall, type Census, browserCalls, judge } from "./browser";
3import {
4 type Cap,
5 type Machine,
6 judge as judgeCaps,
7 loadPerCore,
8 parseCaps,
9 plan as planCaps,
10 pressureLevel,
11 processes,
12} from "./caps";
13import { segments } from "./command";
14import { type Level, type Thresholds, level, reminder } from "./pace";
15
16const MOD = "load";
17const MAIN = "main";
18
19const ENDED = new Set(["completed", "failed", "killed"]);
20const CONTINUING = new Set(["clear", "resume"]);
21
22// SubagentStop closes an agent's sessions at once, but a background subagent
23// stopped with TaskStop doesn't fire it, so its sessions are looked for on a
24// timer while one is open.
25const SWEEP_MS = 30_000;
26
27// Pacing samples the machine at most this often, so most tool calls cost nothing.
28const SAMPLE_MS = 15_000;
29
30interface Config {
31 browserSessions: number;
32 caps: Cap[];
33 invalid: string[];
34 refuse: number;
35 pace: Thresholds;
36}
37
38function configOf(options: PluginOptions): Config {
39 const entries = options.caps;
40 const number = (key: string) => {
41 const value = options[key];
42 return typeof value === "number" ? value : 0;
43 };
44 return {
45 browserSessions: number("browserSessions"),
46 ...parseCaps(Array.isArray(entries) ? entries : []),
47 refuse: number("refuse"),
48 pace: { remind: number("remind"), warn: number("warn") },
49 };
50}
51
52interface State {
53 /** Session to the agent that launched it. */
54 owners: Map<string, string>;
55 pending: Set<string>;
56 /** Pools of capped jobs allowed to start whose call has not returned. */
57 starting: string[];
58 sweep: { cancel: () => void } | undefined;
59 sample: { at: number; machine: Machine } | undefined;
60 /** Pacing level each agent was last told. */
61 told: Map<string, Level>;
62}
63
64async function liveSessions($: EngineInterface): Promise<Set<string>> {
65 const { exitCode, stdout, stderr } = await $.process.run(
66 ["agent-browser", "session", "list", "--json"],
67 { timeoutMs: 5000 },
68 );
69 if (exitCode !== 0) throw new Error(`agent-browser session list exited ${exitCode}: ${stderr}`);
70 const parsed: unknown = JSON.parse(stdout);
71 const sessions =
72 typeof parsed === "object" &&
73 parsed !== null &&
74 "data" in parsed &&
75 typeof parsed.data === "object" &&
76 parsed.data !== null &&
77 "sessions" in parsed.data
78 ? parsed.data.sessions
79 : undefined;
80 if (!Array.isArray(sessions)) throw new Error(`unexpected session list: ${stdout}`);
81 return new Set(sessions.filter((s) => typeof s === "string"));
82}
83
84async function machine($: EngineInterface, caps: readonly Cap[]): Promise<Machine> {
85 const [ps, sysctl] = await Promise.all([
86 $.process.run(["ps", "-axo", "pid=,ppid=,command="], { timeoutMs: 5000 }),
87 // The pressure level is hidden from `sysctl -a` but reads by name without root.
88 $.process.run(
89 ["sysctl", "-n", "vm.loadavg", "hw.ncpu", "kern.memorystatus_vm_pressure_level"],
90 { timeoutMs: 5000 },
91 ),
92 ]);
93 return {
94 ...processes(caps, ps.stdout),
95 loadPerCore: loadPerCore(sysctl.stdout),
96 pressure: pressureLevel(sysctl.stdout),
97 };
98}
99
100async function sampled($: EngineInterface, state: State, config: Config): Promise<Machine> {
101 const now = await $.clock.now();
102 if (state.sample === undefined || now - state.sample.at >= SAMPLE_MS) {
103 state.sample = { at: now, machine: await machine($, config.caps) };
104 }
105 return state.sample.machine;
106}
107
108/** Guidance for an agent whose machine got busier since it was last told. */
109async function pace(
110 $: EngineInterface,
111 state: State,
112 config: Config,
113 owner: string,
114): Promise<string | undefined> {
115 if (config.pace.remind <= 0) return undefined;
116 const now = await sampled($, state, config);
117 const grade = level(now, config.pace);
118 const told = state.told.get(owner) ?? 0;
119 // A calmer machine re-arms the reminder for when load climbs again.
120 if (grade < told) state.told.set(owner, grade);
121 if (grade <= told) return undefined;
122 state.told.set(owner, grade);
123 void $.modEvents.emit({
124 mod: MOD,
125 event: "pace",
126 detail: {
127 level: grade,
128 loadPerCore: now.loadPerCore ?? null,
129 pressure: now.pressure ?? null,
130 sessions: now.sessions,
131 running: now.running,
132 agent: owner === MAIN ? null : owner,
133 },
134 });
135 return reminder(now, grade);
136}
137
138function census(state: State, owner: string, isSubagent: boolean, live: Set<string>): Census {
139 const mine = new Set<string>();
140 for (const [session, by] of state.owners) {
141 if (by === owner && (live.has(session) || state.pending.has(session))) mine.add(session);
142 }
143 // The main loop may close every session.
144 const others = isSubagent ? new Set([...live].filter((s) => !mine.has(s))) : new Set<string>();
145 return { live, pending: state.pending, mine, others };
146}
147
148async function close(
149 $: EngineInterface,
150 state: State,
151 session: string,
152 trigger: string,
153 timeoutMs: number,
154): Promise<void> {
155 const owner = state.owners.get(session);
156 const agent = owner === MAIN ? null : (owner ?? null);
157 state.owners.delete(session);
158 const { exitCode, stderr } = await $.process
159 .run(["agent-browser", "--session", session, "close"], { timeoutMs })
160 .catch((error: unknown) => ({ exitCode: -1, stderr: String(error) }));
161 void $.modEvents.emit({
162 mod: MOD,
163 event: "browser.close",
164 ok: exitCode === 0,
165 detail: { session, agent, trigger, exitCode, stderr: stderr.trim() },
166 });
167}
168
169async function sweep($: EngineInterface, state: State): Promise<void> {
170 const owned = [...state.owners].filter(([, owner]) => owner !== MAIN);
171 if (owned.length === 0) {
172 state.sweep?.cancel();
173 state.sweep = undefined;
174 return;
175 }
176 state.sweep ??= $.clock.every(SWEEP_MS, () => {
177 sweep($, state).catch((error: unknown) => {
178 failed($, "sweep", "threw", String(error));
179 });
180 });
181 const agents = await $.agent.list();
182 // A workflow's agents are absent from the list, so only a listed agent that
183 // ended has its sessions closed. The rest wait for the idle timeout.
184 const ended = new Set(agents.filter((a) => ENDED.has(a.status)).map((a) => a.id));
185 await Promise.all(
186 owned
187 .filter(([session, owner]) => ended.has(owner) && !state.pending.has(session))
188 .map(([session]) => close($, state, session, "agent-end", 5000)),
189 );
190}
191
192function record(state: State, calls: BrowserCall[], owner: string, live: Set<string>): string[] {
193 const launched: string[] = [];
194 for (const call of calls) {
195 if (call.effect !== "launch" || live.has(call.session) || state.owners.has(call.session)) {
196 continue;
197 }
198 state.owners.set(call.session, owner);
199 state.pending.add(call.session);
200 launched.push(call.session);
201 }
202 return launched;
203}
204
205function forget(state: State, calls: BrowserCall[]): void {
206 for (const call of calls) {
207 if (call.effect === "close") state.owners.delete(call.session);
208 if (call.effect === "close-all") state.owners.clear();
209 }
210}
211
212function failed($: EngineInterface, hook: string, kind: string, message?: string): void {
213 $.modEvents
214 .emit({
215 mod: MOD,
216 event: "error",
217 ok: false,
218 detail: { hook, kind, message: message ?? null },
219 })
220 .catch(() => undefined);
221}
222
223export function register(on: On, options: PluginOptions): void {
224 const config = configOf(options);
225 const state: State = {
226 owners: new Map(),
227 pending: new Set(),
228 starting: [],
229 sweep: undefined,
230 sample: undefined,
231 told: new Map(),
232 };
233
234 on("session.start", ($, e, next) => {
235 void $.modEvents.emit({
236 mod: MOD,
237 event: "session.start",
238 ...(config.invalid.length > 0 && { ok: false, detail: { invalidCaps: config.invalid } }),
239 });
240 return next(e);
241 });
242
243 // Runs after the tool, so the sample never delays the call itself.
244 on("tool.call", async ($, e, next) => {
245 const result = await next(e);
246 if (result.deny !== undefined) return result;
247 const text = await pace($, state, config, e.agentId ?? MAIN);
248 return text === undefined ? result : { ...result, context: [...(result.context ?? []), text] };
249 }).catch(($, e, next) => {
250 failed($, "pace", next.error.kind, next.error.message);
251 return next(e);
252 });
253
254 on("tool.call", { tool: "Bash" }, async ($, e, next) => {
255 const parts = segments(e.command);
256 const calls = browserCalls(parts);
257 const plan = planCaps(config.caps, parts);
258 if (calls.length === 0 && plan.pools.length === 0) return next(e);
259
260 const owner = e.agentId ?? MAIN;
261 const agent = e.agentId ?? null;
262 let live = new Set<string>();
263 if (calls.length > 0) {
264 live = await liveSessions($);
265 const verdict = judge(
266 calls,
267 census(state, owner, e.agentId !== undefined, live),
268 config.browserSessions,
269 );
270 if (verdict.deny !== undefined) {
271 void $.modEvents.emit({
272 mod: MOD,
273 event: "browser.deny",
274 detail: {
275 reason: verdict.reason,
276 sessions: calls.map((c) => c.session),
277 live: live.size,
278 agent,
279 },
280 });
281 return { deny: verdict.deny };
282 }
283 }
284
285 if (plan.pools.length > 0) {
286 const probed = await machine($, config.caps);
287 state.sample = { at: await $.clock.now(), machine: probed };
288 const now = { ...probed, running: [...probed.running, ...state.starting] };
289 const verdict = judgeCaps(config.caps, plan, now, config.refuse);
290 void $.modEvents.emit({
291 mod: MOD,
292 event: verdict.deny === undefined ? "cap.start" : "cap.deny",
293 detail: {
294 reason: verdict.reason ?? null,
295 pools: plan.pools,
296 running: now.running,
297 loadPerCore: now.loadPerCore ?? null,
298 pressure: now.pressure ?? null,
299 agent,
300 },
301 });
302 if (verdict.deny !== undefined) return { deny: verdict.deny };
303 }
304
305 state.starting.push(...plan.pools);
306 const launched = record(state, calls, owner, live);
307 for (const session of launched) {
308 void $.modEvents.emit({
309 mod: MOD,
310 event: "browser.launch",
311 detail: { session, live: live.size, agent },
312 });
313 }
314 try {
315 return await next(e);
316 } finally {
317 for (const session of launched) state.pending.delete(session);
318 for (const pool of plan.pools) state.starting.splice(state.starting.indexOf(pool), 1);
319 forget(state, calls);
320 if (launched.length > 0) await sweep($, state);
321 }
322 // Fails open: refusing on a broken probe would block every matching call.
323 }).catch(($, e, next) => {
324 failed($, "tool.call", next.error.kind, next.error.message);
325 return next(e);
326 });
327
328 on("turn.complete", async ($, e, next) => {
329 await sweep($, state);
330 return next(e);
331 }).catch(($, e, next) => {
332 failed($, "turn.complete", next.error.kind, next.error.message);
333 return next(e);
334 });
335
336 on("classic.SubagentStop", async ($, e, next) => {
337 const sessions = [...state.owners]
338 .filter(([session, owner]) => owner === e.agent_id && !state.pending.has(session))
339 .map(([session]) => session);
340 await Promise.all(sessions.map((s) => close($, state, s, "agent-stop", 5000)));
341 if (sessions.length > 0) await sweep($, state);
342 return next(e);
343 }).catch(($, e, next) => next(e));
344
345 on("session.end", async ($, e, next) => {
346 if (CONTINUING.has(e.reason)) return next(e);
347 state.sweep?.cancel();
348 state.sweep = undefined;
349 // session.end shares 1.5s across hooks. The idle timeout catches stragglers.
350 await Promise.all([...state.owners.keys()].map((s) => close($, state, s, "session-end", 1000)));
351 return next(e);
352 }).catch(($, e, next) => {
353 failed($, "session.end", next.error.kind, next.error.message);
354 return next(e);
355 });
356}
357mod/browser.ts 163 lines1import { type Segment, splitPrefix } from "./command";
2
3export type Effect = "launch" | "close" | "close-all" | "none";
4
5export interface BrowserCall {
6 session: string;
7 effect: Effect;
8}
9
10const RUNNERS = new Set(["npx", "bunx", "pnpx"]);
11
12// Options whose value is a separate word.
13const VALUED = new Set([
14 "--session",
15 "--namespace",
16 "--profile",
17 "--session-name",
18 "--state",
19 "--headers",
20 "--executable-path",
21 "--extension",
22 "--init-script",
23 "--enable",
24 "--args",
25 "--user-agent",
26 "--proxy",
27 "--proxy-bypass",
28 "--ca-cert",
29 "--cdp",
30 "-p",
31 "--provider",
32 "--device",
33 "--screenshot-dir",
34 "--screenshot-quality",
35 "--screenshot-format",
36 "--input-mode",
37 "--idle-timeout",
38 "--restore-save",
39 "--model",
40]);
41
42const INERT = new Set([
43 "session",
44 "skills",
45 "help",
46 "install",
47 "upgrade",
48 "doctor",
49 "dashboard",
50 "profiles",
51 "auth",
52 "plugin",
53 "mcp",
54]);
55
56const INERT_FLAGS = new Set(["--help", "-h", "--version", "-V"]);
57
58function isAgentBrowser(word: string | undefined): boolean {
59 return word !== undefined && (word === "agent-browser" || word.endsWith("/agent-browser"));
60}
61
62function parse(argv: string[], envSession: string | undefined): BrowserCall {
63 let session = envSession;
64 let subcommand: string | undefined;
65 const rest: string[] = [];
66 for (let i = 0; i < argv.length; i++) {
67 const word = argv[i] ?? "";
68 if (word.startsWith("--session=")) {
69 session = word.slice("--session=".length);
70 } else if (word === "--session") {
71 session = argv[i + 1];
72 i++;
73 } else if (VALUED.has(word)) {
74 i++;
75 } else if (subcommand === undefined && !word.startsWith("-")) {
76 subcommand = word;
77 } else {
78 rest.push(word);
79 }
80 }
81 const resolved = session === undefined || session === "" ? "default" : session;
82 if (subcommand === "close") {
83 return { session: resolved, effect: rest.includes("--all") ? "close-all" : "close" };
84 }
85 const isInert =
86 subcommand === undefined || INERT.has(subcommand) || rest.some((word) => INERT_FLAGS.has(word));
87 return { session: resolved, effect: isInert ? "none" : "launch" };
88}
89
90export function browserCalls(segments: Segment[]): BrowserCall[] {
91 const calls: BrowserCall[] = [];
92 for (const { words } of segments) {
93 const { env, argv } = splitPrefix(words);
94 let start = 0;
95 if (RUNNERS.has(argv[0] ?? "")) {
96 start = 1;
97 while ((argv[start] ?? "").startsWith("-")) start++;
98 }
99 if (!isAgentBrowser(argv[start])) continue;
100 calls.push(parse(argv.slice(start + 1), env.get("AGENT_BROWSER_SESSION")));
101 }
102 return calls;
103}
104
105export interface Verdict {
106 deny?: string;
107 reason?: "owned" | "cap" | "close-all" | "dynamic";
108}
109
110export interface Census {
111 live: Set<string>;
112 /** Allowed to launch, call not yet returned. */
113 pending: Set<string>;
114 mine: Set<string>;
115 others: Set<string>;
116}
117
118const list = (sessions: Iterable<string>) => [...sessions].map((s) => `\`${s}\``).join(", ");
119
120/** `sessions` caps browsers running machine-wide; 0 caps nothing. */
121export function judge(calls: BrowserCall[], census: Census, sessions: number): Verdict {
122 if (calls.some((call) => call.effect === "close-all") && census.others.size > 0) {
123 return {
124 reason: "close-all",
125 deny: `\`agent-browser close --all\` would close browser sessions other agents are using (${list(census.others)}). Close only your own: \`agent-browser --session <name> close\`.`,
126 };
127 }
128 const dynamic = calls.find((call) => call.effect === "launch" && call.session.includes("$"));
129 if (dynamic !== undefined) {
130 return {
131 reason: "dynamic",
132 deny: `Browser session \`${dynamic.session}\` is named by a shell expansion, so each run can start another browser. Name one session for this agent literally and navigate it from item to item.`,
133 };
134 }
135 const launching = new Set(
136 calls
137 .filter((call) => call.effect === "launch" && !census.live.has(call.session))
138 .map((call) => call.session),
139 );
140 const mine = new Set(census.mine);
141 const pending = new Set(census.pending);
142 for (const session of launching) {
143 if (pending.has(session)) continue;
144 const held = [...mine].filter((owned) => owned !== session);
145 if (held.length > 0) {
146 return {
147 reason: "owned",
148 deny: `You already have browser session ${list(held)} open. Reuse it for this item with \`--session ${held[0]}\` (navigate it to the next page), or run \`agent-browser --session ${held[0]} close\` before starting \`${session}\`. Keep one browser session per agent.`,
149 };
150 }
151 const running = new Set([...census.live, ...pending]);
152 if (sessions > 0 && running.size >= sessions) {
153 return {
154 reason: "cap",
155 deny: `${running.size} browser sessions are already running on this machine (${list(running)}), the limit is ${sessions}. Reuse one you own, close one you are done with, or finish this item without a browser and retry once another agent finishes.`,
156 };
157 }
158 mine.add(session);
159 pending.add(session);
160 }
161 return {};
162}
163mod/caps.ts 160 lines1import { type Segment, splitPrefix } from "./command";
2
3/** A pool of commands that may run at most `limit` at once on the machine. */
4export interface Cap {
5 pool: string;
6 limit: number;
7 pattern: RegExp;
8}
9
10const ENTRY = /^([\w-]+):(\d+):(.+)$/s;
11
12/** Parses `pool:limit:regex` entries. Entries sharing a pool share its limit. */
13export function parseCaps(entries: readonly string[]): { caps: Cap[]; invalid: string[] } {
14 const caps: Cap[] = [];
15 const invalid: string[] = [];
16 for (const entry of entries) {
17 const match = ENTRY.exec(entry);
18 try {
19 if (match === null) throw new Error("not pool:limit:regex");
20 caps.push({
21 pool: match[1] ?? "",
22 limit: Number(match[2]),
23 pattern: new RegExp(match[3] ?? ""),
24 });
25 } catch {
26 invalid.push(entry);
27 }
28 }
29 return { caps, invalid };
30}
31
32function poolOf(caps: readonly Cap[], line: string): Cap | undefined {
33 return caps.find(({ pattern }) => pattern.test(line));
34}
35
36export interface Plan {
37 pools: string[];
38 isParallel: boolean;
39}
40
41const PARALLEL_RUNNERS = /^(?:parallel|xargs .*-P ?(?:0|[2-9]|\d{2,})\b)/;
42const LOOPS = new Set(["for", "while", "until"]);
43
44export function plan(caps: readonly Cap[], segments: Segment[]): Plan {
45 const pools: string[] = [];
46 let backgrounded = 0;
47 let fanned = false;
48 const isLoop = segments.some(({ words }) => LOOPS.has(words[0] ?? ""));
49 for (const { words, isBackground } of segments) {
50 // A quoted phrase (`git commit -m "fix vite build"`) mentions a command
51 // rather than running it.
52 const line = splitPrefix(words)
53 .argv.filter((word) => !/\s/.test(word))
54 .join(" ");
55 const cap = poolOf(caps, line);
56 if (cap === undefined) continue;
57 pools.push(cap.pool);
58 if (isBackground) backgrounded++;
59 if (PARALLEL_RUNNERS.test(line)) fanned = true;
60 }
61 // A backgrounded job inside a loop starts one job per iteration at once.
62 const isParallel = fanned || (backgrounded > 0 && (pools.length > 1 || isLoop));
63 return { pools, isParallel };
64}
65
66export interface Processes {
67 /** Pool of each running capped job, counted once per process tree. */
68 running: string[];
69 /** Claude Code processes, one per session. */
70 sessions: number;
71}
72
73const basename = (word: string | undefined) => word?.split("/").at(-1) ?? "";
74
75/** Reads `ps -axo pid=,ppid=,command=`. */
76export function processes(caps: readonly Cap[], ps: string): Processes {
77 const rows = ps
78 .split("\n")
79 .map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line))
80 .filter((match) => match !== null)
81 .map(([, pid, ppid, command]) => ({ pid, ppid, command: command ?? "" }));
82 const pools = new Map(rows.map(({ pid, command }) => [pid, poolOf(caps, command)?.pool]));
83 const running: string[] = [];
84 for (const { pid, ppid } of rows) {
85 const pool = pools.get(pid);
86 // Wrappers (`zsh -c`, `npm exec`) and workers repeat a job's words, so
87 // only the top of a matching tree counts.
88 if (pool !== undefined && pools.get(ppid) !== pool) running.push(pool);
89 }
90 const sessions = rows.filter(({ command }) => basename(command.split(" ")[0]) === "claude");
91 return { running, sessions: sessions.length };
92}
93
94/** Parses `sysctl -n vm.loadavg hw.ncpu kern.memorystatus_vm_pressure_level`. */
95export function loadPerCore(sysctl: string): number | undefined {
96 const match = /\{\s*([\d.]+)[^}]*\}\s+(\d+)/.exec(sysctl);
97 if (match === null) return undefined;
98 const cores = Number(match[2]);
99 return cores > 0 ? Number(match[1]) / cores : undefined;
100}
101
102/** macOS memory pressure: 1 normal, 2 warn, 4 critical. Missing on Linux. */
103export function pressureLevel(sysctl: string): number | undefined {
104 const line = sysctl.split("\n")[2]?.trim();
105 return line !== undefined && /^\d+$/.test(line) ? Number(line) : undefined;
106}
107
108export const PRESSURE_WARN = 2;
109export const PRESSURE_CRITICAL = 4;
110
111export interface Machine extends Processes {
112 loadPerCore: number | undefined;
113 pressure: number | undefined;
114}
115
116export interface Verdict {
117 deny?: string;
118 reason?: "parallel" | "pressure" | "running" | "load";
119}
120
121export function judge(
122 caps: readonly Cap[],
123 { pools, isParallel }: Plan,
124 machine: Machine,
125 refuse: number,
126): Verdict {
127 if (pools.length === 0) return {};
128 const jobs = pools.join(", ");
129 if (isParallel) {
130 return {
131 reason: "parallel",
132 deny: `This command starts ${pools.length} heavy jobs side by side (${jobs}). Run them one at a time, each to completion, in separate commands or a sequential loop without \`&\`.`,
133 };
134 }
135 if ((machine.pressure ?? 0) >= PRESSURE_CRITICAL) {
136 return {
137 reason: "pressure",
138 deny: `The machine is out of memory (critical memory pressure). Wait for running work to finish before starting a ${jobs} job.`,
139 };
140 }
141 for (const pool of new Set(pools)) {
142 const limit = caps.find((cap) => cap.pool === pool)?.limit ?? Infinity;
143 const running = machine.running.filter((p) => p === pool).length;
144 if (running >= limit) {
145 return {
146 reason: "running",
147 deny: `${running} ${pool} jobs are already running on this machine, the limit is ${limit}. Wait for one to finish before starting this one.`,
148 };
149 }
150 }
151 const load = machine.loadPerCore;
152 if (refuse > 0 && load !== undefined && load > refuse) {
153 return {
154 reason: "load",
155 deny: `The machine is saturated (load ${load.toFixed(1)}x its core count). Wait for running work to finish before starting a ${jobs} job.`,
156 };
157 }
158 return {};
159}
160mod/command.ts 88 lines1export interface Segment {
2 words: string[];
3 isBackground: boolean;
4}
5
6const SEPARATORS = new Set([";", "|", "\n", "(", ")", "`"]);
7
8/** Splits a command line into simple commands. `2>&1` and `&>` stay inside one. */
9export function segments(command: string): Segment[] {
10 const out: Segment[] = [];
11 let words: string[] = [];
12 let word: string | undefined;
13
14 const endWord = () => {
15 if (word !== undefined) words.push(word);
16 word = undefined;
17 };
18 const endSegment = (isBackground: boolean) => {
19 endWord();
20 if (words.length > 0) out.push({ words, isBackground });
21 words = [];
22 };
23
24 for (let i = 0; i < command.length; i++) {
25 const char = command.charAt(i);
26 if (char === "'" || char === '"') {
27 const end = command.indexOf(char, i + 1);
28 const stop = end === -1 ? command.length : end;
29 word = (word ?? "") + command.slice(i + 1, stop);
30 i = stop;
31 } else if (char === "\\") {
32 word = (word ?? "") + command.charAt(i + 1);
33 i++;
34 } else if (char === "&" && (command[i - 1] === ">" || command[i + 1] === ">")) {
35 word = (word ?? "") + char;
36 } else if (char === "&" && command[i + 1] === "&") {
37 endSegment(false);
38 i++;
39 } else if (char === "&") {
40 endSegment(true);
41 } else if (SEPARATORS.has(char)) {
42 endSegment(false);
43 } else if (/\s/.test(char)) {
44 endWord();
45 } else {
46 word = (word ?? "") + char;
47 }
48 }
49 endSegment(false);
50 return out;
51}
52
53const DURATION = /^\d+(?:\.\d+)?[smhd]?$/;
54
55const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
56
57const PREFIXES = new Set([
58 "do",
59 "then",
60 "else",
61 "{",
62 "!",
63 "time",
64 "nohup",
65 "exec",
66 "command",
67 "env",
68 "nice",
69]);
70
71export function splitPrefix(words: string[]): { env: Map<string, string>; argv: string[] } {
72 const env = new Map<string, string>();
73 let i = 0;
74 for (; i < words.length; i++) {
75 const word = words[i] ?? "";
76 if (PREFIXES.has(word)) continue;
77 if (word === "timeout") {
78 while (i + 1 < words.length && !DURATION.test(words[i + 1] ?? "")) i++;
79 i++;
80 continue;
81 }
82 const match = ASSIGNMENT.exec(word);
83 if (match === null) break;
84 env.set(match[1] ?? "", match[2] ?? "");
85 }
86 return { env, argv: words.slice(i) };
87}
88mod/pace.ts 48 lines1import { type Machine, PRESSURE_CRITICAL, PRESSURE_WARN } from "./caps";
2
3/** 0 calm, 1 busy, 2 strained. */
4export type Level = 0 | 1 | 2;
5
6export interface Thresholds {
7 /** Load per core that makes the machine busy; 0 turns reminders off. */
8 remind: number;
9 /** Load per core that makes it strained; 0 leaves only memory pressure. */
10 warn: number;
11}
12
13export function level(machine: Machine, { remind, warn }: Thresholds): Level {
14 if (remind <= 0) return 0;
15 const load = machine.loadPerCore ?? 0;
16 const pressure = machine.pressure ?? 0;
17 if (pressure >= PRESSURE_CRITICAL || (warn > 0 && load >= warn)) return 2;
18 if (pressure >= PRESSURE_WARN || load >= remind) return 1;
19 return 0;
20}
21
22const PRESSURE = new Map([
23 [PRESSURE_WARN, "warning"],
24 [PRESSURE_CRITICAL, "critical"],
25]);
26
27function describe(machine: Machine): string {
28 const facts: string[] = [];
29 if (machine.loadPerCore !== undefined) {
30 facts.push(`load ${machine.loadPerCore.toFixed(1)}x its cores`);
31 }
32 const pressure = PRESSURE.get(machine.pressure ?? 0);
33 if (pressure !== undefined) facts.push(`${pressure} memory pressure`);
34 if (machine.sessions > 1) facts.push(`${machine.sessions} Claude sessions`);
35 if (machine.running.length > 0) facts.push(`running ${machine.running.join(", ")}`);
36 return facts.join("; ");
37}
38
39/** Guidance for the model, or undefined when the machine is calm. */
40export function reminder(machine: Machine, grade: Level): string | undefined {
41 if (grade === 0) return undefined;
42 const facts = describe(machine);
43 if (grade === 1) {
44 return `This machine is busy (${facts}), so the user is likely doing other work on it. Before starting heavy work (builds, test suites, browsers, data jobs), weigh how much it matters to the task now: defer what can wait, prefer targeted tests over full suites, lower worker and thread counts, run one job at a time, and prefix long jobs with \`nice\`.`;
45 }
46 return `This machine is strained (${facts}) and everything on it is slowing down. Start no heavy work the current task does not need. Finish in-flight work with the smallest jobs that will do, one at a time, with minimal worker and thread counts.`;
47}
48