v7: multi-agent support (Codex + Claude + opencode scaffold)

This commit is contained in:
2026-06-18 14:34:30 +08:00
parent 6a75b46453
commit ae114159ff
4 changed files with 208 additions and 269 deletions
@@ -13,7 +13,7 @@
], ],
"Settings": { "Settings": {
"pollInterval": 1000, "pollInterval": 1000,
"showHealth": true "agent": "codex"
}, },
"Controllers": ["Keypad", "Information"], "Controllers": ["Keypad", "Information"],
"UserTitleEnabled": true, "UserTitleEnabled": true,
@@ -3,52 +3,88 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const os = require('os'); const os = require('os');
const plugin = new Plugins('codex-monitor'); const plugin = new Plugins('ai-monitor');
const timers = {}; const timers = {};
const sessionOffsets = {}; const sessionOffsets = {};
const healthOffsets = {};
// ─── 直接调试日志 ──────────────────────────────────────
const DEBUG_LOG = path.join(__dirname, '..', 'debug.log'); const DEBUG_LOG = path.join(__dirname, '..', 'debug.log');
function dlog(msg) { function dlog(msg) { try { fs.appendFileSync(DEBUG_LOG, '[' + new Date().toISOString() + '] ' + msg + '\n'); } catch (_) {} }
try { fs.appendFileSync(DEBUG_LOG, '[' + new Date().toISOString() + '] ' + msg + '\n'); } catch (_) {} dlog('=== AI Monitor v7 multi-agent ===');
}
dlog('=== Plugin started v6 ===');
// ─── 路径配置 ───────────────────────────────────────────
const HOME = os.homedir(); const HOME = os.homedir();
const HEALTH_MARKER = 'app_server_connection.state_changed';
const DEFAULT_POLL = 1000; const DEFAULT_POLL = 1000;
const DONE_CUE_MS = 800; const DONE_CUE_MS = 800;
const COOLDOWN_MS = 300; const COOLDOWN_MS = 300;
const IDLE_TIMEOUT_MS = 3000; const IDLE_TIMEOUT_MS = 3000;
// ─── 简单递归文件查找 ────────────────────────────────── var AGENTS = {
function findFiles(rootDir, suffix, maxDepth) { codex: {
var results = []; label: 'Codex',
maxDepth = maxDepth || 16; scanDir: path.join(HOME, '.codex', 'sessions'),
if (!fs.existsSync(rootDir)) return results; fileSuffix: '.jsonl',
(function walk(dir, depth) { normalize: function(obj) {
if (depth > maxDepth) return; var t = obj.type || '';
var names; var pt = (obj.payload || {}).type || '';
try { names = fs.readdirSync(dir); } catch (_) { return; } var it = ((obj.payload || {}).item || {}).type || '';
for (var i = 0; i < names.length; i++) { if (t === 'event_msg') {
var name = names[i]; if (pt === 'task_started') return 'thinking';
var full = path.join(dir, name); if (pt === 'task_complete') return 'done';
var st; if (pt === 'turn_aborted') return 'error';
try { st = fs.statSync(full); } catch (_) { continue; } if (pt === 'agent_message') return 'typing';
if (st.isDirectory()) walk(full, depth + 1); if (pt === 'user_message') return 'prompt';
else if (st.isFile() && name.endsWith(suffix)) results.push(full); if (pt === 'web_search_end') return 'working';
if (pt === 'agent_reasoning') return 'thinking';
return null;
}
if (t === 'response_item') {
var nt = pt || it;
if (nt === 'function_call' || nt === 'custom_tool_call' || nt === 'function_call_output' || nt === 'custom_tool_call_output') return 'working';
if (nt === 'web_search_call') return 'working';
if (nt === 'reasoning') return 'thinking';
if (nt === 'message') return 'typing';
return null;
}
return null;
}
},
claude: {
label: 'Claude',
scanDir: path.join(HOME, '.claude', 'projects'),
fileSuffix: '.jsonl',
normalize: function(obj) {
var t = obj.type || '';
if (t === 'user') return 'prompt';
if (t === 'assistant') {
var content = (obj.message || {}).content || [];
for (var i = 0; i < content.length; i++) {
var ct = content[i].type || '';
if (ct === 'tool_use') return 'working';
if (ct === 'thinking') return 'thinking';
}
for (var j = 0; j < content.length; j++) {
if ((content[j].type || '') === 'text') return 'typing';
}
return 'typing';
}
if (t === 'system') { if (obj.subtype === 'turn_duration') return 'done'; return null; }
if (t === 'error' || t === 'api_error') return 'error';
return null;
}
},
opencode: {
label: 'opencode',
scanDir: path.join(HOME, '.opencode', 'sessions'),
fileSuffix: '.jsonl',
normalize: function(obj) {
var t = obj.type || '';
if (t === 'user') return 'prompt';
if (t === 'assistant') return 'typing';
if (t === 'tool' || t === 'tool_call') return 'working';
if (t === 'thinking' || t === 'reasoning') return 'thinking';
if (t === 'done' || t === 'complete') return 'done';
if (t === 'error') return 'error';
return null;
} }
})(rootDir, 0);
return results;
} }
// ─── 状态映射 ───────────────────────────────────────────
var STATE = {
IDLE: 'idle', PROMPT: 'prompt', THINK: 'thinking', WORK: 'working',
TYPING: 'typing', DONE: 'done', ERROR: 'error', WAITING: 'waiting',
RECONNECTING: 'reconnecting', RECOVERED: 'recovered'
}; };
var STATUS_DISPLAY = {}; var STATUS_DISPLAY = {};
@@ -63,8 +99,9 @@ STATUS_DISPLAY['waiting'] = { title: 'Waiting', fill: '#ef4444', blink: true, br
STATUS_DISPLAY['reconnecting'] = { title: 'Reconnect', fill: '#ef4444', blink: true, breathe: false }; STATUS_DISPLAY['reconnecting'] = { title: 'Reconnect', fill: '#ef4444', blink: true, breathe: false };
STATUS_DISPLAY['recovered'] = { title: 'Online', fill: '#22c55e', blink: false, breathe: false }; STATUS_DISPLAY['recovered'] = { title: 'Online', fill: '#22c55e', blink: false, breathe: false };
// 优先级: ERROR > WORK > TYPING > THINK > PROMPT > DONE > IDLE
var STATE_PRIORITY = ['error','waiting','reconnecting','working','typing','thinking','prompt','done','idle']; var STATE_PRIORITY = ['error','waiting','reconnecting','working','typing','thinking','prompt','done','idle'];
var currentCtx = null, currentState = 'idle', lastHwSet = 0, lastActivityTime = 0;
var animationHandle = null, currentAgent = null;
function makeSvg(fill, label, blink, breathe) { function makeSvg(fill, label, blink, breathe) {
var anim = ''; var anim = '';
@@ -79,20 +116,14 @@ function setDisplay(context, state) {
plugin.setImage(context, 'data:image/svg+xml;charset=utf-8,' + makeSvg(d.fill, d.title, d.blink, d.breathe)); plugin.setImage(context, 'data:image/svg+xml;charset=utf-8,' + makeSvg(d.fill, d.title, d.blink, d.breathe));
} }
// ─── 状态管理 ──────────────────────────────────────────
var currentCtx = null, currentState = 'idle', lastHwSet = 0, lastActivityTime = 0;
var animationHandle = null;
function animateTick() { function animateTick() {
if (!currentCtx) return; if (!currentCtx) return;
var d = STATUS_DISPLAY[currentState] || STATUS_DISPLAY['idle']; var d = STATUS_DISPLAY[currentState] || STATUS_DISPLAY['idle'];
if (d.blink || d.breathe) { if (d.blink || d.breathe) {
var now = Date.now(); var now = Date.now(); var period = d.blink ? 800 : 2000; var phase = (now % period) / period;
var period = d.blink ? 800 : 2000;
var phase = (now % period) / period;
var alpha = d.blink ? (phase < 0.5 ? 1 : 0.2) : 0.4 + 0.6 * Math.sin(phase * Math.PI); var alpha = d.blink ? (phase < 0.5 ? 1 : 0.2) : 0.4 + 0.6 * Math.sin(phase * Math.PI);
var r = parseInt(d.fill.slice(1,3), 16), g = parseInt(d.fill.slice(3,5), 16), b = parseInt(d.fill.slice(5,7), 16); var _r = parseInt(d.fill.slice(1,3),16), _g = parseInt(d.fill.slice(3,5),16), _b = parseInt(d.fill.slice(5,7),16);
var color = 'rgb(' + Math.round(16+(r-16)*alpha) + ',' + Math.round(16+(g-16)*alpha) + ',' + Math.round(16+(b-16)*alpha) + ')'; var color = 'rgb(' + Math.round(16+(_r-16)*alpha) + ',' + Math.round(16+(_g-16)*alpha) + ',' + Math.round(16+(_b-16)*alpha) + ')';
var svg = '<svg width="144" height="144" xmlns="http://www.w3.org/2000/svg"><rect width="144" height="144" rx="20" fill="#1a1a2e"/><circle cx="72" cy="58" r="32" fill="' + color + '"/><text x="72" y="118" font-family="Arial" font-weight="bold" font-size="13" fill="white" text-anchor="middle">' + d.title + '</text></svg>'; var svg = '<svg width="144" height="144" xmlns="http://www.w3.org/2000/svg"><rect width="144" height="144" rx="20" fill="#1a1a2e"/><circle cx="72" cy="58" r="32" fill="' + color + '"/><text x="72" y="118" font-family="Arial" font-weight="bold" font-size="13" fill="white" text-anchor="middle">' + d.title + '</text></svg>';
plugin.setImage(currentCtx, 'data:image/svg+xml;charset=utf-8,' + svg); plugin.setImage(currentCtx, 'data:image/svg+xml;charset=utf-8,' + svg);
} }
@@ -101,57 +132,38 @@ function animateTick() {
function setState(context, state) { function setState(context, state) {
if (state === currentState && context === currentCtx && Date.now() - lastHwSet < COOLDOWN_MS) return; if (state === currentState && context === currentCtx && Date.now() - lastHwSet < COOLDOWN_MS) return;
if (state === 'done') { if (state === 'done') {
setDisplay(context, 'done'); setDisplay(context, 'done'); currentState = 'done';
currentState = 'done'; setTimeout(function() { if (currentState === 'done') { currentState = 'idle'; setDisplay(context, 'idle'); } }, DONE_CUE_MS);
setTimeout(function () { } else if (state === 'recovered') { currentState = 'idle'; setDisplay(context, 'idle'); }
if (currentState === 'done') { currentState = 'idle'; setDisplay(context, 'idle'); } else { currentState = state; setDisplay(context, state); }
}, DONE_CUE_MS); lastHwSet = Date.now(); dlog('State: ' + state + ' [' + (currentAgent ? currentAgent.label : '?') + ']');
} else if (state === 'recovered') {
currentState = 'idle'; setDisplay(context, 'idle');
} else {
currentState = state; setDisplay(context, state);
}
lastHwSet = Date.now();
dlog('State: ' + state);
} }
// ─── Session JSONL 解析 ──────────────────────────────── function findFiles(rootDir, suffix, maxDepth) {
function normalizeEvent(obj) { var results = []; maxDepth = maxDepth || 16;
var type = obj.type || ''; if (!fs.existsSync(rootDir)) return results;
var pt = (obj.payload || {}).type || ''; (function walk(dir, depth) {
var it = ((obj.payload || {}).item || {}).type || ''; if (depth > maxDepth) return;
if (type === 'event_msg') { var names; try { names = fs.readdirSync(dir); } catch (_) { return; }
if (pt === 'task_started') return 'thinking'; for (var i = 0; i < names.length; i++) {
if (pt === 'task_complete') return 'done'; var full = path.join(dir, names[i]);
if (pt === 'turn_aborted') return 'error'; var st; try { st = fs.statSync(full); } catch (_) { continue; }
if (pt === 'agent_message') return 'typing'; if (st.isDirectory()) walk(full, depth + 1);
if (pt === 'user_message') return 'prompt'; else if (st.isFile() && names[i].endsWith(suffix)) results.push(full);
if (pt === 'web_search_end') return 'working';
if (pt === 'agent_reasoning') return 'thinking';
return null;
} }
if (type === 'response_item') { })(rootDir, 0);
var nt = pt || it; return results;
if (nt === 'function_call' || nt === 'custom_tool_call' || nt === 'function_call_output' || nt === 'custom_tool_call_output') return 'working';
if (nt === 'web_search_call') return 'working';
if (nt === 'reasoning') return 'thinking';
if (nt === 'message') return 'typing';
return null;
}
return null;
} }
// ─── Session tails ───────────────────────────────────── function latestFiles(rootDir, suffix, limit) {
function latestSessionFiles() {
try { try {
var dir = path.join(HOME, '.codex', 'sessions'); var files = findFiles(rootDir, suffix);
var files = findFiles(dir, '.jsonl');
files.sort(function(a,b) { return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs; }); files.sort(function(a,b) { return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs; });
return files.slice(0, 3); return files.slice(0, limit || 3);
} catch (_) { return []; } } catch (_) { return []; }
} }
function tailSession(filePath, context) { function tailFile(filePath, agent, context) {
var detected = false; var detected = false;
try { try {
var stat = fs.statSync(filePath); var stat = fs.statSync(filePath);
@@ -169,152 +181,65 @@ function tailSession(filePath, context) {
for (var i = 0; i < lines.length; i++) { for (var i = 0; i < lines.length; i++) {
try { try {
var obj = JSON.parse(lines[i]); var obj = JSON.parse(lines[i]);
var s = normalizeEvent(obj); var s = agent.normalize(obj);
if (s) { if (s) { var pri = STATE_PRIORITY.indexOf(s); if (pri >= 0 && pri < bestPri) { bestPri = pri; bestState = s; } }
var pri = STATE_PRIORITY.indexOf(s);
if (pri >= 0 && pri < bestPri) { bestPri = pri; bestState = s; }
}
} catch (_) {} } catch (_) {}
} }
if (bestState) { if (bestState) { dlog('Detected: ' + bestState + ' from ' + path.basename(filePath)); setState(context, bestState); detected = true; }
dlog('Detected: ' + bestState + ' from ' + path.basename(filePath));
setState(context, bestState);
detected = true;
}
} catch (_) { delete sessionOffsets[filePath]; } } catch (_) { delete sessionOffsets[filePath]; }
return detected; return detected;
} }
// ─── Health monitoring ─────────────────────────────────
var healthState = { reconnecting: false };
function parseHealthLine(line) {
if (line.indexOf(HEALTH_MARKER) === -1) return null;
var fieldRe = /([A-Za-z][A-Za-z0-9_]*)=("[^"]*"|\S+)/g;
var fields = {}, m;
while ((m = fieldRe.exec(line)) !== null) {
var val = m[2];
if (val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') val = val.slice(1, -1);
fields[m[1]] = val;
}
var next = fields.next || '';
var prev = fields.previous || '';
var attempt = parseInt(fields.reconnectAttempt || '0', 10);
var scheduled = (fields.reconnectTimerScheduled || '').toLowerCase() === 'true';
var err = fields.connectionError || '';
var cause = fields.cause || '';
if (next === 'connected' && healthState.reconnecting) { healthState.reconnecting = false; return 'recovered'; }
if ((next === 'connecting' || next === 'disconnected') && (attempt > 0 || scheduled || (err && err.toLowerCase() !== 'null') || (prev === 'connected' && cause !== 'stop_process' && cause !== 'shutdown'))) {
healthState.reconnecting = true; return 'reconnecting';
}
return null;
}
function latestHealthLogs() {
try {
var dir = process.platform === 'win32' ? path.join(HOME, 'AppData', 'Local', 'Codex', 'Logs') : path.join(HOME, 'Library', 'Logs', 'com.openai.codex');
var files = findFiles(dir, '.log');
files.sort(function (a, b) { return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs; });
return files.slice(0, 3);
} catch (_) { return []; }
}
function tailHealth(filePath, context) {
try {
var stat = fs.statSync(filePath);
var off = healthOffsets[filePath] || 0;
if (stat.size < off) { healthOffsets[filePath] = 0; return; }
if (stat.size === off) return;
var fd = fs.openSync(filePath, 'r');
var grow = Math.min(stat.size - off, 65536);
var buf = Buffer.alloc(grow);
fs.readSync(fd, buf, 0, grow, off);
fs.closeSync(fd);
healthOffsets[filePath] = stat.size;
var lines = buf.toString('utf-8').split('\n').filter(function (l) { return l.trim(); });
var lastHealth = null;
for (var i = 0; i < lines.length; i++) {
var s = parseHealthLine(lines[i]);
if (s) lastHealth = s;
}
if (lastHealth) { dlog('Health: ' + lastHealth); setState(context, lastHealth); }
} catch (_) { delete healthOffsets[filePath]; }
}
// ─── 主轮询 ────────────────────────────────────────────
var pollCount = 0; var pollCount = 0;
function poll(context, interval, showHealth) { function poll(context, interval, agent) {
pollCount++; pollCount++;
if (pollCount % 10 === 1) dlog('Poll #' + pollCount); if (pollCount % 10 === 1) dlog('Poll #' + pollCount + ' [' + (agent ? agent.label : '?') + ']');
if (!agent) return;
var detected = false; var detected = false;
var files = latestSessionFiles(); var files = latestFiles(agent.scanDir, agent.fileSuffix);
for (var i = 0; i < files.length; i++) { for (var i = 0; i < files.length; i++) { if (tailFile(files[i], agent, context)) detected = true; }
if (tailSession(files[i], context)) detected = true;
}
if (detected) lastActivityTime = Date.now(); if (detected) lastActivityTime = Date.now();
// Idle timeout: return to IDLE if nothing happened for IDLE_TIMEOUT_MS
if (currentState !== 'idle' && currentState !== 'done' && Date.now() - lastActivityTime > IDLE_TIMEOUT_MS) { if (currentState !== 'idle' && currentState !== 'done' && Date.now() - lastActivityTime > IDLE_TIMEOUT_MS) {
dlog('Idle timeout - returning to IDLE'); dlog('Idle timeout - returning to IDLE'); setState(context, 'idle');
setState(context, 'idle');
}
if (showHealth) {
var hfiles = latestHealthLogs();
for (var j = 0; j < hfiles.length; j++) tailHealth(hfiles[j], context);
} }
} }
// ─── Action 定义 ───────────────────────────────────────
plugin.monitor = new Actions({ plugin.monitor = new Actions({
default: { pollInterval: DEFAULT_POLL, showHealth: true }, default: { pollInterval: DEFAULT_POLL, agent: 'codex' },
_willAppear: function(data) { _willAppear: function(data) {
var ctx = data.context; var ctx = data.context, s = plugin.monitor.data[ctx], agentKey = s.agent || 'codex', agent = AGENTS[agentKey];
dlog('WillAppear: ' + ctx); if (!agent) { agent = AGENTS['codex']; dlog('Unknown agent: ' + agentKey + ', falling back to codex'); }
currentCtx = ctx; currentAgent = agent; dlog('WillAppear: ' + ctx + ' agent=' + agentKey);
currentState = 'idle'; currentCtx = ctx; currentState = 'idle'; lastHwSet = 0; lastActivityTime = Date.now();
lastHwSet = 0;
lastActivityTime = Date.now();
setDisplay(ctx, 'idle'); setDisplay(ctx, 'idle');
var s = plugin.monitor.data[ctx];
var interval = s.pollInterval || DEFAULT_POLL; var interval = s.pollInterval || DEFAULT_POLL;
var showHealth = s.showHealth !== false; poll(ctx, interval, agent);
poll(ctx, interval, showHealth); timers[ctx] = setInterval(function() { poll(ctx, interval, agent); }, interval);
timers[ctx] = setInterval(function () { poll(ctx, interval, showHealth); }, interval);
if (!animationHandle) animationHandle = setInterval(animateTick, 200); if (!animationHandle) animationHandle = setInterval(animateTick, 200);
}, },
_willDisappear: function(data) { _willDisappear: function(data) {
var ctx = data.context; var ctx = data.context;
dlog('WillDisappear: ' + ctx);
if (timers[ctx]) { clearInterval(timers[ctx]); delete timers[ctx]; } if (timers[ctx]) { clearInterval(timers[ctx]); delete timers[ctx]; }
if (currentCtx === ctx) { currentCtx = null; currentState = 'idle'; } if (currentCtx === ctx) { currentCtx = null; currentAgent = null; currentState = 'idle'; }
if (Object.keys(timers).length === 0 && animationHandle) { clearInterval(animationHandle); animationHandle = null; } if (Object.keys(timers).length === 0 && animationHandle) { clearInterval(animationHandle); animationHandle = null; }
}, },
_didReceiveSettings: function(data) { _didReceiveSettings: function(data) {
var ctx = data.context; var ctx = data.context;
if (timers[ctx]) clearInterval(timers[ctx]); if (timers[ctx]) clearInterval(timers[ctx]);
var s = plugin.monitor.data[ctx]; var s = plugin.monitor.data[ctx], agentKey = s.agent || 'codex', agent = AGENTS[agentKey];
if (!agent) agent = AGENTS['codex']; currentAgent = agent;
var interval = s.pollInterval || DEFAULT_POLL; var interval = s.pollInterval || DEFAULT_POLL;
var showHealth = s.showHealth !== false; poll(ctx, interval, agent);
poll(ctx, interval, showHealth); timers[ctx] = setInterval(function() { poll(ctx, interval, agent); }, interval);
timers[ctx] = setInterval(function () { poll(ctx, interval, showHealth); }, interval);
}, },
keyUp: function(data) { keyUp: function(data) {
var s = plugin.monitor.data[data.context]; var s = plugin.monitor.data[data.context], agent = AGENTS[s.agent || 'codex'] || AGENTS['codex'];
poll(data.context, s.pollInterval || DEFAULT_POLL, s.showHealth !== false); poll(data.context, s.pollInterval || DEFAULT_POLL, agent);
}, },
sendToPlugin: function(data) { sendToPlugin: function(data) {
if (data.payload && data.payload.command === 'refresh') { if (data.payload && data.payload.command === 'refresh') {
var s = plugin.monitor.data[data.context]; var s = plugin.monitor.data[data.context], agent = AGENTS[s.agent || 'codex'] || AGENTS['codex'];
poll(data.context, s.pollInterval || DEFAULT_POLL, s.showHealth !== false); poll(data.context, s.pollInterval || DEFAULT_POLL, agent);
} }
} }
}); });
@@ -105,6 +105,14 @@
</style> </style>
</head> </head>
<body> <body>
<div class="section">
<label>Agent</label>
<select id="agentSelect" style="width:100%;padding:6px 8px;background:#16213e;border:1px solid #333;border-radius:6px;color:#e0e0e0;font-size:13px;">
<option value="codex">Codex Desktop</option>
<option value="claude">Claude Desktop</option>
<option value="opencode">opencode</option>
</select>
</div>
<div class="section"> <div class="section">
<label data-localize="PollInterval">轮询间隔 (ms)</label> <label data-localize="PollInterval">轮询间隔 (ms)</label>
<div class="range-row"> <div class="range-row">
@@ -1,6 +1,7 @@
(function () { (function () {
'use strict'; 'use strict';
const agentSelect = document.getElementById('agentSelect');
const pollSlider = document.getElementById('pollInterval'); const pollSlider = document.getElementById('pollInterval');
const pollVal = document.getElementById('pollVal'); const pollVal = document.getElementById('pollVal');
const showHealthToggle = document.getElementById('showHealth'); const showHealthToggle = document.getElementById('showHealth');
@@ -11,6 +12,7 @@
$settings = $settings || {}; $settings = $settings || {};
function applySettings(settings) { function applySettings(settings) {
if (settings.agent) { agentSelect.value = settings.agent; }
if (settings.pollInterval !== undefined) { if (settings.pollInterval !== undefined) {
pollSlider.value = settings.pollInterval; pollSlider.value = settings.pollInterval;
pollVal.textContent = settings.pollInterval + 'ms'; pollVal.textContent = settings.pollInterval + 'ms';
@@ -20,6 +22,10 @@
} }
} }
agentSelect.addEventListener('change', function () {
$settings.agent = this.value;
});
pollSlider.addEventListener('input', function () { pollSlider.addEventListener('input', function () {
const val = parseInt(this.value, 10); const val = parseInt(this.value, 10);
pollVal.textContent = val + 'ms'; pollVal.textContent = val + 'ms';