@zaferyalcin/agent-office 0.0.0-stage → 0.1.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.
@@ -0,0 +1,743 @@
1
+ // Antigravity CLI reader: conversations in ~/.gemini/antigravity-cli/brain, optional runner job folders.
2
+ // Read only. Wrapped by antigravity.js, which maps its nodes onto the shared session shape.
3
+ 'use strict';
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const http = require('http');
7
+ const os = require('os');
8
+ const { exec } = require('child_process');
9
+
10
+ function defaultConfig() {
11
+ return {
12
+ brain: process.env.AGY_BRAIN || path.join(os.homedir(), '.gemini', 'antigravity-cli', 'brain'),
13
+ out: process.env.AGY_OUT || '',
14
+ usageCmd: process.env.AGY_USAGE_CMD || 'agy usage',
15
+ noUsage: !!process.env.AGY_NO_USAGE,
16
+ };
17
+ }
18
+ const CFG = {
19
+ get brain() { return defaultConfig().brain; },
20
+ get out() { return defaultConfig().out; },
21
+ get usageCmd() { return defaultConfig().usageCmd; },
22
+ get noUsage() { return defaultConfig().noUsage; },
23
+ };
24
+ const SEC = 1e3, MIN = 60e3, HOUR = 3600e3;
25
+ const TAIL_FIRST = 5 * 1024 * 1024; // files bigger than this: first read only the tail
26
+ const HEAD_BYTES = 256 * 1024; // ...plus this much of the head (first prompt)
27
+ // unfinished and silent this long: no longer "stalled" (no alert), reported as failed / abandoned
28
+ const abandonedAfter = () => (Number(process.env.AGY_ABANDON_MIN) || 90) * 60e3;
29
+ const BUILTIN_TYPES = new Set(['self', 'research', 'image-generator']);
30
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
31
+
32
+ // ---------------------------------------------------------------- small helpers
33
+ const oneLine = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim();
34
+ const cut = (s, n) => { s = String(s == null ? '' : s); return s.length > n ? s.slice(0, n - 1) + '\u2026' : s; };
35
+ const short = (s, n) => cut(oneLine(s), n);
36
+ const stripBom = (s) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
37
+ function tryJSON(s) { try { return JSON.parse(s); } catch (e) { return undefined; } }
38
+ function readText(f, max) {
39
+ try {
40
+ if (!max) return stripBom(fs.readFileSync(f, 'utf8'));
41
+ const fd = fs.openSync(f, 'r');
42
+ try { const b = Buffer.alloc(max); const n = fs.readSync(fd, b, 0, max, 0); return stripBom(b.slice(0, n).toString('utf8')); }
43
+ finally { fs.closeSync(fd); }
44
+ } catch (e) { return null; }
45
+ }
46
+ function readJSONFile(f) { const t = readText(f); return t == null ? null : tryJSON(t.trim()) || null; }
47
+ function statOrNull(f) { try { return fs.statSync(f); } catch (e) { return null; } }
48
+ function listDir(d) { try { return fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } }
49
+ function tailText(f, bytes) {
50
+ const st = statOrNull(f); if (!st) return null;
51
+ try {
52
+ const fd = fs.openSync(f, 'r');
53
+ try {
54
+ const n = Math.min(bytes, st.size), b = Buffer.alloc(n);
55
+ fs.readSync(fd, b, 0, n, st.size - n);
56
+ let s = b.toString('utf8'); if (n < st.size) s = s.slice(s.indexOf('\n') + 1);
57
+ return stripBom(s);
58
+ } finally { fs.closeSync(fd); }
59
+ } catch (e) { return null; }
60
+ }
61
+ function family(m) {
62
+ m = String(m || '').toLowerCase();
63
+ if (m.startsWith('claude')) return 'claude';
64
+ if (m.startsWith('gpt') || m.startsWith('o1') || m.startsWith('o3') || m.startsWith('o4')) return 'gpt';
65
+ if (m.startsWith('gemini') || /neon|carbon|hydrogen/.test(m)) return 'gemini';
66
+ return 'other';
67
+ }
68
+ // tool-call args arrive as an object whose values are JSON-encoded strings
69
+ function decodeArgs(args) {
70
+ const out = {};
71
+ if (!args || typeof args !== 'object') return out;
72
+ for (const k of Object.keys(args)) {
73
+ const v = args[k];
74
+ if (typeof v === 'string') { const d = tryJSON(v); out[k] = d === undefined ? v : d; } else out[k] = v;
75
+ }
76
+ return out;
77
+ }
78
+ function firstString(o) { for (const k in o) if (typeof o[k] === 'string' && o[k]) return o[k]; return ''; }
79
+ function argShort(name, a) {
80
+ switch (name) {
81
+ case 'read_file': case 'write_file': case 'edit_file': case 'view_file':
82
+ return a.Path || a.TargetFile || a.AbsolutePath || a.File || firstString(a);
83
+ case 'run_command': return (a.BypassSandbox === true || a.BypassSandbox === 'true' ? '[unsandboxed] ' : '') + (a.CommandLine || '');
84
+ case 'invoke_subagent': return (a.TypeName || '?') + (a.Role ? ' \u00b7 ' + a.Role : '') + ': ' + oneLine(a.Prompt || '');
85
+ case 'send_message': return '\u2192 ' + String(a.Recipient || '').slice(0, 8) + ': ' + oneLine(a.Message || '');
86
+ case 'search_web': return a.query || '';
87
+ case 'manage_task': case 'manage_subagents': return [a.Action, a.TaskId, Array.isArray(a.ConversationIds) ? a.ConversationIds.join(',') : ''].filter(Boolean).join(' ');
88
+ case 'update_steps': return Array.isArray(a.steps) ? a.steps.length + ' steps' : '';
89
+ case 'schedule': return a.DurationSeconds ? a.DurationSeconds + ' s: ' + oneLine(a.Prompt || '') : oneLine(a.Prompt || a.CronExpression || '');
90
+ default: return firstString(a);
91
+ }
92
+ }
93
+ function stripTimes(content) {
94
+ // GENERIC results start with one or two "Created At / Completed At" pairs
95
+ return content.replace(/^(?:Created At: \S+\s*\nCompleted At: \S+\s*\n?)+/, '');
96
+ }
97
+ function cleanUserText(c) {
98
+ const m = /<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/.exec(c);
99
+ if (m) return m[1];
100
+ return c.replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/g, '').replace(/<\/?[A-Z_]+>/g, '').trim();
101
+ }
102
+ function parseSystemMessage(c) {
103
+ const m = /\[Message\] timestamp=(\S+) sender=(\S+) priority=\S+ content=([\s\S]*)/.exec(c);
104
+ if (!m) return { text: c.replace(/<\/?SYSTEM_MESSAGE>/g, '').replace(/^The following is a [\s\S]*?attention to\.\s*/, '') };
105
+ return { sender: m[2], mts: Date.parse(m[1]) || 0, text: m[3].replace(/\s*<\/SYSTEM_MESSAGE>\s*$/, '') };
106
+ }
107
+
108
+ // ---------------------------------------------------------------- transcript parsing (compact steps)
109
+ function compactStep(o, lineOff, lineLen) {
110
+ const s = {
111
+ i: typeof o.step_index === 'number' ? o.step_index : -1,
112
+ type: o.type || '?', st: o.status || '', ts: Date.parse(o.created_at) || 0,
113
+ off: lineOff, ll: lineLen,
114
+ };
115
+ if (o.model) s.model = o.model;
116
+ if (o.input_tokens || o.cache_read_tokens || o.output_tokens) {
117
+ s.tin = o.input_tokens || 0; s.tc = o.cache_read_tokens || 0; s.tout = o.output_tokens || 0;
118
+ }
119
+ const content = typeof o.content === 'string' ? o.content : '';
120
+ s.len = content.length;
121
+ if (Array.isArray(o.truncated_fields) && o.truncated_fields.length) s.trunc = 1;
122
+ if (s.type === 'GENERIC') {
123
+ const m = /^Created At: (\S+)\s*\nCompleted At: (\S+)/.exec(content);
124
+ if (m) { const a = Date.parse(m[1]), b = Date.parse(m[2]); if (a && b) { s.t0 = a; s.dur = Math.max(0, b - a); } }
125
+ const body = stripTimes(content);
126
+ if (s.st === 'ERROR' || /^Encountered error/.test(body)) s.err = 1;
127
+ const c = /Created the following subagent:\s*\{[\s\S]*?"conversationId":\s*"([0-9a-f-]{36})"/.exec(body);
128
+ if (c) s.child = c[1];
129
+ s.text = cut(body.trim(), 300);
130
+ } else if (s.type === 'USER_INPUT') {
131
+ const t = cleanUserText(content); s.text = cut(t, 300); s.big = cut(t, 4096);
132
+ } else if (s.type === 'SYSTEM_MESSAGE') {
133
+ const p = parseSystemMessage(content);
134
+ if (p.sender) s.sender = p.sender;
135
+ s.text = cut(p.text, 300); s.big = cut(p.text, 4096);
136
+ } else if (s.type === 'PLANNER_RESPONSE') {
137
+ s.text = cut(content.trim(), 300);
138
+ if (o.thinking) s.think = cut(oneLine(o.thinking), 200);
139
+ if (Array.isArray(o.tool_calls) && o.tool_calls.length) {
140
+ s.calls = o.tool_calls.map((tc) => {
141
+ const a = decodeArgs(tc.args), c = { n: tc.name || '?', a: short(argShort(tc.name, a), 220) };
142
+ if (tc.name === 'write_file' || tc.name === 'edit_file') {
143
+ c.file = a.Path || a.TargetFile || '';
144
+ c.op = tc.name === 'write_file' && !(a.Overwrite === true || a.Overwrite === 'true' || a.Append === true || a.Append === 'true') ? 'created' : 'edited';
145
+ }
146
+ if (tc.name === 'run_command') c.cmd = cut(oneLine(a.CommandLine || ''), 400);
147
+ if (tc.name === 'invoke_subagent') { c.big = cut(String(a.Prompt || ''), 4096); c.role = a.Role || ''; c.type = a.TypeName || ''; }
148
+ if (tc.name === 'send_message') { c.to = a.Recipient || ''; c.big = cut(String(a.Message || ''), 4096); }
149
+ return c;
150
+ });
151
+ } else if (content) s.big = cut(content.trim(), 4096);
152
+ } else {
153
+ s.text = cut(content.trim(), 300);
154
+ }
155
+ return s;
156
+ }
157
+
158
+ class Transcript {
159
+ constructor(id, file) {
160
+ this.id = id; this.file = file;
161
+ this.size = 0; this.mtimeMs = 0; this.offset = 0; this.rest = null;
162
+ this.map = new Map(); this.steps = []; this.partial = false; this.badLines = 0; this.version = 0;
163
+ this.error = null;
164
+ }
165
+ // Read only bytes appended since the last call. A trailing half-written line is kept for next time.
166
+ update() {
167
+ const st = statOrNull(this.file);
168
+ if (!st) { this.error = 'missing'; return false; }
169
+ this.error = null;
170
+ if (st.size === this.size && st.mtimeMs === this.mtimeMs) return false;
171
+ if (st.size < this.offset) { // rewritten / truncated: start over
172
+ this.offset = 0; this.rest = null; this.map.clear(); this.partial = false;
173
+ }
174
+ let fd;
175
+ try { fd = fs.openSync(this.file, 'r'); } catch (e) { this.error = e.code; return false; }
176
+ try {
177
+ if (this.offset === 0 && st.size > TAIL_FIRST) {
178
+ // huge file, first read: head (for the first prompt) + tail
179
+ const hb = Buffer.alloc(Math.min(HEAD_BYTES, st.size));
180
+ fs.readSync(fd, hb, 0, hb.length, 0);
181
+ const lastNl = hb.lastIndexOf(10);
182
+ if (lastNl > 0) this._ingest(hb.slice(0, lastNl + 1), 0, false);
183
+ const start = st.size - TAIL_FIRST;
184
+ const tb = Buffer.alloc(TAIL_FIRST);
185
+ fs.readSync(fd, tb, 0, TAIL_FIRST, start);
186
+ const nl = tb.indexOf(10);
187
+ this.partial = true;
188
+ this.offset = start + nl + 1;
189
+ this.rest = null;
190
+ this._ingest(tb.slice(nl + 1), this.offset, true);
191
+ } else if (st.size > this.offset) {
192
+ const len = st.size - this.offset, b = Buffer.alloc(len);
193
+ let got = 0; while (got < len) { const n = fs.readSync(fd, b, got, len - got, this.offset + got); if (!n) break; got += n; }
194
+ this._ingest(b.slice(0, got), this.offset, true);
195
+ }
196
+ } catch (e) { this.error = e.code || String(e); }
197
+ finally { fs.closeSync(fd); }
198
+ this.size = st.size; this.mtimeMs = st.mtimeMs;
199
+ this.steps = [...this.map.values()].sort((a, b) => a.i - b.i);
200
+ // token-bearing steps without a model field inherit the model of the step before them
201
+ let lastModel = null;
202
+ for (const s of this.steps) { if (s.model) lastModel = s.model; else if (s.tin != null && lastModel) s.model = lastModel; }
203
+ this.version++;
204
+ return true;
205
+ }
206
+ _ingest(buf, base, advance) {
207
+ let data = buf, dataBase = base;
208
+ if (advance && this.rest && this.rest.length) { data = Buffer.concat([this.rest, buf]); dataBase = base - this.rest.length; }
209
+ let pos = 0;
210
+ for (;;) {
211
+ const nl = data.indexOf(10, pos);
212
+ if (nl < 0) break;
213
+ this._line(data, pos, nl, dataBase);
214
+ pos = nl + 1;
215
+ }
216
+ let rest = data.slice(pos);
217
+ // a final line without "\n" that already parses is complete (writer may not end with a newline)
218
+ if (rest.length && this._line(data, pos, data.length, dataBase, true)) { pos = data.length; rest = Buffer.alloc(0); }
219
+ // offset = end of the bytes read so far; the unfinished tail is kept in `rest` and prepended next time
220
+ if (advance) { this.rest = rest.length ? Buffer.from(rest) : null; this.offset = dataBase + data.length; }
221
+ }
222
+ _line(data, a, b, base, quiet) {
223
+ let end = b; if (end > a && data[end - 1] === 13) end--;
224
+ if (end <= a) return false;
225
+ const o = tryJSON(data.toString('utf8', a, end));
226
+ if (!o || typeof o !== 'object') { if (!quiet) this.badLines++; return false; }
227
+ const s = compactStep(o, base + a, end - a);
228
+ if (s.i < 0) s.i = this.map.size ? Math.max(...this.map.keys()) + 1 : 0;
229
+ this.map.set(s.i, s);
230
+ return true;
231
+ }
232
+ }
233
+
234
+ // ---------------------------------------------------------------- conversation summary
235
+ function summarize(tr) {
236
+ const steps = tr.steps;
237
+ const sum = {
238
+ first: 0, last: 0, steps: steps.length, maxIndex: steps.length ? steps[steps.length - 1].i : -1,
239
+ tokens: { in: 0, cache: 0, out: 0 }, models: {}, tools: {}, files: new Map(), commands: [],
240
+ firstUser: null, firstSys: null, finalText: null, lastStep: null, lastResult: null,
241
+ spawned: [], sentTo: {}, partial: tr.partial, pendingRunning: false,
242
+ };
243
+ const cmdSet = new Set();
244
+ for (const s of steps) {
245
+ if (s.ts) { if (!sum.first || s.ts < sum.first) sum.first = s.ts; if (s.ts > sum.last) sum.last = s.ts; }
246
+ if (s.t0 && s.dur != null && s.t0 + s.dur > sum.last) sum.last = s.t0 + s.dur;
247
+ if (s.tin != null) {
248
+ sum.tokens.in += s.tin; sum.tokens.cache += s.tc; sum.tokens.out += s.tout;
249
+ const m = s.model || 'unknown', mm = sum.models[m] || (sum.models[m] = { in: 0, cache: 0, out: 0 });
250
+ mm.in += s.tin; mm.cache += s.tc; mm.out += s.tout;
251
+ }
252
+ if (!sum.firstUser && s.type === 'USER_INPUT') sum.firstUser = s;
253
+ if (!sum.firstSys && s.type === 'SYSTEM_MESSAGE' && s.sender && UUID_RE.test(s.sender)) sum.firstSys = s;
254
+ if (s.calls) for (const c of s.calls) {
255
+ sum.tools[c.n] = (sum.tools[c.n] || 0) + 1;
256
+ if (c.file) { const prev = sum.files.get(c.file); sum.files.set(c.file, prev === 'created' ? 'created' : c.op); }
257
+ if (c.cmd && !cmdSet.has(c.cmd)) { cmdSet.add(c.cmd); sum.commands.push(c.cmd); }
258
+ if (c.n === 'send_message' && c.to) sum.sentTo[c.to] = { ts: s.ts, big: c.big };
259
+ }
260
+ if (s.child) sum.spawned.push({ child: s.child, i: s.i });
261
+ if (s.type === 'GENERIC') sum.lastResult = s;
262
+ if (s.type === 'PLANNER_RESPONSE' && !s.calls && s.big) sum.finalText = { ts: s.ts, big: s.big };
263
+ }
264
+ // the model reported for a conversation: the one that produced most output tokens
265
+ let best = null, bestOut = -1;
266
+ for (const m in sum.models) if (sum.models[m].out > bestOut) { best = m; bestOut = sum.models[m].out; }
267
+ sum.model = best;
268
+ sum.lastStep = steps.length ? steps[steps.length - 1] : null;
269
+ return sum;
270
+ }
271
+
272
+ // ---------------------------------------------------------------- collector
273
+ class Collector {
274
+ constructor(cfg) {
275
+ const base = defaultConfig();
276
+ this.cfg = { ...base };
277
+ if (cfg) {
278
+ for (const k of Object.keys(cfg)) {
279
+ if (cfg[k] !== undefined) this.cfg[k] = cfg[k];
280
+ }
281
+ }
282
+ this.transcripts = new Map(); // id -> Transcript
283
+ this.summaries = new Map(); // id -> {version, sum}
284
+ this.subMeta = new Map(); // childId -> {parent, typeName, role, state, spawnStepIndex}
285
+ this.subDirCache = new Map(); // parentId -> {mtimeMs, files}
286
+ this.runCache = new Map(); // folder -> {sig, data}
287
+ this.quota = { checked: 0, tried: 0, groups: [], error: null };
288
+ this.quotaBusy = false;
289
+ this.cache = null; this.cacheTs = 0;
290
+ }
291
+
292
+ // ---- agy usage (at most once a minute, async, never blocks a request)
293
+ refreshQuota(force) {
294
+ if (this.cfg.noUsage || this.quotaBusy) return;
295
+ if (!force && Date.now() - this.quota.tried < MIN) return;
296
+ this.quotaBusy = true; this.quota.tried = Date.now();
297
+ exec(this.cfg.usageCmd, { timeout: 45 * SEC, windowsHide: true, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
298
+ this.quotaBusy = false;
299
+ const groups = parseUsage(String(stdout || ''));
300
+ if (groups.length) { this.quota.groups = groups; this.quota.checked = Date.now(); this.quota.error = null; }
301
+ else this.quota.error = short((err && err.message) || stderr || 'no output from agy usage', 200);
302
+ });
303
+ }
304
+
305
+ scanBrain() {
306
+ const ents = listDir(this.cfg.brain);
307
+ if (!ents) return false;
308
+ const seen = new Set();
309
+ for (const e of ents) {
310
+ if (!e.isDirectory() || !UUID_RE.test(e.name)) continue;
311
+ const id = e.name;
312
+ const dir = path.join(this.cfg.brain, id);
313
+ let tr = this.transcripts.get(id);
314
+ if (!tr && this.cfg.windowMs) {
315
+ // conversations untouched for longer than the window are never parsed
316
+ const tst = statOrNull(path.join(dir, '.system_generated', 'logs', 'transcript.jsonl'));
317
+ if (!tst || tst.mtimeMs < Date.now() - this.cfg.windowMs) continue;
318
+ }
319
+ seen.add(id);
320
+ if (!tr) { tr = new Transcript(id, path.join(dir, '.system_generated', 'logs', 'transcript.jsonl')); this.transcripts.set(id, tr); }
321
+ tr.update();
322
+ this.scanSubagents(id, path.join(dir, '.system_generated', 'subagents'));
323
+ }
324
+ for (const id of [...this.transcripts.keys()]) if (!seen.has(id)) { this.transcripts.delete(id); this.summaries.delete(id); }
325
+ return true;
326
+ }
327
+ scanSubagents(parent, dir) {
328
+ const st = statOrNull(dir);
329
+ if (!st) return;
330
+ const c = this.subDirCache.get(parent);
331
+ if (c && c.mtimeMs === st.mtimeMs && Date.now() - c.read < 15 * SEC) return;
332
+ const ents = listDir(dir) || [];
333
+ for (const e of ents) {
334
+ if (!e.name.endsWith('.json')) continue;
335
+ const j = readJSONFile(path.join(dir, e.name));
336
+ if (!j || !j.conversationId) continue;
337
+ const d = j.subagentDescriptor || {};
338
+ this.subMeta.set(j.conversationId, { parent, typeName: d.typeName || '', role: d.role || '', state: j.state || '', spawn: j.spawnStepIndex });
339
+ }
340
+ this.subDirCache.set(parent, { mtimeMs: st.mtimeMs, read: Date.now() });
341
+ }
342
+ summary(id) {
343
+ const tr = this.transcripts.get(id); if (!tr) return null;
344
+ const c = this.summaries.get(id);
345
+ if (c && c.version === tr.version) return c.sum;
346
+ const sum = summarize(tr); this.summaries.set(id, { version: tr.version, sum }); return sum;
347
+ }
348
+
349
+ // ---- agy-out runner folders: <stamp>-<agent>/{status.json, run.json, task.md, response.md}
350
+ scanRuns() {
351
+ if (!this.cfg.out) return [];
352
+ const ents = listDir(this.cfg.out);
353
+ if (!ents) return null;
354
+ const runs = [];
355
+ for (const e of ents) {
356
+ if (!e.isDirectory()) continue;
357
+ const m = /^(\d{8})-(\d{6})-(.+)$/.exec(e.name);
358
+ if (!m) continue;
359
+ const dir = path.join(this.cfg.out, e.name);
360
+ const sSt = statOrNull(path.join(dir, 'status.json')), rSt = statOrNull(path.join(dir, 'run.json')), tSt = statOrNull(path.join(dir, 'task.md'));
361
+ const sig = [sSt && sSt.mtimeMs, rSt && rSt.mtimeMs, tSt && tSt.mtimeMs].join('|');
362
+ const c = this.runCache.get(e.name);
363
+ if (c && c.sig === sig) { runs.push(c.data); continue; }
364
+ const d = m[1], t = m[2];
365
+ const started = new Date(+d.slice(0, 4), +d.slice(4, 6) - 1, +d.slice(6, 8), +t.slice(0, 2), +t.slice(2, 4), +t.slice(4, 6)).getTime();
366
+ const status = readJSONFile(path.join(dir, 'status.json'));
367
+ const run = readJSONFile(path.join(dir, 'run.json'));
368
+ const taskTxt = readText(path.join(dir, 'task.md'), 16384);
369
+ const data = {
370
+ folder: e.name, dir, agent: (status && status.agent) || m[3], started,
371
+ status, run, conv: (run && run.conversation_id) || null,
372
+ task: taskTitle(taskTxt), updated: status && status.updated ? Date.parse(status.updated) || 0 : 0,
373
+ };
374
+ this.runCache.set(e.name, { sig, data });
375
+ runs.push(data);
376
+ }
377
+ return runs;
378
+ }
379
+
380
+ collect(force) {
381
+ const now = Date.now();
382
+ if (!force && this.cache && now - this.cacheTs < 1000) return this.cache;
383
+ const brainOk = this.scanBrain();
384
+ const runs = this.scanRuns();
385
+ if (brainOk) this.refreshQuota();
386
+ const agents = this.build(runs || [], now);
387
+ const state = {
388
+ now, version: 2,
389
+ sources: {
390
+ brain_ok: brainOk, agyout_ok: runs != null, usage_ok: !this.quota.error && !!this.quota.checked,
391
+ brain: this.cfg.brain, agyout: this.cfg.out,
392
+ usage_error: this.quota.error, bad_lines: [...this.transcripts.values()].reduce((n, t) => n + t.badLines, 0),
393
+ },
394
+ quota: { checked: this.quota.checked, groups: this.quota.groups, error: this.quota.error },
395
+
396
+ agents,
397
+ ...aggregate(agents, this, now),
398
+ };
399
+ this.cache = state; this.cacheTs = now;
400
+ return state;
401
+ }
402
+
403
+ build(runs, now) {
404
+ const nodes = new Map();
405
+ const runByConv = new Map(), runByFolder = new Map();
406
+ for (const r of runs) { r.used = false; runByFolder.set(r.folder, r); if (r.conv) runByConv.set(r.conv, r); }
407
+ // conversations
408
+ for (const [id] of this.transcripts) {
409
+ const sum = this.summary(id);
410
+ if (!sum || (!sum.steps && this.transcripts.get(id).error)) continue;
411
+ const n = baseNode(id, sum);
412
+ const meta = this.subMeta.get(id);
413
+ const firstText = sum.firstUser ? sum.firstUser.big || sum.firstUser.text : '';
414
+ // runner job? (run.json, else the first prompt names its agy-out folder)
415
+ let run = runByConv.get(id);
416
+ if (!run && firstText) {
417
+ const m = /agy-out[\\/]+(\d{8}-\d{6}-[^\\/\s]+)[\\/]/.exec(firstText);
418
+ if (m && runByFolder.has(m[1])) { run = runByFolder.get(m[1]); if (!run.conv) run.conv = id; }
419
+ }
420
+ if (meta) {
421
+ n.parent = meta.parent; n.kind = BUILTIN_TYPES.has(meta.typeName) ? 'inline' : 'subagent';
422
+ n.name = meta.typeName || 'subagent'; n.role = meta.role; n.sub_state = meta.state;
423
+ } else if (sum.firstSys && !sum.firstUser) {
424
+ n.parent = sum.firstSys.sender.split('/')[0]; n.kind = 'inline'; n.name = 'subagent';
425
+ } else if (run) {
426
+ n.kind = 'runner'; n.name = run.agent; n.out = run.dir; n.run = run; run.used = true;
427
+ } else if (/you are the producer/i.test(firstText)) {
428
+ n.kind = 'producer'; n.name = 'producer';
429
+ } else { n.kind = 'session'; n.name = 'agy session'; }
430
+ // task title
431
+ if (n.kind === 'runner' && run.task) n.task = run.task;
432
+ else if (n.kind === 'producer') { const m = /TASKS-([\w.-]+?)\.md/i.exec(firstText); n.task = m ? 'Producer: ' + m[1] : short(firstText, 160); }
433
+ else if (sum.firstSys && n.parent) n.task = (n.role ? n.role + ' \u2014 ' : '') + short(firstLine(sum.firstSys.big || sum.firstSys.text), 160);
434
+ else n.task = short(firstLine(firstText), 160);
435
+ nodes.set(id, n);
436
+ }
437
+ // runner folders without a transcript (yet)
438
+ for (const r of runs) {
439
+ if (r.used || (r.conv && nodes.has(r.conv))) continue;
440
+ const id = 'run:' + r.folder;
441
+ nodes.set(id, {
442
+ id, name: r.agent, kind: 'runner', role: '', model: null, models: {}, parent: null, children: [],
443
+ started: r.started, last: Math.max(r.updated || 0, r.started), steps: (r.status && r.status.steps) || 0,
444
+ task: r.task || r.folder, tokens: { in: 0, cache: 0, out: 0 }, tools: {}, n_files: 0, n_commands: 0,
445
+ out: r.dir, run: r, partial: false, no_transcript: true,
446
+ });
447
+ if (r.run && r.run.usage) { const u = r.run.usage; nodes.get(id).tokens = { in: u.input_tokens || 0, cache: u.cache_read_tokens || 0, out: u.output_tokens || 0 }; }
448
+ }
449
+ // children links
450
+ for (const n of nodes.values()) if (n.parent && !nodes.has(n.parent)) n.parent_missing = n.parent;
451
+ for (const n of nodes.values()) if (n.parent && nodes.has(n.parent)) nodes.get(n.parent).children.push(n.id);
452
+ // edge labels
453
+ for (const n of nodes.values()) {
454
+ if (!n.parent || !nodes.has(n.parent)) continue;
455
+ const meta = this.subMeta.get(n.id);
456
+ n.edge_label = n.role || (meta && meta.role) || short(firstLine(n.task), 60);
457
+ }
458
+ // state (children first so parents can see them)
459
+ const order = topoOrder(nodes);
460
+ for (const n of order) deriveState(n, nodes, now);
461
+ // roll-ups
462
+ const rateCut = now - 5 * MIN;
463
+ for (const n of order) {
464
+ const own = n.tokens; const tree = { in: own.in, cache: own.cache, out: own.out };
465
+ n.rate_per_min = Math.round(this.windowTokens(n.id, rateCut) / 5);
466
+ let rt = n.rate_per_min;
467
+ for (const c of n.children) { const k = nodes.get(c); tree.in += k.tokens_tree.in; tree.cache += k.tokens_tree.cache; tree.out += k.tokens_tree.out; rt += k.rate_per_min_tree; }
468
+ n.tokens_tree = tree; n.rate_per_min_tree = rt;
469
+ }
470
+ const list = [...nodes.values()].map((n) => { delete n.run; delete n._sum; return n; });
471
+ list.sort((a, b) => b.last - a.last);
472
+ return list;
473
+ }
474
+ windowTokens(id, from) {
475
+ const tr = this.transcripts.get(id); if (!tr) return 0;
476
+ let n = 0; const st = tr.steps;
477
+ for (let k = st.length - 1; k >= 0; k--) { const s = st[k]; if (s.ts && s.ts < from) break; if (s.tin != null) n += s.tin + s.tc + s.tout; }
478
+ return n;
479
+ }
480
+
481
+ // ---- on-demand detail for the inspector
482
+ trace(id, limit) {
483
+ this.collect();
484
+ const node = this.cache.agents.find((a) => a.id === id);
485
+ if (!node) return null;
486
+ const tr = this.transcripts.get(id);
487
+ const res = { id, total: 0, rows: [], task_full: null, result: null, files: [], commands: [], messages: [], events: [], extra: [] };
488
+ const runDir = node.out || null;
489
+ if (runDir) {
490
+ res.events = readEvents(path.join(this.cfg.out, 'events.log'), runDir).concat(readEvents(path.join(runDir, 'events.log'), null));
491
+ res.task_full = readText(path.join(runDir, 'task.md'), 8192);
492
+ const resp = readText(path.join(runDir, 'response.md'), 8192);
493
+ if (resp && resp.trim()) res.result = resp;
494
+ const err = readText(path.join(runDir, 'stderr.log'), 4096);
495
+ if (err && err.trim()) res.extra.push({ title: 'stderr.log', text: err });
496
+ }
497
+ if (node.kind === 'producer' && this.cfg.out) {
498
+ for (const f of ['producer-log.md', 'producer-report.md']) {
499
+ const t = tailText(path.join(this.cfg.out, f), 6144);
500
+ if (t != null) res.extra.push({ title: f, text: t });
501
+ }
502
+ }
503
+ if (!tr) return res;
504
+ const sum = this.summary(id);
505
+ const rows = buildRows(tr.steps, this);
506
+ res.total = rows.length;
507
+ res.rows = limit === 'all' ? rows : rows.slice(-(Number(limit) || 20));
508
+ res.files = [...sum.files].map(([p, op]) => ({ path: p, op })).slice(0, 300);
509
+ res.commands = sum.commands.slice(-200);
510
+ res.partial = tr.partial;
511
+ // messages with the parent (task in, notes, result out) and with children
512
+ const msgs = [];
513
+ const inbox = readInbox(path.join(this.cfg.brain, id, '.system_generated', 'messages'));
514
+ if (node.parent) {
515
+ for (const m of inbox) if (m.sender && m.sender.split('/')[0] === node.parent) msgs.push({ dir: 'in', peer: node.parent, ts: m.ts, text: m.text });
516
+ for (const s of tr.steps) if (s.calls) for (const c of s.calls) if (c.n === 'send_message' && c.to === node.parent) msgs.push({ dir: 'out', peer: node.parent, ts: s.ts, text: c.big || c.a });
517
+ } else if (sum.firstUser) {
518
+ msgs.push({ dir: 'in', peer: null, ts: sum.firstUser.ts, text: sum.firstUser.big || sum.firstUser.text });
519
+ }
520
+ for (const c of node.children) {
521
+ for (const s of tr.steps) if (s.calls) for (const k of s.calls) if (k.to === c) msgs.push({ dir: 'to-child', peer: c, ts: s.ts, text: k.big || k.a });
522
+ for (const m of inbox) if (m.sender && m.sender.split('/')[0] === c) msgs.push({ dir: 'from-child', peer: c, ts: m.ts, text: m.text });
523
+ }
524
+ msgs.sort((a, b) => a.ts - b.ts);
525
+ res.messages = msgs.slice(-60);
526
+ if (!res.task_full) { const first = msgs.find((m) => m.dir === 'in'); res.task_full = first ? first.text : (sum.firstSys ? sum.firstSys.big : null); }
527
+ if (!res.result) {
528
+ const outs = msgs.filter((m) => m.dir === 'out');
529
+ if (outs.length && (!sum.finalText || outs[outs.length - 1].ts >= sum.finalText.ts - 60 * SEC)) res.result = outs[outs.length - 1].text;
530
+ else if (sum.finalText) res.result = sum.finalText.big;
531
+ }
532
+ return res;
533
+ }
534
+ expand(id, i) {
535
+ const tr = this.transcripts.get(id); if (!tr) return null;
536
+ const s = tr.map.get(i); if (!s) return null;
537
+ let o = null;
538
+ try {
539
+ const fd = fs.openSync(tr.file, 'r');
540
+ try { const b = Buffer.alloc(s.ll); fs.readSync(fd, b, 0, s.ll, s.off); o = tryJSON(b.toString('utf8')); } finally { fs.closeSync(fd); }
541
+ } catch (e) { /* fall through */ }
542
+ if (o && s.trunc) {
543
+ // the compact log cut this step; the full log has it
544
+ const full = path.join(path.dirname(tr.file), 'transcript_full.jsonl');
545
+ const st = statOrNull(full);
546
+ if (st && st.size < 200 * 1024 * 1024) {
547
+ const txt = readText(full) || '';
548
+ const key = '"step_index":' + i + ',';
549
+ for (const line of txt.split('\n')) if (line.includes(key)) { const f = tryJSON(line); if (f && f.step_index === i) { o = f; break; } }
550
+ }
551
+ }
552
+ if (!o) return null;
553
+ let text = typeof o.content === 'string' ? o.content : '';
554
+ if (o.type === 'GENERIC') text = stripTimes(text);
555
+ if (o.type === 'USER_INPUT') text = cleanUserText(text);
556
+ if (o.type === 'SYSTEM_MESSAGE') text = parseSystemMessage(text).text;
557
+ if (Array.isArray(o.tool_calls) && o.tool_calls.length) {
558
+ text += (text ? '\n\n' : '') + o.tool_calls.map((c) => {
559
+ const a = decodeArgs(c.args);
560
+ return '\u25b8 ' + c.name + '\n' + Object.keys(a).map((k) => ' ' + k + ': ' + (typeof a[k] === 'string' ? a[k] : JSON.stringify(a[k]))).join('\n');
561
+ }).join('\n\n');
562
+ }
563
+ if (o.thinking) text = '[thinking]\n' + o.thinking + '\n\n' + text;
564
+ return { i, text: cut(text, 20480), len: text.length };
565
+ }
566
+ }
567
+
568
+ function firstLine(s) {
569
+ const lines = String(s || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
570
+ return lines[0] || '';
571
+ }
572
+ // task.md title: "Task: ..." line, else the line after a "## Task" heading, else the first line that is not boilerplate
573
+ function taskTitle(txt) {
574
+ if (!txt) return null;
575
+ const raw = txt.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
576
+ const plain = (l) => l.replace(/^#+\s*/, '').trim();
577
+ for (const l of raw) { const m = /^#*\s*task:\s*(.+)/i.exec(l); if (m) return short(m[1], 160); }
578
+ for (let k = 0; k < raw.length - 1; k++) {
579
+ if (/^#+\s*(your |the )?task\s*$/i.test(raw[k])) { const nx = raw.slice(k + 1).find((l) => !/^#/.test(l)); if (nx) return short(nx, 160); }
580
+ }
581
+ for (const l of raw) { const p = plain(l); if (/^(task for |your role|role$|rules?\b|context\b|```)/i.test(p)) continue; return short(p, 160); }
582
+ return null;
583
+ }
584
+ function baseNode(id, sum) {
585
+ return {
586
+ id, name: '', kind: '', role: '', model: sum.model, models: sum.models, parent: null, children: [],
587
+ started: sum.first, last: sum.last, steps: sum.steps, task: '',
588
+ tokens: sum.tokens, tools: sum.tools, n_files: sum.files.size, n_commands: sum.commands.length,
589
+ partial: sum.partial, _sum: sum,
590
+ };
591
+ }
592
+ function topoOrder(nodes) {
593
+ const out = [], seen = new Set();
594
+ const visit = (n, depth) => {
595
+ if (seen.has(n.id) || depth > 50) return; seen.add(n.id);
596
+ for (const c of n.children) visit(nodes.get(c), depth + 1);
597
+ out.push(n);
598
+ };
599
+ for (const n of nodes.values()) visit(n, 0);
600
+ return out;
601
+ }
602
+ // State rules (first match wins), see README: failed / done / stalled / idle / working.
603
+ function deriveState(n, nodes, now) {
604
+ const sum = n._sum, run = n.run, rs = run && run.status && run.status.state;
605
+ if (run && run.updated > n.last) n.last = run.updated;
606
+ if (run && run.status) n.note = run.status.note || '';
607
+ const age = now - (n.last || n.started || 0);
608
+ const last = sum && sum.lastStep;
609
+ let state, why = '';
610
+ if (rs === 'failed') { state = 'failed'; why = 'runner reported failed'; }
611
+ else if (rs === 'stalled') { state = 'stalled'; why = 'runner reported stalled'; }
612
+ else if (rs === 'done') { state = 'done'; why = 'runner reported done'; }
613
+ else if (last && last.type === 'PLANNER_RESPONSE' && last.st === 'CANCELED') { state = 'done'; why = 'canceled'; }
614
+ else if (last && last.type === 'PLANNER_RESPONSE' && !last.calls && last.st !== 'RUNNING') { state = 'done'; why = 'final answer'; }
615
+ else if (last && last.err && age > 2 * MIN) { state = 'failed'; why = 'last step is an error'; }
616
+ else if (age <= MIN) state = 'working';
617
+ else if (last && last.st === 'RUNNING' && age < 30 * MIN) { state = 'working'; why = 'tool call in progress'; }
618
+ else if (age <= 10 * MIN) { state = 'idle'; why = 'no step for ' + Math.round(age / SEC) + ' s'; }
619
+ else if (age <= abandonedAfter()) { state = 'stalled'; why = 'no step for ' + Math.round(age / MIN) + ' min'; }
620
+ else { state = 'failed'; why = 'abandoned: no final answer'; }
621
+ // an orchestrator that answered but still has live children is waiting on them
622
+ if (state === 'done' && why === 'final answer' && n.children.length) {
623
+ const live = n.children.map((c) => nodes.get(c)).filter((c) => c.state === 'working' || c.state === 'idle');
624
+ if (live.length) { state = live.some((c) => c.state === 'working') ? 'working' : 'idle'; why = 'waiting on ' + live.length + ' subagent' + (live.length > 1 ? 's' : ''); }
625
+ }
626
+ n.state = state; n.state_why = why;
627
+ n.ended = state === 'done' || state === 'failed' ? n.last : null;
628
+ if (sum && sum.finalText && state === 'done') n.result_short = short(sum.finalText.big, 240);
629
+ }
630
+
631
+ function buildRows(steps, col) {
632
+ // one row per tool call (duration and result from its GENERIC step), plus prompts, messages and answers
633
+ const rows = []; const queue = [];
634
+ let prevTs = 0; const first = steps.length ? steps[0].ts : 0;
635
+ for (const s of steps) {
636
+ if (s.type === 'PLANNER_RESPONSE') {
637
+ const think = s.ts && prevTs ? Math.max(0, s.ts - prevTs) : null;
638
+ const tok = s.tin != null ? { tin: s.tin, tc: s.tc, tout: s.tout } : {};
639
+ if (s.calls && s.calls.length) {
640
+ s.calls.forEach((c, k) => {
641
+ const r = { key: s.i + '.' + k, i: s.i, ts: s.ts, kind: c.n === 'invoke_subagent' ? 'sub' : 'tool', tool: c.n, arg: c.a, model: s.model, think_ms: k === 0 ? think : null };
642
+ if (k === 0) { Object.assign(r, tok); if (s.text) r.text = s.text; }
643
+ rows.push(r); queue.push(r);
644
+ });
645
+ } else {
646
+ rows.push({ key: s.i + '', i: s.i, ts: s.ts, kind: s.st === 'CANCELED' ? 'err' : 'answer', tool: s.st === 'CANCELED' ? 'canceled' : 'answer', text: s.text, len: s.len, model: s.model, think_ms: think, ...tok });
647
+ }
648
+ } else if (s.type === 'GENERIC') {
649
+ const r = queue.shift();
650
+ if (r) { r.ri = s.i; r.dur = s.dur; r.res = s.text; r.rlen = s.len; if (s.err) { r.err = 1; } if (s.child) r.child = s.child; if (s.st === 'RUNNING') r.running = 1; }
651
+ else rows.push({ key: s.i + '', i: s.i, ts: s.ts, kind: s.err ? 'err' : 'res', tool: s.err ? 'error' : 'result', res: s.text, rlen: s.len, ri: s.i, dur: s.dur });
652
+ } else if (s.type === 'USER_INPUT') {
653
+ rows.push({ key: s.i + '', i: s.i, ts: s.ts, kind: 'in', tool: 'task in', text: s.text, len: s.len });
654
+ } else if (s.type === 'SYSTEM_MESSAGE') {
655
+ rows.push({ key: s.i + '', i: s.i, ts: s.ts, kind: 'msg', tool: 'message', from: s.sender || 'system', text: s.text, len: s.len });
656
+ } else {
657
+ rows.push({ key: s.i + '', i: s.i, ts: s.ts, kind: 'res', tool: s.type.toLowerCase(), text: s.text, len: s.len });
658
+ }
659
+ if (s.ts) prevTs = s.ts;
660
+ }
661
+ for (const r of rows) r.off = first && r.ts ? r.ts - first : 0;
662
+ return rows;
663
+ }
664
+ function readInbox(dir) {
665
+ const ents = listDir(dir); if (!ents) return [];
666
+ const out = [];
667
+ for (const e of ents) {
668
+ if (!e.name.endsWith('.json') || e.name === 'read.json') continue;
669
+ const j = readJSONFile(path.join(dir, e.name));
670
+ if (!j || typeof j.content !== 'string') continue;
671
+ out.push({ sender: j.sender || '', ts: Date.parse(j.timestamp) || 0, text: cut(j.content, 8192) });
672
+ }
673
+ return out.sort((a, b) => a.ts - b.ts);
674
+ }
675
+ function readEvents(file, filterDir) {
676
+ const t = tailText(file, 64 * 1024); if (!t) return [];
677
+ const out = [];
678
+ for (const line of t.split(/\r?\n/)) {
679
+ const c = line.split('\t'); if (c.length < 3) continue;
680
+ if (filterDir && c[4] && path.normalize(c[4]).toLowerCase() !== path.normalize(filterDir).toLowerCase()) continue;
681
+ out.push({ ts: Date.parse(c[0]) || 0, agent: c[1], state: c[2], note: c[3] || '', out: c[4] || '' });
682
+ }
683
+ return out.slice(-40);
684
+ }
685
+ function producerFiles(outDir) {
686
+ const r = {};
687
+ for (const f of ['producer-log.md', 'producer-report.md']) {
688
+ const st = statOrNull(path.join(outDir, f));
689
+ r[f] = st ? { exists: true, mtime: st.mtimeMs, size: st.size } : { exists: false };
690
+ }
691
+ return r;
692
+ }
693
+ function parseUsage(txt) {
694
+ const groups = new Map();
695
+ for (const line of txt.split(/\r?\n/)) {
696
+ const c = line.split('\t').map((x) => x.trim());
697
+ if (c.length < 3) continue;
698
+ const pct = parseFloat(String(c[2]).replace('%', ''));
699
+ if (!isFinite(pct)) continue;
700
+ const g = groups.get(c[0]) || { name: c[0], left_pct: 100, limits: [] };
701
+ g.limits.push({ name: c[1], pct, reset: c[3] || null });
702
+ g.left_pct = Math.min(g.left_pct, pct);
703
+ groups.set(c[0], g);
704
+ }
705
+ return [...groups.values()];
706
+ }
707
+
708
+ function aggregate(agents, col, now) {
709
+ const day = new Date(now); day.setHours(0, 0, 0, 0);
710
+ const dayStart = day.getTime(), BIN = 10 * MIN, NB = 36, binStart = Math.floor((now - 6 * HOUR) / BIN) * BIN + BIN;
711
+ const bins = []; for (let k = 0; k < NB; k++) bins.push({ t: binStart + k * BIN - BIN, claude: 0, gpt: 0, gemini: 0, other: 0 });
712
+ let today = 0; const byModel = {};
713
+ for (const [, tr] of col.transcripts) {
714
+ for (let k = tr.steps.length - 1; k >= 0; k--) {
715
+ const s = tr.steps[k];
716
+ if (s.ts && s.ts < Math.min(dayStart, binStart - BIN)) break;
717
+ if (s.tin == null) continue;
718
+ const tot = s.tin + s.tc + s.tout;
719
+ if (s.ts >= dayStart) {
720
+ today += tot;
721
+ const m = s.model || 'unknown', b = byModel[m] || (byModel[m] = { in: 0, cache: 0, out: 0, total: 0 });
722
+ b.in += s.tin; b.cache += s.tc; b.out += s.tout; b.total += tot;
723
+ }
724
+ const bi = Math.floor((s.ts - (binStart - BIN)) / BIN);
725
+ if (bi >= 0 && bi < NB) bins[bi][family(s.model)] += tot;
726
+ }
727
+ }
728
+ const real = agents.filter((a) => a.kind);
729
+ return {
730
+ totals: {
731
+ working: real.filter((a) => a.state === 'working').length,
732
+ idle: real.filter((a) => a.state === 'idle').length,
733
+ stalled: real.filter((a) => a.state === 'stalled').map((a) => a.id),
734
+ tokens_today: today,
735
+ rate_per_min: real.filter((a) => !a.parent || !agents.some((b) => b.id === a.parent)).reduce((n, a) => n + a.rate_per_min_tree, 0),
736
+ conversations: col.transcripts.size,
737
+ },
738
+ by_model_today: byModel,
739
+ series: { bin_min: 10, bins },
740
+ };
741
+ }
742
+
743
+ module.exports = { CFG, defaultConfig, Collector, Transcript, compactStep, summarize, parseUsage, buildRows, taskTitle };