feat: per-tool settings, persistent settings file, Codex and Antigravity sessions, tokens and hooks (#40 B, C1, C2, D)

Part B: Model Pricing, Hook Configuration and CLAUDE_HOME move from
Settings → Dashboard to the Claude Code tab's AgentHub sub-tab
(ClaudeAgentHubSettings.tsx); CODEX_HOME is editable in Codex → AgentHub.
A home that is or contains the OS home is refused (EBADHOME).

Settings persistence: dashboard-saved settings go to
~/.config/agenthub/settings.env (AGENTHUB_SETTINGS_FILE), outside the plugin
cache an update wipes. Load order: real env > the checkout's .env > that file.
The first CLAUDE_HOME change pins DASHBOARD_DATA_DIR so the DB stays put.

C1: codex-usage.js reads Codex rollout journals into sessions (new column
tool) and token_usage, tracked per file in codex_rollouts; forks deduped by
total vector, sub-agent threads folded into the root; pricing-sync also
prices OpenAI models; PricingSettings with a vendor filter.

C2: codex-hooks.js installs AgentHub's hooks into $CODEX_HOME/hooks.json on
a click, through a stable forwarder; Codex trust is never written. The hook
route creates tool='codex' sessions and folds sub-agent hooks into the root.

D: antigravity-usage.js reads agy's per-conversation SQLite files (tokens
from ModelUsageStats) into tool='antigravity' sessions; antigravity-hooks.js
installs the named hook `agenthub` (PreInvocation, PostToolUse, Stop — never
PreToolUse) into ~/.gemini/config/hooks.json; Settings → Antigravity tab;
Gemini pricing.

Whole-change review fixes: sameOriginGuard on both home PUTs, routers.missing
on a CLAUDE_HOME change, reset-pricing scope, GET /api/sessions?tool=,
clear-data covering the new tables, Codex child-thread events moving no
status, hooks owning status only while current, EFOREIGN for a forwarder
that is not ours, agy quiet window and turn rules, AGENTHUB_SETTINGS_FILE
honoured from .env.

