@ulm0/gonogo 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +24 -2
- package/bin/gonogo.js +18 -0
- package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
- package/dist/client/apple-touch-icon.png +0 -0
- package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
- package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
- package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/dist/client/assets/index-BqCn1SM7.js +50 -0
- package/dist/client/assets/index-KZtFVMJG.css +1 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +19 -0
- package/dist/server/audited.js +133 -0
- package/dist/server/blackbox.js +261 -0
- package/dist/server/board.js +123 -0
- package/dist/server/cleanroom.js +214 -0
- package/dist/server/clearance.js +158 -0
- package/dist/server/cli.js +763 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +465 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/hangar.js +311 -0
- package/dist/server/home.js +520 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2642 -0
- package/dist/server/launcher.js +547 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logchart.js +58 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/massbudget.js +169 -0
- package/dist/server/mcp.js +228 -0
- package/dist/server/migrate.js +122 -0
- package/dist/server/missionlog.js +211 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +199 -0
- package/dist/server/recorder.js +176 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/relief.js +226 -0
- package/dist/server/rollout.js +172 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/telemetry.js +110 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1607 -0
- package/dist/shared/cron.js +149 -0
- package/dist/shared/fuel.js +18 -0
- package/dist/shared/livery.js +348 -0
- package/dist/shared/positions.js +132 -0
- package/dist/shared/protocol.js +245 -0
- package/package.json +84 -3
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flight Plan: the task board (docs/flight-plan-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* The Director (the browser) and every agent (the MCP tools task_list, task_create, task_update) change one list, kept in
|
|
5
|
+
* tasks.json. The server stamps who did what: `createdBy`, and one history line per change. Assigning a task to an agent
|
|
6
|
+
* sends that agent a message through the normal path: Hub.sendFromUser for the Director, Hub.sendFromAgent for an agent, so
|
|
7
|
+
* the send limit, Redline, held mail and the hop limit apply. The clock and the send are injected for tests.
|
|
8
|
+
*
|
|
9
|
+
* shortcut: the whole list is in every frame and every snapshot; at the limits (500 open tasks with 4000-character details)
|
|
10
|
+
* that nears the 4 MB socket buffer of web.ts. Send the details on demand if a board ever gets that big.
|
|
11
|
+
* shortcut: `assignee` is an agent name, so a task does not follow a renamed console and keeps the name of a removed one;
|
|
12
|
+
* key by record id if renames get common.
|
|
13
|
+
*/
|
|
14
|
+
import { randomBytes } from 'node:crypto';
|
|
15
|
+
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { AGENT_NAME_PATTERN, STATION_NAME_PATTERN, SUBJECT_MAX_CHARS, TASK_DETAIL_MAX_CHARS, TASK_NOTE_MAX_CHARS, TASK_STATUSES, TASK_TITLE_MAX_CHARS, TASKS_OPEN_MAX, taskSubject, } from '../shared/protocol.js';
|
|
18
|
+
import { FILE_MODE, TASK_NOTES_MAX, TASKS_DONE_KEEP, TASKS_FILE } from './constants.js';
|
|
19
|
+
import { isRecord } from './hooks.js';
|
|
20
|
+
import { HubError } from './hub.js';
|
|
21
|
+
import { UNSAFE_IN_NAME } from './schedules.js';
|
|
22
|
+
const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
|
|
23
|
+
const STATION_RE = new RegExp(STATION_NAME_PATTERN);
|
|
24
|
+
const ID_RE = /^t[1-9]\d{0,5}$/;
|
|
25
|
+
const CREATE_FIELDS = ['title', 'detail', 'assignee'];
|
|
26
|
+
const PATCH_FIELDS = ['status', 'assignee', 'note'];
|
|
27
|
+
const bad = (message, field) => new HubError('bad_request', message, field);
|
|
28
|
+
const copy = (task) => ({ ...task, notes: [...task.notes] });
|
|
29
|
+
const isOpen = (task) => task.status !== 'done';
|
|
30
|
+
/** "2026-11-17 14:03 UTC": a history line starts with it. */
|
|
31
|
+
const stamp = (at) => `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
32
|
+
const director = (actor) => (actor.kind === 'dock' ? `Director of ${actor.station}` : 'Director');
|
|
33
|
+
const line = (actor, text, at) => `${stamp(at)} ${actor.kind === 'agent' ? actor.name : director(actor)}: ${text}`;
|
|
34
|
+
/** The fields a request may carry, checked one by one. A task is made with a title; a change has at least one field. */
|
|
35
|
+
function validate(input, whole, isAgent) {
|
|
36
|
+
if (!isRecord(input))
|
|
37
|
+
throw bad('request body must be a JSON object');
|
|
38
|
+
const allowed = whole ? CREATE_FIELDS : PATCH_FIELDS;
|
|
39
|
+
for (const key of Object.keys(input))
|
|
40
|
+
if (!allowed.includes(key))
|
|
41
|
+
throw bad(`unknown field "${key}"`, key);
|
|
42
|
+
if (whole && input.title === undefined)
|
|
43
|
+
throw bad('title is required', 'title');
|
|
44
|
+
if (!whole && Object.keys(input).length === 0)
|
|
45
|
+
throw bad('nothing to change: give a status, an assignee or a note');
|
|
46
|
+
const out = {};
|
|
47
|
+
if (input.title !== undefined) {
|
|
48
|
+
const title = typeof input.title === 'string' ? input.title.trim() : '';
|
|
49
|
+
if (title === '' || title.length > TASK_TITLE_MAX_CHARS || UNSAFE_IN_NAME.test(title)) {
|
|
50
|
+
throw bad(`title must be 1 to ${TASK_TITLE_MAX_CHARS} characters on one line`, 'title');
|
|
51
|
+
}
|
|
52
|
+
out.title = title;
|
|
53
|
+
}
|
|
54
|
+
if (input.detail !== undefined) {
|
|
55
|
+
if (typeof input.detail !== 'string' || input.detail.length > TASK_DETAIL_MAX_CHARS)
|
|
56
|
+
throw bad(`detail must be text of at most ${TASK_DETAIL_MAX_CHARS} characters`, 'detail');
|
|
57
|
+
out.detail = input.detail.trim();
|
|
58
|
+
}
|
|
59
|
+
if (input.status !== undefined) {
|
|
60
|
+
if (typeof input.status !== 'string' || !TASK_STATUSES.includes(input.status))
|
|
61
|
+
throw bad(`status must be one of: ${TASK_STATUSES.join(', ')}`, 'status');
|
|
62
|
+
out.status = input.status;
|
|
63
|
+
}
|
|
64
|
+
if (input.assignee !== undefined) {
|
|
65
|
+
if (input.assignee !== null && (typeof input.assignee !== 'string' || !NAME_RE.test(input.assignee) || !isAgent(input.assignee))) {
|
|
66
|
+
throw bad('assignee must be the name of an agent in the room, or null', 'assignee');
|
|
67
|
+
}
|
|
68
|
+
out.assignee = input.assignee;
|
|
69
|
+
}
|
|
70
|
+
if (input.note !== undefined) {
|
|
71
|
+
// one line: the history is a list of lines
|
|
72
|
+
const note = typeof input.note === 'string' ? input.note.replace(/\s+/g, ' ').trim() : '';
|
|
73
|
+
if (note === '' || note.length > TASK_NOTE_MAX_CHARS || UNSAFE_IN_NAME.test(note))
|
|
74
|
+
throw bad(`note must be 1 to ${TASK_NOTE_MAX_CHARS} characters`, 'note');
|
|
75
|
+
out.note = note;
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** A saved record read back; one that is not a task throws, and the caller skips it. Unlike a request, it may name an agent that is gone. */
|
|
80
|
+
function fromRecord(raw, at) {
|
|
81
|
+
if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
|
|
82
|
+
throw new Error('no valid id');
|
|
83
|
+
const { id, title, detail, status, assignee, createdBy, createdAt, updatedAt, notes, handedOff } = raw;
|
|
84
|
+
if (typeof title !== 'string' || title === '' || title.length > TASK_TITLE_MAX_CHARS)
|
|
85
|
+
throw new Error('no valid title');
|
|
86
|
+
if (typeof status !== 'string' || !TASK_STATUSES.includes(status))
|
|
87
|
+
throw new Error('no valid status');
|
|
88
|
+
return {
|
|
89
|
+
id,
|
|
90
|
+
title,
|
|
91
|
+
detail: typeof detail === 'string' ? detail.slice(0, TASK_DETAIL_MAX_CHARS) : '',
|
|
92
|
+
status: status,
|
|
93
|
+
assignee: typeof assignee === 'string' && NAME_RE.test(assignee) ? assignee : null,
|
|
94
|
+
createdBy: typeof createdBy === 'string' && NAME_RE.test(createdBy) ? createdBy : 'user',
|
|
95
|
+
createdAt: typeof createdAt === 'number' ? createdAt : at,
|
|
96
|
+
updatedAt: typeof updatedAt === 'number' ? updatedAt : at,
|
|
97
|
+
notes: Array.isArray(notes) ? notes.filter((n) => typeof n === 'string').slice(-TASK_NOTES_MAX) : [],
|
|
98
|
+
...(typeof handedOff === 'string' && STATION_RE.test(handedOff) ? { handedOff } : {}),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
export function createTasks(options) {
|
|
102
|
+
const { dir, now, log } = options;
|
|
103
|
+
const path = join(dir, TASKS_FILE);
|
|
104
|
+
let tasks = [];
|
|
105
|
+
let seq = 0;
|
|
106
|
+
let chain = Promise.resolve();
|
|
107
|
+
const later = (fn) => {
|
|
108
|
+
const run = chain.then(fn);
|
|
109
|
+
chain = run.catch((error) => log.error('flight plan could not write', error));
|
|
110
|
+
return run.then(() => undefined);
|
|
111
|
+
};
|
|
112
|
+
const save = () => {
|
|
113
|
+
// `seq` is the number of the last id given, so an id that was removed or dropped is not given again after a restart
|
|
114
|
+
const json = JSON.stringify({ version: 1, seq, tasks }, null, 2);
|
|
115
|
+
return later(async () => {
|
|
116
|
+
const tmp = join(dir, `.${TASKS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
117
|
+
await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
|
|
118
|
+
await rename(tmp, path);
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
const list = () => tasks.map(copy);
|
|
122
|
+
/** Tells the browsers and saves. */
|
|
123
|
+
const changed = () => {
|
|
124
|
+
options.emit(list());
|
|
125
|
+
return save();
|
|
126
|
+
};
|
|
127
|
+
const find = (id) => {
|
|
128
|
+
const task = ID_RE.test(id) ? tasks.find((x) => x.id === id) : undefined;
|
|
129
|
+
if (!task)
|
|
130
|
+
throw new HubError('not_found', 'unknown task');
|
|
131
|
+
return task;
|
|
132
|
+
};
|
|
133
|
+
const full = () => new HubError('conflict', `at most ${TASKS_OPEN_MAX} open tasks: finish or remove one first`, 'tasks');
|
|
134
|
+
/** Done tasks are history: the newest TASKS_DONE_KEEP stay, so the file and every frame stop growing. */
|
|
135
|
+
const prune = () => {
|
|
136
|
+
const done = tasks.filter((x) => !isOpen(x));
|
|
137
|
+
if (done.length <= TASKS_DONE_KEEP)
|
|
138
|
+
return;
|
|
139
|
+
const drop = new Set(done.sort((a, b) => b.updatedAt - a.updatedAt).slice(TASKS_DONE_KEEP));
|
|
140
|
+
tasks = tasks.filter((x) => !drop.has(x));
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* Tells the assignee of `task`. Runs before the change is stored, so a refusal of the hub (the session of the acting agent
|
|
144
|
+
* ended, the recipient is being removed) leaves the board as it was. A message that was made but not delivered is a note.
|
|
145
|
+
*/
|
|
146
|
+
const tell = (actor, task, at) => {
|
|
147
|
+
const to = task.assignee;
|
|
148
|
+
if (to === null || (actor.kind === 'agent' && actor.name === to))
|
|
149
|
+
return;
|
|
150
|
+
const by = actor.kind === 'agent' ? actor.name : `the ${director(actor)}`;
|
|
151
|
+
const body = `${task.detail === '' ? '(no detail)' : task.detail}\n\nAssigned by ${by}. Set its status with task_update.`;
|
|
152
|
+
const sent = options.send(actor, { to, subject: taskSubject(task.id, task.title).slice(0, SUBJECT_MAX_CHARS), body });
|
|
153
|
+
if (!sent.ok)
|
|
154
|
+
task.notes.push(line(actor, `the message to ${to} was not delivered: ${sent.note ?? 'no reason given'}`, at));
|
|
155
|
+
};
|
|
156
|
+
return {
|
|
157
|
+
async load() {
|
|
158
|
+
let saved = null;
|
|
159
|
+
try {
|
|
160
|
+
saved = JSON.parse(await readFile(path, 'utf8'));
|
|
161
|
+
if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.tasks))
|
|
162
|
+
throw new Error('not a version 1 tasks file');
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
saved = null;
|
|
166
|
+
if (error.code !== 'ENOENT') {
|
|
167
|
+
// kept aside, so that the next save cannot overwrite what the Director and the agents wrote
|
|
168
|
+
log.error(`${TASKS_FILE} could not be read; the board starts empty and the file is kept as ${TASKS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
|
|
169
|
+
await rename(path, `${path}.bad`).catch(() => undefined);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const records = isRecord(saved) && Array.isArray(saved.tasks) ? saved.tasks : [];
|
|
173
|
+
if (isRecord(saved) && typeof saved.seq === 'number' && Number.isSafeInteger(saved.seq) && saved.seq > 0)
|
|
174
|
+
seq = saved.seq;
|
|
175
|
+
for (const raw of records) {
|
|
176
|
+
try {
|
|
177
|
+
const task = fromRecord(raw, now());
|
|
178
|
+
if (tasks.some((x) => x.id === task.id))
|
|
179
|
+
throw new Error(`the id ${task.id} is used twice`);
|
|
180
|
+
tasks.push(task);
|
|
181
|
+
seq = Math.max(seq, Number(task.id.slice(1)));
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
log.warn(`${TASKS_FILE}: a task was skipped: ${error instanceof Error ? error.message : String(error)}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
list,
|
|
189
|
+
async create(actor, input) {
|
|
190
|
+
const request = validate(input, true, options.isAgent);
|
|
191
|
+
if (tasks.filter(isOpen).length >= TASKS_OPEN_MAX)
|
|
192
|
+
throw full();
|
|
193
|
+
const at = now();
|
|
194
|
+
const task = {
|
|
195
|
+
id: `t${seq + 1}`,
|
|
196
|
+
title: request.title ?? '',
|
|
197
|
+
detail: request.detail ?? '',
|
|
198
|
+
status: 'todo',
|
|
199
|
+
assignee: request.assignee ?? null,
|
|
200
|
+
createdBy: actor.kind === 'agent' ? actor.name : 'user',
|
|
201
|
+
createdAt: at,
|
|
202
|
+
updatedAt: at,
|
|
203
|
+
notes: [],
|
|
204
|
+
};
|
|
205
|
+
task.notes.push(line(actor, task.assignee === null ? 'created' : `created; assigned to ${task.assignee}`, at));
|
|
206
|
+
tell(actor, task, at);
|
|
207
|
+
seq += 1;
|
|
208
|
+
tasks.push(task);
|
|
209
|
+
prune();
|
|
210
|
+
await changed();
|
|
211
|
+
return copy(task);
|
|
212
|
+
},
|
|
213
|
+
async handOff(id, station, assignee) {
|
|
214
|
+
const task = find(id);
|
|
215
|
+
if (!isOpen(task) || task.handedOff !== undefined)
|
|
216
|
+
throw new HubError('conflict', 'only a task that is open here can be handed off', 'task');
|
|
217
|
+
const at = now();
|
|
218
|
+
const next = copy(task);
|
|
219
|
+
next.status = 'done';
|
|
220
|
+
next.handedOff = station;
|
|
221
|
+
next.updatedAt = at;
|
|
222
|
+
next.notes.push(line({ kind: 'user' }, `handed off to ${assignee === null ? '' : `${assignee}@`}${station}`, at));
|
|
223
|
+
next.notes = next.notes.slice(-TASK_NOTES_MAX);
|
|
224
|
+
tasks[tasks.indexOf(task)] = next;
|
|
225
|
+
prune();
|
|
226
|
+
await changed();
|
|
227
|
+
return copy(next);
|
|
228
|
+
},
|
|
229
|
+
async update(actor, id, input) {
|
|
230
|
+
const task = find(id);
|
|
231
|
+
const patch = validate(input, false, options.isAgent);
|
|
232
|
+
const at = now();
|
|
233
|
+
const next = copy(task);
|
|
234
|
+
const parts = [];
|
|
235
|
+
if (patch.status !== undefined && patch.status !== task.status) {
|
|
236
|
+
if (!isOpen(task) && patch.status !== 'done' && tasks.filter(isOpen).length >= TASKS_OPEN_MAX)
|
|
237
|
+
throw full();
|
|
238
|
+
next.status = patch.status;
|
|
239
|
+
parts.push(`status ${patch.status}`);
|
|
240
|
+
}
|
|
241
|
+
if (patch.assignee !== undefined && patch.assignee !== task.assignee) {
|
|
242
|
+
next.assignee = patch.assignee;
|
|
243
|
+
parts.push(patch.assignee === null ? 'unassigned' : `assigned to ${patch.assignee}`);
|
|
244
|
+
}
|
|
245
|
+
if (patch.note !== undefined)
|
|
246
|
+
parts.push(patch.note);
|
|
247
|
+
if (parts.length === 0)
|
|
248
|
+
return copy(task);
|
|
249
|
+
next.updatedAt = at;
|
|
250
|
+
next.notes.push(line(actor, parts.join('; '), at));
|
|
251
|
+
if (next.assignee !== task.assignee)
|
|
252
|
+
tell(actor, next, at);
|
|
253
|
+
next.notes = next.notes.slice(-TASK_NOTES_MAX);
|
|
254
|
+
tasks[tasks.indexOf(task)] = next;
|
|
255
|
+
// the Director sees what he moved himself; the inbox is for what an agent did
|
|
256
|
+
if (actor.kind === 'agent' && next.status !== task.status && (next.status === 'blocked' || next.status === 'review')) {
|
|
257
|
+
options.notify?.('flight-plan', `${actor.name} moved ${next.id} to ${next.status}: ${next.title}`);
|
|
258
|
+
}
|
|
259
|
+
prune();
|
|
260
|
+
await changed();
|
|
261
|
+
return copy(next);
|
|
262
|
+
},
|
|
263
|
+
async remove(id) {
|
|
264
|
+
const task = find(id);
|
|
265
|
+
tasks = tasks.filter((x) => x !== task);
|
|
266
|
+
await changed();
|
|
267
|
+
},
|
|
268
|
+
close() {
|
|
269
|
+
return chain.then(() => undefined);
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telemetry: the tool calls of each agent, from the hooks gonogo already receives (docs/telemetry-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* A PreToolUse opens a call; the PostToolUse or PostToolUseFailure with the same `tool_use_id` closes it (Gemini CLI sends
|
|
5
|
+
* no id: the oldest open call of the same tool is closed). Each agent keeps its newest TELEMETRY_PER_AGENT calls in memory.
|
|
6
|
+
* A closed call is appended to telemetry.jsonl; at start the file is read back and rewritten with only the kept calls,
|
|
7
|
+
* and during a run it is rewritten the same way once it holds TELEMETRY_FILE_SLACK more lines than were kept.
|
|
8
|
+
*
|
|
9
|
+
* shortcut: calls are keyed by agent name, so a renamed agent starts an empty list and a removed agent's calls stay on disk
|
|
10
|
+
* (at most TELEMETRY_PER_AGENT per name); key by record id and drop them on remove if that ever matters.
|
|
11
|
+
*/
|
|
12
|
+
import { appendFile, readFile, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { TELEMETRY_PER_AGENT } from '../shared/protocol.js';
|
|
15
|
+
import { FILE_MODE } from './constants.js';
|
|
16
|
+
import { describeDoing } from './hub.js';
|
|
17
|
+
const FILE = 'telemetry.jsonl';
|
|
18
|
+
/** Lines appended since the last rewrite before the file is cut back to the kept calls. */
|
|
19
|
+
export const TELEMETRY_FILE_SLACK = 2000;
|
|
20
|
+
const str = (v) => (typeof v === 'string' && v !== '' ? v : null);
|
|
21
|
+
function isCall(v) {
|
|
22
|
+
if (typeof v !== 'object' || v === null)
|
|
23
|
+
return false;
|
|
24
|
+
const c = v;
|
|
25
|
+
return typeof c.agent === 'string' && typeof c.at === 'number' && (c.ms === null || typeof c.ms === 'number') && typeof c.tool === 'string' && typeof c.summary === 'string' && typeof c.failed === 'boolean';
|
|
26
|
+
}
|
|
27
|
+
const plain = (c) => ({ at: c.at, ms: c.ms, tool: c.tool, summary: c.summary, failed: c.failed });
|
|
28
|
+
export function createTelemetry(options) {
|
|
29
|
+
const { now, log } = options;
|
|
30
|
+
const path = join(options.dir, FILE);
|
|
31
|
+
/** Agent to its calls, oldest first, at most TELEMETRY_PER_AGENT. */
|
|
32
|
+
const byAgent = new Map();
|
|
33
|
+
let appended = 0;
|
|
34
|
+
let chain = Promise.resolve();
|
|
35
|
+
const later = (step) => {
|
|
36
|
+
chain = chain.then(step).catch((error) => log.warn(`${FILE} could not be written`, error));
|
|
37
|
+
};
|
|
38
|
+
const push = (agent, call) => {
|
|
39
|
+
const list = byAgent.get(agent) ?? [];
|
|
40
|
+
list.push(call);
|
|
41
|
+
if (list.length > TELEMETRY_PER_AGENT)
|
|
42
|
+
list.splice(0, list.length - TELEMETRY_PER_AGENT);
|
|
43
|
+
byAgent.set(agent, list);
|
|
44
|
+
};
|
|
45
|
+
const snapshot = () => [...byAgent].flatMap(([agent, list]) => list.filter((c) => c.ms !== null).map((c) => JSON.stringify({ agent, ...plain(c) }) + '\n')).join('');
|
|
46
|
+
return {
|
|
47
|
+
async load() {
|
|
48
|
+
let text = '';
|
|
49
|
+
try {
|
|
50
|
+
text = await readFile(path, 'utf8');
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code !== 'ENOENT')
|
|
54
|
+
log.warn(`${FILE} could not be read; telemetry starts empty`, error);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const read = [];
|
|
58
|
+
for (const line of text.split('\n')) {
|
|
59
|
+
if (line === '')
|
|
60
|
+
continue;
|
|
61
|
+
try {
|
|
62
|
+
const v = JSON.parse(line);
|
|
63
|
+
if (isCall(v))
|
|
64
|
+
read.push(v);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// a torn last line after a crash: skipped
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// lines are written when a call ends; the list is in start order
|
|
71
|
+
for (const v of read.sort((x, y) => x.at - y.at))
|
|
72
|
+
push(v.agent, { at: v.at, ms: v.ms, tool: v.tool, summary: v.summary, failed: v.failed, id: null });
|
|
73
|
+
const kept = snapshot();
|
|
74
|
+
if (kept !== text)
|
|
75
|
+
later(() => writeFile(path, kept, { mode: FILE_MODE }));
|
|
76
|
+
},
|
|
77
|
+
hook(agent, event, payload) {
|
|
78
|
+
const tool = str(payload.tool_name) ?? 'tool';
|
|
79
|
+
const id = str(payload.tool_use_id);
|
|
80
|
+
if (event === 'PreToolUse') {
|
|
81
|
+
push(agent, { id, at: now(), ms: null, tool, summary: describeDoing(payload.tool_name, payload.tool_input), failed: false });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (event !== 'PostToolUse' && event !== 'PostToolUseFailure')
|
|
85
|
+
return;
|
|
86
|
+
const list = byAgent.get(agent) ?? [];
|
|
87
|
+
const call = id !== null ? list.find((c) => c.id === id && c.ms === null) : list.find((c) => c.ms === null && c.tool === tool);
|
|
88
|
+
if (call === undefined)
|
|
89
|
+
return;
|
|
90
|
+
call.ms = Math.max(0, now() - call.at);
|
|
91
|
+
call.failed = event === 'PostToolUseFailure';
|
|
92
|
+
appended += 1;
|
|
93
|
+
if (appended >= TELEMETRY_FILE_SLACK) {
|
|
94
|
+
appended = 0;
|
|
95
|
+
const kept = snapshot();
|
|
96
|
+
later(() => writeFile(path, kept, { mode: FILE_MODE }));
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
const line = JSON.stringify({ agent, ...plain(call) }) + '\n';
|
|
100
|
+
later(() => appendFile(path, line, { mode: FILE_MODE }));
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
calls(agent) {
|
|
104
|
+
return (byAgent.get(agent) ?? []).map(plain).reverse();
|
|
105
|
+
},
|
|
106
|
+
close() {
|
|
107
|
+
return chain;
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|