feat: Claude Code Monitor — lanes, pipelines and a merged workspace

Internal SmartGift build of a Claude Code monitoring dashboard.

Lanes: a durable unit of parallel agent work, one per working directory,
tracked across session restarts. Managed lanes are git worktrees the
dashboard provisions and can reset or remove behind a three-check destroy
guard and a counted preflight; adopted lanes are directories you already
own and are never destroyable.

Pipelines: a lane moves through pipeline stages. A stage the agent declares
with evidence renders green; a stage inferred from the tool-event stream
renders dashed amber and never counts as done. Detection is forward-only
within a 30-minute window, and never writes the declared stage.

Workspace: one page at /run with a lane grid, the selected lane's pipeline,
and a full Claude console behind a disclosure.
This commit is contained in:
2026-07-29 17:07:45 +07:00
commit 57dc91585d
783 changed files with 221743 additions and 0 deletions
+185
View File
@@ -0,0 +1,185 @@
/**
* @file agent-tools.ts
* @description Defines and registers tools for managing agents in the dashboard, including listing agents with filters, retrieving agent details, creating new agents, and updating existing agents. Each tool includes input validation using Zod schemas and interacts with the dashboard API to perform the necessary operations. The tools also check for mutation permissions before allowing changes to agent data, ensuring that the application configuration is respected.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../core/tool-registry.js`
* - `../../policy/tool-guards.js`
* - `../schemas.js`
* - `../../types/tool-context.js`
*
* ## Public surface
* - `registerAgentTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerAgentTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertMutationsEnabled } from "../../policy/tool-guards.js";
import { AgentStatusSchema, JsonObjectSchema } from "../schemas.js";
import type { ToolContext } from "../../types/tool-context.js";
/**
* Registers the four agent-management tools backing `/api/agents/*`. List/
* get are unconditional reads; create/update call
* {@link assertMutationsEnabled} first. Agents mirror Claude Code's own
* main-agent/subagent model: one main agent plus zero or more subagents
* (`type: "subagent"`, optional `subagent_type`, linked via `parent_agent_id`).
*/
export function registerAgentTools(context: ToolContext): void {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
// Policy: none. Input: limit (1-500, default 50), offset (default 0),
// status/session_id (optional). Calls GET /api/agents?... — the dashboard
// honors only ONE of status/session_id per call (session_id wins,
// ignoring limit/offset), so passing both doesn't intersect-filter.
// Output: { agents, limit, offset }, each agent's own cost attached (from
// its metadata token buckets, not its session's total).
register(
"dashboard_list_agents",
"List agents with optional status/session filters and pagination.",
{
limit: z.number().int().min(1).max(500).optional(),
offset: z.number().int().min(0).max(100_000).optional(),
status: AgentStatusSchema.optional(),
session_id: z.string().min(1).max(256).optional(),
},
async (args) => {
const limit = (args.limit as number | undefined) ?? 50;
const offset = (args.offset as number | undefined) ?? 0;
return api.get("/api/agents", {
query: {
limit,
offset,
status: args.status as string | undefined,
session_id: args.session_id as string | undefined,
},
});
}
);
// Policy: none. Input: agent_id (required). Calls GET /api/agents/:id.
// Output: { agent } — 404s (ApiError, NOT_FOUND) if missing; unlike
// dashboard_list_agents, no per-agent cost is attached.
register(
"dashboard_get_agent",
"Get a single agent by ID.",
{
agent_id: z.string().min(1).max(256),
},
async (args) => {
const agentId = args.agent_id as string;
return api.get(`/api/agents/${encodeURIComponent(agentId)}`);
}
);
// Policy: MUTATIONS required. Input: id/session_id/name (required); type
// (default "main"), subagent_type, status (default "waiting"), task,
// parent_agent_id, metadata (all optional). Calls POST /api/agents.
// Output: { agent, created } — an existing id returns as-is (created: false).
register(
"dashboard_create_agent",
"Create a new agent in a session.",
{
id: z.string().min(1).max(256),
session_id: z.string().min(1).max(256),
name: z.string().min(1).max(500),
type: z.enum(["main", "subagent"]).optional(),
subagent_type: z.string().max(128).optional(),
status: AgentStatusSchema.optional(),
task: z.string().max(5000).optional(),
parent_agent_id: z.string().max(256).optional(),
metadata: JsonObjectSchema.optional(),
},
async (args) => {
assertMutationsEnabled(config);
return api.post("/api/agents", {
body: {
id: args.id,
session_id: args.session_id,
name: args.name,
type: args.type,
subagent_type: args.subagent_type,
status: args.status,
task: args.task,
parent_agent_id: args.parent_agent_id,
metadata: args.metadata,
},
});
}
);
// Policy: MUTATIONS required. Input: agent_id (required);
// name/status/task/current_tool/ended_at/metadata optional — current_tool
// is nullable (explicitly clearable) and preserved when omitted entirely.
// Calls PATCH /api/agents/:id. Output: { agent } — 404s if missing.
register(
"dashboard_update_agent",
"Update an existing agent's lifecycle state and metadata.",
{
agent_id: z.string().min(1).max(256),
name: z.string().max(500).optional(),
status: AgentStatusSchema.optional(),
task: z.string().max(5000).optional(),
current_tool: z.string().max(256).nullable().optional(),
ended_at: z.string().datetime().optional(),
metadata: JsonObjectSchema.optional(),
},
async (args) => {
assertMutationsEnabled(config);
const agentId = args.agent_id as string;
return api.patch(`/api/agents/${encodeURIComponent(agentId)}`, {
body: {
name: args.name,
status: args.status,
task: args.task,
current_tool: args.current_tool,
ended_at: args.ended_at,
metadata: args.metadata,
},
});
}
);
}
+128
View File
@@ -0,0 +1,128 @@
/**
* @file event-tools.ts
* @description Defines tools related to event management in the dashboard, including listing events with optional filters and ingesting hook events from Claude Code. The tools are registered with the tool registry and include input validation using Zod schemas. The event listing tool supports pagination and session filtering, while the hook event ingestion tool allows for adding new events into the dashboard pipeline, with a guard to ensure that mutations are enabled in the configuration.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../core/tool-registry.js`
* - `../../policy/tool-guards.js`
* - `../schemas.js`
* - `../../types/tool-context.js`
*
* ## Public surface
* - `registerEventTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerEventTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertMutationsEnabled } from "../../policy/tool-guards.js";
import { HookTypeSchema, JsonObjectSchema } from "../schemas.js";
import type { ToolContext } from "../../types/tool-context.js";
/**
* Registers the two event-related tools: a read-only list and a mutation
* that feeds the same ingestion pipeline the installed Claude Code hooks
* use (`scripts/hook-handler.js` → `POST /api/hooks/event`) — the one domain
* where a tool can inject data into the dashboard's real-time pipeline
* (websocket broadcast + alert evaluation), useful for testing hook
* behavior without a live Claude Code session.
*/
export function registerEventTools(context: ToolContext): void {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
// Policy: none. Input: limit (1-200, default 50), offset (default 0),
// session_id (optional). Calls GET /api/events?limit&offset&session_id.
// Output: paginated event rows, most recent first.
register(
"dashboard_list_events",
"List events with optional session filter and pagination.",
{
limit: z.number().int().min(1).max(200).optional(),
offset: z.number().int().min(0).max(100_000).optional(),
session_id: z.string().min(1).max(256).optional(),
},
async (args) => {
const limit = (args.limit as number | undefined) ?? 50;
const offset = (args.offset as number | undefined) ?? 0;
return api.get("/api/events", {
query: {
limit,
offset,
session_id: args.session_id as string | undefined,
},
});
}
);
// Policy: MUTATIONS required. Input: hook_type (one of the seven Claude
// Code hook names); data (arbitrary JSON — MUST include session_id, which
// the dashboard uses to target the session). Calls POST /api/hooks/event,
// the same endpoint scripts/hook-handler.js posts to on every real hook
// firing. Output: { ok: true, event }. Side effects: bumps the session's
// updated_at, broadcasts "new_event" over websocket, fire-and-forget
// evaluates alert rules (failures swallowed), and — only for
// "SubagentStop" with a transcript_path — scans that session's subagent
// JSONL files for tool calls not yet recorded as events (the only path
// that attributes subagent tool_use to the right agent_id, since those
// never fire their own hooks). Throws (ApiError, MISSING_SESSION) if data
// has no session_id.
register(
"dashboard_ingest_hook_event",
"Ingest one Claude Code hook event into the dashboard pipeline.",
{
hook_type: HookTypeSchema,
data: JsonObjectSchema,
},
async (args) => {
assertMutationsEnabled(config);
return api.post("/api/hooks/event", {
body: {
hook_type: args.hook_type,
data: args.data,
},
});
}
);
}
+157
View File
@@ -0,0 +1,157 @@
/**
* @file maintenance-tools.ts
* @description Defines a set of maintenance tools for the MCP dashboard, including functions to clean up stale sessions, re-import legacy data, reinstall hooks, and clear all data. These tools are registered with the MCP server and include appropriate guards to ensure that mutating and destructive actions are only performed when explicitly allowed in the configuration. The tools interact with the MCP server's API to perform the necessary maintenance tasks, providing a way for administrators to manage the dashboard's data and settings effectively.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../core/tool-registry.js`
* - `../../policy/tool-guards.js`
* - `../../types/tool-context.js`
*
* ## Public surface
* - `registerMaintenanceTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerMaintenanceTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertDestructiveEnabled, assertMutationsEnabled } from "../../policy/tool-guards.js";
import type { ToolContext } from "../../types/tool-context.js";
/**
* Registers four administrative tools against `/api/settings/*`. All four
* require mutations; `dashboard_clear_all_data` additionally requires the
* destructive tier plus an exact confirmation token, since it's the only
* irreversible one (cleanup only touches stale/old rows; reimport and
* reinstall-hooks are idempotent, repeatable operations).
*/
export function registerMaintenanceTools(context: ToolContext): void {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
// Policy: MUTATIONS required (checked before the "at least one field"
// validation below). Input: abandon_hours (1 to 24*365) and/or purge_days
// (1-3650) — at least one required. Calls POST /api/settings/cleanup.
// abandon_hours marks "active" sessions with no recent events as
// "abandoned" (completing lingering agents); purge_days permanently
// deletes terminal sessions (+ agents/events) older than N days. Output:
// { abandoned, purged_sessions, purged_events, purged_agents } counts.
register(
"dashboard_cleanup_data",
"Maintenance: abandon stale sessions and/or purge old completed data.",
{
abandon_hours: z
.number()
.int()
.min(1)
.max(24 * 365)
.optional(),
purge_days: z.number().int().min(1).max(3650).optional(),
},
async (args) => {
assertMutationsEnabled(config);
const abandonHours = args.abandon_hours as number | undefined;
const purgeDays = args.purge_days as number | undefined;
if (abandonHours === undefined && purgeDays === undefined) {
throw new Error("At least one field is required: abandon_hours or purge_days.");
}
return api.post("/api/settings/cleanup", {
body: {
abandon_hours: abandonHours,
purge_days: purgeDays,
},
});
}
);
// Policy: MUTATIONS required. Calls POST /api/settings/reimport, invoking
// scripts/import-history.js against ~/.claude session-history JSONL files
// — useful for backfilling sessions that predate hook installation or
// recovering after a reset. Output: { ok: true, ...result }. Throws
// (ApiError, IMPORT_FAILED) if the import script itself throws.
register(
"dashboard_reimport_history",
"Re-import legacy Claude sessions from ~/.claude into the local dashboard database.",
{},
async () => {
assertMutationsEnabled(config);
return api.post("/api/settings/reimport");
}
);
// Policy: MUTATIONS required. Calls POST /api/settings/reinstall-hooks,
// invoking scripts/install-hooks.js to (re)write the seven hook entries
// (PreToolUse/PostToolUse/Stop/SubagentStop/Notification/SessionStart/
// SessionEnd) into ~/.claude/settings.json, overwriting any existing
// config. Output: { ok, hooks } — same shape as dashboard_get_system_info.
register(
"dashboard_reinstall_hooks",
"Reinstall Claude Code hooks in ~/.claude/settings.json.",
{},
async () => {
assertMutationsEnabled(config);
return api.post("/api/settings/reinstall-hooks");
}
);
// Policy: DESTRUCTIVE required — the strictest gate in the server. Input:
// confirmation_token, must exactly equal "CLEAR_ALL_DATA". Calls
// POST /api/settings/clear-data, irreversibly deleting every row from
// sessions, agents, events, token_usage, alert_events, and
// webhook_deliveries — but preserving alert rules, webhook targets, and
// pricing rules (user configuration, not activity data). Output:
// { ok: true, cleared } with pre-deletion row counts. No undo; the only
// tool gated by MCP_DASHBOARD_ALLOW_DESTRUCTIVE.
register(
"dashboard_clear_all_data",
"Delete all tracked sessions, agents, events, and token usage. Highly destructive.",
{
confirmation_token: z.string().min(1),
},
async (args) => {
const confirmationToken = args.confirmation_token as string;
assertDestructiveEnabled(config, confirmationToken);
return api.post("/api/settings/clear-data");
}
);
}
@@ -0,0 +1,168 @@
/**
* @file observability-tools.ts
* @description Tool registration for observability-related tools in the MCP server. This module defines a set of tools that interact with the Agent Dashboard API to provide health checks, stats, analytics, system information, data export, and operational snapshots. These tools enable users to monitor and analyze the performance and usage of their agents and sessions through the dashboard. Each tool is registered with a name, description, input schema (if applicable), and an asynchronous handler function that makes API calls to retrieve the necessary data.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../types/tool-context.js`
* - `../../core/tool-registry.js`
*
* ## Public surface
* - `registerObservabilityTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerObservabilityTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import type { ToolContext } from "../../types/tool-context.js";
import { createToolRegistrar } from "../../core/tool-registry.js";
/**
* Registers the six read-only observability tools. None call
* {@link assertMutationsEnabled}/{@link assertDestructiveEnabled} — all are
* plain GETs, always available regardless of policy flags.
* `dashboard_get_operational_snapshot` is the only one fanning out to
* multiple endpoints in parallel rather than proxying a single one.
*/
export function registerObservabilityTools(context: ToolContext): void {
const { api, logger, server } = context;
const register = createToolRegistrar(server, logger);
// Calls GET /api/health. Output: dashboard liveness payload — a fast
// pre-flight check, since every other tool needs the dashboard running at
// config.dashboardBaseUrl or it fails with an ApiError network/timeout.
register(
"dashboard_health_check",
"Check health of the local Agent Dashboard API.",
{},
async () => api.get("/api/health")
);
// Calls GET /api/stats. Output: session/agent counts by status,
// events-today, and live websocket connection count.
register(
"dashboard_get_stats",
"Get dashboard overview stats including session/agent counts and websocket connections.",
{},
async () => api.get("/api/stats")
);
// Calls GET /api/analytics. Output: token totals/cost, per-tool usage
// counts, daily event/session counts, agent type distribution, and
// event-type breakdown — backs the dashboard's Analytics page.
register(
"dashboard_get_analytics",
"Get analytics summary including token totals, usage trends, and distributions.",
{},
async () => api.get("/api/analytics")
);
// Calls GET /api/settings/info. Output: SQLite path/size/counts/pragmas,
// recent ingestion load (5/15/60 min), Claude Code hook install status,
// and Node/OS process info (uptime, memory, cpu, ws connections).
register(
"dashboard_get_system_info",
"Get system info, DB stats, and hook installation status.",
{},
async () => api.get("/api/settings/info")
);
// Calls GET /api/settings/export. Output: the full dashboard dataset —
// sessions, agents, events, token_usage, pricing rules — same payload the
// UI's "Export Data" button downloads (its attachment header has no
// effect on this client).
register(
"dashboard_export_data",
"Export complete dashboard data payload (sessions, agents, events, tokens, pricing).",
{},
async () => api.get("/api/settings/export")
);
// Input: three optional per-section limits, each defaulted below. Fans
// out via Promise.all to GET /api/stats, /api/analytics, /api/events,
// /api/sessions?status=active, and /api/agents queried twice
// (status=working, status=connected — the dashboard filters one status
// per call). Output: one combined { stats, analytics, recent_events,
// active_sessions, active_agents: {working, connected}, generated_at }.
register(
"dashboard_get_operational_snapshot",
"Get a high-signal operational snapshot combining stats, analytics, active sessions, active agents, and recent events.",
{
recent_events_limit: z.number().int().min(1).max(50).optional(),
active_sessions_limit: z.number().int().min(1).max(100).optional(),
active_agents_limit: z.number().int().min(1).max(200).optional(),
},
async (args) => {
const eventsLimit = (args.recent_events_limit as number | undefined) ?? 20;
const sessionsLimit = (args.active_sessions_limit as number | undefined) ?? 25;
const agentsLimit = (args.active_agents_limit as number | undefined) ?? 100;
const [stats, analytics, recentEvents, activeSessions, workingAgents, connectedAgents] =
await Promise.all([
api.get("/api/stats"),
api.get("/api/analytics"),
api.get("/api/events", { query: { limit: eventsLimit, offset: 0 } }),
api.get("/api/sessions", {
query: { status: "active", limit: sessionsLimit, offset: 0 },
}),
api.get("/api/agents", {
query: { status: "working", limit: agentsLimit, offset: 0 },
}),
api.get("/api/agents", {
query: { status: "connected", limit: agentsLimit, offset: 0 },
}),
]);
return {
stats,
analytics,
recent_events: recentEvents,
active_sessions: activeSessions,
active_agents: {
working: workingAgents,
connected: connectedAgents,
},
generated_at: new Date().toISOString(),
};
}
);
}
+169
View File
@@ -0,0 +1,169 @@
/**
* @file pricing-tools.ts
* @description Tool registration for pricing-related functionalities in the dashboard. This includes tools for retrieving pricing rules and calculating total costs based on usage. The tools interact with the backend API to fetch the necessary data and perform calculations as needed. The file also includes input validation using Zod schemas to ensure that the tool arguments are correctly formatted before processing. These tools are essential for providing users with insights into their costs and helping them manage their usage effectively.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../core/tool-registry.js`
* - `../../policy/tool-guards.js`
* - `../../types/tool-context.js`
*
* ## Public surface
* - `registerPricingTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerPricingTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertMutationsEnabled } from "../../policy/tool-guards.js";
import type { ToolContext } from "../../types/tool-context.js";
/**
* Registers six tools covering `/api/pricing/*` plus the pricing-adjacent
* `/api/settings/reset-pricing`. Reads are always available; writes
* (upsert/delete/reset) require {@link assertMutationsEnabled}. Costs are
* priced as of the usage date (session start date), not today's rate, so
* historical costs stay correct across a promotional-rate cutover.
*/
export function registerPricingTools(context: ToolContext): void {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
// Policy: none. Calls GET /api/pricing. Output: all model_pricing rows
// (model_pattern, display_name, per-million-token rates).
register(
"dashboard_get_pricing_rules",
"List all model pricing rules used for cost calculations.",
{},
async () => api.get("/api/pricing")
);
// Policy: none. Calls GET /api/pricing/cost. Output: aggregate cost/token
// totals across all sessions plus a per-day daily_costs breakdown, each
// day priced at the rate effective on that date.
register(
"dashboard_get_total_cost",
"Get total model usage cost across all tracked sessions.",
{},
async () => api.get("/api/pricing/cost")
);
// Policy: none. Input: session_id (required). Calls
// GET /api/pricing/cost/:sessionId. Output: cost/token breakdown for that
// session, priced as of its start date.
register(
"dashboard_get_session_cost",
"Get model usage cost breakdown for one session.",
{
session_id: z.string().min(1).max(256),
},
async (args) => {
const sessionId = args.session_id as string;
return api.get(`/api/pricing/cost/${encodeURIComponent(sessionId)}`);
}
);
// Policy: MUTATIONS required. Input: model_pattern + display_name
// (required); input/output/cache_read/cache_write rates (optional,
// defaulted to 0 here). Calls PUT /api/pricing — a true `INSERT ...
// ON CONFLICT DO UPDATE` upsert (unlike sessions/agents' create-if-absent):
// an existing rule is fully overwritten. CAUTION: cache_write_1h_per_mtok/
// fast_input_per_mtok/fast_output_per_mtok aren't exposed here, so
// upserting an existing rule silently zeroes those columns. Time-limited
// intro_* rates are untouched (server only rewrites them when an intro_*
// field is sent). Output: the upserted rule.
register(
"dashboard_upsert_pricing_rule",
"Create or update a pricing rule.",
{
model_pattern: z.string().min(1).max(256),
display_name: z.string().min(1).max(256),
input_per_mtok: z.number().min(0).max(1_000_000).optional(),
output_per_mtok: z.number().min(0).max(1_000_000).optional(),
cache_read_per_mtok: z.number().min(0).max(1_000_000).optional(),
cache_write_per_mtok: z.number().min(0).max(1_000_000).optional(),
},
async (args) => {
assertMutationsEnabled(config);
return api.put("/api/pricing", {
body: {
model_pattern: args.model_pattern,
display_name: args.display_name,
input_per_mtok: args.input_per_mtok ?? 0,
output_per_mtok: args.output_per_mtok ?? 0,
cache_read_per_mtok: args.cache_read_per_mtok ?? 0,
cache_write_per_mtok: args.cache_write_per_mtok ?? 0,
},
});
}
);
// Policy: MUTATIONS required. Input: model_pattern (exact match). Calls
// DELETE /api/pricing/:model_pattern. Output: { ok: true }. Throws
// (ApiError, NOT_FOUND) if no rule matches.
register(
"dashboard_delete_pricing_rule",
"Delete one pricing rule by exact model_pattern.",
{
model_pattern: z.string().min(1).max(256),
},
async (args) => {
assertMutationsEnabled(config);
return api.delete(`/api/pricing/${encodeURIComponent(args.model_pattern as string)}`);
}
);
// Policy: MUTATIONS required. Calls POST /api/settings/reset-pricing,
// which deletes ALL rules (including custom ones) and reseeds the
// built-in defaults, then re-applies any active intro-rate promos so they
// aren't lost. Output: { ok: true, pricing: [...] } — the reseeded list.
register(
"dashboard_reset_pricing_defaults",
"Reset pricing rules to dashboard defaults.",
{},
async () => {
assertMutationsEnabled(config);
return api.post("/api/settings/reset-pricing");
}
);
}
+50
View File
@@ -0,0 +1,50 @@
/**
* @file remote-tools.ts
* @description MCP tools for Remote Data Sources — list configured SSH sources
* and trigger on-demand syncs so agents can operate remotes without the UI/CLI.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertMutationsEnabled } from "../../policy/tool-guards.js";
import type { ToolContext } from "../../types/tool-context.js";
/**
* Registers remote-source tools against `/api/remote-sources/*`.
* List is read-only; sync tools require the mutations policy gate.
*/
export function registerRemoteTools(context: ToolContext): void {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
register(
"dashboard_list_remote_sources",
"List configured Remote Data Sources (SSH machines) with status and last sync.",
{},
async () => api.get("/api/remote-sources")
);
register(
"dashboard_sync_remote_source",
"Trigger an immediate SSH pull+import for one Remote Data Source by id.",
{
source_id: z.string().min(1).describe("Remote source id (src_…)"),
},
async (args) => {
assertMutationsEnabled(config);
const id = encodeURIComponent(args.source_id as string);
return api.post(`/api/remote-sources/${id}/sync`);
}
);
register(
"dashboard_sync_all_remote_sources",
"Trigger an immediate SSH pull+import for every enabled Remote Data Source.",
{},
async () => {
assertMutationsEnabled(config);
return api.post("/api/remote-sources/sync-all");
}
);
}
+165
View File
@@ -0,0 +1,165 @@
/**
* @file session-tools.ts
* @description Defines and registers tools for managing sessions in the dashboard, including listing sessions with optional filters, retrieving session details, creating new sessions, and updating existing sessions. Each tool includes input validation using Zod schemas and interacts with the dashboard API to perform the necessary operations. The tools also check for mutation permissions before allowing changes to session data, ensuring that the application configuration is respected.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../core/tool-registry.js`
* - `../../policy/tool-guards.js`
* - `../schemas.js`
* - `../../types/tool-context.js`
*
* ## Public surface
* - `registerSessionTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerSessionTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertMutationsEnabled } from "../../policy/tool-guards.js";
import { SessionStatusSchema, JsonObjectSchema } from "../schemas.js";
import type { ToolContext } from "../../types/tool-context.js";
/**
* Registers the four session-management tools backing `/api/sessions/*`.
* List/get are read-only; create/update both call
* {@link assertMutationsEnabled} first. None are gated by the
* destructive-tools flag.
*/
export function registerSessionTools(context: ToolContext): void {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
// Policy: none. Input: limit (1-200, default 50), offset (default 0),
// status (optional; omitted means all). Calls
// GET /api/sessions?limit&offset&status. Output: { sessions, total, limit,
// offset }.
register(
"dashboard_list_sessions",
"List sessions with optional status filter and pagination.",
{
limit: z.number().int().min(1).max(200).optional(),
offset: z.number().int().min(0).max(100_000).optional(),
status: SessionStatusSchema.optional(),
},
async (args) => {
const limit = (args.limit as number | undefined) ?? 50;
const offset = (args.offset as number | undefined) ?? 0;
const status = args.status as string | undefined;
return api.get("/api/sessions", { query: { limit, offset, status } });
}
);
// Policy: none. Input: session_id (required). Calls
// GET /api/sessions/:id. Output: { session, agents, events, workflows } —
// agents carry their own cost (from agent.metadata token buckets),
// workflows are any Workflow-tool runs launched in this session. 404s
// (ApiError, NOT_FOUND) if missing.
register(
"dashboard_get_session",
"Get one session with its full agents list and event timeline.",
{
session_id: z.string().min(1).max(256),
},
async (args) => {
const sessionId = args.session_id as string;
return api.get(`/api/sessions/${encodeURIComponent(sessionId)}`);
}
);
// Policy: MUTATIONS required. Input: id (required); name/cwd/model/
// metadata (optional). Calls POST /api/sessions. Output: { session,
// created } — an existing id returns as-is (created: false), matching how
// the hook pipeline lazily creates sessions without erroring on a
// duplicate id; a new session starts as "active".
register(
"dashboard_create_session",
"Create a new session record if it does not already exist.",
{
id: z.string().min(1).max(256),
name: z.string().max(500).optional(),
cwd: z.string().max(2048).optional(),
model: z.string().max(256).optional(),
metadata: JsonObjectSchema.optional(),
},
async (args) => {
assertMutationsEnabled(config);
return api.post("/api/sessions", {
body: {
id: args.id,
name: args.name,
cwd: args.cwd,
model: args.model,
metadata: args.metadata,
},
});
}
);
// Policy: MUTATIONS required. Input: session_id (required);
// name/status/ended_at/metadata (optional; ended_at is ISO-8601). Calls
// PATCH /api/sessions/:id. Output: the updated session record.
register(
"dashboard_update_session",
"Update session metadata or lifecycle status.",
{
session_id: z.string().min(1).max(256),
name: z.string().max(500).optional(),
status: SessionStatusSchema.optional(),
ended_at: z.string().datetime().optional(),
metadata: JsonObjectSchema.optional(),
},
async (args) => {
assertMutationsEnabled(config);
const sessionId = args.session_id as string;
return api.patch(`/api/sessions/${encodeURIComponent(sessionId)}`, {
body: {
name: args.name,
status: args.status,
ended_at: args.ended_at,
metadata: args.metadata,
},
});
}
);
}