@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,115 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Google Gemini CLI: ~/.gemini/tmp/<project>/chats/session-*.json (whole JSON file, rewritten as the chat grows).
|
|
3
|
+
// The project folder is in ~/.gemini/tmp/<project>/.project_root when the CLI wrote one.
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { MIN, DAY, short, cut, tryJSON, statOrNull, listDir, readJSONFile, readText, Samples, firstLine } = require('../util');
|
|
7
|
+
|
|
8
|
+
const MAX_FILE = 32 * 1024 * 1024;
|
|
9
|
+
|
|
10
|
+
function textOf(c) {
|
|
11
|
+
if (typeof c === 'string') return c;
|
|
12
|
+
if (Array.isArray(c)) return c.map((p) => (p && (p.text || '')) || '').join('\n');
|
|
13
|
+
return '';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
class GeminiCli {
|
|
17
|
+
constructor(cfg) {
|
|
18
|
+
this.id = 'gemini-cli'; this.label = 'Gemini CLI';
|
|
19
|
+
this.root = (cfg && cfg.root) || path.join(os.homedir(), '.gemini', 'tmp');
|
|
20
|
+
this.cache = new Map(); // file -> { mtimeMs, size, data }
|
|
21
|
+
this.acct = null; this.acctAt = 0;
|
|
22
|
+
}
|
|
23
|
+
available() { return !!statOrNull(this.root); }
|
|
24
|
+
account() {
|
|
25
|
+
if (Date.now() - this.acctAt < 5 * MIN) return this.acct;
|
|
26
|
+
this.acctAt = Date.now();
|
|
27
|
+
const j = readJSONFile(path.join(os.homedir(), '.gemini', 'google_accounts.json'));
|
|
28
|
+
const email = j && typeof j.active === 'string' ? j.active : '';
|
|
29
|
+
this.acct = email ? { name: email.split('@')[0], email } : null;
|
|
30
|
+
return this.acct;
|
|
31
|
+
}
|
|
32
|
+
scan(now, windowMs) {
|
|
33
|
+
const from = now - windowMs, out = [], seen = new Set(), acct = this.account();
|
|
34
|
+
for (const p of listDir(this.root) || []) {
|
|
35
|
+
if (!p.isDirectory()) continue;
|
|
36
|
+
const pdir = path.join(this.root, p.name);
|
|
37
|
+
const chats = path.join(pdir, 'chats');
|
|
38
|
+
const cst = statOrNull(chats);
|
|
39
|
+
if (!cst || cst.mtimeMs < from - DAY) continue;
|
|
40
|
+
const rootTxt = readText(path.join(pdir, '.project_root'), 4096);
|
|
41
|
+
for (const f of listDir(chats) || []) {
|
|
42
|
+
if (!f.name.endsWith('.json')) continue;
|
|
43
|
+
const file = path.join(chats, f.name), st = statOrNull(file);
|
|
44
|
+
if (!st || st.mtimeMs < from || st.size > MAX_FILE) continue;
|
|
45
|
+
seen.add(file);
|
|
46
|
+
let c = this.cache.get(file);
|
|
47
|
+
if (!c || c.mtimeMs !== st.mtimeMs || c.size !== st.size) {
|
|
48
|
+
c = { mtimeMs: st.mtimeMs, size: st.size, data: this.parse(file, now) };
|
|
49
|
+
this.cache.set(file, c);
|
|
50
|
+
}
|
|
51
|
+
const d = c.data; if (!d) continue;
|
|
52
|
+
out.push({
|
|
53
|
+
id: 'gc:' + d.id, provider: this.id, tool: this.label, kind: 'session', parent: null, name: 'Gemini CLI', role: '',
|
|
54
|
+
task: d.task, cwd: rootTxt ? rootTxt.trim() : '', branch: '', client: 'cli',
|
|
55
|
+
user: acct ? acct.name : '', account: acct ? acct.email : '',
|
|
56
|
+
started: d.first, last: d.last, steps: d.steps, model: d.model, models: d.models,
|
|
57
|
+
tokens: d.tokens, end: d.end, interactive: true, last_action: d.lastAction, samples: d.samples, file,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
for (const k of [...this.cache.keys()]) if (!seen.has(k)) this.cache.delete(k);
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
parse(file, now) {
|
|
65
|
+
const j = readJSONFile(file);
|
|
66
|
+
if (!j || !Array.isArray(j.messages)) return null;
|
|
67
|
+
const d = { id: j.sessionId || path.basename(file, '.json'), first: Date.parse(j.startTime) || 0, last: Date.parse(j.lastUpdated) || 0,
|
|
68
|
+
steps: 0, models: {}, tokens: { in: 0, cache: 0, out: 0 }, samples: new Samples(), task: '', end: '', lastAction: '', model: null, rows: [] };
|
|
69
|
+
let bestOut = -1;
|
|
70
|
+
for (const m of j.messages) {
|
|
71
|
+
const ts = Date.parse(m.timestamp) || 0;
|
|
72
|
+
if (ts > d.last) d.last = ts;
|
|
73
|
+
if (m.type === 'user') {
|
|
74
|
+
const t = textOf(m.content).trim();
|
|
75
|
+
if (t && !d.task) d.task = short(firstLine(t), 160);
|
|
76
|
+
d.end = ''; d.rows.push({ ts, kind: 'in', tool: 'prompt', text: cut(t, 300) });
|
|
77
|
+
} else if (m.type === 'gemini' || m.type === 'model') {
|
|
78
|
+
d.steps++;
|
|
79
|
+
const tk = m.tokens || {};
|
|
80
|
+
const cached = tk.cached || 0, tin = Math.max(0, (tk.input || 0) - cached), tout = (tk.output || 0) + (tk.thoughts || 0);
|
|
81
|
+
const model = m.model || 'gemini';
|
|
82
|
+
if (tin || cached || tout) {
|
|
83
|
+
const mm = d.models[model] || (d.models[model] = { in: 0, cache: 0, out: 0 });
|
|
84
|
+
mm.in += tin; mm.cache += cached; mm.out += tout;
|
|
85
|
+
d.tokens.in += tin; d.tokens.cache += cached; d.tokens.out += tout;
|
|
86
|
+
if (ts >= now - 8 * DAY) d.samples.add(ts, model, tin, cached, tout);
|
|
87
|
+
if (mm.out > bestOut) { bestOut = mm.out; d.model = model; }
|
|
88
|
+
}
|
|
89
|
+
const calls = Array.isArray(m.toolCalls) ? m.toolCalls : [];
|
|
90
|
+
for (const c of calls) {
|
|
91
|
+
const a = c.args || {};
|
|
92
|
+
const arg = short(a.command || a.file_path || a.absolute_path || a.path || a.pattern || a.query || '', 200);
|
|
93
|
+
d.lastAction = (c.name || 'tool') + (arg ? ': ' + arg : '');
|
|
94
|
+
d.rows.push({ ts, kind: 'tool', tool: c.name || 'tool', arg, err: c.status === 'error' ? 1 : 0, res: cut(textOf(c.resultDisplay) || '', 300) });
|
|
95
|
+
}
|
|
96
|
+
const t = textOf(m.content).trim();
|
|
97
|
+
if (t) d.rows.push({ ts, kind: 'answer', tool: 'text', text: cut(t, 300), model });
|
|
98
|
+
d.end = calls.some((c) => c.status === 'executing' || c.status === 'scheduled') ? 'tool' : calls.length ? '' : 'turn';
|
|
99
|
+
} else if (m.type === 'error') { d.end = 'error'; d.rows.push({ ts, kind: 'err', tool: 'error', text: cut(textOf(m.content), 300) }); }
|
|
100
|
+
}
|
|
101
|
+
d.rows = d.rows.slice(-200);
|
|
102
|
+
return d;
|
|
103
|
+
}
|
|
104
|
+
quotas() { return []; }
|
|
105
|
+
trace(id) {
|
|
106
|
+
for (const c of this.cache.values()) if (c.data && 'gc:' + c.data.id === id) {
|
|
107
|
+
const rows = c.data.rows;
|
|
108
|
+
const firstIn = rows.find((r) => r.kind === 'in'); const lastAns = [...rows].reverse().find((r) => r.kind === 'answer');
|
|
109
|
+
return { rows: rows.slice(-30), total: rows.length, task_full: firstIn ? firstIn.text : '', result: lastAns ? lastAns.text : null, files: [], commands: [], messages: [] };
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = GeminiCli;
|
package/src/server.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Local HTTP server. Binds to 127.0.0.1 by default; read-only except for the guarded POST /api/open.
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const http = require('http');
|
|
7
|
+
const { Collector } = require('./collector');
|
|
8
|
+
const { openPath } = require('./open');
|
|
9
|
+
const { UpdateChecker, updateCheckEnabled } = require('./update');
|
|
10
|
+
const { tryJSON, readText, statOrNull } = require('./util');
|
|
11
|
+
|
|
12
|
+
const PUBLIC = path.resolve(__dirname, '..', 'public');
|
|
13
|
+
const MAX_OPEN_BODY = 4096;
|
|
14
|
+
const MIME = {
|
|
15
|
+
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
16
|
+
'.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function loadConfig(file) {
|
|
20
|
+
if (file !== undefined && file !== null) {
|
|
21
|
+
if (!file) throw new Error('Config file path is empty');
|
|
22
|
+
if (!statOrNull(file)) throw new Error('Config file not found: ' + file);
|
|
23
|
+
const t = readText(file);
|
|
24
|
+
if (t == null) throw new Error('Could not read ' + file);
|
|
25
|
+
const j = tryJSON(t);
|
|
26
|
+
if (!j || typeof j !== 'object' || Array.isArray(j)) throw new Error('Could not parse ' + file);
|
|
27
|
+
j._file = file;
|
|
28
|
+
return j;
|
|
29
|
+
}
|
|
30
|
+
const candidates = [
|
|
31
|
+
path.join(process.cwd(), 'agent-office.config.json'),
|
|
32
|
+
path.join(os.homedir(), '.config', 'agent-office', 'config.json'),
|
|
33
|
+
];
|
|
34
|
+
for (const f of candidates) {
|
|
35
|
+
const t = readText(f);
|
|
36
|
+
if (t == null) continue;
|
|
37
|
+
const j = tryJSON(t);
|
|
38
|
+
if (!j || typeof j !== 'object' || Array.isArray(j)) throw new Error('Could not parse ' + f);
|
|
39
|
+
j._file = f;
|
|
40
|
+
return j;
|
|
41
|
+
}
|
|
42
|
+
return {};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function pickPort(...vals) {
|
|
46
|
+
for (const v of vals) {
|
|
47
|
+
if (v !== undefined && v !== null && v !== '') return Number(v);
|
|
48
|
+
}
|
|
49
|
+
return 4777;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isDemoEnv() {
|
|
53
|
+
const v = String(process.env.AO_DEMO || '').trim().toLowerCase();
|
|
54
|
+
return v === '1' || v === 'true' || v === 'yes';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function serve(opts) {
|
|
58
|
+
opts = opts || {};
|
|
59
|
+
const demoOpt = !!(opts.demo || isDemoEnv());
|
|
60
|
+
const cfg = demoOpt && opts.config === undefined ? { demo: true } : loadConfig(opts.config);
|
|
61
|
+
if (demoOpt) cfg.demo = true;
|
|
62
|
+
const host = opts.host || cfg.host || '127.0.0.1';
|
|
63
|
+
const reqPort = pickPort(opts.port, process.env.AO_PORT, cfg.port);
|
|
64
|
+
const col = new Collector(cfg);
|
|
65
|
+
const updates = opts.updateCheck !== false && updateCheckEnabled(cfg) ? new UpdateChecker({ fetch: opts.fetch }).start() : null;
|
|
66
|
+
const okHosts = new Set();
|
|
67
|
+
const setOkHosts = (p) => {
|
|
68
|
+
okHosts.clear();
|
|
69
|
+
okHosts.add(host + ':' + p);
|
|
70
|
+
okHosts.add('localhost:' + p);
|
|
71
|
+
okHosts.add('127.0.0.1:' + p);
|
|
72
|
+
};
|
|
73
|
+
if (reqPort > 0) setOkHosts(reqPort);
|
|
74
|
+
const send = (res, code, body, type, cache) => {
|
|
75
|
+
res.writeHead(code, { 'Content-Type': type || 'application/json; charset=utf-8', 'Cache-Control': cache || 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' });
|
|
76
|
+
res.end(body);
|
|
77
|
+
};
|
|
78
|
+
const srv = http.createServer((req, res) => {
|
|
79
|
+
// DNS-rebinding guard: only answer requests addressed to this host
|
|
80
|
+
if (host === '127.0.0.1' && !okHosts.has(String(req.headers.host || ''))) return send(res, 403, '{"error":"bad host"}');
|
|
81
|
+
let u;
|
|
82
|
+
try { u = new URL(req.url, 'http://x'); } catch (e) { return send(res, 400, '{"error":"bad url"}'); }
|
|
83
|
+
if (req.method === 'POST' && u.pathname === '/api/open') {
|
|
84
|
+
if (cfg.allow_open === false) return send(res, 403, '{"error":"disabled"}');
|
|
85
|
+
if (String(req.headers['x-agent-office'] || '').trim() !== '1') return send(res, 403, '{"error":"missing header"}');
|
|
86
|
+
const ct = String(req.headers['content-type'] || '').toLowerCase().split(';')[0].trim();
|
|
87
|
+
if (ct !== 'application/json') return send(res, 415, '{"error":"json required"}');
|
|
88
|
+
readJsonBody(req, MAX_OPEN_BODY, (err, body) => {
|
|
89
|
+
if (err) return send(res, err.code, JSON.stringify({ error: err.msg }));
|
|
90
|
+
try {
|
|
91
|
+
const id = typeof body.id === 'string' ? body.id : '';
|
|
92
|
+
const what = body.what;
|
|
93
|
+
if (!id || (what !== 'folder' && what !== 'terminal')) return send(res, 400, '{"error":"bad request"}');
|
|
94
|
+
if (!col.cache) col.collect();
|
|
95
|
+
const dir = col.sessionDir(id);
|
|
96
|
+
if (dir === null) return send(res, 404, '{"error":"unknown session"}');
|
|
97
|
+
if (!dir) return send(res, 404, '{"error":"folder not found"}');
|
|
98
|
+
if (col.demo) return send(res, 200, JSON.stringify({ ok: true, demo: true, path: dir }));
|
|
99
|
+
const st = statOrNull(dir);
|
|
100
|
+
if (!st || !st.isDirectory()) return send(res, 404, '{"error":"folder not found"}');
|
|
101
|
+
openPath(dir, what, { spawn: opts.spawn, platform: opts.platform });
|
|
102
|
+
return send(res, 200, JSON.stringify({ ok: true, path: dir }));
|
|
103
|
+
} catch (e) {
|
|
104
|
+
console.error(e);
|
|
105
|
+
return send(res, 500, JSON.stringify({ error: String((e && e.message) || e) }));
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, '{"error":"read-only"}');
|
|
111
|
+
try {
|
|
112
|
+
if (u.pathname === '/api/state') {
|
|
113
|
+
const st = col.collect();
|
|
114
|
+
const upd = updates ? updates.info() : null;
|
|
115
|
+
if (upd) st.update = upd; else delete st.update;
|
|
116
|
+
return send(res, 200, JSON.stringify(st));
|
|
117
|
+
}
|
|
118
|
+
if (u.pathname === '/api/history') return send(res, 200, JSON.stringify(col.history()));
|
|
119
|
+
if (u.pathname === '/api/report') {
|
|
120
|
+
const r = col.report(u.searchParams.get('day'));
|
|
121
|
+
return r ? send(res, 200, JSON.stringify(r)) : send(res, 400, '{"error":"invalid day"}');
|
|
122
|
+
}
|
|
123
|
+
const m = /^\/api\/trace\/(.+)$/.exec(u.pathname);
|
|
124
|
+
if (m) {
|
|
125
|
+
const id = decodeURIComponent(m[1]);
|
|
126
|
+
if (u.searchParams.has('expand')) {
|
|
127
|
+
const r = col.expand(id, Number(u.searchParams.get('expand')));
|
|
128
|
+
return r ? send(res, 200, JSON.stringify(r)) : send(res, 404, '{"error":"step not found"}');
|
|
129
|
+
}
|
|
130
|
+
const r = col.trace(id, u.searchParams.get('limit') || '30');
|
|
131
|
+
return r ? send(res, 200, JSON.stringify(r)) : send(res, 404, '{"error":"unknown session"}');
|
|
132
|
+
}
|
|
133
|
+
// static files from public/
|
|
134
|
+
let rel = decodeURIComponent(u.pathname).replace(/^\/+/, '') || 'index.html';
|
|
135
|
+
const full = path.resolve(PUBLIC, rel);
|
|
136
|
+
if (!full.startsWith(PUBLIC + path.sep)) return send(res, 404, '{"error":"not found"}');
|
|
137
|
+
const st = statOrNull(full);
|
|
138
|
+
const type = MIME[path.extname(full).toLowerCase()];
|
|
139
|
+
if (!st || !st.isFile() || !type) return send(res, 404, '{"error":"not found"}');
|
|
140
|
+
return send(res, 200, fs.readFileSync(full), type, rel.startsWith('vendor/') ? 'public, max-age=86400' : 'no-cache');
|
|
141
|
+
} catch (e) {
|
|
142
|
+
console.error(e);
|
|
143
|
+
return send(res, 500, JSON.stringify({ error: String((e && e.message) || e) }));
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
srv.on('error', (e) => {
|
|
147
|
+
if (e.code === 'EADDRINUSE') console.error('Port ' + reqPort + ' is busy. Agent Office may already be running at http://' + host + ':' + reqPort + '/');
|
|
148
|
+
else console.error(e);
|
|
149
|
+
process.exit(1);
|
|
150
|
+
});
|
|
151
|
+
srv.listen(reqPort, host, () => {
|
|
152
|
+
const addr = srv.address();
|
|
153
|
+
const port = addr && typeof addr === 'object' ? addr.port : reqPort;
|
|
154
|
+
setOkHosts(port);
|
|
155
|
+
const avail = col.providers.filter((p) => p.available()).map((p) => p.label);
|
|
156
|
+
console.log('Agent Office on http://' + host + ':' + port + '/');
|
|
157
|
+
console.log('Found: ' + (avail.length ? avail.join(', ') : 'no agent logs yet') + (cfg._file ? ' (config: ' + cfg._file + ')' : ''));
|
|
158
|
+
if (opts.open) openBrowser('http://' + host + ':' + port + '/');
|
|
159
|
+
});
|
|
160
|
+
srv.on('close', () => { if (updates) updates.stop(); });
|
|
161
|
+
return { srv, col, updates };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function readJsonBody(req, maxBytes, cb) {
|
|
165
|
+
const chunks = [];
|
|
166
|
+
let total = 0, tooBig = false, done = false;
|
|
167
|
+
const finish = (err, data) => { if (done) return; done = true; cb(err, data); };
|
|
168
|
+
req.on('data', (chunk) => {
|
|
169
|
+
if (done) return;
|
|
170
|
+
total += chunk.length;
|
|
171
|
+
if (total > maxBytes) {
|
|
172
|
+
tooBig = true;
|
|
173
|
+
chunks.length = 0;
|
|
174
|
+
if (total > maxBytes * 16) {
|
|
175
|
+
finish({ code: 413, msg: 'body too large' });
|
|
176
|
+
req.destroy();
|
|
177
|
+
}
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
chunks.push(chunk);
|
|
181
|
+
});
|
|
182
|
+
req.on('end', () => {
|
|
183
|
+
if (done) return;
|
|
184
|
+
if (tooBig) return finish({ code: 413, msg: 'body too large' });
|
|
185
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
186
|
+
const parsed = tryJSON(text);
|
|
187
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
188
|
+
return finish({ code: 400, msg: 'invalid json' });
|
|
189
|
+
}
|
|
190
|
+
finish(null, parsed);
|
|
191
|
+
});
|
|
192
|
+
req.on('error', () => finish({ code: 400, msg: 'read error' }));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function openBrowser(url) {
|
|
196
|
+
const { spawn } = require('child_process');
|
|
197
|
+
const cmd = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
|
|
198
|
+
try { spawn(cmd[0], cmd[1], { detached: true, stdio: 'ignore', windowsHide: true }).unref(); } catch (e) { /* ignore */ }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = { serve, loadConfig, isDemoEnv };
|
package/src/state.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// One set of state rules for every tool. Providers report what the log ends with (`end`) and the
|
|
3
|
+
// collector turns that plus the time since the last activity into a state. First match wins.
|
|
4
|
+
//
|
|
5
|
+
// end: 'final' the agent gave its final answer (a one-shot task is over)
|
|
6
|
+
// 'turn' an interactive session finished its turn and waits for the person
|
|
7
|
+
// 'tool' a tool call is still running
|
|
8
|
+
// 'error' the last thing logged is an error
|
|
9
|
+
// 'canceled' the person stopped it
|
|
10
|
+
// '' anything else (mid-turn)
|
|
11
|
+
// runner: optional state reported by an external job runner ('done' | 'failed' | 'stalled' | 'running')
|
|
12
|
+
const { SEC, MIN, short, firstLine } = require('./util');
|
|
13
|
+
|
|
14
|
+
const abandonedAfter = () => (Number(process.env.AO_ABANDON_MIN) || 90) * MIN;
|
|
15
|
+
const failedTtl = () => {
|
|
16
|
+
const n = Number(process.env.AO_FAILED_TTL_MIN);
|
|
17
|
+
return (n > 0 ? n : 180) * MIN;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Failed sessions older than AO_FAILED_TTL_MIN age out to finished with ended_badly so old failures
|
|
21
|
+
// do not keep a workspace red forever.
|
|
22
|
+
function ageFailed(s, now) {
|
|
23
|
+
if (s.state !== 'failed') return;
|
|
24
|
+
const age = now - (s.last || s.started || 0);
|
|
25
|
+
if (age <= failedTtl()) return;
|
|
26
|
+
const abandoned = s.end !== 'error' && /abandoned|no final answer|without a final answer/i.test(String(s.state_why || ''));
|
|
27
|
+
s.state = 'done';
|
|
28
|
+
s.state_why = abandoned ? 'ended without a final answer' : 'ended with an error';
|
|
29
|
+
s.ended_badly = true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function deriveState(s, now) {
|
|
33
|
+
const age = now - (s.last || s.started || 0);
|
|
34
|
+
const end = s.end || '';
|
|
35
|
+
let state, why = '';
|
|
36
|
+
delete s.ended_badly;
|
|
37
|
+
if (s.runner === 'failed') { state = 'failed'; why = 'runner reported failed'; }
|
|
38
|
+
else if (s.runner === 'stalled') { state = 'stalled'; why = 'runner reported stalled'; }
|
|
39
|
+
else if (s.runner === 'done') { state = 'done'; why = 'runner reported done'; }
|
|
40
|
+
else if (end === 'canceled') { state = 'done'; why = 'stopped'; }
|
|
41
|
+
else if (end === 'final') { state = 'done'; why = 'final answer'; }
|
|
42
|
+
else if (end === 'turn') {
|
|
43
|
+
if (age <= 10 * MIN) { state = 'idle'; why = 'waiting for input'; }
|
|
44
|
+
else { state = 'done'; why = 'turn finished'; }
|
|
45
|
+
}
|
|
46
|
+
else if (end === 'error' && age > 2 * MIN) { state = 'failed'; why = 'last step is an error'; }
|
|
47
|
+
else if (age <= MIN) state = 'working';
|
|
48
|
+
else if (end === 'tool' && age < 30 * MIN) { state = 'working'; why = 'tool call in progress'; }
|
|
49
|
+
else if (age <= 10 * MIN) { state = 'idle'; why = 'quiet for ' + Math.round(age / SEC) + ' s'; }
|
|
50
|
+
else if (age <= abandonedAfter()) { state = 'stalled'; why = 'quiet for ' + Math.round(age / MIN) + ' min'; }
|
|
51
|
+
else if (s.interactive) { state = 'done'; why = 'inactive'; }
|
|
52
|
+
else { state = 'failed'; why = 'abandoned without a final answer'; }
|
|
53
|
+
s.state = state; s.state_why = why;
|
|
54
|
+
ageFailed(s, now);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// A parent that already answered but still has live children is waiting on them.
|
|
58
|
+
function liftParents(byId) {
|
|
59
|
+
for (const s of byId.values()) {
|
|
60
|
+
if (!s.children.length || (s.state !== 'done' && s.state !== 'idle')) continue;
|
|
61
|
+
const live = s.children.map((c) => byId.get(c)).filter((c) => c && (c.state === 'working' || c.state === 'idle'));
|
|
62
|
+
if (!live.length) continue;
|
|
63
|
+
const working = live.some((c) => c.state === 'working');
|
|
64
|
+
if (s.state === 'done' || working) {
|
|
65
|
+
s.state = working ? 'working' : 'idle';
|
|
66
|
+
s.state_why = 'waiting on ' + live.length + ' subagent' + (live.length > 1 ? 's' : '');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Extracts a normalized markdown task file path from task text, or '' if none is present.
|
|
72
|
+
function taskFilePath(text) {
|
|
73
|
+
const s = String(text || '');
|
|
74
|
+
let m = /[a-zA-Z]:[\\/][^"'<>|*?\r\n:]*?\.md\b/i.exec(s);
|
|
75
|
+
if (!m) {
|
|
76
|
+
m = /(?:^|[\s"'(`])((?:\.\.?[\\/]|[\\/]|[\w.-]+[\\/])[^\s"'<>|*?\r\n)]*?\.md)\b/i.exec(s);
|
|
77
|
+
if (m) m = [m[1]];
|
|
78
|
+
}
|
|
79
|
+
if (!m) return '';
|
|
80
|
+
return m[0].replace(/\\/g, '/').replace(/\/+/g, '/').trim().toLowerCase();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function normLabel(s) {
|
|
84
|
+
const lbl = String(s.label || '').trim().toLowerCase();
|
|
85
|
+
if (!lbl) return '';
|
|
86
|
+
if (!s.task && s.tool && lbl === String(s.tool).trim().toLowerCase()) return '';
|
|
87
|
+
return lbl;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// If a newer session in the same workspace with the same label or task file path finished
|
|
91
|
+
// successfully later, mark the older failed one done with "replaced by a later run".
|
|
92
|
+
function markSuperseded(sessions) {
|
|
93
|
+
const byLabel = new Map();
|
|
94
|
+
const byFile = new Map();
|
|
95
|
+
for (const s of sessions) {
|
|
96
|
+
if (s.state !== 'done' || s.ended_badly) continue;
|
|
97
|
+
if (s.end === 'canceled' || s.state_why === 'stopped' || s.state_why === 'canceled') continue;
|
|
98
|
+
const ws = s.workspace || (s.ws ? s.ws.id : '');
|
|
99
|
+
const ts = s.last || 0;
|
|
100
|
+
if (!ts) continue;
|
|
101
|
+
const lbl = normLabel(s);
|
|
102
|
+
if (ws && lbl) {
|
|
103
|
+
const k = ws + '\0' + lbl;
|
|
104
|
+
if (ts > (byLabel.get(k) || 0)) byLabel.set(k, ts);
|
|
105
|
+
}
|
|
106
|
+
const fp = taskFilePath(s.task);
|
|
107
|
+
if (fp) {
|
|
108
|
+
const k = ws + '\0' + fp;
|
|
109
|
+
if (ts > (byFile.get(k) || 0)) byFile.set(k, ts);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
for (const s of sessions) {
|
|
113
|
+
if (s.state !== 'failed' && !(s.state === 'done' && s.ended_badly)) continue;
|
|
114
|
+
const ws = s.workspace || (s.ws ? s.ws.id : '');
|
|
115
|
+
const ts = s.last || 0;
|
|
116
|
+
const lbl = normLabel(s);
|
|
117
|
+
const fp = taskFilePath(s.task);
|
|
118
|
+
const newerLabel = !!(ws && lbl && (byLabel.get(ws + '\0' + lbl) || 0) > ts);
|
|
119
|
+
const newerFile = !!(fp && (byFile.get(ws + '\0' + fp) || 0) > ts);
|
|
120
|
+
if (newerLabel || newerFile) {
|
|
121
|
+
s.state = 'done';
|
|
122
|
+
s.state_why = 'replaced by a later run';
|
|
123
|
+
s.ended_badly = true;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Plain failure reason from a session trace: "Last step failed: <tool> <short error>", or '' if unavailable.
|
|
129
|
+
function traceFailReason(tr) {
|
|
130
|
+
if (!tr || !Array.isArray(tr.rows) || !tr.rows.length) return '';
|
|
131
|
+
let r = null;
|
|
132
|
+
for (let i = tr.rows.length - 1; i >= 0; i--) {
|
|
133
|
+
if (tr.rows[i] && (tr.rows[i].err || tr.rows[i].kind === 'err')) { r = tr.rows[i]; break; }
|
|
134
|
+
}
|
|
135
|
+
if (!r) return '';
|
|
136
|
+
const tool = r.tool && !/^(error|canceled)$/i.test(String(r.tool)) ? String(r.tool).trim() : '';
|
|
137
|
+
const err = short(firstLine(r.res || r.text || ''), 100);
|
|
138
|
+
if (!tool && !err) return '';
|
|
139
|
+
return 'Last step failed: ' + [tool, err].filter(Boolean).join(' ');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = { deriveState, ageFailed, liftParents, markSuperseded, taskFilePath, traceFailReason };
|
package/src/update.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Checks now and then whether a newer Agent Office has been released, so the dashboard can say so.
|
|
3
|
+
// One small anonymous GET to GitHub (falling back to the npm registry); no data about you or your agents is sent.
|
|
4
|
+
// Off in demo mode, with config "update_check": false, or with AO_NO_UPDATE_CHECK=1. Any failure is silent.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
|
|
8
|
+
const REPO = 'zaferyalcin/agent-office';
|
|
9
|
+
const NPM_NAME = '@zaferyalcin/agent-office';
|
|
10
|
+
const EVERY = 12 * 3600e3;
|
|
11
|
+
const FIRST_DELAY = 5000;
|
|
12
|
+
const TIMEOUT = 6000;
|
|
13
|
+
|
|
14
|
+
// "v1.2.3" / "1.2.3-beta.1" -> [1, 2, 3, pre] ; null when it is not a version
|
|
15
|
+
function parseVersion(v) {
|
|
16
|
+
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(v || '').trim());
|
|
17
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] || ''] : null;
|
|
18
|
+
}
|
|
19
|
+
// true when a is a newer version than b (a release beats a pre-release of the same number)
|
|
20
|
+
function isNewer(a, b) {
|
|
21
|
+
const x = parseVersion(a), y = parseVersion(b);
|
|
22
|
+
if (!x || !y) return false;
|
|
23
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
|
|
24
|
+
if (x[3] === y[3]) return false;
|
|
25
|
+
if (!x[3]) return true;
|
|
26
|
+
if (!y[3]) return false;
|
|
27
|
+
return x[3] > y[3];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function updateCheckEnabled(cfg) {
|
|
31
|
+
const env = String(process.env.AO_NO_UPDATE_CHECK || '').trim().toLowerCase();
|
|
32
|
+
if (env === '1' || env === 'true' || env === 'yes') return false;
|
|
33
|
+
if (cfg && cfg.demo) return false;
|
|
34
|
+
return !(cfg && cfg.update_check === false);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
class UpdateChecker {
|
|
38
|
+
constructor(opts) {
|
|
39
|
+
opts = opts || {};
|
|
40
|
+
this.current = opts.current || require('../package.json').version;
|
|
41
|
+
this.fetch = opts.fetch || (typeof fetch === 'function' ? fetch : null);
|
|
42
|
+
this.root = opts.root || path.resolve(__dirname, '..');
|
|
43
|
+
this.latest = null; this.url = null; this.checked = 0; this.timer = null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// How this copy was installed, so the dashboard can show the matching update command.
|
|
47
|
+
how() {
|
|
48
|
+
try { if (fs.existsSync(path.join(this.root, '.git'))) return 'git'; } catch (e) { /* ignore */ }
|
|
49
|
+
return 'npx';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async getJSON(url) {
|
|
53
|
+
const ac = typeof AbortController === 'function' ? new AbortController() : null;
|
|
54
|
+
const t = ac ? setTimeout(() => ac.abort(), TIMEOUT) : null;
|
|
55
|
+
try {
|
|
56
|
+
const r = await this.fetch(url, { headers: { Accept: 'application/json', 'User-Agent': 'agent-office-update-check' }, signal: ac ? ac.signal : undefined });
|
|
57
|
+
if (!r || !r.ok) return null;
|
|
58
|
+
return await r.json();
|
|
59
|
+
} catch (e) {
|
|
60
|
+
return null;
|
|
61
|
+
} finally { if (t) clearTimeout(t); }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async check() {
|
|
65
|
+
if (!this.fetch) return null;
|
|
66
|
+
let latest = null, url = null;
|
|
67
|
+
const gh = await this.getJSON('https://api.github.com/repos/' + REPO + '/releases/latest');
|
|
68
|
+
if (gh && parseVersion(gh.tag_name) && !gh.draft && !gh.prerelease) {
|
|
69
|
+
latest = String(gh.tag_name).replace(/^v/, '');
|
|
70
|
+
url = typeof gh.html_url === 'string' && gh.html_url.startsWith('https://github.com/') ? gh.html_url : 'https://github.com/' + REPO + '/releases';
|
|
71
|
+
} else {
|
|
72
|
+
const npm = await this.getJSON('https://registry.npmjs.org/' + NPM_NAME.replace('/', '%2F') + '/latest');
|
|
73
|
+
if (npm && parseVersion(npm.version)) { latest = String(npm.version); url = 'https://github.com/' + REPO + '/releases'; }
|
|
74
|
+
}
|
|
75
|
+
this.checked = Date.now();
|
|
76
|
+
if (latest) { this.latest = latest; this.url = url; }
|
|
77
|
+
return this.info();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// What /api/state carries: null unless a newer version is known.
|
|
81
|
+
info() {
|
|
82
|
+
if (!this.latest || !isNewer(this.latest, this.current)) return null;
|
|
83
|
+
return { current: this.current, latest: this.latest, url: this.url, how: this.how(), checked: this.checked };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
start() {
|
|
87
|
+
if (this.timer || !this.fetch) return this;
|
|
88
|
+
const run = () => { this.check().catch(() => {}); };
|
|
89
|
+
const first = setTimeout(run, FIRST_DELAY);
|
|
90
|
+
if (first.unref) first.unref();
|
|
91
|
+
this.timer = setInterval(run, EVERY);
|
|
92
|
+
if (this.timer.unref) this.timer.unref();
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
stop() { if (this.timer) clearInterval(this.timer); this.timer = null; }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { UpdateChecker, isNewer, parseVersion, updateCheckEnabled, REPO, NPM_NAME };
|