@ulm0/gonogo 0.0.0-stage → 0.1.1
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 +30 -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-B6MsSoeo.css +1 -0
- package/dist/client/assets/index-DRtiRh1Y.js +31 -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/cleanroom.js +214 -0
- package/dist/server/cli.js +630 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +427 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/home.js +497 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2484 -0
- package/dist/server/launcher.js +542 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/mcp.js +196 -0
- package/dist/server/migrate.js +119 -0
- package/dist/server/missionlog.js +209 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +137 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1466 -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 +212 -0
- package/package.json +84 -3
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns an agent record into a claude process (contract section 7): the generated files under <home>/agents/<name>,
|
|
3
|
+
* the exact command line, the child environment and the token of one start. Claude's own files are touched in seed
|
|
4
|
+
* mode only.
|
|
5
|
+
*/
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { unlinkSync } from 'node:fs';
|
|
8
|
+
import { chmod, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
10
|
+
import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
|
|
11
|
+
import { cleanRoomBranch, HOOK_EVENTS, MCP_SERVER_NAME, PERMISSION_MODES, PROVIDER_INFO } from '../shared/protocol.js';
|
|
12
|
+
import { AGENT_NAME_PATTERN, AGENT_TOKEN_FILE, AGENTS_DIR, ALLOWED_TOOLS, API_KEY_HELPER_COMMAND, CLAUDE_BIN, CLEAN_ROOM_CREDENTIALS, CLEAN_ROOM_ENV, CLEAN_ROOM_NOTE, COLORTERM_VALUE, DENIED_TOOLS, DIR_MODE, DOCKER_BIN, FILE_MODE, HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_FILE, MCP_PATH, MEMORY_FILE, nullLogger, PAYLOAD_PLUGIN_DIR, PAYLOAD_PLUGIN_NAME, ROLE_PREAMBLE, SCRUB_ENV_EXACT, SCRUB_ENV_PREFIXES, SETTINGS_FILE, TERM_VALUE, TOKEN_BYTES, TRUST_VERIFY_ATTEMPTS, TRUST_VERIFY_DELAY_MS, } from './constants.js';
|
|
13
|
+
import { buildDockerArgs, cleanRoomImage, containerUrl, prepareCleanRoom, removeContainer } from './cleanroom.js';
|
|
14
|
+
import { parseAgentCmd } from './command.js';
|
|
15
|
+
import { buildProviderStart } from './providers.js';
|
|
16
|
+
const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
|
|
17
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
18
|
+
/** claude blocks http hooks to private addresses without saying so, so only the two loopback forms of 0.3 item 13 are written. */
|
|
19
|
+
const LOOPBACK_URL_RE = /^http:\/\/(?:127\.0\.0\.1|\[::1\]):\d{1,5}$/;
|
|
20
|
+
const CLAUDE_JSON = '.claude.json';
|
|
21
|
+
/** Open item O11 (contract 13): claude rewrites .claude.json on every start, so look once more after it had time to. Not in constants.ts. */
|
|
22
|
+
const TRUST_RECHECK_MS = 2_000;
|
|
23
|
+
const NO_PROXY_HOSTS = ['127.0.0.1', 'localhost'];
|
|
24
|
+
const SCRUB_EXACT = new Set(SCRUB_ENV_EXACT);
|
|
25
|
+
/** The operator's own additions to the scrub lists (README, environment variables). Not in constants.ts. */
|
|
26
|
+
const SCRUB_EXTRA_VAR = 'GONOGO_SCRUB_ENV';
|
|
27
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
28
|
+
const hasText = (value) => typeof value === 'string' && value !== '';
|
|
29
|
+
const errorCode = (error) => (isObject(error) ? error.code : undefined);
|
|
30
|
+
const errorText = (error) => (error instanceof Error ? error.message : String(error));
|
|
31
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
32
|
+
/* ---- pure builders (exported so the tests can compare them with the JSON of section 7) ---- */
|
|
33
|
+
/** Re-exported: the reader lives in command.ts so that home.ts and web.ts can use it without importing the launcher. */
|
|
34
|
+
export { parseAgentCmd };
|
|
35
|
+
/**
|
|
36
|
+
* One pass with a function replacer: a string replacement would read `$&`, `$'` and `$$` in the role, and replacing the
|
|
37
|
+
* placeholders one after the other would expand a `{memory}` the owner wrote inside the role.
|
|
38
|
+
*/
|
|
39
|
+
export function buildRoleText(name, role, memoryPath) {
|
|
40
|
+
const values = { name, memory: memoryPath, role: role.trim() };
|
|
41
|
+
return ROLE_PREAMBLE.replace(/\{(name|memory|role)\}/g, (_, key) => values[key]);
|
|
42
|
+
}
|
|
43
|
+
export function buildSettings(input) {
|
|
44
|
+
const hooks = {};
|
|
45
|
+
for (const event of HOOK_EVENTS) {
|
|
46
|
+
hooks[event] = [
|
|
47
|
+
{
|
|
48
|
+
hooks: [
|
|
49
|
+
{
|
|
50
|
+
type: 'http',
|
|
51
|
+
url: `${input.hubUrl}${HOOK_PATH_PREFIX}${input.name}/${event}`,
|
|
52
|
+
timeout: HOOK_TIMEOUT_S,
|
|
53
|
+
// claude sends "Bearer " with an empty token unless allowedEnvVars names the variable
|
|
54
|
+
headers: { Authorization: 'Bearer $GONOGO_TOKEN' },
|
|
55
|
+
allowedEnvVars: ['GONOGO_TOKEN'],
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
},
|
|
59
|
+
];
|
|
60
|
+
}
|
|
61
|
+
const memoryRule = `//${input.memoryPath.replace(/^\//, '')}`;
|
|
62
|
+
const settings = {
|
|
63
|
+
hooks,
|
|
64
|
+
tui: 'fullscreen',
|
|
65
|
+
promptSuggestionEnabled: false,
|
|
66
|
+
crossSessionInbound: 'refuse',
|
|
67
|
+
permissions: { deny: [...DENIED_TOOLS], allow: [`Read(${memoryRule})`, `Edit(${memoryRule})`] },
|
|
68
|
+
};
|
|
69
|
+
if (input.mode === 'bypassPermissions')
|
|
70
|
+
settings.skipDangerousModePermissionPrompt = true;
|
|
71
|
+
if (input.apiKeyHelper)
|
|
72
|
+
settings.apiKeyHelper = API_KEY_HELPER_COMMAND;
|
|
73
|
+
return settings;
|
|
74
|
+
}
|
|
75
|
+
/** `servers` are the agent's Payload servers; gonogo's own entry comes last so that nothing can replace it. */
|
|
76
|
+
export function buildMcpConfig(hubUrl, servers = {}) {
|
|
77
|
+
return {
|
|
78
|
+
mcpServers: {
|
|
79
|
+
...servers,
|
|
80
|
+
[MCP_SERVER_NAME]: {
|
|
81
|
+
type: 'http', // without it claude reads the entry as stdio and skips it
|
|
82
|
+
url: `${hubUrl}${MCP_PATH}`,
|
|
83
|
+
headers: { Authorization: 'Bearer ${GONOGO_TOKEN}' }, // expanded by claude from its environment
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Every flag on every start: --resume restores history and model, not settings, MCP config, tools, mode or role text. */
|
|
89
|
+
export function buildArgv(input) {
|
|
90
|
+
return [
|
|
91
|
+
input.flag === 'resume' ? '--resume' : '--session-id',
|
|
92
|
+
input.sessionId,
|
|
93
|
+
'--permission-mode',
|
|
94
|
+
input.mode,
|
|
95
|
+
'--settings',
|
|
96
|
+
input.settingsPath,
|
|
97
|
+
'--strict-mcp-config',
|
|
98
|
+
'--mcp-config',
|
|
99
|
+
input.mcpPath,
|
|
100
|
+
...(input.pluginDir ? ['--plugin-dir', input.pluginDir] : []),
|
|
101
|
+
'--append-system-prompt',
|
|
102
|
+
input.roleText,
|
|
103
|
+
'--system-prompt-snapshot',
|
|
104
|
+
'off',
|
|
105
|
+
'--allowedTools', // variadic, so it stays last
|
|
106
|
+
...ALLOWED_TOOLS,
|
|
107
|
+
];
|
|
108
|
+
}
|
|
109
|
+
/** claude sends http hooks through HTTP(S)_PROXY unless the host is listed; the operator's own entries stay. */
|
|
110
|
+
function withLoopback(existing) {
|
|
111
|
+
const hosts = (existing ?? '')
|
|
112
|
+
.split(',')
|
|
113
|
+
.map((host) => host.trim())
|
|
114
|
+
.filter((host) => host !== '');
|
|
115
|
+
for (const loopback of NO_PROXY_HOSTS) {
|
|
116
|
+
if (!hosts.some((host) => host.toLowerCase() === loopback))
|
|
117
|
+
hosts.push(loopback);
|
|
118
|
+
}
|
|
119
|
+
return hosts.join(',');
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Comma separated; an entry ending in an underscore is a prefix, any other entry an exact name. It is applied to the
|
|
123
|
+
* variables the owner's shell passed on, before gonogo sets its own, so it cannot take away TERM, GONOGO_TOKEN and the like.
|
|
124
|
+
*/
|
|
125
|
+
function operatorScrub(value) {
|
|
126
|
+
const exact = new Set();
|
|
127
|
+
const prefixes = [];
|
|
128
|
+
for (const raw of (value ?? '').split(',')) {
|
|
129
|
+
const entry = raw.trim();
|
|
130
|
+
if (entry === '')
|
|
131
|
+
continue;
|
|
132
|
+
if (entry.endsWith('_'))
|
|
133
|
+
prefixes.push(entry);
|
|
134
|
+
else
|
|
135
|
+
exact.add(entry);
|
|
136
|
+
}
|
|
137
|
+
return { exact, prefixes };
|
|
138
|
+
}
|
|
139
|
+
/** `seed` must only be true once the folder trust is on disk: IS_DEMO hides the trust dialog without trusting the folder. */
|
|
140
|
+
export function buildChildEnv(input) {
|
|
141
|
+
const env = {};
|
|
142
|
+
const extra = operatorScrub(input.base[SCRUB_EXTRA_VAR]);
|
|
143
|
+
for (const [key, value] of Object.entries(input.base)) {
|
|
144
|
+
if (value === undefined || SCRUB_EXACT.has(key) || extra.exact.has(key))
|
|
145
|
+
continue;
|
|
146
|
+
if (SCRUB_ENV_PREFIXES.some((prefix) => key.startsWith(prefix)) || extra.prefixes.some((prefix) => key.startsWith(prefix)))
|
|
147
|
+
continue;
|
|
148
|
+
env[key] = value;
|
|
149
|
+
}
|
|
150
|
+
if (input.seed) {
|
|
151
|
+
env.IS_DEMO = '1';
|
|
152
|
+
// A plain ANTHROPIC_API_KEY triggers a dialog whose default is "No" (or "Not logged in" under IS_DEMO)
|
|
153
|
+
const apiKey = env.ANTHROPIC_API_KEY;
|
|
154
|
+
if (hasText(apiKey)) {
|
|
155
|
+
delete env.ANTHROPIC_API_KEY;
|
|
156
|
+
env.GONOGO_API_KEY = apiKey;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
env.TERM = TERM_VALUE;
|
|
160
|
+
env.COLORTERM = COLORTERM_VALUE;
|
|
161
|
+
if (input.token !== null)
|
|
162
|
+
env.GONOGO_TOKEN = input.token;
|
|
163
|
+
env.NO_PROXY = withLoopback(env.NO_PROXY);
|
|
164
|
+
env.no_proxy = withLoopback(env.no_proxy);
|
|
165
|
+
return env;
|
|
166
|
+
}
|
|
167
|
+
/** The lookup of a transcript must name a project directory the way claude does. */
|
|
168
|
+
export function transcriptDirName(cwd) {
|
|
169
|
+
return cwd.replace(/[^A-Za-z0-9]/g, '-');
|
|
170
|
+
}
|
|
171
|
+
/* ---- files ---- */
|
|
172
|
+
/** Temp file in the same directory, then rename: a reader never sees half a file. */
|
|
173
|
+
async function writeFileAtomic(path, data, mode) {
|
|
174
|
+
const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
175
|
+
try {
|
|
176
|
+
await writeFile(temp, data, { flag: 'wx', mode });
|
|
177
|
+
await chmod(temp, mode); // the umask may have taken bits away
|
|
178
|
+
await rename(temp, path);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Payload skills: a plugin folder under the agent's own folder, made again at every start, with a symlink to each skill
|
|
187
|
+
* folder. `claude --plugin-dir` loads it for that session only, so the owner's project and ~/.claude stay as they are.
|
|
188
|
+
* Returns the folder, or null when the agent has no skills (a folder left by earlier skills is removed).
|
|
189
|
+
*/
|
|
190
|
+
async function writeSkillsPlugin(base, skills) {
|
|
191
|
+
const dir = join(base, PAYLOAD_PLUGIN_DIR);
|
|
192
|
+
await rm(dir, { recursive: true, force: true });
|
|
193
|
+
if (skills === undefined || skills.length === 0)
|
|
194
|
+
return null;
|
|
195
|
+
for (const skill of skills) {
|
|
196
|
+
const found = await stat(join(skill, 'SKILL.md')).then((info) => info.isFile(), () => false);
|
|
197
|
+
if (!found)
|
|
198
|
+
throw new Error(`the skill folder has no SKILL.md: ${skill}`);
|
|
199
|
+
}
|
|
200
|
+
await mkdir(dir, { mode: DIR_MODE });
|
|
201
|
+
await mkdir(join(dir, '.claude-plugin'), { mode: DIR_MODE });
|
|
202
|
+
await mkdir(join(dir, 'skills'), { mode: DIR_MODE });
|
|
203
|
+
await writeFile(join(dir, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: PAYLOAD_PLUGIN_NAME, description: 'Skills chosen for this agent in gonogo' }, null, 2), { mode: FILE_MODE });
|
|
204
|
+
for (const skill of skills)
|
|
205
|
+
await symlink(skill, join(dir, 'skills', basename(skill)));
|
|
206
|
+
return dir;
|
|
207
|
+
}
|
|
208
|
+
/** A missing file is an empty object; a file that is not a JSON object is an error (it is the user's, never overwrite it). */
|
|
209
|
+
async function readJsonObject(path) {
|
|
210
|
+
let text;
|
|
211
|
+
try {
|
|
212
|
+
text = await readFile(path, 'utf8');
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (errorCode(error) === 'ENOENT')
|
|
216
|
+
return {};
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
let parsed;
|
|
220
|
+
try {
|
|
221
|
+
parsed = JSON.parse(text);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
throw new Error('the file is not valid JSON; fix or delete it');
|
|
225
|
+
}
|
|
226
|
+
if (!isObject(parsed))
|
|
227
|
+
throw new Error('the file does not hold a JSON object; fix or delete it');
|
|
228
|
+
return parsed;
|
|
229
|
+
}
|
|
230
|
+
const isTrusted = (doc, dirs) => dirs.every((dir) => {
|
|
231
|
+
const entry = isObject(doc.projects) ? doc.projects[dir] : undefined;
|
|
232
|
+
return isObject(entry) && entry.hasTrustDialogAccepted === true;
|
|
233
|
+
});
|
|
234
|
+
/** Everything but the trust keys belongs to the user and to claude, so it is carried over untouched. */
|
|
235
|
+
function withTrust(doc, dirs) {
|
|
236
|
+
const projects = doc.projects === undefined ? {} : doc.projects;
|
|
237
|
+
if (!isObject(projects))
|
|
238
|
+
throw new Error('"projects" is not an object; fix or delete the file');
|
|
239
|
+
const merged = { ...projects };
|
|
240
|
+
for (const dir of dirs) {
|
|
241
|
+
const entry = merged[dir] === undefined ? {} : merged[dir];
|
|
242
|
+
if (!isObject(entry))
|
|
243
|
+
throw new Error(`the entry of ${dir} under "projects" is not an object; fix or delete the file`);
|
|
244
|
+
merged[dir] = { ...entry, hasTrustDialogAccepted: true };
|
|
245
|
+
}
|
|
246
|
+
return { ...doc, projects: merged };
|
|
247
|
+
}
|
|
248
|
+
/** `outer` is `inner` or holds it. */
|
|
249
|
+
const holds = (outer, inner) => {
|
|
250
|
+
const way = relative(outer, inner);
|
|
251
|
+
return way === '' || (way !== '..' && !way.startsWith(`..${sep}`) && !isAbsolute(way));
|
|
252
|
+
};
|
|
253
|
+
/**
|
|
254
|
+
* Claude Code trusts every non-git folder below a trusted one, so trust for the root, for the home directory or for a
|
|
255
|
+
* folder above gonogo's or Claude's own files would switch the trust dialog and the hook gate off far beyond the
|
|
256
|
+
* project the owner meant. Returns why `dirs` (the folder and its real path) must not be trusted, or null.
|
|
257
|
+
* shortcut: paths are compared as spelled, so another letter case of the same folder on a case-insensitive disk passes; upgrade when a real run shows it.
|
|
258
|
+
*/
|
|
259
|
+
async function broadTrustReason(dirs, guards) {
|
|
260
|
+
for (const dir of dirs) {
|
|
261
|
+
if (dir === parse(dir).root)
|
|
262
|
+
return 'it is the root of the file system';
|
|
263
|
+
for (const guard of guards) {
|
|
264
|
+
for (const path of new Set([guard.path, await realpath(guard.path).catch(() => guard.path)])) {
|
|
265
|
+
if (!holds(dir, path))
|
|
266
|
+
continue;
|
|
267
|
+
return relative(dir, path) === '' ? `it is ${guard.what}` : `it holds ${guard.what} (${guard.path})`;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Records and verifies the trust of `dirs` in `file` and returns the path that was written. Rewrites until a read-back
|
|
275
|
+
* shows the keys, because claude rewrites the same file on every start (O11) and a lost update would leave the hooks
|
|
276
|
+
* of an IS_DEMO child silent with nothing on screen to say so.
|
|
277
|
+
*/
|
|
278
|
+
async function seedTrust(file, dirs) {
|
|
279
|
+
try {
|
|
280
|
+
await mkdir(dirname(file), { recursive: true, mode: DIR_MODE });
|
|
281
|
+
// a symlinked file keeps being a symlink: rename over it would replace the link with a copy
|
|
282
|
+
const target = await realpath(file).catch(() => file);
|
|
283
|
+
for (let attempt = 1;; attempt++) {
|
|
284
|
+
const doc = await readJsonObject(target);
|
|
285
|
+
if (isTrusted(doc, dirs))
|
|
286
|
+
return target;
|
|
287
|
+
const mode = await stat(target).then((info) => info.mode & 0o777, () => FILE_MODE);
|
|
288
|
+
await writeFileAtomic(target, JSON.stringify(withTrust(doc, dirs), null, 2), mode);
|
|
289
|
+
if (isTrusted(await readJsonObject(target), dirs))
|
|
290
|
+
return target;
|
|
291
|
+
if (attempt >= TRUST_VERIFY_ATTEMPTS) {
|
|
292
|
+
throw new Error(`the trust entry did not stay in the file (${TRUST_VERIFY_ATTEMPTS} attempts)`);
|
|
293
|
+
}
|
|
294
|
+
await sleep(TRUST_VERIFY_DELAY_MS);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
throw new Error(`cannot record folder trust in ${file}: ${errorText(error)}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Claude keeps a transcript where the working directory was when the session began, so a later start from another
|
|
303
|
+
* directory must still find it: look in the project directory of each candidate, then in every project directory.
|
|
304
|
+
*/
|
|
305
|
+
async function transcriptExists(projectsRoot, dirs, sessionId) {
|
|
306
|
+
const file = `${sessionId}.jsonl`;
|
|
307
|
+
const isFile = (path) => stat(path).then((info) => info.isFile(), () => false);
|
|
308
|
+
for (const dir of dirs) {
|
|
309
|
+
if (await isFile(join(projectsRoot, transcriptDirName(dir), file)))
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
const names = await readdir(projectsRoot).catch(() => []);
|
|
313
|
+
for (const name of names) {
|
|
314
|
+
if (await isFile(join(projectsRoot, name, file)))
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
/* ---- the launcher ---- */
|
|
320
|
+
export function createLauncher(options) {
|
|
321
|
+
const log = options.log ?? nullLogger;
|
|
322
|
+
const homeDir = resolve(options.homeDir);
|
|
323
|
+
const byToken = new Map();
|
|
324
|
+
/** `container`: the Clean Room container of that start, removed when the start ends. */
|
|
325
|
+
const byAgent = new Map();
|
|
326
|
+
/** A removal still running per agent: the next start of that agent waits for it, so it never removes the new container. */
|
|
327
|
+
const removals = new Map();
|
|
328
|
+
let trustChain = Promise.resolve();
|
|
329
|
+
const agentDir = (name) => {
|
|
330
|
+
if (typeof name !== 'string' || !NAME_RE.test(name))
|
|
331
|
+
throw new Error('invalid agent name');
|
|
332
|
+
return join(homeDir, AGENTS_DIR, name);
|
|
333
|
+
};
|
|
334
|
+
const issue = (name, generation) => {
|
|
335
|
+
const older = byAgent.get(name);
|
|
336
|
+
if (older)
|
|
337
|
+
byToken.delete(older.token);
|
|
338
|
+
const token = randomBytes(TOKEN_BYTES).toString('hex');
|
|
339
|
+
byToken.set(token, { agent: name, generation });
|
|
340
|
+
byAgent.set(name, { token, generation });
|
|
341
|
+
return token;
|
|
342
|
+
};
|
|
343
|
+
// Synchronous on purpose: a restart that follows the exit must not find this unlink still queued behind its own token write
|
|
344
|
+
const revoke = (name, generation) => {
|
|
345
|
+
const current = byAgent.get(name);
|
|
346
|
+
if (!current || current.generation !== generation)
|
|
347
|
+
return;
|
|
348
|
+
byToken.delete(current.token);
|
|
349
|
+
byAgent.delete(name);
|
|
350
|
+
if (current.container !== undefined)
|
|
351
|
+
removals.set(name, removeContainer(current.container, options.env ?? process.env));
|
|
352
|
+
try {
|
|
353
|
+
unlinkSync(join(agentDir(name), AGENT_TOKEN_FILE));
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
if (errorCode(error) !== 'ENOENT')
|
|
357
|
+
log.warn(`could not delete the token file of ${name}: ${errorText(error)}`);
|
|
358
|
+
}
|
|
359
|
+
log.debug(`revoked the token of ${name} (generation ${generation})`);
|
|
360
|
+
};
|
|
361
|
+
// Several agents start together and each one reads, merges and renames the same file
|
|
362
|
+
const recordTrust = (file, dirs) => {
|
|
363
|
+
const run = trustChain.then(() => seedTrust(file, dirs));
|
|
364
|
+
trustChain = run.catch(() => undefined);
|
|
365
|
+
return run;
|
|
366
|
+
};
|
|
367
|
+
const recheckTrust = (name, shown, written, dirs) => {
|
|
368
|
+
setTimeout(() => {
|
|
369
|
+
readJsonObject(written)
|
|
370
|
+
.then((doc) => {
|
|
371
|
+
if (!isTrusted(doc, dirs)) {
|
|
372
|
+
log.warn(`the trust entry of ${name}'s folder is no longer in ${shown} ${TRUST_RECHECK_MS / 1000} s after its start; the next start records it again`);
|
|
373
|
+
}
|
|
374
|
+
})
|
|
375
|
+
.catch((error) => log.debug(`could not re-check the folder trust of ${name}: ${errorText(error)}`));
|
|
376
|
+
}, TRUST_RECHECK_MS).unref();
|
|
377
|
+
};
|
|
378
|
+
/** A custom command is a plain terminal: no settings, MCP file, token or memory file, and no folder trust. */
|
|
379
|
+
const prepareCustom = async (agent) => {
|
|
380
|
+
const { name } = agent;
|
|
381
|
+
let words;
|
|
382
|
+
try {
|
|
383
|
+
words = parseAgentCmd(agent.command);
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
throw new Error(`the command of ${name} cannot be read: ${errorText(error).replace(/^GONOGO_AGENT_CMD: /, '')}`);
|
|
387
|
+
}
|
|
388
|
+
const [file, ...args] = words ?? [];
|
|
389
|
+
if (!file)
|
|
390
|
+
throw new Error(`the command of ${name} is empty`);
|
|
391
|
+
const dirInfo = await stat(agent.dir).catch(() => null);
|
|
392
|
+
if (!dirInfo?.isDirectory())
|
|
393
|
+
throw new Error(`working directory does not exist: ${agent.dir}`);
|
|
394
|
+
return { spec: { file, args, env: buildChildEnv({ base: options.env ?? process.env, token: null, seed: false }), cwd: agent.dir }, flag: 'session-id', token: '' };
|
|
395
|
+
};
|
|
396
|
+
/** Engine Bay: another agent CLI, started by its program name with the files and flags of its adapter (providers.ts). */
|
|
397
|
+
const prepareOther = async (agent, provider, base, hubUrl, memoryPath, token) => {
|
|
398
|
+
const ctx = {
|
|
399
|
+
name: agent.name,
|
|
400
|
+
mode: agent.mode,
|
|
401
|
+
role: agent.role.trim(),
|
|
402
|
+
roleText: buildRoleText(agent.name, agent.role, memoryPath),
|
|
403
|
+
servers: agent.payload?.mcpServers,
|
|
404
|
+
hubUrl,
|
|
405
|
+
agentDir: base,
|
|
406
|
+
tokenFile: join(base, AGENT_TOKEN_FILE),
|
|
407
|
+
token,
|
|
408
|
+
seed: options.seed,
|
|
409
|
+
};
|
|
410
|
+
const start = buildProviderStart(provider, ctx);
|
|
411
|
+
for (const [file, content] of Object.entries(start.files))
|
|
412
|
+
await writeFileAtomic(join(base, file), content, FILE_MODE);
|
|
413
|
+
const env = { ...buildChildEnv({ base: options.env ?? process.env, token, seed: false }), ...start.env };
|
|
414
|
+
log.debug(`prepared ${agent.name} to run ${provider}`);
|
|
415
|
+
return { spec: { file: PROVIDER_INFO[provider].bin, args: start.args, env, cwd: agent.dir }, flag: 'session-id', token };
|
|
416
|
+
};
|
|
417
|
+
const prepareStart = async (agent, opts) => {
|
|
418
|
+
const { name } = agent;
|
|
419
|
+
const base = agentDir(name);
|
|
420
|
+
const provider = agent.provider ?? 'claude';
|
|
421
|
+
if (provider === 'custom')
|
|
422
|
+
return prepareCustom(agent);
|
|
423
|
+
if (typeof agent.sessionId !== 'string' || !UUID_RE.test(agent.sessionId)) {
|
|
424
|
+
throw new Error(`invalid session id for ${name}`);
|
|
425
|
+
}
|
|
426
|
+
if (!PERMISSION_MODES.includes(agent.mode))
|
|
427
|
+
throw new Error(`unknown permission mode for ${name}`);
|
|
428
|
+
const hubUrl = String(options.hubUrl()).replace(/\/+$/, '');
|
|
429
|
+
if (!LOOPBACK_URL_RE.test(hubUrl)) {
|
|
430
|
+
throw new Error(`the hub URL must be http://127.0.0.1:<port> or http://[::1]:<port>, got ${JSON.stringify(hubUrl)}`);
|
|
431
|
+
}
|
|
432
|
+
const env = options.env ?? process.env;
|
|
433
|
+
const dirInfo = await stat(agent.dir).catch(() => null);
|
|
434
|
+
if (!dirInfo?.isDirectory())
|
|
435
|
+
throw new Error(`working directory does not exist: ${agent.dir}`);
|
|
436
|
+
const dir = resolve(agent.dir);
|
|
437
|
+
await mkdir(base, { recursive: true, mode: DIR_MODE });
|
|
438
|
+
if (((await stat(base)).mode & 0o777) !== DIR_MODE)
|
|
439
|
+
await chmod(base, DIR_MODE);
|
|
440
|
+
const memoryPath = join(base, MEMORY_FILE);
|
|
441
|
+
await writeFile(memoryPath, `# Memory of ${name}\n\nNotes that survive restarts. Keep it short.\n`, {
|
|
442
|
+
flag: 'wx',
|
|
443
|
+
mode: FILE_MODE,
|
|
444
|
+
}).catch((error) => {
|
|
445
|
+
if (errorCode(error) !== 'EEXIST')
|
|
446
|
+
throw error;
|
|
447
|
+
});
|
|
448
|
+
const token = issue(name, opts.generation);
|
|
449
|
+
try {
|
|
450
|
+
await writeFileAtomic(join(base, AGENT_TOKEN_FILE), `${token}\n`, FILE_MODE);
|
|
451
|
+
if (provider !== 'claude')
|
|
452
|
+
return await prepareOther(agent, provider, base, hubUrl, memoryPath, token);
|
|
453
|
+
// Clean Room: a container has the worktree and the agent's own folder only, so it gets a home of its own under the agent's folder.
|
|
454
|
+
if (agent.cleanRoom !== undefined)
|
|
455
|
+
await removals.get(name);
|
|
456
|
+
const clean = agent.cleanRoom === undefined ? null : await prepareCleanRoom(agent, homeDir, base, env);
|
|
457
|
+
// A fresh container home has no folder trust and no login, so its dialogs are skipped as in seed mode.
|
|
458
|
+
const seed = options.seed || clean !== null;
|
|
459
|
+
const agentUrl = clean === null ? hubUrl : containerUrl(hubUrl);
|
|
460
|
+
const settingsPath = join(base, SETTINGS_FILE);
|
|
461
|
+
const mcpPath = join(base, MCP_FILE);
|
|
462
|
+
const moveApiKey = seed && hasText(env.ANTHROPIC_API_KEY);
|
|
463
|
+
const settings = buildSettings({ hubUrl: agentUrl, name, mode: agent.mode, memoryPath, apiKeyHelper: moveApiKey });
|
|
464
|
+
await writeFileAtomic(settingsPath, JSON.stringify(settings, null, 2), FILE_MODE);
|
|
465
|
+
await writeFileAtomic(mcpPath, JSON.stringify(buildMcpConfig(agentUrl, agent.payload?.mcpServers), null, 2), FILE_MODE);
|
|
466
|
+
const pluginDir = await writeSkillsPlugin(base, agent.payload?.skills);
|
|
467
|
+
const configDir = hasText(env.CLAUDE_CONFIG_DIR) ? env.CLAUDE_CONFIG_DIR : null;
|
|
468
|
+
const realDir = await realpath(dir).catch(() => dir);
|
|
469
|
+
const trustDirs = clean === null ? [...new Set([realDir, dir])] : [clean.cwd];
|
|
470
|
+
// the folder of the config that claude reads: the owner's, or the container's own home
|
|
471
|
+
const claudeRoot = clean === null ? configDir ?? homedir() : clean.home;
|
|
472
|
+
const claudeJson = join(claudeRoot, CLAUDE_JSON);
|
|
473
|
+
let recheck = null;
|
|
474
|
+
if (seed) {
|
|
475
|
+
const broad = await broadTrustReason(trustDirs, [
|
|
476
|
+
{ path: homedir(), what: 'your home directory' },
|
|
477
|
+
{ path: homeDir, what: "gonogo's home directory" },
|
|
478
|
+
{ path: configDir ?? join(homedir(), '.claude'), what: "Claude Code's configuration folder" },
|
|
479
|
+
]);
|
|
480
|
+
if (broad !== null) {
|
|
481
|
+
throw new Error(`cannot record folder trust for ${dir}: ${broad} and trust covers every folder below it; use a project folder instead`);
|
|
482
|
+
}
|
|
483
|
+
if (moveApiKey && hasText(env.CLAUDE_CODE_OAUTH_TOKEN)) {
|
|
484
|
+
log.warn('both ANTHROPIC_API_KEY and CLAUDE_CODE_OAUTH_TOKEN are set; the API key is used');
|
|
485
|
+
}
|
|
486
|
+
const written = await recordTrust(claudeJson, trustDirs);
|
|
487
|
+
recheck = () => recheckTrust(name, claudeJson, written, trustDirs);
|
|
488
|
+
}
|
|
489
|
+
const projectsRoot = join(clean === null ? configDir ?? join(homedir(), '.claude') : clean.home, 'projects');
|
|
490
|
+
const flag = opts.flag ?? ((await transcriptExists(projectsRoot, clean === null ? [dir, realDir] : [clean.cwd], agent.sessionId)) ? 'resume' : 'session-id');
|
|
491
|
+
const roleText = buildRoleText(name, agent.role, memoryPath) + (clean === null ? '' : `\n${CLEAN_ROOM_NOTE.replace('{branch}', cleanRoomBranch(name))}`);
|
|
492
|
+
const claudeArgs = buildArgv({ flag, sessionId: agent.sessionId, mode: agent.mode, settingsPath, mcpPath, roleText, pluginDir });
|
|
493
|
+
const [file, ...leading] = options.agentCmd?.length ? options.agentCmd : [options.claudeBin ?? CLAUDE_BIN];
|
|
494
|
+
const childEnv = buildChildEnv({ base: env, token, seed });
|
|
495
|
+
let spec;
|
|
496
|
+
if (clean === null) {
|
|
497
|
+
spec = { file, args: [...leading, ...claudeArgs], env: childEnv, cwd: agent.dir };
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
const uid = process.getuid?.();
|
|
501
|
+
const gid = process.getgid?.();
|
|
502
|
+
if (uid === undefined || gid === undefined)
|
|
503
|
+
throw new Error('Clean Room needs a user id: it runs on macOS and Linux only');
|
|
504
|
+
// by name: docker reads the values from its own environment, so no secret is on the command line
|
|
505
|
+
const names = [...CLEAN_ROOM_ENV, ...CLEAN_ROOM_CREDENTIALS].filter((variable) => hasText(childEnv[variable]));
|
|
506
|
+
const command = [file, ...leading, ...claudeArgs];
|
|
507
|
+
const args = buildDockerArgs({ image: cleanRoomImage(agent.cleanRoom ?? {}, env), uid, gid, place: clean, agentDir: base, names, command });
|
|
508
|
+
spec = { file: DOCKER_BIN, args, env: childEnv, cwd: clean.worktree };
|
|
509
|
+
const started = byAgent.get(name);
|
|
510
|
+
if (started?.generation === opts.generation)
|
|
511
|
+
started.container = clean.container;
|
|
512
|
+
}
|
|
513
|
+
const prepared = { spec, flag, token };
|
|
514
|
+
recheck?.();
|
|
515
|
+
log.debug(`prepared ${name} (generation ${opts.generation}) with --${flag}`);
|
|
516
|
+
return prepared;
|
|
517
|
+
}
|
|
518
|
+
catch (error) {
|
|
519
|
+
revoke(name, opts.generation);
|
|
520
|
+
throw error;
|
|
521
|
+
}
|
|
522
|
+
};
|
|
523
|
+
const renameAgentFiles = async (oldName, newName) => {
|
|
524
|
+
const from = agentDir(oldName);
|
|
525
|
+
const to = agentDir(newName);
|
|
526
|
+
const exists = (path) => lstat(path).then(() => true, () => false);
|
|
527
|
+
// The hub shows this text to the owner: no internal path, and a way out
|
|
528
|
+
if (await exists(to)) {
|
|
529
|
+
throw new Error(`the name "${newName}" is taken by a notes folder left over from a removed agent; choose another name, or delete that folder from the agents folder of the gonogo home`);
|
|
530
|
+
}
|
|
531
|
+
if (!(await exists(from)))
|
|
532
|
+
return;
|
|
533
|
+
await rename(from, to);
|
|
534
|
+
};
|
|
535
|
+
return {
|
|
536
|
+
prepareStart,
|
|
537
|
+
resolveToken: (token) => byToken.get(token) ?? null,
|
|
538
|
+
revoke,
|
|
539
|
+
renameAgentFiles,
|
|
540
|
+
memoryPath: (name) => join(agentDir(name), MEMORY_FILE),
|
|
541
|
+
};
|
|
542
|
+
}
|