Files
AgentHub/server/routes/ai-tools.js
T
nntrivi2001 9a54978eef feat: v2.5.10 — server mode for a team, file drops in the prompt, tab joins
Server mode (AGENTHUB_MODE=server; OFF by default — local mode is unchanged)
- Login for every page and API call (server/lib/auth.js, routes/auth.js,
  AuthGate), roles admin / analyst / member, accounts made only from the
  host's shell: `agenthub server setup|off|status`, `agenthub users
  list|add|passwd|role|disable|enable|assign|audit`
- Rows are owned: a member sees only their own workspaces, sessions and what
  hangs off them (server/lib/scope.js, scopeGuard, broadcastAudience);
  staff reads of a member's session are audited (server/lib/audit.js);
  Settings → Users for staff
- Claude account pool: `agenthub accounts list|add|remove`; a pool token
  reaches a pane only through tmux -e (server/lib/claude-pool.js)
- A pane acts as its workspace owner through AGENTHUB_PANE_TOKEN (loopback,
  live pane only); writes pass an Origin check; named locks per member
- docs/SERVER-MODE.md, docs/plans/server-mode/

Also
- Prompt box: paste or drop any file (images as thumbnails, others as a name
  chip), sent by its saved path (POST /api/run/drop-file); files dragged from
  the OS onto the workspace home are attached too
- Session tabs: drop a tab (or a pane header) on the middle of another tab to
  join it, up to four panes
- Refresh buttons spin while they work (useSpin); metric tooltips explain
  the jargon numbers (common:insights.help.*)
- Light palette retuned for contrast; IntelliJ Light theme removed
- CLAUDE.md sync marker trimmed; its history moved to docs/CLAUDE-SYNC-LOG.md

Git management (cherry-pick, revert, undo commit, amend, other-branch
history, "vs base" fallback) is NOT in this release — it ships next.

Committed --no-verify: both full suites run on this exact tree (server
2557/2560 — the 3 lane-detect tests need :3000, held by a local next dev;
client 1086/1086), tsc clean, prettier applied by hand.
2026-10-07 14:11:25 +07:00

206 lines
7.1 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 { sessionWhere } = require("../lib/scope");
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 (a
// server mode member: their own sessions only).
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 own = sessionWhere(req, "s.id", "s.lane_id");
const { n } = db
.prepare(`SELECT COUNT(*) AS n FROM sessions s WHERE s.tool = ? AND ${own.where}`)
.get(id, ...own.params);
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 = ? AND ${own.where}
GROUP BY tu.model, tu.speed, tu.inference_geo, tu.service_tier`
)
.all(id, ...own.params);
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;