@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,630 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { accessSync, constants as fsConstants, existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { stat } from 'node:fs/promises';
|
|
4
|
+
import { homedir, hostname } from 'node:os';
|
|
5
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { PROTOCOL_VERSION } from '../shared/protocol.js';
|
|
8
|
+
import { MAX_AGENTS } from '../shared/protocol.js';
|
|
9
|
+
import { CLAUDE_BIN, DEFAULT_HOME_DIRNAME, DEFAULT_HOST, DEFAULT_MAX_HOPS, DEFAULT_PORT, DOWNLINK_HISTORY, MAX_HOPS_LIMIT, MAX_WORKING_ENV, REDLINE_ENV, ROSTER_ROLE_CHARS, SHUTDOWN_MAX_MS, STATION_ENV, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_PREFIXES, createLogger, nullLogger, } from './constants.js';
|
|
10
|
+
import { createDocking, stationName } from './docking.js';
|
|
11
|
+
import { createDownlink } from './downlink.js';
|
|
12
|
+
import { createHub } from './hub.js';
|
|
13
|
+
import { checkCleanRoom } from './cleanroom.js';
|
|
14
|
+
import { openHome } from './home.js';
|
|
15
|
+
import { createLauncher, parseAgentCmd } from './launcher.js';
|
|
16
|
+
import { createTerminalHost } from './terminal.js';
|
|
17
|
+
import { createWebServer } from './web.js';
|
|
18
|
+
import { createPropellant } from './propellant.js';
|
|
19
|
+
import { createRelay } from './relay.js';
|
|
20
|
+
import { createSchedules } from './schedules.js';
|
|
21
|
+
import { createLiveries } from './livery.js';
|
|
22
|
+
import { createMissionLog } from './missionlog.js';
|
|
23
|
+
import { createTasks } from './tasks.js';
|
|
24
|
+
import { createUplinks } from './uplinks.js';
|
|
25
|
+
import { installedProviders, onPath } from './providers.js';
|
|
26
|
+
/* ---------------------------------------------------------------- arguments */
|
|
27
|
+
export const USAGE = `Usage: gonogo [options]
|
|
28
|
+
|
|
29
|
+
Run a mission-control room of Claude Code agents from a browser tab.
|
|
30
|
+
|
|
31
|
+
Options:
|
|
32
|
+
--port <n> listen port (default ${DEFAULT_PORT}; env GONOGO_PORT)
|
|
33
|
+
--host <addr> bind address (default ${DEFAULT_HOST}; env GONOGO_HOST)
|
|
34
|
+
--home <dir> state directory (default ~/${DEFAULT_HOME_DIRNAME}; env GONOGO_HOME)
|
|
35
|
+
--seed-claude record Claude's folder trust and skip its startup dialogs (env GONOGO_SEED_CLAUDE=1)
|
|
36
|
+
--allow-host <name> accept this Host name too, for a reverse proxy; repeatable (env GONOGO_ALLOWED_HOSTS, comma list)
|
|
37
|
+
-h, --help show this help
|
|
38
|
+
-v, --version show the version
|
|
39
|
+
|
|
40
|
+
Environment:
|
|
41
|
+
GONOGO_MAX_HOPS hop cap for messages between agents (default ${DEFAULT_MAX_HOPS})
|
|
42
|
+
GONOGO_MAX_WORKING Max Q: at most this many Claude agents work at once, 1 to ${MAX_AGENTS} (default off)
|
|
43
|
+
GONOGO_STATION this station's name for Docking (default: the host name)
|
|
44
|
+
GONOGO_AGENT_CMD command that replaces claude
|
|
45
|
+
GONOGO_CLEANROOM_IMAGE Docker image of a Clean Room console (default ghcr.io/ulm0/gonogo)
|
|
46
|
+
GONOGO_LOG_LEVEL debug, info, warn or error (default info)
|
|
47
|
+
GONOGO_SCRUB_ENV extra variables to keep out of the agents (comma list; a name ending in _ is a prefix)
|
|
48
|
+
`;
|
|
49
|
+
const VALUE_FLAGS = ['--port', '--host', '--home', '--allow-host'];
|
|
50
|
+
function parsePort(value, label) {
|
|
51
|
+
const port = /^\d{1,5}$/.test(value) ? Number(value) : -1;
|
|
52
|
+
if (port < 0 || port > 65535)
|
|
53
|
+
throw new Error(`invalid ${label} "${value}" (use a number from 0 to 65535)`);
|
|
54
|
+
return port;
|
|
55
|
+
}
|
|
56
|
+
/** Flags only; the environment fallbacks are applied by startGonogo, so a flag always wins. */
|
|
57
|
+
export function parseArgs(argv) {
|
|
58
|
+
if (argv.includes('--help') || argv.includes('-h'))
|
|
59
|
+
return { kind: 'help' };
|
|
60
|
+
if (argv.includes('--version') || argv.includes('-v'))
|
|
61
|
+
return { kind: 'version' };
|
|
62
|
+
const options = {};
|
|
63
|
+
const allowedHosts = [];
|
|
64
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
65
|
+
const arg = argv[i] ?? '';
|
|
66
|
+
if (arg === '--seed-claude') {
|
|
67
|
+
options.seed = true;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const eq = arg.startsWith('--') ? arg.indexOf('=') : -1;
|
|
71
|
+
const flag = eq === -1 ? arg : arg.slice(0, eq);
|
|
72
|
+
if (!VALUE_FLAGS.includes(flag))
|
|
73
|
+
return { kind: 'error', message: `unknown option ${arg}` };
|
|
74
|
+
let value;
|
|
75
|
+
if (eq !== -1) {
|
|
76
|
+
value = arg.slice(eq + 1);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
const next = argv[i + 1];
|
|
80
|
+
if (next === undefined || next.startsWith('-'))
|
|
81
|
+
return { kind: 'error', message: `${flag} needs a value` };
|
|
82
|
+
value = next;
|
|
83
|
+
i += 1;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
switch (flag) {
|
|
87
|
+
case '--port':
|
|
88
|
+
options.port = parsePort(value, 'port');
|
|
89
|
+
break;
|
|
90
|
+
case '--host':
|
|
91
|
+
options.host = value;
|
|
92
|
+
break;
|
|
93
|
+
case '--home':
|
|
94
|
+
if (value === '')
|
|
95
|
+
throw new Error('--home needs a directory');
|
|
96
|
+
options.home = value;
|
|
97
|
+
break;
|
|
98
|
+
default:
|
|
99
|
+
if (value.trim() === '')
|
|
100
|
+
throw new Error('--allow-host needs a host name');
|
|
101
|
+
allowedHosts.push(value.trim());
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
return { kind: 'error', message: e instanceof Error ? e.message : String(e) };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// any --allow-host replaces the GONOGO_ALLOWED_HOSTS list, like every other flag replaces its variable
|
|
109
|
+
if (allowedHosts.length > 0)
|
|
110
|
+
options.allowedHosts = allowedHosts;
|
|
111
|
+
return { kind: 'run', options };
|
|
112
|
+
}
|
|
113
|
+
/** "localhost" would bind whichever address the resolver lists first, often ::1 only, and every 127.0.0.1 URL handed to the agents would be refused. */
|
|
114
|
+
function bindHost(raw) {
|
|
115
|
+
const host = raw.trim().replace(/^\[|\]$/g, '');
|
|
116
|
+
return host === '' || host.toLowerCase() === 'localhost' ? '127.0.0.1' : host;
|
|
117
|
+
}
|
|
118
|
+
function defaultStaticDir() {
|
|
119
|
+
const dir = fileURLToPath(new URL('../client/', import.meta.url));
|
|
120
|
+
return existsSync(join(dir, 'index.html')) ? dir : null;
|
|
121
|
+
}
|
|
122
|
+
export function resolveSettings(options, log = nullLogger) {
|
|
123
|
+
const env = options.env ?? process.env;
|
|
124
|
+
const port = options.port ?? (env.GONOGO_PORT ? parsePort(env.GONOGO_PORT, 'GONOGO_PORT') : DEFAULT_PORT);
|
|
125
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
126
|
+
throw new Error(`invalid port "${port}" (use a number from 0 to 65535)`);
|
|
127
|
+
const hopsText = options.maxHops !== undefined ? String(options.maxHops) : env.GONOGO_MAX_HOPS;
|
|
128
|
+
let maxHops = DEFAULT_MAX_HOPS;
|
|
129
|
+
if (hopsText !== undefined && hopsText !== '') {
|
|
130
|
+
const hops = /^\d{1,4}$/.test(hopsText) ? Number(hopsText) : 0;
|
|
131
|
+
if (hops >= 1 && hops <= MAX_HOPS_LIMIT)
|
|
132
|
+
maxHops = hops;
|
|
133
|
+
else
|
|
134
|
+
log.warn(`ignoring max hops "${hopsText}": use a whole number from 1 to ${MAX_HOPS_LIMIT}; using ${DEFAULT_MAX_HOPS}`);
|
|
135
|
+
}
|
|
136
|
+
const workingText = options.maxWorking !== undefined ? String(options.maxWorking) : env[MAX_WORKING_ENV];
|
|
137
|
+
let maxWorking = null;
|
|
138
|
+
if (workingText !== undefined && workingText !== '') {
|
|
139
|
+
const working = /^\d{1,3}$/.test(workingText) ? Number(workingText) : 0;
|
|
140
|
+
if (working >= 1 && working <= MAX_AGENTS)
|
|
141
|
+
maxWorking = working;
|
|
142
|
+
else
|
|
143
|
+
log.warn(`ignoring ${MAX_WORKING_ENV} "${workingText}": use a whole number from 1 to ${MAX_AGENTS}; the load limit stays off`);
|
|
144
|
+
}
|
|
145
|
+
const redlineText = env[REDLINE_ENV]?.trim().toLowerCase();
|
|
146
|
+
const redline = !(redlineText === 'off' || redlineText === '0' || redlineText === 'false');
|
|
147
|
+
const seedText = env.GONOGO_SEED_CLAUDE?.toLowerCase();
|
|
148
|
+
return {
|
|
149
|
+
host: bindHost(options.host ?? env.GONOGO_HOST ?? DEFAULT_HOST),
|
|
150
|
+
port,
|
|
151
|
+
home: resolve(options.home ?? (env.GONOGO_HOME || join(homedir(), DEFAULT_HOME_DIRNAME))),
|
|
152
|
+
seed: options.seed ?? (seedText === '1' || seedText === 'true'),
|
|
153
|
+
agentCmd: options.agentCmd !== undefined ? options.agentCmd : parseAgentCmd(env.GONOGO_AGENT_CMD),
|
|
154
|
+
cwd: resolve(options.cwd ?? process.cwd()),
|
|
155
|
+
maxHops,
|
|
156
|
+
maxWorking,
|
|
157
|
+
redline,
|
|
158
|
+
allowedHosts: options.allowedHosts ??
|
|
159
|
+
(env.GONOGO_ALLOWED_HOSTS ?? '')
|
|
160
|
+
.split(',')
|
|
161
|
+
.map((h) => h.trim())
|
|
162
|
+
.filter((h) => h !== ''),
|
|
163
|
+
staticDir: options.staticDir !== undefined ? options.staticDir : defaultStaticDir(),
|
|
164
|
+
env,
|
|
165
|
+
checkClaude: options.checkClaude ?? true,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function packageVersion() {
|
|
169
|
+
try {
|
|
170
|
+
const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
171
|
+
if (typeof pkg === 'object' && pkg !== null && 'version' in pkg && typeof pkg.version === 'string')
|
|
172
|
+
return pkg.version;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
// an unreadable package.json only costs the version string
|
|
176
|
+
}
|
|
177
|
+
return '0.0.0';
|
|
178
|
+
}
|
|
179
|
+
/** The host of the printed URL: a wildcard bind is reached on loopback, an IPv6 address needs brackets (contract 0.5 item 14). */
|
|
180
|
+
function displayHost(host) {
|
|
181
|
+
if (['0.0.0.0', '::', '127.0.0.1'].includes(host))
|
|
182
|
+
return '127.0.0.1';
|
|
183
|
+
return host.includes(':') ? `[${host}]` : host;
|
|
184
|
+
}
|
|
185
|
+
function listenError(e, host, port) {
|
|
186
|
+
const code = typeof e === 'object' && e !== null && 'code' in e && typeof e.code === 'string' ? e.code : undefined;
|
|
187
|
+
const where = `${host.includes(':') ? `[${host}]` : host}:${port}`;
|
|
188
|
+
if (code === 'EADDRINUSE')
|
|
189
|
+
return new Error(`cannot listen on ${where}: the port is already in use (EADDRINUSE). Stop whatever uses it, or pass --port.`);
|
|
190
|
+
if (code === 'EACCES')
|
|
191
|
+
return new Error(`cannot listen on ${where}: permission denied (EACCES). Ports below 1024 need extra rights; pass --port.`);
|
|
192
|
+
if (code === 'EADDRNOTAVAIL')
|
|
193
|
+
return new Error(`cannot listen on ${where}: that address does not belong to this machine (EADDRNOTAVAIL). Check --host.`);
|
|
194
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
195
|
+
}
|
|
196
|
+
/* ---------------------------------------------------------------- start */
|
|
197
|
+
export async function startGonogo(options = {}) {
|
|
198
|
+
const log = options.log ?? nullLogger;
|
|
199
|
+
const settings = resolveSettings(options, log);
|
|
200
|
+
const { host, port, seed, agentCmd, cwd, maxHops, maxWorking, redline, allowedHosts, staticDir, env } = settings;
|
|
201
|
+
if (agentCmd === null && settings.checkClaude && !onPath(CLAUDE_BIN, env.PATH)) {
|
|
202
|
+
throw new Error('the claude CLI was not found on PATH. Install Claude Code and sign in, or set GONOGO_AGENT_CMD.');
|
|
203
|
+
}
|
|
204
|
+
const home = openHome(settings.home, log);
|
|
205
|
+
let hub;
|
|
206
|
+
let hubStarting = false;
|
|
207
|
+
let web;
|
|
208
|
+
let terminals;
|
|
209
|
+
let baseUrl = '';
|
|
210
|
+
let ready = false;
|
|
211
|
+
let running;
|
|
212
|
+
const startedAt = Date.now();
|
|
213
|
+
const version = packageVersion();
|
|
214
|
+
const bound = { host, port };
|
|
215
|
+
try {
|
|
216
|
+
// a corrupt agents.json stops the start here, before anything listens
|
|
217
|
+
home.loadRoster();
|
|
218
|
+
const terminalHost = createTerminalHost({ log: log.child('terminal') });
|
|
219
|
+
terminals = terminalHost;
|
|
220
|
+
for (const dir of new Set([home.dir, cwd])) {
|
|
221
|
+
try {
|
|
222
|
+
accessSync(dir, fsConstants.W_OK);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
log.warn(`${dir} is not writable by uid ${process.getuid?.() ?? '?'}; chown it to that uid`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const launcher = createLauncher({
|
|
229
|
+
homeDir: home.dir,
|
|
230
|
+
hubUrl: () => baseUrl,
|
|
231
|
+
seed,
|
|
232
|
+
env,
|
|
233
|
+
agentCmd,
|
|
234
|
+
log: log.child('launcher'),
|
|
235
|
+
});
|
|
236
|
+
const propellant = createPropellant({
|
|
237
|
+
dir: home.dir,
|
|
238
|
+
projectsRoot: join(env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude'), 'projects'),
|
|
239
|
+
now: () => Date.now(),
|
|
240
|
+
log: log.child('propellant'),
|
|
241
|
+
});
|
|
242
|
+
await propellant.load();
|
|
243
|
+
const downlink = createDownlink({
|
|
244
|
+
dir: home.dir,
|
|
245
|
+
now: () => Date.now(),
|
|
246
|
+
history: () => home.loadRecentMessages(DOWNLINK_HISTORY),
|
|
247
|
+
emit: (view) => web?.broadcast({ t: 'downlink', downlink: view }),
|
|
248
|
+
log: log.child('downlink'),
|
|
249
|
+
});
|
|
250
|
+
await downlink.load();
|
|
251
|
+
const relay = createRelay({
|
|
252
|
+
dir: home.dir,
|
|
253
|
+
now: () => Date.now(),
|
|
254
|
+
fetch: options.fetch ?? ((url, init) => fetch(url, init)),
|
|
255
|
+
sleep: (ms) => new Promise((done) => setTimeout(done, ms).unref()),
|
|
256
|
+
log: log.child('relay'),
|
|
257
|
+
});
|
|
258
|
+
await relay.load();
|
|
259
|
+
/** What the parts of the server tell the Director's inbox goes to the targets of Relay too. */
|
|
260
|
+
const tell = (kind, text) => {
|
|
261
|
+
downlink.post(kind, text);
|
|
262
|
+
relay.event(kind, text);
|
|
263
|
+
};
|
|
264
|
+
let seq = home.lastMessageSeq();
|
|
265
|
+
// arrow functions on purpose: nothing here relies on `this` of the object it came from
|
|
266
|
+
const io = {
|
|
267
|
+
now: () => Date.now(),
|
|
268
|
+
setTimer: (fn, ms) => setTimeout(fn, ms).unref(),
|
|
269
|
+
clearTimer: (handle) => clearTimeout(handle),
|
|
270
|
+
newMessageId: () => 'm' + ++seq,
|
|
271
|
+
newSessionId: () => randomUUID(),
|
|
272
|
+
checkDirectory: async (p) => {
|
|
273
|
+
if (!isAbsolute(p))
|
|
274
|
+
return { ok: false, error: 'directory must be an absolute path' };
|
|
275
|
+
let info;
|
|
276
|
+
try {
|
|
277
|
+
info = await stat(p);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return { ok: false, error: `directory does not exist: ${p}` };
|
|
281
|
+
}
|
|
282
|
+
if (!info.isDirectory())
|
|
283
|
+
return { ok: false, error: `not a directory: ${p}` };
|
|
284
|
+
return { ok: true, path: resolve(p) };
|
|
285
|
+
},
|
|
286
|
+
checkCleanRoom: (dir) => checkCleanRoom(dir, env),
|
|
287
|
+
loadRoster: async () => home.loadRoster(),
|
|
288
|
+
saveRoster: (r) => home.saveRoster(r),
|
|
289
|
+
loadHistory: async (n) => home.loadRecentMessages(n),
|
|
290
|
+
logMessage: (r) => home.appendMessage(r),
|
|
291
|
+
renameAgentFiles: async (oldName, newName) => {
|
|
292
|
+
await launcher.renameAgentFiles(oldName, newName);
|
|
293
|
+
terminalHost.rename(oldName, newName);
|
|
294
|
+
},
|
|
295
|
+
spawn: async (req) => {
|
|
296
|
+
const prepared = await launcher.prepareStart(req.agent, { generation: req.generation, flag: req.flag });
|
|
297
|
+
try {
|
|
298
|
+
const { pid } = terminalHost.spawn(req.agent.name, req.generation, prepared.spec);
|
|
299
|
+
return { generation: req.generation, flag: prepared.flag, pid };
|
|
300
|
+
}
|
|
301
|
+
catch (e) {
|
|
302
|
+
launcher.revoke(req.agent.name, req.generation);
|
|
303
|
+
throw e;
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
stop: (name, generation) => terminalHost.stop(name, generation),
|
|
307
|
+
typePointer: (name, generation, text) => terminalHost.submit(name, generation, text),
|
|
308
|
+
// TerminalHost.write has no generation: only keys for the running process of that generation may be typed.
|
|
309
|
+
press: (name, generation, data) => {
|
|
310
|
+
const info = terminalHost.info(name);
|
|
311
|
+
return info !== null && info.running && info.generation === generation && terminalHost.write(name, data);
|
|
312
|
+
},
|
|
313
|
+
meter: (name, _generation, transcriptPath) => {
|
|
314
|
+
void propellant.record(name, transcriptPath).then((tokens) => {
|
|
315
|
+
if (tokens === 0 || !hub)
|
|
316
|
+
return;
|
|
317
|
+
web?.broadcast({ t: 'propellant', propellant: propellant.view() });
|
|
318
|
+
const over = propellant.over(name);
|
|
319
|
+
if (over === null)
|
|
320
|
+
return;
|
|
321
|
+
// a room limit stops every Claude agent that runs, an agent's own limit only that agent
|
|
322
|
+
const names = over.scope === 'room' ? hub.views().filter((v) => v.provider === 'claude').map((v) => v.name) : [name];
|
|
323
|
+
for (const n of names) {
|
|
324
|
+
try {
|
|
325
|
+
hub.trip(n, over.reason);
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
log.debug(`could not trip ${n}`, e);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
},
|
|
333
|
+
screen: (name) => terminalHost.screen(name),
|
|
334
|
+
title: (name) => terminalHost.title(name),
|
|
335
|
+
outputBytes: (name) => terminalHost.outputBytes(name),
|
|
336
|
+
forget: (name) => terminalHost.forget?.(name),
|
|
337
|
+
emit: (event) => {
|
|
338
|
+
web?.broadcast(event);
|
|
339
|
+
downlink.observe(event);
|
|
340
|
+
relay.observe(event);
|
|
341
|
+
},
|
|
342
|
+
notify: tell,
|
|
343
|
+
log: log.child('hub'),
|
|
344
|
+
};
|
|
345
|
+
const hubInstance = createHub(io, { maxHops, bossDir: cwd, maxWorking, redline });
|
|
346
|
+
hub = hubInstance;
|
|
347
|
+
// subscribed before the first spawn; the revoke comes first so a hook that is still in flight after the exit gets a 401
|
|
348
|
+
terminalHost.onEvent((event) => {
|
|
349
|
+
if (event.kind === 'exit')
|
|
350
|
+
launcher.revoke(event.name, event.generation);
|
|
351
|
+
hubInstance.onTerminalEvent(event);
|
|
352
|
+
});
|
|
353
|
+
const info = () => ({
|
|
354
|
+
protocol: PROTOCOL_VERSION,
|
|
355
|
+
version,
|
|
356
|
+
cwd,
|
|
357
|
+
home: home.dir,
|
|
358
|
+
host: bound.host,
|
|
359
|
+
port: bound.port,
|
|
360
|
+
seed,
|
|
361
|
+
agentCmd: agentCmd ? agentCmd.join(' ') : null,
|
|
362
|
+
maxHops,
|
|
363
|
+
startedAt,
|
|
364
|
+
installed: installedProviders(env.PATH, agentCmd !== null),
|
|
365
|
+
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
366
|
+
});
|
|
367
|
+
const schedules = createSchedules({
|
|
368
|
+
dir: home.dir,
|
|
369
|
+
now: io.now,
|
|
370
|
+
setTimer: io.setTimer,
|
|
371
|
+
clearTimer: io.clearTimer,
|
|
372
|
+
send: (request) => hubInstance.sendFromUser(request),
|
|
373
|
+
emit: (list) => web?.broadcast({ t: 'schedules', schedules: list }),
|
|
374
|
+
notify: tell,
|
|
375
|
+
log: log.child('launch window'),
|
|
376
|
+
});
|
|
377
|
+
const uplinks = createUplinks({
|
|
378
|
+
dir: home.dir,
|
|
379
|
+
now: io.now,
|
|
380
|
+
send: (request) => hubInstance.sendFromUser(request),
|
|
381
|
+
emit: (list) => web?.broadcast({ t: 'uplinks', uplinks: list }),
|
|
382
|
+
notify: tell,
|
|
383
|
+
inbound: relay,
|
|
384
|
+
log: log.child('uplink'),
|
|
385
|
+
});
|
|
386
|
+
const tasks = createTasks({
|
|
387
|
+
dir: home.dir,
|
|
388
|
+
now: io.now,
|
|
389
|
+
isAgent: (name) => hubInstance.views().some((v) => v.name === name),
|
|
390
|
+
send: (actor, request) => actor.kind === 'user'
|
|
391
|
+
? hubInstance.sendFromUser(request)
|
|
392
|
+
: actor.kind === 'agent'
|
|
393
|
+
? hubInstance.sendFromAgent(actor.name, actor.generation, request)
|
|
394
|
+
: hubInstance.sendFromStation(actor.station, { from: 'director', to: request.to, subject: request.subject ?? '', body: request.body, hops: 0 }),
|
|
395
|
+
emit: (list) => web?.broadcast({ t: 'tasks', tasks: list }),
|
|
396
|
+
notify: tell,
|
|
397
|
+
log: log.child('flight plan'),
|
|
398
|
+
});
|
|
399
|
+
const docking = createDocking({
|
|
400
|
+
dir: home.dir,
|
|
401
|
+
name: stationName(env[STATION_ENV], hostname()),
|
|
402
|
+
now: io.now,
|
|
403
|
+
fetch: options.fetch ?? ((url, init) => fetch(url, init)),
|
|
404
|
+
deliver: (station, message) => hubInstance.sendFromStation(station, message),
|
|
405
|
+
roster: () => hubInstance.views().map((v) => ({ name: v.name, role: v.role.slice(0, ROSTER_ROLE_CHARS), state: v.state, boss: v.boss })),
|
|
406
|
+
tasks,
|
|
407
|
+
emit: (view) => web?.broadcast({ t: 'docking', docking: view }),
|
|
408
|
+
log: log.child('docking'),
|
|
409
|
+
});
|
|
410
|
+
io.dock = docking;
|
|
411
|
+
const missionLog = createMissionLog({
|
|
412
|
+
dir: home.dir,
|
|
413
|
+
now: io.now,
|
|
414
|
+
emit: (frame) => web?.broadcast(frame),
|
|
415
|
+
log: log.child('mission log'),
|
|
416
|
+
});
|
|
417
|
+
const liveries = createLiveries({
|
|
418
|
+
dir: home.dir,
|
|
419
|
+
send: (request) => hubInstance.sendFromUser(request),
|
|
420
|
+
emit: (frame) => web?.broadcast(frame),
|
|
421
|
+
notify: tell,
|
|
422
|
+
log: log.child('livery'),
|
|
423
|
+
});
|
|
424
|
+
const webServer = createWebServer({
|
|
425
|
+
host,
|
|
426
|
+
port,
|
|
427
|
+
browserToken: home.browserToken,
|
|
428
|
+
allowedHosts,
|
|
429
|
+
staticDir,
|
|
430
|
+
hub: hubInstance,
|
|
431
|
+
terminals: terminalHost,
|
|
432
|
+
resolveToken: (token) => launcher.resolveToken(token),
|
|
433
|
+
info,
|
|
434
|
+
isReady: () => ready,
|
|
435
|
+
propellant,
|
|
436
|
+
schedules,
|
|
437
|
+
uplinks,
|
|
438
|
+
tasks,
|
|
439
|
+
downlink,
|
|
440
|
+
missionLog,
|
|
441
|
+
liveries,
|
|
442
|
+
relay,
|
|
443
|
+
docking,
|
|
444
|
+
log: log.child('web'),
|
|
445
|
+
});
|
|
446
|
+
web = webServer;
|
|
447
|
+
let addr;
|
|
448
|
+
try {
|
|
449
|
+
addr = await webServer.listen();
|
|
450
|
+
}
|
|
451
|
+
catch (e) {
|
|
452
|
+
throw listenError(e, host, port);
|
|
453
|
+
}
|
|
454
|
+
bound.host = addr.host;
|
|
455
|
+
bound.port = addr.port;
|
|
456
|
+
// agents are handed a loopback URL whatever the bind address is: claude blocks http hooks to private addresses (contract 2.8 step 8)
|
|
457
|
+
baseUrl = `http://${host === '::1' ? '[::1]' : '127.0.0.1'}:${addr.port}`;
|
|
458
|
+
// before the hub starts any agent: a task_create that came first would take an id of the file and lose that task
|
|
459
|
+
await tasks.load();
|
|
460
|
+
await missionLog.load();
|
|
461
|
+
await liveries.load();
|
|
462
|
+
await docking.load();
|
|
463
|
+
hubStarting = true;
|
|
464
|
+
await hubInstance.start();
|
|
465
|
+
await schedules.load();
|
|
466
|
+
await uplinks.load();
|
|
467
|
+
ready = true;
|
|
468
|
+
docking.start();
|
|
469
|
+
let stopping;
|
|
470
|
+
const step = async (what, run) => {
|
|
471
|
+
try {
|
|
472
|
+
await run();
|
|
473
|
+
}
|
|
474
|
+
catch (e) {
|
|
475
|
+
log.error(`${what} failed`, e);
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
const shutdown = async () => {
|
|
479
|
+
// no schedule fires from here on
|
|
480
|
+
await step('schedules close', () => schedules.close());
|
|
481
|
+
// the hub first: it refuses new lifecycle calls from here on, while hooks, MCP and open sockets keep working so the agents can finish
|
|
482
|
+
await step('hub shutdown', () => hubInstance.shutdown());
|
|
483
|
+
await step('terminal shutdown', () => terminalHost.stopAll());
|
|
484
|
+
await step('web server close', () => webServer.close());
|
|
485
|
+
await step('docking close', () => docking.close());
|
|
486
|
+
await step('uplinks close', () => uplinks.close());
|
|
487
|
+
await step('tasks close', () => tasks.close());
|
|
488
|
+
await step('mission log close', () => missionLog.close());
|
|
489
|
+
await step('livery close', () => liveries.close());
|
|
490
|
+
await step('relay close', () => relay.close());
|
|
491
|
+
await step('downlink close', () => downlink.close());
|
|
492
|
+
await step('propellant close', () => propellant.close());
|
|
493
|
+
await step('home close', () => home.close());
|
|
494
|
+
};
|
|
495
|
+
const stop = () => {
|
|
496
|
+
stopping ??= (async () => {
|
|
497
|
+
let timer;
|
|
498
|
+
const tooLong = new Promise((done) => {
|
|
499
|
+
timer = setTimeout(() => {
|
|
500
|
+
log.warn(`shutdown did not finish within ${SHUTDOWN_MAX_MS} ms`);
|
|
501
|
+
done();
|
|
502
|
+
}, SHUTDOWN_MAX_MS);
|
|
503
|
+
});
|
|
504
|
+
await Promise.race([shutdown(), tooLong]);
|
|
505
|
+
clearTimeout(timer);
|
|
506
|
+
})();
|
|
507
|
+
return stopping;
|
|
508
|
+
};
|
|
509
|
+
log.info(`listening on ${addr.host.includes(':') ? `[${addr.host}]` : addr.host}:${addr.port}, home ${home.dir}`);
|
|
510
|
+
running = {
|
|
511
|
+
url: `http://${displayHost(host)}:${addr.port}/#token=${home.browserToken}`,
|
|
512
|
+
host: addr.host,
|
|
513
|
+
port: addr.port,
|
|
514
|
+
browserToken: home.browserToken,
|
|
515
|
+
home: home.dir,
|
|
516
|
+
stop,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
catch (e) {
|
|
520
|
+
// a failed start leaves no listening port, no process and no lock
|
|
521
|
+
const quietly = async (what, run) => {
|
|
522
|
+
try {
|
|
523
|
+
await run();
|
|
524
|
+
}
|
|
525
|
+
catch (err) {
|
|
526
|
+
log.error(`${what} failed`, err);
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
if (hubStarting)
|
|
530
|
+
await quietly('hub shutdown', () => hub?.shutdown());
|
|
531
|
+
await quietly('web server close', () => web?.close());
|
|
532
|
+
await quietly('terminal shutdown', () => terminals?.stopAll());
|
|
533
|
+
await quietly('home close', () => home.close());
|
|
534
|
+
throw e;
|
|
535
|
+
}
|
|
536
|
+
return running;
|
|
537
|
+
}
|
|
538
|
+
/* ---------------------------------------------------------------- the CLI */
|
|
539
|
+
/** An error a client or a vanished terminal can cause: logged, never fatal (contract 2.8). */
|
|
540
|
+
export function isTransientError(e) {
|
|
541
|
+
if (typeof e !== 'object' || e === null || !('code' in e) || typeof e.code !== 'string')
|
|
542
|
+
return false;
|
|
543
|
+
const code = e.code;
|
|
544
|
+
return TRANSIENT_ERROR_CODES.includes(code) || TRANSIENT_ERROR_PREFIXES.some((p) => code.startsWith(p));
|
|
545
|
+
}
|
|
546
|
+
function exit(code) {
|
|
547
|
+
process.exit(code);
|
|
548
|
+
}
|
|
549
|
+
let streamsGuarded = false;
|
|
550
|
+
/** A closed terminal or pipe must not end the agents: the logger and the fatal handler write to these same streams. */
|
|
551
|
+
function guardStreams() {
|
|
552
|
+
if (streamsGuarded)
|
|
553
|
+
return;
|
|
554
|
+
streamsGuarded = true;
|
|
555
|
+
process.stdout.on('error', () => undefined);
|
|
556
|
+
process.stderr.on('error', () => undefined);
|
|
557
|
+
}
|
|
558
|
+
function logLevel(value) {
|
|
559
|
+
return value === 'debug' || value === 'info' || value === 'warn' || value === 'error' ? value : 'info';
|
|
560
|
+
}
|
|
561
|
+
function installProcessHandlers(running, log) {
|
|
562
|
+
let signalled = false;
|
|
563
|
+
const onSignal = (signal) => {
|
|
564
|
+
if (signalled) {
|
|
565
|
+
exit(130);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
signalled = true;
|
|
569
|
+
log.info(`${signal} received; stopping`);
|
|
570
|
+
void running
|
|
571
|
+
.stop()
|
|
572
|
+
.catch((e) => log.error('stop failed', e))
|
|
573
|
+
.finally(() => exit(0));
|
|
574
|
+
};
|
|
575
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'])
|
|
576
|
+
process.on(signal, onSignal);
|
|
577
|
+
// the last resort, not the policy: every agent dies with the server
|
|
578
|
+
let failing = false;
|
|
579
|
+
const onFatal = (what, error) => {
|
|
580
|
+
if (isTransientError(error)) {
|
|
581
|
+
log.warn(`${what} ignored: a client or a terminal caused it`, error);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
log.error(`${what}; stopping`, error);
|
|
585
|
+
if (failing)
|
|
586
|
+
return;
|
|
587
|
+
failing = true;
|
|
588
|
+
void running
|
|
589
|
+
.stop()
|
|
590
|
+
.catch((e) => log.error('stop failed', e))
|
|
591
|
+
.finally(() => exit(1));
|
|
592
|
+
};
|
|
593
|
+
process.on('uncaughtException', (error) => onFatal('uncaught exception', error));
|
|
594
|
+
process.on('unhandledRejection', (reason) => onFatal('unhandled rejection', reason));
|
|
595
|
+
}
|
|
596
|
+
export async function main(argv, env = process.env) {
|
|
597
|
+
guardStreams();
|
|
598
|
+
const parsed = parseArgs(argv);
|
|
599
|
+
if (parsed.kind === 'help') {
|
|
600
|
+
process.stdout.write(USAGE);
|
|
601
|
+
exit(0);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
if (parsed.kind === 'version') {
|
|
605
|
+
process.stdout.write(`gonogo ${packageVersion()}\n`);
|
|
606
|
+
exit(0);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (parsed.kind === 'error') {
|
|
610
|
+
process.stderr.write(`gonogo: ${parsed.message}\n\n${USAGE}`);
|
|
611
|
+
exit(2);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
const level = logLevel(env.GONOGO_LOG_LEVEL);
|
|
615
|
+
const log = createLogger({ level });
|
|
616
|
+
// shortcut: a signal during the start-up (about a second) takes Node's default and ends the process at once; the ptys hang up on their children and the next start replaces the stale lock
|
|
617
|
+
let running;
|
|
618
|
+
try {
|
|
619
|
+
running = await startGonogo({ ...parsed.options, env, log });
|
|
620
|
+
}
|
|
621
|
+
catch (e) {
|
|
622
|
+
process.stderr.write(`gonogo: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
623
|
+
if (level === 'debug' && e instanceof Error && e.stack)
|
|
624
|
+
process.stderr.write(e.stack + '\n');
|
|
625
|
+
exit(1);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
installProcessHandlers(running, log);
|
|
629
|
+
process.stdout.write(`gonogo ready: ${running.url}\n`);
|
|
630
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a command written as text is read: a JSON array of strings when it starts with `[`, words split on whitespace
|
|
3
|
+
* otherwise (no quoting: a path with spaces needs the array form). One reader for GONOGO_AGENT_CMD, for the command of a
|
|
4
|
+
* custom agent when it is hired, edited, loaded from the roster file and started. No imports: home.ts, web.ts and the
|
|
5
|
+
* launcher all use it.
|
|
6
|
+
*/
|
|
7
|
+
const ENV_PREFIX = 'GONOGO_AGENT_CMD: ';
|
|
8
|
+
export function parseAgentCmd(value) {
|
|
9
|
+
const text = value?.trim();
|
|
10
|
+
if (!text)
|
|
11
|
+
return null;
|
|
12
|
+
// A NUL ends a C string: the program would be started with an argument cut short.
|
|
13
|
+
if (text.includes('\u0000'))
|
|
14
|
+
throw new Error(`${ENV_PREFIX}the command cannot contain a NUL character`);
|
|
15
|
+
if (!text.startsWith('['))
|
|
16
|
+
return text.split(/\s+/);
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(text);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new Error(`${ENV_PREFIX}not a valid JSON array`);
|
|
23
|
+
}
|
|
24
|
+
if (!Array.isArray(parsed) || parsed.length === 0 || !parsed.every((item) => typeof item === 'string')) {
|
|
25
|
+
throw new Error(`${ENV_PREFIX}expected a JSON array of one or more strings`);
|
|
26
|
+
}
|
|
27
|
+
// The same rule for an escaped NUL (\u0000) that JSON.parse has just turned into the character.
|
|
28
|
+
if (parsed.some((item) => item.includes('\u0000')))
|
|
29
|
+
throw new Error(`${ENV_PREFIX}the command cannot contain a NUL character`);
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
/** The words of a custom agent's command, or an Error with a one-line reason (no mention of the environment variable). */
|
|
33
|
+
export function readCustomCommand(command) {
|
|
34
|
+
let words;
|
|
35
|
+
try {
|
|
36
|
+
words = parseAgentCmd(command);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
throw new Error(`the command is not usable: ${(error instanceof Error ? error.message : String(error)).replace(ENV_PREFIX, '')}`);
|
|
40
|
+
}
|
|
41
|
+
if (words === null || words[0] === undefined || words[0] === '')
|
|
42
|
+
throw new Error('the command is not usable: it is empty');
|
|
43
|
+
return words;
|
|
44
|
+
}
|