mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-06-11 02:33:10 +08:00
feat: add ECC2 local control pane (#2131)
* feat: add ECC2 local control pane * fix: refresh control pane package locks * test: harden control pane coverage * test: allow portable control pane shutdown * test: retry local control pane fetches * fix: harden control pane error handling * fix: wrap control pane metadata
This commit is contained in:
65
scripts/control-pane.js
Executable file
65
scripts/control-pane.js
Executable file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const {
|
||||
createControlPaneServer,
|
||||
parseArgs,
|
||||
usage,
|
||||
} = require('./lib/control-pane/server');
|
||||
|
||||
function openBrowser(url) {
|
||||
if (process.platform !== 'darwin') return;
|
||||
const child = spawn('open', [url], {
|
||||
stdio: 'ignore',
|
||||
detached: true,
|
||||
});
|
||||
child.on('error', error => {
|
||||
console.error(`[control-pane] failed to open browser: ${error.message}`);
|
||||
});
|
||||
child.unref();
|
||||
}
|
||||
|
||||
async function main(argv = process.argv) {
|
||||
const args = parseArgs(argv);
|
||||
|
||||
if (args.help) {
|
||||
console.log(usage());
|
||||
return;
|
||||
}
|
||||
|
||||
const app = createControlPaneServer(args);
|
||||
await app.listen();
|
||||
|
||||
console.log(`ECC Control Pane: ${app.url}`);
|
||||
console.log(`ECC2 database: ${app.config.dbPath}`);
|
||||
console.log(args.allowActions ? 'Actions: enabled for local allowlist' : 'Actions: read-only');
|
||||
|
||||
if (args.openBrowser) {
|
||||
openBrowser(app.url);
|
||||
}
|
||||
|
||||
const shutdown = async () => {
|
||||
try {
|
||||
await app.close();
|
||||
} finally {
|
||||
process.exit(0);
|
||||
}
|
||||
};
|
||||
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch(error => {
|
||||
console.error(`[control-pane] ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
main,
|
||||
openBrowser,
|
||||
};
|
||||
@@ -21,6 +21,10 @@ const COMMANDS = {
|
||||
script: 'consult.js',
|
||||
description: 'Recommend ECC components and profiles from a natural language query',
|
||||
},
|
||||
'control-pane': {
|
||||
script: 'control-pane.js',
|
||||
description: 'Run the local ECC2 operator control pane',
|
||||
},
|
||||
'install-plan': {
|
||||
script: 'install-plan.js',
|
||||
description: 'Alias for plan',
|
||||
@@ -80,6 +84,7 @@ const PRIMARY_COMMANDS = [
|
||||
'plan',
|
||||
'catalog',
|
||||
'consult',
|
||||
'control-pane',
|
||||
'list-installed',
|
||||
'doctor',
|
||||
'repair',
|
||||
@@ -118,6 +123,7 @@ Examples:
|
||||
ecc catalog components --family language
|
||||
ecc catalog show framework:nextjs
|
||||
ecc consult "security reviews"
|
||||
ecc control-pane --port 8765
|
||||
ecc list-installed --json
|
||||
ecc doctor --target cursor
|
||||
ecc repair --dry-run
|
||||
|
||||
133
scripts/lib/control-pane/actions.js
Normal file
133
scripts/lib/control-pane/actions.js
Normal file
@@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const ACTION_DEFINITIONS = new Map([
|
||||
[
|
||||
'sync-knowledge',
|
||||
{
|
||||
label: 'Sync Knowledge',
|
||||
description: 'Import all configured ECC2 memory connectors into the context graph.',
|
||||
args: ({ limit }) => [
|
||||
'run',
|
||||
'--quiet',
|
||||
'--',
|
||||
'graph',
|
||||
'connector-sync',
|
||||
'--all',
|
||||
'--json',
|
||||
'--limit',
|
||||
String(limit),
|
||||
],
|
||||
executable: true,
|
||||
},
|
||||
],
|
||||
[
|
||||
'recall-knowledge',
|
||||
{
|
||||
label: 'Recall Knowledge',
|
||||
description: 'Run ECC2 context recall for the current operator query.',
|
||||
args: ({ query, limit }) => [
|
||||
'run',
|
||||
'--quiet',
|
||||
'--',
|
||||
'graph',
|
||||
'recall',
|
||||
query || 'ECC control pane',
|
||||
'--json',
|
||||
'--limit',
|
||||
String(limit),
|
||||
],
|
||||
executable: true,
|
||||
},
|
||||
],
|
||||
[
|
||||
'graph-sync',
|
||||
{
|
||||
label: 'Backfill Graph',
|
||||
description: 'Backfill the ECC2 graph from sessions, decisions, file activity, and messages.',
|
||||
args: ({ limit }) => [
|
||||
'run',
|
||||
'--quiet',
|
||||
'--',
|
||||
'graph',
|
||||
'sync',
|
||||
'--all',
|
||||
'--json',
|
||||
'--limit',
|
||||
String(limit),
|
||||
],
|
||||
executable: true,
|
||||
},
|
||||
],
|
||||
[
|
||||
'open-dashboard',
|
||||
{
|
||||
label: 'Open TUI',
|
||||
description: 'Launch the ECC2 terminal dashboard.',
|
||||
args: () => ['run', '--quiet', '--', 'dashboard'],
|
||||
executable: false,
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
function normalizeLimit(value, fallback = 25) {
|
||||
const parsed = Number.parseInt(String(value ?? fallback), 10);
|
||||
if (!Number.isFinite(parsed) || parsed < 1) return fallback;
|
||||
return Math.min(parsed, 500);
|
||||
}
|
||||
|
||||
function shellQuote(value) {
|
||||
const text = String(value);
|
||||
if (text.length === 0) return "''";
|
||||
if (/^[A-Za-z0-9_./:=@%+-]+$/.test(text)) return text;
|
||||
return `'${text.replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
function commandLineFor(action) {
|
||||
return [
|
||||
`cd ${shellQuote(action.cwd)}`,
|
||||
'&&',
|
||||
shellQuote(action.command),
|
||||
...action.args.map(shellQuote),
|
||||
].join(' ');
|
||||
}
|
||||
|
||||
function buildControlPaneAction(actionId, options = {}) {
|
||||
const definition = ACTION_DEFINITIONS.get(actionId);
|
||||
if (!definition) {
|
||||
throw new Error(`Unknown control-pane action: ${actionId}`);
|
||||
}
|
||||
|
||||
const repoRoot = path.resolve(options.repoRoot || process.cwd());
|
||||
const cwd = path.join(repoRoot, 'ecc2');
|
||||
const limit = normalizeLimit(options.limit);
|
||||
const query = String(options.query || '').trim();
|
||||
const args = definition.args({ limit, query });
|
||||
const action = {
|
||||
id: actionId,
|
||||
label: definition.label,
|
||||
description: definition.description,
|
||||
command: 'cargo',
|
||||
args,
|
||||
cwd,
|
||||
executable: definition.executable,
|
||||
};
|
||||
|
||||
return {
|
||||
...action,
|
||||
commandLine: commandLineFor(action),
|
||||
};
|
||||
}
|
||||
|
||||
function buildControlPaneActions(options = {}) {
|
||||
return Array.from(ACTION_DEFINITIONS.keys()).map(actionId =>
|
||||
buildControlPaneAction(actionId, options)
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildControlPaneAction,
|
||||
buildControlPaneActions,
|
||||
shellQuote,
|
||||
};
|
||||
270
scripts/lib/control-pane/server.js
Normal file
270
scripts/lib/control-pane/server.js
Normal file
@@ -0,0 +1,270 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const { buildControlPaneAction } = require('./actions');
|
||||
const { buildControlPaneSnapshot, resolveControlPaneConfig } = require('./state');
|
||||
const { renderControlPaneHtml } = require('./ui');
|
||||
|
||||
function usage() {
|
||||
return [
|
||||
'Usage:',
|
||||
' node scripts/control-pane.js [--host 127.0.0.1] [--port 8765] [--db <ecc2.db>] [--config <ecc2.toml>] [--query <text>]',
|
||||
'',
|
||||
'Options:',
|
||||
' --read-only Disable action execution endpoints',
|
||||
' --no-open Do not open a browser after the server starts',
|
||||
' --help Show this help',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function valueAfter(args, name) {
|
||||
const index = args.indexOf(name);
|
||||
return index >= 0 ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = argv.slice(2);
|
||||
const help = args.includes('--help') || args.includes('-h');
|
||||
const host = valueAfter(args, '--host') || '127.0.0.1';
|
||||
const portValue = valueAfter(args, '--port') || '8765';
|
||||
const port = Number.parseInt(portValue, 10);
|
||||
if (!Number.isFinite(port) || port < 0 || port > 65535) {
|
||||
throw new Error(`Invalid --port value: ${portValue}`);
|
||||
}
|
||||
|
||||
return {
|
||||
help,
|
||||
host,
|
||||
port,
|
||||
dbPath: valueAfter(args, '--db'),
|
||||
configPath: valueAfter(args, '--config'),
|
||||
query: valueAfter(args, '--query') || '',
|
||||
openBrowser: !args.includes('--no-open'),
|
||||
allowActions: !args.includes('--read-only'),
|
||||
};
|
||||
}
|
||||
|
||||
function sendJson(res, statusCode, payload) {
|
||||
const body = JSON.stringify(payload, null, 2);
|
||||
res.writeHead(statusCode, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
});
|
||||
res.end(`${body}\n`);
|
||||
}
|
||||
|
||||
function sendText(res, statusCode, body, contentType = 'text/plain; charset=utf-8') {
|
||||
res.writeHead(statusCode, {
|
||||
'content-type': contentType,
|
||||
'cache-control': 'no-store',
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
async function readRequestJson(req) {
|
||||
const chunks = [];
|
||||
for await (const chunk of req) chunks.push(chunk);
|
||||
if (chunks.length === 0) return {};
|
||||
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
||||
if (!raw) return {};
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
function boundedOutput(value, limit = 20000) {
|
||||
const text = String(value || '');
|
||||
if (text.length <= limit) return text;
|
||||
return `${text.slice(0, limit)}\n[truncated ${text.length - limit} chars]`;
|
||||
}
|
||||
|
||||
function runAction(action, options = {}) {
|
||||
const timeoutMs = options.timeoutMs || 120000;
|
||||
return new Promise(resolve => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const child = spawn(action.command, action.args, {
|
||||
cwd: action.cwd,
|
||||
env: process.env,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let settled = false;
|
||||
const timeout = setTimeout(() => {
|
||||
if (!settled) {
|
||||
child.kill('SIGTERM');
|
||||
}
|
||||
}, timeoutMs);
|
||||
|
||||
child.stdout.on('data', chunk => {
|
||||
stdout += chunk.toString('utf8');
|
||||
});
|
||||
child.stderr.on('data', chunk => {
|
||||
stderr += chunk.toString('utf8');
|
||||
});
|
||||
child.on('error', error => {
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolve({
|
||||
ok: false,
|
||||
action: action.id,
|
||||
startedAt,
|
||||
finishedAt: new Date().toISOString(),
|
||||
code: null,
|
||||
error: error.message,
|
||||
stdout: boundedOutput(stdout),
|
||||
stderr: boundedOutput(stderr),
|
||||
});
|
||||
});
|
||||
child.on('close', (code, signal) => {
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolve({
|
||||
ok: code === 0,
|
||||
action: action.id,
|
||||
startedAt,
|
||||
finishedAt: new Date().toISOString(),
|
||||
code,
|
||||
signal,
|
||||
stdout: boundedOutput(stdout),
|
||||
stderr: boundedOutput(stderr),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function createControlPaneServer(options = {}) {
|
||||
const repoRoot = path.resolve(options.repoRoot || path.join(__dirname, '..', '..', '..'));
|
||||
const host = options.host || '127.0.0.1';
|
||||
const port = options.port === null || options.port === undefined ? 8765 : options.port;
|
||||
const allowActions = options.allowActions !== false;
|
||||
const resolvedConfig = resolveControlPaneConfig({
|
||||
cwd: options.cwd || repoRoot,
|
||||
configPath: options.configPath,
|
||||
dbPath: options.dbPath,
|
||||
env: options.env || process.env,
|
||||
});
|
||||
const baseQuery = options.query || '';
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const requestUrl = new URL(req.url, `http://${host}:${port || 0}`);
|
||||
|
||||
if (req.method === 'GET' && requestUrl.pathname === '/') {
|
||||
sendText(res, 200, renderControlPaneHtml(), 'text/html; charset=utf-8');
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && requestUrl.pathname === '/assets/ecc-icon.svg') {
|
||||
const iconPath = path.join(repoRoot, 'assets', 'ecc-icon.svg');
|
||||
if (!fs.existsSync(iconPath)) {
|
||||
sendText(res, 404, 'not found');
|
||||
return;
|
||||
}
|
||||
sendText(res, 200, fs.readFileSync(iconPath, 'utf8'), 'image/svg+xml; charset=utf-8');
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && requestUrl.pathname === '/api/health') {
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
repoRoot,
|
||||
dbPath: resolvedConfig.dbPath,
|
||||
allowActions,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && requestUrl.pathname === '/api/snapshot') {
|
||||
const snapshot = await buildControlPaneSnapshot({
|
||||
repoRoot,
|
||||
dbPath: resolvedConfig.dbPath,
|
||||
config: resolvedConfig,
|
||||
query: requestUrl.searchParams.get('query') || baseQuery,
|
||||
limit: requestUrl.searchParams.get('limit') || 12,
|
||||
allowActions,
|
||||
});
|
||||
sendJson(res, 200, snapshot);
|
||||
return;
|
||||
}
|
||||
|
||||
const actionMatch = requestUrl.pathname.match(/^\/api\/actions\/([^/]+)$/);
|
||||
if (req.method === 'POST' && actionMatch) {
|
||||
if (!allowActions) {
|
||||
sendJson(res, 403, {
|
||||
ok: false,
|
||||
error: 'Control-pane action execution is disabled by --read-only.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await readRequestJson(req);
|
||||
const action = buildControlPaneAction(decodeURIComponent(actionMatch[1]), {
|
||||
repoRoot,
|
||||
query: body.query || baseQuery,
|
||||
limit: body.limit || 25,
|
||||
});
|
||||
|
||||
if (!action.executable) {
|
||||
sendJson(res, 400, {
|
||||
ok: false,
|
||||
action: action.id,
|
||||
error: 'This action is copy-only and cannot be executed from the browser.',
|
||||
commandLine: action.commandLine,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await runAction(action);
|
||||
sendJson(res, result.ok ? 200 : 500, {
|
||||
...result,
|
||||
commandLine: action.commandLine,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
sendJson(res, 404, { ok: false, error: 'not found' });
|
||||
} catch (error) {
|
||||
sendJson(res, 500, {
|
||||
ok: false,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
get url() {
|
||||
const address = server.address();
|
||||
const actualPort = address && typeof address === 'object' ? address.port : port;
|
||||
return `http://${host}:${actualPort}`;
|
||||
},
|
||||
server,
|
||||
config: resolvedConfig,
|
||||
listen() {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(port, host, () => {
|
||||
server.off('error', reject);
|
||||
resolve(this);
|
||||
});
|
||||
});
|
||||
},
|
||||
close() {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close(error => {
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createControlPaneServer,
|
||||
parseArgs,
|
||||
runAction,
|
||||
usage,
|
||||
};
|
||||
518
scripts/lib/control-pane/state.js
Normal file
518
scripts/lib/control-pane/state.js
Normal file
@@ -0,0 +1,518 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const initSqlJs = require('sql.js');
|
||||
const toml = require('@iarna/toml');
|
||||
|
||||
const { buildControlPaneActions } = require('./actions');
|
||||
|
||||
const SNAPSHOT_SCHEMA_VERSION = 'ecc.control-pane.snapshot.v1';
|
||||
|
||||
function homeDir(env = process.env) {
|
||||
return env.HOME || env.USERPROFILE || os.homedir() || '.';
|
||||
}
|
||||
|
||||
function defaultDbPath(env = process.env) {
|
||||
return path.join(homeDir(env), '.claude', 'ecc2.db');
|
||||
}
|
||||
|
||||
function defaultConfigPaths(cwd = process.cwd(), env = process.env) {
|
||||
const home = homeDir(env);
|
||||
const paths = [
|
||||
path.join(home, 'Library', 'Application Support', 'ecc2', 'config.toml'),
|
||||
path.join(home, '.config', 'ecc2', 'config.toml'),
|
||||
path.join(home, '.claude', 'ecc2.toml'),
|
||||
];
|
||||
|
||||
let current = path.resolve(cwd);
|
||||
while (current && current !== path.dirname(current)) {
|
||||
paths.push(path.join(current, '.claude', 'ecc2.toml'));
|
||||
paths.push(path.join(current, 'ecc2.toml'));
|
||||
current = path.dirname(current);
|
||||
}
|
||||
|
||||
return Array.from(new Set(paths));
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function deepMerge(base, override) {
|
||||
const merged = { ...base };
|
||||
for (const [key, value] of Object.entries(override || {})) {
|
||||
if (isPlainObject(value) && isPlainObject(merged[key])) {
|
||||
merged[key] = deepMerge(merged[key], value);
|
||||
} else {
|
||||
merged[key] = value;
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
function toCamelCase(value) {
|
||||
return String(value).replace(/_([a-z])/g, (_, char) => char.toUpperCase());
|
||||
}
|
||||
|
||||
function normalizeObjectKeys(value) {
|
||||
if (Array.isArray(value)) return value.map(normalizeObjectKeys);
|
||||
if (!isPlainObject(value)) return value;
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, item]) => [toCamelCase(key), normalizeObjectKeys(item)])
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeMemoryConnectors(connectors = {}) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(connectors || {})
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([name, connector]) => [name, normalizeObjectKeys(connector)])
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeConfig(rawConfig = {}, options = {}) {
|
||||
const { memory_connectors: snakeMemoryConnectors, memoryConnectors, ...rest } = rawConfig;
|
||||
const normalized = normalizeObjectKeys(rest);
|
||||
const connectorConfig = memoryConnectors || snakeMemoryConnectors || normalized.memoryConnectors;
|
||||
return {
|
||||
dbPath: options.dbPath || normalized.dbPath || defaultDbPath(options.env),
|
||||
memoryConnectors: normalizeMemoryConnectors(connectorConfig),
|
||||
};
|
||||
}
|
||||
|
||||
function readTomlConfig(configPath) {
|
||||
const raw = fs.readFileSync(configPath, 'utf8');
|
||||
return toml.parse(raw);
|
||||
}
|
||||
|
||||
function resolveControlPaneConfig(options = {}) {
|
||||
const env = options.env || process.env;
|
||||
const cwd = options.cwd || process.cwd();
|
||||
const configPaths = options.configPath
|
||||
? [path.resolve(options.configPath)]
|
||||
: defaultConfigPaths(cwd, env);
|
||||
let merged = {};
|
||||
|
||||
for (const configPath of configPaths) {
|
||||
if (fs.existsSync(configPath)) {
|
||||
merged = deepMerge(merged, readTomlConfig(configPath));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...normalizeConfig(merged, {
|
||||
env,
|
||||
dbPath: options.dbPath || env.ECC2_DB_PATH || null,
|
||||
}),
|
||||
configPaths: configPaths.filter(configPath => fs.existsSync(configPath)),
|
||||
};
|
||||
}
|
||||
|
||||
async function openSqlDatabase(dbPath) {
|
||||
if (!dbPath || !fs.existsSync(dbPath)) return null;
|
||||
const SQL = await initSqlJs();
|
||||
const buffer = fs.readFileSync(dbPath);
|
||||
return new SQL.Database(buffer);
|
||||
}
|
||||
|
||||
function execRows(db, sql, params = []) {
|
||||
const stmt = db.prepare(sql);
|
||||
try {
|
||||
stmt.bind(params);
|
||||
const rows = [];
|
||||
while (stmt.step()) rows.push(stmt.getAsObject());
|
||||
return rows;
|
||||
} finally {
|
||||
stmt.free();
|
||||
}
|
||||
}
|
||||
|
||||
function tableExists(db, tableName) {
|
||||
const rows = execRows(
|
||||
db,
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",
|
||||
[tableName]
|
||||
);
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
function parseJson(value, fallback) {
|
||||
if (typeof value !== 'string' || value.trim() === '') return fallback;
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function toNumber(value, fallback = 0) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function normalizeSession(row, unreadMessages) {
|
||||
const id = String(row.id || '');
|
||||
return {
|
||||
id,
|
||||
task: String(row.task || ''),
|
||||
project: String(row.project || ''),
|
||||
taskGroup: String(row.task_group || ''),
|
||||
agentType: String(row.agent_type || ''),
|
||||
harness: String(row.harness || 'unknown'),
|
||||
detectedHarnesses: parseJson(row.detected_harnesses_json, []),
|
||||
workingDir: String(row.working_dir || '.'),
|
||||
state: String(row.state || 'pending'),
|
||||
pid: row.pid === null || row.pid === undefined ? null : toNumber(row.pid),
|
||||
worktree: row.worktree_path
|
||||
? {
|
||||
path: String(row.worktree_path),
|
||||
branch: row.worktree_branch ? String(row.worktree_branch) : null,
|
||||
base: row.worktree_base ? String(row.worktree_base) : null,
|
||||
}
|
||||
: null,
|
||||
metrics: {
|
||||
inputTokens: toNumber(row.input_tokens),
|
||||
outputTokens: toNumber(row.output_tokens),
|
||||
tokensUsed: toNumber(row.tokens_used),
|
||||
toolCalls: toNumber(row.tool_calls),
|
||||
filesChanged: toNumber(row.files_changed),
|
||||
durationSecs: toNumber(row.duration_secs),
|
||||
costUsd: toNumber(row.cost_usd),
|
||||
},
|
||||
unreadMessages: unreadMessages.get(id) || 0,
|
||||
createdAt: String(row.created_at || ''),
|
||||
updatedAt: String(row.updated_at || ''),
|
||||
lastHeartbeatAt: String(row.last_heartbeat_at || ''),
|
||||
};
|
||||
}
|
||||
|
||||
function readUnreadMessageCounts(db) {
|
||||
if (!tableExists(db, 'messages')) return new Map();
|
||||
return new Map(
|
||||
execRows(
|
||||
db,
|
||||
'SELECT to_session, COUNT(*) AS unread_count FROM messages WHERE read = 0 GROUP BY to_session'
|
||||
).map(row => [String(row.to_session), toNumber(row.unread_count)])
|
||||
);
|
||||
}
|
||||
|
||||
function readSessions(db) {
|
||||
if (!tableExists(db, 'sessions')) return [];
|
||||
const unreadMessages = readUnreadMessageCounts(db);
|
||||
return execRows(
|
||||
db,
|
||||
`SELECT *
|
||||
FROM sessions
|
||||
ORDER BY updated_at DESC, created_at DESC, id ASC
|
||||
LIMIT 100`
|
||||
).map(row => normalizeSession(row, unreadMessages));
|
||||
}
|
||||
|
||||
function summarizeSessions(sessions) {
|
||||
const summary = {
|
||||
totalSessions: sessions.length,
|
||||
runningSessions: 0,
|
||||
pendingSessions: 0,
|
||||
idleSessions: 0,
|
||||
failedSessions: 0,
|
||||
stoppedSessions: 0,
|
||||
completedSessions: 0,
|
||||
unreadMessages: 0,
|
||||
activeWorktrees: 0,
|
||||
totalTokens: 0,
|
||||
totalCostUsd: 0,
|
||||
};
|
||||
|
||||
for (const session of sessions) {
|
||||
if (session.state === 'running') summary.runningSessions += 1;
|
||||
if (session.state === 'pending') summary.pendingSessions += 1;
|
||||
if (session.state === 'idle') summary.idleSessions += 1;
|
||||
if (session.state === 'failed') summary.failedSessions += 1;
|
||||
if (session.state === 'stopped') summary.stoppedSessions += 1;
|
||||
if (session.state === 'completed') summary.completedSessions += 1;
|
||||
if (session.worktree) summary.activeWorktrees += 1;
|
||||
summary.unreadMessages += session.unreadMessages;
|
||||
summary.totalTokens += session.metrics.tokensUsed;
|
||||
summary.totalCostUsd += session.metrics.costUsd;
|
||||
}
|
||||
|
||||
summary.totalCostUsd = Number(summary.totalCostUsd.toFixed(6));
|
||||
return summary;
|
||||
}
|
||||
|
||||
function readEntities(db) {
|
||||
if (!tableExists(db, 'context_graph_entities')) return [];
|
||||
return execRows(
|
||||
db,
|
||||
`SELECT *
|
||||
FROM context_graph_entities
|
||||
ORDER BY updated_at DESC, id DESC
|
||||
LIMIT 500`
|
||||
).map(row => ({
|
||||
id: toNumber(row.id),
|
||||
sessionId: row.session_id ? String(row.session_id) : null,
|
||||
entityType: String(row.entity_type || ''),
|
||||
name: String(row.name || ''),
|
||||
path: row.path ? String(row.path) : null,
|
||||
summary: String(row.summary || ''),
|
||||
metadata: parseJson(row.metadata_json, {}),
|
||||
createdAt: String(row.created_at || ''),
|
||||
updatedAt: String(row.updated_at || ''),
|
||||
}));
|
||||
}
|
||||
|
||||
function readObservations(db) {
|
||||
if (!tableExists(db, 'context_graph_observations')) return [];
|
||||
return execRows(
|
||||
db,
|
||||
`SELECT *
|
||||
FROM context_graph_observations
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1000`
|
||||
).map(row => ({
|
||||
id: toNumber(row.id),
|
||||
sessionId: row.session_id ? String(row.session_id) : null,
|
||||
entityId: toNumber(row.entity_id),
|
||||
observationType: String(row.observation_type || ''),
|
||||
priority: toNumber(row.priority, 1),
|
||||
pinned: toNumber(row.pinned) === 1,
|
||||
summary: String(row.summary || ''),
|
||||
details: parseJson(row.details_json, {}),
|
||||
createdAt: String(row.created_at || ''),
|
||||
}));
|
||||
}
|
||||
|
||||
function readRelationCounts(db) {
|
||||
if (!tableExists(db, 'context_graph_relations')) return new Map();
|
||||
const rows = execRows(
|
||||
db,
|
||||
`SELECT entity_id, SUM(relation_count) AS relation_count
|
||||
FROM (
|
||||
SELECT from_entity_id AS entity_id, COUNT(*) AS relation_count
|
||||
FROM context_graph_relations
|
||||
GROUP BY from_entity_id
|
||||
UNION ALL
|
||||
SELECT to_entity_id AS entity_id, COUNT(*) AS relation_count
|
||||
FROM context_graph_relations
|
||||
GROUP BY to_entity_id
|
||||
)
|
||||
GROUP BY entity_id`
|
||||
);
|
||||
return new Map(rows.map(row => [toNumber(row.entity_id), toNumber(row.relation_count)]));
|
||||
}
|
||||
|
||||
function tokenize(value) {
|
||||
return String(value || '')
|
||||
.toLowerCase()
|
||||
.split(/[^a-z0-9_.-]+/g)
|
||||
.map(token => token.trim())
|
||||
.filter(token => token.length >= 2);
|
||||
}
|
||||
|
||||
function scoreEntity(entity, observations, relationCount, queryTerms) {
|
||||
const observationText = observations.map(observation => observation.summary).join(' ');
|
||||
const metadataText = Object.entries(entity.metadata || {})
|
||||
.map(([key, value]) => `${key} ${value}`)
|
||||
.join(' ');
|
||||
const haystacks = [
|
||||
{ text: entity.name, weight: 12 },
|
||||
{ text: entity.entityType, weight: 5 },
|
||||
{ text: entity.path || '', weight: 6 },
|
||||
{ text: entity.summary, weight: 8 },
|
||||
{ text: metadataText, weight: 5 },
|
||||
{ text: observationText, weight: 10 },
|
||||
].map(item => ({ ...item, text: item.text.toLowerCase() }));
|
||||
const matchedTerms = [];
|
||||
let score = 0;
|
||||
|
||||
for (const term of queryTerms) {
|
||||
let matched = false;
|
||||
for (const haystack of haystacks) {
|
||||
if (haystack.text.includes(term)) {
|
||||
score += haystack.weight;
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
if (matched) matchedTerms.push(term);
|
||||
}
|
||||
|
||||
const maxPriority = observations.reduce(
|
||||
(highest, observation) => Math.max(highest, observation.priority),
|
||||
0
|
||||
);
|
||||
const hasPinnedObservation = observations.some(observation => observation.pinned);
|
||||
score += Math.min(relationCount, 8);
|
||||
score += maxPriority * 3;
|
||||
if (hasPinnedObservation) score += 8;
|
||||
|
||||
return {
|
||||
score,
|
||||
matchedTerms,
|
||||
observationCount: observations.length,
|
||||
relationCount,
|
||||
maxObservationPriority: maxPriority,
|
||||
hasPinnedObservation,
|
||||
};
|
||||
}
|
||||
|
||||
function recallKnowledgeEntries({ entities, observations, relationCounts, query, limit = 12 }) {
|
||||
const queryTerms = Array.from(new Set(tokenize(query)));
|
||||
const observationsByEntity = new Map();
|
||||
for (const observation of observations) {
|
||||
const bucket = observationsByEntity.get(observation.entityId) || [];
|
||||
bucket.push(observation);
|
||||
observationsByEntity.set(observation.entityId, bucket);
|
||||
}
|
||||
|
||||
return entities
|
||||
.map(entity => {
|
||||
const entityObservations = observationsByEntity.get(entity.id) || [];
|
||||
const score = queryTerms.length > 0
|
||||
? scoreEntity(entity, entityObservations, relationCounts.get(entity.id) || 0, queryTerms)
|
||||
: {
|
||||
score: entityObservations.some(observation => observation.pinned) ? 10 : 1,
|
||||
matchedTerms: [],
|
||||
observationCount: entityObservations.length,
|
||||
relationCount: relationCounts.get(entity.id) || 0,
|
||||
maxObservationPriority: entityObservations.reduce(
|
||||
(highest, observation) => Math.max(highest, observation.priority),
|
||||
0
|
||||
),
|
||||
hasPinnedObservation: entityObservations.some(observation => observation.pinned),
|
||||
};
|
||||
return {
|
||||
entity,
|
||||
...score,
|
||||
latestObservation: entityObservations[0] || null,
|
||||
};
|
||||
})
|
||||
.filter(entry => queryTerms.length === 0 || entry.matchedTerms.length > 0)
|
||||
.sort((left, right) => {
|
||||
if (right.score !== left.score) return right.score - left.score;
|
||||
return String(right.entity.updatedAt).localeCompare(String(left.entity.updatedAt));
|
||||
})
|
||||
.slice(0, Math.max(1, Math.min(Number(limit) || 12, 50)));
|
||||
}
|
||||
|
||||
function readConnectorCheckpointRows(db) {
|
||||
if (!tableExists(db, 'context_graph_connector_checkpoints')) return [];
|
||||
return execRows(
|
||||
db,
|
||||
`SELECT connector_name, COUNT(*) AS synced_sources, MAX(updated_at) AS last_synced_at
|
||||
FROM context_graph_connector_checkpoints
|
||||
GROUP BY connector_name`
|
||||
);
|
||||
}
|
||||
|
||||
function connectorStatus(config, db) {
|
||||
const checkpoints = new Map(
|
||||
(db ? readConnectorCheckpointRows(db) : []).map(row => [
|
||||
String(row.connector_name),
|
||||
{
|
||||
syncedSources: toNumber(row.synced_sources),
|
||||
lastSyncedAt: row.last_synced_at ? String(row.last_synced_at) : null,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
return Object.entries(config.memoryConnectors || {})
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([name, connector]) => {
|
||||
const checkpoint = checkpoints.get(name) || { syncedSources: 0, lastSyncedAt: null };
|
||||
return {
|
||||
name,
|
||||
kind: connector.kind || 'unknown',
|
||||
path: connector.path || null,
|
||||
recurse: Boolean(connector.recurse),
|
||||
defaultEntityType: connector.defaultEntityType || null,
|
||||
defaultObservationType: connector.defaultObservationType || null,
|
||||
includeSafeValues: Boolean(connector.includeSafeValues),
|
||||
syncedSources: checkpoint.syncedSources,
|
||||
lastSyncedAt: checkpoint.lastSyncedAt,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function buildControlPaneSnapshot(options = {}) {
|
||||
const repoRoot = path.resolve(options.repoRoot || path.join(__dirname, '..', '..', '..'));
|
||||
const config = options.config
|
||||
? normalizeConfig(options.config, {
|
||||
env: options.env || process.env,
|
||||
dbPath: options.dbPath || options.config.dbPath || null,
|
||||
})
|
||||
: resolveControlPaneConfig(options);
|
||||
const dbPath = options.dbPath || config.dbPath;
|
||||
const query = String(options.query || '').trim();
|
||||
const limit = Math.max(1, Math.min(Number.parseInt(String(options.limit || 12), 10) || 12, 50));
|
||||
const generatedAt = new Date().toISOString();
|
||||
const base = {
|
||||
schemaVersion: SNAPSHOT_SCHEMA_VERSION,
|
||||
generatedAt,
|
||||
repoRoot,
|
||||
dbPath,
|
||||
database: {
|
||||
exists: Boolean(dbPath && fs.existsSync(dbPath)),
|
||||
},
|
||||
config: {
|
||||
configPaths: config.configPaths || [],
|
||||
memoryConnectorCount: Object.keys(config.memoryConnectors || {}).length,
|
||||
},
|
||||
execution: {
|
||||
allowActions: options.allowActions !== false,
|
||||
},
|
||||
summary: summarizeSessions([]),
|
||||
sessions: [],
|
||||
knowledge: {
|
||||
query,
|
||||
entityCount: 0,
|
||||
observationCount: 0,
|
||||
results: [],
|
||||
},
|
||||
connectors: connectorStatus(config, null),
|
||||
actions: buildControlPaneActions({ repoRoot, query, limit }),
|
||||
};
|
||||
|
||||
const db = await openSqlDatabase(dbPath);
|
||||
if (!db) {
|
||||
return base;
|
||||
}
|
||||
|
||||
try {
|
||||
const sessions = readSessions(db);
|
||||
const entities = readEntities(db);
|
||||
const observations = readObservations(db);
|
||||
const relationCounts = readRelationCounts(db);
|
||||
return {
|
||||
...base,
|
||||
summary: summarizeSessions(sessions),
|
||||
sessions,
|
||||
knowledge: {
|
||||
query,
|
||||
entityCount: entities.length,
|
||||
observationCount: observations.length,
|
||||
results: recallKnowledgeEntries({
|
||||
entities,
|
||||
observations,
|
||||
relationCounts,
|
||||
query,
|
||||
limit,
|
||||
}),
|
||||
},
|
||||
connectors: connectorStatus(config, db),
|
||||
};
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SNAPSHOT_SCHEMA_VERSION,
|
||||
buildControlPaneSnapshot,
|
||||
defaultConfigPaths,
|
||||
recallKnowledgeEntries,
|
||||
resolveControlPaneConfig,
|
||||
};
|
||||
554
scripts/lib/control-pane/ui.js
Normal file
554
scripts/lib/control-pane/ui.js
Normal file
@@ -0,0 +1,554 @@
|
||||
'use strict';
|
||||
|
||||
function renderControlPaneHtml() {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>ECC Control Pane</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #101312;
|
||||
--panel: #181d1b;
|
||||
--panel-2: #202622;
|
||||
--ink: #f4f0e8;
|
||||
--muted: #aab3aa;
|
||||
--line: #344038;
|
||||
--accent: #6fd8b5;
|
||||
--accent-2: #e6c35c;
|
||||
--danger: #ff7a72;
|
||||
--blue: #82aaff;
|
||||
--shadow: rgba(0, 0, 0, 0.28);
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
min-width: 320px;
|
||||
}
|
||||
|
||||
button, input {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.shell {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-rows: auto 1fr;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 18px;
|
||||
padding: 14px 18px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #121715;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.brand img {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 18px;
|
||||
line-height: 1.1;
|
||||
margin: 0;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.query {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
min-width: 220px;
|
||||
max-width: 780px;
|
||||
}
|
||||
|
||||
input[type="search"] {
|
||||
width: 100%;
|
||||
color: var(--ink);
|
||||
background: #0c0f0e;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 9px 10px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input[type="search"]:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button {
|
||||
color: var(--ink);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 9px 12px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button.primary {
|
||||
color: #06100c;
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 18px;
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
grid-template-columns: minmax(0, 1.2fr) minmax(360px, 0.8fr);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.metrics {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.metric,
|
||||
section {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 12px 30px var(--shadow);
|
||||
}
|
||||
|
||||
.metric {
|
||||
padding: 12px;
|
||||
min-height: 84px;
|
||||
}
|
||||
|
||||
.metric span {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.metric strong {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 26px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
section {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.section-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #151a18;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.subtle {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid rgba(52, 64, 56, 0.7);
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
font-size: 13px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
th {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0;
|
||||
background: #131816;
|
||||
}
|
||||
|
||||
.stack {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.result,
|
||||
.connector,
|
||||
.action {
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid rgba(52, 64, 56, 0.7);
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.result:last-child,
|
||||
.connector:last-child,
|
||||
.action:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.row > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 22px;
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: #222a26;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pill.good { color: #07110d; background: var(--accent); }
|
||||
.pill.warn { color: #171000; background: var(--accent-2); }
|
||||
.pill.bad { color: #190706; background: var(--danger); }
|
||||
.pill.blue { color: #071020; background: var(--blue); }
|
||||
|
||||
code {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 9px;
|
||||
background: #0c0f0e;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
color: #d6e7dc;
|
||||
overflow-x: auto;
|
||||
white-space: pre;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
#run-output {
|
||||
min-height: 44px;
|
||||
max-height: 260px;
|
||||
}
|
||||
|
||||
#app {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
max-width: min(640px, calc(100vw - 32px));
|
||||
max-height: 45vh;
|
||||
overflow: auto;
|
||||
padding: 12px 14px;
|
||||
background: #190706;
|
||||
border: 1px solid var(--danger);
|
||||
border-radius: 8px;
|
||||
color: #ffe5e2;
|
||||
box-shadow: 0 12px 30px var(--shadow);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 18px 14px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
@media (max-width: 1040px) {
|
||||
main { grid-template-columns: 1fr; }
|
||||
.metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
header { align-items: stretch; flex-direction: column; }
|
||||
.query { max-width: none; width: 100%; }
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
main { padding: 12px; }
|
||||
.metrics { grid-template-columns: 1fr; }
|
||||
.query { flex-direction: column; }
|
||||
th:nth-child(4), td:nth-child(4) { display: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header>
|
||||
<div class="brand">
|
||||
<img src="/assets/ecc-icon.svg" alt="">
|
||||
<h1>ECC Control Pane</h1>
|
||||
</div>
|
||||
<form class="query" id="query-form">
|
||||
<input id="query" type="search" placeholder="Recall operator memory, session context, runbooks">
|
||||
<button class="primary" type="submit">Recall</button>
|
||||
<button type="button" id="refresh">Refresh</button>
|
||||
</form>
|
||||
</header>
|
||||
<main>
|
||||
<div class="stack">
|
||||
<div class="metrics" id="metrics"></div>
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<h2>Sessions</h2>
|
||||
<span class="subtle" id="db-path"></span>
|
||||
</div>
|
||||
<div id="sessions"></div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="stack">
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<h2>Knowledge</h2>
|
||||
<span class="subtle" id="knowledge-count"></span>
|
||||
</div>
|
||||
<div id="knowledge"></div>
|
||||
</section>
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<h2>Connectors</h2>
|
||||
<span class="subtle" id="connector-count"></span>
|
||||
</div>
|
||||
<div id="connectors"></div>
|
||||
</section>
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<h2>Actions</h2>
|
||||
<span class="subtle" id="action-status">local allowlist</span>
|
||||
</div>
|
||||
<div id="actions"></div>
|
||||
<div class="action">
|
||||
<code id="run-output">No action output yet.</code>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<div id="app" hidden></div>
|
||||
<script>
|
||||
const state = { query: '' };
|
||||
const $ = selector => document.querySelector(selector);
|
||||
const escapeHtml = value => String(value ?? '').replace(/[&<>"']/g, char => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||
})[char]);
|
||||
const fmt = new Intl.NumberFormat('en-US');
|
||||
|
||||
function formatError(error) {
|
||||
if (!error) return 'Unknown error';
|
||||
return error.stack || error.message || String(error);
|
||||
}
|
||||
|
||||
function showError(targetSelector, error) {
|
||||
const target = $(targetSelector);
|
||||
if (!target) return;
|
||||
target.hidden = false;
|
||||
target.textContent = formatError(error);
|
||||
}
|
||||
|
||||
function clearError(targetSelector) {
|
||||
const target = $(targetSelector);
|
||||
if (!target) return;
|
||||
target.hidden = true;
|
||||
target.textContent = '';
|
||||
}
|
||||
|
||||
async function readJsonResponse(response) {
|
||||
let payload;
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch (error) {
|
||||
throw new Error('Expected JSON response from control pane: ' + error.message);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const detail = payload && payload.error ? payload.error : response.status + ' ' + response.statusText;
|
||||
throw new Error(detail);
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
function statePill(stateName) {
|
||||
const state = String(stateName || 'unknown');
|
||||
const klass = state === 'running' ? 'good' : state === 'failed' ? 'bad' : state === 'pending' ? 'warn' : 'blue';
|
||||
return '<span class="pill ' + klass + '">' + escapeHtml(state) + '</span>';
|
||||
}
|
||||
|
||||
function renderMetrics(summary) {
|
||||
const items = [
|
||||
['Sessions', summary.totalSessions],
|
||||
['Running', summary.runningSessions],
|
||||
['Unread', summary.unreadMessages],
|
||||
['Tokens', fmt.format(summary.totalTokens || 0)],
|
||||
];
|
||||
$('#metrics').innerHTML = items.map(([label, value]) =>
|
||||
'<div class="metric"><span>' + escapeHtml(label) + '</span><strong>' + escapeHtml(value) + '</strong></div>'
|
||||
).join('');
|
||||
}
|
||||
|
||||
function renderSessions(sessions) {
|
||||
if (!sessions.length) {
|
||||
$('#sessions').innerHTML = '<div class="empty">No ECC2 sessions found.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
$('#sessions').innerHTML = '<table><thead><tr><th>State</th><th>Session</th><th>Harness</th><th>Worktree</th><th>Updated</th></tr></thead><tbody>' +
|
||||
sessions.map(session => '<tr>' +
|
||||
'<td>' + statePill(session.state) + '</td>' +
|
||||
'<td><strong>' + escapeHtml(session.id) + '</strong><br><span class="subtle">' + escapeHtml(session.task) + '</span></td>' +
|
||||
'<td>' + escapeHtml(session.agentType || session.harness) + '<br><span class="subtle">' + escapeHtml((session.detectedHarnesses || []).join(', ')) + '</span></td>' +
|
||||
'<td>' + escapeHtml(session.worktree ? session.worktree.branch || session.worktree.path : '-') + '</td>' +
|
||||
'<td>' + escapeHtml(session.updatedAt || '-') + '</td>' +
|
||||
'</tr>').join('') +
|
||||
'</tbody></table>';
|
||||
}
|
||||
|
||||
function renderKnowledge(knowledge) {
|
||||
$('#knowledge-count').textContent = knowledge.entityCount + ' entities';
|
||||
if (!knowledge.results.length) {
|
||||
$('#knowledge').innerHTML = '<div class="empty">No recall results for this query.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
$('#knowledge').innerHTML = knowledge.results.map(result => {
|
||||
const entity = result.entity;
|
||||
const obs = result.latestObservation;
|
||||
return '<div class="result">' +
|
||||
'<div class="row"><strong>' + escapeHtml(entity.name) + '</strong><span class="pill good">score ' + escapeHtml(result.score) + '</span></div>' +
|
||||
'<div class="subtle">' + escapeHtml(entity.entityType) + (entity.path ? ' - ' + escapeHtml(entity.path) : '') + '</div>' +
|
||||
'<div>' + escapeHtml(entity.summary || '') + '</div>' +
|
||||
(obs ? '<div class="subtle">' + (result.hasPinnedObservation ? 'Pinned - ' : '') + escapeHtml(obs.summary) + '</div>' : '') +
|
||||
'<div class="subtle">terms: ' + escapeHtml((result.matchedTerms || []).join(', ') || '-') + '</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderConnectors(connectors) {
|
||||
$('#connector-count').textContent = connectors.length + ' configured';
|
||||
if (!connectors.length) {
|
||||
$('#connectors').innerHTML = '<div class="empty">No memory connectors configured.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
$('#connectors').innerHTML = connectors.map(connector => {
|
||||
const status = connector.syncedSources > 0 ? '<span class="pill good">synced</span>' : '<span class="pill warn">not synced</span>';
|
||||
return '<div class="connector">' +
|
||||
'<div class="row"><strong>' + escapeHtml(connector.name) + '</strong>' + status + '</div>' +
|
||||
'<div class="subtle">' + escapeHtml(connector.kind) + ' - ' + escapeHtml(connector.path || '-') + '</div>' +
|
||||
'<div class="subtle">sources ' + escapeHtml(connector.syncedSources) + ' - last ' + escapeHtml(connector.lastSyncedAt || '-') + '</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderActions(actions) {
|
||||
$('#actions').innerHTML = actions.map(action => '<div class="action">' +
|
||||
'<div class="row"><strong>' + escapeHtml(action.label) + '</strong>' +
|
||||
(action.executable ? '<button data-action="' + escapeHtml(action.id) + '">Run</button>' : '<span class="pill">copy</span>') + '</div>' +
|
||||
'<div class="subtle">' + escapeHtml(action.description) + '</div>' +
|
||||
'<code>' + escapeHtml(action.commandLine) + '</code>' +
|
||||
'</div>').join('');
|
||||
|
||||
document.querySelectorAll('[data-action]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
runAction(button.dataset.action);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function runAction(actionId) {
|
||||
const output = $('#run-output');
|
||||
output.textContent = 'Running ' + actionId + '...';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/actions/' + encodeURIComponent(actionId), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ query: state.query })
|
||||
});
|
||||
const payload = await readJsonResponse(response);
|
||||
output.textContent = JSON.stringify(payload, null, 2);
|
||||
await load();
|
||||
} catch (error) {
|
||||
output.textContent = formatError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const url = new URL('/api/snapshot', window.location.href);
|
||||
if (state.query) url.searchParams.set('query', state.query);
|
||||
const response = await fetch(url);
|
||||
const snapshot = await readJsonResponse(response);
|
||||
$('#query').value = snapshot.knowledge.query || state.query;
|
||||
$('#db-path').textContent = snapshot.database.exists ? snapshot.dbPath : 'database missing';
|
||||
$('#action-status').textContent = snapshot.execution.allowActions ? 'local allowlist' : 'read-only';
|
||||
renderMetrics(snapshot.summary);
|
||||
renderSessions(snapshot.sessions);
|
||||
renderKnowledge(snapshot.knowledge);
|
||||
renderConnectors(snapshot.connectors);
|
||||
renderActions(snapshot.actions.map(action => ({
|
||||
...action,
|
||||
executable: snapshot.execution.allowActions && action.executable
|
||||
})));
|
||||
clearError('#app');
|
||||
}
|
||||
|
||||
$('#query-form').addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
state.query = $('#query').value.trim();
|
||||
load().catch(error => showError('#app', error));
|
||||
});
|
||||
$('#refresh').addEventListener('click', () => {
|
||||
load().catch(error => showError('#app', error));
|
||||
});
|
||||
load().catch(error => showError('#app', error));
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
renderControlPaneHtml,
|
||||
};
|
||||
Reference in New Issue
Block a user