@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
@@ -9,11 +9,15 @@ import { AGENT_NAME_PATTERN, CLEAN_ROOM_HOST, MAX_COLS, MAX_REST_BODY_BYTES, MAX
9
9
  import { bearerToken, createHookHandler, hubErrorInfo, isRecord, readBody, sendApiError, sendJson, sendMethodNotAllowed, sendNotFound, sendText, sendUnauthorized, } from './hooks.js';
10
10
  import { readCustomCommand } from './command.js';
11
11
  import { DOCK_ROUTES } from './docking.js';
12
+ import { HANGAR_BODY_MAX_BYTES } from './hangar.js';
12
13
  import { createMcpHandler } from './mcp.js';
13
14
  import { parsePropellantRequest } from './propellant.js';
15
+ import { parsePricesRequest } from './prices.js';
16
+ import { PRICE_PREFIX_PATTERN } from '../shared/prices.js';
14
17
  const NO_PROPELLANT = {
15
18
  room: { used: { '5h': 0, day: 0, week: 0, month: 0 }, limits: {} },
16
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 },
17
21
  };
18
22
  const ERROR_STATUS = {
19
23
  bad_request: 400,
@@ -158,7 +162,7 @@ function commandProblem(command) {
158
162
  }
159
163
  }
160
164
  function parseHire(o) {
161
- const { name, role, dir, mode, confirmBypass, position, provider, command, payload, cleanRoom } = o;
165
+ const { name, role, dir, mode, confirmBypass, position, provider, command, payload, cleanRoom, worktree, remoteControl, model, keys } = o;
162
166
  if (typeof name !== 'string')
163
167
  return fieldError('name', 'a string');
164
168
  if (typeof role !== 'string')
@@ -201,6 +205,27 @@ function parseHire(o) {
201
205
  return fieldError('cleanRoom', 'an object');
202
206
  value.cleanRoom = cleanRoom;
203
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
+ }
218
+ // The hub reads the text of a model and the inside of keys, and names the field that is wrong.
219
+ if (model !== undefined) {
220
+ if (typeof model !== 'string')
221
+ return fieldError('model', 'a string');
222
+ value.model = model;
223
+ }
224
+ if (keys !== undefined) {
225
+ if (!isRecord(keys))
226
+ return fieldError('keys', 'an object');
227
+ value.keys = keys;
228
+ }
204
229
  return { ok: true, value };
205
230
  }
206
231
  function parsePoll(o) {
@@ -210,6 +235,11 @@ function parsePoll(o) {
210
235
  return fieldError('agents', 'a list of names');
211
236
  value.agents = o.agents;
212
237
  }
238
+ if (o.subject !== undefined) {
239
+ if (typeof o.subject !== 'string')
240
+ return fieldError('subject', 'text');
241
+ value.subject = o.subject;
242
+ }
213
243
  return { ok: true, value };
214
244
  }
215
245
  function parseGovernor(o) {
@@ -221,7 +251,11 @@ function parseGovernor(o) {
221
251
  function parseAnswer(o) {
222
252
  if (typeof o.go !== 'boolean')
223
253
  return fieldError('go', 'true or false');
224
- 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 } };
225
259
  }
226
260
  function parseEdit(o) {
227
261
  const value = {};
@@ -266,6 +300,26 @@ function parseEdit(o) {
266
300
  return fieldError('cleanRoom', 'an object or null');
267
301
  value.cleanRoom = o.cleanRoom;
268
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
+ }
313
+ if (o.model !== undefined) {
314
+ if (o.model !== null && typeof o.model !== 'string')
315
+ return fieldError('model', 'a string or null');
316
+ value.model = o.model;
317
+ }
318
+ if (o.keys !== undefined) {
319
+ if (!isRecord(o.keys))
320
+ return fieldError('keys', 'an object');
321
+ value.keys = o.keys;
322
+ }
269
323
  return { ok: true, value };
270
324
  }
271
325
  function parseUserMessage(o) {
@@ -316,8 +370,11 @@ export function createWebServer(options) {
316
370
  hub,
317
371
  resolveToken: options.resolveToken,
318
372
  tasks: options.tasks,
373
+ missions: options.missions,
319
374
  missionLog: options.missionLog,
375
+ board: options.board,
320
376
  liveries: options.liveries,
377
+ relief: options.relief,
321
378
  log: log.child('mcp'),
322
379
  version: () => options.info().version,
323
380
  });
