@ulm0/gonogo 0.1.1 → 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.
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Relief: a boss that asks for more hands (docs/relief-spec.md).
3
+ *
4
+ * The boss calls `hire_agent`; that only makes a request. The request waits in memory, shown to the Director with every
5
+ * parameter, and only his GO makes the hub staff the agent, through `Hub.hire`, the call of the hire form. Everything the
6
+ * boss can ask is capped here, on the server: no mode above acceptEdits, no custom command, no payload, at most
7
+ * RELIEF_PENDING_MAX requests waiting and RELIEF_RATE_MAX in RELIEF_RATE_WINDOW_MS, a request expires after RELIEF_TTL_MS,
8
+ * a name is a valid free name, the folder passes the check of the form, a Clean Room boss hires Clean Room agents inside
9
+ * its own folder only. `hub.hire` checks everything again (name, room cap of MAX_AGENTS, folder, Docker) when the GO comes.
10
+ *
11
+ * shortcut: requests are not saved, so a restart drops them and the boss is not told; the Downlink event of the request stays.
12
+ * shortcut: a Clean Room boss's folder is checked with realpath when asked and again at the GO, not held open between the two.
13
+ */
14
+ import { realpath } from 'node:fs/promises';
15
+ import { isAbsolute, relative, sep } from 'node:path';
16
+ import { positionById, POSITION_IDS } from '../shared/positions.js';
17
+ import { AGENT_NAME_PATTERN, DIR_MAX_CHARS, MAX_AGENTS, PERMISSION_MODES, PROVIDERS, RELIEF_MODES, RESERVED_NAMES, ROLE_MAX_CHARS } from '../shared/protocol.js';
18
+ import { providerInfo } from '../shared/protocol.js';
19
+ import { RELIEF_PENDING_MAX, RELIEF_RATE_MAX, RELIEF_RATE_WINDOW_MS, RELIEF_TTL_MS } from './constants.js';
20
+ import { isRecord } from './hooks.js';
21
+ import { HubError } from './hub.js';
22
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
23
+ const ID_RE = /^h[1-9]\d{0,9}$/;
24
+ const FIELDS = new Set(['name', 'position', 'role', 'dir', 'engine', 'mode']);
25
+ /**
26
+ * What a person cannot see in the block but the new agent reads: control codes (a newline, a return and a tab are fine), format
27
+ * characters (zero width, direction overrides, the Unicode tag block that hides a whole sentence), line and paragraph
28
+ * separators, private-use and unassigned code points, and the variation selectors of the supplement.
29
+ */
30
+ const HIDDEN_RE = /[^\P{Cc}\n\r\t]|[\p{Cf}\p{Zl}\p{Zp}\p{Co}\p{Cn}\u{E0100}-\u{E01EF}]/u;
31
+ const MINUTES = (ms) => Math.round(ms / 60_000);
32
+ const bad = (message, field) => new HubError('bad_request', message, field);
33
+ /** `dir` is `root` or inside it, after symbolic links are followed on both. */
34
+ export async function insideRealpath(root, dir) {
35
+ try {
36
+ const [r, d] = await Promise.all([realpath(root), realpath(dir)]);
37
+ const rel = relative(r, d);
38
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ export function createRelief(options) {
45
+ const { hub, now, log } = options;
46
+ const pending = new Map();
47
+ /** When each request of the window was made, oldest first. */
48
+ let made = [];
49
+ let seq = 0;
50
+ const view = () => ({ requests: [...pending.values()].map(({ request }) => ({ ...request, cleanRoom: request.cleanRoom === null ? null : { ...request.cleanRoom } })) });
51
+ const changed = () => options.emit({ t: 'relief', relief: view() });
52
+ const notify = (text) => options.notify?.('relief', text);
53
+ /** The boss hears the answer as a message from the Director's side, as it hears a T-minus result. */
54
+ const tell = (boss, subject, body) => {
55
+ try {
56
+ hub.sendFromUser({ to: boss, subject, body });
57
+ }
58
+ catch (error) {
59
+ log.debug(`could not tell ${boss} about a hire request`, error);
60
+ }
61
+ };
62
+ const drop = (id) => {
63
+ const found = pending.get(id);
64
+ if (!found)
65
+ return null;
66
+ pending.delete(id);
67
+ options.clearTimer(found.timer);
68
+ return found.request;
69
+ };
70
+ /** Expires every request whose time is up; run before each request and each answer, and by the timers. */
71
+ const sweep = () => {
72
+ for (const [id, { request }] of [...pending]) {
73
+ if (request.expiresAt > now())
74
+ continue;
75
+ drop(id);
76
+ notify(`request to hire ${request.name} expired unanswered`);
77
+ tell(request.by, `Relief: request for ${request.name} expired`, `The Director did not answer within ${MINUTES(RELIEF_TTL_MS)} minutes, so the request to hire ${request.name} is gone. Ask again only if it is still needed.`);
78
+ changed();
79
+ }
80
+ };
81
+ /** The limits that do not need the disk. Run before the folder is checked and again right before the request is stored (two calls may overlap). */
82
+ const limits = (name) => {
83
+ sweep();
84
+ const cutoff = now() - RELIEF_RATE_WINDOW_MS;
85
+ made = made.filter((at) => at > cutoff);
86
+ if (made.length >= RELIEF_RATE_MAX) {
87
+ throw new HubError('rate_limited', `at most ${RELIEF_RATE_MAX} hire requests in ${MINUTES(RELIEF_RATE_WINDOW_MS)} minutes: wait, or tell the Director what you need`);
88
+ }
89
+ if (pending.size >= RELIEF_PENDING_MAX) {
90
+ throw new HubError('conflict', `${RELIEF_PENDING_MAX} hire requests already wait for the Director: wait for his answer`);
91
+ }
92
+ if (hub.views().some((agent) => agent.name === name) || [...pending.values()].some(({ request }) => request.name === name)) {
93
+ throw new HubError('conflict', `an agent or a request named "${name}" exists already: choose another name`, 'name');
94
+ }
95
+ if (hub.views().length >= MAX_AGENTS)
96
+ throw new HubError('conflict', `the operations room is full (${MAX_AGENTS} agents)`);
97
+ };
98
+ /** The request as the hire form would send it. No confirmBypass, no command, no payload: the tool cannot ask for them. */
99
+ const hireOf = (r) => {
100
+ const hire = { name: r.name, role: r.role, dir: r.dir, mode: r.mode, provider: r.provider };
101
+ if (r.position !== null)
102
+ hire.position = r.position;
103
+ if (r.cleanRoom !== null)
104
+ hire.cleanRoom = r.cleanRoom;
105
+ return hire;
106
+ };
107
+ /** Is the boss that asked still the boss, and is `dir` in its box when it is a Clean Room agent? */
108
+ const confine = async (requester, dir) => {
109
+ if (requester.cleanRoom !== null && !(await insideRealpath(requester.dir, dir))) {
110
+ throw new HubError('forbidden', 'a Clean Room agent can hire only inside its own project folder: leave dir out to use it', 'dir');
111
+ }
112
+ };
113
+ return {
114
+ async request(by, input) {
115
+ // identity first: the token names the agent, the generation says it is this run of it
116
+ const requester = hub.views().find((agent) => agent.name === by.agent);
117
+ if (!requester)
118
+ throw new HubError('not_found', 'unknown agent');
119
+ if (requester.generation !== by.generation || requester.transition !== null)
120
+ throw new HubError('conflict', 'this session has ended');
121
+ if (!requester.boss)
122
+ throw new HubError('forbidden', 'only the boss can ask for a hire');
123
+ if (!isRecord(input))
124
+ throw bad('the request must be an object');
125
+ for (const key of Object.keys(input))
126
+ if (!FIELDS.has(key))
127
+ throw bad(`unknown field "${key}": a request has name, position, role, dir, engine and mode`, key);
128
+ const { name } = input;
129
+ if (typeof name !== 'string' || !NAME_RE.test(name))
130
+ throw bad('name must be 1 to 32 lowercase letters, digits or hyphens, and start with a letter or digit', 'name');
131
+ if (RESERVED_NAMES.includes(name))
132
+ throw bad(`"${name}" is a reserved name`, 'name');
133
+ const engine = input.engine === undefined ? 'claude' : input.engine;
134
+ if (typeof engine !== 'string' || !PROVIDERS.includes(engine))
135
+ throw bad(`engine must be one of ${PROVIDERS.filter((p) => p !== 'custom').join(', ')}`, 'engine');
136
+ if (engine === 'custom')
137
+ throw bad('a custom command cannot be asked for: only the Director can hire one', 'engine');
138
+ const provider = engine;
139
+ const asked = input.mode === undefined ? 'default' : input.mode;
140
+ if (typeof asked !== 'string' || !PERMISSION_MODES.includes(asked))
141
+ throw bad(`mode must be one of ${RELIEF_MODES.join(', ')}`, 'mode');
142
+ if (!RELIEF_MODES.includes(asked))
143
+ throw bad(`a request can ask for ${RELIEF_MODES.join(' or ')} at most, not ${asked}: only the Director can give more`, 'mode');
144
+ // an engine without permission modes is started in default whatever is asked, and the Director is shown what will happen
145
+ const mode = providerInfo(provider).modes ? asked : 'default';
146
+ const { position, role } = input;
147
+ if (position !== undefined && (typeof position !== 'string' || !POSITION_IDS.includes(position)))
148
+ throw bad(`position must be one of ${POSITION_IDS.join(', ')}`, 'position');
149
+ if (role !== undefined && (typeof role !== 'string' || role.trim().length === 0 || role.trim().length > ROLE_MAX_CHARS))
150
+ throw bad(`role must be 1 to ${ROLE_MAX_CHARS} characters`, 'role');
151
+ // the Director approves the text he reads: nothing in it may be hidden from him
152
+ if (typeof role === 'string' && HIDDEN_RE.test(role))
153
+ throw bad('role must not hold control, invisible or direction-changing characters: the Director reads all of it', 'role');
154
+ const roleText = typeof role === 'string' ? role.trim() : typeof position === 'string' ? (positionById(position)?.role ?? '') : '';
155
+ if (roleText === '')
156
+ throw bad('give a position or a role', 'role');
157
+ const cleanRoom = requester.cleanRoom === null ? null : { ...requester.cleanRoom };
158
+ if (cleanRoom !== null && provider !== 'claude')
159
+ throw bad('a Clean Room agent hires Clean Room agents, and those run Claude Code only', 'engine');
160
+ const asDir = input.dir === undefined ? (cleanRoom === null ? undefined : requester.dir) : input.dir;
161
+ if (typeof asDir !== 'string' || asDir.length === 0 || asDir.length > DIR_MAX_CHARS)
162
+ throw bad(`dir must be an absolute path of 1 to ${DIR_MAX_CHARS} characters`, 'dir');
163
+ limits(name);
164
+ const checked = await options.checkDirectory(asDir);
165
+ if (!checked.ok)
166
+ throw bad(checked.error, 'dir');
167
+ await confine(requester, checked.path);
168
+ // the checks above waited on the disk: another request may have taken the name or the last place meanwhile
169
+ limits(name);
170
+ seq += 1;
171
+ const at = now();
172
+ made.push(at);
173
+ const id = `h${seq}`;
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
+ pending.set(id, { request, timer: options.setTimer(sweep, RELIEF_TTL_MS + 1) });
176
+ changed();
177
+ notify(`${requester.name} asks to hire ${name}${request.position === null ? '' : ` as ${request.position.toUpperCase()}`}: ${provider}, ${mode}, ${checked.path}`);
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
+ },
180
+ view,
181
+ async decide(idInput, verdict, by) {
182
+ if (!by || by.kind !== 'user')
183
+ throw new HubError('forbidden', 'only the Director answers a hire request');
184
+ if (verdict !== 'go' && verdict !== 'no-go')
185
+ throw bad('the answer is go or no-go');
186
+ sweep();
187
+ const id = typeof idInput === 'string' && ID_RE.test(idInput) ? idInput : '';
188
+ // taken out of the list before anything waits, so a second answer to the same request finds nothing
189
+ const request = drop(id);
190
+ if (request === null)
191
+ throw new HubError('not_found', 'no such hire request: it may have expired or been answered');
192
+ changed();
193
+ if (verdict === 'no-go') {
194
+ notify(`hire of ${request.name} refused`);
195
+ tell(request.by, `Relief: request for ${request.name} refused`, `The Director said no-go to hiring ${request.name}. Do not ask again unless he asks you to.`);
196
+ return view();
197
+ }
198
+ try {
199
+ const requester = hub.views().find((agent) => agent.name === request.by);
200
+ // the boss may have been edited since it asked: a Clean Room boss hires only Clean Room agents, inside its box
201
+ if (requester) {
202
+ if (requester.cleanRoom !== null && request.cleanRoom === null)
203
+ throw new HubError('forbidden', 'the boss runs in a Clean Room now: the agent it asked for would not, so ask again');
204
+ await confine(requester, request.dir);
205
+ }
206
+ const hired = await hub.hire(hireOf(request));
207
+ notify(`${hired.name} hired (asked by ${request.by})`);
208
+ tell(request.by, `Relief: ${hired.name} is staffed`, `The Director said go. ${hired.name} is hired in ${hired.dir} and starting. Brief it with send_message.`);
209
+ }
210
+ catch (error) {
211
+ const reason = error instanceof HubError ? error.message : 'an internal error';
212
+ if (!(error instanceof HubError))
213
+ log.error('hire after a go failed', error);
214
+ notify(`${request.name} could not be hired: ${reason}`);
215
+ tell(request.by, `Relief: ${request.name} could not be hired`, `The Director said go, but the hire failed: ${reason}.`);
216
+ throw error;
217
+ }
218
+ return view();
219
+ },
220
+ close() {
221
+ for (const { timer } of pending.values())
222
+ options.clearTimer(timer);
223
+ pending.clear();
224
+ },
225
+ };
226
+ }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Rollout (docs/rollout-spec.md): tells the Director when a newer @ulm0/gonogo exists.
3
+ *
4
+ * Once a day (not more) a plain GET asks registry.npmjs.org for the `latest` version of the package. The request has an Accept
5
+ * header and nothing else of ours: no version, no id, no cookie, nothing about the user or the machine. The answer is read
6
+ * up to a limit, must hold a stable `x.y.z`, and is cached in rollout.json (mode 0600, with the time of the try). Nothing is
7
+ * ever installed: `updateCommand` only says which command updates the way this gonogo was installed. Off with
8
+ * GONOGO_UPDATE_CHECK=0 or --no-update-check; then nothing is asked and no note shows. The clock and fetch are injected for tests.
9
+ */
10
+ import { randomBytes } from 'node:crypto';
11
+ import { readFileSync } from 'node:fs';
12
+ import { readFile, rename, rm, writeFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { FILE_MODE, nullLogger, ROLLOUT_EVERY_MS, ROLLOUT_FILE, ROLLOUT_MAX_BYTES, ROLLOUT_OFF_WORDS, ROLLOUT_TIMEOUT_MS, ROLLOUT_URL } from './constants.js';
15
+ const STABLE = /^\d{1,6}\.\d{1,6}\.\d{1,6}$/;
16
+ const CHECK_TICK_MS = 60 * 60 * 1000;
17
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
18
+ /** GONOGO_UPDATE_CHECK says no: `0`, `off`, `false` or `no`. */
19
+ export const updateCheckOff = (value) => ROLLOUT_OFF_WORDS.includes((value ?? '').trim().toLowerCase());
20
+ /** `latest` is a stable x.y.z above `current`; a prerelease of the same x.y.z is below it. Anything else is not newer. */
21
+ export function isNewer(latest, current) {
22
+ const next = STABLE.test(latest) ? latest.split('.').map(Number) : null;
23
+ const now = /^(\d+)\.(\d+)\.(\d+)(-|$)/.exec(current);
24
+ if (next === null || now === null)
25
+ return false;
26
+ for (let i = 0; i < 3; i += 1) {
27
+ const have = Number(now[i + 1]);
28
+ if (next[i] !== have)
29
+ return (next[i] ?? 0) > have;
30
+ }
31
+ return now[4] === '-';
32
+ }
33
+ /**
34
+ * The command that updates the way this gonogo was installed, from the path of its own file. `docker`: it runs in a container;
35
+ * `clone`: its folder is a git checkout. Never run by gonogo.
36
+ * shortcut: an install is told from its path (pnpm's global and dlx folders, npm's lib/node_modules); anything else gets the pnpm global command.
37
+ */
38
+ export function updateCommand(where) {
39
+ const path = where.file.replace(/\\/g, '/');
40
+ if (where.docker)
41
+ return 'docker compose pull && docker compose up -d';
42
+ if (where.clone)
43
+ return 'git pull && pnpm install && pnpm build';
44
+ if (path.includes('/pnpm/dlx/'))
45
+ return 'pnpm dlx @ulm0/gonogo@latest';
46
+ if (path.includes('/lib/node_modules/@ulm0/gonogo/'))
47
+ return 'npm install -g @ulm0/gonogo@latest';
48
+ return 'pnpm add -g @ulm0/gonogo@latest';
49
+ }
50
+ /** What `gonogo update` prints. */
51
+ export function updateText(command, docker, view) {
52
+ const state = view.newer ? `gonogo ${view.latest} is out; this is ${view.current}.` : `This is gonogo ${view.current}${view.latest === null ? '' : `; the newest the last check saw is ${view.latest}`}.`;
53
+ return [state, 'To update, run:', '', ` ${command}`, '', docker ? 'in the folder of your compose.yaml. gonogo never updates itself.' : 'gonogo never updates itself.'].join('\n') + '\n';
54
+ }
55
+ /** The last check as `gonogo --version` shows it, from the file alone: no network. */
56
+ export function cachedLatest(home) {
57
+ try {
58
+ const saved = JSON.parse(readFileSync(join(home, ROLLOUT_FILE), 'utf8'));
59
+ return isRecord(saved) && typeof saved.latest === 'string' && STABLE.test(saved.latest) ? saved.latest : null;
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ /** The body of an answer, or null when it is longer than `max` bytes. */
66
+ async function readCapped(res, max) {
67
+ const reader = res.body?.getReader();
68
+ if (reader === undefined)
69
+ return null;
70
+ const chunks = [];
71
+ let size = 0;
72
+ for (;;) {
73
+ const { done, value } = await reader.read();
74
+ if (done)
75
+ break;
76
+ size += value.length;
77
+ if (size > max) {
78
+ await reader.cancel();
79
+ return null;
80
+ }
81
+ chunks.push(value);
82
+ }
83
+ return Buffer.concat(chunks).toString('utf8');
84
+ }
85
+ export function createRollout(options) {
86
+ const log = options.log ?? nullLogger;
87
+ const path = join(options.dir, ROLLOUT_FILE);
88
+ let latest = null;
89
+ let checkedAt = null;
90
+ let timer;
91
+ let closed = false;
92
+ let running = null;
93
+ const view = () => ({
94
+ enabled: options.enabled,
95
+ current: options.current,
96
+ latest,
97
+ checkedAt,
98
+ newer: options.enabled && latest !== null && isNewer(latest, options.current),
99
+ command: options.command,
100
+ });
101
+ async function save() {
102
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
103
+ try {
104
+ await writeFile(temp, JSON.stringify({ version: 1, checkedAt, latest }, null, 2), { flag: 'wx', mode: FILE_MODE });
105
+ await rename(temp, path);
106
+ }
107
+ catch (error) {
108
+ await rm(temp, { force: true }).catch(() => undefined);
109
+ log.warn(`could not save ${ROLLOUT_FILE}: ${error instanceof Error ? error.message : String(error)}`);
110
+ }
111
+ }
112
+ /** One GET. A refusal, a timeout, a long answer or a version that is not x.y.z leaves `latest` as it was; the try still counts. */
113
+ async function ask() {
114
+ try {
115
+ const res = await options.fetch(ROLLOUT_URL, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(ROLLOUT_TIMEOUT_MS) });
116
+ // a refusal's body is not read: let the connection go
117
+ if (!res.ok)
118
+ await res.body?.cancel().catch(() => undefined);
119
+ const text = res.ok ? await readCapped(res, ROLLOUT_MAX_BYTES) : null;
120
+ const doc = text === null ? null : JSON.parse(text);
121
+ if (isRecord(doc) && typeof doc.version === 'string' && STABLE.test(doc.version))
122
+ latest = doc.version;
123
+ }
124
+ catch (error) {
125
+ log.debug(`the update check did not get an answer: ${error instanceof Error ? error.name : 'error'}`);
126
+ }
127
+ checkedAt = options.now();
128
+ await save();
129
+ const done = view();
130
+ if (!closed)
131
+ options.emit(done);
132
+ return done;
133
+ }
134
+ const check = () => (options.enabled ? (running ??= ask().finally(() => (running = null))) : Promise.resolve(view()));
135
+ const due = () => checkedAt === null || options.now() - checkedAt >= ROLLOUT_EVERY_MS || checkedAt > options.now();
136
+ return {
137
+ async load() {
138
+ try {
139
+ const saved = JSON.parse(await readFile(path, 'utf8'));
140
+ if (isRecord(saved) && saved.version === 1) {
141
+ if (typeof saved.latest === 'string' && STABLE.test(saved.latest))
142
+ latest = saved.latest;
143
+ if (typeof saved.checkedAt === 'number' && Number.isFinite(saved.checkedAt))
144
+ checkedAt = saved.checkedAt;
145
+ }
146
+ }
147
+ catch {
148
+ // no file yet, or one that is not ours: the next check makes it. Nothing in it is a secret.
149
+ }
150
+ },
151
+ view,
152
+ check,
153
+ start() {
154
+ if (!options.enabled || closed)
155
+ return;
156
+ const tick = () => {
157
+ if (closed)
158
+ return;
159
+ if (due())
160
+ void check();
161
+ timer = setTimeout(tick, CHECK_TICK_MS);
162
+ timer.unref();
163
+ };
164
+ tick();
165
+ },
166
+ async close() {
167
+ closed = true;
168
+ clearTimeout(timer);
169
+ await running?.catch(() => undefined);
170
+ },
171
+ };
172
+ }
@@ -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
+ }