Files
AgentHub/scripts/hook-handler.js
T
nntrivi2001 fa27b299e7 feat(server-mode): spend quota per user — no new session, prompts refused once used up
An admin sets a default spend quota on the Users page and overrides it per
user (Edit user → Spend quota: default / no limit / their own), in dollars
per local day or per sliding 5 hours. Spend is the users page's own
hourlyTokenRows + calculateCost over the sessions a user owns.

Over the quota, until it opens again:
- spawnRun refuses every start/resume/home prompt with EQUOTA (429);
- a minute sweep writes each pane's AGENTHUB_QUOTA_FILE (host: data dir,
  member: handoff dir via write-as) and hook-handler.js exits 2 on
  UserPromptSubmit from that file alone (Claude Code, Codex with trusted
  hooks) — fail-open, never asks the dashboard, never for Antigravity;
- a member's omp on the shared login loses its gateway key (clientsFor);
- panes no hook can stop (Antigravity, Cursor, Codex without trusted
  hooks, omp on its own login) are ended.

GET /api/me/quota feeds a "Quota N%" chip in the status bar.
New: server/lib/user-quota.js, user_quotas table, PUT /api/users/quota-default,
PATCH /api/users/:id {quota}, docs in SERVER-MODE.md § Spend quotas.
2026-10-28 14:31:11 +07:00

156 lines
5.9 KiB
JavaScript

#!/usr/bin/env node
/**
* 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**
* SQLite data directories (e.g. the macOS desktop app alongside `npm run dev`
* when each has its own DB). Servers sharing one database receive hooks through
* a single ingest port so events are never duplicated.
*
* Delivery is fire-and-forget: we exit as soon as the request body is on the
* wire, WITHOUT waiting for the dashboard's HTTP response. The hook only needs
* to *deliver* the event — on loopback the local server reads the buffered
* request and processes it even after this short-lived process exits. Waiting
* for the response is what made Claude Code sit at "running hooks" for seconds
* whenever a dashboard was busy, slow, or wedged.
*
* The one thing it may refuse: in server mode a pane carries
* `AGENTHUB_QUOTA_FILE` (server/lib/user-quota.js), and while that file says
* its owner is over their spend quota a Claude Code or Codex
* `UserPromptSubmit` exits 2 with the reason on stderr — both CLIs then drop
* the prompt and show why. Decided from that local file alone, never by
* asking the dashboard, and fail-open: no file, an unreadable one or an
* expired `until` lets the prompt through. Antigravity never gets a refusal.
*
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const fs = require("fs");
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
* back to the `CLAUDE_DASHBOARD_PORT` override or the conventional 4820 if
* the discovery module can't load for any reason. Never throws.
*/
function resolvePorts() {
try {
return require("../server/lib/server-info").resolveHookIngestPorts();
} catch {
const envPort = parseInt(process.env.CLAUDE_DASHBOARD_PORT || "", 10);
return [Number.isInteger(envPort) && envPort > 0 ? envPort : 4820];
}
}
const ports = resolvePorts();
/** The reason to refuse this prompt (spend quota used up), or null to let it through. */
function quotaRefusal() {
const file = process.env.AGENTHUB_QUOTA_FILE;
if (!file || hookType !== "UserPromptSubmit" || tool === "antigravity") return null;
try {
if (fs.statSync(file).size > 64 * 1024) return null;
const flag = JSON.parse(fs.readFileSync(file, "utf8"));
if (flag?.blocked !== true) return null;
const until = Date.parse(flag.until);
if (Number.isFinite(until) && until <= Date.now()) return null;
return typeof flag.message === "string" && flag.message
? flag.message
: "AgentHub: your spend quota is used up.";
} catch {
return null;
}
}
const refusal = quotaRefusal();
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => (input += chunk));
process.stdin.on("end", () => {
if (refusal) {
// The prompt never runs, so it is not reported either.
process.stderr.write(`${refusal}\n`);
process.exit(2);
}
let parsedData;
try {
parsedData = JSON.parse(input);
} catch {
parsedData = { raw: input };
}
const payload = JSON.stringify({
hook_type: hookType,
data: parsedData,
...(tool && { tool }),
// Set in every pane the dashboard starts (server/lib/pty-run.js): names
// the pane this session runs in. Absent in a user's own terminal.
...(process.env.AGENTHUB_RUN_ID && { run_id: process.env.AGENTHUB_RUN_ID }),
});
const contentLength = Buffer.byteLength(payload);
// Fan out one POST per live server. Each per-target promise resolves the
// moment the request body has been flushed — NOT when the dashboard replies
// — so a busy, slow, or wedged dashboard can't stall the hook. Each promise
// always resolves (never rejects), so one dead listener can't starve the
// others and Promise.all can't be left hanging by a single failure.
const sends = ports.map(
(port) =>
new Promise((resolve) => {
let settled = false;
const done = () => {
if (settled) return;
settled = true;
resolve();
};
const req = http.request(
{
hostname: "127.0.0.1",
port,
path: "/api/hooks/event",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": contentLength,
},
timeout: 2000,
},
// Drain any response so the socket closes cleanly if the server does
// reply before we exit. We never block on it.
(res) => res.resume()
);
req.on("error", done); // dead listener (ECONNREFUSED) — nothing to deliver
req.on("timeout", () => {
req.destroy();
done();
});
req.write(payload);
// The 'end' callback fires once the body is on the wire: delivery is
// done and the local server will process it on its own schedule.
req.end(done);
})
);
// Give the kernel one tick to hand the buffered request bytes to the local
// server before our sockets close, then exit. The hook returns in ms.
Promise.all(sends).finally(() => setImmediate(() => process.exit(0)));
});
// Safety net — guarantees the hook never blocks Claude Code even if a send
// somehow never settles. Shorter than the old 5s wait because we no longer
// block on the dashboard's response, only on the request flush.
setTimeout(() => process.exit(0), 2500);