@@ -396,9 +453,12 @@ export function createWebServer(options) {
396
453
  schedules: options.schedules?.list() ?? [],
397
454
  uplinks: options.uplinks?.list() ?? [],
398
455
  tasks: options.tasks?.list() ?? [],
456
+ missions: options.missions?.list() ?? [],
399
457
  downlink: options.downlink?.view() ?? { unread: 0, items: [] },
400
458
  livery: options.liveries?.view(),
401
459
  docking: options.docking?.view(),
460
+ relief: options.relief?.view(),
461
+ rollout: options.rollout?.view(),
402
462
  });
403
463
  const sendHubError = (res, e) => {
404
464
  const info = hubErrorInfo(e);
@@ -412,8 +472,8 @@ export function createWebServer(options) {
412
472
  const hasBody = (req) => req.headers['transfer-encoding'] !== undefined || Number(req.headers['content-length'] ?? 0) > 0;
413
473
  const isJsonRequest = (req) => (req.headers['content-type'] ?? '').split(';')[0]?.trim().toLowerCase() === 'application/json';
414
474
  /** The JSON object in the body, or null after the error answer went out. */
415
- const jsonObject = async (req, res) => {
416
- const body = await readBody(req, MAX_REST_BODY_BYTES);
475
+ const jsonObject = async (req, res, limit = MAX_REST_BODY_BYTES) => {
476
+ const body = await readBody(req, limit);
417
477
  if (!body.ok) {
418
478
  if (body.reason === 'too_large')
419
479
  sendApiError(res, 413, 'request body too large', 'too_large');
@@ -440,10 +500,59 @@ export function createWebServer(options) {
440
500
  sendNotFound(res, 'unknown agent');
441
501
  return null;
442
502
  };
503
+ /** /api/agents/<name>/files, file and git: Hangar and Recorder. The query is read here; the checks of the path are theirs. */
504
+ const matchWorkspace = (s) => {
505
+ const { hangar, recorder } = options;
506
+ const query = (req) => new URL(req.url ?? '/', 'http://localhost').searchParams;
507
+ const run = (res, work) => {
508
+ const name = agentName(res, s[2]);
509
+ if (name !== null)
510
+ return work(name).then((answer) => sendJson(res, 200, answer));
511
+ };
512
+ if (hangar && s.length === 4 && s[3] === 'files') {
513
+ return { allow: ['GET'], run: (req, res) => run(res, (name) => hangar.list(name, query(req).get('path') ?? '')) };
514
+ }
515
+ if (hangar && s.length === 4 && s[3] === 'file') {
516
+ return {
517
+ allow: ['GET', 'PUT', 'POST'],
518
+ run: async (req, res) => {
519
+ if (req.method === 'GET')
520
+ return run(res, (name) => hangar.read(name, query(req).get('path') ?? ''));
521
+ const body = await jsonObject(req, res, HANGAR_BODY_MAX_BYTES);
522
+ if (body)
523
+ await run(res, (name) => (req.method === 'PUT' ? hangar.save(name, body) : hangar.create(name, body)));
524
+ },
525
+ };
526
+ }
527
+ if (recorder && s[3] === 'git' && s.length === 4)
528
+ return { allow: ['GET'], run: (_req, res) => run(res, (name) => recorder.status(name)) };
529
+ if (recorder && s[3] === 'git' && s.length === 5 && s[4] === 'log')
530
+ return { allow: ['GET'], run: (_req, res) => run(res, (name) => recorder.log(name)) };
531
+ if (recorder && s[3] === 'git' && s.length === 5 && s[4] === 'diff') {
532
+ return { allow: ['GET'], run: (req, res) => run(res, (name) => recorder.diff(name, query(req).get('path') ?? '', query(req).get('staged') === '1')) };
533
+ }
534
+ if (recorder && s[3] === 'git' && s.length === 5 && s[4] === 'commit') {
535
+ return {
536
+ allow: ['POST'],
537
+ run: async (req, res) => {
538
+ const body = await jsonObject(req, res);
539
+ if (body)
540
+ await run(res, (name) => recorder.commit(name, body));
541
+ },
542
+ };
543
+ }
544
+ return null;
545
+ };
443
546
  const matchApi = (s) => {
444
547
  if (s.length === 2 && s[1] === 'state') {
445
548
  return { allow: ['GET'], run: (_req, res) => sendJson(res, 200, snapshot()) };
446
549
  }
550
+ if (s.length === 2 && s[1] === 'engines') {
551
+ const engines = options.engines;
552
+ if (!engines)
553
+ return null;
554
+ return { allow: ['GET'], run: async (_req, res) => sendJson(res, 200, await engines()) };
555
+ }
447
556
  if (s.length === 2 && s[1] === 'agents') {
448
557
  return {
449
558
  allow: ['POST'],
@@ -506,12 +615,67 @@ export function createWebServer(options) {
506
615
  sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
507
616
  return;
508
617
  }
509
- 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
+ }
510
626
  broadcast({ t: 'propellant', propellant: view });
511
627
  sendJson(res, 200, view);
512
628
  },
513
629
  };
514
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
+ }
515
679
  if (s[1] === 'schedules' && s.length <= 4) {
516
680
  const schedules = options.schedules;
517
681
  if (!schedules)
@@ -657,6 +821,42 @@ export function createWebServer(options) {
657
821
  },
658
822
  };
659
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
+ }
660
860
  if (s[1] === 'log' && s.length <= 3) {
661
861
  const missionLog = options.missionLog;
662
862
  if (!missionLog)
@@ -676,6 +876,8 @@ export function createWebServer(options) {
676
876
  };
677
877
  }
678
878
  const id = s[2] ?? '';
879
+ if (id === 'chart')
880
+ return { allow: ['GET'], run: (_req, res) => sendJson(res, 200, missionLog.chart()) };
679
881
  return {
680
882
  allow: ['GET', 'PUT', 'DELETE'],
681
883
  run: async (req, res) => {
@@ -695,6 +897,29 @@ export function createWebServer(options) {
695
897
  },
696
898
  };
697
899
  }
900
+ if (s[1] === 'board' && s.length === 2) {
901
+ const board = options.board;
902
+ if (!board)
903
+ return null;
904
+ return {
905
+ allow: ['GET', 'PUT'],
906
+ run: async (req, res) => {
907
+ if (req.method === 'GET') {
908
+ sendJson(res, 200, board.get());
909
+ return;
910
+ }
911
+ const body = await jsonObject(req, res);
912
+ if (body)
913
+ sendJson(res, 200, await board.write('user', body));
914
+ },
915
+ };
916
+ }
917
+ if (s[1] === 'black-box' && s.length === 2) {
918
+ const blackBox = options.blackBox;
919
+ if (!blackBox)
920
+ return null;
921
+ return { allow: ['GET'], run: (_req, res) => sendJson(res, 200, blackBox.view()) };
922
+ }
698
923
  if (s[1] === 'liveries' || s[1] === 'livery') {
699
924
  const liveries = options.liveries;
700
925
  if (!liveries)
@@ -725,6 +950,22 @@ export function createWebServer(options) {
725
950
  }
726
951
  return { allow: ['DELETE'], run: async (_req, res) => sendJson(res, 200, await liveries.remove(s[2] ?? '')) };
727
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
+ }
728
969
  if (s[1] === 'relay' && s.length <= 4) {
729
970
  const relay = options.relay;
730
971
  if (!relay)
@@ -743,10 +984,22 @@ export function createWebServer(options) {
743
984
  }
744
985
  const body = await jsonObject(req, res);
745
986
  if (body)
746
- 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)));
747
988
  },
