@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
@@ -5,7 +5,8 @@
5
5
  * A transcript is JSON lines; an assistant line carries `message.usage`, and one reply is written as several lines (one
6
6
  * per content block) that repeat the same `message.id` and the same usage, so only the first line of an id counts.
7
7
  * Tokens = input + cache creation + output. Cache reads are left out: in a long session they dwarf the rest and would
8
- * make every limit meaningless.
8
+ * make every limit meaningless. The ledger also keeps the split per model (i, cw, o, cr) so the use can be priced when the view
9
+ * is built (docs/cost-spec.md); an old line without a model counts for tokens and shows as unpriced.
9
10
  *
10
11
  * shortcut: subagent (Task tool) transcripts are other files and are not counted; read them too if that spend matters.
11
12
  * shortcut: the ledger and the limits are keyed by agent name, so a rename starts from zero; key by record id if renames get common.
@@ -14,16 +15,22 @@ import { appendFile, open, readFile, realpath, rename, writeFile } from 'node:fs
14
15
  import { join, sep } from 'node:path';
15
16
  import { randomBytes } from 'node:crypto';
16
17
  import { AGENT_NAME_PATTERN, FUEL_WINDOWS } from '../shared/protocol.js';
18
+ import { moneyText, costOf, mergePrices, priceFor } from '../shared/prices.js';
17
19
  import { tokenText } from '../shared/fuel.js';
18
- import { FILE_MODE, FUEL_KEEP_MS, FUEL_LIMIT_MAX, METER_READ_MAX_BYTES, PROPELLANT_FILE as LIMITS_FILE } from './constants.js';
20
+ import { BUDGET_MAX_USD, FILE_MODE, FUEL_KEEP_MS, FUEL_LIMIT_MAX, METER_READ_MAX_BYTES, PROPELLANT_FILE as LIMITS_FILE } from './constants.js';
19
21
  const HOUR = 3_600_000;
20
22
  export const WINDOW_MS = { '5h': 5 * HOUR, day: 24 * HOUR, week: 7 * 24 * HOUR, month: 30 * 24 * HOUR };
21
23
  const LEDGER_FILE = 'fuel.jsonl';
22
24
  const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
25
+ /** Dollar budgets per window, and the share of a budget at which Downlink is told. */
26
+ const WARN_AT = 0.8;
27
+ const DAYS_SHOWN = 14;
28
+ const WINDOW_LABEL = { '5h': '5 h', day: '24 h', week: '7 d', month: '30 d' };
29
+ const WINDOW_NAME = { '5h': '5-hour', day: 'day', week: 'week', month: 'month' };
23
30
  function isRecord(value) {
24
31
  return typeof value === 'object' && value !== null && !Array.isArray(value);
25
32
  }
26
- /** The tokens of one transcript line and its message id, or null for a line without usage. */
33
+ /** The tokens of one transcript line, its model and its split, and its message id, or null for a line without usage. */
27
34
  export function lineUsage(line) {
28
35
  let value;
29
36
  try {
@@ -43,7 +50,26 @@ export function lineUsage(line) {
43
50
  return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0;
44
51
  };
45
52
  const at = typeof value.timestamp === 'string' ? Date.parse(value.timestamp) : NaN;
46
- return { id, at: Number.isFinite(at) ? at : null, tokens: n('input_tokens') + n('cache_creation_input_tokens') + n('output_tokens') };
53
+ const split = { i: n('input_tokens'), cw: n('cache_creation_input_tokens'), o: n('output_tokens'), cr: n('cache_read_input_tokens') };
54
+ const model = typeof value.message.model === 'string' && value.message.model !== '' ? value.message.model.slice(0, 120) : null;
55
+ return { id, at: Number.isFinite(at) ? at : null, tokens: split.i + split.cw + split.o, model, split };
56
+ }
57
+ /** Budgets from untrusted JSON: dollars in whole cents from 0.01 to BUDGET_MAX_USD per known window, or null; anything else is refused. */
58
+ export function parseBudget(value, what) {
59
+ if (!isRecord(value))
60
+ return `${what} must be an object of windows (${FUEL_WINDOWS.join(', ')})`;
61
+ const budget = {};
62
+ for (const [key, v] of Object.entries(value)) {
63
+ if (!FUEL_WINDOWS.includes(key))
64
+ return `${what}: unknown window "${key}"`;
65
+ if (v === null)
66
+ continue;
67
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0.01 || v > BUDGET_MAX_USD || Math.abs(v * 100 - Math.round(v * 100)) > 1e-6) {
68
+ return `${what}.${key} must be dollars in whole cents from 0.01 to ${BUDGET_MAX_USD}, or null`;
69
+ }
70
+ budget[key] = Math.round(v * 100) / 100;
71
+ }
72
+ return budget;
47
73
  }
