claude-hud
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/jarrodwatts-claude-hud)HTML
<a href="/listings/jarrodwatts-claude-hud"><img src="/api/listings/jarrodwatts-claude-hud/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Inside Claude Code, run:
/plugin marketplace add jarrodwatts/claude-hud /plugin install claude-hud /reload-plugins /hud
`/hud` checks your setup and points your status line at the HUD, after asking you. It needs Node.js 22.18 or later; if yours is older, `/hud` finds a newer one on your machine or helps you install one.
<details> <summary><strong>Prefer the terminal?</strong></summary>
claude plugin marketplace add jarrodwatts/claude-hud claude plugin install claude-hud@claude-hud
Then run `/reload-plugins` and `/hud` inside a session.
</details>
**Updates:** Claude Code doesn't auto-update third-party plugins by default. To turn it on, run `/plugin`, open **Marketplaces**, select **claude-hud**, and choose **Enable auto-update**. Or update by hand with `claude plugin marketplace update claude-hud` and `claude plugin update claude-hud@claude-hud`, then `/reload-plugins`. You don't need to set it up again.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 19 lines
- {
- "name": "claude-hud",
- "owner": {
- "name": "Jarrod Watts"
- },
- "metadata": {
- "description": "Real-time statusline HUD for Claude Code - context health, tool activity, agent tracking, and todo progress",
- "version": "0.15.3"
- },
- "plugins": [
- {
- "name": "claude-hud",
- "source": "./",
- "description": "Real-time statusline showing context usage, active tools, running agents, and todo progress. Always visible below your input, zero config required.",
- "category": "monitoring",
- "tags": ["hud", "statusline", "monitoring", "context", "tools", "agents", "todos"]
- }
- ]
- }
README.md · README · 92 lines
- # Claude HUD
- A Claude Code plugin that shows what's happening: context usage, rate limits, active tools, running agents, and todo progress, always visible below your input.
- [](LICENSE)
- [](https://github.com/jarrodwatts/claude-hud/stargazers)
- 
- > 🌐 English | [中文文档](README.zh.md)
- ## Install
- Inside Claude Code, run:
- ```
- /plugin marketplace add jarrodwatts/claude-hud
- /plugin install claude-hud
- /reload-plugins
- /hud
- ```
- `/hud` checks your setup and points your status line at the HUD, after asking you. It needs Node.js 22.18 or later; if yours is older, `/hud` finds a newer one on your machine or helps you install one.
- <details>
- <summary><strong>Prefer the terminal?</strong></summary>
- ```bash
- claude plugin marketplace add jarrodwatts/claude-hud
- claude plugin install claude-hud@claude-hud
- ```
- Then run `/reload-plugins` and `/hud` inside a session.
- </details>
- **Updates:** Claude Code doesn't auto-update third-party plugins by default. To turn it on, run `/plugin`, open **Marketplaces**, select **claude-hud**, and choose **Enable auto-update**. Or update by hand with `claude plugin marketplace update claude-hud` and `claude plugin update claude-hud@claude-hud`, then `/reload-plugins`. You don't need to set it up again.
- ## What You See
- The default is two lines:
- ```
- [Opus] │ my-project git:(main*)
- Context █████░░░░░ 45% │ Usage ██░░░░░░░░ 25% (resets in 1h 30m)
- ```
- - **Line 1**: model, a provider label when one is detected (`Bedrock`, `Vertex`, `MiniMax`), project path, and git branch.
- - **Line 2**: context used (green, then yellow, then red as it fills) and your subscriber rate limits.
- Optional lines include tools, agents and todos, plus about a hundred other options:
- ```
- ◐ Edit: auth.ts | ✓ Read ×3 | ✓ Grep ×2 ← tools
- ◐ explore [haiku]: Finding auth code (2m 15s) ← agents
- ▸ Fix authentication bug (2/5) ← todos
- ```
- ## Change It, Fix It, Report It
- Ask Claude, or type `/hud` and say what you want: "show tool activity", "use the compact layout", "the HUD is blank", "the context bar looks wrong". Claude looks up the options, shows you a preview, and saves the change once you approve it. `/hud` also undoes the last change, replays the last real render to explain what you see, and, for a real bug, writes a scrubbed report that you read in full before anything is filed.
- Settings live in `~/.claude/plugins/claude-hud/config.json` (under `$CLAUDE_CONFIG_DIR` if set). To turn the HUD off for one session, start Claude Code with `CLAUDE_HUD_DISABLE=1`.
- ## Security
- The HUD's logic runs in a locked-down Node process. Node's permission model blocks it from starting programs, reading your credentials, and writing anywhere but its own data folder. An import fence keeps Node's network modules and globals out of its reach; that fence blocks every way out found so far, and is tested against each one on every change. A small separate file runs the fixed `git`, `jj` and memory commands it needs. The HUD reads Claude Code's stdin, the session transcript, Claude config files, and git or jj metadata for the current directory, and calls no undocumented APIs.
- `--extra-cmd` runs a shell command on every refresh and puts its output on the first line. It is ignored unless `CLAUDE_HUD_ALLOW_EXTRA_CMD=1` is set in the HUD's environment. Treat it as arbitrary code execution and never use a command from an untrusted source.
- ## Requirements
- - Claude Code v2.1.260 or later
- - Node.js 22.18 or later (Bun can start the HUD, which then runs on Node)
- ## Development
- ```bash
- git clone https://github.com/jarrodwatts/claude-hud
- cd claude-hud
- npm ci && npm test
- ```
- See [CONTRIBUTING.md](CONTRIBUTING.md).
- ## License
- MIT. See [LICENSE](LICENSE).
- ## Star History
- [](https://star-history.com/#jarrodwatts/claude-hud&Date)
hud.mjs · Bundled script · 352 lines · 1 finding marked
- // The status line command. Claude Code runs it after each message with a JSON payload on stdin, and
- // ARCHITECTURE.md draws one such render. `node hud.mjs <command>` runs one of the /hud skill's
- // subcommands instead (see COMMANDS). Every check under verify/ runs logic through the same runCage.
- //
- // Every launcher, the one `hud install` copies today included, reaches main() through the stubs
- // dist/index.js (Node) and src/index.ts (Bun).
- // Keep this file's syntax loadable by old Node and Bun, so they can print the upgrade line.
- import { spawn } from 'node:child_process';
- import fs from 'node:fs';
- import path from 'node:path';
- import { fileURLToPath, pathToFileURL } from 'node:url';
- import * as collector from './collector.mjs';
- const ROOT = path.dirname(fileURLToPath(import.meta.url));
- const LOGIC = path.join(ROOT, 'src', 'main.ts');
- const FENCE = pathToFileURL(path.join(ROOT, 'fence.mjs')).href;
- const MAX_OUTPUT_BYTES = 64 * 1024;
- // The cage's wall stops runaway logic, not slow probes, so it sits well above them. Each probe has its
- // own shorter limit, and a slow one blanks only its own element. Git's runs chain: a config read, then
- // status and line diffs, then branch or tag on a timeout, each up to 1-2 s plus 1.5 s on Windows for its
- // worker to start. The extra command may take 3 s.
- const WALL_MS = 10_000;
- // CLAUDE_HUD_DISABLE=1 blanks the HUD for one session while keeping the statusLine setting.
- export function isHudDisabled(env = process.env) {
- const value = env.CLAUDE_HUD_DISABLE?.trim().toLowerCase();
- return !!value && !['0', 'false', 'off', 'no'].includes(value);
- }
- const upgradeLine = (runtime) => `claude-hud needs Node 22.18+ (this is ${runtime}). Type /hud to fix it.`;
- // ---- What may reach the terminal. One allow list: verify/case.mjs judges output with it too.
- // Whole escape sequences (CSI, OSC, other ESC), then single control and bidi characters.
- const ESCAPES = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[ -/]*[0-~]?|[\x00-\x1f\x7f-\x9f--]/g;
- Note: Usual in code (characters a sanitizer strips): Contains 4 bidirectional-override character(s), which make text display in a different order from how it's read
- Line 35 on GitHub
- const SGR = /^\x1b\[[0-9;]*m$/;
- const OSC8 = /^\x1b\]8;;(.*)\x1b\\$/s;
- const GITHUB_NAME = /^[A-Za-z0-9_.-]+$/;
- /**
- * The filter each line passes on its way to the terminal, for the session in `stdin`. It keeps SGR
- * colour, and OSC 8 links to file: URLs or to pages of the GitHub repo Claude Code reported
- * (stdin.workspace.repo). Every other escape sequence is dropped whole, and every other control or
- * bidi character goes. Logic never decides what reaches the terminal.
- */
- export function terminalFilter(stdin) {
- const repo = stdin?.workspace?.repo;
- const pages = repo?.host === 'github.com' && GITHUB_NAME.test(repo.owner ?? '') && GITHUB_NAME.test(repo.name ?? '')
- ? `https://github.com/${repo.owner}/${repo.name}/`
- : null;
- const linkAllowed = (target) => {
- if (target === '') return true; // closes the open link
- try {
- const url = new URL(target);
- // A web link must already be in the parsed form, so no `..` or encoding trick leaves the repo.
- return url.protocol === 'file:' || (pages !== null && url.href === target && target.startsWith(pages));
- } catch {
- return false;
- }
- };
- const keep = (sequence) => {
- const link = OSC8.exec(sequence);
- return SGR.test(sequence) || (link !== null && linkAllowed(link[1]));
- };
- return (line) => String(line).replace(ESCAPES, (sequence) => (keep(sequence) ? sequence : ''));
- }
- function print(lines, stdin = null) {
- if (lines.length === 0) return;
- const filter = terminalFilter(stdin);
- process.stdout.write(lines.map((line) => `${filter(line)}\n`).join(''));
- }
- const NO_DATA_TIMEOUT_MS = 250;
- const IDLE_TIMEOUT_MS = 250;
- const MAX_STDIN_BYTES = 256 * 1024;
- // Null for a TTY (setup's manual run), no input, oversized input, or invalid JSON. Resolves as
- // soon as the buffered text parses, or after incomplete input goes idle.
- export function readStdin(stream = process.stdin) {
- if (stream.isTTY) return Promise.resolve(null);
- return new Promise((resolve) => {
- let raw = '';
- let done = false;
- let idleTimer;
- const finish = (value) => {
- if (done) return;
- done = true;
- clearTimeout(noDataTimer);
- clearTimeout(idleTimer);
- stream.pause();
- resolve(value);
- };
- const parse = () => {
- try {
- const value = JSON.parse(raw);
- return value !== null && typeof value === 'object' ? value : null;
- } catch {
- return null;
- }
- };
- const noDataTimer = setTimeout(() => {
- if (!raw) finish(null);
- }, NO_DATA_TIMEOUT_MS);
- stream.setEncoding('utf8');
- stream.on('data', (chunk) => {
- raw += chunk;
- if (raw.length > MAX_STDIN_BYTES) return finish(null);
- const parsed = parse();
- if (parsed) return finish(parsed);
- clearTimeout(idleTimer);
- idleTimer = setTimeout(() => finish(parse()), IDLE_TIMEOUT_MS);
- });
- stream.on('end', () => finish(parse()));
- stream.on('error', () => finish(null));
- });
- }
- // Logic sees no secrets: no PATH, no tokens. It only learns whether an API key is set, and the
- // base URL without credentials or query.
- const PASSED_ENV = ['HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'SystemRoot', 'TZ', 'LANG', 'LANGUAGE', 'LC_ALL', 'LC_CTYPE',
- 'LC_TIME', 'LC_MESSAGES', 'COLUMNS', 'DEBUG', 'CLAUDE_CONFIG_DIR', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX'];
- export function cageEnv(env = process.env) {
- const caged = { PATH: '' };
- for (const name of PASSED_ENV) if (typeof env[name] === 'string') caged[name] = env[name];
- if (env.ANTHROPIC_API_KEY?.trim()) caged.ANTHROPIC_API_KEY = 'set';
- for (const name of ['ANTHROPIC_BASE_URL', 'ANTHROPIC_API_BASE_URL']) {
- try {
- const url = new URL(env[name]?.trim() ?? '');
- caged[name] = `${url.origin}${url.pathname}`;
- } catch { /* unset or not a URL */ }
- }
- return caged;
- }
- /**
- * Node flags for the cage. Never --allow-child-process, --allow-worker, --allow-addons or --allow-wasi.
- * --disallow-code-generation-from-strings only stops eval and new Function. It is no wall: logic could
- * write a module and import it. The wall is fence.mjs, which loads nothing from outside the plugin,
- * while data/, the one place logic writes, is never inside the plugin. For the same reason there is no
- * compile cache logic can write: Node trusts a cache entry by its crc32, so such a cache would let it
- * plant code for the next render. The one cache, stripped/, is written by collector.mjs and only read
- * by logic. `audit` swaps --permission for --permission-audit: nothing is denied, and fence.mjs
- * reports each access outside the grants.
- */
- export function cageArgs({ grants, dataDir, entry = LOGIC, audit = false }) {
- return [audit ? '--permission-audit' : '--permission', ...grants.map((grant) => `--allow-fs-read=${grant}`),
- ...(dataDir ? [`--allow-fs-write=${dataDir}`] : []), '--disallow-code-generation-from-strings', `--import=${FENCE}`, entry];
- }
- const isInside = (file, dir) => {
- const relative = path.relative(dir, file);
- return !relative.startsWith('..') && !path.isAbsolute(relative);
- };
- /**
- * The one way logic runs: for a render, for a subcommand, and for every check under verify/.
- * stdin Claude Code's payload, or null now the render's one clock reading
- * probes names => answers: collector.createProbes for a real render, recorded facts in the corpus
- * env the environment; its HOME and CLAUDE_CONFIG_DIR place data/ and every path logic reads
- * entry the logic to run (the escape matrix runs its probe instead)
- * audit see cageArgs
- * command a /hud subcommand, { name, args, facts }, instead of a render
- * Resolves with logic's { lines, snapshot?, config?, failed? }, plus `outside` (the accesses outside
- * the grants) in audit mode.
- */
- export async function runCage({ stdin = null, now = Date.now(), probes = async () => ({}), env = process.env, entry = LOGIC, audit = false, command }) {
- const paths = collector.claudePaths(env);
- let dataDir = null;
- try {
- dataDir = collector.prepareDataDir(paths);
- } catch { /* a read-only home only costs the caches and the cost ledger */ }
- if (dataDir && isInside(dataDir, fs.realpathSync(ROOT))) dataDir = null;
- // A subcommand's project is the folder Claude Code ran it in.
- const named = collector.logicPaths(paths, command ? { ...stdin, cwd: command.facts.cwd } : stdin);
- if (dataDir) named.data = dataDir;
- const stripped = collector.stripLogic(paths.strippedDir, ROOT);
- const grants = collector.readGrants(ROOT, { ...named, stripped: stripped?.dir });
- return new Promise((resolve, reject) => {
- const child = spawn(process.execPath, cageArgs({ grants, dataDir, entry, audit }), {
- env: { ...cageEnv(env), ...(stripped ? { CLAUDE_HUD_STRIPPED: JSON.stringify({ dir: path.join(stripped.dir, path.sep), files: stripped.files }) } : {}) },
- stdio: ['pipe', 'pipe', 'pipe'],
- windowsHide: true,
- });
- let settled = false;
- let output = null;
- let stderr = '';
- const settle = (error, value) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- child.stdin.end();
- if (error) {
- child.kill('SIGKILL');
- reject(error);
- } else {
- resolve(value);
- }
- };
- const timer = setTimeout(() => settle(new Error('timed out')), WALL_MS);
- const send = (message) => {
- if (!settled) child.stdin.write(`${JSON.stringify(message)}\n`);
- };
- let buffered = '';
- let bytes = 0;
- child.stdout.setEncoding('utf8');
- child.stdout.on('data', (chunk) => {
- bytes += Buffer.byteLength(chunk);
- if (bytes > MAX_OUTPUT_BYTES) return settle(new Error('output too large'));
- buffered += chunk;
- for (let newline = buffered.indexOf('\n'); newline !== -1; newline = buffered.indexOf('\n')) {
- let message;
- try {
- message = JSON.parse(buffered.slice(0, newline));
- } catch {
- return settle(new Error('unreadable output'));
- }
- buffered = buffered.slice(newline + 1);
- if (Array.isArray(message?.lines)) {
- output = { lines: message.lines.map(String), snapshot: message.snapshot, config: message.config, failed: message.failed === true };
- // In audit mode the report comes as logic exits, which closing its input makes it do.
- if (audit) child.stdin.end();
- else return settle(null, output);
- } else if (Number.isSafeInteger(message?.id)) {
- Promise.resolve().then(() => probes(message.ask)).catch(() => ({})).then((answers) => send({ id: message.id, answers }));
- }
- }
- });
- child.stderr.setEncoding('utf8');
- child.stderr.on('data', (chunk) => {
- if (audit) stderr = (stderr + chunk).slice(-MAX_OUTPUT_BYTES);
- if (env.DEBUG) process.stderr.write(chunk);
- });
- child.stdin.on('error', () => {});
- child.on('error', (error) => settle(error));
- child.on('close', (code) => {
- if (!output) return settle(new Error(`logic exited with code ${code}`));
- const report = stderr.split('\n').findLast((line) => line.startsWith('claude-hud audit '));
- settle(null, audit ? { ...output, outside: report ? JSON.parse(report.slice('claude-hud audit '.length)) : ['no audit report'] } : output);
- });
- probes.start?.(); // after the spawn: logic's startup is the long pole
- send({ stdin, now, paths: named, ...(command ? { command } : {}) });
- });
- }
- // Bun has no permission model, so logic always runs on Node: hand the whole run to `node`, found the
- // way the collector finds git (on Windows, only in absolute PATH entries, never the repo's folder).
- function relayToNode(argv) {
- const node = process.platform === 'win32' ? collector.resolveWindowsExecutable('node') : 'node';
- return new Promise((resolve) => {
- if (!node) {
- print([upgradeLine(`Bun ${process.versions.bun}`)]);
- return resolve();
- }
- const child = spawn(node, [path.join(ROOT, 'hud.mjs'), ...argv.slice(2)], { stdio: 'inherit' });
- child.on('error', () => resolve(print([upgradeLine(`Bun ${process.versions.bun}`)])));
- child.on('close', (code) => {
- if (code) process.exitCode = code;
- resolve();
- });
- });
- }
- // The /hud skill's subcommands. All but install run as logic in the cage, like a render.
- const COMMANDS = ['doctor', 'schema', 'preview', 'set', 'report', 'install'];
- // The skill reads doctor's and report's answers as facts without asking (doctor before the model reads a
- // word), so hud.mjs writes those answers as JSON itself. Whatever logic says stays inside JSON strings,
- // one line each, and can't pass for the skill's own text. Prose comes out as an array of its lines.
- const FACTS = ['doctor', 'report'];
- export function asJson(lines) {
- let value;
- try {
- value = JSON.parse(lines.join('\n'));
- } catch {
- value = lines;
- }
- return JSON.stringify(value, null, 2).split('\n');
- }
- async function runCommand(name, args, { paths, env }) {
- const facts = collector.commandFacts({ root: ROOT, paths, env });
- const printJson = (value) => process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
- if (!facts.runtime.supported) {
- // Old Node can't run the cage, but doctor can still say what to upgrade to.
- if (name === 'doctor') {
- const { runtime, plugin, runtimes, heartbeat } = facts;
- return printJson({
- runtime, plugin, runtimes,
- lastRender: heartbeat && { at: heartbeat.at, runtime: heartbeat.runtime, path: heartbeat.path, outcome: heartbeat.outcome },
- findings: [`This is ${runtime.name} ${runtime.version}; the HUD needs Node 22.18+. Fix: rerun with a supported runtime from runtimes, or install one.`],
- });
- }
- process.exitCode = 1;
- return print([upgradeLine(process.version)]);
- }
- try {
- if (name === 'install') return printJson((await import('./install.mjs')).install({ configDir: paths.configDir, argv: args, env }));
- if (name === 'set' && args[0] === '--undo') {
- collector.undoConfig(paths);
- return print(['Restored config.json from before the last `hud set`.']);
- }
- // The last render's input, saved by hud.mjs from Claude Code, so preview and report can replay it.
- const stdin = facts.heartbeat?.stdin ?? null;
- const probes = collector.createProbes({ cwd: stdin?.cwd, argv: [], env, usage: collector.usagePaths(paths, env) });
- const output = await runCage({ stdin, env, probes, command: { name, args, facts } });
- // Only `set`, which Claude Code asks the user about, may change config; the rest are pre-approved.
- if (name === 'set' && output.config) collector.writeConfig(paths, output.config);
- if (output.failed) process.exitCode = 1;
- print(FACTS.includes(name) ? asJson(output.lines) : output.lines, stdin);
- } catch (error) {
- process.exitCode = 1;
- print([`claude-hud ${name}: ${error instanceof Error ? error.message : 'Unknown error'}`]);
- }
- }
- export async function main({ argv = process.argv, env = process.env } = {}) {
- const command = COMMANDS.includes(argv[2]) ? argv[2] : null;
- if (!command && isHudDisabled(env)) return;
- if (process.versions.bun) return relayToNode(argv);
- const paths = collector.claudePaths(env);
- if (command) return runCommand(command, argv.slice(3), { paths, env });
- if (!collector.isNodeSupported(process.versions.node)) {
- collector.writeHeartbeat(paths, { outcome: 'upgrade', env });
- return print([upgradeLine(process.version)]);
- }
- const now = Date.now();
- let stdin = null;
- try {
- stdin = await readStdin();
- const setting = collector.userSettings(paths);
- const usage = collector.usagePaths(paths, env, setting);
- const probes = collector.createProbes({ cwd: stdin?.cwd, argv, env, usage, early: collector.probesToStart(setting) });
- const output = await runCage({ stdin, now, probes, env });
- if (output.snapshot) collector.writeUsageSnapshot(usage.write, output.snapshot);
- print(output.lines, stdin);
- // Without input this is a person running the command by hand; keep Claude Code's last render.
- if (stdin) collector.writeHeartbeat(paths, { outcome: output.failed ? output.lines[0] ?? 'failed' : 'ok', stdin, now, env });
- } catch (error) {
- const message = `[claude-hud] Error: ${error instanceof Error ? error.message : 'Unknown error'}`;
- print([`${message}. Type /hud to fix it.`]);
- collector.writeHeartbeat(paths, { outcome: message, stdin, now, env });
- }
- }
- const ENTRIES = [path.join(ROOT, 'hud.mjs'), path.join(ROOT, 'dist', 'index.js'), path.join(ROOT, 'src', 'index.ts')];
- if (process.argv[1] && ENTRIES.some((entry) => collector.samePath(process.argv[1], entry))) {
- await main();
- }
maintainer/harness.mjs · Bundled script · 184 lines · 1 finding marked
- // The maintainer harness (owner-owned). It runs on a fresh GitHub VM as `runner`, which has passwordless sudo.
- // It builds the inbox, keeps the subscription token inside the relay, jails Claude as the unix user `agent`
- // (no sudo, network = the relay only), proves the jail with the reach probe, and collects what Claude left as plain data.
- // RELAY_TOKEN=<subscription token> node maintainer/harness.mjs <out dir>
- import fs from 'node:fs';
- import http from 'node:http';
- import https from 'node:https';
- import crypto from 'node:crypto';
- import path from 'node:path';
- import { execFileSync, spawn } from 'node:child_process';
- import { scorecard } from './scorecard.mjs';
- import { installClaudeCode } from '../verify/lib/claude-code.mjs';
- const MODEL = 'claude-opus-5-5';
- const TOOLS = 'Bash,Read,Edit,Write,Glob,Grep,Task';
- const JAIL = '/tmp/maint';
- const PORT = 8642; // the relay, and the only place `agent` may connect to
- const env = process.env;
- const TOKEN = env.RELAY_TOKEN;
- delete env.RELAY_TOKEN;
- const UPSTREAM = new URL(env.RELAY_UPSTREAM ?? 'https://api.anthropic.com');
- const BUDGET = Number(env.RELAY_BUDGET ?? 3e6); // input + cache-write + output tokens per run
- const DAILY_BUDGET = Number(env.RELAY_DAILY_BUDGET ?? 4 * BUDGET); // across every run in the last 24 hours
- const AGENT_EVENTS = ['issues', 'issue_comment', 'schedule', 'workflow_dispatch']; // the agent job's events; maintain.yml names them twice more, and the maintainer check holds all three equal
- const [outDir] = process.argv.slice(2);
- const sh = (cmd, ...args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] }).trim();
- const agent = (...args) => ['-u', 'agent', 'env', '-i', '-C', `${JAIL}/repo`, 'HOME=/home/agent',
- `PATH=${path.dirname(process.execPath)}:/usr/local/bin:/usr/bin:/bin`, ...args];
- const run = (args, ms) => new Promise((done) => { // async, so the relay in this process keeps serving
- const p = spawn('sudo', args, { stdio: ['ignore', 'pipe', 'inherit'] });
- const timer = ms && setTimeout(() => spawn('sudo', ['pkill', '-KILL', '-u', 'agent']), ms);
- let out = '';
- p.stdout.on('data', (c) => (out += c));
- p.on('close', (code) => { clearTimeout(timer); done({ code, out }); });
- });
- const gh = async (p) => {
- const r = await fetch(`${env.GITHUB_API_URL ?? 'https://api.github.com'}/repos/${env.GITHUB_REPOSITORY}/${p}`, { headers: { authorization: `Bearer ${env.GITHUB_TOKEN}` } });
- if (!r.ok) throw new Error(`GET ${p}: ${r.status}`);
- return p.includes('/logs') ? (await r.text()).slice(-3000) : r.json();
- };
- if (!TOKEN) { console.log('maintainer inactive: no RELAY_TOKEN'); process.exit(0); }
- // 0. The daily cap. Each agent run of the last 24 hours counts what its relay recorded (the artifact
- // relay-tokens-<n>), or its whole per-run budget if it recorded nothing, since it may have died
- // mid-spend. Anything unreadable throws, so no run starts: the cap fails closed.
- const dayAgo = new Date(Date.now() - 864e5);
- const recent = [];
- for (const event of AGENT_EVENTS) {
- for (let page = 1; ; page++) {
- const { workflow_runs: runs } = await gh(`actions/workflows/maintain.yml/runs?event=${event}&created=>=${dayAgo.toISOString().slice(0, 10)}&per_page=100&page=${page}`);
- recent.push(...runs.filter((r) => r.event === event && new Date(r.created_at) > dayAgo && r.id !== Number(env.GITHUB_RUN_ID)));
- if (runs.length < 100) break;
- if (page === 5) throw new Error(`over 500 ${event} runs in two days: not starting`);
- }
- }
- let spentToday = 0;
- for (const r of recent) {
- const recorded = (await gh(`actions/runs/${r.id}/artifacts`)).artifacts.map((a) => /^relay-tokens-(\d+)$/.exec(a.name)?.[1]).find(Boolean);
- if (recorded) spentToday += Number(recorded);
- else if ((await gh(`actions/runs/${r.id}/jobs`)).jobs.some((j) => j.name === 'agent' && j.conclusion !== 'skipped' && j.steps?.length)) spentToday += BUDGET;
- }
- const budget = Math.min(BUDGET, DAILY_BUDGET - spentToday);
- console.log(`relay: ${spentToday} of the daily ${DAILY_BUDGET} tokens spent in the last 24 hours; this run may spend ${Math.max(0, budget)}`);
- if (budget <= 0) { // records a spend of 0, so this run doesn't count against the next day's cap
- console.log('maintainer paused: the daily token cap is spent');
- fs.mkdirSync(outDir, { recursive: true });
- fs.writeFileSync(`${outDir}/relay.json`, JSON.stringify({ model: MODEL, budget: 0, spent: 0 }));
- if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, 'tokens=0\noutbox=no\n');
- process.exit(0);
- }
- // 1. The inbox, read with the job's read-only token, plus the frozen scorecard.
- const since = new Date(Date.now() - 14 * 864e5).toISOString();
- const [items, comments, failed] = await Promise.all([gh(`issues?state=all&since=${since}&per_page=100`),
- gh(`issues/comments?since=${since}&per_page=100`), gh('actions/runs?status=failure&per_page=20')]);
- const cut = (s) => (s ?? '').slice(0, 4000);
- const ci = await Promise.all(failed.workflow_runs.filter((r) => r.head_branch.startsWith('bot/')).slice(0, 5).map(async (r) => ({
- workflow: r.name, branch: r.head_branch, sha: r.head_sha, failed_jobs: await Promise.all((await gh(`actions/runs/${r.id}/jobs`)).jobs
- .filter((j) => j.conclusion === 'failure').map(async (j) => ({ name: j.name, log_tail: await gh(`actions/jobs/${j.id}/logs`) }))) })));
- const inbox = { repo: env.GITHUB_REPOSITORY, now: new Date().toISOString(), scorecard: await scorecard(gh), ci, items: items.map((i) => ({
- number: i.number, kind: i.pull_request ? 'pr' : 'issue', state: i.state, title: i.title, body: cut(i.body), author: i.user.login,
- role: i.author_association, labels: i.labels.map((l) => l.name), updated: i.updated_at, comments: comments.filter((c) => c.issue_url === i.url)
- .map((c) => ({ author: c.user.login, role: c.author_association, at: c.created_at, body: cut(c.body) })) })) };
- // 2. The relay: the only holder of the token. Only POST /v1/messages, model pinned, 400 once the budget is spent
- // (Claude retries a 429 for minutes but stops on a 400). Usage is only known once a reply ends, so each
- // request first reserves the most it could cost, its prompt (a token is never shorter than a byte) plus
- // its max_tokens, and is refused if that doesn't fit: requests sent at once can't overrun the budget
- // together. A reply whose usage it can't read spends the whole budget: accounting that can't count
- // must not keep spending.
- let spent = 0;
- let reserved = 0;
- const usage = (text) => ['input_tokens', 'cache_creation_input_tokens', 'output_tokens']
- .reduce((sum, k) => sum + Math.max(0, ...[...text.matchAll(new RegExp(`"${k}":(\\d+)`, 'g'))].map((m) => Number(m[1]))), 0);
- const placeholder = `relay-${crypto.randomUUID()}`;
- const relay = http.createServer((req, res) => {
- const deny = (why) => { console.log(`relay: refused ${req.method} ${req.url}: ${why}`); if (res.headersSent) return res.destroy();
- res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: `relay: ${why}` } })); };
- if (req.headers.authorization !== `Bearer ${placeholder}`) return deny('wrong placeholder');
- if (req.method !== 'POST' || !/^\/v1\/messages(\/count_tokens)?(\?beta=true)?$/.test(req.url)) return deny('only POST /v1/messages');
- if (spent >= budget) return deny(`run budget of ${budget} tokens spent`);
- let body = '';
- req.on('data', (c) => (body += c)).on('end', () => {
- let request; try { request = JSON.parse(body); } catch { return deny('body is not JSON'); }
- const out = JSON.stringify({ ...request, model: MODEL });
- const most = Buffer.byteLength(out) + (Number.isSafeInteger(request.max_tokens) && request.max_tokens > 0 ? request.max_tokens : budget);
- if (spent + reserved + most > budget) return deny(`run budget of ${budget} tokens: ${spent} spent and ${reserved} held by requests in flight, so this one, which could cost ${most}, can't start`);
- reserved += most;
- let held = most;
- const release = () => { reserved -= held; held = 0; };
- const { 'accept-encoding': _, 'x-api-key': __, ...headers } = req.headers; // plain text back, so usage can be counted
- const up = (UPSTREAM.protocol === 'https:' ? https : http).request(new URL(req.url, UPSTREAM), { method: 'POST',
- headers: { ...headers, host: UPSTREAM.host, authorization: `Bearer ${TOKEN}`, 'content-length': Buffer.byteLength(out) } }, (r) => {
- let text = '';
- res.writeHead(r.statusCode, r.headers);
- r.on('data', (c) => { text += c; res.write(c); }).on('end', () => {
- res.end();
- release();
- const counted = usage(text);
- if (r.statusCode === 200 && counted === 0) console.log(`relay: no usage readable in the reply to ${req.url}; counting the whole budget`);
- spent = r.statusCode === 200 && counted === 0 ? budget : spent + counted;
- console.log(`relay: ${req.url} ${r.statusCode}, ${spent}/${budget} tokens`);
- });
- });
- up.on('error', (e) => { release(); deny(`upstream ${e.code}`); }).end(out);
- });
- });
- await new Promise((ok) => relay.listen(PORT, '127.0.0.1', ok));
- // 3. The jail: user `agent` may connect to the relay and nothing else, the runner's home closed, a fresh clone, and a canary to catch leaks.
- sh('sudo', 'install', '-m', '755', installClaudeCode('/tmp/claude-code'), '/usr/local/bin/claude'); // pinned, checksum checked
- if (!fs.existsSync('/home/agent')) {
- sh('sudo', 'useradd', '--create-home', 'agent');
- sh('sudo', 'iptables', '-A', 'OUTPUT', '-m', 'owner', '--uid-owner', 'agent', '-d', '127.0.0.1', '-p', 'tcp', '--dport', String(PORT), '-j', 'ACCEPT');
- for (const t of ['iptables', 'ip6tables']) sh('sudo', t, '-A', 'OUTPUT', '-m', 'owner', '--uid-owner', 'agent', '-j', 'REJECT');
- }
- sh('sudo', 'chmod', '700', env.HOME); // holds the workspace, step scripts and the runner itself
- sh('sudo', 'rm', '-rf', JAIL);
- fs.mkdirSync(JAIL, { mode: 0o711 });
- fs.mkdirSync(`${JAIL}/out`);
- sh('git', 'clone', '--quiet', '--no-hardlinks', process.cwd(), `${JAIL}/repo`);
- const prs = items.filter((i) => i.pull_request && i.state === 'open').map((i) => `+refs/pull/${i.number}/head:refs/remotes/pr/${i.number}`);
- if (prs.length) sh('git', '-C', `${JAIL}/repo`, 'fetch', '--quiet', `https://github.com/${env.GITHUB_REPOSITORY}`, ...prs);
- execFileSync('npm', ['ci', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: `${JAIL}/repo`, stdio: 'ignore' }); // the agent has no network
- fs.writeFileSync(`${JAIL}/inbox.json`, JSON.stringify(inbox, null, 1));
- fs.copyFileSync(new URL('probe.mjs', import.meta.url), `${JAIL}/probe.mjs`);
- sh('sudo', 'chown', '-R', 'agent:agent', `${JAIL}/repo`, `${JAIL}/out`);
- const canary = `ghp_${crypto.randomBytes(18).toString('hex')}`;
- execFileSync('sudo', ['-u', 'agent', 'sh', '-c', 'mkdir -p /home/agent/.config/gh && cat > /home/agent/.config/gh/hosts.yml'], { input: `github.com:\n oauth_token: ${canary}\n` });
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 150 on GitHub
- // 4. The reach probe, as `agent`. Anything reachable aborts the run.
- const probe = await run(agent('node', `${JAIL}/probe.mjs`, String(PORT), placeholder, String(process.pid), env.HOME, env.RUNNER_TEMP), 120e3);
- console.log(probe.out);
- if (probe.code !== 0) throw new Error('the reach probe found a way out of the jail: run aborted');
- // 5. Claude, as `agent`. It acts only through its final answer, which must match the outbox schema.
- const prompt = `You maintain this repository. Read maintainer/PLAYBOOK.md first and follow it. ${JAIL}/inbox.json holds the GitHub state;
- open PRs are fetched as refs/remotes/pr/<number>. You have no network and no GitHub access: you act only through your final answer.
- To propose a change, save \`git diff\` against main to ${JAIL}/out/<slug>.patch and add a propose action with that slug.`;
- const claude = await run(agent(`ANTHROPIC_BASE_URL=http://127.0.0.1:${PORT}`, `CLAUDE_CODE_OAUTH_TOKEN=${placeholder}`, `GH_TOKEN=${canary}`,
- 'DISABLE_AUTOUPDATER=1', 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1', 'CLAUDE_CODE_DISABLE_AUTO_MEMORY=1',
- 'claude', '-p', prompt, '--model', MODEL, '--output-format', 'json', '--no-session-persistence',
- '--json-schema', fs.readFileSync(new URL('outbox.schema.json', import.meta.url), 'utf8'),
- '--restricted', '--add-dir', JAIL, '--tools', TOOLS, '--allowedTools', TOOLS, '--permission-mode', 'dontAsk', '--permission-prompts', 'none'), 45 * 6e4);
- // 6. Collect: kill everything `agent` left running, then keep only regular files it owns, under size caps, free of the canary.
- await run(['pkill', '-KILL', '-u', 'agent']);
- relay.close();
- const result = (() => { try { return JSON.parse(claude.out); } catch { return {}; } })();
- console.log(`claude exit ${claude.code}: ${result.is_error ? result.result : (result.subtype ?? 'no result')}; relay spent ${spent} tokens`);
- const files = { 'relay.json': JSON.stringify({ model: MODEL, budget, spent }) };
- if (result.structured_output) files['outbox.json'] = JSON.stringify(result.structured_output, null, 1);
- const uid = Number(sh('id', '-u', 'agent'));
- for (const name of fs.readdirSync(`${JAIL}/out`)) {
- const st = fs.lstatSync(`${JAIL}/out/${name}`);
- if (/^[a-z0-9-]{3,40}\.patch$/.test(name) && st.isFile() && st.uid === uid && st.size < 256e3) files[`patches/${name}`] = fs.readFileSync(`${JAIL}/out/${name}`, 'utf8');
- else console.log(`ignored out/${name}`);
- }
- const leaks = [canary, Buffer.from(canary).toString('base64'), Buffer.from(canary).toString('hex'), [...canary].reverse().join('')];
- if (Object.values(files).some((text) => leaks.some((l) => text.includes(l)))) throw new Error('the canary left the jail: run aborted');
- fs.mkdirSync(`${outDir}/patches`, { recursive: true });
- for (const [name, text] of Object.entries(files)) fs.writeFileSync(`${outDir}/${name}`, text);
- if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `tokens=${spent}\noutbox=${files['outbox.json'] ? 'yes' : 'no'}\n`);
src/utils/sanitize.ts · Bundled script · 18 lines · 1 finding marked
- import { truncateString } from './truncate.ts';
- // C0 and C1 controls, DEL, and the bidi marks, embeddings, overrides, and isolates.
- const CONTROL_AND_BIDI = /[\u0000-\u001F\u007F-\u009F---]/g;
- Note: Usual in code (characters a sanitizer strips): Contains 4 bidirectional-override character(s), which make text display in a different order from how it's read
- Line 4 on GitHub
- /** Untrusted text made safe to print: no escape sequences, controls, or bidi overrides. */
- export function sanitizeDisplayText(input: string): string {
- return input
- .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '')
- .replace(/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)/g, '')
- .replace(/\x1B[@-Z\\-_]/g, '')
- .replace(CONTROL_AND_BIDI, '');
- }
- /** An untrusted value as a printable label: sanitized, trimmed, and cut on a grapheme boundary. '' if not a string. */
- export function displayLabel(value: unknown, maxLength: number, suffix = ''): string {
- return typeof value === 'string' ? truncateString(sanitizeDisplayText(value).trim(), maxLength, suffix) : '';
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.