748
989
  };
749
990
  }
991
+ if (s[1] === 'relief' && s.length <= 4) {
992
+ const relief = options.relief;
993
+ if (!relief)
994
+ return null;
995
+ if (s.length === 2)
996
+ return { allow: ['GET'], run: async (_req, res) => sendJson(res, 200, relief.view()) };
997
+ // browser token only, like every /api route: an agent's token never reaches here, so the boss cannot answer its own request
998
+ if (s.length !== 4 || (s[3] !== 'go' && s[3] !== 'no-go'))
999
+ return null;
1000
+ const verdict = s[3];
1001
+ return { allow: ['POST'], run: async (_req, res) => sendJson(res, 200, await relief.decide(s[2] ?? '', verdict, { kind: 'user' })) };
1002
+ }
750
1003
  if (s[1] === 'downlink' && s.length <= 3) {
751
1004
  const downlink = options.downlink;
752
1005
  if (!downlink)
@@ -801,6 +1054,9 @@ export function createWebServer(options) {
801
1054
  }
802
1055
  if (s[1] !== 'agents')
803
1056
  return null;
1057
+ const workspace = s.length >= 4 ? matchWorkspace(s) : null;
1058
+ if (workspace)
1059
+ return workspace;
804
1060
  if (s.length === 3) {
805
1061
  return {
806
1062
  allow: ['PATCH', 'DELETE'],
@@ -809,9 +1065,18 @@ export function createWebServer(options) {
809
1065
  if (name === null)
810
1066
  return;
811
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;
812
1072
  await hub.remove(name);
813
- res.writeHead(204);
814
- 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) });
815
1080
  return;
816
1081
  }
