Files
AgentHub/server/routes/ai-tools.js
T
nntrivi2001 f887c16309 feat: model lists and prices that follow each AI tool, a Settings tab per tool, live lane status (#40)
Pricing: the LiteLLM sync now adds every current Claude / GPT (>= 5) /
Gemini (>= 3) chat model before it is used and keeps its own rows
(model_pricing.source = 'sync', the Auto badge) at the published rate. A
user's row (any PUT) and a deleted pattern (model_pricing_dismissed) are
never touched; a deleted built-in row is not re-seeded at the next start; a
reset re-applies the list at once; retired Claude models are priced only
once used.

Models: GET /api/ai-tools/:id/models reads each tool's own list (Codex's
models_cache.json, Claude's aliases named after the newest version plus
priced versions, a catalog tool's vendor rows plus the models its sessions
used). A catalog `model: {flag, vendor?}` field passes `<flag> <id>`
(validated: never a flag or shell text); a per-tool default model starts
each run, and a resume keeps the session's own model.

Settings: every installed, enabled catalog tool without its own tab gets
one (AiToolConfig.tsx): path, homepage, Update, sessions/cost/lanes,
default model, vendor pricing, and the config files its release catalog
lists, edited over the opened sha, syntax-checked, backed up, written
atomically; credential-looking names refused. Antigravity keeps its hooks
card there.

Lanes: a just-started run no longer reads "dead" (age counts the run's
start while the old session is still bound); a second dashboard on the
same database re-broadcasts the lanes the other changed (PRAGMA
data_version, every 2 s); a lane start with a bad model answers 400.

DB: every migration runs under a cross-process lock (<db>-migrate.lock), so
two dashboards started at once on a fresh database both come up.
2026-10-01 13:39:17 +07:00

201 lines
6.9 KiB
JavaScript

