@ulm0/gonogo 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +24 -2
- package/bin/gonogo.js +18 -0
- package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
- package/dist/client/apple-touch-icon.png +0 -0
- package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
- package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
- package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/dist/client/assets/index-BqCn1SM7.js +50 -0
- package/dist/client/assets/index-KZtFVMJG.css +1 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +19 -0
- package/dist/server/audited.js +133 -0
- package/dist/server/blackbox.js +261 -0
- package/dist/server/board.js +123 -0
- package/dist/server/cleanroom.js +214 -0
- package/dist/server/clearance.js +158 -0
- package/dist/server/cli.js +763 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +465 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/hangar.js +311 -0
- package/dist/server/home.js +520 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2642 -0
- package/dist/server/launcher.js +547 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logchart.js +58 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/massbudget.js +169 -0
- package/dist/server/mcp.js +228 -0
- package/dist/server/migrate.js +122 -0
- package/dist/server/missionlog.js +211 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +199 -0
- package/dist/server/recorder.js +176 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/relief.js +226 -0
- package/dist/server/rollout.js +172 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/telemetry.js +110 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1607 -0
- package/dist/shared/cron.js +149 -0
- package/dist/shared/fuel.js +18 -0
- package/dist/shared/livery.js +348 -0
- package/dist/shared/positions.js +132 -0
- package/dist/shared/protocol.js +245 -0
- package/package.json +84 -3
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plot Board: the one current plan of the room (docs/plot-board-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* One file, `<home>/board.md`: a small front matter (version, revision, author, updatedAt; each value JSON on one line) and then the
|
|
5
|
+
* plan as plain text. The Director (the browser route) and the boss (the MCP tool board_write) write it; every agent reads it. Who
|
|
6
|
+
* may write is decided by the caller (the route is the Director's, the tool checks for the boss): this store only checks the text and
|
|
7
|
+
* the revision. A write names the revision it read and is refused when the board has moved on, so a write never replaces text its
|
|
8
|
+
* author did not see. The file is written whole to a temporary file and renamed. A file without our front matter (written by hand) is
|
|
9
|
+
* read as the plan itself. The clock is injected for tests.
|
|
10
|
+
*
|
|
11
|
+
* shortcut: a hand edit made while gonogo runs is not seen until the next start, and the next write replaces it; read the file again
|
|
12
|
+
* on each get if that ever matters.
|
|
13
|
+
*/
|
|
14
|
+
import { randomBytes } from 'node:crypto';
|
|
15
|
+
import { readFile, rename, stat, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { BOARD_MAX_CHARS } from '../shared/protocol.js';
|
|
18
|
+
import { BOARD_FILE, FILE_MODE } from './constants.js';
|
|
19
|
+
import { isRecord } from './hooks.js';
|
|
20
|
+
import { HubError } from './hub.js';
|
|
21
|
+
const FIELDS = ['text', 'revision'];
|
|
22
|
+
/** The keys of our front matter; a file whose first lines are anything else is a plan written by hand. */
|
|
23
|
+
const FRONT_KEYS = ['version', 'revision', 'author', 'updatedAt'];
|
|
24
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
25
|
+
const render = (view) => [
|
|
26
|
+
'---',
|
|
27
|
+
'version: 1',
|
|
28
|
+
`revision: ${JSON.stringify(view.revision)}`,
|
|
29
|
+
`author: ${JSON.stringify(view.author)}`,
|
|
30
|
+
`updatedAt: ${JSON.stringify(view.updatedAt === null ? null : new Date(view.updatedAt).toISOString())}`,
|
|
31
|
+
'---',
|
|
32
|
+
view.text,
|
|
33
|
+
'',
|
|
34
|
+
].join('\n');
|
|
35
|
+
/** The board in a file; one that has our front matter is read by it, any other text is the plan itself. */
|
|
36
|
+
function parse(text, mtime, path) {
|
|
37
|
+
const found = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text.replace(/\r\n/g, '\n'));
|
|
38
|
+
const values = new Map();
|
|
39
|
+
try {
|
|
40
|
+
for (const line of found === null ? [] : (found[1] ?? '').split('\n')) {
|
|
41
|
+
const at = line.indexOf(': ');
|
|
42
|
+
if (at < 0 || !FRONT_KEYS.includes(line.slice(0, at)))
|
|
43
|
+
throw new Error('not ours');
|
|
44
|
+
values.set(line.slice(0, at), JSON.parse(line.slice(at + 2)));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
values.clear();
|
|
49
|
+
}
|
|
50
|
+
if (found === null || values.size === 0)
|
|
51
|
+
return { text: text.replace(/\r\n/g, '\n').trimEnd().slice(0, BOARD_MAX_CHARS), revision: 0, author: null, updatedAt: mtime };
|
|
52
|
+
const { version, revision, author, updatedAt } = Object.fromEntries(values);
|
|
53
|
+
if (version !== undefined && version !== 1) {
|
|
54
|
+
throw new Error(`${path} was saved by a newer gonogo (format version ${String(version)}; this one reads up to 1). Start the gonogo that saved it, or move the file away to start without it.`);
|
|
55
|
+
}
|
|
56
|
+
const at = typeof updatedAt === 'string' ? Date.parse(updatedAt) : Number.NaN;
|
|
57
|
+
return {
|
|
58
|
+
text: (found[2] ?? '').replace(/\n$/, '').slice(0, BOARD_MAX_CHARS),
|
|
59
|
+
revision: typeof revision === 'number' && Number.isSafeInteger(revision) && revision >= 0 ? revision : 0,
|
|
60
|
+
author: typeof author === 'string' && author !== '' ? author : null,
|
|
61
|
+
updatedAt: Number.isNaN(at) ? mtime : at,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function createBoard(options) {
|
|
65
|
+
const { now } = options;
|
|
66
|
+
const path = join(options.dir, BOARD_FILE);
|
|
67
|
+
let current = { text: '', revision: 0, author: null, updatedAt: null };
|
|
68
|
+
let chain = Promise.resolve();
|
|
69
|
+
/** One write at a time, so that two writers of one revision cannot both succeed; a failure goes to the caller and the next write goes on. */
|
|
70
|
+
const locked = (fn) => {
|
|
71
|
+
const run = chain.then(fn);
|
|
72
|
+
chain = run.catch(() => undefined);
|
|
73
|
+
return run;
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
async load() {
|
|
77
|
+
let text;
|
|
78
|
+
try {
|
|
79
|
+
text = await readFile(path, 'utf8');
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code === 'ENOENT')
|
|
83
|
+
return;
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
current = parse(text, (await stat(path)).mtimeMs, path);
|
|
87
|
+
},
|
|
88
|
+
get: () => ({ ...current }),
|
|
89
|
+
write(by, input) {
|
|
90
|
+
return locked(async () => {
|
|
91
|
+
if (!isRecord(input))
|
|
92
|
+
throw bad('request body must be a JSON object');
|
|
93
|
+
for (const key of Object.keys(input))
|
|
94
|
+
if (!FIELDS.includes(key))
|
|
95
|
+
throw bad(`unknown field "${key}"`, key);
|
|
96
|
+
if (typeof input.text !== 'string')
|
|
97
|
+
throw bad('text is required', 'text');
|
|
98
|
+
const text = input.text.replace(/\r\n?/g, '\n').trimEnd();
|
|
99
|
+
if (text.length > BOARD_MAX_CHARS)
|
|
100
|
+
throw bad(`text must be at most ${BOARD_MAX_CHARS} characters`, 'text');
|
|
101
|
+
if (text.includes('\0'))
|
|
102
|
+
throw bad('text must not hold a NUL character', 'text');
|
|
103
|
+
if (typeof input.revision !== 'number' || !Number.isSafeInteger(input.revision) || input.revision < 0)
|
|
104
|
+
throw bad('revision must be a whole number, the one you read', 'revision');
|
|
105
|
+
if (input.revision !== current.revision) {
|
|
106
|
+
throw new HubError('conflict', `the Plot Board is at revision ${current.revision}, not ${input.revision}: read it again, then write`, 'revision');
|
|
107
|
+
}
|
|
108
|
+
// the same text again changes nothing: no new revision, no new file
|
|
109
|
+
if (text === current.text)
|
|
110
|
+
return { ...current };
|
|
111
|
+
const next = { text, revision: current.revision + 1, author: by, updatedAt: now() };
|
|
112
|
+
const tmp = join(options.dir, `.${BOARD_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
113
|
+
await writeFile(tmp, render(next), { mode: FILE_MODE, flag: 'wx' });
|
|
114
|
+
await rename(tmp, path);
|
|
115
|
+
current = next;
|
|
116
|
+
return { ...current };
|
|
117
|
+
});
|
|
118
|
+
},
|
|
119
|
+
close() {
|
|
120
|
+
return chain.then(() => undefined);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clean Room (docs/clean-room-spec.md): an agent that runs in a container on its own git worktree. This file reads the
|
|
3
|
+
* setting, checks Docker and the repository, makes the worktree once and builds the `docker run` arguments. The launcher
|
|
4
|
+
* puts them together with the files and the environment of a Claude Code start.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { lookup } from 'node:dns/promises';
|
|
9
|
+
import { lstat, mkdir, realpath, stat } from 'node:fs/promises';
|
|
10
|
+
import { hostname } from 'node:os';
|
|
11
|
+
import { basename, dirname, join, relative } from 'node:path';
|
|
12
|
+
import { CLEAN_ROOM_DIR, cleanRoomBranch } from '../shared/protocol.js';
|
|
13
|
+
import { CLEAN_ROOM_COMMAND_MS, CLEAN_ROOM_DEFAULT_IMAGE, CLEAN_ROOM_HOME_DIR, CLEAN_ROOM_HOST, CLEAN_ROOM_IMAGE_ENV, CLEAN_ROOM_IMAGE_PATTERN, CLEAN_ROOM_NETWORK_ENV, CLEAN_ROOM_NETWORK_PATTERN, CLEAN_ROOM_NETWORK_SELF, DIR_MODE, DOCKER_BIN, GIT_BIN, } from './constants.js';
|
|
14
|
+
const IMAGE_RE = new RegExp(CLEAN_ROOM_IMAGE_PATTERN);
|
|
15
|
+
const NETWORK_RE = new RegExp(CLEAN_ROOM_NETWORK_PATTERN);
|
|
16
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
17
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
18
|
+
/** The one reader of a Clean Room setting: the hub uses it for hire and edit, home.ts for the roster file. `{}` is the default image. */
|
|
19
|
+
export function parseCleanRoom(value, provider) {
|
|
20
|
+
if (!isRecord(value))
|
|
21
|
+
return { ok: false, error: 'cleanRoom must be an object' };
|
|
22
|
+
if ((provider ?? 'claude') !== 'claude')
|
|
23
|
+
return { ok: false, error: 'a Clean Room runs Claude Code agents only' };
|
|
24
|
+
const unknown = Object.keys(value).find((key) => key !== 'image');
|
|
25
|
+
if (unknown !== undefined)
|
|
26
|
+
return { ok: false, error: `cleanRoom has no field "${unknown}"` };
|
|
27
|
+
const { image } = value;
|
|
28
|
+
if (image === undefined)
|
|
29
|
+
return { ok: true, cleanRoom: {} };
|
|
30
|
+
if (typeof image !== 'string' || !IMAGE_RE.test(image))
|
|
31
|
+
return { ok: false, error: 'the image must be a Docker image name or id (letters, digits and . _ / : @ -)' };
|
|
32
|
+
return { ok: true, cleanRoom: { image } };
|
|
33
|
+
}
|
|
34
|
+
/** The agent's own image, else GONOGO_CLEANROOM_IMAGE, else the project's `ghcr.io/ulm0/gonogo`. */
|
|
35
|
+
export function cleanRoomImage(cleanRoom, env) {
|
|
36
|
+
const image = cleanRoom.image ?? (env[CLEAN_ROOM_IMAGE_ENV]?.trim() || CLEAN_ROOM_DEFAULT_IMAGE);
|
|
37
|
+
if (!IMAGE_RE.test(image))
|
|
38
|
+
throw new Error(`${CLEAN_ROOM_IMAGE_ENV} is not a Docker image name: ${JSON.stringify(image)}`);
|
|
39
|
+
return image;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* GONOGO_CLEANROOM_NETWORK, or null when unset. Only `container:<name>`: the container shares gonogo's network and its
|
|
43
|
+
* hosts file, where host.docker.internal must name 127.0.0.1. Another network would need a private address, and Claude
|
|
44
|
+
* Code blocks HTTP hooks to those. `container:self` is gonogo's own container by its host name, which Docker sets to the
|
|
45
|
+
* container's short id unless `hostname` is set, so compose needs no fixed container name.
|
|
46
|
+
*/
|
|
47
|
+
export function cleanRoomNetwork(env, host = hostname()) {
|
|
48
|
+
const raw = env[CLEAN_ROOM_NETWORK_ENV]?.trim();
|
|
49
|
+
if (!raw)
|
|
50
|
+
return null;
|
|
51
|
+
const value = raw === CLEAN_ROOM_NETWORK_SELF ? `container:${host}` : raw;
|
|
52
|
+
if (!NETWORK_RE.test(value))
|
|
53
|
+
throw new Error(`${CLEAN_ROOM_NETWORK_ENV} must be ${CLEAN_ROOM_NETWORK_SELF} or container:<name of gonogo's own container>, not ${JSON.stringify(raw)}`);
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* With gonogo in a container, the host's Docker mounts a Clean Room's folders by their paths on the host, so gonogo's
|
|
58
|
+
* home must be a bind mount from the same path of the host. `mounts` is `.Mounts` of `docker inspect`. Null when it is.
|
|
59
|
+
*/
|
|
60
|
+
export function sameMountError(mounts, homeDir, container) {
|
|
61
|
+
const covers = (dest) => homeDir === dest || homeDir.startsWith(dest.endsWith('/') ? dest : `${dest}/`);
|
|
62
|
+
const mount = (Array.isArray(mounts) ? mounts : [])
|
|
63
|
+
.filter(isRecord)
|
|
64
|
+
.filter((m) => typeof m.Destination === 'string' && covers(m.Destination))
|
|
65
|
+
.sort((a, b) => String(b.Destination).length - String(a.Destination).length)[0];
|
|
66
|
+
if (mount?.Type === 'bind' && mount.Source === mount.Destination)
|
|
67
|
+
return null;
|
|
68
|
+
return `gonogo's home ${homeDir} is not mounted into the container ${container} from the same path of the host: the host's Docker mounts a Clean Room's folders by their host paths, so mount it as -v ${homeDir}:${homeDir}`;
|
|
69
|
+
}
|
|
70
|
+
/** Runs a program without a shell and answers its output. A failure is an Error whose text is the first line the program printed on stderr. */
|
|
71
|
+
function run(file, args, env) {
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
execFile(file, args, { env: env, timeout: CLEAN_ROOM_COMMAND_MS, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
|
|
74
|
+
if (error === null)
|
|
75
|
+
return resolve(stdout);
|
|
76
|
+
const code = error.code;
|
|
77
|
+
const line = stderr.split('\n').find((l) => l.trim() !== '')?.trim() ?? error.message.split('\n')[0] ?? '';
|
|
78
|
+
reject(new Error(code === 'ENOENT' ? `${file} was not found on PATH` : line.slice(0, 300)));
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/** Docker is there and its daemon answers: `docker version` exits 0 only then. */
|
|
83
|
+
export async function checkDocker(env) {
|
|
84
|
+
try {
|
|
85
|
+
await run(DOCKER_BIN, ['version'], env);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
throw new Error(`Clean Room needs Docker, and "docker version" failed: ${messageOf(error)}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** The top folder of the git repository that holds `dir`. */
|
|
92
|
+
export async function repoRoot(dir, env) {
|
|
93
|
+
try {
|
|
94
|
+
return (await run(GIT_BIN, ['-C', dir, 'rev-parse', '--show-toplevel'], env)).trim();
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
throw new Error(`Clean Room needs the directory to be inside a git repository: ${messageOf(error)}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** What the hub asks at hire and edit: null when Docker works and `dir` is in a repository, else why not. */
|
|
101
|
+
export async function checkCleanRoom(dir, env) {
|
|
102
|
+
try {
|
|
103
|
+
cleanRoomNetwork(env);
|
|
104
|
+
await checkDocker(env);
|
|
105
|
+
await repoRoot(dir, env);
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
return messageOf(error);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** Makes the worktree on its branch the first time and finds it again after that. A folder in its place that git does not know is an error, never reused. */
|
|
113
|
+
export async function ensureWorktree(repo, path, branch, env) {
|
|
114
|
+
const git = (...args) => run(GIT_BIN, ['-C', repo, ...args], env);
|
|
115
|
+
const real = await realpath(path).catch(() => null);
|
|
116
|
+
if (real !== null) {
|
|
117
|
+
const listed = (await git('worktree', 'list', '--porcelain')).split('\n').filter((l) => l.startsWith('worktree ')).map((l) => l.slice(9));
|
|
118
|
+
if (!(await Promise.all(listed.map((p) => realpath(p).catch(() => p)))).includes(real)) {
|
|
119
|
+
throw new Error(`${path} exists but is not a worktree of ${repo}; move it away or give the agent a folder of the repository it was made for`);
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });
|
|
124
|
+
try {
|
|
125
|
+
await git('worktree', 'prune'); // a worktree whose folder was deleted still holds its branch
|
|
126
|
+
const known = await git('show-ref', '--verify', '--quiet', `refs/heads/${branch}`).then(() => true, () => false);
|
|
127
|
+
await git('worktree', 'add', ...(known ? [path, branch] : ['-b', branch, path]));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
throw new Error(`could not make the worktree ${path} on ${branch}: ${messageOf(error)}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** `gonogo-<name>-<hash of the worktree path>`: two gonogo homes on one Docker never share a name. */
|
|
134
|
+
export const containerName = (worktree) => `gonogo-${basename(worktree)}-${createHash('sha256').update(worktree).digest('hex').slice(0, 12)}`;
|
|
135
|
+
/**
|
|
136
|
+
* `docker rm -f`: with `-t` the docker CLI does not pass signals on, so a stopped console's container would keep running
|
|
137
|
+
* after its docker process ended. Called after every exit and before every start. Never fails: no such container is fine.
|
|
138
|
+
*/
|
|
139
|
+
export async function removeContainer(name, env) {
|
|
140
|
+
await run(DOCKER_BIN, ['rm', '-f', name], env).catch(() => undefined);
|
|
141
|
+
}
|
|
142
|
+
/** Everything a start needs on disk: Docker checked, the worktree there, the container's home made. `base` is agents/<name>. */
|
|
143
|
+
export async function prepareCleanRoom(agent, homeDir, base, env) {
|
|
144
|
+
const network = cleanRoomNetwork(env);
|
|
145
|
+
await checkDocker(env);
|
|
146
|
+
if (network !== null) {
|
|
147
|
+
const self = network.slice('container:'.length);
|
|
148
|
+
let mounts;
|
|
149
|
+
try {
|
|
150
|
+
mounts = JSON.parse(await run(DOCKER_BIN, ['inspect', '--format', '{{json .Mounts}}', self], env));
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
throw new Error(`${CLEAN_ROOM_NETWORK_ENV} names the container ${self}, and "docker inspect" failed: ${messageOf(error)}`);
|
|
154
|
+
}
|
|
155
|
+
const error = sameMountError(mounts, homeDir, self);
|
|
156
|
+
if (error !== null)
|
|
157
|
+
throw new Error(error);
|
|
158
|
+
// The Clean Room shares this container's hosts file; keeping the name (not 127.0.0.1) keeps the Host rule: hooks and MCP only.
|
|
159
|
+
const address = await lookup(CLEAN_ROOM_HOST).then((found) => found.address, () => 'nothing');
|
|
160
|
+
if (!address.startsWith('127.'))
|
|
161
|
+
throw new Error(`${CLEAN_ROOM_HOST} names ${address} in the container ${self}, not 127.0.0.1: start it with --add-host ${CLEAN_ROOM_HOST}:127.0.0.1 (compose.yaml has it)`);
|
|
162
|
+
}
|
|
163
|
+
const top = await realpath(await repoRoot(agent.dir, env));
|
|
164
|
+
const worktree = join(homeDir, CLEAN_ROOM_DIR, agent.name);
|
|
165
|
+
await ensureWorktree(top, worktree, cleanRoomBranch(agent.name), env);
|
|
166
|
+
const inside = relative(top, await realpath(agent.dir));
|
|
167
|
+
const cwd = join(worktree, inside);
|
|
168
|
+
if (!(await stat(cwd).then((info) => info.isDirectory(), () => false))) {
|
|
169
|
+
throw new Error(`${inside} is not in the worktree ${worktree}: the worktree is a copy of the last commit, and that folder is not committed`);
|
|
170
|
+
}
|
|
171
|
+
const container = containerName(worktree);
|
|
172
|
+
await removeContainer(container, env);
|
|
173
|
+
const home = join(base, CLEAN_ROOM_HOME_DIR);
|
|
174
|
+
await mkdir(home, { recursive: true, mode: DIR_MODE });
|
|
175
|
+
// The container can write the agent's folder: a link planted there would make gonogo write trust into a file outside it.
|
|
176
|
+
for (const path of [home, join(home, '.claude.json')]) {
|
|
177
|
+
if ((await lstat(path).catch(() => null))?.isSymbolicLink())
|
|
178
|
+
throw new Error(`${path} is a symbolic link, and a Clean Room never follows one out of its folder: delete it`);
|
|
179
|
+
}
|
|
180
|
+
return { worktree, cwd, home, container, network };
|
|
181
|
+
}
|
|
182
|
+
/** The URL an agent in a container reaches gonogo by: the loopback host of the server's URL becomes the host's name. */
|
|
183
|
+
export const containerUrl = (hubUrl) => hubUrl.replace(/^http:\/\/(?:127\.0\.0\.1|\[::1\])/, `http://${CLEAN_ROOM_HOST}`);
|
|
184
|
+
/**
|
|
185
|
+
* `docker run` for one agent: the worktree and the agent's own folder at the same paths, nothing else, as the owner's
|
|
186
|
+
* uid. The worktree's `.git` file is read-only: rewritten, it could point the owner's next git command in the worktree
|
|
187
|
+
* at a config (core.fsmonitor) that runs a program on the host. Variables are named without a value, so docker reads them from its own environment and no secret is on the
|
|
188
|
+
* command line. `command` is the program to run inside and its arguments: the program goes in `--entrypoint`, because the
|
|
189
|
+
* project's own image has `gonogo` as its entrypoint, and HOME and CLAUDE_CONFIG_DIR are set because the image points the
|
|
190
|
+
* second one at a folder this user cannot write.
|
|
191
|
+
*/
|
|
192
|
+
export function buildDockerArgs(input) {
|
|
193
|
+
const { place } = input;
|
|
194
|
+
for (const path of [place.worktree, input.agentDir]) {
|
|
195
|
+
if (path.includes(':'))
|
|
196
|
+
throw new Error(`the path ${path} has a colon, which docker cannot mount`);
|
|
197
|
+
}
|
|
198
|
+
return [
|
|
199
|
+
'run', '--rm', '-i', '-t', '--init',
|
|
200
|
+
'--name', place.container,
|
|
201
|
+
'--user', `${input.uid}:${input.gid}`,
|
|
202
|
+
...(place.network === null ? ['--add-host', `${CLEAN_ROOM_HOST}:host-gateway`] : ['--network', place.network]),
|
|
203
|
+
'-e', `HOME=${place.home}`,
|
|
204
|
+
'-e', `CLAUDE_CONFIG_DIR=${place.home}`,
|
|
205
|
+
...input.names.flatMap((name) => ['-e', name]),
|
|
206
|
+
'-v', `${place.worktree}:${place.worktree}`,
|
|
207
|
+
'-v', `${join(place.worktree, '.git')}:${join(place.worktree, '.git')}:ro`,
|
|
208
|
+
'-v', `${input.agentDir}:${input.agentDir}`,
|
|
209
|
+
'-w', place.cwd,
|
|
210
|
+
'--entrypoint', input.command[0],
|
|
211
|
+
input.image,
|
|
212
|
+
...input.command.slice(1),
|
|
213
|
+
];
|
|
214
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clearance (docs/engine-bay-spec.md): environment variables the Director sets for one agent, usually API keys.
|
|
3
|
+
*
|
|
4
|
+
* keys.json (mode 0600, written whole through a temporary file and a rename) holds the values: agent name to name to value.
|
|
5
|
+
* The roster keeps the names and the time each was set, so the page can say "set"; a value is never sent to a browser and
|
|
6
|
+
* never logged. The launcher puts an agent's keys in that agent's environment only (launcher.ts).
|
|
7
|
+
*
|
|
8
|
+
* shortcut: the values are stored as text (an API key has to be sent as it is), so the file is 0600 and nothing else; encrypt
|
|
9
|
+
* it if the home folder is ever shared.
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from 'node:crypto';
|
|
12
|
+
import { readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { KEY_NAME_PATTERN, KEY_VALUE_PATTERN, KEYS_MAX } from '../shared/protocol.js';
|
|
15
|
+
import { FILE_MODE, KEYS_FILE, nullLogger } from './constants.js';
|
|
16
|
+
const NAME_RE = new RegExp(KEY_NAME_PATTERN);
|
|
17
|
+
const VALUE_RE = new RegExp(KEY_VALUE_PATTERN);
|
|
18
|
+
/** Variables that change what runs or where, or that gonogo sets itself: a key is data, so these are refused. */
|
|
19
|
+
const RESERVED_EXACT = new Set([
|
|
20
|
+
'PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'PWD', 'TMPDIR', 'TERM', 'COLORTERM', 'IS_DEMO', 'NODE_OPTIONS', 'NODE_PATH', 'CLAUDE_CONFIG_DIR',
|
|
21
|
+
// shell and interpreter start-up hooks: each runs a file or a command before the program the agent started
|
|
22
|
+
'BASH_ENV', 'SHELLOPTS', 'BASHOPTS', 'PROMPT_COMMAND', 'IFS', 'PYTHONSTARTUP', 'PYTHONPATH', 'PYTHONHOME', 'RUBYOPT', 'RUBYLIB', 'PERL5OPT', 'PERL5LIB',
|
|
23
|
+
'GIT_SSH_COMMAND', 'GIT_ASKPASS', 'SSH_ASKPASS', 'GIT_EXEC_PATH',
|
|
24
|
+
]);
|
|
25
|
+
// DOCKER_: a Clean Room's docker client runs with the agent's keys in its environment, and DOCKER_HOST would move the container to another daemon.
|
|
26
|
+
// shortcut: the usual start-up hooks, not every variable some program reads as a command; the Director owns the agent anyway, so extend the list when one turns up.
|
|
27
|
+
const RESERVED_PREFIXES = ['GONOGO_', 'LD_', 'DYLD_', 'BASH_FUNC_', 'DOCKER_', 'GIT_CONFIG_'];
|
|
28
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
29
|
+
/** Why this name cannot be a key, or null. */
|
|
30
|
+
export function keyNameProblem(name) {
|
|
31
|
+
// the name is not echoed: a value pasted in the wrong field must not come back in an error
|
|
32
|
+
if (!NAME_RE.test(name))
|
|
33
|
+
return 'a key name uses capital letters, digits and _, starting with a letter (at most 64 characters)';
|
|
34
|
+
if (RESERVED_EXACT.has(name) || RESERVED_PREFIXES.some((prefix) => name.startsWith(prefix)))
|
|
35
|
+
return `${name} is set by gonogo or changes what runs, so it cannot be a key`;
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The shape of a hire's or an edit's keys: name to value, and for an edit also name to null (remove). `current` is the names
|
|
40
|
+
* the agent has (name to time), `names` the names it will have, new and changed ones stamped `now`. Values stay in `patch`.
|
|
41
|
+
* An error names the key and says what is wrong, never what the value was.
|
|
42
|
+
*/
|
|
43
|
+
export function checkKeys(value, current, now, hire) {
|
|
44
|
+
if (!isRecord(value))
|
|
45
|
+
return { ok: false, error: 'keys must be an object of names and values' };
|
|
46
|
+
const entries = Object.entries(value);
|
|
47
|
+
if (entries.length > KEYS_MAX)
|
|
48
|
+
return { ok: false, error: `at most ${KEYS_MAX} keys` };
|
|
49
|
+
const names = { ...current };
|
|
50
|
+
const patch = {};
|
|
51
|
+
for (const [name, item] of entries) {
|
|
52
|
+
const problem = keyNameProblem(name);
|
|
53
|
+
if (problem !== null)
|
|
54
|
+
return { ok: false, error: problem };
|
|
55
|
+
if (item === null && !hire) {
|
|
56
|
+
delete names[name];
|
|
57
|
+
patch[name] = null;
|
|
58
|
+
}
|
|
59
|
+
else if (typeof item === 'string' && VALUE_RE.test(item)) {
|
|
60
|
+
names[name] = now;
|
|
61
|
+
patch[name] = item;
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
return { ok: false, error: `${name} must be text of 1 to 4096 printable characters without a space${hire ? '' : ', or null to remove it'}` };
|
|
65
|
+
}
|
|
66
|
+
if (Object.keys(names).length > KEYS_MAX)
|
|
67
|
+
return { ok: false, error: `at most ${KEYS_MAX} keys` };
|
|
68
|
+
return { ok: true, patch, names };
|
|
69
|
+
}
|
|
70
|
+
export function createClearance(options) {
|
|
71
|
+
const log = options.log ?? nullLogger;
|
|
72
|
+
const path = join(options.dir, KEYS_FILE);
|
|
73
|
+
let agents = new Map();
|
|
74
|
+
let chain = Promise.resolve();
|
|
75
|
+
/** One write after the other; a failed one rejects to its caller and does not stop the next. A change that returns the same map writes nothing. */
|
|
76
|
+
const write = (change) => {
|
|
77
|
+
const run = chain.then(async () => {
|
|
78
|
+
const before = agents;
|
|
79
|
+
agents = change();
|
|
80
|
+
if (agents === before)
|
|
81
|
+
return;
|
|
82
|
+
const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
83
|
+
try {
|
|
84
|
+
await writeFile(temp, JSON.stringify({ version: 1, agents: Object.fromEntries(agents) }, null, 2), { flag: 'wx', mode: FILE_MODE });
|
|
85
|
+
await rename(temp, path);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
agents = before;
|
|
89
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
90
|
+
// the message of a file error holds a path, not a value
|
|
91
|
+
throw new Error(`could not save the keys: ${error instanceof Error ? error.message : String(error)}`);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
chain = run.catch(() => undefined);
|
|
95
|
+
return run;
|
|
96
|
+
};
|
|
97
|
+
return {
|
|
98
|
+
async load() {
|
|
99
|
+
let saved;
|
|
100
|
+
try {
|
|
101
|
+
saved = JSON.parse(await readFile(path, 'utf8'));
|
|
102
|
+
if (!isRecord(saved) || saved.version !== 1 || !isRecord(saved.agents))
|
|
103
|
+
throw new Error('not a version 1 keys file');
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code === 'ENOENT')
|
|
107
|
+
return;
|
|
108
|
+
// kept aside, so that the next save cannot overwrite the keys; a SyntaxError quotes the text around the fault, which can be a key
|
|
109
|
+
log.error(`${KEYS_FILE} could not be read; agents start without keys and the file is kept as ${KEYS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
|
|
110
|
+
await rename(path, `${path}.bad`).catch(() => undefined);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
for (const [agent, keys] of Object.entries(saved.agents)) {
|
|
114
|
+
if (!isRecord(keys))
|
|
115
|
+
continue;
|
|
116
|
+
const own = Object.fromEntries(Object.entries(keys).filter(([name, value]) => keyNameProblem(name) === null && typeof value === 'string' && VALUE_RE.test(value)));
|
|
117
|
+
if (Object.keys(own).length > 0)
|
|
118
|
+
agents.set(agent, own);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
values: (name) => ({ ...agents.get(name) }),
|
|
122
|
+
apply: (name, patch, fresh = false) => write(() => {
|
|
123
|
+
const keys = { ...(fresh ? {} : agents.get(name)) };
|
|
124
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
125
|
+
if (value === null)
|
|
126
|
+
delete keys[key];
|
|
127
|
+
else
|
|
128
|
+
keys[key] = value;
|
|
129
|
+
}
|
|
130
|
+
const empty = Object.keys(keys).length === 0;
|
|
131
|
+
if (empty && !agents.has(name))
|
|
132
|
+
return agents;
|
|
133
|
+
const next = new Map(agents);
|
|
134
|
+
if (empty)
|
|
135
|
+
next.delete(name);
|
|
136
|
+
else
|
|
137
|
+
next.set(name, keys);
|
|
138
|
+
return next;
|
|
139
|
+
}),
|
|
140
|
+
rename: (oldName, newName) => write(() => {
|
|
141
|
+
const keys = agents.get(oldName);
|
|
142
|
+
if (keys === undefined)
|
|
143
|
+
return agents;
|
|
144
|
+
const next = new Map(agents);
|
|
145
|
+
next.delete(oldName);
|
|
146
|
+
next.set(newName, keys);
|
|
147
|
+
return next;
|
|
148
|
+
}),
|
|
149
|
+
remove: (name) => write(() => {
|
|
150
|
+
if (!agents.has(name))
|
|
151
|
+
return agents;
|
|
152
|
+
const next = new Map(agents);
|
|
153
|
+
next.delete(name);
|
|
154
|
+
return next;
|
|
155
|
+
}),
|
|
156
|
+
close: () => chain.then(() => undefined),
|
|
157
|
+
};
|
|
158
|
+
}
|