817
1082
  const body = await jsonObject(req, res);
@@ -836,13 +1101,48 @@ export function createWebServer(options) {
836
1101
  },
837
1102
  };
838
1103
  }
839
- if (s.length === 4 && s[3] === 'resume') {
1104
+ if (s.length === 4 && (s[3] === 'memory' || s[3] === 'reflect') && options.massBudget) {
1105
+ const massBudget = options.massBudget;
1106
+ return {
1107
+ allow: [s[3] === 'memory' ? 'GET' : 'POST'],
1108
+ run: async (_req, res) => {
1109
+ const name = agentName(res, s[2]);
1110
+ if (name !== null)
1111
+ sendJson(res, s[3] === 'memory' ? 200 : 201, await (s[3] === 'memory' ? massBudget.view(name) : massBudget.reflect(name)));
1112
+ },
1113
+ };
1114
+ }
1115
+ if (s.length === 4 && (s[3] === 'resume' || s[3] === 'hold')) {
840
1116
  return {
841
1117
  allow: ['POST'],
842
1118
  run: (_req, res) => {
843
1119
  const name = agentName(res, s[2]);
844
1120
  if (name !== null)
845
- sendJson(res, 200, hub.resume(name));
1121
+ sendJson(res, 200, s[3] === 'hold' ? hub.hold(name) : hub.resume(name));
1122
+ },
1123
+ };
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
+ }
1139
+ if (s.length === 4 && s[3] === 'telemetry') {
1140
+ return {
1141
+ allow: ['GET'],
1142
+ run: (_req, res) => {
1143
+ const name = agentName(res, s[2]);
1144
+ if (name !== null)
1145
+ sendJson(res, 200, { calls: options.telemetry?.calls(name) ?? [] });
846
1146
  },
847
1147
  };
848
1148
  }
@@ -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, ''));
@@ -202,7 +202,7 @@ export const BUILTIN_LIVERIES = [
202
202
  slug: 'instrument',
203
203
  name: 'Instrument',
204
204
  description: 'The default: a warm grey device with a small green screen.',
205
- // the values of base.css and shell.css (a test keeps them equal)
205
+ // the values of tokens.css (a test keeps every livery that ships equal to its block there)
206
206
  tokens: {
207
207
  '--body': '#e4e2dc',
208
208
  '--panel': '#f1f0ec',
@@ -9,7 +9,7 @@ export const POSITIONS = [
9
9
  'You are FLIGHT, the flight director of this team. The Director (the human, the recipient "user") briefs you with goals.',
10
10
  'Split each goal into tasks, find the right position with list_roster, and send each task with send_message: a clear subject and a self-contained body (paths, what done looks like).',
11
11
  'Before a large or risky step, ask the Director for a go or no-go. When a position reports back, check the result and tell the Director the outcome in a few lines.',
12
- 'If no position fits, tell the Director which kind to hire. You cannot hire or remove agents yourself.',
12
+ 'If no position fits, ask the Director for one with hire_agent (a name, a position or a role, a folder, a mode up to acceptEdits): it only makes a request, he sees every field and decides, and you get his answer as a message. You cannot hire or remove agents yourself.',
13
13
  'Send anything risky (spending money, deleting data, changing scope) to "user" and wait for the answer.',
14
14
  ].join(' '),
15
15
  },