@ulm0/gonogo 0.0.0-stage → 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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-BqCn1SM7.js +50 -0
  20. package/dist/client/assets/index-KZtFVMJG.css +1 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/audited.js +133 -0
  25. package/dist/server/blackbox.js +261 -0
  26. package/dist/server/board.js +123 -0
  27. package/dist/server/cleanroom.js +214 -0
  28. package/dist/server/clearance.js +158 -0
  29. package/dist/server/cli.js +763 -0
  30. package/dist/server/command.js +44 -0
  31. package/dist/server/constants.js +465 -0
  32. package/dist/server/docking.js +541 -0
  33. package/dist/server/downlink.js +191 -0
  34. package/dist/server/hangar.js +311 -0
  35. package/dist/server/home.js +520 -0
  36. package/dist/server/hooks.js +166 -0
  37. package/dist/server/hub.js +2642 -0
  38. package/dist/server/launcher.js +547 -0
  39. package/dist/server/livery.js +210 -0
  40. package/dist/server/logchart.js +58 -0
  41. package/dist/server/logsearch.js +112 -0
  42. package/dist/server/massbudget.js +169 -0
  43. package/dist/server/mcp.js +228 -0
  44. package/dist/server/migrate.js +122 -0
  45. package/dist/server/missionlog.js +211 -0
  46. package/dist/server/payload.js +168 -0
  47. package/dist/server/propellant.js +314 -0
  48. package/dist/server/providers.js +199 -0
  49. package/dist/server/recorder.js +176 -0
  50. package/dist/server/relay.js +300 -0
  51. package/dist/server/relaykinds.js +182 -0
  52. package/dist/server/relief.js +226 -0
  53. package/dist/server/rollout.js +172 -0
  54. package/dist/server/schedules.js +277 -0
  55. package/dist/server/tasks.js +272 -0
  56. package/dist/server/telemetry.js +110 -0
  57. package/dist/server/terminal.js +635 -0
  58. package/dist/server/uplinks.js +356 -0
  59. package/dist/server/web.js +1607 -0
  60. package/dist/shared/cron.js +149 -0
  61. package/dist/shared/fuel.js +18 -0
  62. package/dist/shared/livery.js +348 -0
  63. package/dist/shared/positions.js +132 -0
  64. package/dist/shared/protocol.js +245 -0
  65. package/package.json +84 -3
