@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
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plot Board: the one current plan of the room (docs/plot-board-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* One file, `<home>/board.md`: a small front matter (version, revision, author, updatedAt; each value JSON on one line) and then the
|
|
5
|
+
* plan as plain text. The Director (the browser route) and the boss (the MCP tool board_write) write it; every agent reads it. Who
|
|
6
|
+
* may write is decided by the caller (the route is the Director's, the tool checks for the boss): this store only checks the text and
|
|
7
|
+
* the revision. A write names the revision it read and is refused when the board has moved on, so a write never replaces text its
|
|
8
|
+
* author did not see. The file is written whole to a temporary file and renamed. A file without our front matter (written by hand) is
|
|
9
|
+
* read as the plan itself. The clock is injected for tests.
|
|
10
|
+
*
|
|
11
|
+
* shortcut: a hand edit made while gonogo runs is not seen until the next start, and the next write replaces it; read the file again
|
|
12
|
+
* on each get if that ever matters.
|
|
13
|
+
*/
|
|
14
|
+
import { randomBytes } from 'node:crypto';
|
|
15
|
+
import { readFile, rename, stat, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { BOARD_MAX_CHARS } from '../shared/protocol.js';
|
|
18
|
+
import { BOARD_FILE, FILE_MODE } from './constants.js';
|
|
19
|
+
import { isRecord } from './hooks.js';
|
|
20
|
+
import { HubError } from './hub.js';
|
|
21
|
+
const FIELDS = ['text', 'revision'];
|
|
22
|
+
/** The keys of our front matter; a file whose first lines are anything else is a plan written by hand. */
|
|
23
|
+
const FRONT_KEYS = ['version', 'revision', 'author', 'updatedAt'];
|
|
24
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
25
|
+
const render = (view) => [
|
|
26
|
+
'---',
|
|
27
|
+
'version: 1',
|
|
28
|
+
`revision: ${JSON.stringify(view.revision)}`,
|
|
29
|
+
`author: ${JSON.stringify(view.author)}`,
|
|
30
|
+
`updatedAt: ${JSON.stringify(view.updatedAt === null ? null : new Date(view.updatedAt).toISOString())}`,
|
|
31
|
+
'---',
|
|
32
|
+
view.text,
|
|
33
|
+
'',
|
|
34
|
+
].join('\n');
|
|
35
|
+
/** The board in a file; one that has our front matter is read by it, any other text is the plan itself. */
|
|
36
|
+
function parse(text, mtime, path) {
|
|
37
|
+
const found = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text.replace(/\r\n/g, '\n'));
|
|
38
|
+
const values = new Map();
|
|
39
|
+
try {
|
|
40
|
+
for (const line of found === null ? [] : (found[1] ?? '').split('\n')) {
|
|
41
|
+
const at = line.indexOf(': ');
|
|
42
|
+
if (at < 0 || !FRONT_KEYS.includes(line.slice(0, at)))
|
|
43
|
+
throw new Error('not ours');
|
|
44
|
+
values.set(line.slice(0, at), JSON.parse(line.slice(at + 2)));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
values.clear();
|
|
49
|
+
}
|
|
50
|
+
if (found === null || values.size === 0)
|
|
51
|
+
return { text: text.replace(/\r\n/g, '\n').trimEnd().slice(0, BOARD_MAX_CHARS), revision: 0, author: null, updatedAt: mtime };
|
|
52
|
+
const { version, revision, author, updatedAt } = Object.fromEntries(values);
|
|
53
|
+
if (version !== undefined && version !== 1) {
|
|
54
|
+
throw new Error(`${path} was saved by a newer gonogo (format version ${String(version)}; this one reads up to 1). Start the gonogo that saved it, or move the file away to start without it.`);
|
|
55
|
+
}
|
|
56
|
+
const at = typeof updatedAt === 'string' ? Date.parse(updatedAt) : Number.NaN;
|
|
57
|
+
return {
|
|
58
|
+
text: (found[2] ?? '').replace(/\n$/, '').slice(0, BOARD_MAX_CHARS),
|
|
59
|
+
revision: typeof revision === 'number' && Number.isSafeInteger(revision) && revision >= 0 ? revision : 0,
|
|
60
|
+
author: typeof author === 'string' && author !== '' ? author : null,
|
|
61
|
+
updatedAt: Number.isNaN(at) ? mtime : at,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function createBoard(options) {
|
|
65
|
+
const { now } = options;
|
|
66
|
+
const path = join(options.dir, BOARD_FILE);
|
|
67
|
+
let current = { text: '', revision: 0, author: null, updatedAt: null };
|
|
68
|
+
let chain = Promise.resolve();
|
|
69
|
+
/** One write at a time, so that two writers of one revision cannot both succeed; a failure goes to the caller and the next write goes on. */
|
|
70
|
+
const locked = (fn) => {
|
|
71
|
+
const run = chain.then(fn);
|
|
72
|
+
chain = run.catch(() => undefined);
|
|
73
|
+
return run;
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
async load() {
|
|
77
|
+
let text;
|
|
78
|
+
try {
|
|
79
|
+
text = await readFile(path, 'utf8');
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code === 'ENOENT')
|
|
83
|
+
return;
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
current = parse(text, (await stat(path)).mtimeMs, path);
|
|
87
|
+
},
|
|
88
|
+
get: () => ({ ...current }),
|
|
89
|
+
write(by, input) {
|
|
90
|
+
return locked(async () => {
|
|
91
|
+
if (!isRecord(input))
|
|
92
|
+
throw bad('request body must be a JSON object');
|
|
93
|
+
for (const key of Object.keys(input))
|
|
94
|
+
if (!FIELDS.includes(key))
|
|
95
|
+
throw bad(`unknown field "${key}"`, key);
|
|
96
|
+
if (typeof input.text !== 'string')
|
|
97
|
+
throw bad('text is required', 'text');
|
|
98
|
+
const text = input.text.replace(/\r\n?/g, '\n').trimEnd();
|
|
99
|
+
if (text.length > BOARD_MAX_CHARS)
|
|
100
|
+
throw bad(`text must be at most ${BOARD_MAX_CHARS} characters`, 'text');
|
|
101
|
+
if (text.includes('\0'))
|
|
102
|
+
throw bad('text must not hold a NUL character', 'text');
|
|
103
|
+
if (typeof input.revision !== 'number' || !Number.isSafeInteger(input.revision) || input.revision < 0)
|
|
104
|
+
throw bad('revision must be a whole number, the one you read', 'revision');
|
|
105
|
+
if (input.revision !== current.revision) {
|
|
106
|
+
throw new HubError('conflict', `the Plot Board is at revision ${current.revision}, not ${input.revision}: read it again, then write`, 'revision');
|
|
107
|
+
}
|
|
108
|
+
// the same text again changes nothing: no new revision, no new file
|
|
109
|
+
if (text === current.text)
|
|
110
|
+
return { ...current };
|
|
111
|
+
const next = { text, revision: current.revision + 1, author: by, updatedAt: now() };
|
|
112
|
+
const tmp = join(options.dir, `.${BOARD_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
113
|
+
await writeFile(tmp, render(next), { mode: FILE_MODE, flag: 'wx' });
|
|
114
|
+
await rename(tmp, path);
|
|
115
|
+
current = next;
|
|
116
|
+
return { ...current };
|
|
117
|
+
});
|
|
118
|
+
},
|
|
119
|
+
close() {
|
|
120
|
+
return chain.then(() => undefined);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
package/dist/server/cleanroom.js
CHANGED
|
@@ -3,18 +3,18 @@
|
|
|
3
3
|
* setting, checks Docker and the repository, makes the worktree once and builds the `docker run` arguments. The launcher
|
|
4
4
|
* puts them together with the files and the environment of a Claude Code start.
|
|
5
5
|
*/
|
|
6
|
-
import { execFile } from 'node:child_process';
|
|
7
6
|
import { createHash } from 'node:crypto';
|
|
8
7
|
import { lookup } from 'node:dns/promises';
|
|
9
|
-
import { lstat, mkdir, realpath
|
|
8
|
+
import { lstat, mkdir, realpath } from 'node:fs/promises';
|
|
10
9
|
import { hostname } from 'node:os';
|
|
11
|
-
import { basename,
|
|
10
|
+
import { basename, join } from 'node:path';
|
|
12
11
|
import { CLEAN_ROOM_DIR, cleanRoomBranch } from '../shared/protocol.js';
|
|
13
|
-
import {
|
|
12
|
+
import { cwdInWorktree, ensureWorktree, messageOf, run, topOf } from './worktree.js';
|
|
13
|
+
export { ensureWorktree };
|
|
14
|
+
import { CLEAN_ROOM_DEFAULT_IMAGE, CLEAN_ROOM_HOME_DIR, CLEAN_ROOM_HOST, CLEAN_ROOM_IMAGE_ENV, CLEAN_ROOM_IMAGE_PATTERN, CLEAN_ROOM_NETWORK_ENV, CLEAN_ROOM_NETWORK_PATTERN, CLEAN_ROOM_NETWORK_SELF, DIR_MODE, DOCKER_BIN, } from './constants.js';
|
|
14
15
|
const IMAGE_RE = new RegExp(CLEAN_ROOM_IMAGE_PATTERN);
|
|
15
16
|
const NETWORK_RE = new RegExp(CLEAN_ROOM_NETWORK_PATTERN);
|
|
16
17
|
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
17
|
-
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
18
18
|
/** The one reader of a Clean Room setting: the hub uses it for hire and edit, home.ts for the roster file. `{}` is the default image. */
|
|
19
19
|
export function parseCleanRoom(value, provider) {
|
|
20
20
|
if (!isRecord(value))
|
|
@@ -67,18 +67,6 @@ export function sameMountError(mounts, homeDir, container) {
|
|
|
67
67
|
return null;
|
|
68
68
|
return `gonogo's home ${homeDir} is not mounted into the container ${container} from the same path of the host: the host's Docker mounts a Clean Room's folders by their host paths, so mount it as -v ${homeDir}:${homeDir}`;
|
|
69
69
|
}
|
|
70
|
-
/** Runs a program without a shell and answers its output. A failure is an Error whose text is the first line the program printed on stderr. */
|
|
71
|
-
function run(file, args, env) {
|
|
72
|
-
return new Promise((resolve, reject) => {
|
|
73
|
-
execFile(file, args, { env: env, timeout: CLEAN_ROOM_COMMAND_MS, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
|
|
74
|
-
if (error === null)
|
|
75
|
-
return resolve(stdout);
|
|
76
|
-
const code = error.code;
|
|
77
|
-
const line = stderr.split('\n').find((l) => l.trim() !== '')?.trim() ?? error.message.split('\n')[0] ?? '';
|
|
78
|
-
reject(new Error(code === 'ENOENT' ? `${file} was not found on PATH` : line.slice(0, 300)));
|
|
79
|
-
});
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
70
|
/** Docker is there and its daemon answers: `docker version` exits 0 only then. */
|
|
83
71
|
export async function checkDocker(env) {
|
|
84
72
|
try {
|
|
@@ -89,14 +77,7 @@ export async function checkDocker(env) {
|
|
|
89
77
|
}
|
|
90
78
|
}
|
|
91
79
|
/** The top folder of the git repository that holds `dir`. */
|
|
92
|
-
export
|
|
93
|
-
try {
|
|
94
|
-
return (await run(GIT_BIN, ['-C', dir, 'rev-parse', '--show-toplevel'], env)).trim();
|
|
95
|
-
}
|
|
96
|
-
catch (error) {
|
|
97
|
-
throw new Error(`Clean Room needs the directory to be inside a git repository: ${messageOf(error)}`);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
80
|
+
export const repoRoot = (dir, env) => topOf(dir, env, 'Clean Room needs');
|
|
100
81
|
/** What the hub asks at hire and edit: null when Docker works and `dir` is in a repository, else why not. */
|
|
101
82
|
export async function checkCleanRoom(dir, env) {
|
|
102
83
|
try {
|
|
@@ -109,27 +90,6 @@ export async function checkCleanRoom(dir, env) {
|
|
|
109
90
|
return messageOf(error);
|
|
110
91
|
}
|
|
111
92
|
}
|
|
112
|
-
/** Makes the worktree on its branch the first time and finds it again after that. A folder in its place that git does not know is an error, never reused. */
|
|
113
|
-
export async function ensureWorktree(repo, path, branch, env) {
|
|
114
|
-
const git = (...args) => run(GIT_BIN, ['-C', repo, ...args], env);
|
|
115
|
-
const real = await realpath(path).catch(() => null);
|
|
116
|
-
if (real !== null) {
|
|
117
|
-
const listed = (await git('worktree', 'list', '--porcelain')).split('\n').filter((l) => l.startsWith('worktree ')).map((l) => l.slice(9));
|
|
118
|
-
if (!(await Promise.all(listed.map((p) => realpath(p).catch(() => p)))).includes(real)) {
|
|
119
|
-
throw new Error(`${path} exists but is not a worktree of ${repo}; move it away or give the agent a folder of the repository it was made for`);
|
|
120
|
-
}
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });
|
|
124
|
-
try {
|
|
125
|
-
await git('worktree', 'prune'); // a worktree whose folder was deleted still holds its branch
|
|
126
|
-
const known = await git('show-ref', '--verify', '--quiet', `refs/heads/${branch}`).then(() => true, () => false);
|
|
127
|
-
await git('worktree', 'add', ...(known ? [path, branch] : ['-b', branch, path]));
|
|
128
|
-
}
|
|
129
|
-
catch (error) {
|
|
130
|
-
throw new Error(`could not make the worktree ${path} on ${branch}: ${messageOf(error)}`);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
93
|
/** `gonogo-<name>-<hash of the worktree path>`: two gonogo homes on one Docker never share a name. */
|
|
134
94
|
export const containerName = (worktree) => `gonogo-${basename(worktree)}-${createHash('sha256').update(worktree).digest('hex').slice(0, 12)}`;
|
|
135
95
|
/**
|
|
@@ -163,11 +123,7 @@ export async function prepareCleanRoom(agent, homeDir, base, env) {
|
|
|
163
123
|
const top = await realpath(await repoRoot(agent.dir, env));
|
|
164
124
|
const worktree = join(homeDir, CLEAN_ROOM_DIR, agent.name);
|
|
165
125
|
await ensureWorktree(top, worktree, cleanRoomBranch(agent.name), env);
|
|
166
|
-
const
|
|
167
|
-
const cwd = join(worktree, inside);
|
|
168
|
-
if (!(await stat(cwd).then((info) => info.isDirectory(), () => false))) {
|
|
169
|
-
throw new Error(`${inside} is not in the worktree ${worktree}: the worktree is a copy of the last commit, and that folder is not committed`);
|
|
170
|
-
}
|
|
126
|
+
const cwd = await cwdInWorktree(top, worktree, agent.dir);
|
|
171
127
|
const container = containerName(worktree);
|
|
172
128
|
await removeContainer(container, env);
|
|
173
129
|
const home = join(base, CLEAN_ROOM_HOME_DIR);
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clearance (docs/engine-bay-spec.md): environment variables the Director sets for one agent, usually API keys.
|
|
3
|
+
*
|
|
4
|
+
* keys.json (mode 0600, written whole through a temporary file and a rename) holds the values: agent name to name to value.
|
|
5
|
+
* The roster keeps the names and the time each was set, so the page can say "set"; a value is never sent to a browser and
|
|
6
|
+
* never logged. The launcher puts an agent's keys in that agent's environment only (launcher.ts).
|
|
7
|
+
*
|
|
8
|
+
* shortcut: the values are stored as text (an API key has to be sent as it is), so the file is 0600 and nothing else; encrypt
|
|
9
|
+
* it if the home folder is ever shared.
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from 'node:crypto';
|
|
12
|
+
import { readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { KEY_NAME_PATTERN, KEY_VALUE_PATTERN, KEYS_MAX } from '../shared/protocol.js';
|
|
15
|
+
import { FILE_MODE, KEYS_FILE, nullLogger } from './constants.js';
|
|
16
|
+
const NAME_RE = new RegExp(KEY_NAME_PATTERN);
|
|
17
|
+
const VALUE_RE = new RegExp(KEY_VALUE_PATTERN);
|
|
18
|
+
/** Variables that change what runs or where, or that gonogo sets itself: a key is data, so these are refused. */
|
|
19
|
+
const RESERVED_EXACT = new Set([
|
|
20
|
+
'PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'PWD', 'TMPDIR', 'TERM', 'COLORTERM', 'IS_DEMO', 'NODE_OPTIONS', 'NODE_PATH', 'CLAUDE_CONFIG_DIR',
|
|
21
|
+
// shell and interpreter start-up hooks: each runs a file or a command before the program the agent started
|
|
22
|
+
'BASH_ENV', 'SHELLOPTS', 'BASHOPTS', 'PROMPT_COMMAND', 'IFS', 'PYTHONSTARTUP', 'PYTHONPATH', 'PYTHONHOME', 'RUBYOPT', 'RUBYLIB', 'PERL5OPT', 'PERL5LIB',
|
|
23
|
+
'GIT_SSH_COMMAND', 'GIT_ASKPASS', 'SSH_ASKPASS', 'GIT_EXEC_PATH',
|
|
24
|
+
]);
|
|
25
|
+
// DOCKER_: a Clean Room's docker client runs with the agent's keys in its environment, and DOCKER_HOST would move the container to another daemon.
|
|
26
|
+
// shortcut: the usual start-up hooks, not every variable some program reads as a command; the Director owns the agent anyway, so extend the list when one turns up.
|
|
27
|
+
const RESERVED_PREFIXES = ['GONOGO_', 'LD_', 'DYLD_', 'BASH_FUNC_', 'DOCKER_', 'GIT_CONFIG_'];
|
|
28
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
29
|
+
/** Why this name cannot be a key, or null. */
|
|
30
|
+
export function keyNameProblem(name) {
|
|
31
|
+
// the name is not echoed: a value pasted in the wrong field must not come back in an error
|
|
32
|
+
if (!NAME_RE.test(name))
|
|
33
|
+
return 'a key name uses capital letters, digits and _, starting with a letter (at most 64 characters)';
|
|
34
|
+
if (RESERVED_EXACT.has(name) || RESERVED_PREFIXES.some((prefix) => name.startsWith(prefix)))
|
|
35
|
+
return `${name} is set by gonogo or changes what runs, so it cannot be a key`;
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The shape of a hire's or an edit's keys: name to value, and for an edit also name to null (remove). `current` is the names
|
|
40
|
+
* the agent has (name to time), `names` the names it will have, new and changed ones stamped `now`. Values stay in `patch`.
|
|
41
|
+
* An error names the key and says what is wrong, never what the value was.
|
|
42
|
+
*/
|
|
43
|
+
export function checkKeys(value, current, now, hire) {
|
|
44
|
+
if (!isRecord(value))
|
|
45
|
+
return { ok: false, error: 'keys must be an object of names and values' };
|
|
46
|
+
const entries = Object.entries(value);
|
|
47
|
+
if (entries.length > KEYS_MAX)
|
|
48
|
+
return { ok: false, error: `at most ${KEYS_MAX} keys` };
|
|
49
|
+
const names = { ...current };
|
|
50
|
+
const patch = {};
|
|
51
|
+
for (const [name, item] of entries) {
|
|
52
|
+
const problem = keyNameProblem(name);
|
|
53
|
+
if (problem !== null)
|
|
54
|
+
return { ok: false, error: problem };
|
|
55
|
+
if (item === null && !hire) {
|
|
56
|
+
delete names[name];
|
|
57
|
+
patch[name] = null;
|
|
58
|
+
}
|
|
59
|
+
else if (typeof item === 'string' && VALUE_RE.test(item)) {
|
|
60
|
+
names[name] = now;
|
|
61
|
+
patch[name] = item;
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
return { ok: false, error: `${name} must be text of 1 to 4096 printable characters without a space${hire ? '' : ', or null to remove it'}` };
|
|
65
|
+
}
|
|
66
|
+
if (Object.keys(names).length > KEYS_MAX)
|
|
67
|
+
return { ok: false, error: `at most ${KEYS_MAX} keys` };
|
|
68
|
+
return { ok: true, patch, names };
|
|
69
|
+
}
|
|
70
|
+
export function createClearance(options) {
|
|
71
|
+
const log = options.log ?? nullLogger;
|
|
72
|
+
const path = join(options.dir, KEYS_FILE);
|
|
73
|
+
let agents = new Map();
|
|
74
|
+
let chain = Promise.resolve();
|
|
75
|
+
/** One write after the other; a failed one rejects to its caller and does not stop the next. A change that returns the same map writes nothing. */
|
|
76
|
+
const write = (change) => {
|
|
77
|
+
const run = chain.then(async () => {
|
|
78
|
+
const before = agents;
|
|
79
|
+
agents = change();
|
|
80
|
+
if (agents === before)
|
|
81
|
+
return;
|
|
82
|
+
const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
83
|
+
try {
|
|
84
|
+
await writeFile(temp, JSON.stringify({ version: 1, agents: Object.fromEntries(agents) }, null, 2), { flag: 'wx', mode: FILE_MODE });
|
|
85
|
+
await rename(temp, path);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
agents = before;
|
|
89
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
90
|
+
// the message of a file error holds a path, not a value
|
|
91
|
+
throw new Error(`could not save the keys: ${error instanceof Error ? error.message : String(error)}`);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
chain = run.catch(() => undefined);
|
|
95
|
+
return run;
|
|
96
|
+
};
|
|
97
|
+
return {
|
|
98
|
+
async load() {
|
|
99
|
+
let saved;
|
|
100
|
+
try {
|
|
101
|
+
saved = JSON.parse(await readFile(path, 'utf8'));
|
|
102
|
+
if (!isRecord(saved) || saved.version !== 1 || !isRecord(saved.agents))
|
|
103
|
+
throw new Error('not a version 1 keys file');
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code === 'ENOENT')
|
|
107
|
+
return;
|
|
108
|
+
// kept aside, so that the next save cannot overwrite the keys; a SyntaxError quotes the text around the fault, which can be a key
|
|
109
|
+
log.error(`${KEYS_FILE} could not be read; agents start without keys and the file is kept as ${KEYS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
|
|
110
|
+
await rename(path, `${path}.bad`).catch(() => undefined);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
for (const [agent, keys] of Object.entries(saved.agents)) {
|
|
114
|
+
if (!isRecord(keys))
|
|
115
|
+
continue;
|
|
116
|
+
const own = Object.fromEntries(Object.entries(keys).filter(([name, value]) => keyNameProblem(name) === null && typeof value === 'string' && VALUE_RE.test(value)));
|
|
117
|
+
if (Object.keys(own).length > 0)
|
|
118
|
+
agents.set(agent, own);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
values: (name) => ({ ...agents.get(name) }),
|
|
122
|
+
apply: (name, patch, fresh = false) => write(() => {
|
|
123
|
+
const keys = { ...(fresh ? {} : agents.get(name)) };
|
|
124
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
125
|
+
if (value === null)
|
|
126
|
+
delete keys[key];
|
|
127
|
+
else
|
|
128
|
+
keys[key] = value;
|
|
129
|
+
}
|
|
130
|
+
const empty = Object.keys(keys).length === 0;
|
|
131
|
+
if (empty && !agents.has(name))
|
|
132
|
+
return agents;
|
|
133
|
+
const next = new Map(agents);
|
|
134
|
+
if (empty)
|
|
135
|
+
next.delete(name);
|
|
136
|
+
else
|
|
137
|
+
next.set(name, keys);
|
|
138
|
+
return next;
|
|
139
|
+
}),
|
|
140
|
+
rename: (oldName, newName) => write(() => {
|
|
141
|
+
const keys = agents.get(oldName);
|
|
142
|
+
if (keys === undefined)
|
|
143
|
+
return agents;
|
|
144
|
+
const next = new Map(agents);
|
|
145
|
+
next.delete(oldName);
|
|
146
|
+
next.set(newName, keys);
|
|
147
|
+
return next;
|
|
148
|
+
}),
|
|
149
|
+
remove: (name) => write(() => {
|
|
150
|
+
if (!agents.has(name))
|
|
151
|
+
return agents;
|
|
152
|
+
const next = new Map(agents);
|
|
153
|
+
next.delete(name);
|
|
154
|
+
return next;
|
|
155
|
+
}),
|
|
156
|
+
close: () => chain.then(() => undefined),
|
|
157
|
+
};
|
|
158
|
+
}
|