mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
- Add zero-SDK standalone HTTP server (`standalone.mjs` / `standalone-server.mjs`) with responsive centered Web shell, `127.0.0.1` default loopback guard, mandatory `--token` enforcement on non-loopback binds (`HttpOnly; SameSite=Strict` cookie + `Bearer` auth), and optional background auto-hosting via `standalonePort` / `USAGE_MONITOR_STANDALONE_PORT`. - Extend multi-root data discovery across `~/.gemini/antigravity` and `~/.gemini/antigravity-cli`, plus `daemon/hub_*.json` and `/proc` + `ss` Language Server endpoint discovery on minimal headless Linux hosts without `lsof`. - Add read-only `node:sqlite` + lightweight protobuf wire reader (`cli-sqlite-reader.mjs`) to recover CLI session titles (`annotations/*.pbtxt` & `conversation_summaries.db`), nanosecond request duration/TPS, native TTFT, thinking/response token split, 10-channel context breakdown, and `Antigravity CLI` source attribution. - Add regression tests (124 passing) and bilingual CLI / SSH tunnel / `--token` documentation in `README.zh-CN.md` and `README.md`. Closes #18
160 lines
5.3 KiB
JavaScript
160 lines
5.3 KiB
JavaScript
/**
|
||
* @fileoverview Antigravity IDE / 2.0 / CLI 独立后台守护进程 (`bridge-daemon.mjs`)。
|
||
*
|
||
* 由 `mcp-entry.mjs` 托管拉起(亦支持命令行 `--standalone` 直接启动),负责:
|
||
* 1. 动态探测本机运行中的 `agy` (`daemon/hub_*.json` / `--hub` / `remote-control`) 或 `language_server` 端点;
|
||
* 2. 在桌面端 / IDE 环境启动本地回环桥接服务并通过 CDP 挂载监控胶囊;
|
||
* 3. 当配置了 `USAGE_MONITOR_STANDALONE_PORT` 或 `settings.json` 中的 `standalonePort`(`1024..65535`)时,
|
||
* 自动在后台托管独立 Web 监控端口,无需手工另开进程;
|
||
* 4. 收到父进程 `SHUTDOWN_DISPOSE` 指令或终止信号时,主动清理窗口浮层与独立端口并平滑退出。
|
||
*/
|
||
|
||
import { resolve } from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
import {
|
||
bootWindowBridgeRuntime,
|
||
setStandalonePortListener,
|
||
} from './backend/api-actions.mjs';
|
||
import { loadSettings, normalizeStandalonePort } from './backend/config.mjs';
|
||
import {
|
||
createStandaloneWebServer,
|
||
parseStandaloneCliArgs,
|
||
} from './backend/standalone-server.mjs';
|
||
import { runStandaloneCli } from './standalone.mjs';
|
||
|
||
export function startBridgeDaemon() {
|
||
let shuttingDown = false;
|
||
let sawShutdownDispose = false;
|
||
let stdinBuf = '';
|
||
let standaloneController = null;
|
||
let activeStandalonePort = 0;
|
||
let reconcileChain = Promise.resolve();
|
||
|
||
const envArgs = parseStandaloneCliArgs([], process.env, { defaultPort: 0 });
|
||
const envPinnedPort = envArgs.portExplicit ? normalizeStandalonePort(envArgs.port) : null;
|
||
|
||
const triggerRestart = () => {
|
||
void shutdown({ disposeWindows: false, exitCode: 0 });
|
||
};
|
||
|
||
const controller = bootWindowBridgeRuntime({
|
||
allowDynamicLs: true,
|
||
onRestart: triggerRestart,
|
||
});
|
||
|
||
function resolveDesiredStandalonePort(settingsOverride = null) {
|
||
if (envPinnedPort !== null) {
|
||
return envPinnedPort;
|
||
}
|
||
const settings = settingsOverride || loadSettings();
|
||
return normalizeStandalonePort(settings?.standalonePort);
|
||
}
|
||
|
||
function scheduleStandaloneReconcile(targetPort) {
|
||
reconcileChain = reconcileChain
|
||
.then(async () => {
|
||
if (shuttingDown) return;
|
||
const nextPort = normalizeStandalonePort(targetPort);
|
||
if (nextPort === activeStandalonePort && standaloneController) {
|
||
return;
|
||
}
|
||
if (standaloneController) {
|
||
const prev = standaloneController;
|
||
standaloneController = null;
|
||
activeStandalonePort = 0;
|
||
await prev.stop().catch(() => {});
|
||
}
|
||
if (nextPort <= 0 || shuttingDown) {
|
||
return;
|
||
}
|
||
try {
|
||
const srv = createStandaloneWebServer({
|
||
host: envArgs.host,
|
||
port: nextPort,
|
||
token: envArgs.token,
|
||
onRestart: triggerRestart,
|
||
skipStartupDiscovery: true,
|
||
});
|
||
const status = await srv.start();
|
||
standaloneController = srv;
|
||
activeStandalonePort = nextPort;
|
||
console.error(`[usage-monitor] Auto-hosted standalone Web UI at ${status.url}`);
|
||
} catch (err) {
|
||
if (err?.code === 'EADDRINUSE') {
|
||
console.error(
|
||
`[usage-monitor] Standalone port ${nextPort} already in use; keeping existing listener.`
|
||
);
|
||
} else {
|
||
console.error(`[usage-monitor] Auto-hosted standalone server skipped: ${err.message}`);
|
||
}
|
||
}
|
||
})
|
||
.catch(() => {});
|
||
}
|
||
|
||
setStandalonePortListener((updatedPort) => {
|
||
if (envPinnedPort === null) {
|
||
scheduleStandaloneReconcile(updatedPort);
|
||
}
|
||
});
|
||
scheduleStandaloneReconcile(resolveDesiredStandalonePort());
|
||
|
||
async function shutdown({ disposeWindows = false, exitCode = 0 } = {}) {
|
||
if (shuttingDown) return;
|
||
shuttingDown = true;
|
||
setStandalonePortListener(null);
|
||
const forceTimer = setTimeout(() => {
|
||
process.exit(exitCode);
|
||
}, 1500);
|
||
forceTimer.unref?.();
|
||
try {
|
||
await Promise.allSettled([
|
||
controller?.stop?.({ disposeWindows }),
|
||
standaloneController?.stop?.(),
|
||
]);
|
||
} catch {
|
||
// 忽略退出清理异常
|
||
} finally {
|
||
clearTimeout(forceTimer);
|
||
process.exit(exitCode);
|
||
}
|
||
}
|
||
|
||
process.stdin.setEncoding('utf8');
|
||
process.stdin.on('data', (chunk) => {
|
||
stdinBuf += String(chunk || '');
|
||
if (stdinBuf.includes('SHUTDOWN_DISPOSE')) {
|
||
sawShutdownDispose = true;
|
||
void shutdown({ disposeWindows: true, exitCode: 0 });
|
||
} else if (stdinBuf.length > 4096) {
|
||
stdinBuf = stdinBuf.slice(-1024);
|
||
}
|
||
});
|
||
|
||
process.stdin.on('end', () => {
|
||
void shutdown({ disposeWindows: sawShutdownDispose, exitCode: 0 });
|
||
});
|
||
process.stdin.on('close', () => {
|
||
void shutdown({ disposeWindows: sawShutdownDispose, exitCode: 0 });
|
||
});
|
||
process.on('SIGTERM', () => {
|
||
void shutdown({ disposeWindows: true, exitCode: 0 });
|
||
});
|
||
process.on('SIGINT', () => {
|
||
void shutdown({ disposeWindows: true, exitCode: 0 });
|
||
});
|
||
|
||
process.stdin.resume();
|
||
return controller;
|
||
}
|
||
|
||
const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
||
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||
const cliArgs = process.argv.slice(2);
|
||
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
||
void runStandaloneCli(cliArgs);
|
||
} else {
|
||
startBridgeDaemon();
|
||
}
|
||
}
|