@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.
- package/dist/client/assets/index-DxUnpGbS.js +52 -0
- package/dist/client/assets/index-tpcmltjw.css +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/audited.js +26 -3
- package/dist/server/cleanroom.js +7 -51
- package/dist/server/cli.js +87 -19
- package/dist/server/constants.js +15 -2
- package/dist/server/hangar.js +4 -4
- package/dist/server/home.js +17 -1
- package/dist/server/hub.js +102 -9
- package/dist/server/launcher.js +17 -10
- package/dist/server/mcp.js +41 -2
- package/dist/server/migrate.js +2 -1
- package/dist/server/missions.js +310 -0
- package/dist/server/models.js +73 -0
- package/dist/server/phone.js +122 -0
- package/dist/server/phonetag.js +47 -0
- package/dist/server/prices.js +112 -0
- package/dist/server/propellant.js +243 -16
- package/dist/server/providers.js +52 -0
- package/dist/server/relay.js +53 -7
- package/dist/server/relaykinds.js +11 -1
- package/dist/server/relief.js +2 -2
- package/dist/server/remotecontrol.js +15 -0
- package/dist/server/tasks.js +44 -8
- package/dist/server/uplinks.js +7 -0
- package/dist/server/web.js +165 -6
- package/dist/server/worktree.js +137 -0
- package/dist/shared/fuel.js +8 -0
- package/dist/shared/prices.js +75 -0
- package/dist/shared/protocol.js +16 -3
- package/package.json +1 -1
- package/dist/client/assets/index-BqCn1SM7.js +0 -50
- package/dist/client/assets/index-KZtFVMJG.css +0 -1
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
183
|
-
const
|
|
184
|
-
|
|
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
|
-
|
|
187
|
-
|
|
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
|
-
|
|
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)
|
|
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() {
|
package/dist/server/providers.js
CHANGED
|
@@ -58,6 +58,54 @@ export function buildGeminiSettings(ctx, node = process.execPath) {
|
|
|
58
58
|
hooks,
|
|
59
59
|
};
|
|
60
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
|
+
}
|
|
61
109
|
/** The MCP entry for a CLI that reads Claude's mcp.json shape but may not expand variables: the token is written in. */
|
|
62
110
|
function mcpJson(ctx, extra = {}) {
|
|
63
111
|
const server = { type: 'http', url: `${ctx.hubUrl}${MCP_PATH}`, headers: { Authorization: `Bearer ${ctx.token}` }, ...extra };
|
|
@@ -79,6 +127,10 @@ export function buildProviderStart(provider, ctx) {
|
|
|
79
127
|
env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: file(GEMINI_SETTINGS_FILE) },
|
|
80
128
|
files: { [GEMINI_SETTINGS_FILE]: JSON.stringify(buildGeminiSettings(ctx), null, 2) },
|
|
81
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: {} };
|
|
82
134
|
case 'codex':
|
|
83
135
|
// -c overrides config.toml for this run only, so CODEX_HOME (and the owner's login in it) stays as it is.
|
|
84
136
|
return {
|
package/dist/server/relay.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { randomBytes } from 'node:crypto';
|
|
19
19
|
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
20
20
|
import { join } from 'node:path';
|
|
21
|
-
import { RELAY_FORWARD_KINDS, RELAY_SERVICES } from '../shared/protocol.js';
|
|
21
|
+
import { PHONE_MODES, RELAY_FORWARD_KINDS, RELAY_SERVICES } from '../shared/protocol.js';
|
|
22
22
|
import { FILE_MODE, RELAY_BACKOFF_MS, RELAY_FILE, RELAY_NOTE_MAX_CHARS, RELAY_QUEUE_MAX, RELAY_RETRY_AFTER_MAX_MS, RELAY_SEEN_MAX, RELAY_TEXT_MAX_CHARS, RELAY_THREADS_MAX, RELAY_TIMEOUT_MS, RELAY_TRIES, } from './constants.js';
|
|
23
23
|
import { isRecord } from './hooks.js';
|
|
24
24
|
import { cutText, HubError } from './hub.js';
|
|
@@ -50,11 +50,11 @@ const SERVICES = {
|
|
|
50
50
|
token: /^\d{4,15}:[A-Za-z0-9_-]{20,64}$/,
|
|
51
51
|
to: /^-?[1-9]\d{0,19}$/,
|
|
52
52
|
toHint: 'the chat id, a number such as 123456789',
|
|
53
|
-
request: (target, text) => ({
|
|
53
|
+
request: (target, text, extra) => ({
|
|
54
54
|
// the token is part of the address: this url is never logged
|
|
55
55
|
url: `https://api.telegram.org/bot${target.token}/sendMessage`,
|
|
56
56
|
headers: { 'Content-Type': 'application/json' },
|
|
57
|
-
body: { chat_id: target.to, text },
|
|
57
|
+
body: { chat_id: target.to, text, ...extra },
|
|
58
58
|
}),
|
|
59
59
|
answer: (json, target) => {
|
|
60
60
|
const id = pick(json, ['result', 'message_id']);
|
|
@@ -87,6 +87,7 @@ export function createRelay(options) {
|
|
|
87
87
|
const last = {};
|
|
88
88
|
/** Everything is sent until the Director chooses. */
|
|
89
89
|
let forwarded = new Set(RELAY_FORWARD_KINDS);
|
|
90
|
+
let phone = 'off';
|
|
90
91
|
/** Forwarded messages by the service's own id, oldest first (a Map keeps the order of insertion). */
|
|
91
92
|
const threads = new Map();
|
|
92
93
|
const handled = new Set();
|
|
@@ -100,7 +101,7 @@ export function createRelay(options) {
|
|
|
100
101
|
return run.then(() => undefined);
|
|
101
102
|
};
|
|
102
103
|
const save = () => {
|
|
103
|
-
const json = JSON.stringify({ version: 1, ...targets, forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)) }, null, 2);
|
|
104
|
+
const json = JSON.stringify({ version: 1, ...targets, forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)), phone }, null, 2);
|
|
104
105
|
return later(async () => {
|
|
105
106
|
const tmp = join(dir, `.${RELAY_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
106
107
|
await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
|
|
@@ -109,12 +110,12 @@ export function createRelay(options) {
|
|
|
109
110
|
};
|
|
110
111
|
const view = () => {
|
|
111
112
|
const of = (service) => (targets[service] ? { to: targets[service].to, last: last[service] ?? null } : null);
|
|
112
|
-
return { slack: of('slack'), telegram: of('telegram'), forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)) };
|
|
113
|
+
return { slack: of('slack'), telegram: of('telegram'), forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)), phone };
|
|
113
114
|
};
|
|
114
115
|
/** One message to one service: the id the service gave it, or why it did not go. Never throws, never says the token. */
|
|
115
|
-
async function post(service, target, text, tries) {
|
|
116
|
+
async function post(service, target, text, tries, extra) {
|
|
116
117
|
const def = SERVICES[service];
|
|
117
|
-
const { url, headers, body } = def.request(target, text);
|
|
118
|
+
const { url, headers, body } = def.request(target, text, extra);
|
|
118
119
|
let note = '';
|
|
119
120
|
for (let attempt = 1; attempt <= tries && !closing.signal.aborted; attempt++) {
|
|
120
121
|
let wait = RELAY_BACKOFF_MS * 2 ** (attempt - 1);
|
|
@@ -219,6 +220,8 @@ export function createRelay(options) {
|
|
|
219
220
|
else
|
|
220
221
|
log.warn(`${RELAY_FILE}: the ${service} target was skipped`);
|
|
221
222
|
}
|
|
223
|
+
if (typeof saved.phone === 'string' && PHONE_MODES.includes(saved.phone))
|
|
224
|
+
phone = saved.phone;
|
|
222
225
|
if (Array.isArray(saved.forward))
|
|
223
226
|
forwarded = new Set(saved.forward.filter((k) => typeof k === 'string' && isForward(k)));
|
|
224
227
|
},
|
|
@@ -262,6 +265,49 @@ export function createRelay(options) {
|
|
|
262
265
|
await save();
|
|
263
266
|
return view();
|
|
264
267
|
},
|
|
268
|
+
async setPhone(input) {
|
|
269
|
+
if (!isRecord(input))
|
|
270
|
+
throw bad('request body must be a JSON object');
|
|
271
|
+
for (const key of Object.keys(input))
|
|
272
|
+
if (key !== 'mode')
|
|
273
|
+
throw bad(`unknown field "${key}"`, key);
|
|
274
|
+
if (typeof input.mode !== 'string' || !PHONE_MODES.includes(input.mode))
|
|
275
|
+
throw bad(`mode must be one of: ${PHONE_MODES.join(', ')}`, 'mode');
|
|
276
|
+
phone = input.mode;
|
|
277
|
+
await save();
|
|
278
|
+
return view();
|
|
279
|
+
},
|
|
280
|
+
phoneTelegram: () => (phone === 'telegram' || phone === 'both') && targets.telegram !== undefined,
|
|
281
|
+
async sendButtons(text, markup) {
|
|
282
|
+
const target = targets.telegram;
|
|
283
|
+
if (!target || closing.signal.aborted)
|
|
284
|
+
return false;
|
|
285
|
+
const clipped = text.length > RELAY_TEXT_MAX_CHARS ? `${cutText(text, RELAY_TEXT_MAX_CHARS - 1)}…` : text;
|
|
286
|
+
// not in the queue of the other forwards: a button that waits behind them may be late for its dialog
|
|
287
|
+
const sent = await post('telegram', target, clipped, RELAY_TRIES, { reply_markup: markup });
|
|
288
|
+
last.telegram = { at: now(), ok: sent.ok, note: sent.note };
|
|
289
|
+
if (!sent.ok)
|
|
290
|
+
log.warn(`relay: telegram: ${sent.note}`);
|
|
291
|
+
return sent.ok;
|
|
292
|
+
},
|
|
293
|
+
async telegramCall(method, body) {
|
|
294
|
+
const target = targets.telegram;
|
|
295
|
+
if (!target || closing.signal.aborted)
|
|
296
|
+
return false;
|
|
297
|
+
try {
|
|
298
|
+
const res = await options.fetch(`https://api.telegram.org/bot${target.token}/${method}`, {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
headers: { 'Content-Type': 'application/json' },
|
|
301
|
+
body: JSON.stringify({ chat_id: target.to, ...body }),
|
|
302
|
+
redirect: 'error',
|
|
303
|
+
signal: AbortSignal.any([AbortSignal.timeout(RELAY_TIMEOUT_MS), closing.signal]),
|
|
304
|
+
});
|
|
305
|
+
return res.ok;
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
},
|
|
265
311
|
async test(name) {
|
|
266
312
|
const service = serviceOf(name);
|
|
267
313
|
const target = targets[service];
|
|
@@ -160,7 +160,17 @@ const telegramAuthentic = (_raw, headers, secret) => {
|
|
|
160
160
|
return given !== null && same(given, secret);
|
|
161
161
|
};
|
|
162
162
|
function telegramRead(raw, _headers, inbound) {
|
|
163
|
-
const
|
|
163
|
+
const update = parse(raw);
|
|
164
|
+
// a button of phone approvals: only from the chat of the target, and what it means is for phone.ts to check (the tag)
|
|
165
|
+
const query = update.callback_query;
|
|
166
|
+
if (isRecord(query)) {
|
|
167
|
+
const chat = str(get(query, 'message.chat.id'));
|
|
168
|
+
const queryId = str(query.id);
|
|
169
|
+
if (chat === '' || chat !== inbound.telegramChat() || queryId === '' || typeof query.data !== 'string')
|
|
170
|
+
return null;
|
|
171
|
+
return { callback: { queryId, data: query.data, chat, messageId: str(get(query, 'message.message_id')) } };
|
|
172
|
+
}
|
|
173
|
+
const message = update.message;
|
|
164
174
|
const said = str(get(message, 'text')).trim();
|
|
165
175
|
const chat = str(get(message, 'chat.id'));
|
|
166
176
|
// a bot can be found and written to by anybody on Telegram: only the chat of the target is the Director
|
package/dist/server/relief.js
CHANGED
|
@@ -49,7 +49,7 @@ export function createRelief(options) {
|
|
|
49
49
|
let seq = 0;
|
|
50
50
|
const view = () => ({ requests: [...pending.values()].map(({ request }) => ({ ...request, cleanRoom: request.cleanRoom === null ? null : { ...request.cleanRoom } })) });
|
|
51
51
|
const changed = () => options.emit({ t: 'relief', relief: view() });
|
|
52
|
-
const notify = (text) => options.notify?.('relief', text);
|
|
52
|
+
const notify = (text, ref) => options.notify?.('relief', text, ref);
|
|
53
53
|
/** The boss hears the answer as a message from the Director's side, as it hears a T-minus result. */
|
|
54
54
|
const tell = (boss, subject, body) => {
|
|
55
55
|
try {
|
|
@@ -174,7 +174,7 @@ export function createRelief(options) {
|
|
|
174
174
|
const request = { id, by: requester.name, at, expiresAt: at + RELIEF_TTL_MS, name, position: typeof position === 'string' ? position : null, role: roleText, dir: checked.path, provider, mode, cleanRoom };
|
|
175
175
|
pending.set(id, { request, timer: options.setTimer(sweep, RELIEF_TTL_MS + 1) });
|
|
176
176
|
changed();
|
|
177
|
-
notify(`${requester.name} asks to hire ${name}${request.position === null ? '' : ` as ${request.position.toUpperCase()}`}: ${provider}, ${mode}, ${checked.path}
|
|
177
|
+
notify(`${requester.name} asks to hire ${name}${request.position === null ? '' : ` as ${request.position.toUpperCase()}`}: ${provider}, ${mode}, ${checked.path}`, { kind: 'relief', id });
|
|
178
178
|
return { id, status: 'pending', note: `waiting for the Director; you get a message with his answer, and the request expires after ${MINUTES(RELIEF_TTL_MS)} minutes` };
|
|
179
179
|
},
|
|
180
180
|
view,
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** The one reader of the setting: the hub for hire and edit, home.ts for the roster file. `{}` is the only value. It needs Claude Code, and not a Clean Room (its token cannot open a session in the app). */
|
|
2
|
+
export function parseRemoteControl(value, provider, cleanRoom) {
|
|
3
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
4
|
+
return { ok: false, error: 'remoteControl must be an object' };
|
|
5
|
+
const unknown = Object.keys(value).find((key) => value[key] !== undefined);
|
|
6
|
+
if (unknown !== undefined)
|
|
7
|
+
return { ok: false, error: `remoteControl has no field "${unknown}"` };
|
|
8
|
+
if ((provider ?? 'claude') !== 'claude')
|
|
9
|
+
return { ok: false, error: 'Remote Control is for Claude Code agents only' };
|
|
10
|
+
if (cleanRoom)
|
|
11
|
+
return { ok: false, error: 'a Clean Room agent cannot use Remote Control: it has no claude.ai login' };
|
|
12
|
+
return { ok: true, remoteControl: {} };
|
|
13
|
+
}
|
|
14
|
+
/** The session name the app shows. */
|
|
15
|
+
export const remoteControlName = (agent) => `gonogo-${agent}`;
|