@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.
Files changed (46) hide show
  1. package/README.md +5 -11
  2. package/dist/client/assets/index-DxUnpGbS.js +52 -0
  3. package/dist/client/assets/index-tpcmltjw.css +1 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/audited.js +156 -0
  6. package/dist/server/blackbox.js +261 -0
  7. package/dist/server/board.js +123 -0
  8. package/dist/server/cleanroom.js +7 -51
  9. package/dist/server/clearance.js +158 -0
  10. package/dist/server/cli.js +229 -28
  11. package/dist/server/constants.js +54 -3
  12. package/dist/server/hangar.js +311 -0
  13. package/dist/server/home.js +41 -2
  14. package/dist/server/hub.js +280 -29
  15. package/dist/server/launcher.js +25 -13
  16. package/dist/server/logchart.js +58 -0
  17. package/dist/server/massbudget.js +169 -0
  18. package/dist/server/mcp.js +73 -2
  19. package/dist/server/migrate.js +7 -3
  20. package/dist/server/missionlog.js +2 -0
  21. package/dist/server/missions.js +310 -0
  22. package/dist/server/models.js +73 -0
  23. package/dist/server/phone.js +122 -0
  24. package/dist/server/phonetag.js +47 -0
  25. package/dist/server/prices.js +112 -0
  26. package/dist/server/propellant.js +243 -16
  27. package/dist/server/providers.js +123 -9
  28. package/dist/server/recorder.js +176 -0
  29. package/dist/server/relay.js +53 -7
  30. package/dist/server/relaykinds.js +11 -1
  31. package/dist/server/relief.js +226 -0
  32. package/dist/server/remotecontrol.js +15 -0
  33. package/dist/server/rollout.js +172 -0
  34. package/dist/server/tasks.js +44 -8
  35. package/dist/server/telemetry.js +110 -0
  36. package/dist/server/uplinks.js +7 -0
  37. package/dist/server/web.js +310 -10
  38. package/dist/server/worktree.js +137 -0
  39. package/dist/shared/fuel.js +8 -0
  40. package/dist/shared/livery.js +1 -1
  41. package/dist/shared/positions.js +1 -1
  42. package/dist/shared/prices.js +75 -0
  43. package/dist/shared/protocol.js +61 -15
  44. package/package.json +1 -1
  45. package/dist/client/assets/index-B6MsSoeo.css +0 -1
  46. package/dist/client/assets/index-DRtiRh1Y.js +0 -31
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Missions (docs/missions-spec.md): a named goal with a status, a lead and a history. Its tasks are the tasks of the Flight Plan
3
+ * whose `missionId` is its id, so the list of a mission is derived and a task is in one place only.
4
+ *
5
+ * The Director (the browser) changes everything; the boss may make a mission and change its status through the MCP tools
6
+ * (mission_create, mission_update), every other agent only reads. The server stamps the actor on each history line. Becoming
7
+ * `active` briefs the boss once (a message from the Director, or from the boss itself when it did it). Nothing closes a mission by
8
+ * itself: when the last open task of an active mission is done, the Director is told once and decides. The clock, the lists of the
9
+ * room and the send are injected for tests.
10
+ *
11
+ * shortcut: the whole list is in every frame and every snapshot; at the limits (50 open missions with 2000-character goals) that
12
+ * is far below the 4 MB socket buffer of web.ts.
13
+ * shortcut: `lead` is an agent name, so a mission does not follow a renamed console, as `assignee` of a task does not.
14
+ */
15
+ import { randomBytes } from 'node:crypto';
16
+ import { readFile, rename, writeFile } from 'node:fs/promises';
17
+ import { join } from 'node:path';
18
+ import { AGENT_NAME_PATTERN, MISSION_GOAL_MAX_CHARS, MISSION_NAME_MAX_CHARS, MISSION_NOTE_MAX_CHARS, MISSION_STATUSES, MISSIONS_OPEN_MAX, missionSubject, SUBJECT_MAX_CHARS, } from '../shared/protocol.js';
19
+ import { FILE_MODE, MISSION_NOTES_MAX, MISSIONS_DONE_KEEP, MISSIONS_FILE } from './constants.js';
20
+ import { isRecord } from './hooks.js';
21
+ import { HubError } from './hub.js';
22
+ import { UNSAFE_IN_NAME } from './schedules.js';
23
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
24
+ const ID_RE = /^ms[1-9]\d{0,5}$/;
25
+ const CREATE_FIELDS = ['name', 'goal', 'lead'];
26
+ const PATCH_FIELDS = ['name', 'goal', 'status', 'lead', 'note'];
27
+ const bad = (message, field) => new HubError('bad_request', message, field);
28
+ const copy = (m) => ({ ...m, history: [...m.history] });
29
+ const isFinished = (m) => m.status === 'done' || m.status === 'aborted';
30
+ const stamp = (at) => `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
31
+ const line = (actor, text, at) => `${stamp(at)} ${actor.kind === 'agent' ? actor.name : 'Director'}: ${text}`;
32
+ function validate(input, whole, isAgent) {
33
+ if (!isRecord(input))
34
+ throw bad('request body must be a JSON object');
35
+ const allowed = whole ? CREATE_FIELDS : PATCH_FIELDS;
36
+ for (const key of Object.keys(input))
37
+ if (!allowed.includes(key))
38
+ throw bad(`unknown field "${key}"`, key);
39
+ if (whole && input.name === undefined)
40
+ throw bad('name is required', 'name');
41
+ if (!whole && Object.keys(input).length === 0)
42
+ throw bad('nothing to change: give a name, a goal, a status, a lead or a note');
43
+ const out = {};
44
+ if (input.name !== undefined) {
45
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
46
+ if (name === '' || name.length > MISSION_NAME_MAX_CHARS || UNSAFE_IN_NAME.test(name))
47
+ throw bad(`name must be 1 to ${MISSION_NAME_MAX_CHARS} characters on one line`, 'name');
48
+ out.name = name;
49
+ }
50
+ if (input.goal !== undefined) {
51
+ if (typeof input.goal !== 'string' || input.goal.length > MISSION_GOAL_MAX_CHARS)
52
+ throw bad(`goal must be text of at most ${MISSION_GOAL_MAX_CHARS} characters`, 'goal');
53
+ out.goal = input.goal.trim();
54
+ }
55
+ if (input.status !== undefined) {
56
+ if (typeof input.status !== 'string' || !MISSION_STATUSES.includes(input.status))
57
+ throw bad(`status must be one of: ${MISSION_STATUSES.join(', ')}`, 'status');
58
+ out.status = input.status;
59
+ }
60
+ if (input.lead !== undefined) {
61
+ if (input.lead !== null && (typeof input.lead !== 'string' || !NAME_RE.test(input.lead) || !isAgent(input.lead)))
62
+ throw bad('lead must be the name of an agent in the room, or null', 'lead');
63
+ out.lead = input.lead;
64
+ }
65
+ if (input.note !== undefined) {
66
+ const note = typeof input.note === 'string' ? input.note.replace(/\s+/g, ' ').trim() : '';
67
+ if (note === '' || note.length > MISSION_NOTE_MAX_CHARS || UNSAFE_IN_NAME.test(note))
68
+ throw bad(`note must be 1 to ${MISSION_NOTE_MAX_CHARS} characters`, 'note');
69
+ out.note = note;
70
+ }
71
+ return out;
72
+ }
73
+ /** A saved record read back; one that is not a mission throws, and the caller skips it. */
74
+ function fromRecord(raw, at) {
75
+ if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
76
+ throw new Error('no valid id');
77
+ const { id, name, goal, status, lead, createdBy, createdAt, updatedAt, startedAt, endedAt, history } = raw;
78
+ if (typeof name !== 'string' || name === '' || name.length > MISSION_NAME_MAX_CHARS)
79
+ throw new Error('no valid name');
80
+ if (typeof status !== 'string' || !MISSION_STATUSES.includes(status))
81
+ throw new Error('no valid status');
82
+ const time = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
83
+ return {
84
+ id,
85
+ name,
86
+ goal: typeof goal === 'string' ? goal.slice(0, MISSION_GOAL_MAX_CHARS) : '',
87
+ status: status,
88
+ lead: typeof lead === 'string' && NAME_RE.test(lead) ? lead : null,
89
+ createdBy: typeof createdBy === 'string' && NAME_RE.test(createdBy) ? createdBy : 'user',
90
+ createdAt: time(createdAt) ?? at,
91
+ updatedAt: time(updatedAt) ?? at,
92
+ startedAt: time(startedAt),
93
+ endedAt: time(endedAt),
94
+ history: Array.isArray(history) ? history.filter((n) => typeof n === 'string').slice(-MISSION_NOTES_MAX) : [],
95
+ };
96
+ }
97
+ export function createMissions(options) {
98
+ const { dir, now, log } = options;
99
+ const path = join(dir, MISSIONS_FILE);
100
+ let missions = [];
101
+ let seq = 0;
102
+ let chain = Promise.resolve();
103
+ /** Open tasks of each active mission at the last look, to tell once when the last one is done. */
104
+ const openBefore = new Map();
105
+ const later = (fn) => {
106
+ const run = chain.then(fn);
107
+ chain = run.catch((error) => log.error('missions could not write', error));
108
+ return run.then(() => undefined);
109
+ };
110
+ const save = () => {
111
+ // `seq` is the number of the last id given, so an id that was removed or trimmed is not given again after a restart
112
+ const json = JSON.stringify({ version: 1, seq, missions }, null, 2);
113
+ return later(async () => {
114
+ const tmp = join(dir, `.${MISSIONS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
115
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
116
+ await rename(tmp, path);
117
+ });
118
+ };
119
+ const list = () => missions.map(copy);
120
+ const changed = () => {
121
+ options.emit(list());
122
+ return save();
123
+ };
124
+ const find = (id) => {
125
+ const mission = ID_RE.test(id) ? missions.find((x) => x.id === id) : undefined;
126
+ if (!mission)
127
+ throw new HubError('not_found', 'unknown mission');
128
+ return mission;
129
+ };
130
+ const linked = (id) => options.tasks().filter((t) => t.missionId === id);
131
+ const open = (id) => linked(id).filter((t) => t.status !== 'done');
132
+ const full = () => new HubError('conflict', `at most ${MISSIONS_OPEN_MAX} missions that are not finished: finish or remove one first`, 'missions');
133
+ /** The 20 most recent finished missions stay, so the file and every frame stop growing. */
134
+ const prune = () => {
135
+ const done = missions.filter(isFinished);
136
+ if (done.length <= MISSIONS_DONE_KEEP)
137
+ return;
138
+ const drop = new Set(done.sort((a, b) => (b.endedAt ?? b.updatedAt) - (a.endedAt ?? a.updatedAt)).slice(MISSIONS_DONE_KEEP));
139
+ missions = missions.filter((x) => !drop.has(x));
140
+ for (const m of drop)
141
+ void options.unlink(m.id).catch(() => undefined);
142
+ };
143
+ /** The briefing of the boss when a mission starts: once, as a message from whoever started it. A refusal is a note, not a failure. */
144
+ const brief = (actor, mission, at) => {
145
+ const boss = options.boss();
146
+ if (boss === null || (actor.kind === 'agent' && actor.name === boss))
147
+ return;
148
+ const tasks = open(mission.id);
149
+ const taskLines = tasks.length === 0 ? 'No tasks are linked yet.' : `Open tasks:\n${tasks.map((t) => `- ${t.id} [${t.status}] ${t.title}${t.assignee === null ? '' : ` (${t.assignee})`}`).join('\n')}`;
150
+ const body = `${mission.goal === '' ? '(no goal written)' : mission.goal}\n\n${taskLines}\n\nStarted by ${actor.kind === 'agent' ? actor.name : 'the Director'}. See mission_list; link tasks with missionId.`;
151
+ try {
152
+ const sent = options.send(actor, { to: boss, subject: missionSubject(mission.name).slice(0, SUBJECT_MAX_CHARS), body });
153
+ if (!sent.ok)
154
+ mission.history.push(line(actor, `the briefing to ${boss} was not delivered: ${sent.note ?? 'no reason given'}`, at));
155
+ }
156
+ catch (error) {
157
+ mission.history.push(line(actor, `the briefing to ${boss} was not sent: ${error instanceof HubError ? error.message : 'it failed'}`, at));
158
+ }
159
+ };
160
+ return {
161
+ async load() {
162
+ let saved = null;
163
+ try {
164
+ saved = JSON.parse(await readFile(path, 'utf8'));
165
+ if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.missions))
166
+ throw new Error('not a version 1 missions file');
167
+ }
168
+ catch (error) {
169
+ saved = null;
170
+ if (error.code !== 'ENOENT') {
171
+ // kept aside, so that the next save cannot overwrite what the Director and the boss wrote
172
+ log.error(`${MISSIONS_FILE} could not be read; the room starts with no missions and the file is kept as ${MISSIONS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
173
+ await rename(path, `${path}.bad`).catch(() => undefined);
174
+ }
175
+ }
176
+ const records = isRecord(saved) && Array.isArray(saved.missions) ? saved.missions : [];
177
+ if (isRecord(saved) && typeof saved.seq === 'number' && Number.isSafeInteger(saved.seq) && saved.seq > 0)
178
+ seq = saved.seq;
179
+ for (const raw of records) {
180
+ try {
181
+ const mission = fromRecord(raw, now());
182
+ if (missions.some((x) => x.id === mission.id))
183
+ throw new Error(`the id ${mission.id} is used twice`);
184
+ missions.push(mission);
185
+ seq = Math.max(seq, Number(mission.id.slice(2)));
186
+ }
187
+ catch (error) {
188
+ log.warn(`${MISSIONS_FILE}: a mission was skipped: ${error instanceof Error ? error.message : String(error)}`);
189
+ }
190
+ }
191
+ },
192
+ list,
193
+ has: (id) => ID_RE.test(id) && missions.some((x) => x.id === id),
194
+ async create(actor, input) {
195
+ const request = validate(input, true, options.isAgent);
196
+ if (missions.filter((m) => !isFinished(m)).length >= MISSIONS_OPEN_MAX)
197
+ throw full();
198
+ const at = now();
199
+ const lead = request.lead === undefined ? options.boss() : request.lead;
200
+ const mission = {
201
+ id: `ms${seq + 1}`,
202
+ name: request.name ?? '',
203
+ goal: request.goal ?? '',
204
+ status: 'planned',
205
+ lead,
206
+ createdBy: actor.kind === 'agent' ? actor.name : 'user',
207
+ createdAt: at,
208
+ updatedAt: at,
209
+ startedAt: null,
210
+ endedAt: null,
211
+ history: [line(actor, lead === null ? 'created' : `created; lead ${lead}`, at)],
212
+ };
213
+ seq += 1;
214
+ missions.push(mission);
215
+ prune();
216
+ await changed();
217
+ return copy(mission);
218
+ },
219
+ async update(actor, id, input) {
220
+ const mission = find(id);
221
+ const patch = validate(input, false, options.isAgent);
222
+ // an agent (the boss) changes the status and writes notes; the name, the goal and the lead are the Director's
223
+ if (actor.kind === 'agent') {
224
+ for (const key of ['name', 'goal', 'lead'])
225
+ if (patch[key] !== undefined)
226
+ throw new HubError('forbidden', `only the Director changes the ${key} of a mission`, key);
227
+ }
228
+ const at = now();
229
+ const next = copy(mission);
230
+ const parts = [];
231
+ if (patch.name !== undefined && patch.name !== mission.name) {
232
+ next.name = patch.name;
233
+ parts.push('renamed');
234
+ }
235
+ if (patch.goal !== undefined && patch.goal !== mission.goal) {
236
+ next.goal = patch.goal;
237
+ parts.push('goal changed');
238
+ }
239
+ if (patch.lead !== undefined && patch.lead !== mission.lead) {
240
+ next.lead = patch.lead;
241
+ parts.push(patch.lead === null ? 'lead removed' : `lead ${patch.lead}`);
242
+ }
243
+ let started = false;
244
+ let ended = false;
245
+ if (patch.status !== undefined && patch.status !== mission.status) {
246
+ if (isFinished(mission) && !isFinished({ ...mission, status: patch.status }) && missions.filter((m) => !isFinished(m)).length >= MISSIONS_OPEN_MAX)
247
+ throw full();
248
+ next.status = patch.status;
249
+ parts.push(`status ${patch.status}`);
250
+ if (patch.status === 'active') {
251
+ next.startedAt = at;
252
+ started = true;
253
+ }
254
+ next.endedAt = isFinished(next) ? at : null;
255
+ ended = isFinished(next);
256
+ }
257
+ if (patch.note !== undefined)
258
+ parts.push(patch.note);
259
+ if (parts.length === 0)
260
+ return copy(mission);
261
+ next.updatedAt = at;
262
+ next.history.push(line(actor, parts.join('; '), at));
263
+ if (started)
264
+ brief(actor, next, at);
265
+ next.history = next.history.slice(-MISSION_NOTES_MAX);
266
+ missions[missions.indexOf(mission)] = next;
267
+ if (started) {
268
+ openBefore.set(next.id, open(next.id).length);
269
+ options.notify?.('mission', `Mission started: ${next.name}`);
270
+ }
271
+ if (ended) {
272
+ openBefore.delete(next.id);
273
+ const counted = linked(next.id);
274
+ options.notify?.('mission', `Mission ${next.status}: ${next.name} (${counted.filter((t) => t.status === 'done').length} of ${counted.length} tasks done)`);
275
+ }
276
+ if (next.status !== 'active')
277
+ openBefore.delete(next.id);
278
+ prune();
279
+ await changed();
280
+ return copy(next);
281
+ },
282
+ async remove(id, unlink) {
283
+ const mission = find(id);
284
+ const tasks = linked(id);
285
+ if (tasks.length > 0 && !unlink)
286
+ throw new HubError('conflict', `the mission has ${tasks.length} linked ${tasks.length === 1 ? 'task' : 'tasks'}: remove it with unlink to keep them on the board`, 'unlink');
287
+ if (tasks.length > 0)
288
+ await options.unlink(id);
289
+ missions = missions.filter((x) => x !== mission);
290
+ openBefore.delete(id);
291
+ await changed();
292
+ },
293
+ observe(tasks) {
294
+ for (const mission of missions) {
295
+ if (mission.status !== 'active')
296
+ continue;
297
+ const mine = tasks.filter((t) => t.missionId === mission.id);
298
+ const openNow = mine.filter((t) => t.status !== 'done').length;
299
+ const before = openBefore.get(mission.id);
300
+ openBefore.set(mission.id, openNow);
301
+ if (before !== undefined && before > 0 && openNow === 0 && mine.length > 0) {
302
+ options.notify?.('mission', `All ${mine.length} ${mine.length === 1 ? 'task' : 'tasks'} of ${mission.name} are done: close it?`);
303
+ }
304
+ }
305
+ },
306
+ close() {
307
+ return chain.then(() => undefined);
308
+ },
309
+ };
310
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Default models (docs/engine-bay-spec.md): the room's model for each engine that takes one, used at an agent's start when the agent
3
+ * has no `model` of its own. models.json holds `{ version: 1, models: { claude: 'sonnet' } }`; names only, no secret. A model of the
4
+ * agent always wins, and a change applies at the next start of each agent (the launcher asks at every start).
5
+ */
6
+ import { randomBytes } from 'node:crypto';
7
+ import { readFile, rename, rm, writeFile } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import { MODEL_PATTERN, PROVIDERS, providerInfo } from '../shared/protocol.js';
10
+ import { FILE_MODE, MODELS_FILE, nullLogger } from './constants.js';
11
+ import { HubError } from './hub.js';
12
+ const MODEL_RE = new RegExp(MODEL_PATTERN);
13
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ export function createModelDefaults(options) {
15
+ const log = options.log ?? nullLogger;
16
+ const path = join(options.dir, MODELS_FILE);
17
+ let models = {};
18
+ let chain = Promise.resolve();
19
+ const usable = (provider, model) => typeof provider === 'string' && PROVIDERS.includes(provider) && providerInfo(provider).model !== null && typeof model === 'string' && MODEL_RE.test(model);
20
+ return {
21
+ async load() {
22
+ try {
23
+ const saved = JSON.parse(await readFile(path, 'utf8'));
24
+ if (!isRecord(saved) || saved.version !== 1 || !isRecord(saved.models))
25
+ throw new Error('not a version 1 models file');
26
+ models = Object.fromEntries(Object.entries(saved.models).filter(([provider, model]) => usable(provider, model)));
27
+ }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT')
30
+ return;
31
+ log.error(`${MODELS_FILE} could not be read; the room has no default models and the file is kept as ${MODELS_FILE}.bad`, error);
32
+ await rename(path, `${path}.bad`).catch(() => undefined);
33
+ }
34
+ },
35
+ view: () => ({ models: { ...models } }),
36
+ get: (provider) => models[provider],
37
+ async set(provider, model) {
38
+ if (typeof provider !== 'string' || !PROVIDERS.includes(provider))
39
+ throw new HubError('bad_request', 'unknown engine', 'provider');
40
+ if (providerInfo(provider).model === null)
41
+ throw new HubError('bad_request', `${providerInfo(provider).label} takes no model setting`, 'provider');
42
+ const name = model === null || model === undefined ? '' : typeof model === 'string' ? model.trim() : null;
43
+ if (name === null)
44
+ throw new HubError('bad_request', 'model must be text or null', 'model');
45
+ if (name !== '' && !MODEL_RE.test(name))
46
+ throw new HubError('bad_request', 'model must be 1 to 100 letters, digits or . _ : / @ + -, starting with a letter or digit', 'model');
47
+ const run = chain.then(async () => {
48
+ const before = models;
49
+ const next = { ...models };
50
+ if (name === '')
51
+ delete next[provider];
52
+ else
53
+ next[provider] = name;
54
+ if (JSON.stringify(next) === JSON.stringify(before))
55
+ return;
56
+ models = next;
57
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
58
+ try {
59
+ await writeFile(temp, JSON.stringify({ version: 1, models }, null, 2), { flag: 'wx', mode: FILE_MODE });
60
+ await rename(temp, path);
61
+ }
62
+ catch (error) {
63
+ models = before;
64
+ await rm(temp, { force: true }).catch(() => undefined);
65
+ throw new Error(`could not save the default models: ${error instanceof Error ? error.message : String(error)}`);
66
+ }
67
+ });
68
+ chain = run.catch(() => undefined);
69
+ return run.then(() => ({ models: { ...models } }));
70
+ },
71
+ close: () => chain.then(() => undefined),
72
+ };
73
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Phone approvals, Path A (docs/phone-approvals-spec.md): a pending permission or hire request goes to the Director's Telegram chat
3
+ * with buttons, and a press comes back through the Telegram uplink as a signed `callback_query`.
4
+ *
5
+ * Buttons carry `a:<kind>:<id>:<verdict>:<tag>` (phonetag.ts). For a permission the id is a short handle (`p7`) of this process's
6
+ * map to the agent and the dialog number (`needSeq`); the answer is `Hub.answer(name, { go, needSeq })`, so a press that comes
7
+ * late, for a dialog that was answered or replaced, does nothing. For a hire request the id is the Relief id, and only NO-GO and
8
+ * Open are offered: the role text is not shown on a phone, so GO is the page's (docs/relief-spec.md). A dialog or a request whose
9
+ * text was cut also gets NO-GO and Open only.
10
+ *
11
+ * Every id starts with a nonce made at start: the signing secret survives a restart but the handles do not, so without it an old
12
+ * "GO p1" would approve the new dialog p1. A button of before a restart answers "too late".
13
+ * shortcut: the handles are in memory and bounded.
14
+ * shortcut: Telegram does not say who pressed beyond the chat; the chat of the target is the Director's, as for messages.
15
+ */
16
+ import { randomBytes } from 'node:crypto';
17
+ import { callbackData, verifyCallback } from './phonetag.js';
18
+ /** Presses taken in a minute: more are told "slow down". */
19
+ export const PHONE_PRESS_MAX = 10;
20
+ const PRESS_WINDOW_MS = 60_000;
21
+ const HANDLES_MAX = 200;
22
+ const OPEN_NOTE = 'Open gonogo to read it and answer';
23
+ const PERMISSION_CUT = '…';
24
+ export function createPhone(options) {
25
+ const { hub, relief, relay, log } = options;
26
+ /** 4 hex characters, new for each process: part of every id that is signed. */
27
+ const nonce = options.nonce?.() ?? randomBytes(2).toString('hex');
28
+ const handles = new Map();
29
+ let handleSeq = 0;
30
+ let taken = [];
31
+ const reply = (press, text) => relay.telegramCall('answerCallbackQuery', { callback_query_id: press.queryId, text });
32
+ const clear = (press) => press.messageId === '' ? Promise.resolve(false) : relay.telegramCall('editMessageReplyMarkup', { message_id: Number(press.messageId), reply_markup: { inline_keyboard: [] } });
33
+ return {
34
+ approval(ref, text) {
35
+ if (!relay.phoneTelegram())
36
+ return;
37
+ const secret = options.secret();
38
+ if (secret === null)
39
+ return;
40
+ const cut = text.endsWith(PERMISSION_CUT);
41
+ let id;
42
+ let verdicts;
43
+ let shown = text;
44
+ if (ref.kind === 'permission') {
45
+ handleSeq += 1;
46
+ id = `p${nonce}${handleSeq}`;
47
+ handles.set(id, { agent: ref.agent, seq: ref.seq });
48
+ if (handles.size > HANDLES_MAX)
49
+ handles.delete(handles.keys().next().value);
50
+ verdicts = cut ? ['nogo', 'open'] : ['go', 'nogo'];
51
+ if (cut)
52
+ shown = `${text}\n(truncated: open gonogo to see all of it)`;
53
+ }
54
+ else {
55
+ id = `r${nonce}${ref.id}`;
56
+ verdicts = ['nogo', 'open'];
57
+ shown = `${text}\n(role text: open gonogo to read it)`;
58
+ }
59
+ const label = { go: 'GO', nogo: 'NO-GO', open: 'Open' };
60
+ const buttons = verdicts.flatMap((verdict) => {
61
+ const data = callbackData(secret, { kind: ref.kind, id, verdict });
62
+ return data === null ? [] : [{ text: label[verdict], callback_data: data }];
63
+ });
64
+ if (buttons.length === 0)
65
+ return;
66
+ void relay.sendButtons(shown, { inline_keyboard: [buttons] }).catch(() => undefined);
67
+ },
68
+ async press(secret, press) {
69
+ const t = options.now();
70
+ // a bad tag counts too: somebody guessing tags must not have more than the limit of tries
71
+ taken = taken.filter((at) => t - at < PRESS_WINDOW_MS);
72
+ if (taken.length >= PHONE_PRESS_MAX) {
73
+ await reply(press, 'Too many presses: wait a minute');
74
+ return;
75
+ }
76
+ taken.push(t);
77
+ // the Director may have turned the path off since the button was sent
78
+ if (!relay.phoneTelegram()) {
79
+ await reply(press, 'Phone approvals are off');
80
+ return;
81
+ }
82
+ const call = verifyCallback(secret, press.data);
83
+ if (call === null) {
84
+ log.debug('phone: a button with a wrong tag');
85
+ await reply(press, 'Invalid button');
86
+ return;
87
+ }
88
+ if (call.verdict === 'open') {
89
+ await reply(press, OPEN_NOTE);
90
+ return;
91
+ }
92
+ const go = call.verdict === 'go';
93
+ try {
94
+ if (call.kind === 'permission') {
95
+ const found = handles.get(call.id);
96
+ if (found === undefined)
97
+ throw new Error('too late: that dialog is gone');
98
+ hub.answer(found.agent, { go, needSeq: found.seq });
99
+ }
100
+ else {
101
+ // GO is never offered for a hire request; a signed one that was made by hand is refused all the same
102
+ if (go)
103
+ throw new Error('hire requests are approved in gonogo');
104
+ // r<nonce><id>: a button of another process is a request that is gone
105
+ if (!call.id.startsWith(`r${nonce}`))
106
+ throw new Error('too late: that request is gone');
107
+ await relief.decide(call.id.slice(1 + nonce.length), 'no-go', { kind: 'user' });
108
+ }
109
+ }
110
+ catch (error) {
111
+ const why = error instanceof Error ? error.message : String(error);
112
+ log.debug(`phone: ${call.kind} ${call.id}: ${why}`);
113
+ await reply(press, why.startsWith('too late') || /answered or replaced|not asking|no such hire/.test(why) ? 'Too late: already answered' : cutWhy(why));
114
+ await clear(press);
115
+ return;
116
+ }
117
+ await reply(press, go ? 'Sent GO' : 'Sent NO-GO');
118
+ await clear(press);
119
+ },
120
+ };
121
+ }
122
+ const cutWhy = (why) => (why.length > 150 ? `${why.slice(0, 149)}…` : why);
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Phone approvals: the signed `callback_data` of a Telegram button (docs/phone-approvals-spec.md, Path A).
3
+ *
4
+ * `a:<kind>:<id>:<verdict>:<tag>` fits Telegram's 64 bytes. `<tag>` is the first 8 hex characters (32 bits) of
5
+ * HMAC-SHA256(secret, "kind:id:verdict"): it binds a button to one request and one verdict, so an edited or forwarded button
6
+ * cannot approve something else. Pure: no clock, no network, no files; the secret is the Telegram uplink's, handed in.
7
+ *
8
+ * shortcut: 32 bits are enough only because the uplink limits callbacks to 10 a minute and a request lives minutes;
9
+ * lengthen the tag (there is room up to 64 bytes) if that ever stops being true.
10
+ */
11
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
12
+ export const PHONE_KINDS = ['permission', 'relief'];
13
+ export const PHONE_VERDICTS = ['go', 'nogo', 'open'];
14
+ /** An id as the hub makes them: the needs_you sequence number or a Relief id. */
15
+ const ID_RE = /^[A-Za-z0-9_-]{1,24}$/;
16
+ const TAG_RE = /^[0-9a-f]{8}$/;
17
+ const TELEGRAM_CALLBACK_MAX_BYTES = 64;
18
+ const digest = (text) => createHash('sha256').update(text, 'utf8').digest();
19
+ const same = (a, b) => timingSafeEqual(digest(a), digest(b));
20
+ /** The tag of one button; null when the parts are not valid (so nothing odd is ever signed). */
21
+ export function callbackTag(secret, call) {
22
+ if (secret === '' || !ID_RE.test(call.id) || !PHONE_KINDS.includes(call.kind) || !PHONE_VERDICTS.includes(call.verdict))
23
+ return null;
24
+ return createHmac('sha256', secret).update(`${call.kind}:${call.id}:${call.verdict}`).digest('hex').slice(0, 8);
25
+ }
26
+ /** The `callback_data` of a button, or null when it would not be valid or would not fit. */
27
+ export function callbackData(secret, call) {
28
+ const tag = callbackTag(secret, call);
29
+ if (tag === null)
30
+ return null;
31
+ const data = `a:${call.kind}:${call.id}:${call.verdict}:${tag}`;
32
+ return Buffer.byteLength(data, 'utf8') <= TELEGRAM_CALLBACK_MAX_BYTES ? data : null;
33
+ }
34
+ /** What a button says if, and only if, its tag is right for this secret; anything else is null. Constant-time compare. */
35
+ export function verifyCallback(secret, data) {
36
+ if (typeof data !== 'string' || Buffer.byteLength(data, 'utf8') > TELEGRAM_CALLBACK_MAX_BYTES)
37
+ return null;
38
+ const parts = data.split(':');
39
+ if (parts.length !== 5 || parts[0] !== 'a')
40
+ return null;
41
+ const [, kind, id, verdict, tag] = parts;
42
+ if (!PHONE_KINDS.includes(kind) || !PHONE_VERDICTS.includes(verdict) || !TAG_RE.test(tag))
43
+ return null;
44
+ const call = { kind, id, verdict };
45
+ const expected = callbackTag(secret, call);
46
+ return expected !== null && same(tag, expected) ? call : null;
47
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The owner's model prices: `prices.json` in gonogo's home, over the defaults of src/shared/prices.ts (docs/cost-spec.md).
3
+ * Local and editable; nothing is fetched. `currency` is a label only, there is no conversion.
4
+ */
5
+ import { randomBytes } from 'node:crypto';
6
+ import { readFile, rename, writeFile } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { mergePrices, PRICE_MAX, PRICE_PREFIX_PATTERN } from '../shared/prices.js';
9
+ import { FILE_MODE, PRICES_FILE } from './constants.js';
10
+ const PREFIX_RE = new RegExp(PRICE_PREFIX_PATTERN);
11
+ const PRICE_KEYS = ['input', 'output', 'cacheWrite', 'cacheRead'];
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /** One price from untrusted JSON: exactly the four numbers, each from 0 to PRICE_MAX; anything else is a message. */
16
+ export function parsePrice(value, what) {
17
+ if (!isRecord(value))
18
+ return `${what} must be an object with ${PRICE_KEYS.join(', ')}`;
19
+ for (const key of Object.keys(value))
20
+ if (!PRICE_KEYS.includes(key))
21
+ return `${what}: unknown field "${key}"`;
22
+ const price = {};
23
+ for (const key of PRICE_KEYS) {
24
+ const v = value[key];
25
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0 || v > PRICE_MAX)
26
+ return `${what}.${key} must be a number of dollars per million tokens from 0 to ${PRICE_MAX}`;
27
+ price[key] = v;
28
+ }
29
+ return price;
30
+ }
31
+ /** The body of PUT /api/prices: `{ models: { <prefix>: price } }` (and `currency`, a label). Strict: unknown fields are refused. */
32
+ export function parsePricesRequest(body) {
33
+ for (const key of Object.keys(body)) {
34
+ if (key !== 'models' && key !== 'currency' && key !== 'version')
35
+ return { ok: false, error: `unknown field "${key}"`, field: key };
36
+ }
37
+ if (body.currency !== undefined && (typeof body.currency !== 'string' || !/^[A-Za-z]{3}$/.test(body.currency))) {
38
+ return { ok: false, error: 'currency must be a three-letter label such as USD', field: 'currency' };
39
+ }
40
+ if (!isRecord(body.models))
41
+ return { ok: false, error: 'models must be an object of model prefixes', field: 'models' };
42
+ const models = {};
43
+ for (const [prefix, raw] of Object.entries(body.models)) {
44
+ if (!PREFIX_RE.test(prefix))
45
+ return { ok: false, error: `models: invalid prefix "${prefix}"`, field: 'models' };
46
+ const price = parsePrice(raw, `models.${prefix}`);
47
+ if (typeof price === 'string')
48
+ return { ok: false, error: price, field: 'models' };
49
+ models[prefix] = price;
50
+ }
51
+ return { ok: true, models };
52
+ }
53
+ export function createPrices(options) {
54
+ const { dir, log } = options;
55
+ const path = join(dir, PRICES_FILE);
56
+ let file = {};
57
+ let currency = 'USD';
58
+ let merged = mergePrices(file);
59
+ let chain = Promise.resolve();
60
+ const save = () => {
61
+ const json = JSON.stringify({ version: 1, currency, models: file }, null, 2);
62
+ const run = chain.then(async () => {
63
+ const tmp = join(dir, `.${PRICES_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
64
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
65
+ await rename(tmp, path);
66
+ });
67
+ chain = run.catch((error) => log.error('prices could not write', error));
68
+ return run;
69
+ };
70
+ const view = () => ({ currency, rows: merged });
71
+ return {
72
+ async load() {
73
+ try {
74
+ const data = JSON.parse(await readFile(path, 'utf8'));
75
+ if (isRecord(data)) {
76
+ const parsed = parsePricesRequest({ models: data.models ?? {}, ...(typeof data.currency === 'string' ? { currency: data.currency } : {}) });
77
+ if (parsed.ok) {
78
+ file = parsed.models;
79
+ if (typeof data.currency === 'string')
80
+ currency = data.currency;
81
+ }
82
+ else
83
+ log.warn(`${PRICES_FILE} is not valid (${parsed.error}); the default prices are used`);
84
+ }
85
+ }
86
+ catch (error) {
87
+ if (error.code !== 'ENOENT')
88
+ log.warn(`${PRICES_FILE} could not be read; the default prices are used`, error);
89
+ }
90
+ merged = mergePrices(file);
91
+ },
92
+ table: () => merged,
93
+ view,
94
+ async replace(models, label) {
95
+ file = { ...models };
96
+ if (label !== undefined)
97
+ currency = label.toUpperCase();
98
+ merged = mergePrices(file);
99
+ await save();
100
+ return view();
101
+ },
102
+ async remove(prefix) {
103
+ if (!(prefix in file))
104
+ return false;
105
+ delete file[prefix];
106
+ merged = mergePrices(file);
107
+ await save();
108
+ return true;
109
+ },
110
+ close: () => chain.then(() => undefined),
111
+ };
112
+ }