@ulm0/gonogo 0.1.1 → 0.2.0
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/README.md +5 -11
- package/dist/client/assets/index-DxUnpGbS.js +52 -0
- package/dist/client/assets/index-tpcmltjw.css +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/audited.js +156 -0
- package/dist/server/blackbox.js +261 -0
- package/dist/server/board.js +123 -0
- package/dist/server/cleanroom.js +7 -51
- package/dist/server/clearance.js +158 -0
- package/dist/server/cli.js +229 -28
- package/dist/server/constants.js +54 -3
- package/dist/server/hangar.js +311 -0
- package/dist/server/home.js +41 -2
- package/dist/server/hub.js +280 -29
- package/dist/server/launcher.js +25 -13
- package/dist/server/logchart.js +58 -0
- package/dist/server/massbudget.js +169 -0
- package/dist/server/mcp.js +73 -2
- package/dist/server/migrate.js +7 -3
- package/dist/server/missionlog.js +2 -0
- package/dist/server/missions.js +310 -0
- package/dist/server/models.js +73 -0
- package/dist/server/phone.js +122 -0
- package/dist/server/phonetag.js +47 -0
- package/dist/server/prices.js +112 -0
- package/dist/server/propellant.js +243 -16
- package/dist/server/providers.js +123 -9
- package/dist/server/recorder.js +176 -0
- package/dist/server/relay.js +53 -7
- package/dist/server/relaykinds.js +11 -1
- package/dist/server/relief.js +226 -0
- package/dist/server/remotecontrol.js +15 -0
- package/dist/server/rollout.js +172 -0
- package/dist/server/tasks.js +44 -8
- package/dist/server/telemetry.js +110 -0
- package/dist/server/uplinks.js +7 -0
- package/dist/server/web.js +310 -10
- package/dist/server/worktree.js +137 -0
- package/dist/shared/fuel.js +8 -0
- package/dist/shared/livery.js +1 -1
- package/dist/shared/positions.js +1 -1
- package/dist/shared/prices.js +75 -0
- package/dist/shared/protocol.js +61 -15
- package/package.json +1 -1
- package/dist/client/assets/index-B6MsSoeo.css +0 -1
- package/dist/client/assets/index-DRtiRh1Y.js +0 -31
package/dist/server/launcher.js
CHANGED
|
@@ -9,7 +9,9 @@ import { chmod, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, sym
|
|
|
9
9
|
import { homedir } from 'node:os';
|
|
10
10
|
import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
|
|
11
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';
|
|
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, WORKTREE_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 { prepareWorktree } from './worktree.js';
|
|
14
|
+
import { remoteControlName } from './remotecontrol.js';
|
|
13
15
|
import { buildDockerArgs, cleanRoomImage, containerUrl, prepareCleanRoom, removeContainer } from './cleanroom.js';
|
|
14
16
|
import { parseAgentCmd } from './command.js';
|
|
15
17
|
import { buildProviderStart } from './providers.js';
|
|
@@ -98,6 +100,8 @@ export function buildArgv(input) {
|
|
|
98
100
|
'--mcp-config',
|
|
99
101
|
input.mcpPath,
|
|
100
102
|
...(input.pluginDir ? ['--plugin-dir', input.pluginDir] : []),
|
|
103
|
+
...(input.model ? ['--model', input.model] : []),
|
|
104
|
+
...(input.remoteControl ? ['--remote-control', input.remoteControl] : []),
|
|
101
105
|
'--append-system-prompt',
|
|
102
106
|
input.roleText,
|
|
103
107
|
'--system-prompt-snapshot',
|
|
@@ -147,6 +151,7 @@ export function buildChildEnv(input) {
|
|
|
147
151
|
continue;
|
|
148
152
|
env[key] = value;
|
|
149
153
|
}
|
|
154
|
+
Object.assign(env, input.keys);
|
|
150
155
|
if (input.seed) {
|
|
151
156
|
env.IS_DEMO = '1';
|
|
152
157
|
// A plain ANTHROPIC_API_KEY triggers a dialog whose default is "No" (or "Not logged in" under IS_DEMO)
|
|
@@ -391,9 +396,11 @@ export function createLauncher(options) {
|
|
|
391
396
|
const dirInfo = await stat(agent.dir).catch(() => null);
|
|
392
397
|
if (!dirInfo?.isDirectory())
|
|
393
398
|
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: '' };
|
|
399
|
+
return { spec: { file, args, env: buildChildEnv({ base: options.env ?? process.env, token: null, seed: false, keys: options.keys?.(name) }), cwd: (await plainWorktree(agent, options.env ?? process.env))?.cwd ?? agent.dir }, flag: 'session-id', token: '' };
|
|
395
400
|
};
|
|
396
401
|
/** Engine Bay: another agent CLI, started by its program name with the files and flags of its adapter (providers.ts). */
|
|
402
|
+
/** A plain worktree (not a Clean Room's): made or found, and the folder the agent starts in; null when the agent starts in its own folder. */
|
|
403
|
+
const plainWorktree = async (agent, from) => (agent.worktree === undefined || agent.cleanRoom !== undefined ? null : prepareWorktree(agent, homeDir, from));
|
|
397
404
|
const prepareOther = async (agent, provider, base, hubUrl, memoryPath, token) => {
|
|
398
405
|
const ctx = {
|
|
399
406
|
name: agent.name,
|
|
@@ -406,13 +413,14 @@ export function createLauncher(options) {
|
|
|
406
413
|
tokenFile: join(base, AGENT_TOKEN_FILE),
|
|
407
414
|
token,
|
|
408
415
|
seed: options.seed,
|
|
416
|
+
model: agent.model ?? options.defaultModel?.(provider),
|
|
409
417
|
};
|
|
410
418
|
const start = buildProviderStart(provider, ctx);
|
|
411
419
|
for (const [file, content] of Object.entries(start.files))
|
|
412
420
|
await writeFileAtomic(join(base, file), content, FILE_MODE);
|
|
413
|
-
const env = { ...buildChildEnv({ base: options.env ?? process.env, token, seed: false }), ...start.env };
|
|
421
|
+
const env = { ...buildChildEnv({ base: options.env ?? process.env, token, seed: false, keys: options.keys?.(agent.name) }), ...start.env };
|
|
414
422
|
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 };
|
|
423
|
+
return { spec: { file: PROVIDER_INFO[provider].bin, args: start.args, env, cwd: (await plainWorktree(agent, options.env ?? process.env))?.cwd ?? agent.dir }, flag: 'session-id', token };
|
|
416
424
|
};
|
|
417
425
|
const prepareStart = async (agent, opts) => {
|
|
418
426
|
const { name } = agent;
|
|
@@ -455,18 +463,21 @@ export function createLauncher(options) {
|
|
|
455
463
|
await removals.get(name);
|
|
456
464
|
const clean = agent.cleanRoom === undefined ? null : await prepareCleanRoom(agent, homeDir, base, env);
|
|
457
465
|
// A fresh container home has no folder trust and no login, so its dialogs are skipped as in seed mode.
|
|
466
|
+
const plain = await plainWorktree(agent, env);
|
|
458
467
|
const seed = options.seed || clean !== null;
|
|
459
468
|
const agentUrl = clean === null ? hubUrl : containerUrl(hubUrl);
|
|
460
469
|
const settingsPath = join(base, SETTINGS_FILE);
|
|
461
470
|
const mcpPath = join(base, MCP_FILE);
|
|
462
|
-
const
|
|
471
|
+
const keys = options.keys?.(name) ?? {};
|
|
472
|
+
const moveApiKey = seed && hasText(keys.ANTHROPIC_API_KEY ?? env.ANTHROPIC_API_KEY);
|
|
463
473
|
const settings = buildSettings({ hubUrl: agentUrl, name, mode: agent.mode, memoryPath, apiKeyHelper: moveApiKey });
|
|
464
474
|
await writeFileAtomic(settingsPath, JSON.stringify(settings, null, 2), FILE_MODE);
|
|
465
475
|
await writeFileAtomic(mcpPath, JSON.stringify(buildMcpConfig(agentUrl, agent.payload?.mcpServers), null, 2), FILE_MODE);
|
|
466
476
|
const pluginDir = await writeSkillsPlugin(base, agent.payload?.skills);
|
|
467
477
|
const configDir = hasText(env.CLAUDE_CONFIG_DIR) ? env.CLAUDE_CONFIG_DIR : null;
|
|
468
|
-
const
|
|
469
|
-
const
|
|
478
|
+
const startDir = plain?.cwd ?? dir;
|
|
479
|
+
const realDir = await realpath(startDir).catch(() => startDir);
|
|
480
|
+
const trustDirs = clean === null ? [...new Set([realDir, startDir])] : [clean.cwd];
|
|
470
481
|
// the folder of the config that claude reads: the owner's, or the container's own home
|
|
471
482
|
const claudeRoot = clean === null ? configDir ?? homedir() : clean.home;
|
|
472
483
|
const claudeJson = join(claudeRoot, CLAUDE_JSON);
|
|
@@ -487,14 +498,14 @@ export function createLauncher(options) {
|
|
|
487
498
|
recheck = () => recheckTrust(name, claudeJson, written, trustDirs);
|
|
488
499
|
}
|
|
489
500
|
const projectsRoot = join(clean === null ? configDir ?? join(homedir(), '.claude') : clean.home, 'projects');
|
|
490
|
-
const flag = opts.flag ?? ((await transcriptExists(projectsRoot, clean === null ? [
|
|
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 });
|
|
501
|
+
const flag = opts.flag ?? ((await transcriptExists(projectsRoot, clean === null ? [startDir, realDir] : [clean.cwd], agent.sessionId)) ? 'resume' : 'session-id');
|
|
502
|
+
const roleText = buildRoleText(name, agent.role, memoryPath) + (clean === null ? '' : `\n${CLEAN_ROOM_NOTE.replace('{branch}', cleanRoomBranch(name))}`) + (plain === null ? '' : `\n${WORKTREE_NOTE.replace('{branch}', plain.branch)}`);
|
|
503
|
+
const claudeArgs = buildArgv({ flag, sessionId: agent.sessionId, mode: agent.mode, settingsPath, mcpPath, roleText, pluginDir, model: agent.model ?? options.defaultModel?.('claude'), remoteControl: agent.remoteControl === undefined ? undefined : remoteControlName(name) });
|
|
493
504
|
const [file, ...leading] = options.agentCmd?.length ? options.agentCmd : [options.claudeBin ?? CLAUDE_BIN];
|
|
494
|
-
const childEnv = buildChildEnv({ base: env, token, seed });
|
|
505
|
+
const childEnv = buildChildEnv({ base: env, token, seed, keys });
|
|
495
506
|
let spec;
|
|
496
507
|
if (clean === null) {
|
|
497
|
-
spec = { file, args: [...leading, ...claudeArgs], env: childEnv, cwd:
|
|
508
|
+
spec = { file, args: [...leading, ...claudeArgs], env: childEnv, cwd: startDir };
|
|
498
509
|
}
|
|
499
510
|
else {
|
|
500
511
|
const uid = process.getuid?.();
|
|
@@ -502,7 +513,8 @@ export function createLauncher(options) {
|
|
|
502
513
|
if (uid === undefined || gid === undefined)
|
|
503
514
|
throw new Error('Clean Room needs a user id: it runs on macOS and Linux only');
|
|
504
515
|
// by name: docker reads the values from its own environment, so no secret is on the command line
|
|
505
|
-
|
|
516
|
+
// The agent's own keys go the same way: the container gets their names, and nothing else of the host's environment.
|
|
517
|
+
const names = [...new Set([...CLEAN_ROOM_ENV, ...CLEAN_ROOM_CREDENTIALS, ...Object.keys(keys)])].filter((variable) => hasText(childEnv[variable]));
|
|
506
518
|
const command = [file, ...leading, ...claudeArgs];
|
|
507
519
|
const args = buildDockerArgs({ image: cleanRoomImage(agent.cleanRoom ?? {}, env), uid, gid, place: clean, agentDir: base, names, command });
|
|
508
520
|
spec = { file: DOCKER_BIN, args, env: childEnv, cwd: clean.worktree };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export const CHART_ENTRIES_MAX = 150;
|
|
2
|
+
export const CHART_TAGS_MAX = 40;
|
|
3
|
+
/** Two tags are joined by a co-occurrence edge when this many entries hold both. */
|
|
4
|
+
export const COOCCUR_MIN = 2;
|
|
5
|
+
/** An entry id as a word of its own: `l12`, `(l12)`, `l12.`; not `cl12`, `l12x` or `l12-b`. */
|
|
6
|
+
const MENTION = /(?<![\p{L}\p{N}_-])l([1-9]\d{0,5})(?![\p{L}\p{N}_-])/gu;
|
|
7
|
+
/** The ids of other entries named in a text, each once, in order of appearance. */
|
|
8
|
+
export function mentions(text, self) {
|
|
9
|
+
const found = new Set();
|
|
10
|
+
for (const match of text.matchAll(MENTION))
|
|
11
|
+
if (`l${match[1]}` !== self)
|
|
12
|
+
found.add(`l${match[1]}`);
|
|
13
|
+
return [...found];
|
|
14
|
+
}
|
|
15
|
+
export function buildChart(all) {
|
|
16
|
+
const shown = [...all].sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt || a.id.localeCompare(b.id)).slice(0, CHART_ENTRIES_MAX);
|
|
17
|
+
const ids = new Set(shown.map((e) => e.id));
|
|
18
|
+
const uses = new Map();
|
|
19
|
+
for (const entry of shown)
|
|
20
|
+
for (const tag of entry.tags)
|
|
21
|
+
uses.set(tag, (uses.get(tag) ?? 0) + 1);
|
|
22
|
+
const tags = [...uses].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, CHART_TAGS_MAX);
|
|
23
|
+
const tagged = new Set(tags.map(([tag]) => tag));
|
|
24
|
+
const authors = new Map();
|
|
25
|
+
for (const entry of shown)
|
|
26
|
+
authors.set(entry.author, (authors.get(entry.author) ?? 0) + 1);
|
|
27
|
+
const edges = [];
|
|
28
|
+
const named = new Map();
|
|
29
|
+
const together = new Map();
|
|
30
|
+
for (const entry of shown) {
|
|
31
|
+
const from = `entry:${entry.id}`;
|
|
32
|
+
for (const tag of entry.tags)
|
|
33
|
+
if (tagged.has(tag))
|
|
34
|
+
edges.push({ from, to: `tag:${tag}`, kind: 'tag', weight: 1 });
|
|
35
|
+
edges.push({ from, to: `author:${entry.author}`, kind: 'author', weight: 1 });
|
|
36
|
+
for (const id of mentions(`${entry.title}\n${entry.body}`, entry.id)) {
|
|
37
|
+
if (!ids.has(id))
|
|
38
|
+
continue;
|
|
39
|
+
edges.push({ from, to: `entry:${id}`, kind: 'mention', weight: 1 });
|
|
40
|
+
named.set(id, (named.get(id) ?? 0) + 1);
|
|
41
|
+
}
|
|
42
|
+
const own = entry.tags.filter((t) => tagged.has(t)).sort();
|
|
43
|
+
for (let i = 0; i < own.length; i += 1)
|
|
44
|
+
for (let j = i + 1; j < own.length; j += 1)
|
|
45
|
+
together.set(`${own[i]}\n${own[j]}`, (together.get(`${own[i]}\n${own[j]}`) ?? 0) + 1);
|
|
46
|
+
}
|
|
47
|
+
for (const [pair, weight] of [...together].sort((a, b) => a[0].localeCompare(b[0]))) {
|
|
48
|
+
const [a = '', b = ''] = pair.split('\n');
|
|
49
|
+
if (weight >= COOCCUR_MIN)
|
|
50
|
+
edges.push({ from: `tag:${a}`, to: `tag:${b}`, kind: 'cooccur', weight });
|
|
51
|
+
}
|
|
52
|
+
const nodes = [
|
|
53
|
+
...shown.map((e) => ({ id: `entry:${e.id}`, kind: 'entry', ref: e.id, label: e.title, weight: 1 + (named.get(e.id) ?? 0) })),
|
|
54
|
+
...tags.map(([tag, weight]) => ({ id: `tag:${tag}`, kind: 'tag', ref: tag, label: tag, weight })),
|
|
55
|
+
...[...authors].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([name, weight]) => ({ id: `author:${name}`, kind: 'author', ref: name, label: name, weight })),
|
|
56
|
+
];
|
|
57
|
+
return { total: all.length, shown: shown.length, nodes, edges };
|
|
58
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mass Budget: how big each agent's memory.md is, and a request to the agent to condense it (docs/mass-budget-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* gonogo never writes memory.md: the agent may be writing it. A request is a message from the Director through the hub, so Max Q,
|
|
5
|
+
* Redline and held mail apply, and the agent rewrites its own file. What gonogo does write is one copy, memory.md.bak, taken from
|
|
6
|
+
* the bytes it read when the request is sent and put in place only after the hub took the message (so a refused request keeps
|
|
7
|
+
* the older copy). The file is opened without following a symbolic link and is never read past MEMORY_READ_MAX bytes.
|
|
8
|
+
*
|
|
9
|
+
* shortcut: the lines and the bytes of the soft limit are constants (the role text tells an agent to keep its file under 200
|
|
10
|
+
* lines); make them options if anyone runs agents that need more.
|
|
11
|
+
*/
|
|
12
|
+
import { randomBytes } from 'node:crypto';
|
|
13
|
+
import { constants } from 'node:fs';
|
|
14
|
+
import { lstat, open, rename, rm, writeFile } from 'node:fs/promises';
|
|
15
|
+
import { basename, dirname, join } from 'node:path';
|
|
16
|
+
import { FILE_MODE, MEMORY_FILE } from './constants.js';
|
|
17
|
+
import { HubError } from './hub.js';
|
|
18
|
+
export const MEMORY_BACKUP_FILE = `${MEMORY_FILE}.bak`;
|
|
19
|
+
/** The role text asks for under 200 lines; the size limit is what 200 lines of notes come to. */
|
|
20
|
+
export const MEMORY_SOFT_LINES = 200;
|
|
21
|
+
export const MEMORY_SOFT_BYTES = 16 * 1024;
|
|
22
|
+
/** What the request asks the agent to bring the file down to. */
|
|
23
|
+
export const MEMORY_TARGET_LINES = 100;
|
|
24
|
+
/** A larger file is not copied or counted: trim it by hand. */
|
|
25
|
+
export const MEMORY_READ_MAX = 1024 * 1024;
|
|
26
|
+
/** The message to the agent. Everything it needs is in it: the file, the size, what to keep, what to drop, how to write it and how to answer. */
|
|
27
|
+
export function reflectBody(input) {
|
|
28
|
+
return [
|
|
29
|
+
'The Director asks you to condense your memory file.',
|
|
30
|
+
`File: ${input.path} (${input.bytes} bytes, ${input.lines} lines). gonogo copied it to ${input.path}.bak when it sent this message: do not use that copy as notes and do not edit it.`,
|
|
31
|
+
'When your current step is done:',
|
|
32
|
+
'1. Read the whole file.',
|
|
33
|
+
`2. Write a shorter version of at most ${MEMORY_TARGET_LINES} lines. Keep what is still true and still useful: decisions and their reasons, rules and conventions, paths, commands, names, ids and open problems. Drop what is done, repeated or replaced, and any step-by-step log of what you did. Merge notes on one subject. Add nothing that is not in the file.`,
|
|
34
|
+
'3. A finding that every agent should know goes to the Mission Log with log_write, and leaves your file.',
|
|
35
|
+
`4. Replace the file with the new text in one write. Keep the first line "# Memory of ${input.name}" and plain markdown. Do not change any other file.`,
|
|
36
|
+
'5. Then send_message to "user" with the subject "Memory condensed" and one sentence: the lines before and after. If the file is already short and has nothing to drop, change nothing and say so in one sentence.',
|
|
37
|
+
].join('\n');
|
|
38
|
+
}
|
|
39
|
+
const conflict = (message) => new HubError('conflict', message);
|
|
40
|
+
const lineCount = (text) => {
|
|
41
|
+
if (text.length === 0)
|
|
42
|
+
return 0;
|
|
43
|
+
let lines = 0;
|
|
44
|
+
for (const byte of text)
|
|
45
|
+
if (byte === 0x0a)
|
|
46
|
+
lines += 1;
|
|
47
|
+
return text[text.length - 1] === 0x0a ? lines : lines + 1;
|
|
48
|
+
};
|
|
49
|
+
/** The file as it is, read without following a link. null when it is not there. A link, a folder or a device is refused. */
|
|
50
|
+
async function readMemory(path) {
|
|
51
|
+
let handle;
|
|
52
|
+
try {
|
|
53
|
+
// O_NONBLOCK: opening a named pipe in that place must not wait for a writer
|
|
54
|
+
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
const code = error.code;
|
|
58
|
+
if (code === 'ENOENT')
|
|
59
|
+
return null;
|
|
60
|
+
if (code === 'ELOOP')
|
|
61
|
+
throw conflict(`${basename(path)} is a symbolic link: gonogo does not follow it`);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const info = await handle.stat();
|
|
66
|
+
if (!info.isFile())
|
|
67
|
+
throw conflict(`${basename(path)} is not a regular file`);
|
|
68
|
+
if (info.size > MEMORY_READ_MAX)
|
|
69
|
+
return { bytes: info.size, data: null, changedAt: info.mtimeMs };
|
|
70
|
+
const data = Buffer.alloc(info.size);
|
|
71
|
+
let got = 0;
|
|
72
|
+
while (got < data.length) {
|
|
73
|
+
const { bytesRead } = await handle.read(data, got, data.length - got, got);
|
|
74
|
+
if (bytesRead === 0)
|
|
75
|
+
break;
|
|
76
|
+
got += bytesRead;
|
|
77
|
+
}
|
|
78
|
+
return { bytes: got, data: data.subarray(0, got), changedAt: info.mtimeMs };
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
await handle.close();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function createMassBudget(options) {
|
|
85
|
+
const { log } = options;
|
|
86
|
+
/** One request per agent at a time: a double click must not send the message twice. */
|
|
87
|
+
const asking = new Set();
|
|
88
|
+
const known = (name) => {
|
|
89
|
+
const agent = options.agent(name);
|
|
90
|
+
if (!agent)
|
|
91
|
+
throw new HubError('not_found', 'unknown agent');
|
|
92
|
+
if (agent.provider === 'custom')
|
|
93
|
+
throw new HubError('not_found', `${name} runs a custom command: it has no memory file`);
|
|
94
|
+
return agent;
|
|
95
|
+
};
|
|
96
|
+
const backupOf = async (path) => {
|
|
97
|
+
try {
|
|
98
|
+
const info = await lstat(`${path}.bak`);
|
|
99
|
+
return info.isFile() ? { bytes: info.size, at: info.mtimeMs } : null;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const describe = async (path, read) => {
|
|
106
|
+
const bytes = read?.bytes ?? 0;
|
|
107
|
+
const lines = read === null ? 0 : read.data === null ? null : lineCount(read.data);
|
|
108
|
+
return {
|
|
109
|
+
exists: read !== null,
|
|
110
|
+
bytes,
|
|
111
|
+
lines,
|
|
112
|
+
softLines: MEMORY_SOFT_LINES,
|
|
113
|
+
softBytes: MEMORY_SOFT_BYTES,
|
|
114
|
+
over: bytes > MEMORY_SOFT_BYTES || (lines ?? Infinity) > MEMORY_SOFT_LINES,
|
|
115
|
+
changedAt: read?.changedAt ?? null,
|
|
116
|
+
backup: await backupOf(path),
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
return {
|
|
120
|
+
async view(name) {
|
|
121
|
+
known(name);
|
|
122
|
+
const path = options.memoryPath(name);
|
|
123
|
+
return describe(path, await readMemory(path));
|
|
124
|
+
},
|
|
125
|
+
async reflect(name) {
|
|
126
|
+
known(name);
|
|
127
|
+
if (asking.has(name))
|
|
128
|
+
throw conflict(`a request to ${name} is being sent`);
|
|
129
|
+
asking.add(name);
|
|
130
|
+
try {
|
|
131
|
+
const path = options.memoryPath(name);
|
|
132
|
+
const read = await readMemory(path);
|
|
133
|
+
if (read === null)
|
|
134
|
+
throw conflict(`${name} has no memory file yet: start it first`);
|
|
135
|
+
if (read.data === null)
|
|
136
|
+
throw conflict(`${MEMORY_FILE} of ${name} is ${Math.round(read.bytes / 1024)} KiB, more than the ${MEMORY_READ_MAX / 1024} KiB gonogo copies: trim it by hand`);
|
|
137
|
+
// written first, put in place after the hub took the message
|
|
138
|
+
const tmp = join(dirname(path), `.${MEMORY_BACKUP_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
139
|
+
await writeFile(tmp, read.data, { mode: FILE_MODE, flag: 'wx' }).catch(async (error) => {
|
|
140
|
+
// a full disk leaves half a file behind
|
|
141
|
+
await rm(tmp, { force: true });
|
|
142
|
+
throw error;
|
|
143
|
+
});
|
|
144
|
+
let send;
|
|
145
|
+
try {
|
|
146
|
+
send = options.send({ to: name, subject: 'Mass Budget: condense your memory file', body: reflectBody({ name, path, bytes: read.bytes, lines: lineCount(read.data) }) });
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
await rm(tmp, { force: true });
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
if (send.ok) {
|
|
153
|
+
// rename puts the copy in place of a link too, never through it
|
|
154
|
+
await rename(tmp, `${path}.bak`).catch(async (error) => {
|
|
155
|
+
log.warn(`could not write ${MEMORY_BACKUP_FILE} of ${name}`, error);
|
|
156
|
+
await rm(tmp, { force: true });
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
await rm(tmp, { force: true });
|
|
161
|
+
}
|
|
162
|
+
return { send, memory: await describe(path, await readMemory(path)) };
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
asking.delete(name);
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
package/dist/server/mcp.js
CHANGED
|
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
2
2
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { LIVERY_DESCRIPTION_MAX_CHARS, LIVERY_NAME_MAX_CHARS } from '../shared/livery.js';
|
|
5
|
-
import { LOG_BODY_MAX_CHARS, LOG_QUERY_MAX_CHARS, LOG_SEARCH_MAX, LOG_TAGS_MAX, LOG_TITLE_MAX_CHARS, MCP_SERVER_NAME, POLL_VOTES, TASK_DETAIL_MAX_CHARS, TASK_NOTE_MAX_CHARS, TASK_STATUSES, TASK_TITLE_MAX_CHARS, } from '../shared/protocol.js';
|
|
5
|
+
import { AGENT_NAME_MAX, DIR_MAX_CHARS, BOARD_MAX_CHARS, LOG_BODY_MAX_CHARS, LOG_QUERY_MAX_CHARS, LOG_SEARCH_MAX, LOG_TAGS_MAX, LOG_TITLE_MAX_CHARS, MCP_SERVER_NAME, POLL_VOTES, ROLE_MAX_CHARS, TASK_DETAIL_MAX_CHARS, MISSION_GOAL_MAX_CHARS, MISSION_NAME_MAX_CHARS, MISSION_NOTE_MAX_CHARS, MISSION_STATUSES, TASK_NOTE_MAX_CHARS, TASK_STATUSES, TASK_TITLE_MAX_CHARS, } from '../shared/protocol.js';
|
|
6
6
|
import { BODY_MAX_CHARS, MAX_MCP_BODY_BYTES, MCP_DESCRIPTIONS, POLL_REASON_MAX_CHARS, READ_MAX_CHARS, SUBJECT_MAX_CHARS } from './constants.js';
|
|
7
7
|
import { bearerToken, hubErrorInfo, readBody, sendJson, sendUnauthorized } from './hooks.js';
|
|
8
8
|
/** JSON-RPC error codes: parse error, invalid request, "server error" (the SDK's own value for a refused method), internal error. */
|
|
@@ -88,7 +88,7 @@ export function createMcpHandler(deps) {
|
|
|
88
88
|
}));
|
|
89
89
|
server.registerTool('task_create', {
|
|
90
90
|
description: MCP_DESCRIPTIONS.task_create,
|
|
91
|
-
inputSchema: { title: z.string().min(1).max(TASK_TITLE_MAX_CHARS), detail: z.string().max(TASK_DETAIL_MAX_CHARS).optional(), assignee: z.string().min(1).max(64).optional() },
|
|
91
|
+
inputSchema: { title: z.string().min(1).max(TASK_TITLE_MAX_CHARS), detail: z.string().max(TASK_DETAIL_MAX_CHARS).optional(), assignee: z.string().min(1).max(64).optional(), missionId: z.string().min(1).max(16).optional() },
|
|
92
92
|
}, (args) => guarded('task_create', async () => (tasks ? toolResult({ ok: true, task: await tasks.create(actor, args) }, false) : noBoard())));
|
|
93
93
|
server.registerTool('task_update', {
|
|
94
94
|
description: MCP_DESCRIPTIONS.task_update,
|
|
@@ -97,8 +97,47 @@ export function createMcpHandler(deps) {
|
|
|
97
97
|
status: z.enum(TASK_STATUSES).optional(),
|
|
98
98
|
assignee: z.string().min(1).max(64).nullable().optional(),
|
|
99
99
|
note: z.string().max(TASK_NOTE_MAX_CHARS).optional(),
|
|
100
|
+
missionId: z.string().min(1).max(16).nullable().optional(),
|
|
100
101
|
},
|
|
101
102
|
}, ({ id, ...patch }) => guarded('task_update', async () => (tasks ? toolResult({ ok: true, task: await tasks.update(actor, id, patch) }, false) : noBoard())));
|
|
103
|
+
const { missions } = deps;
|
|
104
|
+
const noMissions = () => toolResult({ ok: false, error: 'Missions are not available' }, true);
|
|
105
|
+
const bossOnly = () => toolResult({ ok: false, error: 'only the boss may change missions' }, true);
|
|
106
|
+
const isBoss = () => hub.rosterFor(agent, generation).boss === agent;
|
|
107
|
+
server.registerTool('mission_list', { description: MCP_DESCRIPTIONS.mission_list, inputSchema: { status: z.enum(MISSION_STATUSES).optional() } }, (args) => guarded('mission_list', () => {
|
|
108
|
+
if (!missions)
|
|
109
|
+
return noMissions();
|
|
110
|
+
const found = missions
|
|
111
|
+
.list()
|
|
112
|
+
.filter((m) => args.status === undefined || m.status === args.status)
|
|
113
|
+
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
114
|
+
const taskList = tasks?.list() ?? [];
|
|
115
|
+
const shown = found.map((m) => {
|
|
116
|
+
const mine = taskList.filter((t) => t.missionId === m.id);
|
|
117
|
+
return { ...m, tasksDone: mine.filter((t) => t.status === 'done').length, tasksTotal: mine.length };
|
|
118
|
+
});
|
|
119
|
+
return toolResult({ count: shown.length, missions: shown }, false);
|
|
120
|
+
}));
|
|
121
|
+
server.registerTool('mission_create', {
|
|
122
|
+
description: MCP_DESCRIPTIONS.mission_create,
|
|
123
|
+
inputSchema: { name: z.string().min(1).max(MISSION_NAME_MAX_CHARS), goal: z.string().max(MISSION_GOAL_MAX_CHARS).optional(), lead: z.string().min(1).max(64).optional() },
|
|
124
|
+
}, (args) => guarded('mission_create', async () => {
|
|
125
|
+
if (!missions)
|
|
126
|
+
return noMissions();
|
|
127
|
+
if (!isBoss())
|
|
128
|
+
return bossOnly();
|
|
129
|
+
return toolResult({ ok: true, mission: await missions.create(actor, args) }, false);
|
|
130
|
+
}));
|
|
131
|
+
server.registerTool('mission_update', {
|
|
132
|
+
description: MCP_DESCRIPTIONS.mission_update,
|
|
133
|
+
inputSchema: { id: z.string().min(1).max(16), status: z.enum(MISSION_STATUSES).optional(), note: z.string().max(MISSION_NOTE_MAX_CHARS).optional() },
|
|
134
|
+
}, ({ id, ...patch }) => guarded('mission_update', async () => {
|
|
135
|
+
if (!missions)
|
|
136
|
+
return noMissions();
|
|
137
|
+
if (!isBoss())
|
|
138
|
+
return bossOnly();
|
|
139
|
+
return toolResult({ ok: true, mission: await missions.update(actor, id, patch) }, false);
|
|
140
|
+
}));
|
|
102
141
|
const { missionLog } = deps;
|
|
103
142
|
const noLog = () => toolResult({ ok: false, error: 'the Mission Log is not available' }, true);
|
|
104
143
|
server.registerTool('log_write', {
|
|
@@ -126,6 +165,20 @@ export function createMcpHandler(deps) {
|
|
|
126
165
|
return toolResult({ count: hits.length, results: hits }, false);
|
|
127
166
|
}));
|
|
128
167
|
server.registerTool('log_read', { description: MCP_DESCRIPTIONS.log_read, inputSchema: { id: z.string().min(1).max(16) } }, ({ id }) => guarded('log_read', () => (missionLog ? toolResult({ ok: true, entry: missionLog.get(id) }, false) : noLog())));
|
|
168
|
+
const { board } = deps;
|
|
169
|
+
const noPlot = () => toolResult({ ok: false, error: 'the Plot Board is not available' }, true);
|
|
170
|
+
// the boss is the one the hub says it is, asked at each call: a rename or a new boss takes effect at once
|
|
171
|
+
const bossName = () => hub.rosterFor(agent, generation).boss;
|
|
172
|
+
server.registerTool('board_read', { description: MCP_DESCRIPTIONS.board_read }, () => guarded('board_read', () => (board ? toolResult({ ok: true, ...board.get(), canWrite: bossName() === agent }, false) : noPlot())));
|
|
173
|
+
server.registerTool('board_write', { description: MCP_DESCRIPTIONS.board_write, inputSchema: { text: z.string().max(BOARD_MAX_CHARS), revision: z.number().int().min(0) } }, (args) => guarded('board_write', async () => {
|
|
174
|
+
if (!board)
|
|
175
|
+
return noPlot();
|
|
176
|
+
if (bossName() !== agent)
|
|
177
|
+
return toolResult({ ok: false, error: 'only the boss may write the Plot Board' }, true);
|
|
178
|
+
// the author is the caller's own name, never a field of the call
|
|
179
|
+
const view = await board.write(agent, args);
|
|
180
|
+
return toolResult({ ok: true, revision: view.revision, updatedAt: view.updatedAt }, false);
|
|
181
|
+
}));
|
|
129
182
|
const { liveries } = deps;
|
|
130
183
|
server.registerTool('livery_submit', {
|
|
131
184
|
description: MCP_DESCRIPTIONS.livery_submit,
|
|
@@ -137,6 +190,24 @@ export function createMcpHandler(deps) {
|
|
|
137
190
|
const entry = await liveries.submit(agent, args);
|
|
138
191
|
return toolResult({ ok: true, slug: entry.slug, note: 'saved; the Director chooses whether to apply it' }, false);
|
|
139
192
|
}));
|
|
193
|
+
const { relief } = deps;
|
|
194
|
+
server.registerTool('hire_agent', {
|
|
195
|
+
description: MCP_DESCRIPTIONS.hire_agent,
|
|
196
|
+
// strict: a field the tool does not have (confirmBypass, command, payload) is refused, not dropped; the mode is checked by Relief, so that its answer says why
|
|
197
|
+
inputSchema: z.strictObject({
|
|
198
|
+
name: z.string().min(1).max(AGENT_NAME_MAX),
|
|
199
|
+
position: z.string().max(32).optional(),
|
|
200
|
+
role: z.string().max(ROLE_MAX_CHARS).optional(),
|
|
201
|
+
dir: z.string().max(DIR_MAX_CHARS).optional(),
|
|
202
|
+
engine: z.string().max(32).optional(),
|
|
203
|
+
mode: z.string().max(32).optional(),
|
|
204
|
+
}),
|
|
205
|
+
}, (args) => guarded('hire_agent', async () => {
|
|
206
|
+
if (!relief)
|
|
207
|
+
return toolResult({ ok: false, error: 'Relief is not available' }, true);
|
|
208
|
+
// the requester is the agent of the token, never a field of the call
|
|
209
|
+
return toolResult({ ok: true, ...(await relief.request({ agent, generation }, args)) }, false);
|
|
210
|
+
}));
|
|
140
211
|
return server;
|
|
141
212
|
};
|
|
142
213
|
return async (req, res) => {
|
package/dist/server/migrate.js
CHANGED
|
@@ -10,15 +10,16 @@
|
|
|
10
10
|
* To change a format: add a step at the end of `steps` of its entry in FORMATS (version n to n + 1; it gets the parsed file and
|
|
11
11
|
* returns the new one; the runner sets `version`), and change the store to read and write the new shape.
|
|
12
12
|
*
|
|
13
|
-
* Not run through here: the logs messages.jsonl
|
|
14
|
-
* new file name) and the Mission Log entries (their front matter has `version`,
|
|
13
|
+
* Not run through here: the logs messages.jsonl, fuel.jsonl and the day files of the Black Box (a line a reader cannot parse is
|
|
14
|
+
* skipped; a new line format needs a new file name), and the Mission Log entries and board.md (their front matter has `version`,
|
|
15
|
+
* checked in missionlog.ts and board.ts).
|
|
15
16
|
* shortcut: a home with one file too new and another to upgrade can upgrade the second before it refuses the first; the copy
|
|
16
17
|
* makes that harmless, so there is no check pass.
|
|
17
18
|
*/
|
|
18
19
|
import { randomBytes } from 'node:crypto';
|
|
19
20
|
import { chmodSync, constants, copyFileSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
20
21
|
import { basename, dirname, join } from 'node:path';
|
|
21
|
-
import { AGENTS_FILE, DOCKING_FILE, DOWNLINK_FILE, FILE_MODE, LIVERY_DIR, LIVERY_FILE, PROPELLANT_FILE, RELAY_FILE, SCHEDULES_FILE, STATION_FILE, TASKS_FILE, UPLINKS_FILE, } from './constants.js';
|
|
22
|
+
import { AGENTS_FILE, DOCKING_FILE, DOWNLINK_FILE, FILE_MODE, KEYS_FILE, LIVERY_DIR, LIVERY_FILE, PRICES_FILE, PROPELLANT_FILE, RELAY_FILE, ROLLOUT_FILE, SCHEDULES_FILE, STATION_FILE, TASKS_FILE, UPLINKS_FILE, } from './constants.js';
|
|
22
23
|
const ALL_JSON = '/*.json';
|
|
23
24
|
/** Everything is still at version 1: no step yet. */
|
|
24
25
|
export const FORMATS = [
|
|
@@ -32,6 +33,9 @@ export const FORMATS = [
|
|
|
32
33
|
STATION_FILE,
|
|
33
34
|
LIVERY_FILE,
|
|
34
35
|
PROPELLANT_FILE,
|
|
36
|
+
PRICES_FILE,
|
|
37
|
+
KEYS_FILE,
|
|
38
|
+
ROLLOUT_FILE,
|
|
35
39
|
LIVERY_DIR + ALL_JSON,
|
|
36
40
|
].map((file) => (file === PROPELLANT_FILE ? { file, steps: [], unversionedIs1: true } : { file, steps: [] }));
|
|
37
41
|
function isRecord(x) {
|
|
@@ -20,6 +20,7 @@ import { LOG_BODY_MAX_CHARS, LOG_ENTRIES_MAX, LOG_QUERY_MAX_CHARS, LOG_SEARCH_MA
|
|
|
20
20
|
import { DIR_MODE, FILE_MODE, LOG_DIR } from './constants.js';
|
|
21
21
|
import { isRecord } from './hooks.js';
|
|
22
22
|
import { HubError } from './hub.js';
|
|
23
|
+
import { buildChart } from './logchart.js';
|
|
23
24
|
import { createIndex, snippet } from './logsearch.js';
|
|
24
25
|
import { UNSAFE_IN_NAME } from './schedules.js';
|
|
25
26
|
const ID_RE = /^l[1-9]\d{0,5}$/;
|
|
@@ -162,6 +163,7 @@ export function createMissionLog(options) {
|
|
|
162
163
|
return { total: entries.size, hits: found.map((e) => hit(e, q)) };
|
|
163
164
|
},
|
|
164
165
|
get: (id) => copy(find(id)),
|
|
166
|
+
chart: () => buildChart([...entries.values()]),
|
|
165
167
|
create(author, input) {
|
|
166
168
|
return locked(async () => {
|
|
167
169
|
const fields = validate(input, true);
|