/**
* @file HTTP surface for the AI Tools catalog (server/lib/ai-tools.js): list
* what is known and installed, re-detect after hydrating PATH from the login
* shell, and enable/disable a tool or make it the default. Nothing here takes
* a command or an argument from the request — the catalog files are the only
* source of what a lane may run, or an install/update may execute. Also: start
* an install/update job and read it back, npm version badges, the
* server-cached icons, and each tool's model choices + default model. Writes sit behind the same-origin guard.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const express = require("express");
const aiTools = require("../lib/ai-tools");
const jobs = require("../lib/ai-tool-jobs");
const versions = require("../lib/ai-tool-versions");
const { iconFor } = require("../lib/ai-tool-icons");
const { hydrateShellPath } = require("../lib/shell-path");
const { sameOriginGuard } = require("../lib/same-origin");
const { listModels } = require("../lib/ai-tool-models");
const toolConfig = require("../lib/ai-tool-config");
const { calculateCost } = require("./pricing");
const { db, stmts } = require("../db");
const router = express.Router();
router.get("/", (_req, res) => {
res.json(aiTools.view());
});
router.post("/refresh", sameOriginGuard, async (_req, res) => {
await hydrateShellPath();
aiTools.refresh();
versions.invalidate(); // a CLI updated by hand shows its new version after Refresh
res.json(aiTools.view());
});
router.put("/:id", sameOriginGuard, (req, res) => {
const { enabled, default: makeDefault, defaultModel } = req.body || {};
// Every field checked before anything is written: a bad one saves nothing.
if (enabled !== undefined && typeof enabled !== "boolean") {
return res
.status(400)
.json({ error: { code: "EBADFIELD", message: "enabled must be a boolean" } });
}
if (defaultModel && !aiTools.validModel(defaultModel)) {
return res.status(400).json({ error: { code: "EBADMODEL", message: "not a model id" } });
}
try {
if (defaultModel !== undefined) {
// "" or null = no default (the CLI's own).
aiTools.setDefaultModel(req.params.id, defaultModel || null);
}
if (enabled !== undefined) aiTools.setEnabled(req.params.id, enabled);
if (makeDefault === true) aiTools.setDefault(req.params.id);
else if (enabled === undefined && defaultModel === undefined && !aiTools.has(req.params.id)) {
return res.status(404).json({ error: { code: "ENOTOOL", message: "unknown AI tool" } });
}
res.json(aiTools.view());
} catch (e) {
const status =
e.code === "ENOTOOL" ? 404 : e.code === "EBADDEFAULT" || e.code === "EBADMODEL" ? 400 : 500;
res.status(status).json({ error: { code: e.code || "EINTERNAL", message: e.message } });
}
});
const JOB_STATUS = {
ENOTOOL: 404,
ENOINSTALL: 400,
ENOUPDATE: 400,
ENOTHING: 400,
ENONPM: 409,
EINSTALLED: 409,
ENOTINSTALLED: 409,
ENOTNPM: 409,
EBUSY: 409,
};
async function startJob(res, fn) {
try {
res.status(202).json({ job: await fn() });
} catch (e) {
res
.status(JOB_STATUS[e.code] || 500)
.json({ error: { code: e.code || "EINTERNAL", message: e.message } });
}
}
router.post("/update-all", sameOriginGuard, (_req, res) => startJob(res, jobs.startUpdateAll));
router.post("/:id/install", sameOriginGuard, (req, res) =>
startJob(res, () => jobs.start(req.params.id, "install"))
);
router.post("/:id/update", sameOriginGuard, (req, res) =>
startJob(res, () => jobs.start(req.params.id, "update"))
);
// The model choices a run of this tool offers, from the tool's own source
// (server/lib/ai-tool-models.js), plus the default the user picked.
router.get("/:id/models", (req, res) => {
if (!aiTools.has(req.params.id)) {
return res.status(404).json({ error: { code: "ENOTOOL", message: "unknown AI tool" } });
}
res.json({
...listModels(req.params.id, db),
defaultModel: aiTools.readState().models[req.params.id] || null,
});
});
const CONFIG_STATUS = {
ENOTOOL: 404,
ENOFILE: 404,
ENOENT: 404,
ESECRET: 403,
ESTALE: 409,
ETOOBIG: 413,
EBINARY: 415,
EBADSYNTAX: 400,
EBADFIELD: 400,
};
function configRoute(fn) {
return (req, res) => {
try {
res.json(fn(req));
} catch (err) {
// An unexpected failure (EACCES, a full disk) is a JSON 500 too.
res
.status(CONFIG_STATUS[err.code] || 500)
.json({ error: { code: err.code || "EINTERNAL", message: err.message } });
}
};
}
const index = (req) => (/^\d+$/.test(req.params.index) ? Number(req.params.index) : -1);
// The tool's own config files, as its trusted catalog file lists them.
router.get(
"/:id/config",
configRoute((req) => ({ files: toolConfig.listConfig(req.params.id) }))
);
router.get(
"/:id/config/:index",
configRoute((req) => toolConfig.readConfig(req.params.id, index(req)))
);
router.put(
"/:id/config/:index",
sameOriginGuard,
configRoute((req) =>
toolConfig.writeConfig(req.params.id, index(req), req.body?.text, req.body?.baseSha)
)
);
// How much a tool has been used: its sessions and their priced tokens.
router.get("/:id/usage", (req, res) => {
if (!aiTools.has(req.params.id)) {
return res.status(404).json({ error: { code: "ENOTOOL", message: "unknown AI tool" } });
}
const id = req.params.id;
const { n } = db.prepare("SELECT COUNT(*) AS n FROM sessions WHERE tool = ?").get(id);
const rows = db
.prepare(
`SELECT tu.model AS model, tu.speed AS speed, tu.inference_geo AS inference_geo,
tu.service_tier AS service_tier,
SUM(tu.input_tokens + tu.baseline_input) AS input_tokens,
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
FROM token_usage tu JOIN sessions s ON s.id = tu.session_id
WHERE s.tool = ?
GROUP BY tu.model, tu.speed, tu.inference_geo, tu.service_tier`
)
.all(id);
res.json({ sessions: n, cost: calculateCost(rows, stmts.listPricing.all()).total_cost });
});
router.get("/job", (_req, res) => {
res.json(jobs.current());
});
router.get("/versions", async (_req, res) => {
res.json(await versions.versions());
});
router.get("/:id/icon", async (req, res) => {
if (!aiTools.has(req.params.id)) return res.status(404).end();
const icon = await iconFor(req.params.id);
// 204, not 404: a miss is a normal state, and a 404 per letter-avatar would
// log a console error for every such tool on every visit to Settings.
if (!icon) return res.status(204).end();
res.set({
"Content-Type": icon.type,
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "sandbox",
"Cache-Control": "max-age=86400",
});
res.end(icon.body);
});
module.exports = router;