feat: v2.5.12 — plan and quota for every AI tool, Grok Build and Kimi Code, Quit AgentHub (#65)

Usage panel (status bar):
- every account shows its plan (Claude subscriptionType, Codex
  chatgpt_plan_type, Cursor membershipType, Grok subscriptionTier)
- new quota rows: Cursor CLI (cursor.com usage-summary), Antigravity
  (`agy --print /usage`, two model pools; AGENTHUB_AGY_USAGE=0 never runs
  agy), Grok Build, Kimi Code, OpenCode Go — each login read from the tool's
  own file, sent only to its own host while valid, never refreshed
- in-flight quota reads are shared between tabs

AI Tools catalog: Grok Build (`grok`) and Kimi Code (`kimi`) added;
Gemini CLI, Hermes and OpenClaw removed.

Also: Quit AgentHub (#65, `agenthub stop`), status-area icon, Add to Chat
on an editor selection, Settings in three groups, JetBrains-style Changes
panel (ticked files/hunks, ignore, blame, file history), terminal font.

--no-verify: :3000 is taken by another dev server (lane-detect tests);
both suites run by hand — server 2636/2639 (the 3 are :3000), client
1131/1131.
This commit is contained in:
2026-10-08 12:22:14 +07:00
parent 6ef9a5d4b7
commit a9c71cd905
133 changed files with 8007 additions and 1830 deletions
+6 -1
View File
@@ -170,7 +170,12 @@ router.get("/:id/usage", (req, res) => {
SUM(tu.output_tokens + tu.baseline_output) AS output_tokens,
SUM(tu.cache_read_tokens + tu.baseline_cache_read) AS cache_read_tokens,
SUM(tu.cache_write_tokens + tu.baseline_cache_write) AS cache_write_tokens,
SUM(tu.cache_write_1h_tokens + tu.baseline_cache_write_1h) AS cache_write_1h_tokens
SUM(tu.cache_write_1h_tokens + tu.baseline_cache_write_1h) AS cache_write_1h_tokens,
SUM(tu.long_input_tokens) AS long_input_tokens,
SUM(tu.long_output_tokens) AS long_output_tokens,
SUM(tu.long_cache_read_tokens) AS long_cache_read_tokens,
SUM(tu.long_cache_write_tokens) AS long_cache_write_tokens,
SUM(tu.long_cache_write_1h_tokens) AS long_cache_write_1h_tokens
FROM token_usage tu JOIN sessions s ON s.id = tu.session_id
WHERE s.tool = ? AND ${own.where}
GROUP BY tu.model, tu.speed, tu.inference_geo, tu.service_tier`
+13 -1
View File
@@ -18,6 +18,7 @@ function broadcast(type, data) {
}
const TranscriptCache = require("../lib/transcript-cache");
const { writeHourly } = require("../lib/hourly-usage");
const { longArgs } = require("../lib/token-usage");
const { scanAndImportSubagents } = require("../../scripts/import-history");
const { evaluateEvent } = require("../lib/alerts");
const { ingestWorkflowsForSession } = require("../lib/workflow-ingest");
@@ -1036,6 +1037,17 @@ const processEventTx = db.transaction((hookType, data, tool = "claude") => {
tokens.webFetch,
tokens.codeExec
);
const long = longArgs(tokens);
if (long) {
stmts.raiseLongTokens.run(
...long,
sessionId,
tokens.model,
tokens.speed,
tokens.geo,
tokens.tier
);
}
}
writeHourly(sessionId, result.tokensByHour);
}
@@ -1602,7 +1614,7 @@ router.post("/event", (req, res) => {
// ── POST /api/hooks/ingest-batch ────────────────────────────────────────────
// Hooks from a machine this dashboard cannot reach over SSH, pushed with the
// bearer token Settings → Data → Push ingest makes (server/lib/push-token.js).
// bearer token Settings → Database → Push ingest makes (server/lib/push-token.js).
// Off — 503 — until a token exists. Body: {source, events: [{hook_type, data,
// tool?}]}; each event goes through ingestHook exactly as POST /event would,
// with its session tagged `push:<source>`. Under /hooks, so DASHBOARD_TOKEN
+39 -12
View File
@@ -57,6 +57,7 @@ const {
listTree,
listTreeAll,
readFileAt,
blameFile,
readImageAt,
} = require("../lib/git-diff");
const { runGitAction } = require("../lib/git-ops");
@@ -1010,6 +1011,29 @@ router.get("/:id/git/file", async (req, res) => {
}
});
/**
* Annotate (`?path=`): who last changed each line of the working-tree file —
* git-diff.js's `blameFile`, with the whole-file read's guards (lexical lane
* guard, 403 ESECRET, a size cap). A read like `/git/file`, so unguarded too.
*/
router.get("/:id/git/blame", async (req, res) => {
const t = await gitTargetOr404(req, res);
if (!t) return;
try {
const blame = await blameFile(t.cwd, typeof req.query.path === "string" ? req.query.path : "");
res.json({ available: true, ...blame });
} catch (err) {
if (err.code === "ESECRET") {
return res.status(403).json({ error: { code: err.code, message: err.message } });
}
if (["EBADPATH", "ENOFILE", "ETOOBIG"].includes(err.code)) {
return res.status(400).json({ error: { code: err.code, message: err.message } });
}
// Not tracked (git blame has no history for it) or not a repo.
res.json({ available: false });
}
});
/**
* One image's bytes (`?path=&rev=work|HEAD|<sha>`) for the viewer's `<img>`:
* `readImageAt`'s guards (the file read's, plus an image-extension allowlist
@@ -1145,9 +1169,10 @@ router.post("/:id/git/commit-message", sameOriginGuard, async (req, res) => {
const t = await gitTargetOr404(req, res);
if (!t) return;
try {
res.json({ message: await suggestCommitMessage(t.cwd) });
const paths = Array.isArray(req.body?.paths) ? req.body.paths : undefined;
res.json({ message: await suggestCommitMessage(t.cwd, { paths }) });
} catch (err) {
const status = ["ENOSTAGED", "ENOTOOL"].includes(err.code)
const status = ["ENOSTAGED", "ENOTOOL", "EBADPATH"].includes(err.code)
? 400
: err.code === "EAI"
? 502
@@ -1200,6 +1225,7 @@ router.post("/:id/git/:action", sameOriginGuard, async (req, res) => {
"EBADSHA",
"EMERGECOMMIT",
"ENOPARENT",
"ETRACKED",
];
// A numeric code is git's own exit status (execFile reports one that way):
// git ran and refused — a rejected push, a failed credential, a diverged
@@ -1209,16 +1235,17 @@ router.post("/:id/git/:action", sameOriginGuard, async (req, res) => {
// EHUNKGONE is the same kind of answer: the tree moved under the click.
const status = badRequest.includes(err.code)
? 400
: exited || [
"EHUNKGONE",
"EGITAUTH",
"EMERGING",
"ENOMERGE",
"ECONFLICTS",
"EPUSHED",
"EEMPTY",
"ESTALE",
].includes(err.code)
: exited ||
[
"EHUNKGONE",
"EGITAUTH",
"EMERGING",
"ENOMERGE",
"ECONFLICTS",
"EPUSHED",
"EEMPTY",
"ESTALE",
].includes(err.code)
? 409
: 500;
// git's own stderr is the useful half of a failed push or pull (a
+40 -4
View File
@@ -83,6 +83,35 @@ function ratesForBucket(rule, row, asOf) {
return { rIn, rOut, rRead, r5m, r1h };
}
const LONG_COLS = [
"input_tokens",
"output_tokens",
"cache_read_tokens",
"cache_write_tokens",
"cache_write_1h_tokens",
].map((c) => `long_${c}`);
/**
* What the long-context part of a bucket adds on top of pricing ALL of it at
* the bucket's rates: each long subset (`long_<col>`, capped at its total) at
* (factor - 1) x its rate. The input-side factor is long_input / input and
* also scales the cache rates, as fast mode's does; output has its own. A rule
* with no long rates adds nothing.
*/
function longContextExtra(rule, row, { rIn, rOut, rRead, r5m, r1h }) {
const r = rule || {};
const factor = (longRate, base) => (longRate > 0 && base > 0 ? longRate / base : 1);
const fIn = factor(r.long_input_per_mtok, r.input_per_mtok);
const fOut = factor(r.long_output_per_mtok, r.output_per_mtok);
if (fIn === 1 && fOut === 1) return 0;
const long = (col) => Math.min(row[`long_${col}`] || 0, row[col] || 0);
const l1h = long("cache_write_1h_tokens");
const l5m = Math.max(0, long("cache_write_tokens") - l1h);
const inSide =
long("input_tokens") * rIn + long("cache_read_tokens") * rRead + l5m * r5m + l1h * r1h;
return ((fIn - 1) * inSide + (fOut - 1) * long("output_tokens") * rOut) / 1e6;
}
// Calculate cost for a set of token buckets against pricing rules. Each bucket
// is (model, speed, inference_geo, service_tier) with token counts plus the 1h
// cache-write split and server-tool request counts. Cost = token cost (rate-
@@ -128,7 +157,8 @@ function calculateCost(tokenRows, pricingRules, asOf) {
unpriced.set(row.model, u);
}
const { rIn, rOut, rRead, r5m, r1h } = ratesForBucket(rule, row, asOf);
const rates = ratesForBucket(rule, row, asOf);
const { rIn, rOut, rRead, r5m, r1h } = rates;
const cw1h = row.cache_write_1h_tokens || 0;
const cw5m = Math.max(0, (row.cache_write_tokens || 0) - cw1h);
const tCost =
@@ -136,7 +166,8 @@ function calculateCost(tokenRows, pricingRules, asOf) {
(row.output_tokens / 1e6) * rOut +
(row.cache_read_tokens / 1e6) * rRead +
(cw5m / 1e6) * r5m +
(cw1h / 1e6) * r1h;
(cw1h / 1e6) * r1h +
longContextExtra(rule, row, rates);
const wsCost = ((row.web_search_requests || 0) / 1000) * WEB_SEARCH_PER_1K_SEARCHES;
const ceHours = estimateCodeExecHours(
@@ -163,6 +194,7 @@ function calculateCost(tokenRows, pricingRules, asOf) {
web_search_requests: 0,
web_fetch_requests: 0,
code_execution_requests: 0,
...Object.fromEntries(LONG_COLS.map((c) => [c, 0])),
_cost: 0,
matched_rule: rule?.model_pattern || null,
};
@@ -174,6 +206,7 @@ function calculateCost(tokenRows, pricingRules, asOf) {
agg.web_search_requests += row.web_search_requests || 0;
agg.web_fetch_requests += row.web_fetch_requests || 0;
agg.code_execution_requests += row.code_execution_requests || 0;
for (const c of LONG_COLS) agg[c] += row[c] || 0;
agg._cost += tCost + wsCost;
breakdownMap.set(key, agg);
}
@@ -221,6 +254,7 @@ function calculateDailyCosts(dailyTokenRows, pricingRules) {
web_search_requests: row.web_search_requests,
web_fetch_requests: row.web_fetch_requests,
code_execution_requests: row.code_execution_requests,
...Object.fromEntries(LONG_COLS.map((c) => [c, row[c]])),
});
rowsByDate.set(row.date, rows);
}
@@ -239,6 +273,7 @@ const USAGE_COLS = [
"web_search_requests",
"web_fetch_requests",
"code_execution_requests",
...LONG_COLS,
];
const BUCKET_COLS = ["model", "speed", "inference_geo", "service_tier"];
@@ -263,7 +298,8 @@ function dailyTokenRows(tzModifier, whereClause, params) {
tu.cache_write_1h_tokens + tu.baseline_cache_write_1h as cache_write_1h_tokens,
tu.web_search_requests + tu.baseline_web_search as web_search_requests,
tu.web_fetch_requests + tu.baseline_web_fetch as web_fetch_requests,
tu.code_execution_requests + tu.baseline_code_execution as code_execution_requests
tu.code_execution_requests + tu.baseline_code_execution as code_execution_requests,
${LONG_COLS.map((c) => `tu.${c}`).join(", ")}
FROM token_usage tu
JOIN sessions s ON s.id = tu.session_id
${whereClause}`
@@ -582,7 +618,7 @@ router.get("/cost", (req, res) => {
res.json(computeCost(scope, range, tzModifier));
});
// GET /api/pricing/quota - plan quota spent per native tool (Claude, Codex):
// GET /api/pricing/quota - plan quota spent per AI tool (server/lib/quota.js lists them):
// percentages and reset times only, `?force=1` for a Refresh click (server/lib/quota.js).
router.get("/quota", async (req, res) => {
const out = await quotas({ force: req.query.force === "1" });
+3 -1
View File
@@ -138,7 +138,9 @@ function tokensForSessions(ids) {
cache_write_1h_tokens + baseline_cache_write_1h as cache_write_1h_tokens,
web_search_requests + baseline_web_search as web_search_requests,
web_fetch_requests + baseline_web_fetch as web_fetch_requests,
code_execution_requests + baseline_code_execution as code_execution_requests
code_execution_requests + baseline_code_execution as code_execution_requests,
long_input_tokens, long_output_tokens, long_cache_read_tokens,
long_cache_write_tokens, long_cache_write_1h_tokens
FROM token_usage WHERE session_id IN (${ids.map(() => "?").join(",")})`
)
.all(...ids);
+30 -12
View File
@@ -67,18 +67,9 @@ function getHookStatus() {
}
const raw = fs.readFileSync(getSettingsPath(), "utf8");
const settings = JSON.parse(raw);
const hookTypes = [
"PreToolUse",
"PostToolUse",
"Stop",
"SubagentStop",
"Notification",
"SessionStart",
"SessionEnd",
];
// The enabled plugin runs the hooks from its own plugin.json, so
// settings.json rightly holds none of ours (installHooks removes them).
const { pluginProvidesHooks } = require("../../scripts/install-hooks");
const { HOOK_TYPES: hookTypes, pluginProvidesHooks } = require("../../scripts/install-hooks");
if (pluginProvidesHooks(settings)) {
return {
installed: true,
@@ -200,10 +191,10 @@ function clearAll() {
// not cascade and stay as orphans.
db.prepare("DELETE FROM workflows").run();
// session_snapshots survive: a snapshot is a frozen copy the user chose to
// keep, like alert rules — deleted only from Settings → Snapshots.
// keep, like alert rules — deleted only from Settings → Snapshots & reports.
// report_definitions and report_runs survive too: a definition is user
// configuration and a run's files are reports already delivered — removed
// only from Settings → Reports.
// only from Settings → Snapshots & reports.
}
// POST /api/settings/reimport — re-import legacy sessions from ~/.claude/
@@ -283,6 +274,33 @@ router.put("/autostart", sameOriginGuard, (req, res) => {
}
});
// GET/PUT /api/settings/tray — AgentHub's icon in the OS status area
// (server/lib/tray.js). On by default; a PUT starts or stops the icon process.
const tray = require("../lib/tray");
router.get("/tray", (_req, res) => res.json(tray.status()));
router.put("/tray", sameOriginGuard, (req, res) => {
if (typeof req.body?.enabled !== "boolean") {
return res
.status(400)
.json({ error: { code: "EBADVALUE", message: "`enabled` must be a boolean" } });
}
res.json(tray.setEnabled(req.body.enabled));
});
// POST /api/settings/quit — Quit AgentHub (server/lib/quit.js): kill every
// lane pane, then stop this server once the answer is out. It stays stopped
// (the bootstrap starts none) until a server starts again — `agenthub start`,
// or boot/login through an enabled autostart unit.
const quit = require("../lib/quit");
router.post("/quit", sameOriginGuard, (_req, res) => {
quit.markQuit();
const runs = require("../lib/pty-run");
let killed = 0;
for (const run of runs.listRuns()) if (runs.killRun(run.id)) killed++;
res.on("finish", () => quit.stopServer());
res.json({ ok: true, killed });
});
// POST /api/settings/reset-pricing — reset pricing to defaults. The seed is
// Claude's; a model priced by the automatic sync (an OpenAI one, from Codex
// sessions) is fetched back at once, waiting at most RESET_SYNC_MS for it.
+118 -3
View File
@@ -5,15 +5,23 @@
* `GET /` lists every account with its workspaces, sessions and $ spent in the
* last 7 and 30 days (from `token_usage_hourly`, sessions owned through their
* workspace — server/lib/scope.js); `GET /audit` the newest audit entries
* (server/lib/audit.js). Read-only: accounts are managed from the host's shell.
* (server/lib/audit.js).
*
* The Users page's account changes — `POST /` (create), `PATCH /:id` (role,
* disabled), `POST /:id/password` (reset) and `POST /:id/workspaces` (give a
* workspace) — are an admin's only (`/users` is in ADMIN_WRITE_PREFIXES), each
* needs the admin's own password again (`currentPassword`, `confirmPassword`),
* an admin never demotes or disables themselves (ESELF), every change is
* audited, and in local mode — no login to check — they all refuse.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { Router } = require("express");
const { db, stmts } = require("../db");
const { listUsers } = require("../lib/auth");
const auth = require("../lib/auth");
const { listUsers } = auth;
const { sessionWhere } = require("../lib/scope");
const { listAudit } = require("../lib/audit");
const { listAudit, recordAccountChange } = require("../lib/audit");
const router = Router();
@@ -26,6 +34,11 @@ const USAGE_COLS = [
"web_search_requests",
"web_fetch_requests",
"code_execution_requests",
"long_input_tokens",
"long_output_tokens",
"long_cache_read_tokens",
"long_cache_write_tokens",
"long_cache_write_1h_tokens",
];
/** $ and tokens a member's sessions spent since `sinceHour` (UTC `YYYY-MM-DDTHH`). */
@@ -70,4 +83,106 @@ router.get("/audit", (req, res) => {
res.json({ entries: listAudit(req.query.limit) });
});
const STATUS = {
EBADUSER: 400,
EBADPASSWORD: 400,
EBADROLE: 400,
EBADFIELD: 400,
EREAUTH: 403,
ELOCALMODE: 403,
ENOUSER: 404,
ENOLANE: 404,
EEXISTS: 409,
ESELF: 409,
ETOOMANY: 429,
};
/**
* One account change: server mode only, the admin's password confirmed, the
* change made, then audited. `fn(target)` returns the audit text.
*/
function accountChange(handler) {
return async (req, res) => {
try {
if (!auth.isServerMode() || !req.user) {
throw Object.assign(new Error("accounts are managed in server mode only"), {
code: "ELOCALMODE",
});
}
const body = req.body && typeof req.body === "object" ? req.body : {};
await auth.confirmPassword(req.user, body.currentPassword);
const out = await handler(req, body);
recordAccountChange(req.user.id, out.user.id, req.method, out.action);
res.status(out.status || 200).json({ user: out.user });
} catch (err) {
const status = STATUS[err.code];
if (!status) return res.status(500).json({ error: { message: err.message } });
res.status(status).json({ error: { code: err.code, message: err.message } });
}
};
}
/** The account `:id` names (404 ENOUSER otherwise). */
function target(req) {
const u = db.prepare("SELECT * FROM users WHERE id = ?").get(Number(req.params.id));
if (!u) throw Object.assign(new Error("no such user"), { code: "ENOUSER" });
return u;
}
router.post(
"/",
accountChange(async (_req, body) => {
const role = body.role === undefined ? "member" : body.role;
const user = await auth.createUser(body.username, body.password, role);
return { status: 201, user, action: `create ${user.username} (${user.role})` };
})
);
router.patch(
"/:id",
accountChange(async (req, body) => {
const u = target(req);
const self = u.id === req.user.id;
const done = [];
if (body.role !== undefined && body.role !== u.role) {
if (self)
throw Object.assign(new Error("you cannot change your own role"), { code: "ESELF" });
auth.setRole(u.username, body.role);
done.push(`role ${body.role}`);
}
if (body.disabled !== undefined) {
if (typeof body.disabled !== "boolean") {
throw Object.assign(new Error("disabled: true or false"), { code: "EBADFIELD" });
}
if (self && body.disabled) {
throw Object.assign(new Error("you cannot disable yourself"), { code: "ESELF" });
}
auth.setDisabled(u.username, body.disabled);
done.push(body.disabled ? "disable" : "enable");
}
return {
user: auth.publicUser(target(req)),
action: `${u.username}: ${done.join(", ") || "no change"}`,
};
})
);
router.post(
"/:id/password",
accountChange(async (req, body) => {
const u = target(req);
await auth.setPassword(u.username, body.password);
return { user: auth.publicUser(u), action: `${u.username}: password reset` };
})
);
router.post(
"/:id/workspaces",
accountChange(async (req, body) => {
const u = target(req);
auth.assignWorkspace(body.laneId, u.username);
return { user: auth.publicUser(u), action: `${u.username}: workspace ${Number(body.laneId)}` };
})
);
module.exports = router;