Docs, OpenAPI and the CLAUDE.md marker updated. Server 2141, client 779.
This commit is contained in:
2026-09-29 16:09:19 +07:00
parent 7ec5a7cd85
commit 969b06253c
95 changed files with 9278 additions and 1696 deletions
+7 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
/**
* Claude Code hook handler.
* Claude Code (and Codex, and Antigravity) hook handler.
* Receives hook event JSON on stdin and forwards it to every live Agent
* Dashboard server. Designed to fail silently so it never blocks Claude
* Code, and to fan out across multiple dashboards that use **different**
@@ -22,6 +22,11 @@
const http = require("http");
const hookType = process.argv[2] || "unknown";
// Codex runs this through `<CODEX_HOME>/agenthub-hook.sh <Event>`, which adds
// `codex` (server/lib/codex-hooks.js), Antigravity through
// `~/.gemini/config/agenthub-hook.sh`, which adds `antigravity`
// (server/lib/antigravity-hooks.js); Claude Code passes no second argument.
const tool = ["codex", "antigravity"].includes(process.argv[3]) ? process.argv[3] : undefined;
/**
* Resolve every live dashboard server's port via the discovery file. Falls
@@ -54,6 +59,7 @@ process.stdin.on("end", () => {
const payload = JSON.stringify({
hook_type: hookType,
data: parsedData,
...(tool && { tool }),
});
const contentLength = Buffer.byteLength(payload);
+19 -18
View File
@@ -31,7 +31,8 @@ const {
} = require("../server/lib/claude-home");
const { extractFirstUserText } = require("../server/lib/transcript-cache");
const CLAUDE_DIR = getClaudeHome();
const PROJECTS_DIR = getProjectsDir();
// The projects dir is read per call, not at load: CLAUDE_HOME can change while
// the dashboard runs (Settings → Claude Code → AgentHub).
// Max session files a directory sweep scans synchronously before it yields to
// the event loop. A long synchronous scan of a large ~/.claude/projects tree —
@@ -1699,18 +1700,18 @@ function importSession(dbModule, session) {
* agents + events that are missing. Safe to run repeatedly (deduplicated).
*/
async function backfillCompactions(dbModule) {
if (!fs.existsSync(PROJECTS_DIR)) return { backfilled: 0 };
if (!fs.existsSync(getProjectsDir())) return { backfilled: 0 };
const { stmts } = dbModule;
const projectDirs = fs
.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.readdirSync(getProjectsDir(), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
let backfilled = 0;
for (const projDir of projectDirs) {
const projPath = path.join(PROJECTS_DIR, projDir);
const projPath = path.join(getProjectsDir(), projDir);
const files = fs.readdirSync(projPath).filter((f) => f.endsWith(".jsonl"));
for (const file of files) {
@@ -1782,10 +1783,10 @@ async function parseSessionForImport(projPath, sourcePath) {
* Designed to be fast on repeat runs (skips existing sessions).
*/
async function importAllSessions(dbModule) {
if (!fs.existsSync(PROJECTS_DIR)) return { imported: 0, skipped: 0, errors: 0 };
if (!fs.existsSync(getProjectsDir())) return { imported: 0, skipped: 0, errors: 0 };
const projectDirs = fs
.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.readdirSync(getProjectsDir(), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
@@ -1802,7 +1803,7 @@ async function importAllSessions(dbModule) {
});
for (const projDir of projectDirs) {
const projPath = path.join(PROJECTS_DIR, projDir);
const projPath = path.join(getProjectsDir(), projDir);
const files = fs.readdirSync(projPath).filter((f) => f.endsWith(".jsonl"));
if (files.length === 0) continue;
@@ -1884,12 +1885,12 @@ async function ingestWorkflowsForBatch(dbModule, sessions) {
async function syncDefaultProjects(dbModule, options = {}) {
const mtimeCache = options.mtimeCache instanceof Map ? options.mtimeCache : new Map();
const changed = [];
if (!fs.existsSync(PROJECTS_DIR)) return { changed };
if (!fs.existsSync(getProjectsDir())) return { changed };
let projectDirs;
try {
projectDirs = fs
.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.readdirSync(getProjectsDir(), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
} catch {
@@ -1901,7 +1902,7 @@ async function syncDefaultProjects(dbModule, options = {}) {
let scanned = 0;
for (const projDir of projectDirs) {
const projPath = path.join(PROJECTS_DIR, projDir);
const projPath = path.join(getProjectsDir(), projDir);
let files;
try {
files = fs.readdirSync(projPath).filter((f) => f.endsWith(".jsonl"));
@@ -1992,10 +1993,10 @@ async function syncDefaultProjects(dbModule, options = {}) {
async function reconcileTokens(dbModule, options = {}) {
const onProgress = typeof options.onProgress === "function" ? options.onProgress : () => {};
const counters = { reconciled: 0, sessionsTouched: 0, modelsWritten: 0, missingFiles: 0 };
if (!fs.existsSync(PROJECTS_DIR)) return counters;
if (!fs.existsSync(getProjectsDir())) return counters;
const projectDirs = fs
.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.readdirSync(getProjectsDir(), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
@@ -2003,7 +2004,7 @@ async function reconcileTokens(dbModule, options = {}) {
// already present in the DB.
const sessionPaths = new Map();
for (const projDir of projectDirs) {
const projPath = path.join(PROJECTS_DIR, projDir);
const projPath = path.join(getProjectsDir(), projDir);
let files;
try {
files = fs.readdirSync(projPath).filter((f) => f.endsWith(".jsonl"));
@@ -2105,8 +2106,8 @@ if (require.main === module) {
console.log("RECONCILE — refreshing token totals for already-imported sessions\n");
if (projectFilter) console.log(`Filtering to project: ${projectFilter}\n`);
if (!fs.existsSync(PROJECTS_DIR)) {
console.error(`Projects directory not found: ${PROJECTS_DIR}`);
if (!fs.existsSync(getProjectsDir())) {
console.error(`Projects directory not found: ${getProjectsDir()}`);
process.exit(1);
}
@@ -2166,14 +2167,14 @@ if (require.main === module) {
if (dryRun) {
const projectDirs = fs
.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.readdirSync(getProjectsDir(), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
let total = 0;
for (const projDir of projectDirs) {
if (projectFilter && !projDir.includes(projectFilter)) continue;
const projPath = path.join(PROJECTS_DIR, projDir);
const projPath = path.join(getProjectsDir(), projDir);
const files = fs.readdirSync(projPath).filter((f) => f.endsWith(".jsonl"));
if (files.length === 0) continue;
@@ -2690,7 +2691,7 @@ async function backfillSubagentTokenMetadata(dbModule) {
slug = null;
}
if (slug) {
const candidate = path.join(PROJECTS_DIR, slug, `${s.session_id}.jsonl`);
const candidate = path.join(getProjectsDir(), slug, `${s.session_id}.jsonl`);
// The file itself may be gone, but findSessionSubagents only needs the
// path to derive the sibling subagents dir — so accept the candidate as
// long as its directory exists.
+8 -8
View File
@@ -11,7 +11,7 @@ const fs = require("fs");
const path = require("path");
const { getSettingsPath } = require("../server/lib/claude-home");
const SETTINGS_PATH = getSettingsPath();
// Read per call, not at load: the dashboard's CLAUDE_HOME can change while it runs.
const HOOK_HANDLER = path.resolve(__dirname, "hook-handler.js").replace(/\\/g, "/");
/**
@@ -81,7 +81,7 @@ function containerRefusalMessage() {
` The hook command would embed this handler path:`,
` ${HOOK_HANDLER}`,
` written into:`,
` ${SETTINGS_PATH}`,
` ${getSettingsPath()}`,
"",
" Claude Code runs on the HOST. When ~/.claude is bind-mounted, a",
" container-internal handler path does not exist on the host, so every host",
@@ -155,12 +155,12 @@ function installHooks(silent = false) {
}
let settings = {};
if (fs.existsSync(SETTINGS_PATH)) {
if (fs.existsSync(getSettingsPath())) {
try {
const raw = fs.readFileSync(SETTINGS_PATH, "utf8");
const raw = fs.readFileSync(getSettingsPath(), "utf8");
settings = JSON.parse(raw);
} catch (err) {
if (!silent) console.error(`Failed to parse ${SETTINGS_PATH}:`, err.message);
if (!silent) console.error(`Failed to parse ${getSettingsPath()}:`, err.message);
return false;
}
}
@@ -185,13 +185,13 @@ function installHooks(silent = false) {
}
}
const dir = path.dirname(SETTINGS_PATH);
const dir = path.dirname(getSettingsPath());
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + "\n", "utf8");
fs.writeFileSync(getSettingsPath(), JSON.stringify(settings, null, 2) + "\n", "utf8");
if (!silent) {
console.log(`Hook handler: ${HOOK_HANDLER}`);
console.log(`Settings file: ${SETTINGS_PATH}`);
console.log(`Settings file: ${getSettingsPath()}`);
console.log(`Installed: ${installed} new, updated: ${updated} existing`);
console.log("Claude Code hooks configured. Start a new Claude Code session to begin tracking.");
}
+8
View File
@@ -12,6 +12,9 @@
* It also points `DASHBOARD_PIPELINES_DIR` at `server/__tests__/fixtures/
* pipelines/`: AgentHub ships no pipeline template any more, and the two old
* ones kept there are what the dormant stage/detection code is tested against.
* `AGENTHUB_SETTINGS_FILE` goes to the same temp dir, so a suite that saves a
* setting never writes the developer's real `~/.config/agenthub/settings.env`,
* and `AGENTHUB_PRICING_SYNC=0` keeps every suite off the network.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
@@ -32,6 +35,11 @@ const tmuxDir = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-test-tmux-"));
const env = {
...process.env,
TMUX_TMPDIR: tmuxDir,
// Never the developer's real ~/.config/agenthub/settings.env: it can pin
// DASHBOARD_DATA_DIR at their live database.
AGENTHUB_SETTINGS_FILE: path.join(tmuxDir, "settings.env"),
// No suite may fetch LiteLLM's price list (reset-pricing syncs at once).
AGENTHUB_PRICING_SYNC: "0",
DASHBOARD_PIPELINES_DIR: path.join(dir, "fixtures", "pipelines"),
};
delete env.TMUX;