@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.
- package/LICENSE +21 -0
- package/README.md +476 -2
- package/bin/agent-office.js +64 -0
- package/package.json +25 -4
- package/public/app.css +1035 -0
- package/public/app.js +2034 -0
- package/public/favicon.svg +1 -0
- package/public/i18n.js +1119 -0
- package/public/index.html +141 -0
- package/public/studio.js +1951 -0
- package/public/vendor/three/LICENSE +21 -0
- package/public/vendor/three/three.core.js +61162 -0
- package/public/vendor/three/three.module.js +19537 -0
- package/src/collector.js +501 -0
- package/src/history.js +161 -0
- package/src/open.js +57 -0
- package/src/providers/antigravity-core.js +743 -0
- package/src/providers/antigravity.js +136 -0
- package/src/providers/claude-code.js +465 -0
- package/src/providers/codex.js +168 -0
- package/src/providers/demo.js +1379 -0
- package/src/providers/gemini-cli.js +115 -0
- package/src/server.js +201 -0
- package/src/state.js +142 -0
- package/src/update.js +99 -0
- package/src/util.js +139 -0
- package/src/workspace.js +112 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Antigravity CLI (agy): wraps antigravity-core.js and maps its conversation tree onto the shared session shape.
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const core = require('./antigravity-core');
|
|
7
|
+
const { MIN, DAY, Samples, readJSONFile, statOrNull } = require('../util');
|
|
8
|
+
const { guessDir } = require('../workspace');
|
|
9
|
+
|
|
10
|
+
// absolute paths inside free text; Windows paths may contain spaces ("C:\My Projects\...")
|
|
11
|
+
const PATH_RE = /(?:[a-zA-Z]:\\(?:[^\\"'<>|*?\r\n:]+\\?)+|\/(?:home|Users|mnt|srv|opt|var|tmp)\/[^\s"'<>|*?\r\n]+)/g;
|
|
12
|
+
|
|
13
|
+
class Antigravity {
|
|
14
|
+
constructor(cfg) {
|
|
15
|
+
cfg = cfg || {};
|
|
16
|
+
this.id = 'antigravity'; this.label = 'Antigravity';
|
|
17
|
+
const base = core.defaultConfig();
|
|
18
|
+
const out = cfg.runs !== undefined ? (cfg.runs || '')
|
|
19
|
+
: process.env.AO_AGY_RUNS !== undefined ? process.env.AO_AGY_RUNS
|
|
20
|
+
: base.out;
|
|
21
|
+
this.col = new core.Collector({
|
|
22
|
+
...base,
|
|
23
|
+
brain: cfg.brain || base.brain,
|
|
24
|
+
out,
|
|
25
|
+
noUsage: cfg.quota === false || base.noUsage,
|
|
26
|
+
});
|
|
27
|
+
this.samples = new Map(); // conversation id -> { version, samples }
|
|
28
|
+
this.dirs = new Map(); // conversation id -> { version, dir }
|
|
29
|
+
this.acct = null; this.acctAt = 0;
|
|
30
|
+
}
|
|
31
|
+
available() { return !!statOrNull(this.col.cfg.brain); }
|
|
32
|
+
account() {
|
|
33
|
+
if (Date.now() - this.acctAt < 5 * MIN) return this.acct;
|
|
34
|
+
this.acctAt = Date.now();
|
|
35
|
+
const j = readJSONFile(path.join(os.homedir(), '.gemini', 'google_accounts.json'));
|
|
36
|
+
const email = j && typeof j.active === 'string' ? j.active : '';
|
|
37
|
+
this.acct = email ? { name: email.split('@')[0], email } : null;
|
|
38
|
+
return this.acct;
|
|
39
|
+
}
|
|
40
|
+
scan(now, windowMs) {
|
|
41
|
+
this.col.cfg.windowMs = Math.max(windowMs, 8 * DAY);
|
|
42
|
+
const state = this.col.collect(true);
|
|
43
|
+
this.lastState = state;
|
|
44
|
+
const acct = this.account();
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const n of state.agents) {
|
|
47
|
+
const tr = this.col.transcripts.get(n.id);
|
|
48
|
+
out.push({
|
|
49
|
+
id: 'ag:' + n.id, provider: this.id, tool: this.label,
|
|
50
|
+
kind: n.kind === 'inline' ? 'subagent' : (n.kind || 'session'),
|
|
51
|
+
parent: n.parent ? 'ag:' + n.parent : null,
|
|
52
|
+
name: n.kind === 'session' ? 'Antigravity' : n.name, role: n.role || '', task: n.task || '',
|
|
53
|
+
cwd: this.dirFor(n.id, tr), branch: '', client: n.kind === 'runner' ? 'runner' : 'cli',
|
|
54
|
+
user: acct ? acct.name : '', account: acct ? acct.email : '',
|
|
55
|
+
started: n.started, last: n.last, steps: n.steps, model: n.model, models: n.models || {}, tokens: n.tokens,
|
|
56
|
+
state: n.state, state_why: n.state_why, note: n.note || '', result_short: n.result_short || '',
|
|
57
|
+
last_action: lastAction(tr), partial: !!n.partial, n_files: n.n_files || 0,
|
|
58
|
+
samples: this.samplesFor(n.id, tr, now),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
samplesFor(id, tr, now) {
|
|
64
|
+
if (!tr) return null;
|
|
65
|
+
const c = this.samples.get(id);
|
|
66
|
+
if (c && c.version === tr.version) return c.samples;
|
|
67
|
+
const s = new Samples(), from = now - 8 * DAY;
|
|
68
|
+
for (const st of tr.steps) if (st.tin != null && st.ts >= from) s.add(st.ts, st.model, st.tin, st.tc, st.tout);
|
|
69
|
+
this.samples.set(id, { version: tr.version, samples: s });
|
|
70
|
+
return s;
|
|
71
|
+
}
|
|
72
|
+
dirFor(id, tr) {
|
|
73
|
+
if (!tr) return '';
|
|
74
|
+
const c = this.dirs.get(id);
|
|
75
|
+
if (c && c.version === tr.version && c.dir) return c.dir;
|
|
76
|
+
const sum = this.col.summary(id);
|
|
77
|
+
const paths = [...(sum ? sum.files.keys() : [])];
|
|
78
|
+
for (const s of tr.steps) {
|
|
79
|
+
if (s.calls) for (const k of s.calls) { const m = String(k.a || '').match(PATH_RE); if (m) paths.push(...m); }
|
|
80
|
+
if (paths.length > 400) break;
|
|
81
|
+
}
|
|
82
|
+
const first = sum && sum.firstUser ? (sum.firstUser.big || sum.firstUser.text || '') : '';
|
|
83
|
+
paths.push(...(first.match(PATH_RE) || []));
|
|
84
|
+
const dir = guessDir(paths);
|
|
85
|
+
this.dirs.set(id, { version: tr.version, dir });
|
|
86
|
+
return dir;
|
|
87
|
+
}
|
|
88
|
+
quotas(now) {
|
|
89
|
+
const q = this.col.quota;
|
|
90
|
+
if (!q.groups.length) return q.error && this.col.transcripts.size ? [{ id: 'antigravity', tool: this.label, label: 'Antigravity quota', windows: [], error: q.error, checked: null }] : [];
|
|
91
|
+
return q.groups.map((g) => ({
|
|
92
|
+
id: 'antigravity:' + g.name, tool: this.label,
|
|
93
|
+
label: g.name.replace(/\s+models?$/i, ''), shared: /and/i.test(g.name),
|
|
94
|
+
vendors: vendorsIn(g.name), checked: q.checked,
|
|
95
|
+
windows: g.limits.map((l) => {
|
|
96
|
+
const reset = Date.parse(l.reset) || 0;
|
|
97
|
+
return {
|
|
98
|
+
window: /five|5.?h/i.test(l.name) ? '5h' : /week/i.test(l.name) ? 'week' : /day/i.test(l.name) ? 'day' : 'other',
|
|
99
|
+
label: /five|week|day/i.test(l.name) ? null : l.name,
|
|
100
|
+
left_pct: l.pct, resets_at: reset > 0 && reset > 86400e3 ? reset : null,
|
|
101
|
+
note: reset > 0 && reset <= 86400e3 ? 'window not started' : null,
|
|
102
|
+
};
|
|
103
|
+
}),
|
|
104
|
+
}));
|
|
105
|
+
}
|
|
106
|
+
trace(id, limit) {
|
|
107
|
+
if (!this.available()) return null;
|
|
108
|
+
const r = this.col.trace(id.replace(/^ag:/, ''), limit);
|
|
109
|
+
if (!r) return null;
|
|
110
|
+
for (const row of r.rows) if (row.child) row.child = 'ag:' + row.child;
|
|
111
|
+
for (const m of r.messages) if (m.peer) m.peer = 'ag:' + m.peer;
|
|
112
|
+
return r;
|
|
113
|
+
}
|
|
114
|
+
expand(id, i) {
|
|
115
|
+
if (!this.available()) return null;
|
|
116
|
+
return this.col.expand(id.replace(/^ag:/, ''), i);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function lastAction(tr) {
|
|
121
|
+
if (!tr) return '';
|
|
122
|
+
for (let k = tr.steps.length - 1; k >= 0 && k > tr.steps.length - 12; k--) {
|
|
123
|
+
const s = tr.steps[k];
|
|
124
|
+
if (s.calls && s.calls.length) { const c = s.calls[s.calls.length - 1]; return c.n + (c.a ? ': ' + c.a : ''); }
|
|
125
|
+
}
|
|
126
|
+
return '';
|
|
127
|
+
}
|
|
128
|
+
function vendorsIn(name) {
|
|
129
|
+
const n = name.toLowerCase(), v = [];
|
|
130
|
+
if (n.includes('claude')) v.push('anthropic');
|
|
131
|
+
if (n.includes('gpt')) v.push('openai');
|
|
132
|
+
if (n.includes('gemini')) v.push('google');
|
|
133
|
+
return v;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
module.exports = Antigravity;
|
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Claude Code: ~/.claude/projects/<project>/<session>.jsonl, subagents in <session>/subagents/agent-*.jsonl.
|
|
3
|
+
// Read only. Each file is tailed incrementally; only compact facts are kept in memory.
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const https = require('https');
|
|
7
|
+
const {
|
|
8
|
+
MIN, HOUR, DAY, short, cut, tryJSON, statOrNull, listDir, readJSONFile, readText, JsonlTail, Samples, firstLine,
|
|
9
|
+
} = require('../util');
|
|
10
|
+
|
|
11
|
+
const MAX_FIRST = 24 * 1024 * 1024;
|
|
12
|
+
const QUOTA_POLL_MS = 5 * MIN;
|
|
13
|
+
const QUOTA_MAX_BACKOFF_MS = 60 * MIN;
|
|
14
|
+
const QUOTA_STALE_MS = 15 * MIN;
|
|
15
|
+
// bookkeeping records Claude Code writes next to the conversation; never needed here
|
|
16
|
+
const SKIP_HEAD = /^\{"type":"(api-|data-flow|queue-|attachment|file-history|tools-used|derived-from|atis|denial|artifact|cost-state|mode|last-prompt|progress)/;
|
|
17
|
+
|
|
18
|
+
function parseExpiresAt(v) {
|
|
19
|
+
if (typeof v === 'number' && Number.isFinite(v) && v > 0) return v < 1e12 ? v * 1000 : v;
|
|
20
|
+
if (typeof v === 'string') {
|
|
21
|
+
const s = v.trim();
|
|
22
|
+
if (!s) return 0;
|
|
23
|
+
if (/^\d+(\.\d+)?$/.test(s)) {
|
|
24
|
+
const n = Number(s);
|
|
25
|
+
return n > 0 ? (n < 1e12 ? n * 1000 : n) : 0;
|
|
26
|
+
}
|
|
27
|
+
const ts = Date.parse(s);
|
|
28
|
+
return Number.isNaN(ts) ? 0 : ts;
|
|
29
|
+
}
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
function getHeader(headers, name) {
|
|
33
|
+
if (!headers || typeof headers !== 'object') return null;
|
|
34
|
+
const low = name.toLowerCase();
|
|
35
|
+
for (const k of Object.keys(headers)) {
|
|
36
|
+
if (k.toLowerCase() === low) return headers[k];
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
function parseRetryAfter(val, now) {
|
|
41
|
+
if (val == null) return 0;
|
|
42
|
+
const s = String(val).trim();
|
|
43
|
+
if (!s) return 0;
|
|
44
|
+
if (/^\d+(\.\d+)?$/.test(s)) return Math.max(0, Math.round(Number(s) * 1000));
|
|
45
|
+
const ts = Date.parse(s);
|
|
46
|
+
if (!Number.isNaN(ts)) return Math.max(0, ts - now);
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function textOf(content) {
|
|
51
|
+
if (typeof content === 'string') return content;
|
|
52
|
+
if (!Array.isArray(content)) return '';
|
|
53
|
+
return content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('\n');
|
|
54
|
+
}
|
|
55
|
+
function cleanPrompt(t) {
|
|
56
|
+
t = String(t || '');
|
|
57
|
+
const note = /<note>\s*([\s\S]*?)\s*<\/note>/.exec(t);
|
|
58
|
+
if (note) t = note[1];
|
|
59
|
+
const cmd = /<command-name>([^<]*)<\/command-name>[\s\S]*?(?:<command-args>([^<]*)<\/command-args>)?/.exec(t);
|
|
60
|
+
if (cmd) return (cmd[1] + ' ' + (cmd[2] || '')).trim();
|
|
61
|
+
return t.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').replace(/<[^>\n]{1,80}>/g, '').trim();
|
|
62
|
+
}
|
|
63
|
+
function toolArg(name, input) {
|
|
64
|
+
input = input || {};
|
|
65
|
+
const v = input.command || input.file_path || input.path || input.pattern || input.url || input.query
|
|
66
|
+
|| input.description || input.prompt || input.skill || '';
|
|
67
|
+
return short((name === 'Bash' && input.description ? input.description + ': ' : '') + (typeof v === 'string' ? v : JSON.stringify(v)), 200);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
class Session {
|
|
71
|
+
constructor(id, file, meta) {
|
|
72
|
+
this.id = id; this.file = file; this.tail = new JsonlTail(file, { maxFirst: MAX_FIRST, skipHead: SKIP_HEAD, maxLine: 64 * 1024, onBig: (b, x, y) => this.bigLine(b, x, y) });
|
|
73
|
+
this.meta = meta || null;
|
|
74
|
+
this.reset();
|
|
75
|
+
}
|
|
76
|
+
reset() {
|
|
77
|
+
this.seen = new Set(); this.samples = new Samples(); this.models = {}; this.tokens = { in: 0, cache: 0, out: 0 };
|
|
78
|
+
this.first = 0; this.last = 0; this.steps = 0; this.cwd = ''; this.branch = ''; this.client = ''; this.version = '';
|
|
79
|
+
this.prompt = ''; this.metaPrompt = ''; this.title = ''; this.end = ''; this.lastAction = ''; this.pendingTools = 0;
|
|
80
|
+
this.files = new Map(); this.limits = [];
|
|
81
|
+
}
|
|
82
|
+
update() {
|
|
83
|
+
const r = this.tail.update((line) => this.line(line));
|
|
84
|
+
if (r === 'reset') { this.reset(); this.tail.update((line) => this.line(line)); }
|
|
85
|
+
return r;
|
|
86
|
+
}
|
|
87
|
+
// A very long line is almost always a user record carrying a large tool result or a pasted image.
|
|
88
|
+
// Only what the state needs is read from it, without decoding the whole line.
|
|
89
|
+
bigLine(buf, a, b) {
|
|
90
|
+
const tail = buf.toString('utf8', Math.max(a, b - 4096), b);
|
|
91
|
+
if (!tail.includes('"type":"user"') && !buf.toString('utf8', a, Math.min(b, a + 600)).includes('"type":"user"')) return;
|
|
92
|
+
const ts = Date.parse((/"timestamp":"([^"]+)"/.exec(tail) || [])[1]) || 0;
|
|
93
|
+
if (ts) { if (!this.first || ts < this.first) this.first = ts; if (ts > this.last) this.last = ts; }
|
|
94
|
+
let n = 0, pos = a;
|
|
95
|
+
for (;;) { const k = buf.indexOf('"type":"tool_result"', pos); if (k < 0 || k >= b) break; n++; pos = k + 20; }
|
|
96
|
+
if (n) { this.pendingTools = Math.max(0, this.pendingTools - n); this.end = this.pendingTools ? 'tool' : ''; }
|
|
97
|
+
else this.end = '';
|
|
98
|
+
}
|
|
99
|
+
line(text) {
|
|
100
|
+
// cheap pre-filter: skip the large bookkeeping records Claude Code also writes
|
|
101
|
+
if (!(text.includes('"type":"assistant"') || text.includes('"type":"user"') || text.includes('-title"') || text.includes('"type":"summary"'))) return;
|
|
102
|
+
const o = tryJSON(text); if (!o || typeof o !== 'object') return;
|
|
103
|
+
const ts = Date.parse(o.timestamp) || 0;
|
|
104
|
+
if (o.type === 'ai-title' || o.type === 'custom-title' || o.type === 'summary') {
|
|
105
|
+
const t = o.title || o.customTitle || o.aiTitle || o.summary;
|
|
106
|
+
if (t && (o.type === 'custom-title' || !this.title)) this.title = short(t, 160);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (o.type !== 'user' && o.type !== 'assistant') return;
|
|
110
|
+
if (ts) { if (!this.first || ts < this.first) this.first = ts; if (ts > this.last) this.last = ts; }
|
|
111
|
+
if (o.cwd) this.cwd = o.cwd;
|
|
112
|
+
if (o.gitBranch) this.branch = o.gitBranch;
|
|
113
|
+
if (o.entrypoint) this.client = o.entrypoint;
|
|
114
|
+
if (o.version) this.version = o.version;
|
|
115
|
+
const msg = o.message || {};
|
|
116
|
+
if (o.type === 'user') {
|
|
117
|
+
const c = msg.content;
|
|
118
|
+
const isResult = Array.isArray(c) && c.some((b) => b && b.type === 'tool_result');
|
|
119
|
+
if (isResult) {
|
|
120
|
+
this.pendingTools = Math.max(0, this.pendingTools - c.filter((b) => b && b.type === 'tool_result').length);
|
|
121
|
+
this.end = this.pendingTools ? 'tool' : '';
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const t = cleanPrompt(textOf(c));
|
|
125
|
+
if (!t) return;
|
|
126
|
+
if (o.isMeta || o.textNotTyped) { if (!this.metaPrompt) this.metaPrompt = t; }
|
|
127
|
+
else if (!this.prompt) this.prompt = t;
|
|
128
|
+
if (/^\[Request interrupted/.test(t)) this.end = 'canceled'; else this.end = '';
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
// assistant: one API message may span several lines (one per content block); count usage once per message id
|
|
132
|
+
const content = Array.isArray(msg.content) ? msg.content : [];
|
|
133
|
+
for (const b of content) {
|
|
134
|
+
if (b && b.type === 'tool_use') {
|
|
135
|
+
this.lastAction = b.name + (toolArg(b.name, b.input) ? ': ' + toolArg(b.name, b.input) : '');
|
|
136
|
+
this.pendingTools++;
|
|
137
|
+
const fp = b.input && (b.input.file_path || b.input.notebook_path);
|
|
138
|
+
if (fp && /^(Write|Edit|MultiEdit|NotebookEdit)$/.test(b.name)) this.files.set(fp, b.name === 'Write' && !this.files.has(fp) ? 'created' : 'edited');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (o.apiErrorParams && o.apiErrorParams.rate_limit_info) {
|
|
142
|
+
const li = o.apiErrorParams.rate_limit_info;
|
|
143
|
+
if (li.resetsAt) this.limits.push({ ts, kind: li.rateLimitType || '', resetsAt: li.resetsAt * 1000 });
|
|
144
|
+
}
|
|
145
|
+
const id = msg.id || o.uuid;
|
|
146
|
+
if (this.seen.has(id)) { this.stopReason(msg); return; }
|
|
147
|
+
this.seen.add(id);
|
|
148
|
+
if (msg.model && msg.model !== '<synthetic>') {
|
|
149
|
+
this.steps++;
|
|
150
|
+
const u = msg.usage || {};
|
|
151
|
+
const tin = (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0), tc = u.cache_read_input_tokens || 0, tout = u.output_tokens || 0;
|
|
152
|
+
if (tin || tc || tout) {
|
|
153
|
+
const m = this.models[msg.model] || (this.models[msg.model] = { in: 0, cache: 0, out: 0 });
|
|
154
|
+
m.in += tin; m.cache += tc; m.out += tout;
|
|
155
|
+
this.tokens.in += tin; this.tokens.cache += tc; this.tokens.out += tout;
|
|
156
|
+
this.samples.add(ts, msg.model, tin, tc, tout);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
this.stopReason(msg);
|
|
160
|
+
}
|
|
161
|
+
stopReason(msg) {
|
|
162
|
+
if (msg.stop_reason === 'end_turn' || msg.stop_reason === 'stop_sequence') { this.end = 'turn'; this.pendingTools = 0; }
|
|
163
|
+
else if (msg.stop_reason === 'tool_use') this.end = 'tool';
|
|
164
|
+
else if (msg.stop_reason === 'refusal') this.end = 'error';
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
class ClaudeCode {
|
|
169
|
+
constructor(cfg) {
|
|
170
|
+
const base = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
|
|
171
|
+
this.id = 'claude-code'; this.label = 'Claude Code';
|
|
172
|
+
this.root = (cfg && cfg.root) || path.join(base, 'projects');
|
|
173
|
+
this.configFile = process.env.CLAUDE_CONFIG_DIR ? path.join(base, '.claude.json') : path.join(os.homedir(), '.claude.json');
|
|
174
|
+
this.credFile = (cfg && cfg.credFile) || path.join(base, '.credentials.json');
|
|
175
|
+
this.quotaMode = (cfg && cfg.quota) || process.env.AO_CLAUDE_QUOTA || 'off';
|
|
176
|
+
this.requestFn = (cfg && cfg.request) || https.request;
|
|
177
|
+
this.fetchUsage = (cfg && cfg.fetchUsage) || null;
|
|
178
|
+
this.sessions = new Map();
|
|
179
|
+
this.acct = null; this.acctAt = 0;
|
|
180
|
+
this.q = {
|
|
181
|
+
checked: 0, tried: 0, nextTry: 0, retryAt: 0, backoff: 0,
|
|
182
|
+
authBlockedMtime: null, lastCredMtime: null,
|
|
183
|
+
busy: false, windows: null, error: null, errorCode: null,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
available() { return !!statOrNull(this.root); }
|
|
187
|
+
account() {
|
|
188
|
+
if (Date.now() - this.acctAt < 5 * MIN) return this.acct;
|
|
189
|
+
this.acctAt = Date.now();
|
|
190
|
+
const j = readJSONFile(this.configFile);
|
|
191
|
+
const a = j && j.oauthAccount;
|
|
192
|
+
this.acct = a ? { name: a.displayName || a.fullName || '', email: a.emailAddress || '', org: a.organizationName || '' } : null;
|
|
193
|
+
return this.acct;
|
|
194
|
+
}
|
|
195
|
+
scan(now, windowMs) {
|
|
196
|
+
const dirs = listDir(this.root) || [];
|
|
197
|
+
const seen = new Set(), from = now - windowMs;
|
|
198
|
+
for (const d of dirs) {
|
|
199
|
+
if (!d.isDirectory()) continue;
|
|
200
|
+
const pdir = path.join(this.root, d.name);
|
|
201
|
+
for (const f of listDir(pdir) || []) {
|
|
202
|
+
if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
|
|
203
|
+
const file = path.join(pdir, f.name);
|
|
204
|
+
const sid = f.name.slice(0, -6);
|
|
205
|
+
const st = statOrNull(file);
|
|
206
|
+
const subDir = path.join(pdir, sid, 'subagents');
|
|
207
|
+
const subSt = statOrNull(subDir);
|
|
208
|
+
const fresh = st && st.mtimeMs >= from;
|
|
209
|
+
if (fresh) this.track('cc:' + sid, file, null, seen);
|
|
210
|
+
if (subSt && subSt.mtimeMs >= from - DAY) {
|
|
211
|
+
for (const sf of listDir(subDir) || []) {
|
|
212
|
+
if (!sf.name.endsWith('.jsonl')) continue;
|
|
213
|
+
const sfile = path.join(subDir, sf.name), sst = statOrNull(sfile);
|
|
214
|
+
if (!sst || sst.mtimeMs < from) continue;
|
|
215
|
+
const aid = sf.name.slice(0, -6);
|
|
216
|
+
const meta = readJSONFile(path.join(subDir, aid + '.meta.json')) || {};
|
|
217
|
+
meta.parent = 'cc:' + sid;
|
|
218
|
+
if (!this.sessions.has('cc:' + sid)) this.track('cc:' + sid, file, null, seen);
|
|
219
|
+
this.track('cc:' + sid + '/' + aid, sfile, meta, seen);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
for (const id of [...this.sessions.keys()]) if (!seen.has(id)) this.sessions.delete(id);
|
|
225
|
+
const acct = this.account();
|
|
226
|
+
const out = [];
|
|
227
|
+
for (const s of this.sessions.values()) {
|
|
228
|
+
s.samples.prune(now - 8 * DAY);
|
|
229
|
+
if (!s.steps && !s.prompt && !s.metaPrompt) continue;
|
|
230
|
+
const m = s.meta;
|
|
231
|
+
let best = null, bestOut = -1;
|
|
232
|
+
for (const k in s.models) if (s.models[k].out > bestOut) { best = k; bestOut = s.models[k].out; }
|
|
233
|
+
out.push({
|
|
234
|
+
id: s.id, provider: this.id, tool: this.label,
|
|
235
|
+
kind: m ? 'subagent' : 'session', parent: m ? m.parent : null,
|
|
236
|
+
name: m ? (m.agentType || 'subagent') : 'Claude Code',
|
|
237
|
+
role: m ? (m.description || '') : '',
|
|
238
|
+
task: s.title || short(firstLine(s.prompt || s.metaPrompt || (m && m.description) || ''), 160),
|
|
239
|
+
cwd: s.cwd, branch: s.branch, client: s.client ? s.client.replace(/^claude-/, '') : 'cli',
|
|
240
|
+
user: acct ? acct.name : '', account: acct ? acct.email : '',
|
|
241
|
+
started: s.first, last: s.last, steps: s.steps,
|
|
242
|
+
model: best || (m && m.model) || null, models: s.models, tokens: s.tokens,
|
|
243
|
+
end: m ? (m.finished || s.end === 'turn' ? 'final' : s.end) : s.end,
|
|
244
|
+
interactive: !m, last_action: s.lastAction, partial: s.tail.partial,
|
|
245
|
+
n_files: s.files.size, samples: s.samples,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
track(id, file, meta, seen) {
|
|
251
|
+
seen.add(id);
|
|
252
|
+
let s = this.sessions.get(id);
|
|
253
|
+
if (!s) { s = new Session(id, file, meta); this.sessions.set(id, s); }
|
|
254
|
+
else if (meta) s.meta = meta;
|
|
255
|
+
s.update();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Exact limits: a rejected request records its reset time; the opt-in usage check reports both windows.
|
|
259
|
+
quotas(now) {
|
|
260
|
+
if (typeof now !== 'number') now = Date.now();
|
|
261
|
+
this.refreshQuota(now);
|
|
262
|
+
const windows = [];
|
|
263
|
+
if (this.q.windows) {
|
|
264
|
+
for (const w of this.q.windows) {
|
|
265
|
+
if (w.resets_at && w.resets_at <= now) {
|
|
266
|
+
windows.push({ window: w.window, label: w.label, left_pct: null, resets_at: w.resets_at, note: 'reset' });
|
|
267
|
+
} else {
|
|
268
|
+
windows.push({ ...w });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
let hit = null;
|
|
273
|
+
let lastOk = 0;
|
|
274
|
+
for (const s of this.sessions.values()) {
|
|
275
|
+
for (const l of s.limits) if (l.resetsAt > now && (!hit || l.ts > hit.ts)) hit = l;
|
|
276
|
+
const list = s.samples.list; if (list.length && list[list.length - 1][0] > lastOk) lastOk = list[list.length - 1][0];
|
|
277
|
+
}
|
|
278
|
+
// a limit that was hit and then followed by successful requests no longer applies (new plan, extra usage, other account)
|
|
279
|
+
if (hit && lastOk > hit.ts) hit = null;
|
|
280
|
+
const kinds = [['five_hour', '5h'], ['seven_day', 'week']];
|
|
281
|
+
for (const [k, w] of kinds) {
|
|
282
|
+
if (hit && hit.kind === k) windows.push({ window: w, left_pct: 0, resets_at: hit.resetsAt, source: 'limit reached' });
|
|
283
|
+
else windows.push({ window: w, left_pct: null, resets_at: null, note: this.quotaMode === 'oauth' ? (this.q.error ? 'unavailable' : 'checking') : 'not exposed in local files' });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (!this.sessions.size && !this.q.windows && !this.q.error) return [];
|
|
287
|
+
const checked = this.q.checked || null;
|
|
288
|
+
const stale = !!(checked && now - checked > QUOTA_STALE_MS);
|
|
289
|
+
const nextTry = this.q.retryAt && this.q.retryAt > now ? this.q.retryAt : null;
|
|
290
|
+
return [{
|
|
291
|
+
id: 'claude-code', tool: this.label, label: 'Claude subscription', vendors: ['anthropic'],
|
|
292
|
+
windows, checked, stale,
|
|
293
|
+
error: this.q.error || null, error_code: this.q.errorCode || null, next_try: nextTry,
|
|
294
|
+
optin: this.quotaMode !== 'oauth',
|
|
295
|
+
}];
|
|
296
|
+
}
|
|
297
|
+
scheduleBackoff(now, retryAfterVal) {
|
|
298
|
+
const expDelay = Math.min(QUOTA_MAX_BACKOFF_MS, QUOTA_POLL_MS * Math.pow(2, this.q.backoff));
|
|
299
|
+
this.q.backoff = Math.min(this.q.backoff + 1, 6);
|
|
300
|
+
const retryAfterMs = parseRetryAfter(retryAfterVal, now);
|
|
301
|
+
const delay = Math.max(expDelay, retryAfterMs);
|
|
302
|
+
this.q.nextTry = now + delay;
|
|
303
|
+
this.q.retryAt = this.q.nextTry;
|
|
304
|
+
}
|
|
305
|
+
doFetchUsage(tok, cb) {
|
|
306
|
+
if (this.fetchUsage) {
|
|
307
|
+
this.fetchUsage(tok, cb);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
let done = false;
|
|
311
|
+
const finish = (err, res) => { if (done) return; done = true; cb(err, res); };
|
|
312
|
+
const req = this.requestFn({
|
|
313
|
+
host: 'api.anthropic.com', path: '/api/oauth/usage', method: 'GET', timeout: 15000,
|
|
314
|
+
headers: { Authorization: 'Bearer ' + tok, 'anthropic-beta': 'oauth-2025-04-20', 'User-Agent': 'agent-office' },
|
|
315
|
+
}, (res) => {
|
|
316
|
+
let body = '';
|
|
317
|
+
if (typeof res.setEncoding === 'function') res.setEncoding('utf8');
|
|
318
|
+
res.on('data', (d) => { if (body.length < 1e5) body += d; });
|
|
319
|
+
res.on('end', () => finish(null, { statusCode: res.statusCode, headers: res.headers || {}, body }));
|
|
320
|
+
res.on('error', (e) => finish(e));
|
|
321
|
+
});
|
|
322
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
323
|
+
req.on('error', (e) => finish(e));
|
|
324
|
+
req.end();
|
|
325
|
+
}
|
|
326
|
+
refreshQuota(now) {
|
|
327
|
+
if (typeof now !== 'number') now = Date.now();
|
|
328
|
+
if (this.quotaMode !== 'oauth' || this.q.busy) return;
|
|
329
|
+
const st = statOrNull(this.credFile);
|
|
330
|
+
const mtime = st ? st.mtimeMs : null;
|
|
331
|
+
|
|
332
|
+
// On 401/403 stop calling the endpoint until the credentials file changes.
|
|
333
|
+
if (this.q.authBlockedMtime !== null) {
|
|
334
|
+
if (mtime === this.q.authBlockedMtime) return;
|
|
335
|
+
this.q.authBlockedMtime = null;
|
|
336
|
+
this.q.backoff = 0;
|
|
337
|
+
this.q.nextTry = 0;
|
|
338
|
+
}
|
|
339
|
+
if ((this.q.errorCode === 'expired' || this.q.errorCode === 'no_creds') && mtime === this.q.lastCredMtime) return;
|
|
340
|
+
if (this.q.nextTry && now < this.q.nextTry) return;
|
|
341
|
+
|
|
342
|
+
this.q.tried = now;
|
|
343
|
+
this.q.lastCredMtime = mtime;
|
|
344
|
+
const cred = readJSONFile(this.credFile);
|
|
345
|
+
const oauth = cred && cred.claudeAiOauth;
|
|
346
|
+
const tok = oauth && oauth.accessToken;
|
|
347
|
+
if (!tok) {
|
|
348
|
+
this.q.errorCode = 'no_creds';
|
|
349
|
+
this.q.error = 'no local sign-in found';
|
|
350
|
+
this.q.retryAt = 0;
|
|
351
|
+
this.q.nextTry = 0;
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const expMs = parseExpiresAt(oauth.expiresAt);
|
|
355
|
+
if (expMs > 0 && expMs <= now) {
|
|
356
|
+
this.q.errorCode = 'expired';
|
|
357
|
+
this.q.error = 'sign-in expired';
|
|
358
|
+
this.q.retryAt = 0;
|
|
359
|
+
this.q.nextTry = 0;
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
this.q.busy = true;
|
|
364
|
+
this.doFetchUsage(tok, (err, res) => {
|
|
365
|
+
this.q.busy = false;
|
|
366
|
+
if (err) {
|
|
367
|
+
this.scheduleBackoff(now, null);
|
|
368
|
+
this.q.errorCode = 'failed';
|
|
369
|
+
this.q.error = 'usage check failed: ' + (err.message || err);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const status = res.statusCode;
|
|
373
|
+
if (status === 401 || status === 403) {
|
|
374
|
+
this.q.authBlockedMtime = mtime;
|
|
375
|
+
this.q.backoff = 0;
|
|
376
|
+
this.q.nextTry = 0;
|
|
377
|
+
this.q.retryAt = 0;
|
|
378
|
+
this.q.errorCode = 'expired';
|
|
379
|
+
this.q.error = 'sign-in expired (' + status + ')';
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (status === 429 || (status >= 500 && status < 600)) {
|
|
383
|
+
this.scheduleBackoff(now, getHeader(res.headers, 'retry-after'));
|
|
384
|
+
this.q.errorCode = status === 429 ? 'rate_limit' : 'server_error';
|
|
385
|
+
this.q.error = status === 429 ? 'rate limited (429)' : 'usage check failed (' + status + ')';
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
const j = tryJSON(res.body);
|
|
389
|
+
if (status !== 200 || !j) {
|
|
390
|
+
this.q.backoff = 0;
|
|
391
|
+
this.q.nextTry = now + QUOTA_POLL_MS;
|
|
392
|
+
this.q.retryAt = this.q.nextTry;
|
|
393
|
+
this.q.errorCode = 'failed';
|
|
394
|
+
this.q.error = 'usage check failed (' + status + ')';
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const w = [];
|
|
398
|
+
const add = (o, window, label) => { if (o && typeof o.utilization === 'number') w.push({ window, label, left_pct: Math.max(0, Math.round(100 - o.utilization)), resets_at: Date.parse(o.resets_at) || null }); };
|
|
399
|
+
add(j.five_hour, '5h'); add(j.seven_day, 'week');
|
|
400
|
+
add(j.seven_day_opus, 'week', 'Weekly, Opus'); add(j.seven_day_sonnet, 'week', 'Weekly, Sonnet');
|
|
401
|
+
this.q.backoff = 0;
|
|
402
|
+
this.q.authBlockedMtime = null;
|
|
403
|
+
this.q.nextTry = now + QUOTA_POLL_MS;
|
|
404
|
+
this.q.retryAt = 0;
|
|
405
|
+
this.q.windows = w.length ? w : null;
|
|
406
|
+
if (w.length) {
|
|
407
|
+
this.q.checked = now;
|
|
408
|
+
this.q.error = null;
|
|
409
|
+
this.q.errorCode = null;
|
|
410
|
+
} else {
|
|
411
|
+
this.q.error = 'no limits in the answer';
|
|
412
|
+
this.q.errorCode = 'failed';
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
trace(id, limit) {
|
|
418
|
+
const s = this.sessions.get(id); if (!s) return null;
|
|
419
|
+
const txt = (s.tail.size > 4 * 1024 * 1024 ? require('../util').tailText(s.file, 4 * 1024 * 1024) : readText(s.file)) || '';
|
|
420
|
+
const rows = [], pending = new Map(), seen = new Set();
|
|
421
|
+
let firstPrompt = null, lastAnswer = null;
|
|
422
|
+
for (const line of txt.split('\n')) {
|
|
423
|
+
if (!(line.includes('"type":"assistant"') || line.includes('"type":"user"'))) continue;
|
|
424
|
+
const o = tryJSON(line); if (!o || !o.message) continue;
|
|
425
|
+
const ts = Date.parse(o.timestamp) || 0, msg = o.message, c = msg.content;
|
|
426
|
+
if (o.type === 'user') {
|
|
427
|
+
if (Array.isArray(c) && c.some((b) => b && b.type === 'tool_result')) {
|
|
428
|
+
for (const b of c) if (b && b.type === 'tool_result') {
|
|
429
|
+
const r = pending.get(b.tool_use_id);
|
|
430
|
+
const res = typeof b.content === 'string' ? b.content : textOf(b.content);
|
|
431
|
+
if (r) { r.res = cut(res, 300); r.dur = ts - r.ts; if (b.is_error) r.err = 1; pending.delete(b.tool_use_id); }
|
|
432
|
+
}
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const t = cleanPrompt(textOf(c)); if (!t) continue;
|
|
436
|
+
if (!firstPrompt) firstPrompt = t;
|
|
437
|
+
rows.push({ ts, kind: o.isMeta ? 'msg' : 'in', tool: o.isMeta ? 'message' : 'prompt', text: cut(t, 300) });
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const u = msg.usage || {};
|
|
441
|
+
const first = !seen.has(msg.id); seen.add(msg.id);
|
|
442
|
+
for (const b of Array.isArray(c) ? c : []) {
|
|
443
|
+
if (b.type === 'tool_use') {
|
|
444
|
+
const r = { ts, kind: b.name === 'Agent' || b.name === 'Task' ? 'sub' : 'tool', tool: b.name, arg: toolArg(b.name, b.input), model: msg.model };
|
|
445
|
+
rows.push(r); pending.set(b.id, r);
|
|
446
|
+
} else if (b.type === 'text' && b.text && b.text.trim()) {
|
|
447
|
+
rows.push({ ts, kind: 'answer', tool: 'text', text: cut(b.text.trim(), 300), model: msg.model });
|
|
448
|
+
lastAnswer = b.text;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (first && rows.length && (u.output_tokens || u.input_tokens)) {
|
|
452
|
+
const r = rows[rows.length - 1];
|
|
453
|
+
r.tin = (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0); r.tc = u.cache_read_input_tokens || 0; r.tout = u.output_tokens || 0;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
for (const r of pending.values()) r.running = 1;
|
|
457
|
+
return {
|
|
458
|
+
rows: limit === 'all' ? rows : rows.slice(-(Number(limit) || 30)), total: rows.length, partial: s.tail.partial,
|
|
459
|
+
task_full: firstPrompt || s.prompt || s.metaPrompt, result: lastAnswer ? cut(lastAnswer, 6000) : null,
|
|
460
|
+
files: [...s.files].map(([p, op]) => ({ path: p, op })).slice(-200), commands: [], messages: [],
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
module.exports = ClaudeCode;
|