48
74
  /** Limits from untrusted JSON: whole numbers from 1 to FUEL_LIMIT_MAX per known window; anything else is refused. */
49
75
  export function parseLimits(value, what) {
@@ -65,7 +91,7 @@ export function parseLimits(value, what) {
65
91
  export function parsePropellantRequest(body) {
66
92
  const value = {};
67
93
  for (const key of Object.keys(body)) {
68
- if (key !== 'room' && key !== 'agents')
94
+ if (key !== 'room' && key !== 'agents' && key !== 'budget')
69
95
  return { ok: false, error: `unknown field "${key}"`, field: key };
70
96
  }
71
97
  if (body.room !== undefined) {
@@ -87,6 +113,35 @@ export function parsePropellantRequest(body) {
87
113
  value.agents[name] = limits;
88
114
  }
89
115
  }
116
+ if (body.budget !== undefined) {
117
+ if (!isRecord(body.budget))
118
+ return { ok: false, error: 'budget must be an object with room and agents', field: 'budget' };
119
+ for (const key of Object.keys(body.budget)) {
120
+ if (key !== 'room' && key !== 'agents')
121
+ return { ok: false, error: `budget: unknown field "${key}"`, field: 'budget' };
122
+ }
123
+ const budget = {};
124
+ if (body.budget.room !== undefined) {
125
+ const room = parseBudget(body.budget.room, 'budget.room');
126
+ if (typeof room === 'string')
127
+ return { ok: false, error: room, field: 'budget' };
128
+ budget.room = room;
129
+ }
130
+ if (body.budget.agents !== undefined) {
131
+ if (!isRecord(body.budget.agents))
132
+ return { ok: false, error: 'budget.agents must be an object of agent names', field: 'budget' };
133
+ budget.agents = {};
134
+ for (const [name, raw] of Object.entries(body.budget.agents)) {
135
+ if (!NAME_RE.test(name))
136
+ return { ok: false, error: `budget.agents: invalid name "${name}"`, field: 'budget' };
137
+ const b = parseBudget(raw, `budget.agents.${name}`);
138
+ if (typeof b === 'string')
139
+ return { ok: false, error: b, field: 'budget' };
140
+ budget.agents[name] = b;
141
+ }
142
+ }
143
+ value.budget = budget;
144
+ }
90
145
  return { ok: true, value };
91
146
  }
92
147
  export { tokenText };
@@ -95,7 +150,10 @@ export function createPropellant(options) {
95
150
  const ledgerPath = join(dir, LEDGER_FILE);
96
151
  const limitsPath = join(dir, LIMITS_FILE);
97
152
  let entries = [];
98
- let saved = { room: {}, agents: {}, cursors: {} };
153
+ const saved = { room: {}, agents: {}, budget: { room: {}, agents: {} }, cursors: {} };
154
+ const priceTable = options.prices ?? (() => mergePrices());
155
+ /** Scopes (agent or room, and window) that already told Downlink they are at 80 %; cleared when the window drops below it. */
156
+ const warned = new Set();
99
157
  /** The last message id counted per transcript: the repeated lines of one reply follow each other. */
100
158
  const lastId = new Map();
101
159
  /** One read per transcript at a time, and the ledger and limits file written in order. */
@@ -109,7 +167,7 @@ export function createPropellant(options) {
109
167
  };
110
168
  const saveLimits = () => {
111
169
  // a file from before it had a version has none and reads as version 1 (src/server/migrate.ts)
112
- const json = JSON.stringify({ version: 1, ...saved }, null, 2);
170
+ const json = JSON.stringify({ version: 1, ...saved, budget: saved.budget }, null, 2);
113
171
  return later(async () => {
114
172
  const tmp = join(dir, `.${LIMITS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
115
173
  await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
@@ -134,6 +192,113 @@ export function createPropellant(options) {
134
192
  }
135
193
  return { used, limits: { ...limits } };
136
194
  };
195
+ /** Dollars and unpriced tokens of one ledger line at the current prices. */
196
+ const priced = (e, table) => {
197
+ const price = e.model === undefined ? null : priceFor(table, e.model);
198
+ if (price === null)
199
+ return { usd: 0, unpriced: e.tokens };
200
+ return { usd: costOf({ i: e.i ?? 0, cw: e.cw ?? 0, o: e.o ?? 0, cr: e.cr ?? 0 }, price), unpriced: 0 };
201
+ };
202
+ const costGauge = (agent, budget, table) => {
203
+ const t = now();
204
+ const usd = { '5h': 0, day: 0, week: 0, month: 0 };
205
+ const unpriced = { '5h': 0, day: 0, week: 0, month: 0 };
206
+ for (const e of entries) {
207
+ if (agent !== null && e.agent !== agent)
208
+ continue;
209
+ const p = priced(e, table);
210
+ for (const w of FUEL_WINDOWS) {
211
+ if (t - e.at >= WINDOW_MS[w])
212
+ continue;
213
+ usd[w] += p.usd;
214
+ unpriced[w] += p.unpriced;
215
+ }
216
+ }
217
+ return { usd, unpriced, budget: { ...budget } };
218
+ };
219
+ const dayKey = (at) => {
220
+ const d = new Date(at);
221
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
222
+ };
223
+ /** The last DAYS_SHOWN local calendar days, oldest first, each with its dollars per agent. */
224
+ const days = (table) => {
225
+ const out = new Map();
226
+ const today = new Date(now());
227
+ for (let k = DAYS_SHOWN - 1; k >= 0; k--) {
228
+ const date = dayKey(new Date(today.getFullYear(), today.getMonth(), today.getDate() - k, 12).getTime());
229
+ out.set(date, { date, usd: 0, unpriced: 0, byAgent: {} });
230
+ }
231
+ for (const e of entries) {
232
+ const day = out.get(dayKey(e.at));
233
+ if (day === undefined)
234
+ continue;
235
+ const p = priced(e, table);
236
+ day.usd += p.usd;
237
+ day.unpriced += p.unpriced;
238
+ if (p.usd > 0)
239
+ day.byAgent[e.agent] = (day.byAgent[e.agent] ?? 0) + p.usd;
240
+ }
241
+ return [...out.values()];
242
+ };
243
+ const costView = () => {
244
+ const table = priceTable();
245
+ const agents = {};
246
+ const names = new Set([...entries.map((e) => e.agent), ...Object.keys(saved.agents), ...Object.keys(saved.budget.agents)]);
247
+ for (const name of [...names].sort())
248
+ agents[name] = costGauge(name, saved.budget.agents[name] ?? {}, table);
249
+ const modelled = entries.filter((e) => e.model !== undefined).map((e) => e.at);
250
+ return {
251
+ room: costGauge(null, saved.budget.room, table),
252
+ agents,
253
+ days: days(table),
254
+ pricedSince: modelled.length === 0 ? null : Math.min(...modelled),
255
+ };
256
+ };
257
+ /** The first window whose spend has reached its budget, with the numbers for the reason text. */
258
+ const budgetOver = (g) => {
259
+ for (const w of FUEL_WINDOWS) {
260
+ const limit = g.budget[w];
261
+ if (limit !== undefined && g.usd[w] >= limit)
262
+ return { window: w, spent: g.usd[w], limit };
263
+ }
264
+ return null;
265
+ };
266
+ /** Every scope with a budget and its share spent per window. */
267
+ const shares = () => {
268
+ const table = priceTable();
269
+ const out = [];
270
+ const scopes = [['room', 'the room', costGauge(null, saved.budget.room, table)]];
271
+ for (const name of Object.keys(saved.budget.agents))
272
+ scopes.push([`agent:${name}`, name, costGauge(name, saved.budget.agents[name] ?? {}, table)]);
273
+ for (const [scope, who, g] of scopes) {
274
+ for (const w of FUEL_WINDOWS) {
275
+ const limit = g.budget[w];
276
+ if (limit !== undefined)
277
+ out.push({ key: `${scope}|${w}`, who, window: w, share: g.usd[w] / limit });
278
+ }
279
+ }
280
+ return out;
281
+ };
282
+ /** Drops the warning of a scope that fell below 80 % so it can warn again. */
283
+ const rearm = () => {
284
+ if (warned.size === 0)
285
+ return;
286
+ const live = new Map(shares().map((x) => [x.key, x.share]));
287
+ for (const key of [...warned])
288
+ if ((live.get(key) ?? 0) < WARN_AT)
289
+ warned.delete(key);
290
+ };
291
+ /** One Downlink event per scope and window when a budget reaches 80 %, until it drops below again. quiet: remember only. */
292
+ const warn = (quiet) => {
293
+ rearm();
294
+ for (const x of shares()) {
295
+ if (x.share < WARN_AT || warned.has(x.key))
296
+ continue;
297
+ warned.add(x.key);
298
+ if (!quiet)
299
+ options.notify?.('redline', `${x.who} is at ${Math.floor(x.share * 100)} % of its ${WINDOW_NAME[x.window]} budget`);
300
+ }
301
+ };
137
302
  const firstOver = (g) => {
138
303
  for (const w of FUEL_WINDOWS) {
139
304
  const limit = g.limits[w];
@@ -157,6 +322,7 @@ export function createPropellant(options) {
157
322
  }
158
323
  const handle = await open(path, 'r');
159
324
  let tokens = 0;
325
+ let reads = 0;
160
326
  try {
161
327
  const size = (await handle.stat()).size;
162
328
  let offset = saved.cursors[path] ?? 0;
@@ -171,21 +337,33 @@ export function createPropellant(options) {
171
337
  if (end < 0)
172
338
  return 0; // no complete line yet
173
339
  const fresh = [];
340
+ const byKey = new Map();
174
341
  for (const line of buffer.subarray(0, end).toString('utf8').split('\n')) {
175
342
  const usage = lineUsage(line);
176
343
  if (usage === null || usage.id === lastId.get(path))
177
344
  continue;
178
345
  lastId.set(path, usage.id);
179
- if (usage.tokens === 0)
346
+ const { split } = usage;
347
+ if (usage.tokens === 0 && split.cr === 0)
180
348
  continue;
181
349
  const at = usage.at ?? now();
182
- // one ledger line per minute and agent keeps the file small
183
- const last = fresh[fresh.length - 1];
184
- if (last && Math.floor(last.at / 60_000) === Math.floor(at / 60_000))
350
+ // one ledger line per minute, agent and model keeps the file small
351
+ const key = `${Math.floor(at / 60_000)}|${usage.model ?? ''}`;
352
+ const last = byKey.get(key);
353
+ if (last) {
185
354
  last.tokens += usage.tokens;
186
- else
187
- fresh.push({ at, agent, tokens: usage.tokens });
355
+ last.i = (last.i ?? 0) + split.i;
356
+ last.cw = (last.cw ?? 0) + split.cw;
357
+ last.o = (last.o ?? 0) + split.o;
358
+ last.cr = (last.cr ?? 0) + split.cr;
359
+ }
360
+ else {
361
+ const entry = usage.model === null ? { at, agent, tokens: usage.tokens } : { at, agent, model: usage.model, i: split.i, cw: split.cw, o: split.o, cr: split.cr, tokens: usage.tokens };
362
+ byKey.set(key, entry);
363
+ fresh.push(entry);
364
+ }
188
365
  tokens += usage.tokens;
366
+ reads += split.cr;
189
367
  }
190
368
  saved.cursors[path] = offset + end + 1;
191
369
  const cut = now() - FUEL_KEEP_MS;
@@ -196,11 +374,12 @@ export function createPropellant(options) {
196
374
  await later(() => appendFile(ledgerPath, text, { mode: FILE_MODE }));
197
375
  }
198
376
  await saveLimits();
377
+ warn(false);
199
378
  }
200
379
  finally {
201
380
  await handle.close();
202
381
  }
203
- return tokens;
382
+ return tokens + reads;
204
383
  };
205
384
  const view = () => {
206
385
  prune();
@@ -208,7 +387,8 @@ export function createPropellant(options) {
208
387
  const names = new Set([...entries.map((e) => e.agent), ...Object.keys(saved.agents)]);
209
388
  for (const name of [...names].sort())
210
389
  agents[name] = gauge(name, saved.agents[name] ?? {});
211
- return { room: gauge(null, saved.room), agents };
390
+ rearm();
391
+ return { room: gauge(null, saved.room), agents, cost: costView() };
212
392
  };
213
393
  return {
214
394
  async load() {
@@ -225,6 +405,18 @@ export function createPropellant(options) {
225
405
  saved.agents[name] = limits;
226
406
  }
227
407
  }
408
+ if (isRecord(data.budget)) {
409
+ const room = parseBudget(data.budget.room ?? {}, 'budget.room');
410
+ if (typeof room !== 'string')
411
+ saved.budget.room = room;
412
+ if (isRecord(data.budget.agents)) {
413
+ for (const [name, raw] of Object.entries(data.budget.agents)) {
414
+ const b = parseBudget(raw, name);
415
+ if (NAME_RE.test(name) && typeof b !== 'string')
416
+ saved.budget.agents[name] = b;
417
+ }
418
+ }
419
+ }
228
420
  if (isRecord(data.cursors)) {
229
421
  for (const [path, n] of Object.entries(data.cursors)) {
230
422
  if (typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)
@@ -250,7 +442,15 @@ export function createPropellant(options) {
250
442
  continue;
251
443
  try {
252
444
  const e = JSON.parse(line);
253
- if (isRecord(e) && typeof e.at === 'number' && typeof e.agent === 'string' && typeof e.tokens === 'number' && e.tokens > 0) {
445
+ if (!isRecord(e) || typeof e.at !== 'number' || typeof e.agent !== 'string' || typeof e.tokens !== 'number')
446
+ continue;
447
+ const count = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
448
+ if (typeof e.model === 'string' && e.model !== '') {
449
+ const entry = { at: e.at, agent: e.agent, tokens: count(e.tokens), model: e.model, i: count(e.i), cw: count(e.cw), o: count(e.o), cr: count(e.cr) };
450
+ if (entry.tokens > 0 || (entry.cr ?? 0) > 0)
451
+ entries.push(entry);
452
+ }
453
+ else if (e.tokens > 0) {
254
454
  entries.push({ at: e.at, agent: e.agent, tokens: e.tokens });
255
455
  }
256
456
  }
@@ -262,6 +462,8 @@ export function createPropellant(options) {
262
462
  const kept = entries.map((e) => JSON.stringify(e)).join('\n');
263
463
  await later(() => writeFile(ledgerPath, kept === '' ? '' : kept + '\n', { mode: FILE_MODE }));
264
464
  }
465
+ // what is already past 80 % at start was told before: remember it, do not tell again
466
+ warn(true);
265
467
  },
266
468
  record(agent, transcriptPath) {
267
469
  const previous = reading.get(transcriptPath) ?? Promise.resolve(0);
@@ -292,6 +494,22 @@ export function createPropellant(options) {
292
494
  await saveLimits();
293
495
  return view();
294
496
  },
497
+ recheck() {
498
+ warn(false);
499
+ },
500
+ async setBudget(budget) {
501
+ if (budget.room !== undefined)
502
+ saved.budget.room = { ...budget.room };
503
+ for (const [name, b] of Object.entries(budget.agents ?? {})) {
504
+ if (Object.keys(b).length === 0)
505
+ delete saved.budget.agents[name];
506
+ else
507
+ saved.budget.agents[name] = { ...b };
508
+ }
509
+ await saveLimits();
510
+ warn(false);
511
+ return view();
512
+ },
295
513
  over(agent) {
296
514
  const own = gauge(agent, saved.agents[agent] ?? {});
297
515
  const ownWindow = firstOver(own);
@@ -299,12 +517,21 @@ export function createPropellant(options) {
299
517
  const limit = own.limits[ownWindow] ?? 0;
300
518
  return { scope: 'agent', reason: `out of propellant: ${tokenText(own.used[ownWindow])} of ${tokenText(limit)} tokens in ${ownWindow}` };
301
519
  }
520
+ const table = priceTable();
521
+ const ownCost = budgetOver(costGauge(agent, saved.budget.agents[agent] ?? {}, table));
522
+ if (ownCost !== null) {
523
+ return { scope: 'agent', reason: `out of propellant: ${agent} spent ${moneyText(ownCost.spent)} of ${moneyText(ownCost.limit)} in ${WINDOW_LABEL[ownCost.window]}` };
524
+ }
302
525
  const room = gauge(null, saved.room);
303
526
  const roomWindow = firstOver(room);
304
527
  if (roomWindow !== null) {
305
528
  const limit = room.limits[roomWindow] ?? 0;
306
529
  return { scope: 'room', reason: `room out of propellant: ${tokenText(room.used[roomWindow])} of ${tokenText(limit)} tokens in ${roomWindow}` };
307
530
  }
531
+ const roomCost = budgetOver(costGauge(null, saved.budget.room, table));
532
+ if (roomCost !== null) {
533
+ return { scope: 'room', reason: `room out of propellant: the room spent ${moneyText(roomCost.spent)} of ${moneyText(roomCost.limit)} in ${WINDOW_LABEL[roomCost.window]}` };
534
+ }
308
535
  return null;
309
536
  },
310
537
  close() {
@@ -4,10 +4,11 @@
4
4
  * needs in the agent's own folder; what the hub does with the CLI (hooks or output activity, mail or none) is
5
5
  * PROVIDER_INFO in protocol.ts. Nothing here touches the owner's project or the CLI's own home folder.
6
6
  */
7
+ import { execFile } from 'node:child_process';
7
8
  import { accessSync, constants as fsConstants, statSync } from 'node:fs';
8
9
  import { delimiter, join } from 'node:path';
9
10
  import { MCP_SERVER_NAME, PROVIDER_INFO, PROVIDERS } from '../shared/protocol.js';
10
- import { HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_PATH } from './constants.js';
11
+ import { ENGINE_VERSION_CHARS, ENGINE_VERSION_MS, HOOK_PATH_PREFIX, HOOK_TIMEOUT_S, MCP_PATH } from './constants.js';
11
12
  /** Gemini CLI hook event to the hub's own hook event: the hub handles both CLIs with one set of rules. */
12
13
  export const GEMINI_HOOKS = {
13
14
  BeforeAgent: 'UserPromptSubmit',
@@ -57,6 +58,54 @@ export function buildGeminiSettings(ctx, node = process.execPath) {
57
58
  hooks,
58
59
  };
59
60
  }
61
+ // unused until a per-agent hooks.json location is verified (docs/facts/antigravity.md)
62
+ /**
63
+ * Antigravity CLI (agy) hook event to the hub's own. Written from the vendor's hook page (docs/facts/antigravity.md), not from a run.
64
+ * PreInvocation is the nearest of agy's events to a submitted prompt; its stdin carries `lastUserInput`.
65
+ */
66
+ export const AGY_HOOKS = {
67
+ PreInvocation: 'UserPromptSubmit',
68
+ PreToolUse: 'PreToolUse',
69
+ PostToolUse: 'PostToolUse',
70
+ Stop: 'Stop',
71
+ };
72
+ export const AGY_HOOKS_FILE = 'agy-hooks.json';
73
+ export const AGY_MODES = {
74
+ default: [],
75
+ acceptEdits: ['--mode', 'accept-edits'],
76
+ auto: ['--mode', 'auto'],
77
+ bypassPermissions: ['--dangerously-skip-permissions'],
78
+ };
79
+ /**
80
+ * agy runs command hooks too: JSON on stdin in camelCase, JSON on stdout. This is HOOK_SHIM for it: it maps lastUserInput to
81
+ * prompt and toolCall.name and args to tool_name and tool_input, sends a PostToolUse that has an `error` to PostToolUseFailure,
82
+ * and turns the hub's Stop block into agy's Stop continue (the only decision that keeps agy going). A PreToolUse must answer
83
+ * with a decision, so it says allow; any failure prints {} (a Stop or PostToolUse then lets agy go on).
84
+ * No single quote inside: it is passed in single quotes.
85
+ */
86
+ export const AGY_HOOK_SHIM = [
87
+ 'let d="";process.stdin.on("data",c=>d+=c).on("end",async()=>{let u=process.argv[1];const pre=u.endsWith("/PreToolUse");try{',
88
+ 'const i=JSON.parse(d||"{}"),b={},c=i.toolCall&&typeof i.toolCall==="object"?i.toolCall:{};',
89
+ 'if(i.lastUserInput!==undefined)b.prompt=i.lastUserInput;',
90
+ 'if(c.name!==undefined)b.tool_name=c.name;if(c.args!==undefined)b.tool_input=c.args;',
91
+ 'if(i.error&&u.endsWith("/PostToolUse"))u+="Failure";',
92
+ 'const t=require("fs").readFileSync(process.argv[2],"utf8").trim();',
93
+ 'const r=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},',
94
+ `body:JSON.stringify(b),signal:AbortSignal.timeout(${HOOK_TIMEOUT_S * 1000})});`,
95
+ 'const a=r.ok?JSON.parse(await r.text()):{};',
96
+ 'process.stdout.write(JSON.stringify(a.decision==="block"?{decision:"continue",reason:a.reason}:pre?{decision:"allow"}:{}))',
97
+ '}catch{process.stdout.write(pre?"{\\"decision\\":\\"allow\\"}":"{}")}})',
98
+ ].join('');
99
+ /** hooks.json for agy: the tool events take a matcher wrapper (every tool), the others a plain handler list. Its timeout is in seconds. */
100
+ export function buildAgyHooks(ctx, node = process.execPath) {
101
+ const hooks = {};
102
+ for (const [event, ours] of Object.entries(AGY_HOOKS)) {
103
+ const url = `${ctx.hubUrl}${HOOK_PATH_PREFIX}${ctx.name}/${ours}`;
104
+ const handler = { type: 'command', command: [node, '-e', AGY_HOOK_SHIM, url, ctx.tokenFile].map(shellQuote).join(' '), timeout: HOOK_TIMEOUT_S + 1 };
105
+ hooks[event] = event === 'PreToolUse' || event === 'PostToolUse' ? [{ matcher: '*', hooks: [handler] }] : [handler];
106
+ }
107
+ return hooks;
108
+ }
60
109
  /** The MCP entry for a CLI that reads Claude's mcp.json shape but may not expand variables: the token is written in. */
61
110
  function mcpJson(ctx, extra = {}) {
62
111
  const server = { type: 'http', url: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: `Bearer ${ctx.token}` }, ...extra };
@@ -68,14 +117,20 @@ function mcpJson(ctx, extra = {}) {
68
117
  */
69
118
  export function buildProviderStart(provider, ctx) {
70
119
  const file = (name) => join(ctx.agentDir, name);
120
+ // Every engine with a model setting takes `--model <name>` (PROVIDER_INFO.model); the name is one argument, never a shell word.
121
+ const model = ctx.model ? ['--model', ctx.model] : [];
71
122
  switch (provider) {
72
123
  case 'gemini':
73
124
  // GEMINI_CLI_SYSTEM_SETTINGS_PATH is read before the owner's ~/.gemini settings and wins over them; their login stays.
74
125
  return {
75
- args: ['--approval-mode', GEMINI_MODES[ctx.mode], ...(ctx.seed ? ['--skip-trust'] : []), '--prompt-interactive', ctx.roleText],
126
+ args: ['--approval-mode', GEMINI_MODES[ctx.mode], ...(ctx.seed ? ['--skip-trust'] : []), ...model, '--prompt-interactive', ctx.roleText],
76
127
  env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: file(GEMINI_SETTINGS_FILE) },
77
128
  files: { [GEMINI_SETTINGS_FILE]: JSON.stringify(buildGeminiSettings(ctx), null, 2) },
78
129
  };
130
+ case 'antigravity':
131
+ // No hooks and no gonogo tools yet (see PROVIDER_INFO): a terminal with a lamp that knows the mode, the model and its role.
132
+ // The role alone, without the preamble about tools it does not have. -i runs it as the first prompt and stays interactive.
133
+ return { args: [...AGY_MODES[ctx.mode], ...model, '-i', ctx.role], env: {}, files: {} };
79
134
  case 'codex':
80
135
  // -c overrides config.toml for this run only, so CODEX_HOME (and the owner's login in it) stays as it is.
81
136
  return {
@@ -85,6 +140,7 @@ export function buildProviderStart(provider, ctx) {
85
140
  '-c',
86
141
  `mcp_servers.${MCP_SERVER_NAME}.bearer_token_env_var="GONOGO_TOKEN"`,
87
142
  ...CODEX_MODES[ctx.mode],
143
+ ...model,
88
144
  ctx.roleText,
89
145
  ],
90
146
  env: {},
@@ -100,22 +156,25 @@ export function buildProviderStart(provider, ctx) {
100
156
  },
101
157
  };
102
158
  case 'kimi':
103
- return { args: ['--mcp-config-file', file('kimi-mcp.json')], env: {}, files: { 'kimi-mcp.json': mcpJson(ctx) } };
159
+ return { args: ['--mcp-config-file', file('kimi-mcp.json'), ...model], env: {}, files: { 'kimi-mcp.json': mcpJson(ctx) } };
104
160
  case 'copilot':
105
161
  return { args: ['--additional-mcp-config', `@${file('copilot-mcp.json')}`], env: {}, files: { 'copilot-mcp.json': mcpJson(ctx, { tools: ['*'] }) } };
106
162
  case 'pi':
107
163
  // pi reads MCP servers only from its own files, so it gets no gonogo tools: the role alone, without the preamble about them.
108
- return { args: ['--append-system-prompt', ctx.role], env: {}, files: {} };
164
+ return { args: ['--append-system-prompt', ctx.role, ...model], env: {}, files: {} };
165
+ case 'cursor':
166
+ return { args: model, env: {}, files: {} };
109
167
  case 'qwen':
110
168
  case 'grok':
111
169
  case 'crush':
112
- case 'cursor':
113
170
  // No documented per-session MCP config and no checked way to pass a role: a terminal with a lamp, started by name.
114
171
  return { args: [], env: {}, files: {} };
115
172
  }
116
173
  }
117
- /** Whether `name` is an executable file in one of the PATH directories (moved here from cli.ts). */
118
- export function onPath(name, pathVar) {
174
+ /** The path of `name` when it is an executable file in one of the PATH directories, else null. */
175
+ export function findOnPath(name, pathVar) {
176
+ if (name === '')
177
+ return null;
119
178
  for (const dir of (pathVar ?? '').split(delimiter)) {
120
179
  if (dir === '')
121
180
  continue;
@@ -123,13 +182,68 @@ export function onPath(name, pathVar) {
123
182
  const file = join(dir, name);
124
183
  accessSync(file, fsConstants.X_OK);
125
184
  if (statSync(file).isFile())
126
- return true;
185
+ return file;
127
186
  }
128
187
  catch {
129
188
  // not in this directory
130
189
  }
131
190
  }
132
- return false;
191
+ return null;
192
+ }
193
+ /** Whether `name` is an executable file in one of the PATH directories (moved here from cli.ts). */
194
+ export const onPath = (name, pathVar) => findOnPath(name, pathVar) !== null;
195
+ // A terminal sequence (colour, title) whole, then what is left of control, C1 and text-direction characters: the line goes to a terminal and a web page.
196
+ const TERMINAL_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?)/g;
197
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
198
+ /** Pad Check: the first line a program prints for `--version`, with terminal sequences and control characters taken out and cut short. */
199
+ export const versionLine = (output) => {
200
+ const line = output.split('\n').map((l) => l.replace(TERMINAL_SEQUENCE, '').replace(CONTROL, '').trim()).find((l) => l !== '');
201
+ return line === undefined ? null : line.slice(0, ENGINE_VERSION_CHARS);
202
+ };
203
+ /** Versions already read, by path and modification time: a program that was updated is asked again, one that failed is asked every time. */
204
+ const versionCache = new Map();
205
+ /**
206
+ * `<file> --version`, no shell, a few seconds at most, and an environment of PATH, HOME and LANG only, so that no key or token of
207
+ * gonogo's environment reaches a program that is merely asked its version. null when it did not answer or printed nothing.
208
+ */
209
+ async function versionOf(file, env) {
210
+ const key = `${file}\0${statSync(file).mtimeMs}`;
211
+ const known = versionCache.get(key);
212
+ if (known !== undefined)
213
+ return known;
214
+ const output = await new Promise((done) => {
215
+ execFile(file, ['--version'], { timeout: ENGINE_VERSION_MS, maxBuffer: 64 * 1024, env: { PATH: env.PATH, HOME: env.HOME, LANG: env.LANG, NO_COLOR: '1' } }, (error, stdout) => done(error === null ? stdout : ''));
216
+ });
217
+ const line = versionLine(output);
218
+ if (line !== null)
219
+ versionCache.set(key, line);
220
+ return line;
221
+ }
222
+ /** Pad Check: every engine but the custom command, where it was found and what it calls itself. Runs nothing but `--version`; never installs. */
223
+ export function checkEngines(env) {
224
+ return Promise.all(PROVIDERS.filter((provider) => provider !== 'custom').map(async (provider) => {
225
+ const { label, bin, install, docs } = PROVIDER_INFO[provider];
226
+ const path = findOnPath(bin, env.PATH);
227
+ return { provider, label, bin, path, version: path === null ? null : await versionOf(path, env).catch(() => null), install, docs };
228
+ }));
229
+ }
230
+ /** What `gonogo doctor` prints: one line per engine, and under a missing one the vendor's install command to copy. */
231
+ export function formatDoctor(checks, agentCmd) {
232
+ const lines = ['gonogo doctor: which agent CLIs are on the PATH', ''];
233
+ for (const check of checks) {
234
+ if (check.path !== null) {
235
+ lines.push(`ok ${check.label} (${check.bin}) ${check.version ?? 'no version printed'} ${check.path}`);
236
+ continue;
237
+ }
238
+ lines.push(`-- ${check.label} (${check.bin}) not found`);
239
+ lines.push(check.install === null ? ` no install command was checked; see ${check.docs}` : ` install: ${check.install}`);
240
+ if (check.install !== null)
241
+ lines.push(` docs: ${check.docs}`);
242
+ }
243
+ if (agentCmd !== null)
244
+ lines.push('', `GONOGO_AGENT_CMD is set (${agentCmd}): it replaces claude.`);
245
+ lines.push('', 'gonogo never runs an install command: copy the one you want.');
246
+ return lines.join('\n') + '\n';
133
247
  }
134
248
  /** ServerInfo.installed: what the hire form lists first. GONOGO_AGENT_CMD stands in for claude. */
135
249
  export function installedProviders(path, agentCmd) {