@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,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recorder (docs/recorder-spec.md): git for one agent's folder, or its Clean Room worktree, for the Director's browser.
|
|
3
|
+
* Status, a diff (read-only), the last 50 commits, and a commit of all changes or of what is staged, with a message the
|
|
4
|
+
* Director wrote and the author from his own git config. No push, pull, checkout, reset or any other command. Git runs
|
|
5
|
+
* through execFile with an argument list, hooks off, no prompt, a time limit and an output cap.
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { realpath } from 'node:fs/promises';
|
|
9
|
+
import { RECORDER_LOG_MAX, RECORDER_MESSAGE_MAX_CHARS, RECORDER_SCOPES } from '../shared/protocol.js';
|
|
10
|
+
import { GIT_BIN } from './constants.js';
|
|
11
|
+
import { HubError } from './hub.js';
|
|
12
|
+
import { inside, pathParts } from './hangar.js';
|
|
13
|
+
export const RECORDER_READ_MS = 15_000;
|
|
14
|
+
export const RECORDER_WRITE_MS = 30_000;
|
|
15
|
+
/** Output of a read: status and log are cut at 1 MiB, a diff at 256 KiB. */
|
|
16
|
+
export const RECORDER_LIST_CAP = 1024 * 1024;
|
|
17
|
+
export const RECORDER_DIFF_CAP = 256 * 1024;
|
|
18
|
+
export const RECORDER_FILES_MAX = 1000;
|
|
19
|
+
/** Hooks off, and the programs a repository's own config could name for a read (the file system monitor, an external diff) off. */
|
|
20
|
+
const BASE_ARGS = ['--literal-pathspecs', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'core.quotepath=false'];
|
|
21
|
+
/** What git may see of the environment: no GIT_DIR or GIT_WORK_TREE or GIT_EXTERNAL_DIFF from gonogo's own, no credential. */
|
|
22
|
+
const KEEP_ENV = ['PATH', 'HOME', 'USER', 'LOGNAME', 'XDG_CONFIG_HOME', 'TMPDIR'];
|
|
23
|
+
class GitFailure extends Error {
|
|
24
|
+
status;
|
|
25
|
+
constructor(status, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.status = status;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
31
|
+
export function createRecorder(roots, env) {
|
|
32
|
+
const gitEnv = { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' };
|
|
33
|
+
for (const key of KEEP_ENV) {
|
|
34
|
+
const value = env[key];
|
|
35
|
+
if (value !== undefined)
|
|
36
|
+
gitEnv[key] = value;
|
|
37
|
+
}
|
|
38
|
+
/** Runs git in the root. A call over its time is stopped with SIGTERM, not SIGKILL: git then removes its own index.lock, which a kill would leave to block every later add and commit. Output over `cap` is cut and `truncated` says so; a failure is a GitFailure with the first line git printed on stderr. */
|
|
39
|
+
function git(at, args, cap, timeout) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
execFile(GIT_BIN, [...BASE_ARGS, ...args], { cwd: at.root, env: gitEnv, timeout, killSignal: 'SIGTERM', maxBuffer: cap + 1, encoding: 'utf8' }, (error, stdout, stderr) => {
|
|
42
|
+
if (error === null)
|
|
43
|
+
return resolve({ out: stdout.slice(0, cap), truncated: stdout.length > cap });
|
|
44
|
+
const code = error.code;
|
|
45
|
+
if (code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')
|
|
46
|
+
return resolve({ out: String(stdout).slice(0, cap), truncated: true });
|
|
47
|
+
if (code === 'ENOENT')
|
|
48
|
+
return reject(new HubError('unavailable', 'git was not found on PATH'));
|
|
49
|
+
if (error.killed)
|
|
50
|
+
return reject(new HubError('unavailable', 'git did not answer in time'));
|
|
51
|
+
const line = stderr.split('\n').find((l) => l.trim() !== '')?.trim() ?? `git exited with ${String(code)}`;
|
|
52
|
+
reject(new GitFailure(typeof code === 'number' || typeof code === 'string' ? code : null, line.slice(0, 300)));
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** The repository at the root, or why not. It must be the top of a repository, and gonogo's own folder must not be inside it. */
|
|
57
|
+
async function repoProblem(at) {
|
|
58
|
+
let top;
|
|
59
|
+
try {
|
|
60
|
+
top = (await git(at, ['rev-parse', '--show-toplevel'], 4096, RECORDER_READ_MS)).out.trim();
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
if (e instanceof GitFailure)
|
|
64
|
+
return /not a git repository/i.test(e.message) ? 'this folder is not in a git repository' : `git said: ${e.message}`;
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
if ((await realpath(top).catch(() => top)) !== at.root)
|
|
68
|
+
return `this folder is inside the repository at ${top}: the Recorder works at the top of a repository`;
|
|
69
|
+
if (inside(at.root, at.home))
|
|
70
|
+
return 'gonogo\'s own folder is inside this repository, and the Recorder will not commit it';
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
async function author(at) {
|
|
74
|
+
const get = (key) => git(at, ['config', '--get', key], 1024, RECORDER_READ_MS).then((r) => r.out.trim(), (e) => {
|
|
75
|
+
if (e instanceof GitFailure)
|
|
76
|
+
return ''; // exit 1: the key is not set
|
|
77
|
+
throw e;
|
|
78
|
+
});
|
|
79
|
+
const [name, email] = await Promise.all([get('user.name'), get('user.email')]);
|
|
80
|
+
return name === '' || email === '' ? null : { name, email };
|
|
81
|
+
}
|
|
82
|
+
async function ready(name) {
|
|
83
|
+
const at = await roots(name);
|
|
84
|
+
const problem = await repoProblem(at);
|
|
85
|
+
if (problem !== null)
|
|
86
|
+
throw new HubError('conflict', problem);
|
|
87
|
+
return at;
|
|
88
|
+
}
|
|
89
|
+
async function lastCommits(at, count) {
|
|
90
|
+
let out;
|
|
91
|
+
try {
|
|
92
|
+
out = (await git(at, ['log', '-n', String(count), '--no-color', '--no-decorate', '-z', '--format=%H%x1f%an%x1f%at%x1f%s'], RECORDER_LIST_CAP, RECORDER_READ_MS)).out;
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
if (e instanceof GitFailure && /does not have any commits yet/.test(e.message))
|
|
96
|
+
return [];
|
|
97
|
+
throw e;
|
|
98
|
+
}
|
|
99
|
+
return out.split('\0').filter((r) => r !== '').map((record) => {
|
|
100
|
+
const [hash = '', who = '', at2 = '0', ...subject] = record.split('\x1f');
|
|
101
|
+
return { hash, author: who.slice(0, 200), at: Number(at2) * 1000, subject: subject.join('\x1f').slice(0, 300) };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
async status(name) {
|
|
106
|
+
const at = await roots(name);
|
|
107
|
+
const problem = await repoProblem(at);
|
|
108
|
+
if (problem !== null)
|
|
109
|
+
return { repo: false, reason: problem };
|
|
110
|
+
const { out } = await git(at, ['status', '--porcelain=v1', '-z', '--branch', '--untracked-files=normal'], RECORDER_LIST_CAP, RECORDER_READ_MS);
|
|
111
|
+
const records = out.split('\0');
|
|
112
|
+
const files = [];
|
|
113
|
+
let branch = '';
|
|
114
|
+
for (let i = 0; i < records.length; i += 1) {
|
|
115
|
+
const record = records[i] ?? '';
|
|
116
|
+
if (record.startsWith('## '))
|
|
117
|
+
branch = record.slice(3, 203);
|
|
118
|
+
else if (record.length > 3) {
|
|
119
|
+
const file = { path: record.slice(3), index: record[0] ?? ' ', tree: record[1] ?? ' ' };
|
|
120
|
+
if (file.index === 'R' || file.index === 'C')
|
|
121
|
+
file.from = records[(i += 1)];
|
|
122
|
+
files.push(file);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { repo: true, branch, files: files.slice(0, RECORDER_FILES_MAX), more: Math.max(0, files.length - RECORDER_FILES_MAX), author: await author(at) };
|
|
126
|
+
},
|
|
127
|
+
async diff(name, raw, staged) {
|
|
128
|
+
const parts = pathParts(raw ?? '');
|
|
129
|
+
const at = await ready(name);
|
|
130
|
+
const args = ['diff', '--no-ext-diff', '--no-textconv', '--no-color', ...(staged ? ['--cached'] : []), '--', ...(parts.length === 0 ? [] : [parts.join('/')])];
|
|
131
|
+
const { out, truncated } = await git(at, args, RECORDER_DIFF_CAP, RECORDER_READ_MS);
|
|
132
|
+
return { diff: out, truncated };
|
|
133
|
+
},
|
|
134
|
+
async log(name) {
|
|
135
|
+
return lastCommits(await ready(name), RECORDER_LOG_MAX);
|
|
136
|
+
},
|
|
137
|
+
async commit(name, input) {
|
|
138
|
+
if (typeof input !== 'object' || input === null || Array.isArray(input))
|
|
139
|
+
throw bad('the body must be an object');
|
|
140
|
+
const { message, scope } = input;
|
|
141
|
+
if (typeof message !== 'string' || message.trim() === '')
|
|
142
|
+
throw bad('write a message for the commit', 'message');
|
|
143
|
+
if (message.length > RECORDER_MESSAGE_MAX_CHARS)
|
|
144
|
+
throw bad(`the message is longer than ${RECORDER_MESSAGE_MAX_CHARS} characters`, 'message');
|
|
145
|
+
if (message.includes('\0'))
|
|
146
|
+
throw bad('the message has a NUL character', 'message');
|
|
147
|
+
if (scope !== 'all' && scope !== 'staged')
|
|
148
|
+
throw bad(`scope must be one of ${RECORDER_SCOPES.join(', ')}`, 'scope');
|
|
149
|
+
const at = await ready(name);
|
|
150
|
+
if ((await author(at)) === null) {
|
|
151
|
+
throw new HubError('conflict', 'git has no author: set user.name and user.email (git config --global user.name "Your Name"), then commit again', 'author');
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
if (scope === 'all')
|
|
155
|
+
await git(at, ['add', '-A'], 4096, RECORDER_WRITE_MS);
|
|
156
|
+
const staged = await git(at, ['diff', '--cached', '--quiet', '--no-ext-diff'], 4096, RECORDER_READ_MS).then(() => false, (e) => {
|
|
157
|
+
if (e instanceof GitFailure && e.status === 1)
|
|
158
|
+
return true; // exit 1: the index differs from HEAD
|
|
159
|
+
throw e;
|
|
160
|
+
});
|
|
161
|
+
if (!staged)
|
|
162
|
+
throw new HubError('conflict', scope === 'all' ? 'nothing to commit: the folder has no changes' : 'nothing is staged', 'scope');
|
|
163
|
+
await git(at, ['-c', 'user.useConfigOnly=true', 'commit', '-m', message], 4096, RECORDER_WRITE_MS);
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
if (e instanceof GitFailure)
|
|
167
|
+
throw new HubError('conflict', `git refused: ${e.message}`);
|
|
168
|
+
throw e;
|
|
169
|
+
}
|
|
170
|
+
const [commit] = await lastCommits(at, 1);
|
|
171
|
+
if (commit === undefined)
|
|
172
|
+
throw new HubError('internal', 'the commit was made but git does not list it');
|
|
173
|
+
return { commit };
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
package/dist/server/relay.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { randomBytes } from 'node:crypto';
|
|
19
19
|
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
20
20
|
import { join } from 'node:path';
|
|
21
|
-
import { RELAY_FORWARD_KINDS, RELAY_SERVICES } from '../shared/protocol.js';
|
|
21
|
+
import { PHONE_MODES, RELAY_FORWARD_KINDS, RELAY_SERVICES } from '../shared/protocol.js';
|
|
22
22
|
import { FILE_MODE, RELAY_BACKOFF_MS, RELAY_FILE, RELAY_NOTE_MAX_CHARS, RELAY_QUEUE_MAX, RELAY_RETRY_AFTER_MAX_MS, RELAY_SEEN_MAX, RELAY_TEXT_MAX_CHARS, RELAY_THREADS_MAX, RELAY_TIMEOUT_MS, RELAY_TRIES, } from './constants.js';
|
|
23
23
|
import { isRecord } from './hooks.js';
|
|
24
24
|
import { cutText, HubError } from './hub.js';
|
|
@@ -50,11 +50,11 @@ const SERVICES = {
|
|
|
50
50
|
token: /^\d{4,15}:[A-Za-z0-9_-]{20,64}$/,
|
|
51
51
|
to: /^-?[1-9]\d{0,19}$/,
|
|
52
52
|
toHint: 'the chat id, a number such as 123456789',
|
|
53
|
-
request: (target, text) => ({
|
|
53
|
+
request: (target, text, extra) => ({
|
|
54
54
|
// the token is part of the address: this url is never logged
|
|
55
55
|
url: `https://api.telegram.org/bot${target.token}/sendMessage`,
|
|
56
56
|
headers: { 'Content-Type': 'application/json' },
|
|
57
|
-
body: { chat_id: target.to, text },
|
|
57
|
+
body: { chat_id: target.to, text, ...extra },
|
|
58
58
|
}),
|
|
59
59
|
answer: (json, target) => {
|
|
60
60
|
const id = pick(json, ['result', 'message_id']);
|
|
@@ -87,6 +87,7 @@ export function createRelay(options) {
|
|
|
87
87
|
const last = {};
|
|
88
88
|
/** Everything is sent until the Director chooses. */
|
|
89
89
|
let forwarded = new Set(RELAY_FORWARD_KINDS);
|
|
90
|
+
let phone = 'off';
|
|
90
91
|
/** Forwarded messages by the service's own id, oldest first (a Map keeps the order of insertion). */
|
|
91
92
|
const threads = new Map();
|
|
92
93
|
const handled = new Set();
|
|
@@ -100,7 +101,7 @@ export function createRelay(options) {
|
|
|
100
101
|
return run.then(() => undefined);
|
|
101
102
|
};
|
|
102
103
|
const save = () => {
|
|
103
|
-
const json = JSON.stringify({ version: 1, ...targets, forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)) }, null, 2);
|
|
104
|
+
const json = JSON.stringify({ version: 1, ...targets, forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)), phone }, null, 2);
|
|
104
105
|
return later(async () => {
|
|
105
106
|
const tmp = join(dir, `.${RELAY_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
106
107
|
await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
|
|
@@ -109,12 +110,12 @@ export function createRelay(options) {
|
|
|
109
110
|
};
|
|
110
111
|
const view = () => {
|
|
111
112
|
const of = (service) => (targets[service] ? { to: targets[service].to, last: last[service] ?? null } : null);
|
|
112
|
-
return { slack: of('slack'), telegram: of('telegram'), forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)) };
|
|
113
|
+
return { slack: of('slack'), telegram: of('telegram'), forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)), phone };
|
|
113
114
|
};
|
|
114
115
|
/** One message to one service: the id the service gave it, or why it did not go. Never throws, never says the token. */
|
|
115
|
-
async function post(service, target, text, tries) {
|
|
116
|
+
async function post(service, target, text, tries, extra) {
|
|
116
117
|
const def = SERVICES[service];
|
|
117
|
-
const { url, headers, body } = def.request(target, text);
|
|
118
|
+
const { url, headers, body } = def.request(target, text, extra);
|
|
118
119
|
let note = '';
|
|
119
120
|
for (let attempt = 1; attempt <= tries && !closing.signal.aborted; attempt++) {
|
|
120
121
|
let wait = RELAY_BACKOFF_MS * 2 ** (attempt - 1);
|
|
@@ -219,6 +220,8 @@ export function createRelay(options) {
|
|
|
219
220
|
else
|
|
220
221
|
log.warn(`${RELAY_FILE}: the ${service} target was skipped`);
|
|
221
222
|
}
|
|
223
|
+
if (typeof saved.phone === 'string' && PHONE_MODES.includes(saved.phone))
|
|
224
|
+
phone = saved.phone;
|
|
222
225
|
if (Array.isArray(saved.forward))
|
|
223
226
|
forwarded = new Set(saved.forward.filter((k) => typeof k === 'string' && isForward(k)));
|
|
224
227
|
},
|
|
@@ -262,6 +265,49 @@ export function createRelay(options) {
|
|
|
262
265
|
await save();
|
|
263
266
|
return view();
|
|
264
267
|
},
|
|
268
|
+
async setPhone(input) {
|
|
269
|
+
if (!isRecord(input))
|
|
270
|
+
throw bad('request body must be a JSON object');
|
|
271
|
+
for (const key of Object.keys(input))
|
|
272
|
+
if (key !== 'mode')
|
|
273
|
+
throw bad(`unknown field "${key}"`, key);
|
|
274
|
+
if (typeof input.mode !== 'string' || !PHONE_MODES.includes(input.mode))
|
|
275
|
+
throw bad(`mode must be one of: ${PHONE_MODES.join(', ')}`, 'mode');
|
|
276
|
+
phone = input.mode;
|
|
277
|
+
await save();
|
|
278
|
+
return view();
|
|
279
|
+
},
|
|
280
|
+
phoneTelegram: () => (phone === 'telegram' || phone === 'both') && targets.telegram !== undefined,
|
|
281
|
+
async sendButtons(text, markup) {
|
|
282
|
+
const target = targets.telegram;
|
|
283
|
+
if (!target || closing.signal.aborted)
|
|
284
|
+
return false;
|
|
285
|
+
const clipped = text.length > RELAY_TEXT_MAX_CHARS ? `${cutText(text, RELAY_TEXT_MAX_CHARS - 1)}…` : text;
|
|
286
|
+
// not in the queue of the other forwards: a button that waits behind them may be late for its dialog
|
|
287
|
+
const sent = await post('telegram', target, clipped, RELAY_TRIES, { reply_markup: markup });
|
|
288
|
+
last.telegram = { at: now(), ok: sent.ok, note: sent.note };
|
|
289
|
+
if (!sent.ok)
|
|
290
|
+
log.warn(`relay: telegram: ${sent.note}`);
|
|
291
|
+
return sent.ok;
|
|
292
|
+
},
|
|
293
|
+
async telegramCall(method, body) {
|
|
294
|
+
const target = targets.telegram;
|
|
295
|
+
if (!target || closing.signal.aborted)
|
|
296
|
+
return false;
|
|
297
|
+
try {
|
|
298
|
+
const res = await options.fetch(`https://api.telegram.org/bot${target.token}/${method}`, {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
headers: { 'Content-Type': 'application/json' },
|
|
301
|
+
body: JSON.stringify({ chat_id: target.to, ...body }),
|
|
302
|
+
redirect: 'error',
|
|
303
|
+
signal: AbortSignal.any([AbortSignal.timeout(RELAY_TIMEOUT_MS), closing.signal]),
|
|
304
|
+
});
|
|
305
|
+
return res.ok;
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
},
|
|
265
311
|
async test(name) {
|
|
266
312
|
const service = serviceOf(name);
|
|
267
313
|
const target = targets[service];
|
|
@@ -160,7 +160,17 @@ const telegramAuthentic = (_raw, headers, secret) => {
|
|
|
160
160
|
return given !== null && same(given, secret);
|
|
161
161
|
};
|
|
162
162
|
function telegramRead(raw, _headers, inbound) {
|
|
163
|
-
const
|
|
163
|
+
const update = parse(raw);
|
|
164
|
+
// a button of phone approvals: only from the chat of the target, and what it means is for phone.ts to check (the tag)
|
|
165
|
+
const query = update.callback_query;
|
|
166
|
+
if (isRecord(query)) {
|
|
167
|
+
const chat = str(get(query, 'message.chat.id'));
|
|
168
|
+
const queryId = str(query.id);
|
|
169
|
+
if (chat === '' || chat !== inbound.telegramChat() || queryId === '' || typeof query.data !== 'string')
|
|
170
|
+
return null;
|
|
171
|
+
return { callback: { queryId, data: query.data, chat, messageId: str(get(query, 'message.message_id')) } };
|
|
172
|
+
}
|
|
173
|
+
const message = update.message;
|
|
164
174
|
const said = str(get(message, 'text')).trim();
|
|
165
175
|
const chat = str(get(message, 'chat.id'));
|
|
166
176
|
// a bot can be found and written to by anybody on Telegram: only the chat of the target is the Director
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Relief: a boss that asks for more hands (docs/relief-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* The boss calls `hire_agent`; that only makes a request. The request waits in memory, shown to the Director with every
|
|
5
|
+
* parameter, and only his GO makes the hub staff the agent, through `Hub.hire`, the call of the hire form. Everything the
|
|
6
|
+
* boss can ask is capped here, on the server: no mode above acceptEdits, no custom command, no payload, at most
|
|
7
|
+
* RELIEF_PENDING_MAX requests waiting and RELIEF_RATE_MAX in RELIEF_RATE_WINDOW_MS, a request expires after RELIEF_TTL_MS,
|
|
8
|
+
* a name is a valid free name, the folder passes the check of the form, a Clean Room boss hires Clean Room agents inside
|
|
9
|
+
* its own folder only. `hub.hire` checks everything again (name, room cap of MAX_AGENTS, folder, Docker) when the GO comes.
|
|
10
|
+
*
|
|
11
|
+
* shortcut: requests are not saved, so a restart drops them and the boss is not told; the Downlink event of the request stays.
|
|
12
|
+
* shortcut: a Clean Room boss's folder is checked with realpath when asked and again at the GO, not held open between the two.
|
|
13
|
+
*/
|
|
14
|
+
import { realpath } from 'node:fs/promises';
|
|
15
|
+
import { isAbsolute, relative, sep } from 'node:path';
|
|
16
|
+
import { positionById, POSITION_IDS } from '../shared/positions.js';
|
|
17
|
+
import { AGENT_NAME_PATTERN, DIR_MAX_CHARS, MAX_AGENTS, PERMISSION_MODES, PROVIDERS, RELIEF_MODES, RESERVED_NAMES, ROLE_MAX_CHARS } from '../shared/protocol.js';
|
|
18
|
+
import { providerInfo } from '../shared/protocol.js';
|
|
19
|
+
import { RELIEF_PENDING_MAX, RELIEF_RATE_MAX, RELIEF_RATE_WINDOW_MS, RELIEF_TTL_MS } from './constants.js';
|
|
20
|
+
import { isRecord } from './hooks.js';
|
|
21
|
+
import { HubError } from './hub.js';
|
|
22
|
+
const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
|
|
23
|
+
const ID_RE = /^h[1-9]\d{0,9}$/;
|
|
24
|
+
const FIELDS = new Set(['name', 'position', 'role', 'dir', 'engine', 'mode']);
|
|
25
|
+
/**
|
|
26
|
+
* What a person cannot see in the block but the new agent reads: control codes (a newline, a return and a tab are fine), format
|
|
27
|
+
* characters (zero width, direction overrides, the Unicode tag block that hides a whole sentence), line and paragraph
|
|
28
|
+
* separators, private-use and unassigned code points, and the variation selectors of the supplement.
|
|
29
|
+
*/
|
|
30
|
+
const HIDDEN_RE = /[^\P{Cc}\n\r\t]|[\p{Cf}\p{Zl}\p{Zp}\p{Co}\p{Cn}\u{E0100}-\u{E01EF}]/u;
|
|
31
|
+
const MINUTES = (ms) => Math.round(ms / 60_000);
|
|
32
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
33
|
+
/** `dir` is `root` or inside it, after symbolic links are followed on both. */
|
|
34
|
+
export async function insideRealpath(root, dir) {
|
|
35
|
+
try {
|
|
36
|
+
const [r, d] = await Promise.all([realpath(root), realpath(dir)]);
|
|
37
|
+
const rel = relative(r, d);
|
|
38
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function createRelief(options) {
|
|
45
|
+
const { hub, now, log } = options;
|
|
46
|
+
const pending = new Map();
|
|
47
|
+
/** When each request of the window was made, oldest first. */
|
|
48
|
+
let made = [];
|
|
49
|
+
let seq = 0;
|
|
50
|
+
const view = () => ({ requests: [...pending.values()].map(({ request }) => ({ ...request, cleanRoom: request.cleanRoom === null ? null : { ...request.cleanRoom } })) });
|
|
51
|
+
const changed = () => options.emit({ t: 'relief', relief: view() });
|
|
52
|
+
const notify = (text, ref) => options.notify?.('relief', text, ref);
|
|
53
|
+
/** The boss hears the answer as a message from the Director's side, as it hears a T-minus result. */
|
|
54
|
+
const tell = (boss, subject, body) => {
|
|
55
|
+
try {
|
|
56
|
+
hub.sendFromUser({ to: boss, subject, body });
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
log.debug(`could not tell ${boss} about a hire request`, error);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const drop = (id) => {
|
|
63
|
+
const found = pending.get(id);
|
|
64
|
+
if (!found)
|
|
65
|
+
return null;
|
|
66
|
+
pending.delete(id);
|
|
67
|
+
options.clearTimer(found.timer);
|
|
68
|
+
return found.request;
|
|
69
|
+
};
|
|
70
|
+
/** Expires every request whose time is up; run before each request and each answer, and by the timers. */
|
|
71
|
+
const sweep = () => {
|
|
72
|
+
for (const [id, { request }] of [...pending]) {
|
|
73
|
+
if (request.expiresAt > now())
|
|
74
|
+
continue;
|
|
75
|
+
drop(id);
|
|
76
|
+
notify(`request to hire ${request.name} expired unanswered`);
|
|
77
|
+
tell(request.by, `Relief: request for ${request.name} expired`, `The Director did not answer within ${MINUTES(RELIEF_TTL_MS)} minutes, so the request to hire ${request.name} is gone. Ask again only if it is still needed.`);
|
|
78
|
+
changed();
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
/** The limits that do not need the disk. Run before the folder is checked and again right before the request is stored (two calls may overlap). */
|
|
82
|
+
const limits = (name) => {
|
|
83
|
+
sweep();
|
|
84
|
+
const cutoff = now() - RELIEF_RATE_WINDOW_MS;
|
|
85
|
+
made = made.filter((at) => at > cutoff);
|
|
86
|
+
if (made.length >= RELIEF_RATE_MAX) {
|
|
87
|
+
throw new HubError('rate_limited', `at most ${RELIEF_RATE_MAX} hire requests in ${MINUTES(RELIEF_RATE_WINDOW_MS)} minutes: wait, or tell the Director what you need`);
|
|
88
|
+
}
|
|
89
|
+
if (pending.size >= RELIEF_PENDING_MAX) {
|
|
90
|
+
throw new HubError('conflict', `${RELIEF_PENDING_MAX} hire requests already wait for the Director: wait for his answer`);
|
|
91
|
+
}
|
|
92
|
+
if (hub.views().some((agent) => agent.name === name) || [...pending.values()].some(({ request }) => request.name === name)) {
|
|
93
|
+
throw new HubError('conflict', `an agent or a request named "${name}" exists already: choose another name`, 'name');
|
|
94
|
+
}
|
|
95
|
+
if (hub.views().length >= MAX_AGENTS)
|
|
96
|
+
throw new HubError('conflict', `the operations room is full (${MAX_AGENTS} agents)`);
|
|
97
|
+
};
|
|
98
|
+
/** The request as the hire form would send it. No confirmBypass, no command, no payload: the tool cannot ask for them. */
|
|
99
|
+
const hireOf = (r) => {
|
|
100
|
+
const hire = { name: r.name, role: r.role, dir: r.dir, mode: r.mode, provider: r.provider };
|
|
101
|
+
if (r.position !== null)
|
|
102
|
+
hire.position = r.position;
|
|
103
|
+
if (r.cleanRoom !== null)
|
|
104
|
+
hire.cleanRoom = r.cleanRoom;
|
|
105
|
+
return hire;
|
|
106
|
+
};
|
|
107
|
+
/** Is the boss that asked still the boss, and is `dir` in its box when it is a Clean Room agent? */
|
|
108
|
+
const confine = async (requester, dir) => {
|
|
109
|
+
if (requester.cleanRoom !== null && !(await insideRealpath(requester.dir, dir))) {
|
|
110
|
+
throw new HubError('forbidden', 'a Clean Room agent can hire only inside its own project folder: leave dir out to use it', 'dir');
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
return {
|
|
114
|
+
async request(by, input) {
|
|
115
|
+
// identity first: the token names the agent, the generation says it is this run of it
|
|
116
|
+
const requester = hub.views().find((agent) => agent.name === by.agent);
|
|
117
|
+
if (!requester)
|
|
118
|
+
throw new HubError('not_found', 'unknown agent');
|
|
119
|
+
if (requester.generation !== by.generation || requester.transition !== null)
|
|
120
|
+
throw new HubError('conflict', 'this session has ended');
|
|
121
|
+
if (!requester.boss)
|
|
122
|
+
throw new HubError('forbidden', 'only the boss can ask for a hire');
|
|
123
|
+
if (!isRecord(input))
|
|
124
|
+
throw bad('the request must be an object');
|
|
125
|
+
for (const key of Object.keys(input))
|
|
126
|
+
if (!FIELDS.has(key))
|
|
127
|
+
throw bad(`unknown field "${key}": a request has name, position, role, dir, engine and mode`, key);
|
|
128
|
+
const { name } = input;
|
|
129
|
+
if (typeof name !== 'string' || !NAME_RE.test(name))
|
|
130
|
+
throw bad('name must be 1 to 32 lowercase letters, digits or hyphens, and start with a letter or digit', 'name');
|
|
131
|
+
if (RESERVED_NAMES.includes(name))
|
|
132
|
+
throw bad(`"${name}" is a reserved name`, 'name');
|
|
133
|
+
const engine = input.engine === undefined ? 'claude' : input.engine;
|
|
134
|
+
if (typeof engine !== 'string' || !PROVIDERS.includes(engine))
|
|
135
|
+
throw bad(`engine must be one of ${PROVIDERS.filter((p) => p !== 'custom').join(', ')}`, 'engine');
|
|
136
|
+
if (engine === 'custom')
|
|
137
|
+
throw bad('a custom command cannot be asked for: only the Director can hire one', 'engine');
|
|
138
|
+
const provider = engine;
|
|
139
|
+
const asked = input.mode === undefined ? 'default' : input.mode;
|
|
140
|
+
if (typeof asked !== 'string' || !PERMISSION_MODES.includes(asked))
|
|
141
|
+
throw bad(`mode must be one of ${RELIEF_MODES.join(', ')}`, 'mode');
|
|
142
|
+
if (!RELIEF_MODES.includes(asked))
|
|
143
|
+
throw bad(`a request can ask for ${RELIEF_MODES.join(' or ')} at most, not ${asked}: only the Director can give more`, 'mode');
|
|
144
|
+
// an engine without permission modes is started in default whatever is asked, and the Director is shown what will happen
|
|
145
|
+
const mode = providerInfo(provider).modes ? asked : 'default';
|
|
146
|
+
const { position, role } = input;
|
|
147
|
+
if (position !== undefined && (typeof position !== 'string' || !POSITION_IDS.includes(position)))
|
|
148
|
+
throw bad(`position must be one of ${POSITION_IDS.join(', ')}`, 'position');
|
|
149
|
+
if (role !== undefined && (typeof role !== 'string' || role.trim().length === 0 || role.trim().length > ROLE_MAX_CHARS))
|
|
150
|
+
throw bad(`role must be 1 to ${ROLE_MAX_CHARS} characters`, 'role');
|
|
151
|
+
// the Director approves the text he reads: nothing in it may be hidden from him
|
|
152
|
+
if (typeof role === 'string' && HIDDEN_RE.test(role))
|
|
153
|
+
throw bad('role must not hold control, invisible or direction-changing characters: the Director reads all of it', 'role');
|
|
154
|
+
const roleText = typeof role === 'string' ? role.trim() : typeof position === 'string' ? (positionById(position)?.role ?? '') : '';
|
|
155
|
+
if (roleText === '')
|
|
156
|
+
throw bad('give a position or a role', 'role');
|
|
157
|
+
const cleanRoom = requester.cleanRoom === null ? null : { ...requester.cleanRoom };
|
|
158
|
+
if (cleanRoom !== null && provider !== 'claude')
|
|
159
|
+
throw bad('a Clean Room agent hires Clean Room agents, and those run Claude Code only', 'engine');
|
|
160
|
+
const asDir = input.dir === undefined ? (cleanRoom === null ? undefined : requester.dir) : input.dir;
|
|
161
|
+
if (typeof asDir !== 'string' || asDir.length === 0 || asDir.length > DIR_MAX_CHARS)
|
|
162
|
+
throw bad(`dir must be an absolute path of 1 to ${DIR_MAX_CHARS} characters`, 'dir');
|
|
163
|
+
limits(name);
|
|
164
|
+
const checked = await options.checkDirectory(asDir);
|
|
165
|
+
if (!checked.ok)
|
|
166
|
+
throw bad(checked.error, 'dir');
|
|
167
|
+
await confine(requester, checked.path);
|
|
168
|
+
// the checks above waited on the disk: another request may have taken the name or the last place meanwhile
|
|
169
|
+
limits(name);
|
|
170
|
+
seq += 1;
|
|
171
|
+
const at = now();
|
|
172
|
+
made.push(at);
|
|
173
|
+
const id = `h${seq}`;
|
|
174
|
+
const request = { id, by: requester.name, at, expiresAt: at + RELIEF_TTL_MS, name, position: typeof position === 'string' ? position : null, role: roleText, dir: checked.path, provider, mode, cleanRoom };
|
|
175
|
+
pending.set(id, { request, timer: options.setTimer(sweep, RELIEF_TTL_MS + 1) });
|
|
176
|
+
changed();
|
|
177
|
+
notify(`${requester.name} asks to hire ${name}${request.position === null ? '' : ` as ${request.position.toUpperCase()}`}: ${provider}, ${mode}, ${checked.path}`, { kind: 'relief', id });
|
|
178
|
+
return { id, status: 'pending', note: `waiting for the Director; you get a message with his answer, and the request expires after ${MINUTES(RELIEF_TTL_MS)} minutes` };
|
|
179
|
+
},
|
|
180
|
+
view,
|
|
181
|
+
async decide(idInput, verdict, by) {
|
|
182
|
+
if (!by || by.kind !== 'user')
|
|
183
|
+
throw new HubError('forbidden', 'only the Director answers a hire request');
|
|
184
|
+
if (verdict !== 'go' && verdict !== 'no-go')
|
|
185
|
+
throw bad('the answer is go or no-go');
|
|
186
|
+
sweep();
|
|
187
|
+
const id = typeof idInput === 'string' && ID_RE.test(idInput) ? idInput : '';
|
|
188
|
+
// taken out of the list before anything waits, so a second answer to the same request finds nothing
|
|
189
|
+
const request = drop(id);
|
|
190
|
+
if (request === null)
|
|
191
|
+
throw new HubError('not_found', 'no such hire request: it may have expired or been answered');
|
|
192
|
+
changed();
|
|
193
|
+
if (verdict === 'no-go') {
|
|
194
|
+
notify(`hire of ${request.name} refused`);
|
|
195
|
+
tell(request.by, `Relief: request for ${request.name} refused`, `The Director said no-go to hiring ${request.name}. Do not ask again unless he asks you to.`);
|
|
196
|
+
return view();
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
const requester = hub.views().find((agent) => agent.name === request.by);
|
|
200
|
+
// the boss may have been edited since it asked: a Clean Room boss hires only Clean Room agents, inside its box
|
|
201
|
+
if (requester) {
|
|
202
|
+
if (requester.cleanRoom !== null && request.cleanRoom === null)
|
|
203
|
+
throw new HubError('forbidden', 'the boss runs in a Clean Room now: the agent it asked for would not, so ask again');
|
|
204
|
+
await confine(requester, request.dir);
|
|
205
|
+
}
|
|
206
|
+
const hired = await hub.hire(hireOf(request));
|
|
207
|
+
notify(`${hired.name} hired (asked by ${request.by})`);
|
|
208
|
+
tell(request.by, `Relief: ${hired.name} is staffed`, `The Director said go. ${hired.name} is hired in ${hired.dir} and starting. Brief it with send_message.`);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
const reason = error instanceof HubError ? error.message : 'an internal error';
|
|
212
|
+
if (!(error instanceof HubError))
|
|
213
|
+
log.error('hire after a go failed', error);
|
|
214
|
+
notify(`${request.name} could not be hired: ${reason}`);
|
|
215
|
+
tell(request.by, `Relief: ${request.name} could not be hired`, `The Director said go, but the hire failed: ${reason}.`);
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
return view();
|
|
219
|
+
},
|
|
220
|
+
close() {
|
|
221
|
+
for (const { timer } of pending.values())
|
|
222
|
+
options.clearTimer(timer);
|
|
223
|
+
pending.clear();
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** The one reader of the setting: the hub for hire and edit, home.ts for the roster file. `{}` is the only value. It needs Claude Code, and not a Clean Room (its token cannot open a session in the app). */
|
|
2
|
+
export function parseRemoteControl(value, provider, cleanRoom) {
|
|
3
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
4
|
+
return { ok: false, error: 'remoteControl must be an object' };
|
|
5
|
+
const unknown = Object.keys(value).find((key) => value[key] !== undefined);
|
|
6
|
+
if (unknown !== undefined)
|
|
7
|
+
return { ok: false, error: `remoteControl has no field "${unknown}"` };
|
|
8
|
+
if ((provider ?? 'claude') !== 'claude')
|
|
9
|
+
return { ok: false, error: 'Remote Control is for Claude Code agents only' };
|
|
10
|
+
if (cleanRoom)
|
|
11
|
+
return { ok: false, error: 'a Clean Room agent cannot use Remote Control: it has no claude.ai login' };
|
|
12
|
+
return { ok: true, remoteControl: {} };
|
|
13
|
+
}
|
|
14
|
+
/** The session name the app shows. */
|
|
15
|
+
export const remoteControlName = (agent) => `gonogo-${agent}`;
|