@@ -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) => options.notify?.('relief', text);
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}`);
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,172 @@
1
+ /**
2
+ * Rollout (docs/rollout-spec.md): tells the Director when a newer @ulm0/gonogo exists.
3
+ *
4
+ * Once a day (not more) a plain GET asks registry.npmjs.org for the `latest` version of the package. The request has an Accept
5
+ * header and nothing else of ours: no version, no id, no cookie, nothing about the user or the machine. The answer is read
6
+ * up to a limit, must hold a stable `x.y.z`, and is cached in rollout.json (mode 0600, with the time of the try). Nothing is
7
+ * ever installed: `updateCommand` only says which command updates the way this gonogo was installed. Off with
8
+ * GONOGO_UPDATE_CHECK=0 or --no-update-check; then nothing is asked and no note shows. The clock and fetch are injected for tests.
9
+ */
10
+ import { randomBytes } from 'node:crypto';
11
+ import { readFileSync } from 'node:fs';
12
+ import { readFile, rename, rm, writeFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { FILE_MODE, nullLogger, ROLLOUT_EVERY_MS, ROLLOUT_FILE, ROLLOUT_MAX_BYTES, ROLLOUT_OFF_WORDS, ROLLOUT_TIMEOUT_MS, ROLLOUT_URL } from './constants.js';
15
+ const STABLE = /^\d{1,6}\.\d{1,6}\.\d{1,6}$/;
16
+ const CHECK_TICK_MS = 60 * 60 * 1000;
17
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
18
+ /** GONOGO_UPDATE_CHECK says no: `0`, `off`, `false` or `no`. */
19
+ export const updateCheckOff = (value) => ROLLOUT_OFF_WORDS.includes((value ?? '').trim().toLowerCase());
20
+ /** `latest` is a stable x.y.z above `current`; a prerelease of the same x.y.z is below it. Anything else is not newer. */
21
+ export function isNewer(latest, current) {
22
+ const next = STABLE.test(latest) ? latest.split('.').map(Number) : null;
23
+ const now = /^(\d+)\.(\d+)\.(\d+)(-|$)/.exec(current);
24
+ if (next === null || now === null)
25
+ return false;
26
+ for (let i = 0; i < 3; i += 1) {
27
+ const have = Number(now[i + 1]);
28
+ if (next[i] !== have)
29
+ return (next[i] ?? 0) > have;
30
+ }
31
+ return now[4] === '-';
32
+ }
33
+ /**
34
+ * The command that updates the way this gonogo was installed, from the path of its own file. `docker`: it runs in a container;
35
+ * `clone`: its folder is a git checkout. Never run by gonogo.
36
+ * shortcut: an install is told from its path (pnpm's global and dlx folders, npm's lib/node_modules); anything else gets the pnpm global command.
37
+ */
38
+ export function updateCommand(where) {
39
+ const path = where.file.replace(/\\/g, '/');
40
+ if (where.docker)
41
+ return 'docker compose pull && docker compose up -d';
42
+ if (where.clone)
43
+ return 'git pull && pnpm install && pnpm build';
44
+ if (path.includes('/pnpm/dlx/'))
45
+ return 'pnpm dlx @ulm0/gonogo@latest';
46
+ if (path.includes('/lib/node_modules/@ulm0/gonogo/'))
47
+ return 'npm install -g @ulm0/gonogo@latest';
48
+ return 'pnpm add -g @ulm0/gonogo@latest';
49
+ }
50
+ /** What `gonogo update` prints. */
51
+ export function updateText(command, docker, view) {
52
+ const state = view.newer ? `gonogo ${view.latest} is out; this is ${view.current}.` : `This is gonogo ${view.current}${view.latest === null ? '' : `; the newest the last check saw is ${view.latest}`}.`;
53
+ return [state, 'To update, run:', '', ` ${command}`, '', docker ? 'in the folder of your compose.yaml. gonogo never updates itself.' : 'gonogo never updates itself.'].join('\n') + '\n';
54
+ }
55
+ /** The last check as `gonogo --version` shows it, from the file alone: no network. */
56
+ export function cachedLatest(home) {
57
+ try {
58
+ const saved = JSON.parse(readFileSync(join(home, ROLLOUT_FILE), 'utf8'));
59
+ return isRecord(saved) && typeof saved.latest === 'string' && STABLE.test(saved.latest) ? saved.latest : null;
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ /** The body of an answer, or null when it is longer than `max` bytes. */
66
+ async function readCapped(res, max) {
67
+ const reader = res.body?.getReader();
68
+ if (reader === undefined)
69
+ return null;
70
+ const chunks = [];
71
+ let size = 0;
72
+ for (;;) {
73
+ const { done, value } = await reader.read();
74
+ if (done)
75
+ break;
76
+ size += value.length;
77
+ if (size > max) {
78
+ await reader.cancel();
79
+ return null;
80
+ }
81
+ chunks.push(value);
82
+ }
83
+ return Buffer.concat(chunks).toString('utf8');
84
+ }
85
+ export function createRollout(options) {
86
+ const log = options.log ?? nullLogger;
87
+ const path = join(options.dir, ROLLOUT_FILE);
88
+ let latest = null;
89
+ let checkedAt = null;
90
+ let timer;
91
+ let closed = false;
92
+ let running = null;
93
+ const view = () => ({
94
+ enabled: options.enabled,
95
+ current: options.current,
96
+ latest,
97
+ checkedAt,
98
+ newer: options.enabled && latest !== null && isNewer(latest, options.current),
99
+ command: options.command,
100
+ });
101
+ async function save() {
102
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
103
+ try {
104
+ await writeFile(temp, JSON.stringify({ version: 1, checkedAt, latest }, null, 2), { flag: 'wx', mode: FILE_MODE });
105
+ await rename(temp, path);
106
+ }
107
+ catch (error) {
108
+ await rm(temp, { force: true }).catch(() => undefined);
109
+ log.warn(`could not save ${ROLLOUT_FILE}: ${error instanceof Error ? error.message : String(error)}`);
110
+ }
111
+ }
112
+ /** One GET. A refusal, a timeout, a long answer or a version that is not x.y.z leaves `latest` as it was; the try still counts. */
113
+ async function ask() {
114
+ try {
115
+ const res = await options.fetch(ROLLOUT_URL, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(ROLLOUT_TIMEOUT_MS) });
116
+ // a refusal's body is not read: let the connection go
117
+ if (!res.ok)
118
+ await res.body?.cancel().catch(() => undefined);
119
+ const text = res.ok ? await readCapped(res, ROLLOUT_MAX_BYTES) : null;
120
+ const doc = text === null ? null : JSON.parse(text);
121
+ if (isRecord(doc) && typeof doc.version === 'string' && STABLE.test(doc.version))
122
+ latest = doc.version;
123
+ }
124
+ catch (error) {
125
+ log.debug(`the update check did not get an answer: ${error instanceof Error ? error.name : 'error'}`);
126
+ }
127
+ checkedAt = options.now();
128
+ await save();
129
+ const done = view();
130
+ if (!closed)
131
+ options.emit(done);
132
+ return done;
133
+ }
134
+ const check = () => (options.enabled ? (running ??= ask().finally(() => (running = null))) : Promise.resolve(view()));
135
+ const due = () => checkedAt === null || options.now() - checkedAt >= ROLLOUT_EVERY_MS || checkedAt > options.now();
136
+ return {
137
+ async load() {
138
+ try {
139
+ const saved = JSON.parse(await readFile(path, 'utf8'));
140
+ if (isRecord(saved) && saved.version === 1) {
141
+ if (typeof saved.latest === 'string' && STABLE.test(saved.latest))
142
+ latest = saved.latest;
143
+ if (typeof saved.checkedAt === 'number' && Number.isFinite(saved.checkedAt))
144
+ checkedAt = saved.checkedAt;
145
+ }
146
+ }
147
+ catch {
148
+ // no file yet, or one that is not ours: the next check makes it. Nothing in it is a secret.
149
+ }
150
+ },
151
+ view,
152
+ check,
153
+ start() {
154
+ if (!options.enabled || closed)
155
+ return;
156
+ const tick = () => {
157
+ if (closed)
158
+ return;
159
+ if (due())
160
+ void check();
161
+ timer = setTimeout(tick, CHECK_TICK_MS);
162
+ timer.unref();
163
+ };
164
+ tick();
165
+ },
166
+ async close() {
167
+ closed = true;
168
+ clearTimeout(timer);
169
+ await running?.catch(() => undefined);
170
+ },
171
+ };
172
+ }
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Launch Window: messages the Director wrote once and gonogo sends by itself on a cron rule (docs/launch-window-spec.md).
3
+ *
4
+ * A firing is `Hub.sendFromUser`, the same path as a message typed in the Brief box, so Max Q, Redline and held mail apply.
5
+ * One timer runs on the minute: it fires what is due and starts again. A fire more than SCHEDULE_GRACE_MS late (the
6
+ * machine slept, the event loop stalled) is skipped and logged, never replayed, and so are fires missed while gonogo was down.
7
+ * The clock, the timers and the send are injected, so tests run it on a fake clock.
8
+ *
9
+ * shortcut: a schedule that was disabled for a while and then enabled reports "missed" at the next start if its rule
10
+ * would have fired in between; track when it was turned off if the log line ever confuses.
11
+ * shortcut: `to` is an agent name, so after a rename the schedule writes to the old name and its fires end as
12
+ * "not sent: unknown recipient"; follow renames (key by record id) if renames get common.
13
+ */
14
+ import { randomBytes } from 'node:crypto';
15
+ import { readFile, rename, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { nextFire, parseCron } from '../shared/cron.js';
18
+ import { AGENT_NAME_PATTERN, BODY_MAX_CHARS, CRON_MAX_CHARS, SCHEDULE_NAME_MAX_CHARS, SCHEDULES_MAX, scheduleSubject, SUBJECT_MAX_CHARS, } from '../shared/protocol.js';
19
+ import { FILE_MODE, SCHEDULE_GRACE_MS, SCHEDULE_RESULT_MAX_CHARS, SCHEDULES_FILE } from './constants.js';
20
+ import { HubError } from './hub.js';
21
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
22
+ const ID_RE = /^s[1-9]\d{0,5}$/;
23
+ const EDITABLE = ['name', 'to', 'subject', 'body', 'rule', 'enabled'];
24
+ // C0, DEL, C1 and bidi controls: the name is part of a subject and must stay one clean line.
25
+ export const UNSAFE_IN_NAME = /[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/;
26
+ const MINUTE_MS = 60_000;
27
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ const bad = (message, field) => new HubError('bad_request', message, field);
29
+ function ruleOf(text) {
30
+ const rule = parseCron(text);
31
+ if (typeof rule === 'string')
32
+ throw bad(rule, 'rule');
33
+ return rule;
34
+ }
35
+ /** The fields a request may carry, checked one by one. With `whole` the four that have no default must be there. */
36
+ function validate(input, whole) {
37
+ if (!isRecord(input))
38
+ throw new HubError('bad_request', 'request body must be a JSON object');
39
+ for (const key of Object.keys(input))
40
+ if (!EDITABLE.includes(key))
41
+ throw bad(`unknown field "${key}"`, key);
42
+ if (whole)
43
+ for (const key of ['name', 'to', 'body', 'rule'])
44
+ if (input[key] === undefined)
45
+ throw bad(`${key} is required`, key);
46
+ const out = {};
47
+ if (input.name !== undefined) {
48
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
49
+ if (name === '' || name.length > SCHEDULE_NAME_MAX_CHARS || UNSAFE_IN_NAME.test(name)) {
50
+ throw bad(`name must be 1 to ${SCHEDULE_NAME_MAX_CHARS} characters on one line`, 'name');
51
+ }
52
+ out.name = name;
53
+ }
54
+ if (input.to !== undefined) {
55
+ if (typeof input.to !== 'string' || (input.to !== 'boss' && (input.to === 'user' || !NAME_RE.test(input.to)))) {
56
+ throw bad('to must be an agent name or "boss"', 'to');
57
+ }
58
+ out.to = input.to;
59
+ }
60
+ if (input.subject !== undefined) {
61
+ if (typeof input.subject !== 'string')
62
+ throw bad('subject must be text', 'subject');
63
+ out.subject = input.subject.trim();
64
+ }
65
+ if (input.body !== undefined) {
66
+ if (typeof input.body !== 'string' || input.body.trim() === '' || input.body.length > BODY_MAX_CHARS) {
67
+ throw bad(`body must be 1 to ${BODY_MAX_CHARS} characters`, 'body');
68
+ }
69
+ out.body = input.body;
70
+ }
71
+ if (input.rule !== undefined) {
72
+ if (typeof input.rule !== 'string' || input.rule.length > CRON_MAX_CHARS)
73
+ throw bad(`rule must be text of at most ${CRON_MAX_CHARS} characters`, 'rule');
74
+ ruleOf(input.rule);
75
+ out.rule = input.rule.trim().split(/\s+/).join(' ');
76
+ }
77
+ if (input.enabled !== undefined) {
78
+ if (typeof input.enabled !== 'boolean')
79
+ throw bad('enabled must be true or false', 'enabled');
80
+ out.enabled = input.enabled;
81
+ }
82
+ return out;
83
+ }
84
+ /** The whole subject has to fit the hub's limit once the prefix is on it. */
85
+ function checkSubject(schedule) {
86
+ if (scheduleSubject(schedule.name, schedule.subject).length > SUBJECT_MAX_CHARS) {
87
+ throw bad(`the name and the subject together must be at most ${SUBJECT_MAX_CHARS - 'Launch Window: : '.length} characters`, 'subject');
88
+ }
89
+ }
90
+ const cut = (text) => text.slice(0, SCHEDULE_RESULT_MAX_CHARS);
91
+ export function createSchedules(options) {
92
+ const { dir, now, log } = options;
93
+ const path = join(dir, SCHEDULES_FILE);
94
+ let entries = [];
95
+ let seq = 0;
96
+ let timer = null;
97
+ let closed = false;
98
+ let chain = Promise.resolve();
99
+ const later = (fn) => {
100
+ const run = chain.then(fn);
101
+ chain = run.catch((error) => log.error('launch window could not write', error));
102
+ return run.then(() => undefined);
103
+ };
104
+ const save = () => {
105
+ const json = JSON.stringify({ version: 1, schedules: entries.map((e) => e.schedule) }, null, 2);
106
+ return later(async () => {
107
+ const tmp = join(dir, `.${SCHEDULES_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
108
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
109
+ await rename(tmp, path);
110
+ });
111
+ };
112
+ const view = (e) => ({ ...e.schedule, nextAt: e.next });
113
+ const list = () => entries.map(view);
114
+ /** Tells the browsers and saves; a failed save is logged by `later`, so the caller that does not wait may ignore it. */
115
+ const changed = () => {
116
+ options.emit(list());
117
+ return save();
118
+ };
119
+ const entryOf = (id) => {
120
+ const e = ID_RE.test(id) ? entries.find((x) => x.schedule.id === id) : undefined;
121
+ if (!e)
122
+ throw new HubError('not_found', 'unknown schedule');
123
+ return e;
124
+ };
125
+ const nextOf = (e) => (e.schedule.enabled ? nextFire(e.rule, now()) : null);
126
+ const fire = (e) => {
127
+ const s = e.schedule;
128
+ s.lastRunAt = now();
129
+ let failed = false;
130
+ try {
131
+ const sent = options.send({ to: s.to, subject: scheduleSubject(s.name, s.subject), body: s.body });
132
+ failed = !sent.ok;
133
+ s.lastResult = cut(sent.ok ? `sent ${sent.id}: ${sent.status}${sent.note ? ` (${sent.note})` : ''}` : `undelivered ${sent.id}: ${sent.note ?? 'no reason given'}`);
134
+ }
135
+ catch (error) {
136
+ failed = true;
137
+ s.lastResult = cut(`not sent: ${error instanceof Error ? error.message : String(error)}`);
138
+ }
139
+ if (failed)
140
+ options.notify?.('launch-window', `${s.name}: ${s.lastResult}`);
141
+ };
142
+ const tick = () => {
143
+ const t = now();
144
+ let any = false;
145
+ for (const e of entries) {
146
+ if (e.next === null || e.next > t)
147
+ continue;
148
+ const due = e.next;
149
+ e.next = nextFire(e.rule, t);
150
+ any = true;
151
+ if (t - due > SCHEDULE_GRACE_MS)
152
+ log.warn(`launch window "${e.schedule.name}" missed its fire at ${new Date(due).toISOString()}; missed fires are not replayed`);
153
+ else
154
+ fire(e);
155
+ }
156
+ if (any)
157
+ void changed().catch(() => undefined);
158
+ arm();
159
+ };
160
+ // On the minute: a timer that fires a millisecond early only finds nothing due and starts again for that millisecond.
161
+ function arm() {
162
+ if (!closed)
163
+ timer = options.setTimer(tick, MINUTE_MS - (now() % MINUTE_MS));
164
+ }
165
+ return {
166
+ async load() {
167
+ let saved = null;
168
+ try {
169
+ saved = JSON.parse(await readFile(path, 'utf8'));
170
+ if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.schedules))
171
+ throw new Error('not a version 1 schedules file');
172
+ }
173
+ catch (error) {
174
+ saved = null;
175
+ if (error.code !== 'ENOENT') {
176
+ // kept aside, so that the next save cannot overwrite what the Director wrote
177
+ log.error(`${SCHEDULES_FILE} could not be read; schedules start empty and the file is kept as ${SCHEDULES_FILE}.bad`, error);
178
+ await rename(path, `${path}.bad`).catch(() => undefined);
179
+ }
180
+ }
181
+ const t = now();
182
+ const records = isRecord(saved) && Array.isArray(saved.schedules) ? saved.schedules : [];
183
+ for (const raw of records) {
184
+ try {
185
+ if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
186
+ throw new Error('no valid id');
187
+ if (entries.some((x) => x.schedule.id === raw.id))
188
+ throw new Error(`the id ${raw.id} is used twice`);
189
+ const { id, createdAt, lastRunAt, lastResult } = raw;
190
+ const own = validate(Object.fromEntries(EDITABLE.map((k) => [k, raw[k]])), true);
191
+ const schedule = {
192
+ id,
193
+ name: own.name,
194
+ to: own.to,
195
+ subject: own.subject ?? '',
196
+ body: own.body,
197
+ rule: own.rule,
198
+ enabled: own.enabled === true,
199
+ createdAt: typeof createdAt === 'number' ? createdAt : t,
200
+ lastRunAt: typeof lastRunAt === 'number' ? lastRunAt : null,
201
+ lastResult: typeof lastResult === 'string' ? cut(lastResult) : null,
202
+ };
203
+ checkSubject(schedule);
204
+ const e = { schedule, rule: ruleOf(schedule.rule), next: null };
205
+ e.next = nextOf(e);
206
+ entries.push(e);
207
+ seq = Math.max(seq, Number(id.slice(1)));
208
+ }
209
+ catch (error) {
210
+ log.warn(`${SCHEDULES_FILE}: a schedule was skipped: ${error instanceof Error ? error.message : String(error)}`);
211
+ }
212
+ }
213
+ const missed = entries.filter((e) => {
214
+ const at = e.schedule.enabled ? nextFire(e.rule, e.schedule.lastRunAt ?? e.schedule.createdAt) : null;
215
+ // every fire before now counts: one in the last minute before the start is not sent either, so it is logged too
216
+ return at !== null && at <= t;
217
+ });
218
+ if (missed.length > 0)
219
+ log.warn(`launch window: fires were missed while gonogo was down (${missed.map((e) => e.schedule.name).join(', ')}); missed fires are not replayed`);
220
+ arm();
221
+ },
222
+ list,
223
+ async create(input) {
224
+ const request = validate(input, true);
225
+ if (entries.length >= SCHEDULES_MAX)
226
+ throw new HubError('conflict', `at most ${SCHEDULES_MAX} schedules`);
227
+ const schedule = {
228
+ id: `s${seq + 1}`,
229
+ name: request.name,
230
+ to: request.to,
231
+ subject: request.subject ?? '',
232
+ body: request.body,
233
+ rule: request.rule,
234
+ enabled: request.enabled ?? true,
235
+ createdAt: now(),
236
+ lastRunAt: null,
237
+ lastResult: null,
238
+ };
239
+ checkSubject(schedule);
240
+ seq += 1;
241
+ const e = { schedule, rule: ruleOf(schedule.rule), next: null };
242
+ e.next = nextOf(e);
243
+ entries.push(e);
244
+ await changed();
245
+ return view(e);
246
+ },
247
+ async update(id, input) {
248
+ const e = entryOf(id);
249
+ const patch = validate(input, false);
250
+ const next = { ...e.schedule, ...patch };
251
+ checkSubject(next);
252
+ e.schedule = next;
253
+ e.rule = ruleOf(next.rule);
254
+ e.next = nextOf(e);
255
+ await changed();
256
+ return view(e);
257
+ },
258
+ async remove(id) {
259
+ const e = entryOf(id);
260
+ entries = entries.filter((x) => x !== e);
261
+ await changed();
262
+ },
263
+ async run(id) {
264
+ const e = entryOf(id);
265
+ fire(e);
266
+ await changed();
267
+ return view(e);
268
+ },
269
+ close() {
270
+ closed = true;
271
+ if (timer !== null)
272
+ options.clearTimer(timer);
273
+ timer = null;
274
+ return chain.then(() => undefined);
275
+ },
276
+ };
277
+ }