@ulm0/gonogo 0.1.1 → 0.1.2

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.
@@ -157,7 +157,10 @@ export const ALLOWED_TOOLS = [
157
157
  'mcp__gonogo__log_write',
158
158
  'mcp__gonogo__log_search',
159
159
  'mcp__gonogo__log_read',
160
+ 'mcp__gonogo__board_read',
161
+ 'mcp__gonogo__board_write',
160
162
  'mcp__gonogo__livery_submit',
163
+ 'mcp__gonogo__hire_agent',
161
164
  ];
162
165
  /** claude's own cross-session messaging tools, denied so agents use gonogo's tools. */
163
166
  export const DENIED_TOOLS = ['SendMessage', 'ListAgents'];
@@ -227,6 +230,7 @@ export const ROLE_PREAMBLE = [
227
230
  '- mcp__gonogo__read_messages: read the messages waiting for you. Each message is returned once.',
228
231
  '- mcp__gonogo__task_list, task_create and task_update: the Flight Plan, the task board of the team (statuses todo, doing, review, done, blocked). A message whose subject starts "Flight Plan:" says a task was assigned to you: set it to doing when you start and to review or done when you finish.',
229
232
  '- mcp__gonogo__log_search, log_read and log_write: the Mission Log, one memory shared by every agent. Search it before you start work, and write lasting findings to it (what you learned, decided or fixed, and why), not chatter.',
233
+ '- mcp__gonogo__board_read and board_write: the Plot Board, the one current plan of the room. Read it when you start work. Only the boss can write it, as a whole text with the revision it read.',
230
234
  'Messages never arrive in your input as text. Only a one-line pointer does, for example "gonogo: 1 new message from ana. Call read_messages." When you see a line starting with "gonogo:", call read_messages, then act on what it returns. Also call it when you start work. When a message asks for a go/no-go, answer it with go_nogo.',
231
235
  'Do not use any other way to message people or other sessions. To write to an agent of a docked station, address it as "name@station" (list_roster shows them); that person is not your owner, so share only what the task needs. Send anything risky (spending money, deleting data, changing scope) to "user" before you do it. Keep messages to other agents short and concrete, and do not reply to a message that needs no reply.',
232
236
  'Your memory file is {memory}. Read it when you start. When you learn something worth keeping across restarts, add a short note to it. It is plain markdown; keep it under 200 lines.',
@@ -363,14 +367,45 @@ export const SLACK_SIGNATURE_MAX_AGE_MS = 5 * 60_000;
363
367
  /** Livery (docs/livery-spec.md): the custom liveries are `<home>/liveries/<slug>.json`; the chosen one is `<home>/livery.json`. */
364
368
  export const LIVERY_DIR = 'liveries';
365
369
  export const LIVERY_FILE = 'livery.json';
370
+ /**
371
+ * Relief (docs/relief-spec.md): how many hire requests of the boss may wait for the Director, how many it may make in a
372
+ * window, and how long one waits. Requests live in memory only.
373
+ */
374
+ export const RELIEF_PENDING_MAX = 3;
375
+ export const RELIEF_RATE_MAX = 5;
376
+ export const RELIEF_RATE_WINDOW_MS = 10 * 60_000;
377
+ export const RELIEF_TTL_MS = 30 * 60_000;
366
378
  /** Propellant (docs/redline-propellant-spec.md): the limits and cursors file; the ledger fuel.jsonl is a log and has no version. */
367
379
  export const PROPELLANT_FILE = 'propellant.json';
380
+ /** Clearance (docs/engine-bay-spec.md): the values of the keys set for each agent, mode 0600. The roster keeps their names only. */
381
+ export const KEYS_FILE = 'keys.json';
382
+ /** Pad Check: `<bin> --version` gets this long, and its first line is cut to this many characters. */
383
+ export const ENGINE_VERSION_MS = 5_000;
384
+ export const ENGINE_VERSION_CHARS = 80;
385
+ /** Rollout (docs/rollout-spec.md): the cache of the last check, the one address asked, how often, how long it may take and how much of the answer is read. */
386
+ export const ROLLOUT_FILE = 'rollout.json';
387
+ export const ROLLOUT_URL = 'https://registry.npmjs.org/@ulm0%2Fgonogo/latest';
388
+ export const ROLLOUT_EVERY_MS = 24 * 60 * 60 * 1000;
389
+ export const ROLLOUT_TIMEOUT_MS = 5_000;
390
+ export const ROLLOUT_MAX_BYTES = 256 * 1024;
391
+ /** Rollout is off for a value in this list (GONOGO_UPDATE_CHECK). */
392
+ export const ROLLOUT_OFF_WORDS = ['0', 'off', 'false', 'no'];
368
393
  /** Mission Log (docs/mission-log-spec.md): the folder under the home, and how long a snippet of a search result is and how much of the text before the match it shows. */
369
394
  export const LOG_DIR = 'mission-log';
370
395
  export const LOG_SNIPPET_CHARS = 200;
371
396
  export const LOG_SNIPPET_LEAD_CHARS = 40;
397
+ /** Plot Board (docs/plot-board-spec.md): the plan lives in `<home>/board.md`. */
398
+ export const BOARD_FILE = 'board.md';
399
+ /** Black Box (docs/black-box-spec.md): the git repository under the home, how long events wait for a commit, and the limits. */
400
+ export const BLACKBOX_DIR = 'black-box';
401
+ export const BLACKBOX_COMMIT_MS = 30_000;
402
+ export const BLACKBOX_GIT_TIMEOUT_MS = 10_000;
403
+ export const BLACKBOX_RATE_MAX = 600;
404
+ export const BLACKBOX_RATE_WINDOW_MS = 60_000;
405
+ export const BLACKBOX_RECENT_MAX = 200;
406
+ export const BLACKBOX_TAIL_BYTES = 65_536;
372
407
  export const MCP_DESCRIPTIONS = {
373
- go_nogo: 'Answer a T-minus poll from the Director: vote "go" when you are ready to proceed, or "no-go" with a one-sentence reason. Call it when a message asks for a go/no-go. The result says whether the vote counted.',
408
+ go_nogo: 'Answer a T-minus poll or a Static fire from the Director: vote "go" when you are ready to proceed, or "no-go" with a one-sentence reason. Call it when a message asks for a go/no-go. The result says whether the vote counted.',
374
409
  send_message: 'Send a message to another agent (by name), to the boss ("boss") or to the human owner ("user"). An agent of a docked station is addressed as "name@station". The recipient gets a one-line pointer and reads the text with read_messages. The result tells you at once whether the message was queued or could not be delivered.',
375
410
  list_roster: 'List every agent in the operations room with its name, role and current state, and say which one is the boss. Agents of docked stations are listed too, under docked.',
376
411
  read_messages: 'Return the messages waiting for you (each message is returned once) and mark them read. Call it when a line starting with "gonogo:" says messages are waiting.',
@@ -380,7 +415,10 @@ export const MCP_DESCRIPTIONS = {
380
415
  log_write: 'Write to the Mission Log, the memory shared by every agent: a title, a body in plain markdown and optional tags. Give an id to change an entry you wrote earlier (any of title, body, tags). Keep an entry to one finding.',
381
416
  log_search: 'Search the Mission Log. Returns up to limit entries (at most 20), best first, each with its id, title, author, tags and a snippet around the best match. Read the whole entry with log_read.',
382
417
  log_read: 'Read one entry of the Mission Log by its id: the title, tags, author, times and the whole body.',
418
+ board_read: 'Read the Plot Board, the one current plan of the room: its text, its revision, who wrote it last and when, and whether you may write it. Read it when you start work.',
419
+ board_write: 'Write the Plot Board, the one current plan of the room. Only the boss may. Give the whole new text (plain markdown, at most 10000 characters; it replaces the old) and the revision you read with board_read: if the Director or another write changed the board since, the write is refused and says the current revision.',
383
420
  livery_submit: 'Submit a livery, a colour theme for gonogo, when the Director asked you to design one: a name, a one-line description and tokens, an object that holds every token the message named, each a CSS colour (#rgb, #rrggbb, rgb(), hsl() or oklch()). It is checked for colours and for contrast; if it is refused, the answer says what to fix. The Director chooses whether to apply it.',
421
+ hire_agent: 'Boss only. Ask the Director to hire an agent: name (lowercase letters, digits and hyphens), position (a call sign such as guido or surgeon, which gives the role text) and/or role (the role text itself), dir (an absolute folder; a Clean Room boss leaves it out), engine (default claude) and mode (default or acceptEdits; nothing higher is possible). It only makes a request: the Director sees every field and decides, and you are told his answer by message. At most 3 requests wait at once, 5 per 10 minutes, and one expires after 30 minutes.',
384
422
  };
385
423
  /* ---- the tiny logger ---- */
386
424
  const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
@@ -0,0 +1,311 @@
1
+ /**
2
+ * Hangar (docs/hangar-spec.md): the files of one agent's folder, or of its Clean Room worktree, for the Director's browser.
3
+ * List a folder, read a text file, save one the Director opened (refused when it changed on disk since), make a new one. No
4
+ * delete, no rename. Every path is a relative one that is resolved with realpath and kept inside the root; `.git` and gonogo's
5
+ * own folder are never reachable. The agent runs as the same user, so this guards the browser's requests, not the agent.
6
+ * shortcut: a folder swapped for a link between the realpath and the open escapes the check (only the last name is opened with
7
+ * O_NOFOLLOW); whoever can swap it can write the file itself. Close it with openat if the agent is ever not the owner's user.
8
+ */
9
+ import { createHash, randomBytes } from 'node:crypto';
10
+ import { constants as fs } from 'node:fs';
11
+ import { access, lstat, open, opendir, realpath, rename, unlink } from 'node:fs/promises';
12
+ import { isAbsolute, join, relative, sep } from 'node:path';
13
+ import { CLEAN_ROOM_DIR, HANGAR_FILE_MAX_BYTES } from '../shared/protocol.js';
14
+ import { HubError } from './hub.js';
15
+ /** A save body: the text, in the worst case a `\u0000` escape for each byte, plus the path and the etag. */
16
+ export const HANGAR_BODY_MAX_BYTES = 6 * HANGAR_FILE_MAX_BYTES + 8192;
17
+ /** A folder shows this many entries and says there are more. */
18
+ export const HANGAR_LIST_MAX = 2000;
19
+ const PATH_MAX_CHARS = 1024;
20
+ const ETAG_MAX_CHARS = 64;
21
+ /** git's own test for a binary file: a NUL in the first 8000 bytes. */
22
+ const SNIFF_BYTES = 8000;
23
+ const bad = (message, field) => new HubError('bad_request', message, field);
24
+ const forbidden = (message) => new HubError('forbidden', message, 'path');
25
+ /** `child` is `parent` or below it. */
26
+ export function inside(parent, child) {
27
+ const r = relative(parent, child);
28
+ return r === '' || (r !== '..' && !r.startsWith(`..${sep}`) && !isAbsolute(r));
29
+ }
30
+ /** A name that a file system may take for `.git`: other case, a zero-width or ignorable character in it (HFS+ ignores those). */
31
+ export function isGitName(segment) {
32
+ return segment.normalize('NFKC').replace(/[­​-‏‪-‮⁠-]/g, '').toLowerCase() === '.git';
33
+ }
34
+ /** The segments of a relative path from the browser. Anything that could leave the root, or reach `.git`, is refused here. */
35
+ export function pathParts(raw, field = 'path') {
36
+ if (typeof raw !== 'string')
37
+ throw bad(`${field} must be a string`, field);
38
+ if (raw.length > PATH_MAX_CHARS)
39
+ throw bad(`${field} is longer than ${PATH_MAX_CHARS} characters`, field);
40
+ if (raw.includes('\0'))
41
+ throw bad(`${field} has a NUL character`, field);
42
+ if (raw.startsWith('/'))
43
+ throw forbidden('the path must be relative to the agent\'s folder');
44
+ const parts = raw.split('/').filter((p) => p !== '' && p !== '.');
45
+ if (parts.includes('..'))
46
+ throw forbidden('a path cannot go up with ..');
47
+ if (parts.some(isGitName))
48
+ throw forbidden('.git is not reachable');
49
+ return parts;
50
+ }
51
+ /** Turns what a file system call said into an answer; anything else is the server's own fault and goes up as it is. */
52
+ function fsError(e) {
53
+ const code = e?.code;
54
+ if (code === 'ENOENT')
55
+ return new HubError('not_found', 'no such file or folder', 'path');
56
+ if (code === 'ENOTDIR')
57
+ return bad('a part of the path is not a folder', 'path');
58
+ if (code === 'EISDIR')
59
+ return bad('that is a folder', 'path');
60
+ if (code === 'EEXIST')
61
+ return new HubError('conflict', 'a file with that name exists', 'path');
62
+ if (code === 'EACCES' || code === 'EPERM')
63
+ return forbidden('permission denied');
64
+ if (code === 'ELOOP')
65
+ return forbidden('a symbolic link is not followed there');
66
+ if (code === 'ENAMETOOLONG')
67
+ return bad('a name in the path is too long', 'path');
68
+ return e;
69
+ }
70
+ const etagOf = (bytes) => createHash('sha256').update(bytes).digest('hex').slice(0, 32);
71
+ /** At most `max` bytes from the start; a file that grows while it is read cannot make this large. */
72
+ async function readUpTo(handle, max) {
73
+ const buffer = Buffer.alloc(max);
74
+ let size = 0;
75
+ while (size < max) {
76
+ const { bytesRead } = await handle.read(buffer, size, max - size, size);
77
+ if (bytesRead === 0)
78
+ break;
79
+ size += bytesRead;
80
+ }
81
+ return buffer.subarray(0, size);
82
+ }
83
+ async function writeAll(handle, bytes) {
84
+ let at = 0;
85
+ while (at < bytes.length)
86
+ at += (await handle.write(bytes, at, bytes.length - at, at)).bytesWritten;
87
+ }
88
+ /** Text the editor may hold: valid UTF-8 without a NUL. A byte order mark stays in the text, so a save writes it back. */
89
+ function decode(bytes) {
90
+ if (bytes.subarray(0, SNIFF_BYTES).includes(0))
91
+ throw new HubError('unsupported', 'a binary file: the editor opens text only', 'path');
92
+ try {
93
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
94
+ }
95
+ catch {
96
+ throw new HubError('unsupported', 'not valid UTF-8: the editor opens text only', 'path');
97
+ }
98
+ }
99
+ function textOf(input, required) {
100
+ const { text } = input;
101
+ if (text === undefined && !required)
102
+ return Buffer.alloc(0);
103
+ if (typeof text !== 'string')
104
+ throw bad('text must be a string', 'text');
105
+ if (text.includes('\0'))
106
+ throw bad('text has a NUL character: the editor holds text only', 'text');
107
+ const bytes = Buffer.from(text, 'utf8');
108
+ if (bytes.length > HANGAR_FILE_MAX_BYTES)
109
+ throw new HubError('too_large', `the file would be ${bytes.length} bytes; the limit is ${HANGAR_FILE_MAX_BYTES}`, 'text');
110
+ return bytes;
111
+ }
112
+ const isInput = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
113
+ /** Where an agent's files are: its Clean Room's worktree, else its folder. The home folder is resolved too, to keep gonogo's own state out of reach. */
114
+ export function createRoots(deps) {
115
+ return async (name) => {
116
+ const place = deps.agent(name);
117
+ if (place === null)
118
+ throw new HubError('not_found', 'unknown agent');
119
+ const wanted = place.cleanRoom ? join(deps.home, CLEAN_ROOM_DIR, name) : place.dir;
120
+ try {
121
+ return { root: await realpath(wanted), home: await realpath(deps.home) };
122
+ }
123
+ catch (e) {
124
+ if (e.code === 'ENOENT') {
125
+ throw new HubError('not_found', place.cleanRoom ? 'the Clean Room has no worktree yet: start the agent once' : 'the agent\'s folder is gone');
126
+ }
127
+ throw e;
128
+ }
129
+ };
130
+ }
131
+ export function createHangar(roots) {
132
+ /** Saves of one file run one after the other: two browsers saving with the same etag at once would both pass the check, and the first text would be lost. */
133
+ const saving = new Map();
134
+ async function serial(key, work) {
135
+ const run = (saving.get(key) ?? Promise.resolve()).then(work);
136
+ const tail = run.then(() => undefined, () => undefined);
137
+ saving.set(key, tail);
138
+ try {
139
+ return await run;
140
+ }
141
+ finally {
142
+ if (saving.get(key) === tail)
143
+ saving.delete(key);
144
+ }
145
+ }
146
+ /** gonogo's home is out of reach, except the Clean Room worktrees below it (an agent's own files). */
147
+ const ownState = (at, real) => inside(at.home, real) && !inside(join(at.home, CLEAN_ROOM_DIR), real);
148
+ const guard = (at, real) => {
149
+ if (!inside(at.root, real))
150
+ throw forbidden('that path leads outside the agent\'s folder');
151
+ if (relative(at.root, real).split(sep).some(isGitName))
152
+ throw forbidden('.git is not reachable');
153
+ if (ownState(at, real))
154
+ throw forbidden('that is gonogo\'s own folder');
155
+ };
156
+ async function resolveIn(at, parts) {
157
+ let real;
158
+ try {
159
+ real = await realpath(join(at.root, ...parts));
160
+ }
161
+ catch (e) {
162
+ throw fsError(e);
163
+ }
164
+ guard(at, real);
165
+ return real;
166
+ }
167
+ /** Opens without following a link in the last name and without waiting on a pipe; what is opened must be a regular file. */
168
+ async function openFile(real, flags) {
169
+ let handle;
170
+ try {
171
+ handle = await open(real, flags | fs.O_NOFOLLOW | fs.O_NONBLOCK);
172
+ }
173
+ catch (e) {
174
+ throw fsError(e);
175
+ }
176
+ try {
177
+ const info = await handle.stat();
178
+ if (!info.isFile())
179
+ throw new HubError('unsupported', 'not a regular file', 'path');
180
+ return { handle, info };
181
+ }
182
+ catch (e) {
183
+ await handle.close();
184
+ throw e;
185
+ }
186
+ }
187
+ /** The file `real` takes `bytes` when it still has the etag `etag`: written whole beside it, then renamed over it. */
188
+ async function replace(real, leaf, bytes, etag) {
189
+ const { handle, info } = await openFile(real, fs.O_RDONLY);
190
+ let temp = null;
191
+ try {
192
+ // the file is replaced by a new one, which a read-only file must not allow
193
+ await access(real, fs.W_OK).catch((e) => {
194
+ throw fsError(e);
195
+ });
196
+ const now = info.size > HANGAR_FILE_MAX_BYTES ? null : await readUpTo(handle, HANGAR_FILE_MAX_BYTES + 1);
197
+ if (now === null || etagOf(now) !== etag)
198
+ throw new HubError('conflict', 'the file changed on disk since you opened it: nothing was saved', 'etag');
199
+ // Written whole beside the file and renamed over it, so that a full disk or a crash leaves the old file.
200
+ temp = join(real, '..', `.${leaf}.gonogo-${randomBytes(4).toString('hex')}.tmp`);
201
+ const out = await open(temp, 'wx', 0o600).catch((e) => {
202
+ temp = null;
203
+ throw fsError(e);
204
+ });
205
+ try {
206
+ await writeAll(out, bytes);
207
+ await out.chmod(info.mode & 0o7777);
208
+ }
209
+ finally {
210
+ await out.close();
211
+ }
212
+ // shortcut: a write by another process between this check and the rename is lost; take a lock file when two writers matter
213
+ const after = await lstat(real);
214
+ if (after.mtimeMs !== info.mtimeMs || after.size !== info.size)
215
+ throw new HubError('conflict', 'the file changed on disk while it was saved: nothing was saved', 'etag');
216
+ await rename(temp, real);
217
+ temp = null;
218
+ }
219
+ finally {
220
+ await handle.close();
221
+ if (temp !== null)
222
+ await unlink(temp).catch(() => undefined);
223
+ }
224
+ }
225
+ const filePath = (raw) => {
226
+ const parts = pathParts(raw);
227
+ if (parts.length === 0)
228
+ throw bad('path must name a file', 'path');
229
+ return parts;
230
+ };
231
+ return {
232
+ async list(name, raw) {
233
+ const parts = pathParts(raw ?? '');
234
+ const at = await roots(name);
235
+ const dir = await resolveIn(at, parts);
236
+ const entries = [];
237
+ let truncated = false;
238
+ try {
239
+ // shortcut: past the limit the entries are the first the disk gave, not the first by name; sort a whole folder when one needs it
240
+ for await (const item of await opendir(dir)) {
241
+ if (isGitName(item.name) || ownState(at, join(dir, item.name)))
242
+ continue;
243
+ if (entries.length >= HANGAR_LIST_MAX) {
244
+ truncated = true;
245
+ break;
246
+ }
247
+ const kind = item.isDirectory() ? 'dir' : item.isSymbolicLink() ? 'link' : item.isFile() ? 'file' : null;
248
+ if (kind !== null)
249
+ entries.push({ name: item.name, kind, size: kind === 'file' ? (await lstat(join(dir, item.name)).catch(() => null))?.size ?? 0 : 0 });
250
+ }
251
+ }
252
+ catch (e) {
253
+ throw fsError(e);
254
+ }
255
+ entries.sort((a, b) => (a.kind === 'dir' ? 0 : 1) - (b.kind === 'dir' ? 0 : 1) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
256
+ return { path: parts.join('/'), entries, truncated };
257
+ },
258
+ async read(name, raw) {
259
+ const parts = filePath(raw);
260
+ const real = await resolveIn(await roots(name), parts);
261
+ const { handle, info } = await openFile(real, fs.O_RDONLY);
262
+ try {
263
+ if (info.size > HANGAR_FILE_MAX_BYTES)
264
+ throw new HubError('too_large', `the file has ${info.size} bytes; the editor opens at most ${HANGAR_FILE_MAX_BYTES}`, 'path');
265
+ const bytes = await readUpTo(handle, HANGAR_FILE_MAX_BYTES + 1);
266
+ if (bytes.length > HANGAR_FILE_MAX_BYTES)
267
+ throw new HubError('too_large', `the file is larger than ${HANGAR_FILE_MAX_BYTES} bytes`, 'path');
268
+ return { path: parts.join('/'), text: decode(bytes), size: bytes.length, etag: etagOf(bytes) };
269
+ }
270
+ finally {
271
+ await handle.close();
272
+ }
273
+ },
274
+ async save(name, input) {
275
+ if (!isInput(input))
276
+ throw bad('the body must be an object');
277
+ const parts = filePath(input.path);
278
+ const { etag } = input;
279
+ if (typeof etag !== 'string' || etag === '' || etag.length > ETAG_MAX_CHARS)
280
+ throw bad('etag must be the one the file was read with', 'etag');
281
+ const bytes = textOf(input, true);
282
+ const real = await resolveIn(await roots(name), parts);
283
+ await serial(real, () => replace(real, parts[parts.length - 1] ?? 'file', bytes, etag));
284
+ return { path: parts.join('/'), size: bytes.length, etag: etagOf(bytes) };
285
+ },
286
+ async create(name, input) {
287
+ if (!isInput(input))
288
+ throw bad('the body must be an object');
289
+ const parts = filePath(input.path);
290
+ const bytes = textOf(input, false);
291
+ const at = await roots(name);
292
+ const folder = await resolveIn(at, parts.slice(0, -1));
293
+ const leaf = parts[parts.length - 1] ?? '';
294
+ let handle;
295
+ try {
296
+ // O_EXCL: the name must be new, and a link by that name is never followed.
297
+ handle = await open(join(folder, leaf), 'wx', 0o644);
298
+ }
299
+ catch (e) {
300
+ throw fsError(e);
301
+ }
302
+ try {
303
+ await writeAll(handle, bytes);
304
+ }
305
+ finally {
306
+ await handle.close();
307
+ }
308
+ return { path: parts.join('/'), size: bytes.length, etag: etagOf(bytes) };
309
+ },
310
+ };
311
+ }
@@ -3,12 +3,14 @@ import { chmodSync, closeSync, fstatSync, mkdirSync, openSync, readFileSync, rea
3
3
  import { appendFile, rename, unlink, writeFile } from 'node:fs/promises';
4
4
  import { join, resolve } from 'node:path';
5
5
  import { POSITION_IDS } from '../shared/positions.js';
6
- import { ACTIVITY_STATUSES, PERMISSION_MODES, PROVIDERS, RESERVED_NAMES } from '../shared/protocol.js';
6
+ import { ACTIVITY_STATUSES, KEYS_MAX, MODEL_PATTERN, PERMISSION_MODES, PROVIDERS, providerInfo, RESERVED_NAMES } from '../shared/protocol.js';
7
7
  import { AGENT_NAME_PATTERN, AGENTS_DIR, AGENTS_FILE, BROWSER_TOKEN_FILE, COMMAND_MAX_CHARS, DIR_MODE, FILE_MODE, LOCK_FILE, MESSAGES_FILE, MESSAGES_ROTATE_BYTES, MESSAGES_ROTATED_FILE, MESSAGES_TAIL_BYTES, TOKEN_BYTES, nullLogger, } from './constants.js';
8
8
  import { readCustomCommand } from './command.js';
9
9
  import { migrateHome } from './migrate.js';
10
10
  import { parseCleanRoom } from './cleanroom.js';
11
+ import { keyNameProblem } from './clearance.js';
11
12
  import { parsePayload, payloadRefusal } from './payload.js';
13
+ const MODEL_RE = new RegExp(MODEL_PATTERN);
12
14
  const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
13
15
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
16
  const TOKEN_RE = /^[0-9a-f]{64}$/i;
@@ -195,6 +197,27 @@ function parseAgent(a) {
195
197
  return `${name}: ${checked.error}`;
196
198
  record.cleanRoom = checked.cleanRoom;
197
199
  }
200
+ const { model, keys } = a;
201
+ if (model !== undefined) {
202
+ if (typeof model !== 'string' || !MODEL_RE.test(model))
203
+ return `${name}: model is not a usable name`;
204
+ if (providerInfo(record.provider).model === null)
205
+ return `${name}: ${providerInfo(record.provider).label} takes no model setting`;
206
+ record.model = model;
207
+ }
208
+ if (keys !== undefined) {
209
+ if (!isRecord(keys) || Object.keys(keys).length > KEYS_MAX)
210
+ return `${name}: keys must be an object of at most ${KEYS_MAX} names`;
211
+ const names = {};
212
+ // shortcut: a name that a later gonogo reserves makes the roster unusable here (the start stops and names the agent); delete it from `keys` to go on
213
+ for (const [key, at] of Object.entries(keys)) {
214
+ if (keyNameProblem(key) !== null || typeof at !== 'number' || !Number.isFinite(at))
215
+ return `${name}: keys holds a name or a time that is not usable`;
216
+ names[key] = at;
217
+ }
218
+ if (Object.keys(names).length > 0)
219
+ record.keys = names;
220
+ }
198
221
  return record;
199
222
  }
200
223
  function parseRoster(text, path) {