@ulm0/gonogo 0.1.2 → 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.
@@ -22,8 +22,9 @@ import { UNSAFE_IN_NAME } from './schedules.js';
22
22
  const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
23
23
  const STATION_RE = new RegExp(STATION_NAME_PATTERN);
24
24
  const ID_RE = /^t[1-9]\d{0,5}$/;
25
- const CREATE_FIELDS = ['title', 'detail', 'assignee'];
26
- const PATCH_FIELDS = ['status', 'assignee', 'note'];
25
+ const MISSION_ID_RE = /^ms[1-9]\d{0,5}$/;
26
+ const CREATE_FIELDS = ['title', 'detail', 'assignee', 'missionId'];
27
+ const PATCH_FIELDS = ['status', 'assignee', 'note', 'missionId'];
27
28
  const bad = (message, field) => new HubError('bad_request', message, field);
28
29
  const copy = (task) => ({ ...task, notes: [...task.notes] });
29
30
  const isOpen = (task) => task.status !== 'done';
@@ -32,7 +33,7 @@ const stamp = (at) => `${new Date(at).toISOString().slice(0, 16).replace('T', '
32
33
  const director = (actor) => (actor.kind === 'dock' ? `Director of ${actor.station}` : 'Director');
33
34
  const line = (actor, text, at) => `${stamp(at)} ${actor.kind === 'agent' ? actor.name : director(actor)}: ${text}`;
34
35
  /** The fields a request may carry, checked one by one. A task is made with a title; a change has at least one field. */
35
- function validate(input, whole, isAgent) {
36
+ function validate(input, whole, isAgent, hasMission) {
36
37
  if (!isRecord(input))
37
38
  throw bad('request body must be a JSON object');
38
39
  const allowed = whole ? CREATE_FIELDS : PATCH_FIELDS;
@@ -42,7 +43,7 @@ function validate(input, whole, isAgent) {
42
43
  if (whole && input.title === undefined)
43
44
  throw bad('title is required', 'title');
44
45
  if (!whole && Object.keys(input).length === 0)
45
- throw bad('nothing to change: give a status, an assignee or a note');
46
+ throw bad('nothing to change: give a status, an assignee, a mission or a note');
46
47
  const out = {};
47
48
  if (input.title !== undefined) {
48
49
  const title = typeof input.title === 'string' ? input.title.trim() : '';
@@ -67,6 +68,14 @@ function validate(input, whole, isAgent) {
67
68
  }
68
69
  out.assignee = input.assignee;
69
70
  }
71
+ if (input.missionId !== undefined) {
72
+ if (input.missionId !== null && (typeof input.missionId !== 'string' || !MISSION_ID_RE.test(input.missionId) || !hasMission(input.missionId))) {
73
+ throw bad('missionId must be the id of a mission, or null', 'missionId');
74
+ }
75
+ if (whole && input.missionId === null)
76
+ throw bad('missionId must be the id of a mission', 'missionId');
77
+ out.missionId = input.missionId;
78
+ }
70
79
  if (input.note !== undefined) {
71
80
  // one line: the history is a list of lines
72
81
  const note = typeof input.note === 'string' ? input.note.replace(/\s+/g, ' ').trim() : '';
@@ -80,7 +89,7 @@ function validate(input, whole, isAgent) {
80
89
  function fromRecord(raw, at) {
81
90
  if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
82
91
  throw new Error('no valid id');
83
- const { id, title, detail, status, assignee, createdBy, createdAt, updatedAt, notes, handedOff } = raw;
92
+ const { id, title, detail, status, assignee, createdBy, createdAt, updatedAt, notes, handedOff, missionId } = raw;
84
93
  if (typeof title !== 'string' || title === '' || title.length > TASK_TITLE_MAX_CHARS)
85
94
  throw new Error('no valid title');
86
95
  if (typeof status !== 'string' || !TASK_STATUSES.includes(status))
@@ -96,6 +105,7 @@ function fromRecord(raw, at) {
96
105
  updatedAt: typeof updatedAt === 'number' ? updatedAt : at,
97
106
  notes: Array.isArray(notes) ? notes.filter((n) => typeof n === 'string').slice(-TASK_NOTES_MAX) : [],
98
107
  ...(typeof handedOff === 'string' && STATION_RE.test(handedOff) ? { handedOff } : {}),
108
+ ...(typeof missionId === 'string' && MISSION_ID_RE.test(missionId) ? { missionId } : {}),
99
109
  };
100
110
  }
101
111
  export function createTasks(options) {
@@ -118,10 +128,12 @@ export function createTasks(options) {
118
128
  await rename(tmp, path);
119
129
  });
120
130
  };
131
+ const hasMission = (id) => options.hasMission?.(id) ?? false;
121
132
  const list = () => tasks.map(copy);
122
133
  /** Tells the browsers and saves. */
123
134
  const changed = () => {
124
135
  options.emit(list());
136
+ options.afterChange?.(list());
125
137
  return save();
126
138
  };
127
139
  const find = (id) => {
@@ -187,7 +199,7 @@ export function createTasks(options) {
187
199
  },
188
200
  list,
189
201
  async create(actor, input) {
190
- const request = validate(input, true, options.isAgent);
202
+ const request = validate(input, true, options.isAgent, hasMission);
191
203
  if (tasks.filter(isOpen).length >= TASKS_OPEN_MAX)
192
204
  throw full();
193
205
  const at = now();
@@ -201,8 +213,9 @@ export function createTasks(options) {
201
213
  createdAt: at,
202
214
  updatedAt: at,
203
215
  notes: [],
216
+ ...(request.missionId === undefined || request.missionId === null ? {} : { missionId: request.missionId }),
204
217
  };
205
- task.notes.push(line(actor, task.assignee === null ? 'created' : `created; assigned to ${task.assignee}`, at));
218
+ task.notes.push(line(actor, `${task.assignee === null ? 'created' : `created; assigned to ${task.assignee}`}${task.missionId === undefined ? '' : `; mission ${task.missionId}`}`, at));
206
219
  tell(actor, task, at);
207
220
  seq += 1;
208
221
  tasks.push(task);
@@ -228,7 +241,7 @@ export function createTasks(options) {
228
241
  },
229
242
  async update(actor, id, input) {
230
243
  const task = find(id);
231
- const patch = validate(input, false, options.isAgent);
244
+ const patch = validate(input, false, options.isAgent, hasMission);
232
245
  const at = now();
233
246
  const next = copy(task);
234
247
  const parts = [];
@@ -242,6 +255,13 @@ export function createTasks(options) {
242
255
  next.assignee = patch.assignee;
243
256
  parts.push(patch.assignee === null ? 'unassigned' : `assigned to ${patch.assignee}`);
244
257
  }
258
+ if (patch.missionId !== undefined && (patch.missionId ?? undefined) !== task.missionId) {
259
+ if (patch.missionId === null)
260
+ delete next.missionId;
261
+ else
262
+ next.missionId = patch.missionId;
263
+ parts.push(patch.missionId === null ? 'unlinked from its mission' : `mission ${patch.missionId}`);
264
+ }
245
265
  if (patch.note !== undefined)
246
266
  parts.push(patch.note);
247
267
  if (parts.length === 0)
@@ -265,6 +285,22 @@ export function createTasks(options) {
265
285
  tasks = tasks.filter((x) => x !== task);
266
286
  await changed();
267
287
  },
288
+ async unlinkMission(missionId) {
289
+ const at = now();
290
+ let any = false;
291
+ tasks = tasks.map((t) => {
292
+ if (t.missionId !== missionId)
293
+ return t;
294
+ any = true;
295
+ const next = copy(t);
296
+ delete next.missionId;
297
+ next.notes.push(line({ kind: 'user' }, `unlinked: mission ${missionId} was removed`, at));
298
+ next.notes = next.notes.slice(-TASK_NOTES_MAX);
299
+ return next;
300
+ });
301
+ if (any)
302
+ await changed();
303
+ },
268
304
  close() {
269
305
  return chain.then(() => undefined);
270
306
  },
@@ -252,6 +252,7 @@ export function createUplinks(options) {
252
252
  }
253
253
  },
254
254
  list,
255
+ secretOf: (kind) => uplinks.find((u) => u.kind === kind && u.enabled)?.secret ?? null,
255
256
  async create(input) {
256
257
  const request = validate(input, true);
257
258
  const kind = request.kind ?? 'generic';
@@ -330,6 +331,12 @@ export function createUplinks(options) {
330
331
  // before the rate limit: what the agents never hear of (chatter in a channel) must not use up the deliveries of a minute
331
332
  if (made === null)
332
333
  return IGNORED;
334
+ // a button is not a message: it has its own limit (phone.ts), and the answer to Telegram is plain 200
335
+ if ('callback' in made) {
336
+ record(u, 'answered', 'a button of the phone was pressed');
337
+ options.press?.(u.secret, made.callback);
338
+ return { ok: true, answer: { ok: true } };
339
+ }
333
340
  if ('answer' in made) {
334
341
  record(u, 'answered', made.note);
335
342
  return { ok: true, answer: made.answer };
@@ -12,9 +12,12 @@ import { DOCK_ROUTES } from './docking.js';
12
12
  import { HANGAR_BODY_MAX_BYTES } from './hangar.js';
13
13
  import { createMcpHandler } from './mcp.js';
14
14
  import { parsePropellantRequest } from './propellant.js';
15
+ import { parsePricesRequest } from './prices.js';
16
+ import { PRICE_PREFIX_PATTERN } from '../shared/prices.js';
15
17
  const NO_PROPELLANT = {
16
18
  room: { used: { '5h': 0, day: 0, week: 0, month: 0 }, limits: {} },
17
19
  agents: {},
20
+ cost: { room: { usd: { '5h': 0, day: 0, week: 0, month: 0 }, unpriced: { '5h': 0, day: 0, week: 0, month: 0 }, budget: {} }, agents: {}, days: [], pricedSince: null },
18
21
  };
19
22
  const ERROR_STATUS = {
20
23
  bad_request: 400,
@@ -159,7 +162,7 @@ function commandProblem(command) {
159
162
  }
160
163
  }
161
164
  function parseHire(o) {
162
- const { name, role, dir, mode, confirmBypass, position, provider, command, payload, cleanRoom, model, keys } = o;
165
+ const { name, role, dir, mode, confirmBypass, position, provider, command, payload, cleanRoom, worktree, remoteControl, model, keys } = o;
163
166
  if (typeof name !== 'string')
164
167
  return fieldError('name', 'a string');
165
168
  if (typeof role !== 'string')
@@ -202,6 +205,16 @@ function parseHire(o) {
202
205
  return fieldError('cleanRoom', 'an object');
203
206
  value.cleanRoom = cleanRoom;
204
207
  }
208
+ if (worktree !== undefined) {
209
+ if (typeof worktree !== 'object' || worktree === null || Array.isArray(worktree))
210
+ return fieldError('worktree', 'an object');
211
+ value.worktree = worktree;
212
+ }
213
+ if (remoteControl !== undefined) {
214
+ if (typeof remoteControl !== 'object' || remoteControl === null || Array.isArray(remoteControl))
215
+ return fieldError('remoteControl', 'an object');
216
+ value.remoteControl = remoteControl;
217
+ }
205
218
  // The hub reads the text of a model and the inside of keys, and names the field that is wrong.
206
219
  if (model !== undefined) {
207
220
  if (typeof model !== 'string')
@@ -238,7 +251,11 @@ function parseGovernor(o) {
238
251
  function parseAnswer(o) {
239
252
  if (typeof o.go !== 'boolean')
240
253
  return fieldError('go', 'true or false');
241
- return { ok: true, value: { go: o.go } };
254
+ if (o.needSeq === undefined)
255
+ return { ok: true, value: { go: o.go } };
256
+ if (typeof o.needSeq !== 'number' || !Number.isSafeInteger(o.needSeq) || o.needSeq < 0)
257
+ return fieldError('needSeq', 'a whole number');
258
+ return { ok: true, value: { go: o.go, needSeq: o.needSeq } };
242
259
  }
243
260
  function parseEdit(o) {
244
261
  const value = {};
@@ -283,6 +300,16 @@ function parseEdit(o) {
283
300
  return fieldError('cleanRoom', 'an object or null');
284
301
  value.cleanRoom = o.cleanRoom;
285
302
  }
303
+ if (o.worktree !== undefined) {
304
+ if (o.worktree !== null && (typeof o.worktree !== 'object' || Array.isArray(o.worktree)))
305
+ return fieldError('worktree', 'an object or null');
306
+ value.worktree = o.worktree;
307
+ }
308
+ if (o.remoteControl !== undefined) {
309
+ if (o.remoteControl !== null && (typeof o.remoteControl !== 'object' || Array.isArray(o.remoteControl)))
310
+ return fieldError('remoteControl', 'an object or null');
311
+ value.remoteControl = o.remoteControl;
312
+ }
286
313
  if (o.model !== undefined) {
287
314
  if (o.model !== null && typeof o.model !== 'string')
288
315
  return fieldError('model', 'a string or null');
@@ -343,6 +370,7 @@ export function createWebServer(options) {
343
370
  hub,
344
371
  resolveToken: options.resolveToken,
345
372
  tasks: options.tasks,
373
+ missions: options.missions,
346
374
  missionLog: options.missionLog,
347
375
  board: options.board,
348
376
  liveries: options.liveries,
@@ -425,6 +453,7 @@ export function createWebServer(options) {
425
453
  schedules: options.schedules?.list() ?? [],
426
454
  uplinks: options.uplinks?.list() ?? [],
427
455
  tasks: options.tasks?.list() ?? [],
456
+ missions: options.missions?.list() ?? [],
428
457
  downlink: options.downlink?.view() ?? { unread: 0, items: [] },
429
458
  livery: options.liveries?.view(),
430
459
  docking: options.docking?.view(),
@@ -586,12 +615,67 @@ export function createWebServer(options) {
586
615
  sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
587
616
  return;
588
617
  }
589
- const view = await propellant.setLimits(parsed.value);
618
+ const { budget, ...limits } = parsed.value;
619
+ let view = propellant.view();
620
+ if (budget === undefined || Object.keys(limits).length > 0)
621
+ view = await propellant.setLimits(limits);
622
+ if (budget !== undefined) {
623
+ view = await propellant.setBudget(budget);
624
+ options.spendChanged?.();
625
+ }
590
626
  broadcast({ t: 'propellant', propellant: view });
591
627
  sendJson(res, 200, view);
592
628
  },
593
629
  };
594
630
  }
631
+ if (s[1] === 'prices' && s.length <= 3) {
632
+ const prices = options.prices;
633
+ if (!prices)
634
+ return null;
635
+ if (s.length === 2) {
636
+ return {
637
+ allow: ['GET', 'PUT'],
638
+ run: async (req, res) => {
639
+ if (req.method === 'GET') {
640
+ sendJson(res, 200, prices.view());
641
+ return;
642
+ }
643
+ const body = await jsonObject(req, res);
644
+ if (!body)
645
+ return;
646
+ const parsed = parsePricesRequest(body);
647
+ if (!parsed.ok) {
648
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
649
+ return;
650
+ }
651
+ const view = await prices.replace(parsed.models, typeof body.currency === 'string' ? body.currency : undefined);
652
+ // a price changed: the whole history is priced again
653
+ options.spendChanged?.();
654
+ if (options.propellant)
655
+ broadcast({ t: 'propellant', propellant: options.propellant.view() });
656
+ sendJson(res, 200, view);
657
+ },
658
+ };
659
+ }
660
+ return {
661
+ allow: ['DELETE'],
662
+ run: async (_req, res) => {
663
+ const prefix = s[2] ?? '';
664
+ if (!new RegExp(PRICE_PREFIX_PATTERN).test(prefix)) {
665
+ sendApiError(res, 400, 'invalid prefix', 'bad_request', 'prefix');
666
+ return;
667
+ }
668
+ if (!(await prices.remove(prefix))) {
669
+ sendApiError(res, 404, `no price of your own for "${prefix}"`, 'not_found');
670
+ return;
671
+ }
672
+ options.spendChanged?.();
673
+ if (options.propellant)
674
+ broadcast({ t: 'propellant', propellant: options.propellant.view() });
675
+ sendJson(res, 200, prices.view());
676
+ },
677
+ };
678
+ }
595
679
  if (s[1] === 'schedules' && s.length <= 4) {
596
680
  const schedules = options.schedules;
597
681
  if (!schedules)
@@ -737,6 +821,42 @@ export function createWebServer(options) {
737
821
  },
738
822
  };
739
823
  }
824
+ if (s[1] === 'missions' && s.length <= 3) {
825
+ const missions = options.missions;
826
+ if (!missions)
827
+ return null;
828
+ const director = { kind: 'user' };
829
+ if (s.length === 2) {
830
+ return {
831
+ allow: ['GET', 'POST'],
832
+ run: async (req, res) => {
833
+ if (req.method === 'GET') {
834
+ sendJson(res, 200, missions.list());
835
+ return;
836
+ }
837
+ const body = await jsonObject(req, res);
838
+ if (body)
839
+ sendJson(res, 201, await missions.create(director, body));
840
+ },
841
+ };
842
+ }
843
+ const id = s[2] ?? '';
844
+ return {
845
+ allow: ['PATCH', 'DELETE'],
846
+ run: async (req, res) => {
847
+ if (req.method === 'DELETE') {
848
+ const unlink = new URL(req.url ?? '/', 'http://localhost').searchParams.get('unlink') === '1';
849
+ await missions.remove(id, unlink);
850
+ res.writeHead(204);
851
+ res.end();
852
+ return;
853
+ }
854
+ const body = await jsonObject(req, res);
855
+ if (body)
856
+ sendJson(res, 200, await missions.update(director, id, body));
857
+ },
858
+ };
859
+ }
740
860
  if (s[1] === 'log' && s.length <= 3) {
741
861
  const missionLog = options.missionLog;
742
862
  if (!missionLog)
@@ -830,6 +950,22 @@ export function createWebServer(options) {
830
950
  }
831
951
  return { allow: ['DELETE'], run: async (_req, res) => sendJson(res, 200, await liveries.remove(s[2] ?? '')) };
832
952
  }
953
+ if (s[1] === 'models' && s.length <= 3) {
954
+ const models = options.models;
955
+ if (!models)
956
+ return null;
957
+ if (s.length === 2)
958
+ return { allow: ['GET'], run: (_req, res) => sendJson(res, 200, models.view()) };
959
+ return {
960
+ allow: ['PUT'],
961
+ run: async (req, res) => {
962
+ const body = await jsonObject(req, res);
963
+ // the router has decoded the segment already: decoding again made a lone % throw (a 500)
964
+ if (body)
965
+ sendJson(res, 200, await models.set(s[2] ?? '', body.model));
966
+ },
967
+ };
968
+ }
833
969
  if (s[1] === 'relay' && s.length <= 4) {
834
970
  const relay = options.relay;
835
971
  if (!relay)
@@ -848,7 +984,7 @@ export function createWebServer(options) {
848
984
  }
849
985
  const body = await jsonObject(req, res);
850
986
  if (body)
851
- sendJson(res, 200, await (name === 'forward' ? relay.forward(body) : relay.set(name, body)));
987
+ sendJson(res, 200, await (name === 'forward' ? relay.forward(body) : name === 'phone' ? relay.setPhone(body) : relay.set(name, body)));
852
988
  },
853
989
  };
854
990
  }
@@ -929,9 +1065,18 @@ export function createWebServer(options) {
929
1065
  if (name === null)
930
1066
  return;
931
1067
  if (req.method === 'DELETE') {
1068
+ const choice = new URL(req.url ?? '/', 'http://localhost').searchParams.get('worktree');
1069
+ if (choice !== null && choice !== 'keep' && choice !== 'delete')
1070
+ return sendApiError(res, 400, 'worktree is keep or delete', 'bad_request', 'worktree');
1071
+ const discard = choice === 'delete' && options.worktrees?.has(name) === true ? options.worktrees : null;
932
1072
  await hub.remove(name);
933
- res.writeHead(204);
934
- res.end();
1073
+ // the console is gone either way: a refusal of git is an answer, not an error
1074
+ if (discard === null) {
1075
+ res.writeHead(204);
1076
+ res.end();
1077
+ }
1078
+ else
1079
+ sendJson(res, 200, { worktree: await discard.discard(name) });
935
1080
  return;
936
1081
  }
937
1082
  const body = await jsonObject(req, res);
@@ -977,6 +1122,20 @@ export function createWebServer(options) {
977
1122
  },
978
1123
  };
979
1124
  }
1125
+ if (s.length === 4 && s[3] === 'worktree' && options.worktrees) {
1126
+ const worktrees = options.worktrees;
1127
+ return {
1128
+ allow: ['GET'],
1129
+ run: async (_req, res) => {
1130
+ const name = agentName(res, s[2]);
1131
+ if (name === null)
1132
+ return;
1133
+ if (!worktrees.has(name))
1134
+ return sendNotFound(res, 'that agent has no worktree');
1135
+ sendJson(res, 200, await worktrees.status(name));
1136
+ },
1137
+ };
1138
+ }
980
1139
  if (s.length === 4 && s[3] === 'telemetry') {
981
1140
  return {
982
1141
  allow: ['GET'],
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Worktrees (docs/worktrees-spec.md): one git worktree and branch for an agent, shared by Clean Room (which puts a container on it)
3
+ * and by a plain worktree (the agent starts in it on the host). This file reads the setting, runs git, makes the worktree once
4
+ * and finds it again, and works out where the agent starts below it. gonogo never uses --force, -D or prune --expire.
5
+ */
6
+ import { execFile } from 'node:child_process';
7
+ import { mkdir, realpath, stat } from 'node:fs/promises';
8
+ import { dirname, join, relative } from 'node:path';
9
+ import { cleanRoomBranch, WORKTREE_DIR } from '../shared/protocol.js';
10
+ import { CLEAN_ROOM_COMMAND_MS, DIR_MODE, GIT_BIN } from './constants.js';
11
+ export const messageOf = (error) => (error instanceof Error ? error.message : String(error));
12
+ /** The one reader of a worktree setting: the hub uses it for hire and edit, home.ts for the roster file. `{}` is the only value for now. */
13
+ export function parseWorktree(value) {
14
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
15
+ return { ok: false, error: 'worktree must be an object' };
16
+ const unknown = Object.keys(value).find((key) => value[key] !== undefined);
17
+ if (unknown !== undefined)
18
+ return { ok: false, error: `worktree has no field "${unknown}"` };
19
+ return { ok: true, worktree: {} };
20
+ }
21
+ /** The branch of an agent's worktree: the same for a plain worktree and a Clean Room, so an agent switched from one to the other keeps its work. */
22
+ export const worktreeBranch = cleanRoomBranch;
23
+ /** Where a plain worktree is: <home>/worktrees/<name>. */
24
+ export const worktreePath = (home, name) => join(home, WORKTREE_DIR, name);
25
+ /** Runs a program without a shell and answers its output. A failure is an Error whose text is the first line the program printed on stderr. */
26
+ export function run(file, args, env) {
27
+ return new Promise((resolve, reject) => {
28
+ execFile(file, args, { env: env, timeout: CLEAN_ROOM_COMMAND_MS, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
29
+ if (error === null)
30
+ return resolve(stdout);
31
+ const code = error.code;
32
+ const line = stderr.split('\n').find((l) => l.trim() !== '')?.trim() ?? error.message.split('\n')[0] ?? '';
33
+ reject(new Error(code === 'ENOENT' ? `${file} was not found on PATH` : line.slice(0, 300)));
34
+ });
35
+ });
36
+ }
37
+ /** The top folder of the git repository that holds `dir`; `why` starts the error text ("Clean Room needs", "a worktree needs"). */
38
+ export async function topOf(dir, env, why) {
39
+ try {
40
+ return (await run(GIT_BIN, ['-C', dir, 'rev-parse', '--show-toplevel'], env)).trim();
41
+ }
42
+ catch (error) {
43
+ throw new Error(`${why} the directory to be inside a git repository: ${messageOf(error)}`);
44
+ }
45
+ }
46
+ /** What the hub asks at hire and edit for a plain worktree: null when `dir` is in a git repository, else why not. */
47
+ export async function checkWorktree(dir, env) {
48
+ try {
49
+ await topOf(dir, env, 'a worktree needs');
50
+ return null;
51
+ }
52
+ catch (error) {
53
+ return messageOf(error);
54
+ }
55
+ }
56
+ /** Makes the worktree on its branch the first time and finds it again after that. A folder in its place that git does not know is an error, never reused. */
57
+ export async function ensureWorktree(repo, path, branch, env) {
58
+ const git = (...args) => run(GIT_BIN, ['-C', repo, ...args], env);
59
+ const real = await realpath(path).catch(() => null);
60
+ if (real !== null) {
61
+ const listed = (await git('worktree', 'list', '--porcelain')).split('\n').filter((l) => l.startsWith('worktree ')).map((l) => l.slice(9));
62
+ if (!(await Promise.all(listed.map((p) => realpath(p).catch(() => p)))).includes(real)) {
63
+ throw new Error(`${path} exists but is not a worktree of ${repo}; move it away or give the agent a folder of the repository it was made for`);
64
+ }
65
+ return;
66
+ }
67
+ await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });
68
+ try {
69
+ await git('worktree', 'prune'); // a worktree whose folder was deleted still holds its branch
70
+ const known = await git('show-ref', '--verify', '--quiet', `refs/heads/${branch}`).then(() => true, () => false);
71
+ await git('worktree', 'add', ...(known ? [path, branch] : ['-b', branch, path]));
72
+ }
73
+ catch (error) {
74
+ throw new Error(`could not make the worktree ${path} on ${branch}: ${messageOf(error)}`);
75
+ }
76
+ }
77
+ /** Where an agent starts: the same folder below the worktree as `dir` has below the repository's top. Throws when that folder is not committed. */
78
+ export async function cwdInWorktree(top, worktree, dir) {
79
+ const inside = relative(top, await realpath(dir));
80
+ const cwd = join(worktree, inside);
81
+ if (!(await stat(cwd).then((info) => info.isDirectory(), () => false))) {
82
+ throw new Error(`${inside} is not in the worktree ${worktree}: the worktree is a copy of the last commit, and that folder is not committed`);
83
+ }
84
+ return cwd;
85
+ }
86
+ /** A plain worktree for a start: made or found, and the folder to start in. */
87
+ export async function prepareWorktree(agent, homeDir, env) {
88
+ const top = await realpath(await topOf(agent.dir, env, 'a worktree needs'));
89
+ const worktree = worktreePath(homeDir, agent.name);
90
+ const branch = worktreeBranch(agent.name);
91
+ await ensureWorktree(top, worktree, branch, env);
92
+ return { worktree, branch, cwd: await cwdInWorktree(top, worktree, agent.dir) };
93
+ }
94
+ /** The folder of the repository that a worktree belongs to (the one that holds its `.git`), or null when there is none. */
95
+ async function mainRepoOf(path, env) {
96
+ try {
97
+ const common = (await run(GIT_BIN, ['-C', path, 'rev-parse', '--path-format=absolute', '--git-common-dir'], env)).trim();
98
+ return dirname(common);
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
104
+ /** What the Director wants to know before he deletes a worktree. Never throws for a missing folder. */
105
+ export async function worktreeStatus(path, branch, env) {
106
+ const empty = { path, branch, exists: false, dirty: false, ahead: 0, merged: false };
107
+ if (!(await stat(path).then((info) => info.isDirectory(), () => false)))
108
+ return empty;
109
+ const repo = await mainRepoOf(path, env);
110
+ if (repo === null)
111
+ return { ...empty, exists: true };
112
+ const git = (...args) => run(GIT_BIN, ['-C', repo, ...args], env);
113
+ const dirty = (await run(GIT_BIN, ['-C', path, 'status', '--porcelain'], env).catch(() => '')).trim() !== '';
114
+ const ahead = Number((await git('rev-list', '--count', `HEAD..${branch}`).catch(() => '0')).trim()) || 0;
115
+ const merged = (await git('branch', '--merged', 'HEAD', '--list', branch).catch(() => '')).trim() !== '';
116
+ return { path, branch, exists: true, dirty, ahead, merged };
117
+ }
118
+ /** `git worktree remove` without --force, then `git branch -d`: git refuses a dirty folder and an unmerged branch, and so does gonogo. */
119
+ export async function removeWorktree(path, branch, env) {
120
+ const repo = await mainRepoOf(path, env);
121
+ if (repo === null)
122
+ return { removed: false, branchDeleted: false, reason: `${path} is not a worktree of a repository` };
123
+ const git = (...args) => run(GIT_BIN, ['-C', repo, ...args], env);
124
+ try {
125
+ await git('worktree', 'remove', path);
126
+ }
127
+ catch (error) {
128
+ return { removed: false, branchDeleted: false, reason: messageOf(error) };
129
+ }
130
+ try {
131
+ await git('branch', '-d', branch);
132
+ }
133
+ catch (error) {
134
+ return { removed: true, branchDeleted: false, reason: messageOf(error) };
135
+ }
136
+ return { removed: true, branchDeleted: true };
137
+ }
@@ -7,6 +7,14 @@ export function tokenText(n) {
7
7
  return `${+(n / 1000).toFixed(1)}k`;
8
8
  return `${+(n / 1_000_000).toFixed(1)}M`;
9
9
  }
10
+ /** "12", "$12.40", "1.5k" (a dollar sign, spaces and commas ignored) to dollars in whole cents; null when it is not from 0.01 to 1,000,000. */
11
+ export function parseMoney(text) {
12
+ const m = /^\$?(\d+(?:\.\d{1,2})?)([kK]?)$/.exec(text.replace(/[\s,_]/g, ''));
13
+ if (!m)
14
+ return null;
15
+ const usd = Math.round(Number(m[1]) * (m[2] === '' ? 1 : 1000) * 100) / 100;
16
+ return usd >= 0.01 && usd <= 1_000_000 ? usd : null;
17
+ }
10
18
  /** "2000000", "500k", "1.5M" (any case, spaces and commas ignored) to whole tokens; null when it is not a positive amount. */
11
19
  export function parseTokens(text) {
12
20
  const m = /^(\d+(?:\.\d+)?)([kKmM]?)$/.exec(text.replace(/[\s,_]/g, ''));
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Prices of models in dollars per million tokens, and what a split of tokens costs (docs/cost-spec.md). Pure: no file, no network.
3
+ *
4
+ * The defaults are copied by hand from Anthropic's pricing page (https://platform.claude.com/docs/en/about-claude/pricing, the
5
+ * "Model pricing" table) on PRICES_AS_OF; the owner's `~/.gonogo/prices.json` wins over them. Cache writes are the 5-minute
6
+ * column; cache reads are the page's "cache hits" column as printed. The page's cache-read ratio is not the same for every model
7
+ * (0.1x of input for most, 0.05x for Opus 5.5 and Sonnet 5.5, 0.025x for Fable 5.2 and 5.1), so each row below is the printed
8
+ * number, not a formula. Not modelled: the 1-hour cache write, Haiku 5.5 above 100,000 prompt tokens, batch and per-call fees.
9
+ * Mythos models are left out (limited availability).
10
+ *
11
+ * A model that matches no row is unpriced: its tokens are shown, never costed. A default row matches only its own id, with a
12
+ * date (`-20260101`), `-latest` or `[1m]` after it: a newer model that merely starts with the same letters (`claude-sonnet-5-6`)
13
+ * is not guessed to cost the same. Your own rows are prefixes, as you type them.
14
+ */
15
+ export const PRICES_AS_OF = '2026-11-18';
16
+ const p = (input, cacheWrite, cacheRead, output) => ({ input, output, cacheWrite, cacheRead });
17
+ /** Model id (or your prefix) to its list price. */
18
+ export const DEFAULT_PRICES = {
19
+ 'claude-fable-5-2': p(8, 10, 0.2, 40),
20
+ 'claude-fable-5-1': p(10, 12.5, 0.25, 50),
21
+ 'claude-fable-5': p(10, 12.5, 1, 50),
22
+ 'claude-opus-5-5': p(4, 5, 0.2, 20),
23
+ 'claude-opus-5': p(5, 6.25, 0.5, 25),
24
+ 'claude-opus-4-8': p(5, 6.25, 0.5, 25),
25
+ 'claude-opus-4-7': p(5, 6.25, 0.5, 25),
26
+ 'claude-opus-4-6': p(5, 6.25, 0.5, 25),
27
+ 'claude-opus-4-5': p(5, 6.25, 0.5, 25),
28
+ 'claude-opus-4-1': p(15, 18.75, 1.5, 75),
29
+ 'claude-opus-4': p(15, 18.75, 1.5, 75),
30
+ 'claude-sonnet-5-5': p(2, 2.5, 0.1, 10),
31
+ 'claude-sonnet-5': p(2, 2.5, 0.2, 10),
32
+ 'claude-sonnet-4-6': p(3, 3.75, 0.3, 15),
33
+ 'claude-sonnet-4-5': p(3, 3.75, 0.3, 15),
34
+ 'claude-sonnet-4': p(3, 3.75, 0.3, 15),
35
+ 'claude-haiku-5-5': p(0.1, 0.125, 0.01, 0.5),
36
+ 'claude-haiku-4-5': p(1, 1.25, 0.1, 5),
37
+ };
38
+ /** A prefix as the table and the routes accept it. */
39
+ export const PRICE_PREFIX_PATTERN = '^[A-Za-z0-9._-]{1,80}$';
40
+ export const PRICE_MAX = 10_000;
41
+ /** The default table, then the owner's rows over it. */
42
+ export function mergePrices(file = {}) {
43
+ const rows = {};
44
+ for (const [prefix, price] of Object.entries(DEFAULT_PRICES))
45
+ rows[prefix] = { ...price, source: 'default', asOf: PRICES_AS_OF };
46
+ for (const [prefix, price] of Object.entries(file))
47
+ rows[prefix] = { ...price, source: 'file' };
48
+ return rows;
49
+ }
50
+ /** The price of a model by the longest matching prefix, or null (unpriced). */
51
+ export function priceFor(table, model) {
52
+ if (!model)
53
+ return null;
54
+ let best = null;
55
+ for (const [prefix, row] of Object.entries(table)) {
56
+ if (!model.startsWith(prefix))
57
+ continue;
58
+ // a built-in row is one model, not a family: only a date, -latest or [1m] may follow it
59
+ if ('source' in row && row.source === 'default' && !/^(-\d{8}|-latest)?(\[1m\])?$/.test(model.slice(prefix.length)))
60
+ continue;
61
+ if (best === null || prefix.length > best.length)
62
+ best = prefix;
63
+ }
64
+ return best === null ? null : (table[best] ?? null);
65
+ }
66
+ /** Dollars for a split at a price. Not rounded: round to a cent only to show it. */
67
+ export function costOf(split, price) {
68
+ return (split.i * price.input + split.cw * price.cacheWrite + split.o * price.output + split.cr * price.cacheRead) / 1_000_000;
69
+ }
70
+ /** Dollars as people read them: $0.42, $12.40, $1.2k. */
71
+ export function moneyText(usd) {
72
+ if (usd < 1000)
73
+ return `$${usd.toFixed(2)}`;
74
+ return `$${+(usd / 1000).toFixed(1)}k`;
75
+ }