@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,501 @@
1
+ 'use strict';
2
+ // Runs every provider, puts their sessions in one shape, groups them by workspace and adds up usage.
3
+ const { MIN, HOUR, DAY, vendorOf, short } = require('./util');
4
+ const { deriveState, ageFailed, liftParents, markSuperseded, traceFailReason } = require('./state');
5
+ const { resolveWorkspace } = require('./workspace');
6
+ const { QuotaHistory } = require('./history');
7
+
8
+ const PROVIDER_LOADERS = {
9
+ 'claude-code': () => require('./providers/claude-code'),
10
+ antigravity: () => require('./providers/antigravity'),
11
+ codex: () => require('./providers/codex'),
12
+ 'gemini-cli': () => require('./providers/gemini-cli'),
13
+ };
14
+ const VENDOR_LABEL = { anthropic: 'Claude', openai: 'GPT', google: 'Gemini', xai: 'Grok', mistral: 'Mistral', deepseek: 'DeepSeek', qwen: 'Qwen', meta: 'Llama', other: 'Other models' };
15
+ const USAGE_WINDOW = 8 * DAY;
16
+
17
+ class Collector {
18
+ constructor(cfg) {
19
+ this.cfg = cfg || {};
20
+ this.demo = !!this.cfg.demo;
21
+ this.providers = [];
22
+ if (this.demo) {
23
+ const DemoProvider = require('./providers/demo');
24
+ this.providers.push(new DemoProvider(this.cfg));
25
+ } else {
26
+ const pc = this.cfg.providers || {};
27
+ for (const id of Object.keys(PROVIDER_LOADERS)) {
28
+ const c = pc[id] || {};
29
+ if (c.enabled === false) continue;
30
+ const Provider = PROVIDER_LOADERS[id]();
31
+ this.providers.push(new Provider(c));
32
+ }
33
+ }
34
+ this.cache = null; this.cacheTs = 0; this.busy = false;
35
+ this.byId = new Map();
36
+ this.failReasons = new Map(); // id -> { last, reason }
37
+ this.quotaWarnPct = typeof this.cfg.quota_warn_pct === 'number' && Number.isFinite(this.cfg.quota_warn_pct) ? this.cfg.quota_warn_pct : 10;
38
+ this.canOpen = this.cfg.allow_open !== false;
39
+ this.quotaHistory = new QuotaHistory({
40
+ history: this.demo ? false : this.cfg.history,
41
+ file: this.cfg.history_file,
42
+ demo: this.demo,
43
+ });
44
+ }
45
+
46
+ collect(nowOpt) {
47
+ const now = typeof nowOpt === 'number' ? nowOpt : Date.now();
48
+ if (nowOpt === undefined && this.cache && now - this.cacheTs < 1500) return this.cache;
49
+ const sessions = [], provInfo = [], quotas = [];
50
+ for (const p of this.providers) {
51
+ if (p.providersInfo) {
52
+ try {
53
+ if (p.available()) {
54
+ const list = p.scan(now, USAGE_WINDOW);
55
+ sessions.push(...list);
56
+ quotas.push(...(p.quotas(now) || []));
57
+ provInfo.push(...p.providersInfo(list));
58
+ }
59
+ } catch (e) {
60
+ provInfo.push({ id: p.id, label: p.label, available: false, sessions: 0, error: String((e && e.message) || e) });
61
+ console.error('[' + p.id + ']', e);
62
+ }
63
+ continue;
64
+ }
65
+ const info = { id: p.id, label: p.label, available: false, sessions: 0, error: null };
66
+ try {
67
+ info.available = p.available();
68
+ if (info.available) {
69
+ const list = p.scan(now, USAGE_WINDOW);
70
+ info.sessions = list.length;
71
+ sessions.push(...list);
72
+ quotas.push(...(p.quotas(now) || []));
73
+ }
74
+ } catch (e) { info.error = String((e && e.message) || e); console.error('[' + p.id + ']', e); }
75
+ provInfo.push(info);
76
+ }
77
+ const byId = new Map();
78
+ for (const s of sessions) { s.children = []; byId.set(s.id, s); }
79
+ for (const s of sessions) {
80
+ if (s.parent && byId.has(s.parent)) byId.get(s.parent).children.push(s.id);
81
+ else if (s.parent) { s.parent_missing = s.parent; s.parent = null; }
82
+ }
83
+ // state: children first so parents can see them
84
+ for (const s of sessions) {
85
+ if (!s.state) deriveState(s, now);
86
+ else ageFailed(s, now);
87
+ }
88
+ liftParents(byId);
89
+ // workspace: a child without its own folder sits with its parent
90
+ for (const s of sessions) if (!s.ws && s.cwd) s.ws = resolveWorkspace(s.cwd);
91
+ for (const s of sessions) {
92
+ if (s.ws) continue;
93
+ let p = s.parent && byId.get(s.parent);
94
+ for (let k = 0; p && !p.ws && k < 20; k++) p = p.parent && byId.get(p.parent);
95
+ s.ws = p && p.ws ? p.ws : null;
96
+ }
97
+ if (!this.demo) mergeLooseFolders(sessions);
98
+ const usage = this.usage(sessions, now);
99
+ // per-session extras computed from token samples, then drop the samples from the payload
100
+ const rateFrom = now - 5 * MIN, actFrom = now - 30 * MIN;
101
+ for (const s of sessions) {
102
+ const act = new Array(30).fill(0); let rate = 0;
103
+ const list = s.samples ? s.samples.list : [];
104
+ for (let k = list.length - 1; k >= 0; k--) {
105
+ const x = list[k]; if (x[0] < actFrom) break;
106
+ const b = Math.floor((x[0] - actFrom) / MIN); if (b >= 0 && b < 30) act[b]++;
107
+ if (x[0] >= rateFrom) rate += x[2];
108
+ }
109
+ s.activity = act; s.rate_per_min = Math.round(rate / 5);
110
+ s.vendor = vendorOf(s.model);
111
+ if (!s.label) s.label = labelFor(s);
112
+ s.workspace = s.ws ? s.ws.id : '';
113
+ if (!s.branch && s.ws && s.cwd) s.branch = s.ws.branch || '';
114
+ if (s.ws && s.cwd && s.ws.top && s.ws.top !== s.ws.path) s.worktree = s.ws.top;
115
+ }
116
+ markSuperseded(sessions);
117
+ // plain failure reason from the trace (cached per session last timestamp)
118
+ for (const id of [...this.failReasons.keys()]) if (!byId.has(id)) this.failReasons.delete(id);
119
+ for (const s of sessions) {
120
+ if (s.state !== 'failed') { this.failReasons.delete(s.id); continue; }
121
+ if (s.state_why !== 'last step is an error' && s.state_why !== 'runner reported failed') continue;
122
+ const c = this.failReasons.get(s.id);
123
+ let reason;
124
+ if (c && c.last === s.last) {
125
+ reason = c.reason;
126
+ } else {
127
+ reason = '';
128
+ const p = this.find(s.id);
129
+ if (p && p.available && p.available() && p.trace) {
130
+ try {
131
+ const tr = p.trace(s.id, 10);
132
+ if (s.state_why === 'last step is an error') {
133
+ reason = traceFailReason(tr);
134
+ } else if (tr && Array.isArray(tr.rows) && tr.rows.length) {
135
+ const lastRow = tr.rows[tr.rows.length - 1];
136
+ if (lastRow && (lastRow.err || lastRow.kind === 'err')) reason = traceFailReason({ rows: [lastRow] });
137
+ }
138
+ } catch (e) { /* keep current reason */ }
139
+ }
140
+ this.failReasons.set(s.id, { last: s.last, reason });
141
+ }
142
+ if (reason) s.state_why = reason;
143
+ }
144
+ // tree roll-ups (children before parents)
145
+ const done = new Set();
146
+ const roll = (s, d) => {
147
+ if (done.has(s.id) || d > 40) return s;
148
+ done.add(s.id);
149
+ const t = { in: s.tokens.in, cache: s.tokens.cache, out: s.tokens.out }; let r = s.rate_per_min;
150
+ for (const c of s.children) { const k = roll(byId.get(c), d + 1); t.in += k.tokens_tree.in; t.cache += k.tokens_tree.cache; t.out += k.tokens_tree.out; r += k.rate_per_min_tree; }
151
+ s.tokens_tree = t; s.rate_per_min_tree = r; return s;
152
+ };
153
+ for (const s of sessions) roll(s, 0);
154
+ const workspaces = this.groupWorkspaces(sessions, byId);
155
+ const warn = this.quotaWarnPct;
156
+ const outQuotas = quotas.map((q) => ({
157
+ ...q,
158
+ windows: (q.windows || []).map((w) => {
159
+ const copy = { ...w };
160
+ if (copy.left_pct != null && copy.left_pct < warn) copy.low = true;
161
+ return copy;
162
+ }),
163
+ }));
164
+ if (!this.demo) this.quotaHistory.record(outQuotas, now);
165
+ const out = sessions.map((s) => { const o = { ...s }; delete o.samples; delete o.ws; delete o.file; return o; });
166
+ out.sort((a, b) => b.last - a.last);
167
+ const roots = out.filter((s) => !s.parent);
168
+ const state = {
169
+ now, version: 3, app: { name: 'Agent Office', version: require('../package.json').version },
170
+ can_open: this.canOpen, quota_warn_pct: warn,
171
+ providers: provInfo, sessions: out, workspaces, usage, quotas: outQuotas,
172
+ totals: {
173
+ working: out.filter((s) => s.state === 'working').length,
174
+ idle: out.filter((s) => s.state === 'idle').length,
175
+ stalled: out.filter((s) => s.state === 'stalled').map((s) => s.id),
176
+ tokens_today: usage.today, rate_per_min: roots.reduce((n, s) => n + s.rate_per_min_tree, 0),
177
+ sessions: out.length,
178
+ },
179
+ };
180
+ if (this.demo) state.demo = true;
181
+ this.byId = byId;
182
+ this.cache = state; this.cacheTs = now;
183
+ return state;
184
+ }
185
+
186
+ groupWorkspaces(sessions, byId) {
187
+ const map = new Map();
188
+ for (const s of sessions) {
189
+ const key = s.ws ? s.ws.id : '~';
190
+ let w = map.get(key);
191
+ if (!w) {
192
+ w = { id: key, name: s.ws ? s.ws.name : 'Unknown folder', path: s.ws ? s.ws.path : '', branches: new Set(), tools: new Set(), users: new Set(), last: 0, working: 0, idle: 0, stalled: 0, failed: 0, total: 0 };
193
+ map.set(key, w);
194
+ }
195
+ w.total++;
196
+ if (s.branch) w.branches.add(s.branch);
197
+ w.tools.add(s.tool); if (s.user) w.users.add(s.user);
198
+ if (s.last > w.last) w.last = s.last;
199
+ if (w[s.state] != null) w[s.state]++;
200
+ }
201
+ return [...map.values()].map((w) => ({ ...w, branches: [...w.branches], tools: [...w.tools], users: [...w.users] }))
202
+ .sort((a, b) => (b.working - a.working) || (b.last - a.last));
203
+ }
204
+
205
+ usage(sessions, now) {
206
+ const day = new Date(now); day.setHours(0, 0, 0, 0);
207
+ const dayStart = day.getTime(), h5 = now - 5 * HOUR, week = now - 7 * DAY;
208
+ const BIN = 10 * MIN, NB = 36, binStart = Math.floor((now - 6 * HOUR) / BIN) * BIN;
209
+ const vendors = new Map();
210
+ let today = 0;
211
+ for (const s of sessions) {
212
+ if (!s.samples) continue;
213
+ for (const x of s.samples.list) {
214
+ const [ts, model, tot, tin, tc, tout] = x;
215
+ if (ts < week) continue;
216
+ const v = vendorOf(model);
217
+ let V = vendors.get(v);
218
+ if (!V) { V = { vendor: v, label: VENDOR_LABEL[v] || v, today: 0, h5: 0, week: 0, models: new Map(), series: new Array(NB).fill(0), tools: new Set() }; vendors.set(v, V); }
219
+ let M = V.models.get(model);
220
+ if (!M) { M = { model, today: 0, h5: 0, week: 0, in: 0, cache: 0, out: 0, tools: new Set() }; V.models.set(model, M); }
221
+ V.week += tot; M.week += tot; V.tools.add(s.tool); M.tools.add(s.tool);
222
+ if (ts >= h5) { V.h5 += tot; M.h5 += tot; }
223
+ if (ts >= dayStart) { V.today += tot; M.today += tot; M.in += tin; M.cache += tc; M.out += tout; today += tot; }
224
+ const b = Math.floor((ts - binStart) / BIN); if (b >= 0 && b < NB) V.series[b] += tot;
225
+ }
226
+ }
227
+ const list = [...vendors.values()].map((V) => ({
228
+ ...V, tools: [...V.tools],
229
+ models: [...V.models.values()].map((M) => ({ ...M, tools: [...M.tools] })).sort((a, b) => b.week - a.week),
230
+ })).sort((a, b) => b.week - a.week);
231
+ return { today, vendors: list, bin_min: 10, bin_start: binStart };
232
+ }
233
+
234
+ sessionDir(id) {
235
+ const s = this.byId.get(id);
236
+ if (!s) return null;
237
+ return s.cwd || (s.ws && s.ws.path) || '';
238
+ }
239
+
240
+ history(nowOpt) {
241
+ const state = this.collect(nowOpt);
242
+ const now = state.now;
243
+ const { days, bounds } = localDayWindow(now, 7);
244
+ const wsMap = new Map();
245
+ const vendorMap = new Map();
246
+ const rootMap = new Map();
247
+
248
+ for (const s of this.byId.values()) {
249
+ const list = s.samples ? s.samples.list : [];
250
+ if (!list.length) continue;
251
+ const wsId = s.ws ? s.ws.id : '~';
252
+ const wsName = s.ws ? s.ws.name : 'Unknown folder';
253
+ const root = rootOf(s, this.byId);
254
+ for (const x of list) {
255
+ const ts = x[0], model = x[1], tot = x[2] || 0;
256
+ if (!tot) continue;
257
+ const idx = dayIndexOf(ts, bounds);
258
+ if (idx < 0) continue;
259
+
260
+ let w = wsMap.get(wsId);
261
+ if (!w) { w = { id: wsId, name: wsName, tokens: new Array(7).fill(0), total: 0 }; wsMap.set(wsId, w); }
262
+ w.tokens[idx] += tot;
263
+ w.total += tot;
264
+
265
+ const v = vendorOf(model);
266
+ let V = vendorMap.get(v);
267
+ if (!V) { V = { vendor: v, label: VENDOR_LABEL[v] || v, tokens: new Array(7).fill(0), total: 0 }; vendorMap.set(v, V); }
268
+ V.tokens[idx] += tot;
269
+ V.total += tot;
270
+
271
+ let R = rootMap.get(root.id);
272
+ if (!R) { R = { s: root, tokens: new Array(7).fill(0), total: 0 }; rootMap.set(root.id, R); }
273
+ R.tokens[idx] += tot;
274
+ R.total += tot;
275
+ }
276
+ }
277
+
278
+ const by_workspace = [...wsMap.values()].sort((a, b) => (b.total - a.total) || a.name.localeCompare(b.name));
279
+ const by_vendor = [...vendorMap.values()].sort((a, b) => (b.total - a.total) || a.vendor.localeCompare(b.vendor));
280
+ const top_agents = [...rootMap.values()]
281
+ .filter((r) => !r.s.parent && r.total > 0)
282
+ .sort((a, b) => (b.total - a.total) || ((b.s.last || 0) - (a.s.last || 0)))
283
+ .slice(0, 12)
284
+ .map((r) => ({
285
+ id: r.s.id,
286
+ label: r.s.label,
287
+ workspace: r.s.ws ? r.s.ws.id : '~',
288
+ workspace_name: r.s.ws ? r.s.ws.name : 'Unknown folder',
289
+ tool: r.s.tool,
290
+ model: r.s.model,
291
+ tokens: r.tokens,
292
+ total: r.total,
293
+ }));
294
+
295
+ let quota;
296
+ if (this.demo && this.providers[0] && typeof this.providers[0].quotaHistory === 'function') {
297
+ quota = this.providers[0].quotaHistory(now);
298
+ } else {
299
+ quota = this.quotaHistory.list(now);
300
+ }
301
+
302
+ const res = { days, by_workspace, by_vendor, top_agents, quota };
303
+ if (this.demo) res.demo = true;
304
+ return res;
305
+ }
306
+
307
+ report(dayOpt, nowOpt) {
308
+ const state = this.collect(nowOpt);
309
+ const now = state.now;
310
+ const { days, bounds } = localDayWindow(now, 7);
311
+ const day = dayOpt == null || dayOpt === '' ? days[days.length - 1] : String(dayOpt);
312
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return null;
313
+ const dayIdx = days.indexOf(day);
314
+ if (dayIdx < 0) return null;
315
+
316
+ const dayStart = bounds[dayIdx], dayEnd = bounds[dayIdx + 1];
317
+ const inDay = (ts) => typeof ts === 'number' && ts >= dayStart && ts < dayEnd;
318
+
319
+ const vendorMap = new Map();
320
+ const rootAgg = new Map();
321
+ const getAgg = (root) => {
322
+ let a = rootAgg.get(root.id);
323
+ if (!a) { a = { root, tokens: 0, children: 0, activeOnDay: false }; rootAgg.set(root.id, a); }
324
+ return a;
325
+ };
326
+
327
+ for (const s of this.byId.values()) {
328
+ const root = rootOf(s, this.byId);
329
+ const agg = getAgg(root);
330
+ if (s.id !== root.id) agg.children++;
331
+ if (inDay(s.last) || inDay(s.started)) agg.activeOnDay = true;
332
+ const list = s.samples ? s.samples.list : [];
333
+ for (const x of list) {
334
+ const ts = x[0], model = x[1], tot = x[2] || 0;
335
+ if (!inDay(ts)) continue;
336
+ agg.activeOnDay = true;
337
+ if (!tot) continue;
338
+ agg.tokens += tot;
339
+ const v = vendorOf(model);
340
+ let V = vendorMap.get(v);
341
+ if (!V) { V = { vendor: v, label: VENDOR_LABEL[v] || v, tokens: 0 }; vendorMap.set(v, V); }
342
+ V.tokens += tot;
343
+ }
344
+ }
345
+
346
+ const wsMap = new Map();
347
+ let totalTokens = 0, totalAgents = 0, failed = 0, done = 0, active = 0;
348
+
349
+ for (const agg of rootAgg.values()) {
350
+ const r = agg.root;
351
+ if (r.parent || !agg.activeOnDay) continue;
352
+ const wsId = r.ws ? r.ws.id : '~';
353
+ const wsName = r.ws ? r.ws.name : 'Unknown folder';
354
+ let w = wsMap.get(wsId);
355
+ if (!w) { w = { id: wsId, name: wsName, tokens: 0, agents: [] }; wsMap.set(wsId, w); }
356
+ const agent = {
357
+ id: r.id,
358
+ label: r.label,
359
+ tool: r.tool,
360
+ model: r.model,
361
+ user: r.user || '',
362
+ state: r.state,
363
+ task: short(r.task || '', 200),
364
+ first: r.started || 0,
365
+ last: r.last || 0,
366
+ tokens: agg.tokens,
367
+ children: agg.children,
368
+ why: r.state === 'failed' ? (r.state_why || '') : '',
369
+ };
370
+ w.agents.push(agent);
371
+ w.tokens += agg.tokens;
372
+ totalTokens += agg.tokens;
373
+ totalAgents++;
374
+ if (r.state === 'failed') failed++;
375
+ else if (r.state === 'done') done++;
376
+ else active++;
377
+ }
378
+
379
+ const workspaces = [...wsMap.values()].map((w) => {
380
+ w.agents.sort((a, b) => (b.tokens - a.tokens) || (b.last - a.last));
381
+ return w;
382
+ }).sort((a, b) => (b.tokens - a.tokens) || (b.agents.length - a.agents.length));
383
+
384
+ const by_vendor = [...vendorMap.values()].sort((a, b) => (b.tokens - a.tokens) || a.vendor.localeCompare(b.vendor));
385
+ const totals = { tokens: totalTokens, agents: totalAgents, workspaces: workspaces.length, failed, done, active };
386
+ const markdown = buildReportMarkdown(day, totals, workspaces);
387
+
388
+ return { day, totals, by_vendor, workspaces, markdown };
389
+ }
390
+
391
+ find(id) {
392
+ for (const p of this.providers) if ((p.handles && p.handles(id)) || id.startsWith(prefixOf(p.id))) return p;
393
+ return null;
394
+ }
395
+ trace(id, limit, nowOpt) {
396
+ this.collect(nowOpt);
397
+ const p = this.find(id);
398
+ return p && p.available() && p.trace ? p.trace(id, limit, typeof nowOpt === 'number' ? nowOpt : undefined) : null;
399
+ }
400
+ expand(id, i) { const p = this.find(id); return p && p.available() && p.expand ? p.expand(id, i) : null; }
401
+ }
402
+
403
+ function formatLocalDay(d) {
404
+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
405
+ }
406
+ function localDayWindow(now, count) {
407
+ const base = new Date(now);
408
+ const y = base.getFullYear(), m = base.getMonth(), day = base.getDate();
409
+ const days = [], bounds = [];
410
+ for (let i = count - 1; i >= 0; i--) {
411
+ const d = new Date(y, m, day - i);
412
+ days.push(formatLocalDay(d));
413
+ bounds.push(d.getTime());
414
+ }
415
+ bounds.push(new Date(y, m, day + 1).getTime());
416
+ return { days, bounds };
417
+ }
418
+ function dayIndexOf(ts, bounds) {
419
+ if (ts < bounds[0] || ts >= bounds[bounds.length - 1]) return -1;
420
+ for (let i = bounds.length - 2; i >= 0; i--) if (ts >= bounds[i]) return i;
421
+ return -1;
422
+ }
423
+ function rootOf(s, byId) {
424
+ let cur = s;
425
+ const seen = new Set([cur.id]);
426
+ for (let d = 0; cur.parent && d < 40; d++) {
427
+ const p = byId.get(cur.parent);
428
+ if (!p || seen.has(p.id)) break;
429
+ seen.add(p.id);
430
+ cur = p;
431
+ }
432
+ return cur;
433
+ }
434
+ function fmtTokens(n) {
435
+ n = n || 0;
436
+ if (n >= 1e9) return (n / 1e9).toFixed(2).replace(/\.00$/, '') + 'B';
437
+ if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e8 ? 0 : 1).replace(/\.0$/, '') + 'M';
438
+ if (n >= 1e4) return Math.round(n / 1e3) + 'k';
439
+ if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k';
440
+ return String(Math.round(n));
441
+ }
442
+ function buildReportMarkdown(day, totals, workspaces) {
443
+ const lines = [
444
+ '# Agent Office daily summary, ' + day,
445
+ '',
446
+ 'Totals: ' + fmtTokens(totals.tokens) + ' tokens across ' + totals.agents + ' agent' + (totals.agents === 1 ? '' : 's') +
447
+ ' in ' + totals.workspaces + ' workspace' + (totals.workspaces === 1 ? '' : 's') +
448
+ ' (' + totals.active + ' active, ' + totals.done + ' done, ' + totals.failed + ' failed).',
449
+ ];
450
+ if (!workspaces.length) {
451
+ lines.push('', 'No agent activity recorded for this day.');
452
+ return lines.join('\n') + '\n';
453
+ }
454
+ for (const w of workspaces) {
455
+ lines.push('', '## ' + w.name, '');
456
+ for (const a of w.agents) {
457
+ const meta = a.model ? a.tool + ', ' + a.model : a.tool;
458
+ const stateTxt = a.state === 'failed' && a.why ? a.state + ' (' + a.why + ')' : a.state;
459
+ let bullet = '- **' + a.label + '** (' + meta + '): ' + stateTxt + ', ' + fmtTokens(a.tokens) + ' tokens.';
460
+ if (a.task) bullet += ' Task: ' + a.task;
461
+ lines.push(bullet);
462
+ }
463
+ }
464
+ return lines.join('\n') + '\n';
465
+ }
466
+ // A short name that says what the agent works on, instead of the tool's generic name.
467
+ // "Read C:\work\agy-out\characters-ual\TASK.md and carry it through" -> "characters-ual"
468
+ // "Read C:\work\asset-library\TASK-GALLERY.md and do it" -> "asset-library gallery"
469
+ // a subagent keeps its own name ("gem-coder"); anything else gets the first words of its task
470
+ function labelFor(s) {
471
+ if (s.kind !== 'session' && s.name) return s.name;
472
+ const task = String(s.task || '');
473
+ const m = /([^\\/\s]+)[\\/]+(?:TASKS?|BRIEF|PLAN|SPEC)(?:[-_ ]([\w-]+))?\.md/i.exec(task);
474
+ if (m) return m[1] + (m[2] ? ' ' + m[2].toLowerCase().replace(/[-_]/g, ' ') : '');
475
+ // drop path fragments (Windows paths may contain spaces, so any word with a slash or a drive letter goes)
476
+ const words = task.replace(/^(please|read|then|now)\s+/i, '').split(/\s+/).filter((w) => w && !/[\\/]/.test(w) && !/^[a-zA-Z]:$/.test(w));
477
+ const short = words.slice(0, 7).join(' ');
478
+ return short ? short.replace(/[,.;:]+$/, '') + (words.length > 7 ? '\u2026' : '') : (s.branch && s.branch !== 'HEAD' ? s.branch : s.tool);
479
+ }
480
+
481
+ // A session in a plain (non-git) subfolder of another workspace joins that workspace, so work on one
482
+ // project is listed together. The home folder and drive roots never absorb anything.
483
+ function mergeLooseFolders(sessions) {
484
+ const home = require('os').homedir().toLowerCase();
485
+ const tops = new Map();
486
+ for (const s of sessions) if (s.ws) tops.set(s.ws.path.toLowerCase(), s.ws);
487
+ const sep = require('path').sep;
488
+ for (const s of sessions) {
489
+ if (!s.ws || s.ws.git) continue;
490
+ let best = null;
491
+ for (const [p, w] of tops) {
492
+ if (w === s.ws || p === home || p.length <= 3) continue;
493
+ const mine = s.ws.path.toLowerCase();
494
+ if (mine.startsWith(p + sep) && (!best || p.length > best.path.length)) best = w;
495
+ }
496
+ if (best) s.ws = best;
497
+ }
498
+ }
499
+ function prefixOf(pid) { return { 'claude-code': 'cc:', antigravity: 'ag:', codex: 'cx:', 'gemini-cli': 'gc:' }[pid] || pid + ':'; }
500
+
501
+ module.exports = { Collector, VENDOR_LABEL, labelFor, formatLocalDay, fmtTokens };
package/src/history.js ADDED
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+ // Rolling 8-day history of quota window percentages, persisted to a local JSON file.
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { MIN, DAY, tryJSON } = require('./util');
7
+
8
+ const INTERVAL_MS = 10 * MIN;
9
+ const KEEP_MS = 8 * DAY;
10
+ const WINDOW_LABEL = { '5h': '5-hour window', week: 'Weekly', day: 'Daily', other: 'Window' };
11
+
12
+ function defaultHistoryFile() {
13
+ return path.join(os.homedir(), '.config', 'agent-office', 'quota-history.json');
14
+ }
15
+
16
+ function slug(s) {
17
+ return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
18
+ }
19
+
20
+ function quotaWindowKey(q, w, seenInCard) {
21
+ const base = String(q.id || q.tool || 'quota') + ':' + String(w.window || 'other');
22
+ if (!seenInCard || !seenInCard.has(base)) return base;
23
+ const extra = slug(w.label);
24
+ if (extra && !seenInCard.has(base + ':' + extra)) return base + ':' + extra;
25
+ let n = 2;
26
+ while (seenInCard.has(base + ':' + n)) n++;
27
+ return base + ':' + n;
28
+ }
29
+
30
+ function quotaWindowLabel(q, w) {
31
+ const winLabel = w.label || WINDOW_LABEL[w.window] || String(w.window || 'Window');
32
+ const provLabel = q.tool && q.label && q.label !== q.tool && String(q.id || '').includes(':')
33
+ ? q.tool + ' ' + q.label
34
+ : (q.tool || q.label || q.id || '');
35
+ return (provLabel ? provLabel + ' ' : '') + winLabel;
36
+ }
37
+
38
+ class QuotaHistory {
39
+ constructor(opts) {
40
+ opts = opts || {};
41
+ this.persist = opts.history !== false && !opts.demo;
42
+ this.file = opts.file || opts.history_file || defaultHistoryFile();
43
+ this.intervalMs = typeof opts.intervalMs === 'number' && opts.intervalMs > 0 ? opts.intervalMs : INTERVAL_MS;
44
+ this.keepMs = typeof opts.keepMs === 'number' && opts.keepMs > 0 ? opts.keepMs : KEEP_MS;
45
+ this.series = new Map(); // key -> { key, label, points: [[ts, left_pct], ...] }
46
+ this.lastWrite = 0;
47
+ this.dirty = false;
48
+ this.writeErrLogged = false;
49
+ if (this.persist) this.load();
50
+ }
51
+
52
+ load() {
53
+ let raw;
54
+ try { raw = fs.readFileSync(this.file, 'utf8'); } catch (e) { return; }
55
+ const data = tryJSON(raw);
56
+ if (!data || typeof data !== 'object') return;
57
+ const items = Array.isArray(data.quota) ? data.quota : (Array.isArray(data) ? data : null);
58
+ if (!items) return;
59
+ for (const item of items) {
60
+ if (!item || typeof item !== 'object' || typeof item.key !== 'string' || !item.key) continue;
61
+ if (!Array.isArray(item.points)) continue;
62
+ const pts = [];
63
+ for (const pt of item.points) {
64
+ if (!Array.isArray(pt) || pt.length < 2) continue;
65
+ const ts = pt[0], pct = pt[1];
66
+ if (typeof ts !== 'number' || !Number.isFinite(ts)) continue;
67
+ if (typeof pct !== 'number' || !Number.isFinite(pct)) continue;
68
+ pts.push([ts, pct]);
69
+ }
70
+ if (!pts.length) continue;
71
+ pts.sort((a, b) => a[0] - b[0]);
72
+ this.series.set(item.key, {
73
+ key: item.key,
74
+ label: typeof item.label === 'string' && item.label ? item.label : item.key,
75
+ points: pts,
76
+ });
77
+ }
78
+ }
79
+
80
+ prune(now) {
81
+ const cutoff = now - this.keepMs;
82
+ for (const [key, entry] of this.series) {
83
+ const pts = entry.points;
84
+ if (!pts.length) { this.series.delete(key); continue; }
85
+ if (pts[0][0] < cutoff) {
86
+ let k = 0;
87
+ while (k < pts.length && pts[k][0] < cutoff) k++;
88
+ if (k > 0) {
89
+ pts.splice(0, k);
90
+ this.dirty = true;
91
+ }
92
+ if (!pts.length) this.series.delete(key);
93
+ }
94
+ }
95
+ }
96
+
97
+ record(quotas, nowOpt) {
98
+ const now = typeof nowOpt === 'number' ? nowOpt : Date.now();
99
+ this.prune(now);
100
+ for (const q of Array.isArray(quotas) ? quotas : []) {
101
+ if (!q || !Array.isArray(q.windows)) continue;
102
+ const seenInCard = new Set();
103
+ for (const w of q.windows) {
104
+ if (!w || w.left_pct == null || typeof w.left_pct !== 'number' || !Number.isFinite(w.left_pct)) continue;
105
+ const key = quotaWindowKey(q, w, seenInCard);
106
+ seenInCard.add(key);
107
+ const label = quotaWindowLabel(q, w);
108
+ let entry = this.series.get(key);
109
+ if (!entry) {
110
+ entry = { key, label, points: [] };
111
+ this.series.set(key, entry);
112
+ } else {
113
+ entry.label = label;
114
+ }
115
+ const last = entry.points.length ? entry.points[entry.points.length - 1] : null;
116
+ if (!last || now - last[0] >= this.intervalMs) {
117
+ entry.points.push([now, w.left_pct]);
118
+ this.dirty = true;
119
+ }
120
+ }
121
+ }
122
+ if (this.persist && this.dirty && (!this.lastWrite || now - this.lastWrite >= this.intervalMs)) {
123
+ this.save(now);
124
+ }
125
+ }
126
+
127
+ save(nowOpt) {
128
+ if (!this.persist) return false;
129
+ const now = typeof nowOpt === 'number' ? nowOpt : Date.now();
130
+ try {
131
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
132
+ const payload = { version: 1, updated: now, quota: this.list(now) };
133
+ fs.writeFileSync(this.file, JSON.stringify(payload), 'utf8');
134
+ this.lastWrite = now;
135
+ this.dirty = false;
136
+ return true;
137
+ } catch (e) {
138
+ this.lastWrite = now;
139
+ if (!this.writeErrLogged) {
140
+ this.writeErrLogged = true;
141
+ console.error('[history] could not write ' + this.file + ': ' + ((e && e.message) || e));
142
+ }
143
+ return false;
144
+ }
145
+ }
146
+
147
+ list(nowOpt) {
148
+ const cutoff = typeof nowOpt === 'number' ? nowOpt - this.keepMs : -Infinity;
149
+ const out = [];
150
+ for (const entry of this.series.values()) {
151
+ const points = [];
152
+ for (const pt of entry.points) {
153
+ if (pt[0] >= cutoff) points.push([pt[0], pt[1]]);
154
+ }
155
+ if (points.length) out.push({ key: entry.key, label: entry.label, points });
156
+ }
157
+ return out;
158
+ }
159
+ }
160
+
161
+ module.exports = { QuotaHistory, defaultHistoryFile, quotaWindowKey, quotaWindowLabel, WINDOW_LABEL };