diff --git a/.env.example b/.env.example index f58878dccd7743ea6de47ae8349af5bd07d6f5da..23e8941ba92ce168dcbbacbd25c180e68d933075 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,7 @@ +# === Server Port === +# Port the Next.js server listens on (dev and production) +# PORT=3000 + # === Authentication === # Admin user seeded on first run (only if no users exist in DB) AUTH_USER=admin @@ -54,6 +58,9 @@ OPENCLAW_GATEWAY_HOST=127.0.0.1 OPENCLAW_GATEWAY_PORT=18789 # Optional: token used by server-side gateway calls OPENCLAW_GATEWAY_TOKEN= +# Tools profile used when Mission Control spawns sessions via sessions_spawn. +# OpenClaw 2026.3.2+ defaults to "messaging" if omitted. +OPENCLAW_TOOLS_PROFILE=coding # Frontend env vars (NEXT_PUBLIC_ prefix = available in browser) NEXT_PUBLIC_GATEWAY_HOST= @@ -61,6 +68,8 @@ NEXT_PUBLIC_GATEWAY_PORT=18789 NEXT_PUBLIC_GATEWAY_PROTOCOL= NEXT_PUBLIC_GATEWAY_URL= # NEXT_PUBLIC_GATEWAY_TOKEN= # Optional, set if gateway requires auth token +# Gateway client id used in websocket handshake (role=operator UI client). +NEXT_PUBLIC_GATEWAY_CLIENT_ID=openclaw-control-ui # === Data Paths (all optional, defaults to .data/ in project root) === # MISSION_CONTROL_DATA_DIR=.data diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..57100f5e8b3a9359e9545cc406f6177f2a9b6ffa --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,80 @@ +name: Docker Publish + +on: + workflow_run: + workflows: ['Quality Gate'] + branches: [main] + types: [completed] + push: + tags: + - 'v*.*.*' + workflow_dispatch: + +concurrency: + group: docker-publish-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: read + packages: write + id-token: write + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + publish: + if: > + github.event_name == 'workflow_dispatch' || + github.event_name == 'push' || + ( + github.event_name == 'workflow_run' && + github.event.workflow_run.conclusion == 'success' + ) + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GHCR + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=sha,prefix=sha- + type=ref,event=branch + type=ref,event=tag + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest,enable={{is_default_branch}} + + - name: Build and push image + uses: docker/build-push-action@v6 + with: + context: . + file: ./Dockerfile + push: true + platforms: linux/amd64,linux/arm64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + provenance: true + sbom: true diff --git a/Dockerfile b/Dockerfile index fcd789329cfaa638fd678c69b92b78e9e9a88a5b..792ef4a77bb51c4c54a7aa7331d5c07735eb8516 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,19 +3,21 @@ RUN corepack enable && corepack prepare pnpm@latest --activate WORKDIR /app FROM base AS deps +# Copy only dependency manifests first for better layer caching COPY package.json ./ -COPY . . +COPY pnpm-lock.yaml* ./ # better-sqlite3 requires native compilation tools RUN apt-get update && apt-get install -y python3 make g++ --no-install-recommends && rm -rf /var/lib/apt/lists/* RUN if [ -f pnpm-lock.yaml ]; then \ pnpm install --frozen-lockfile; \ else \ - echo "WARN: pnpm-lock.yaml not found in build context; running non-frozen install"; \ + echo "WARN: pnpm-lock.yaml not found in build context; running non-frozen install" && \ pnpm install --no-frozen-lockfile; \ fi FROM base AS build -COPY --from=deps /app ./ +COPY --from=deps /app/node_modules ./node_modules +COPY . . RUN pnpm build FROM node:20-slim AS runtime @@ -24,15 +26,15 @@ ENV NODE_ENV=production RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs COPY --from=build /app/.next/standalone ./ COPY --from=build /app/.next/static ./.next/static -# Copy public directory if it exists (may not exist in all setups) -COPY --from=build /app/public* ./public/ +# Copy schema.sql needed by migration 001_init at runtime +COPY --from=build /app/src/lib/schema.sql ./src/lib/schema.sql # Create data directory with correct ownership for SQLite RUN mkdir -p .data && chown nextjs:nodejs .data RUN apt-get update && apt-get install -y curl --no-install-recommends && rm -rf /var/lib/apt/lists/* USER nextjs -EXPOSE 3000 ENV PORT=3000 +EXPOSE 3000 ENV HOSTNAME=0.0.0.0 HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ - CMD curl -f http://localhost:3000/login || exit 1 + CMD curl -f http://localhost:${PORT:-3000}/login || exit 1 CMD ["node", "server.js"] diff --git a/README.md b/README.md index ca9cec12d376d94c5c495c0490ab8b306c65354e..abaa5c58707ff92496c6f68aea61a4e3ac73245c 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,14 @@ Inter-agent communication via the comms API. Agents can send messages to each ot ### Integrations Outbound webhooks with delivery history, configurable alert rules with cooldowns, and multi-gateway connection management. Optional 1Password CLI integration for secret management. +### Workspace Management +Workspaces (tenant instances) are created and managed through the **Super Admin** panel, accessible from the sidebar under **Admin > Super Admin**. From there, admins can: +- **Create** new client instances (slug, display name, Linux user, gateway port, plan tier) +- **Monitor** provisioning jobs and their step-by-step progress +- **Decommission** tenants with optional cleanup of state directories and Linux users + +Each workspace gets its own isolated environment with a dedicated OpenClaw gateway, state directory, and workspace root. See the [Super Admin API](#api-overview) endpoints under `/api/super/*` for programmatic access. + ### Update Checker Automatic GitHub release check notifies you when a new version is available, displayed as a banner in the dashboard. @@ -202,12 +210,14 @@ All endpoints require authentication unless noted. Full reference below. | `GET` | `/api/agents` | viewer | List agents with task stats | | `POST` | `/api/agents` | operator | Register/update agent | | `GET` | `/api/agents/[id]` | viewer | Agent details | +| `GET` | `/api/agents/[id]/attribution` | viewer | Self-scope attribution/audit/cost report (`?privileged=1` admin override) | | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json | | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) | | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication | | `POST` | `/api/agents/message` | operator | Send message to agent | | `GET` | `/api/tasks` | viewer | List tasks (filter: `?status=`, `?assigned_to=`, `?priority=`) | | `POST` | `/api/tasks` | operator | Create task | +| `GET` | `/api/tasks/queue` | operator | Poll next task for an agent (`?agent=`, optional `?max_capacity=`) | | `GET` | `/api/tasks/[id]` | viewer | Task details | | `PUT` | `/api/tasks/[id]` | operator | Update task | | `DELETE` | `/api/tasks/[id]` | admin | Delete task | @@ -217,6 +227,14 @@ All endpoints require authentication unless noted. Full reference below. +### Attribution Contract (`/api/agents/[id]/attribution`) + +- Self-scope by default: requester identity must match target agent via `x-agent-name` (or matching authenticated username). +- Admin override requires explicit `?privileged=1`. +- Query params: + - `hours`: integer window `1..720` (default `24`) + - `section`: comma-separated subset of `identity,audit,mutations,cost` (default all) +
Monitoring @@ -272,11 +290,26 @@ All endpoints require authentication unless noted. Full reference below. | `GET` | `/api/webhooks/deliveries` | admin | Delivery history | | `GET/POST/PUT/DELETE` | `/api/alerts` | admin | Alert rules | | `GET/POST/PUT/DELETE` | `/api/gateways` | admin | Gateway connections | +| `POST` | `/api/gateways/connect` | operator | Resolve websocket URL + token for selected gateway | | `GET/PUT/DELETE/POST` | `/api/integrations` | admin | Integration management | | `POST` | `/api/github` | admin | Trigger GitHub Issues sync |
+
+Super Admin (Workspace/Tenant Management) + +| Method | Path | Role | Description | +|--------|------|------|-------------| +| `GET` | `/api/super/tenants` | admin | List all tenants with latest provisioning status | +| `POST` | `/api/super/tenants` | admin | Create tenant and queue bootstrap job | +| `POST` | `/api/super/tenants/[id]/decommission` | admin | Queue tenant decommission job | +| `GET` | `/api/super/provision-jobs` | admin | List provisioning jobs (filter: `?tenant_id=`, `?status=`) | +| `POST` | `/api/super/provision-jobs` | admin | Queue additional job for existing tenant | +| `POST` | `/api/super/provision-jobs/[id]/action` | admin | Approve, reject, or cancel a provisioning job | + +
+
Direct CLI @@ -342,20 +375,24 @@ See [`.env.example`](.env.example) for the complete list. Key variables: | `AUTH_PASS` | No | Initial admin password | | `AUTH_PASS_B64` | No | Base64-encoded admin password (overrides `AUTH_PASS` if set) | | `API_KEY` | No | API key for headless access | -| `OPENCLAW_HOME` | Yes* | Path to `.openclaw` directory | +| `OPENCLAW_CONFIG_PATH` | Yes* | Absolute path to `openclaw.json` (preferred) | +| `OPENCLAW_STATE_DIR` | Yes* | OpenClaw state root (default: `~/.openclaw`) | +| `OPENCLAW_HOME` | No | Legacy alias for state dir (fallback if `OPENCLAW_STATE_DIR` unset) | | `OPENCLAW_GATEWAY_HOST` | No | Gateway host (default: `127.0.0.1`) | | `OPENCLAW_GATEWAY_PORT` | No | Gateway WebSocket port (default: `18789`) | | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token | +| `OPENCLAW_TOOLS_PROFILE` | No | Tools profile for `sessions_spawn` (recommended: `coding`) | | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) | +| `NEXT_PUBLIC_GATEWAY_CLIENT_ID` | No | Gateway UI client ID for websocket handshake (default: `openclaw-control-ui`) | | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) | | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) | | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing | | `MC_ALLOWED_HOSTS` | No | Host allowlist for production | -*Memory browser, log viewer, and gateway config require `OPENCLAW_HOME`. +*Memory browser, log viewer, and gateway config require OpenClaw config/state resolution (`OPENCLAW_CONFIG_PATH` and/or `OPENCLAW_STATE_DIR`). > **Memory Browser note:** OpenClaw does not store agent memory markdown files under -> `$OPENCLAW_HOME/memory/` — that directory does not exist by default. Agent memory lives +> `$OPENCLAW_STATE_DIR/memory/` — that directory does not exist by default. Agent memory lives > in each agent's workspace (e.g. `~/clawd-agents/{agent}/memory/`). Set > `OPENCLAW_MEMORY_DIR` to your agents root directory to make the Memory Browser show > daily logs, `MEMORY.md`, and other markdown files: @@ -363,6 +400,32 @@ See [`.env.example`](.env.example) for the complete list. Key variables: > OPENCLAW_MEMORY_DIR=/home/you/clawd-agents > ``` +### Workspace Creation Flow + +To add a new workspace/client instance in the UI: + +1. Open `Workspaces` from the left navigation. +2. Expand `Show Create Client Instance`. +3. Fill tenant/workspace fields (`slug`, `display_name`, optional ports/gateway owner). +4. Click `Create + Queue`. +5. Approve/run the generated provisioning job in the same panel. + +`Workspaces` and `Super Admin` currently point to the same provisioning control plane. + +### Projects and Ticket Prefixes + +Mission Control supports multi-project task organization per workspace: + +- Create/manage projects via Task Board → `Projects`. +- Each project has its own ticket prefix and counter. +- New tasks receive project-scoped ticket refs like `PA-001`, `PA-002`. +- Task board supports filtering by project. + +### Memory Scope Clarification + +- **Agent profile → Memory tab**: per-agent working memory stored in Mission Control DB (`working_memory`). +- **Memory Browser page**: workspace/local filesystem memory tree under `OPENCLAW_MEMORY_DIR`. + ## Deployment ```bash @@ -371,7 +434,7 @@ pnpm install --frozen-lockfile pnpm build # Run -OPENCLAW_HOME=/path/to/.openclaw pnpm start +OPENCLAW_CONFIG_PATH=/path/to/.openclaw/openclaw.json OPENCLAW_STATE_DIR=/path/to/.openclaw pnpm start ``` Network access is restricted by default in production. Set `MC_ALLOWED_HOSTS` (comma-separated) or `MC_ALLOW_ANY_HOST=1` to control access. @@ -388,6 +451,50 @@ pnpm test:e2e # Playwright E2E pnpm quality:gate # All checks ``` +## Workload Signals Contract + +`GET /api/workload` returns a workload snapshot and one recommendation: + +- `normal`: system healthy, submit freely +- `throttle`: reduce submission rate / defer non-critical work +- `shed`: submit only critical work +- `pause`: hold submissions until capacity returns + +Low-signal behavior: + +- `capacity.error_rate_5m` is clamped to `[0,1]` +- `queue.estimated_wait_confidence` is `calculated` or `unknown` +- queue breakdown maps include stable keys even when counts are zero + +Runtime-tunable thresholds: + +- `MC_WORKLOAD_QUEUE_DEPTH_NORMAL` +- `MC_WORKLOAD_QUEUE_DEPTH_THROTTLE` +- `MC_WORKLOAD_QUEUE_DEPTH_SHED` +- `MC_WORKLOAD_BUSY_RATIO_THROTTLE` +- `MC_WORKLOAD_BUSY_RATIO_SHED` +- `MC_WORKLOAD_ERROR_RATE_THROTTLE` +- `MC_WORKLOAD_ERROR_RATE_SHED` +- `MC_WORKLOAD_RECENT_WINDOW_SECONDS` + +## Agent Diagnostics Contract + +`GET /api/agents/{id}/diagnostics` is self-scoped by default. + +- Self access: + - Session user where `username === agent.name`, or + - API-key request with `x-agent-name` matching `{id}` agent name +- Cross-agent access: + - Allowed only with explicit `?privileged=1` and admin auth +- Query validation: + - `hours` must be an integer between `1` and `720` + - `section` must be a comma-separated subset of `summary,tasks,errors,activity,trends,tokens` + +Trend alerts in the `trends.alerts` response are derived from current-vs-previous window comparisons: + +- `warning`: error spikes or severe activity drop +- `info`: throughput drops or potential stall patterns + ## Roadmap See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped. diff --git a/docker-compose.yml b/docker-compose.yml index 3c8b968fcf00b45f803989aa2d57246508f07c15..7ae529a06bb7b77462e9ed513bf8acebf3de0fc6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,14 @@ services: mission-control: build: . + container_name: mission-control ports: - - "3000:3000" - env_file: .env + - "${MC_PORT:-3000}:${PORT:-3000}" + environment: + - PORT=${PORT:-3000} + env_file: + - path: .env + required: false volumes: - mc-data:/app/.data restart: unless-stopped diff --git a/next.config.js b/next.config.js index e24a9435ea80f60a745e337238bf495a7e0788b0..3ee2c7842f0b0d84a920bb092bf00f9c32fdbb12 100644 --- a/next.config.js +++ b/next.config.js @@ -2,6 +2,8 @@ const nextConfig = { output: 'standalone', turbopack: {}, + // Transpile ESM-only packages so they resolve correctly in all environments + transpilePackages: ['react-markdown', 'remark-gfm'], // Security headers async headers() { diff --git a/openapi.json b/openapi.json index e66e16320b50dba93b6613134714b1d3e7569f91..dfe02b06db70575b90dabc1c797ab72320c68615 100644 --- a/openapi.json +++ b/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "Mission Control API", - "version": "1.2.0", + "version": "1.3.0", "description": "AI Agent Orchestration Platform API" }, "servers": [ @@ -75,121 +75,122 @@ { "name": "Connections", "description": "Direct CLI tool connections" + }, + { + "name": "Projects", + "description": "Project management and task grouping" + }, + { + "name": "Mentions", + "description": "User and agent mention autocomplete" + }, + { + "name": "Quality", + "description": "Quality review gate for tasks" + }, + { + "name": "Releases", + "description": "Release and version checking" + }, + { + "name": "Docs", + "description": "API documentation" } ], "paths": { - "/api/auth/login": { - "post": { + "/api/activities": { + "get": { "tags": [ - "Auth" + "Monitoring" ], - "summary": "Login with credentials", - "operationId": "login", - "security": [], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "username", - "password" - ], - "properties": { - "username": { - "type": "string" - }, - "password": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Login successful. Sets mc-session cookie.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "user": { - "$ref": "#/components/schemas/User" - } - } - } - } - }, - "headers": { - "Set-Cookie": { - "schema": { - "type": "string" - }, - "description": "mc-session cookie" - } + "summary": "List activities", + "operationId": "listActivities", + "parameters": [ + { + "name": "type", + "in": "query", + "schema": { + "type": "string" } }, - "400": { - "$ref": "#/components/responses/BadRequest" + { + "name": "actor", + "in": "query", + "schema": { + "type": "string" + } }, - "401": { - "description": "Invalid credentials", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } + { + "name": "entity_type", + "in": "query", + "schema": { + "type": "string" } }, - "429": { - "$ref": "#/components/responses/RateLimited" - } - } - } - }, - "/api/auth/logout": { - "post": { - "tags": [ - "Auth" - ], - "summary": "Logout and clear session", - "operationId": "logout", - "responses": { - "200": { - "description": "Session cleared" + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50 + } }, - "401": { - "$ref": "#/components/responses/Unauthorized" + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "default": 0 + } } - } - } - }, - "/api/auth/me": { - "get": { - "tags": [ - "Auth" ], - "summary": "Get current user info", - "operationId": "getCurrentUser", "responses": { "200": { + "description": "Activity list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "user": { - "$ref": "#/components/schemas/User" + "activities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "entity_type": { + "type": "string" + }, + "entity_id": { + "type": "integer" + }, + "actor": { + "type": "string" + }, + "description": { + "type": "string" + }, + "metadata": { + "type": "object" + }, + "created_at": { + "type": "integer" + } + } + } + }, + "total": { + "type": "integer" } } } } - }, - "description": "Current user" + } }, "401": { "$ref": "#/components/responses/Unauthorized" @@ -197,26 +198,75 @@ } } }, - "/api/auth/users": { + "/api/agents": { "get": { "tags": [ - "Auth" + "Agents" + ], + "summary": "List agents", + "operationId": "listAgents", + "parameters": [ + { + "name": "status", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "online", + "offline", + "busy", + "idle", + "error" + ] + } + }, + { + "name": "role", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50, + "maximum": 200 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "default": 0 + } + } ], - "summary": "List users", - "operationId": "listUsers", "responses": { "200": { - "description": "User list", + "description": "Paginated agent list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "users": { + "agents": { "type": "array", "items": { - "$ref": "#/components/schemas/User" + "$ref": "#/components/schemas/Agent" } + }, + "total": { + "type": "integer" + }, + "page": { + "type": "integer" + }, + "limit": { + "type": "integer" } } } @@ -225,18 +275,15 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" } } }, "post": { "tags": [ - "Auth" + "Agents" ], - "summary": "Create user", - "operationId": "createUser", + "summary": "Create agent", + "operationId": "createAgent", "requestBody": { "required": true, "content": { @@ -244,30 +291,44 @@ "schema": { "type": "object", "required": [ - "username", - "password", + "name", "role" ], "properties": { - "username": { + "name": { "type": "string" }, - "password": { + "role": { "type": "string" }, - "display_name": { + "session_key": { "type": "string" }, - "role": { + "soul_content": { + "type": "string" + }, + "status": { "type": "string", "enum": [ - "admin", - "operator", - "viewer" - ] + "online", + "offline", + "busy", + "idle", + "error" + ], + "default": "offline" }, - "email": { + "config": { + "type": "object" + }, + "template": { "type": "string" + }, + "gateway_config": { + "type": "object" + }, + "write_to_gateway": { + "type": "boolean" } } } @@ -276,14 +337,14 @@ }, "responses": { "201": { - "description": "User created", + "description": "Agent created", "content": { "application/json": { "schema": { "type": "object", "properties": { - "user": { - "$ref": "#/components/schemas/User" + "agent": { + "$ref": "#/components/schemas/Agent" } } } @@ -300,7 +361,7 @@ "$ref": "#/components/responses/Forbidden" }, "409": { - "description": "Username already exists", + "description": "Agent name already exists", "content": { "application/json": { "schema": { @@ -308,15 +369,18 @@ } } } + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } }, "put": { "tags": [ - "Auth" + "Agents" ], - "summary": "Update user", - "operationId": "updateUser", + "summary": "Update agent by name", + "operationId": "updateAgentByName", "requestBody": { "required": true, "content": { @@ -324,27 +388,35 @@ "schema": { "type": "object", "required": [ - "id" + "name" ], "properties": { - "id": { - "type": "integer" - }, - "display_name": { + "name": { "type": "string" }, - "role": { + "status": { "type": "string", "enum": [ - "admin", - "operator", - "viewer" + "online", + "offline", + "busy", + "idle", + "error" ] }, - "email": { + "last_activity": { "type": "string" }, - "password": { + "config": { + "type": "object" + }, + "session_key": { + "type": "string" + }, + "soul_content": { + "type": "string" + }, + "role": { "type": "string" } } @@ -354,14 +426,14 @@ }, "responses": { "200": { - "description": "User updated", + "description": "Agent updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "user": { - "$ref": "#/components/schemas/User" + "success": { + "type": "boolean" } } } @@ -379,15 +451,89 @@ }, "404": { "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } - }, - "delete": { + } + }, + "/api/agents/comms": { + "get": { "tags": [ - "Auth" + "Agents" ], - "summary": "Delete user", - "operationId": "deleteUser", + "summary": "Get agent communications", + "operationId": "getAgentComms", + "parameters": [ + { + "name": "agent", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50 + } + } + ], + "responses": { + "200": { + "description": "Agent communication log", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "from_agent": { + "type": "string" + }, + "to_agent": { + "type": "string" + }, + "content": { + "type": "string" + }, + "type": { + "type": "string" + }, + "created_at": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + } + } + } + }, + "/api/agents/message": { + "post": { + "tags": [ + "Agents" + ], + "summary": "Send message between agents", + "operationId": "sendAgentMessage", "requestBody": { "required": true, "content": { @@ -395,27 +541,82 @@ "schema": { "type": "object", "required": [ - "id" + "from", + "to", + "content" ], "properties": { - "id": { - "type": "integer" + "from": { + "type": "string" + }, + "to": { + "type": "string" + }, + "content": { + "type": "string" + }, + "type": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Message sent", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "id": { + "type": "integer" + } } } } } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } - }, + } + } + }, + "/api/agents/sync": { + "post": { + "tags": [ + "Agents" + ], + "summary": "Sync agents from gateway config", + "operationId": "syncAgents", "responses": { "200": { - "description": "User deleted", + "description": "Sync results", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "synced": { + "type": "integer" + }, + "created": { + "type": "integer" + }, + "updated": { + "type": "integer" } } } @@ -427,58 +628,37 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/auth/access-requests": { + "/api/agents/{id}": { "get": { "tags": [ - "Auth" + "Agents" + ], + "summary": "Get agent by ID", + "operationId": "getAgent", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], - "summary": "List access requests", - "operationId": "listAccessRequests", "responses": { "200": { - "description": "Access request list", + "description": "Agent details", "content": { "application/json": { "schema": { "type": "object", "properties": { - "requests": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "username": { - "type": "string" - }, - "email": { - "type": "string" - }, - "reason": { - "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "pending", - "approved", - "rejected" - ] - }, - "created_at": { - "type": "integer" - } - } - } + "agent": { + "$ref": "#/components/schemas/Agent" } } } @@ -488,45 +668,51 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, - "403": { - "$ref": "#/components/responses/Forbidden" + "404": { + "$ref": "#/components/responses/NotFound" } } }, - "post": { + "put": { "tags": [ - "Auth" + "Agents" + ], + "summary": "Update agent by ID", + "operationId": "updateAgent", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], - "summary": "Approve or reject access request", - "operationId": "handleAccessRequest", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "id", - "action" - ], "properties": { - "id": { - "type": "integer" - }, - "action": { - "type": "string", - "enum": [ - "approve", - "reject" - ] + "name": { + "type": "string" }, "role": { - "type": "string", - "enum": [ - "admin", - "operator", - "viewer" - ] + "type": "string" + }, + "status": { + "type": "string" + }, + "config": { + "type": "object" + }, + "session_key": { + "type": "string" + }, + "soul_content": { + "type": "string" } } } @@ -535,135 +721,117 @@ }, "responses": { "200": { - "description": "Request processed", + "description": "Agent updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "agent": { + "$ref": "#/components/schemas/Agent" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } - } - }, - "/api/auth/google": { - "get": { + }, + "delete": { "tags": [ - "Auth" + "Agents" ], - "summary": "Google OAuth callback", - "operationId": "googleOAuthCallback", - "security": [], + "summary": "Delete agent", + "operationId": "deleteAgent", "parameters": [ { - "name": "code", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "state", - "in": "query", + "name": "id", + "in": "path", + "required": true, "schema": { - "type": "string" + "type": "integer" } } ], "responses": { - "302": { - "description": "Redirects to dashboard after successful auth" + "200": { + "description": "Agent deleted", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + } + } + } + } + } }, - "400": { - "$ref": "#/components/responses/BadRequest" + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/agents": { + "/api/agents/{id}/heartbeat": { "get": { "tags": [ "Agents" ], - "summary": "List agents", - "operationId": "listAgents", + "summary": "Check agent work items", + "operationId": "getAgentHeartbeat", "parameters": [ { - "name": "status", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "online", - "offline", - "busy", - "idle", - "error" - ] - } - }, - { - "name": "role", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "default": 50, - "maximum": 200 - } - }, - { - "name": "offset", - "in": "query", + "name": "id", + "in": "path", + "required": true, "schema": { - "type": "integer", - "default": 0 + "type": "integer" } } ], "responses": { "200": { - "description": "Paginated agent list", + "description": "Heartbeat data with pending work items", "content": { "application/json": { "schema": { "type": "object", "properties": { - "agents": { + "agent": { + "type": "string" + }, + "pending_tasks": { "type": "array", "items": { - "$ref": "#/components/schemas/Agent" + "$ref": "#/components/schemas/Task" } }, - "total": { - "type": "integer" - }, - "page": { - "type": "integer" - }, - "limit": { - "type": "integer" + "messages": { + "type": "array", + "items": { + "type": "object" + } } } } @@ -672,6 +840,9 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } }, @@ -679,96 +850,76 @@ "tags": [ "Agents" ], - "summary": "Create agent", - "operationId": "createAgent", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "name", - "role" - ], - "properties": { - "name": { - "type": "string" - }, - "role": { - "type": "string" - }, - "session_key": { - "type": "string" - }, - "soul_content": { - "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "online", - "offline", - "busy", - "idle", - "error" - ], - "default": "offline" - }, - "config": { - "type": "object" - }, - "template": { - "type": "string" - }, - "gateway_config": { - "type": "object" - }, - "write_to_gateway": { - "type": "boolean" - } - } - } + "summary": "Trigger manual heartbeat", + "operationId": "triggerAgentHeartbeat", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" } } - }, + ], "responses": { - "201": { - "description": "Agent created", + "200": { + "description": "Heartbeat triggered", "content": { "application/json": { "schema": { "type": "object", "properties": { - "agent": { - "$ref": "#/components/schemas/Agent" + "success": { + "type": "boolean" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "409": { - "description": "Agent name already exists", + "404": { + "$ref": "#/components/responses/NotFound" + } + } + } + }, + "/api/agents/{id}/memory": { + "get": { + "tags": [ + "Agents" + ], + "summary": "Get agent memory", + "operationId": "getAgentMemory", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Agent memory data", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Error" + "type": "object" } } } }, - "429": { - "$ref": "#/components/responses/RateLimited" + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } }, @@ -776,54 +927,31 @@ "tags": [ "Agents" ], - "summary": "Update agent by name", - "operationId": "updateAgentByName", + "summary": "Update agent memory", + "operationId": "updateAgentMemory", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "online", - "offline", - "busy", - "idle", - "error" - ] - }, - "last_activity": { - "type": "string" - }, - "config": { - "type": "object" - }, - "session_key": { - "type": "string" - }, - "soul_content": { - "type": "string" - }, - "role": { - "type": "string" - } - } + "type": "object" } } } }, "responses": { "200": { - "description": "Agent updated", + "description": "Memory updated", "content": { "application/json": { "schema": { @@ -837,9 +965,6 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -848,20 +973,17 @@ }, "404": { "$ref": "#/components/responses/NotFound" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } } }, - "/api/agents/{id}": { + "/api/agents/{id}/soul": { "get": { "tags": [ "Agents" ], - "summary": "Get agent by ID", - "operationId": "getAgent", + "summary": "Get agent soul config", + "operationId": "getAgentSoul", "parameters": [ { "name": "id", @@ -874,14 +996,14 @@ ], "responses": { "200": { - "description": "Agent details", + "description": "Soul configuration", "content": { "application/json": { "schema": { "type": "object", "properties": { - "agent": { - "$ref": "#/components/schemas/Agent" + "soul_content": { + "type": "string" } } } @@ -900,8 +1022,8 @@ "tags": [ "Agents" ], - "summary": "Update agent by ID", - "operationId": "updateAgent", + "summary": "Update agent soul config", + "operationId": "updateAgentSoul", "parameters": [ { "name": "id", @@ -918,22 +1040,10 @@ "application/json": { "schema": { "type": "object", + "required": [ + "soul_content" + ], "properties": { - "name": { - "type": "string" - }, - "role": { - "type": "string" - }, - "status": { - "type": "string" - }, - "config": { - "type": "object" - }, - "session_key": { - "type": "string" - }, "soul_content": { "type": "string" } @@ -944,14 +1054,14 @@ }, "responses": { "200": { - "description": "Agent updated", + "description": "Soul updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "agent": { - "$ref": "#/components/schemas/Agent" + "success": { + "type": "boolean" } } } @@ -966,18 +1076,17 @@ }, "404": { "$ref": "#/components/responses/NotFound" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } - }, - "delete": { + } + }, + "/api/agents/{id}/wake": { + "post": { "tags": [ "Agents" ], - "summary": "Delete agent", - "operationId": "deleteAgent", + "summary": "Wake an agent", + "operationId": "wakeAgent", "parameters": [ { "name": "id", @@ -987,10 +1096,24 @@ "type": "integer" } } - ], + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reason": { + "type": "string" + } + } + } + } + } + }, "responses": { "200": { - "description": "Agent deleted", + "description": "Agent woken", "content": { "application/json": { "schema": { @@ -1016,44 +1139,25 @@ } } }, - "/api/agents/{id}/heartbeat": { + "/api/alerts": { "get": { "tags": [ - "Agents" - ], - "summary": "Check agent work items", - "operationId": "getAgentHeartbeat", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } - } + "Alerts" ], + "summary": "List alert rules", + "operationId": "listAlertRules", "responses": { "200": { - "description": "Heartbeat data with pending work items", + "description": "Alert rule list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "agent": { - "type": "string" - }, - "pending_tasks": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Task" - } - }, - "messages": { + "rules": { "type": "array", "items": { - "type": "object" + "$ref": "#/components/schemas/AlertRule" } } } @@ -1063,110 +1167,258 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } }, "post": { "tags": [ - "Agents" + "Alerts" ], - "summary": "Trigger manual heartbeat", - "operationId": "triggerAgentHeartbeat", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" + "summary": "Create alert rule or evaluate rules", + "operationId": "createAlertRule", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "object", + "title": "CreateRule", + "required": [ + "name", + "entity_type", + "condition_field", + "condition_operator", + "condition_value" + ], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "entity_type": { + "type": "string", + "enum": [ + "agent", + "task", + "session", + "activity" + ] + }, + "condition_field": { + "type": "string" + }, + "condition_operator": { + "type": "string", + "enum": [ + "equals", + "not_equals", + "greater_than", + "less_than", + "contains", + "count_above", + "count_below", + "age_minutes_above" + ] + }, + "condition_value": { + "type": "string" + }, + "action_type": { + "type": "string", + "default": "notification" + }, + "action_config": { + "type": "object" + }, + "cooldown_minutes": { + "type": "integer", + "default": 60 + } + } + }, + { + "type": "object", + "title": "EvaluateRules", + "required": [ + "action" + ], + "properties": { + "action": { + "type": "string", + "const": "evaluate" + } + } + } + ] + } } } - ], + }, "responses": { + "201": { + "description": "Rule created", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rule": { + "$ref": "#/components/schemas/AlertRule" + } + } + } + } + } + }, "200": { - "description": "Heartbeat triggered", + "description": "Rules evaluated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "evaluated": { + "type": "integer" + }, + "triggered": { + "type": "integer" + }, + "results": { + "type": "array", + "items": { + "type": "object", + "properties": { + "rule_id": { + "type": "integer" + }, + "rule_name": { + "type": "string" + }, + "triggered": { + "type": "boolean" + }, + "reason": { + "type": "string" + } + } + } } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, - "404": { - "$ref": "#/components/responses/NotFound" + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } - } - }, - "/api/agents/{id}/soul": { - "get": { + }, + "put": { "tags": [ - "Agents" + "Alerts" ], - "summary": "Get agent soul config", - "operationId": "getAgentSoul", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" + "summary": "Update alert rule", + "operationId": "updateAlertRule", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "entity_type": { + "type": "string" + }, + "condition_field": { + "type": "string" + }, + "condition_operator": { + "type": "string" + }, + "condition_value": { + "type": "string" + }, + "action_type": { + "type": "string" + }, + "action_config": { + "type": "object" + }, + "cooldown_minutes": { + "type": "integer" + } + } + } } } - ], + }, "responses": { "200": { - "description": "Soul configuration", + "description": "Rule updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "soul_content": { - "type": "string" + "rule": { + "$ref": "#/components/schemas/AlertRule" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, "404": { "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } }, - "put": { + "delete": { "tags": [ - "Agents" - ], - "summary": "Update agent soul config", - "operationId": "updateAgentSoul", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } - } + "Alerts" ], + "summary": "Delete alert rule", + "operationId": "deleteAlertRule", "requestBody": { "required": true, "content": { @@ -1174,11 +1426,11 @@ "schema": { "type": "object", "required": [ - "soul_content" + "id" ], "properties": { - "soul_content": { - "type": "string" + "id": { + "type": "integer" } } } @@ -1187,13 +1439,13 @@ }, "responses": { "200": { - "description": "Soul updated", + "description": "Rule deleted", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { + "deleted": { "type": "boolean" } } @@ -1201,90 +1453,102 @@ } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" }, - "404": { - "$ref": "#/components/responses/NotFound" + "429": { + "$ref": "#/components/responses/RateLimited" } } } }, - "/api/agents/{id}/memory": { + "/api/audit": { "get": { "tags": [ - "Agents" + "Monitoring" ], - "summary": "Get agent memory", - "operationId": "getAgentMemory", + "summary": "Get audit log", + "operationId": "getAuditLog", "parameters": [ { - "name": "id", - "in": "path", - "required": true, + "name": "action", + "in": "query", "schema": { - "type": "integer" + "type": "string" } - } - ], - "responses": { - "200": { - "description": "Agent memory data", - "content": { - "application/json": { - "schema": { - "type": "object" - } - } + }, + { + "name": "actor", + "in": "query", + "schema": { + "type": "string" } }, - "401": { - "$ref": "#/components/responses/Unauthorized" + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 100 + } }, - "404": { - "$ref": "#/components/responses/NotFound" - } - } - }, - "put": { - "tags": [ - "Agents" - ], - "summary": "Update agent memory", - "operationId": "updateAgentMemory", - "parameters": [ { - "name": "id", - "in": "path", - "required": true, + "name": "offset", + "in": "query", "schema": { - "type": "integer" + "type": "integer", + "default": 0 } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - }, "responses": { "200": { - "description": "Memory updated", + "description": "Audit log entries", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "entries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "action": { + "type": "string" + }, + "actor": { + "type": "string" + }, + "target_type": { + "type": "string" + }, + "target_id": { + "type": "integer" + }, + "detail": { + "type": "object" + }, + "ip_address": { + "type": "string" + }, + "created_at": { + "type": "integer" + } + } + } + }, + "total": { + "type": "integer" } } } @@ -1296,54 +1560,55 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/agents/{id}/wake": { - "post": { + "/api/auth/access-requests": { + "get": { "tags": [ - "Agents" - ], - "summary": "Wake an agent", - "operationId": "wakeAgent", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } - } + "Auth" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "reason": { - "type": "string" - } - } - } - } - } - }, + "summary": "List access requests", + "operationId": "listAccessRequests", "responses": { "200": { - "description": "Agent woken", + "description": "Access request list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "requests": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "username": { + "type": "string" + }, + "email": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "pending", + "approved", + "rejected" + ] + }, + "created_at": { + "type": "integer" + } + } + } } } } @@ -1355,20 +1620,15 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } - } - }, - "/api/agents/message": { + }, "post": { "tags": [ - "Agents" + "Auth" ], - "summary": "Send message between agents", - "operationId": "sendAgentMessage", + "summary": "Approve or reject access request", + "operationId": "handleAccessRequest", "requestBody": { "required": true, "content": { @@ -1376,22 +1636,27 @@ "schema": { "type": "object", "required": [ - "from", - "to", - "content" + "id", + "action" ], "properties": { - "from": { - "type": "string" - }, - "to": { - "type": "string" + "id": { + "type": "integer" }, - "content": { - "type": "string" + "action": { + "type": "string", + "enum": [ + "approve", + "reject" + ] }, - "type": { - "type": "string" + "role": { + "type": "string", + "enum": [ + "admin", + "operator", + "viewer" + ] } } } @@ -1400,7 +1665,7 @@ }, "responses": { "200": { - "description": "Message sent", + "description": "Request processed", "content": { "application/json": { "schema": { @@ -1408,9 +1673,6 @@ "properties": { "success": { "type": "boolean" - }, - "id": { - "type": "integer" } } } @@ -1429,195 +1691,179 @@ } } }, - "/api/agents/comms": { + "/api/auth/google": { "get": { "tags": [ - "Agents" + "Auth" ], - "summary": "Get agent communications", - "operationId": "getAgentComms", + "summary": "Google OAuth callback", + "operationId": "googleOAuthCallback", + "security": [], "parameters": [ { - "name": "agent", + "name": "code", "in": "query", "schema": { "type": "string" } }, { - "name": "limit", + "name": "state", "in": "query", "schema": { - "type": "integer", - "default": 50 + "type": "string" } } ], + "responses": { + "302": { + "description": "Redirects to dashboard after successful auth" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + } + } + } + }, + "/api/auth/login": { + "post": { + "tags": [ + "Auth" + ], + "summary": "Login with credentials", + "operationId": "login", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "username", + "password" + ], + "properties": { + "username": { + "type": "string" + }, + "password": { + "type": "string" + } + } + } + } + } + }, "responses": { "200": { - "description": "Agent communication log", + "description": "Login successful. Sets mc-session cookie.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "messages": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "from_agent": { - "type": "string" - }, - "to_agent": { - "type": "string" - }, - "content": { - "type": "string" - }, - "type": { - "type": "string" - }, - "created_at": { - "type": "integer" - } - } - } + "user": { + "$ref": "#/components/schemas/User" } } } } + }, + "headers": { + "Set-Cookie": { + "schema": { + "type": "string" + }, + "description": "mc-session cookie" + } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { - "$ref": "#/components/responses/Unauthorized" + "description": "Invalid credentials", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } } }, - "/api/agents/sync": { + "/api/auth/logout": { "post": { "tags": [ - "Agents" + "Auth" ], - "summary": "Sync agents from gateway config", - "operationId": "syncAgents", + "summary": "Logout and clear session", + "operationId": "logout", + "responses": { + "200": { + "description": "Session cleared" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + } + } + } + }, + "/api/auth/me": { + "get": { + "tags": [ + "Auth" + ], + "summary": "Get current user info", + "operationId": "getCurrentUser", "responses": { "200": { - "description": "Sync results", "content": { "application/json": { "schema": { "type": "object", "properties": { - "synced": { - "type": "integer" - }, - "created": { - "type": "integer" - }, - "updated": { - "type": "integer" + "user": { + "$ref": "#/components/schemas/User" } } } } - } + }, + "description": "Current user" }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" } } } }, - "/api/tasks": { + "/api/auth/users": { "get": { "tags": [ - "Tasks" - ], - "summary": "List tasks", - "operationId": "listTasks", - "parameters": [ - { - "name": "status", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "inbox", - "assigned", - "in_progress", - "quality_review", - "done" - ] - } - }, - { - "name": "assigned_to", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "priority", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "critical", - "high", - "medium", - "low" - ] - } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "default": 50, - "maximum": 200 - } - }, - { - "name": "offset", - "in": "query", - "schema": { - "type": "integer", - "default": 0 - } - } + "Auth" ], + "summary": "List users", + "operationId": "listUsers", "responses": { "200": { - "description": "Paginated task list", + "description": "User list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "tasks": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Task" - } - }, - "total": { - "type": "integer" - }, - "page": { - "type": "integer" - }, - "limit": { - "type": "integer" + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/User" + } } } } @@ -1626,15 +1872,18 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } } }, "post": { "tags": [ - "Tasks" + "Auth" ], - "summary": "Create task", - "operationId": "createTask", + "summary": "Create user", + "operationId": "createUser", "requestBody": { "required": true, "content": { @@ -1642,56 +1891,30 @@ "schema": { "type": "object", "required": [ - "title" + "username", + "password", + "role" ], "properties": { - "title": { + "username": { "type": "string" }, - "description": { + "password": { "type": "string" }, - "status": { - "type": "string", - "enum": [ - "inbox", - "assigned", - "in_progress", - "quality_review", - "done" - ], - "default": "inbox" + "display_name": { + "type": "string" }, - "priority": { + "role": { "type": "string", "enum": [ - "critical", - "high", - "medium", - "low" - ], - "default": "medium" - }, - "assigned_to": { - "type": "string" - }, - "created_by": { - "type": "string" + "admin", + "operator", + "viewer" + ] }, - "due_date": { + "email": { "type": "string" - }, - "estimated_hours": { - "type": "number" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "metadata": { - "type": "object" } } } @@ -1700,14 +1923,14 @@ }, "responses": { "201": { - "description": "Task created", + "description": "User created", "content": { "application/json": { "schema": { "type": "object", "properties": { - "task": { - "$ref": "#/components/schemas/Task" + "user": { + "$ref": "#/components/schemas/User" } } } @@ -1724,7 +1947,7 @@ "$ref": "#/components/responses/Forbidden" }, "409": { - "description": "Task title already exists", + "description": "Username already exists", "content": { "application/json": { "schema": { @@ -1732,18 +1955,15 @@ } } } - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } }, "put": { "tags": [ - "Tasks" + "Auth" ], - "summary": "Bulk update task statuses", - "operationId": "bulkUpdateTasks", + "summary": "Update user", + "operationId": "updateUser", "requestBody": { "required": true, "content": { @@ -1751,42 +1971,126 @@ "schema": { "type": "object", "required": [ - "tasks" + "id" ], "properties": { - "tasks": { - "type": "array", - "items": { - "type": "object", - "required": [ - "id", - "status" - ], - "properties": { - "id": { - "type": "integer" - }, - "status": { - "type": "string", - "enum": [ - "inbox", - "assigned", - "in_progress", - "quality_review", - "done" - ] - } - } + "id": { + "type": "integer" + }, + "display_name": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ + "admin", + "operator", + "viewer" + ] + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "User updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "user": { + "$ref": "#/components/schemas/User" } } } } } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + } + } + }, + "delete": { + "tags": [ + "Auth" + ], + "summary": "Delete user", + "operationId": "deleteUser", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer" + } + } + } + } } }, "responses": { "200": { - "description": "Tasks updated", + "description": "User deleted", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + } + } + } + }, + "/api/backup": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Trigger backup", + "operationId": "triggerBackup", + "responses": { + "200": { + "description": "Backup completed", "content": { "application/json": { "schema": { @@ -1795,7 +2099,10 @@ "success": { "type": "boolean" }, - "updated": { + "path": { + "type": "string" + }, + "size_bytes": { "type": "integer" } } @@ -1803,48 +2110,126 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "429": { - "$ref": "#/components/responses/RateLimited" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + } + } + } + }, + "/api/chat/conversations": { + "get": { + "tags": [ + "Chat" + ], + "summary": "List conversations", + "operationId": "listConversations", + "responses": { + "200": { + "description": "Conversation list", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "conversations": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + }, + "last_message": { + "type": "string" + }, + "updated_at": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" } } } }, - "/api/tasks/{id}": { + "/api/chat/messages": { "get": { "tags": [ - "Tasks" + "Chat" ], - "summary": "Get task by ID", - "operationId": "getTask", + "summary": "List messages", + "operationId": "listMessages", "parameters": [ { - "name": "id", - "in": "path", - "required": true, + "name": "conversation_id", + "in": "query", "schema": { "type": "integer" } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "default": 0 + } } ], "responses": { "200": { - "description": "Task details", + "description": "Message list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "task": { - "$ref": "#/components/schemas/Task" + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "conversation_id": { + "type": "integer" + }, + "sender": { + "type": "string" + }, + "content": { + "type": "string" + }, + "created_at": { + "type": "integer" + } + } + } } } } @@ -1853,64 +2238,33 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } }, - "put": { + "post": { "tags": [ - "Tasks" - ], - "summary": "Update task", - "operationId": "updateTask", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } - } + "Chat" ], + "summary": "Send message", + "operationId": "sendMessage", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", + "required": [ + "content" + ], "properties": { - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "status": { - "type": "string" - }, - "priority": { - "type": "string" + "conversation_id": { + "type": "integer" }, - "assigned_to": { + "content": { "type": "string" }, - "due_date": { + "recipient": { "type": "string" - }, - "estimated_hours": { - "type": "number" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "metadata": { - "type": "object" } } } @@ -1918,41 +2272,40 @@ } }, "responses": { - "200": { - "description": "Task updated", + "201": { + "description": "Message sent", "content": { "application/json": { "schema": { "type": "object", "properties": { - "task": { - "$ref": "#/components/schemas/Task" + "message": { + "type": "object" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } - }, - "delete": { + } + }, + "/api/chat/messages/{id}": { + "get": { "tags": [ - "Tasks" + "Chat" ], - "summary": "Delete task", - "operationId": "deleteTask", + "summary": "Get message by ID", + "operationId": "getMessage", "parameters": [ { "name": "id", @@ -1965,16 +2318,11 @@ ], "responses": { "200": { - "description": "Task deleted", + "description": "Message details", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - } - } + "type": "object" } } } @@ -1982,22 +2330,17 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, "404": { "$ref": "#/components/responses/NotFound" } } - } - }, - "/api/tasks/{id}/comments": { - "get": { + }, + "delete": { "tags": [ - "Tasks" + "Chat" ], - "summary": "List task comments", - "operationId": "listTaskComments", + "summary": "Delete message", + "operationId": "deleteMessage", "parameters": [ { "name": "id", @@ -2010,34 +2353,14 @@ ], "responses": { "200": { - "description": "Comment list", + "description": "Message deleted", "content": { "application/json": { "schema": { "type": "object", "properties": { - "comments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "task_id": { - "type": "integer" - }, - "author": { - "type": "string" - }, - "content": { - "type": "string" - }, - "created_at": { - "type": "integer" - } - } - } + "success": { + "type": "boolean" } } } @@ -2047,42 +2370,78 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, "404": { "$ref": "#/components/responses/NotFound" } } - }, + } + }, + "/api/claude/sessions": { + "get": { + "tags": [ + "Sessions" + ], + "summary": "List Claude CLI sessions", + "operationId": "listClaudeSessions", + "responses": { + "200": { + "description": "Session list" + } + } + }, + "post": { + "tags": [ + "Sessions" + ], + "summary": "Register a Claude CLI session", + "operationId": "registerClaudeSession", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "session_id": { + "type": "string" + }, + "agent_name": { + "type": "string" + }, + "model": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Session registered" + } + } + } + }, + "/api/cleanup": { "post": { "tags": [ - "Tasks" - ], - "summary": "Add comment to task", - "operationId": "addTaskComment", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } - } + "Admin" ], + "summary": "Trigger cleanup of old data", + "operationId": "triggerCleanup", "requestBody": { - "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "content" - ], "properties": { - "content": { - "type": "string" - }, - "author": { - "type": "string" + "older_than_days": { + "type": "integer", + "default": 30 } } } @@ -2090,14 +2449,17 @@ } }, "responses": { - "201": { - "description": "Comment added", + "200": { + "description": "Cleanup results", "content": { "application/json": { "schema": { "type": "object", "properties": { - "comment": { + "success": { + "type": "boolean" + }, + "deleted": { "type": "object" } } @@ -2105,52 +2467,48 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/tasks/{id}/broadcast": { + "/api/connect": { "post": { "tags": [ - "Tasks" - ], - "summary": "Broadcast task to agents", - "operationId": "broadcastTask", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } - } + "Connections" ], + "summary": "Register a direct CLI connection", + "description": "Registers a CLI tool directly without a gateway. Auto-creates agent if name doesn't exist.", + "operationId": "registerConnection", "requestBody": { + "required": true, "content": { "application/json": { "schema": { "type": "object", + "required": [ + "tool_name", + "agent_name" + ], "properties": { - "agents": { - "type": "array", - "items": { - "type": "string" - } + "tool_name": { + "type": "string" }, - "message": { + "tool_version": { "type": "string" + }, + "agent_name": { + "type": "string" + }, + "agent_role": { + "type": "string" + }, + "metadata": { + "type": "object" } } } @@ -2159,54 +2517,65 @@ }, "responses": { "200": { - "description": "Task broadcast sent", + "description": "Connection registered", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "connection_id": { + "type": "string", + "format": "uuid" }, - "delivered_to": { - "type": "array", - "items": { - "type": "string" - } + "agent_id": { + "type": "integer" + }, + "agent_name": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "connected" + ] + }, + "sse_url": { + "type": "string" + }, + "heartbeat_url": { + "type": "string" + }, + "token_report_url": { + "type": "string" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } - } - }, - "/api/chat/conversations": { + }, "get": { "tags": [ - "Chat" + "Connections" ], - "summary": "List conversations", - "operationId": "listConversations", + "summary": "List all direct connections", + "operationId": "listConnections", "responses": { "200": { - "description": "Conversation list", + "description": "List of connections", "content": { "application/json": { "schema": { "type": "object", "properties": { - "conversations": { + "connections": { "type": "array", "items": { "type": "object", @@ -2214,16 +2583,33 @@ "id": { "type": "integer" }, - "participants": { - "type": "array", - "items": { - "type": "string" - } + "agent_id": { + "type": "integer" }, - "last_message": { + "agent_name": { "type": "string" }, - "updated_at": { + "tool_name": { + "type": "string" + }, + "tool_version": { + "type": "string" + }, + "connection_id": { + "type": "string", + "format": "uuid" + }, + "status": { + "type": "string", + "enum": [ + "connected", + "disconnected" + ] + }, + "last_heartbeat": { + "type": "integer" + }, + "created_at": { "type": "integer" } } @@ -2238,67 +2624,114 @@ "$ref": "#/components/responses/Unauthorized" } } - } - }, - "/api/chat/messages": { - "get": { + }, + "delete": { "tags": [ - "Chat" + "Connections" ], - "summary": "List messages", - "operationId": "listMessages", - "parameters": [ - { - "name": "conversation_id", - "in": "query", - "schema": { - "type": "integer" + "summary": "Disconnect a CLI connection", + "operationId": "disconnectConnection", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "connection_id" + ], + "properties": { + "connection_id": { + "type": "string", + "format": "uuid" + } + } + } } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "default": 50 + } + }, + "responses": { + "200": { + "description": "Disconnected", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "disconnected" + ] + }, + "connection_id": { + "type": "string" + } + } + } + } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" + } + } + } + }, + "/api/cron": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Get cron jobs", + "operationId": "getCronJobs", + "parameters": [ { - "name": "offset", + "name": "action", "in": "query", "schema": { - "type": "integer", - "default": 0 + "type": "string", + "enum": [ + "list", + "logs" + ], + "default": "list" } } ], "responses": { "200": { - "description": "Message list", + "description": "Cron job list or logs", "content": { "application/json": { "schema": { "type": "object", "properties": { - "messages": { + "jobs": { "type": "array", "items": { "type": "object", "properties": { - "id": { - "type": "integer" - }, - "conversation_id": { - "type": "integer" - }, - "sender": { + "name": { "type": "string" }, - "content": { + "schedule": { "type": "string" }, - "created_at": { + "enabled": { + "type": "boolean" + }, + "last_run": { "type": "integer" + }, + "last_status": { + "type": "string" } } } @@ -2310,15 +2743,18 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } } }, "post": { "tags": [ - "Chat" + "Admin" ], - "summary": "Send message", - "operationId": "sendMessage", + "summary": "Manage cron jobs", + "operationId": "manageCronJobs", "requestBody": { "required": true, "content": { @@ -2326,17 +2762,29 @@ "schema": { "type": "object", "required": [ - "content" + "action" ], "properties": { - "conversation_id": { - "type": "integer" + "action": { + "type": "string", + "enum": [ + "toggle", + "trigger", + "add", + "remove" + ] }, - "content": { + "name": { "type": "string" }, - "recipient": { + "schedule": { + "type": "string" + }, + "command": { "type": "string" + }, + "enabled": { + "type": "boolean" } } } @@ -2344,15 +2792,15 @@ } }, "responses": { - "201": { - "description": "Message sent", + "200": { + "description": "Action applied", "content": { "application/json": { "schema": { "type": "object", "properties": { - "message": { - "type": "object" + "success": { + "type": "boolean" } } } @@ -2371,70 +2819,178 @@ } } }, - "/api/chat/messages/{id}": { + "/api/docs": { "get": { "tags": [ - "Chat" + "Docs" ], - "summary": "Get message by ID", - "operationId": "getMessage", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } + "summary": "Get OpenAPI specification", + "operationId": "getOpenApiSpec", + "security": [], + "responses": { + "200": { + "description": "OpenAPI 3.1 JSON spec" } + } + } + }, + "/api/workload": { + "get": { + "tags": [ + "Monitoring" ], + "summary": "Get real-time workload recommendation", + "description": "Returns system workload metrics and an actionable recommendation: `normal`, `throttle`, `shed`, or `pause`. Thresholds are runtime-configurable via `MC_WORKLOAD_*` environment variables.", + "operationId": "getWorkloadSignals", "responses": { "200": { - "description": "Message details", + "description": "Workload snapshot and recommendation", "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "properties": { + "timestamp": { "type": "integer" }, + "workspace_id": { "type": "integer" }, + "capacity": { + "type": "object", + "properties": { + "active_tasks": { "type": "integer" }, + "tasks_last_5m": { "type": "integer" }, + "errors_last_5m": { "type": "integer" }, + "error_rate_5m": { "type": "number", "minimum": 0, "maximum": 1 }, + "completions_last_hour": { "type": "integer" }, + "avg_completion_rate_per_hour": { "type": "number" } + } + }, + "queue": { + "type": "object", + "properties": { + "total_pending": { "type": "integer" }, + "by_status": { "type": "object", "additionalProperties": { "type": "integer" } }, + "by_priority": { "type": "object", "additionalProperties": { "type": "integer" } }, + "oldest_pending_age_seconds": { "type": ["integer", "null"] }, + "estimated_wait_seconds": { "type": ["integer", "null"] }, + "estimated_wait_confidence": { "type": "string", "enum": ["calculated", "unknown"] } + } + }, + "agents": { + "type": "object", + "properties": { + "total": { "type": "integer" }, + "online": { "type": "integer" }, + "busy": { "type": "integer" }, + "idle": { "type": "integer" }, + "offline": { "type": "integer" }, + "busy_ratio": { "type": "number", "minimum": 0, "maximum": 1 }, + "load_distribution": { + "type": "array", + "items": { + "type": "object", + "properties": { + "agent": { "type": "string" }, + "assigned": { "type": "integer" }, + "in_progress": { "type": "integer" } + } + } + } + } + }, + "recommendation": { + "type": "object", + "properties": { + "action": { "type": "string", "enum": ["normal", "throttle", "shed", "pause"] }, + "reason": { "type": "string" }, + "details": { "type": "array", "items": { "type": "string" } }, + "submit_ok": { "type": "boolean" }, + "suggested_delay_ms": { "type": "integer" } + } + }, + "thresholds": { + "type": "object", + "description": "Effective runtime thresholds after environment overrides." + } + } } } } }, "401": { "$ref": "#/components/responses/Unauthorized" + } + } + } + }, + "/api/events": { + "get": { + "tags": [ + "Monitoring" + ], + "summary": "SSE stream for real-time events", + "operationId": "getEventStream", + "responses": { + "200": { + "description": "Server-Sent Events stream", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } }, - "404": { - "$ref": "#/components/responses/NotFound" + "401": { + "$ref": "#/components/responses/Unauthorized" } } - }, - "delete": { + } + }, + "/api/export": { + "get": { "tags": [ - "Chat" + "Admin" ], - "summary": "Delete message", - "operationId": "deleteMessage", + "summary": "Export data", + "operationId": "exportData", "parameters": [ { - "name": "id", - "in": "path", - "required": true, + "name": "type", + "in": "query", "schema": { - "type": "integer" + "type": "string", + "enum": [ + "tasks", + "agents", + "activities", + "all" + ] + } + }, + { + "name": "format", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "json", + "csv" + ], + "default": "json" } } ], "responses": { "200": { - "description": "Message deleted", + "description": "Exported data", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - } - } + "type": "object" + } + }, + "text/csv": { + "schema": { + "type": "string" } } } @@ -2444,211 +3000,135 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/tokens": { + "/api/agents/{id}/attribution": { "get": { "tags": [ - "Tokens" + "Agents" ], - "summary": "Query token usage", - "operationId": "getTokenUsage", + "summary": "Get attribution report for an agent", + "description": "Self-scope by default. Requester must match target agent (`x-agent-name` or username), unless admin uses `?privileged=1`.", + "operationId": "getAgentAttribution", "parameters": [ { - "name": "action", + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "hours", "in": "query", + "required": false, + "description": "Time window in hours, integer range 1..720. Defaults to 24.", "schema": { - "type": "string", - "enum": [ - "list", - "stats", - "agent-costs", - "export", - "trends" - ], - "default": "list" + "type": "integer", + "minimum": 1, + "maximum": 720, + "default": 24 } }, { - "name": "timeframe", + "name": "section", "in": "query", + "required": false, + "description": "Comma-separated subset of identity,audit,mutations,cost. Defaults to all.", "schema": { "type": "string", - "enum": [ - "hour", - "day", - "week", - "month", - "all" - ], - "default": "all" + "example": "identity,audit" } }, { - "name": "format", + "name": "privileged", "in": "query", - "description": "Export format (only for action=export)", + "required": false, + "description": "Set to 1 for admin override of self-scope checks.", "schema": { "type": "string", "enum": [ - "json", - "csv" - ], - "default": "json" + "1" + ] + } + }, + { + "name": "x-agent-name", + "in": "header", + "required": false, + "description": "Attribution identity header used for self-scope authorization.", + "schema": { + "type": "string" } } ], "responses": { "200": { - "description": "Token usage data. Shape varies by action.", + "description": "Attribution report" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + } + } + } + }, + "/api/gateway-config": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Read gateway config", + "operationId": "getGatewayConfig", + "responses": { + "200": { + "description": "Gateway configuration", "content": { "application/json": { "schema": { - "oneOf": [ - { - "type": "object", - "title": "ListResponse", - "properties": { - "usage": { - "type": "array", - "items": { - "$ref": "#/components/schemas/TokenUsageRecord" - } - }, - "total": { - "type": "integer" - }, - "timeframe": { - "type": "string" - } - } - }, - { - "type": "object", - "title": "StatsResponse", - "properties": { - "summary": { - "$ref": "#/components/schemas/TokenStats" - }, - "models": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/TokenStats" - } - }, - "sessions": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/TokenStats" - } - }, - "agents": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/TokenStats" - } - }, - "timeframe": { - "type": "string" - }, - "recordCount": { - "type": "integer" - } - } - }, - { - "type": "object", - "title": "TrendsResponse", - "properties": { - "trends": { - "type": "array", - "items": { - "type": "object", - "properties": { - "timestamp": { - "type": "string" - }, - "tokens": { - "type": "integer" - }, - "cost": { - "type": "number" - }, - "requests": { - "type": "integer" - } - } - } - }, - "timeframe": { - "type": "string" - } - } - } - ] + "type": "object" } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } } }, "post": { "tags": [ - "Tokens" + "Admin" ], - "summary": "Record token usage", - "operationId": "recordTokenUsage", + "summary": "Update gateway config", + "operationId": "updateGatewayConfig", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object", - "required": [ - "model", - "sessionId", - "inputTokens", - "outputTokens" - ], - "properties": { - "model": { - "type": "string" - }, - "sessionId": { - "type": "string" - }, - "inputTokens": { - "type": "integer" - }, - "outputTokens": { - "type": "integer" - }, - "operation": { - "type": "string", - "default": "chat_completion" - }, - "duration": { - "type": "number" - } - } + "type": "object" } } } }, "responses": { "200": { - "description": "Usage recorded", + "description": "Config updated", "content": { "application/json": { "schema": { @@ -2656,18 +3136,12 @@ "properties": { "success": { "type": "boolean" - }, - "record": { - "$ref": "#/components/schemas/TokenUsageRecord" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -2677,59 +3151,39 @@ } } }, - "/api/sessions": { + "/api/gateways": { "get": { "tags": [ - "Sessions" - ], - "summary": "List gateway sessions", - "operationId": "listSessions", - "parameters": [ - { - "name": "agent", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "default": 50 - } - } + "Admin" ], + "summary": "List gateways", + "operationId": "listGateways", "responses": { "200": { - "description": "Session list", + "description": "Gateway list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "sessions": { + "gateways": { "type": "array", "items": { "type": "object", "properties": { - "key": { - "type": "string" + "id": { + "type": "integer" }, - "agent": { + "name": { "type": "string" }, - "model": { + "url": { "type": "string" }, "status": { "type": "string" }, - "totalTokens": { - "type": "integer" - }, - "updatedAt": { + "last_health_check": { "type": "integer" } } @@ -2744,25 +3198,64 @@ "$ref": "#/components/responses/Unauthorized" } } - } - }, - "/api/sessions/{id}/control": { + }, "post": { "tags": [ - "Sessions" + "Admin" ], - "summary": "Control session (pause/resume/kill)", - "operationId": "controlSession", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" + "summary": "Add gateway", + "operationId": "addGateway", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name", + "url" + ], + "properties": { + "name": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Gateway added", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } + } + }, + "put": { + "tags": [ + "Admin" ], + "summary": "Update gateway", + "operationId": "updateGateway", "requestBody": { "required": true, "content": { @@ -2770,16 +3263,17 @@ "schema": { "type": "object", "required": [ - "action" + "id" ], "properties": { - "action": { - "type": "string", - "enum": [ - "pause", - "resume", - "kill" - ] + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" } } } @@ -2788,7 +3282,7 @@ }, "responses": { "200": { - "description": "Action applied", + "description": "Gateway updated", "content": { "application/json": { "schema": { @@ -2802,9 +3296,6 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -2815,28 +3306,41 @@ "$ref": "#/components/responses/NotFound" } } - } - }, - "/api/webhooks": { - "get": { + }, + "delete": { "tags": [ - "Webhooks" + "Admin" ], - "summary": "List webhooks", - "operationId": "listWebhooks", + "summary": "Delete gateway", + "operationId": "deleteGateway", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer" + } + } + } + } + } + }, "responses": { "200": { - "description": "Webhook list with delivery stats", + "description": "Gateway deleted", "content": { "application/json": { "schema": { "type": "object", "properties": { - "webhooks": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Webhook" - } + "success": { + "type": "boolean" } } } @@ -2850,40 +3354,23 @@ "$ref": "#/components/responses/Forbidden" } } - }, + } + }, + "/api/gateways/health": { "post": { "tags": [ - "Webhooks" + "Admin" ], - "summary": "Create webhook", - "operationId": "createWebhook", + "summary": "Probe gateway health", + "operationId": "probeGatewayHealth", "requestBody": { - "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "name", - "url" - ], "properties": { - "name": { - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - }, - "events": { - "type": "array", - "items": { - "type": "string" - } - }, - "generate_secret": { - "type": "boolean", - "default": true + "gateway_id": { + "type": "integer" } } } @@ -2892,61 +3379,42 @@ }, "responses": { "200": { - "description": "Webhook created. Secret is only shown in full on creation.", + "description": "Health check results", "content": { "application/json": { "schema": { "type": "object", "properties": { - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "url": { - "type": "string" - }, - "secret": { - "type": "string" - }, - "events": { - "type": "array", - "items": { - "type": "string" - } - }, - "enabled": { + "healthy": { "type": "boolean" }, - "message": { - "type": "string" + "latency_ms": { + "type": "number" + }, + "details": { + "type": "object" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } - }, - "put": { + } + }, + "/api/gateways/connect": { + "post": { "tags": [ - "Webhooks" + "Admin" ], - "summary": "Update webhook", - "operationId": "updateWebhook", + "summary": "Resolve websocket connect payload for a gateway", + "operationId": "connectGateway", "requestBody": { "required": true, "content": { @@ -2959,25 +3427,6 @@ "properties": { "id": { "type": "integer" - }, - "name": { - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - }, - "events": { - "type": "array", - "items": { - "type": "string" - } - }, - "enabled": { - "type": "boolean" - }, - "regenerate_secret": { - "type": "boolean" } } } @@ -2986,22 +3435,16 @@ }, "responses": { "200": { - "description": "Webhook updated", + "description": "Resolved websocket URL and token metadata", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" - }, - "secret": { - "type": "string", - "description": "Only present when regenerate_secret is true" - }, - "message": { - "type": "string" - } + "id": { "type": "integer" }, + "ws_url": { "type": "string" }, + "token": { "type": "string" }, + "token_set": { "type": "boolean" } } } } @@ -3018,18 +3461,90 @@ }, "404": { "$ref": "#/components/responses/NotFound" + } + } + } + }, + "/api/github": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Get GitHub integration status", + "operationId": "getGithubStatus", + "responses": { + "200": { + "description": "GitHub integration status" + } + } + }, + "post": { + "tags": [ + "Admin" + ], + "summary": "Sync GitHub issues", + "operationId": "syncGithubIssues", + "responses": { + "200": { + "description": "Sync result" + } + } + } + }, + "/api/integrations": { + "get": { + "tags": [ + "Admin" + ], + "summary": "List integrations", + "operationId": "listIntegrations", + "responses": { + "200": { + "description": "Integration list", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "integrations": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "type": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "config": { + "type": "object" + } + } + } + } + } + } + } + } }, - "429": { - "$ref": "#/components/responses/RateLimited" + "401": { + "$ref": "#/components/responses/Unauthorized" } } }, - "delete": { + "post": { "tags": [ - "Webhooks" + "Admin" ], - "summary": "Delete webhook", - "operationId": "deleteWebhook", + "summary": "Integration actions (enable, disable, test, configure)", + "operationId": "integrationAction", "requestBody": { "required": true, "content": { @@ -3037,11 +3552,24 @@ "schema": { "type": "object", "required": [ + "action", "id" ], "properties": { + "action": { + "type": "string", + "enum": [ + "enable", + "disable", + "test", + "configure" + ] + }, "id": { - "type": "integer" + "type": "string" + }, + "config": { + "type": "object" } } } @@ -3050,7 +3578,7 @@ }, "responses": { "200": { - "description": "Webhook deleted", + "description": "Action applied", "content": { "application/json": { "schema": { @@ -3058,9 +3586,6 @@ "properties": { "success": { "type": "boolean" - }, - "deleted": { - "type": "integer" } } } @@ -3075,29 +3600,29 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } } }, - "/api/webhooks/deliveries": { + "/api/logs": { "get": { "tags": [ - "Webhooks" + "Monitoring" ], - "summary": "Get webhook delivery history", - "operationId": "getWebhookDeliveries", + "summary": "Get system logs", + "operationId": "getSystemLogs", "parameters": [ { - "name": "webhook_id", + "name": "level", "in": "query", "schema": { - "type": "integer" + "type": "string", + "enum": [ + "info", + "warn", + "error", + "debug" + ] } }, { @@ -3105,40 +3630,34 @@ "in": "query", "schema": { "type": "integer", - "default": 50 + "default": 100 } } ], "responses": { "200": { - "description": "Delivery history", + "description": "Log entries", "content": { "application/json": { "schema": { "type": "object", "properties": { - "deliveries": { + "logs": { "type": "array", "items": { "type": "object", "properties": { - "id": { - "type": "integer" - }, - "webhook_id": { - "type": "integer" - }, - "event": { + "timestamp": { "type": "string" }, - "status_code": { - "type": "integer" + "level": { + "type": "string" }, - "error": { + "message": { "type": "string" }, - "created_at": { - "type": "integer" + "source": { + "type": "string" } } } @@ -3157,13 +3676,44 @@ } } }, - "/api/webhooks/test": { + "/api/memory": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Get memory files", + "operationId": "getMemoryFiles", + "parameters": [ + { + "name": "path", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Memory file contents", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + } + } + }, "post": { "tags": [ - "Webhooks" + "Admin" ], - "summary": "Test webhook", - "operationId": "testWebhook", + "summary": "Update memory file", + "operationId": "updateMemoryFile", "requestBody": { "required": true, "content": { @@ -3171,11 +3721,15 @@ "schema": { "type": "object", "required": [ - "id" + "path", + "content" ], "properties": { - "id": { - "type": "integer" + "path": { + "type": "string" + }, + "content": { + "type": "string" } } } @@ -3184,7 +3738,7 @@ }, "responses": { "200": { - "description": "Test result", + "description": "Memory updated", "content": { "application/json": { "schema": { @@ -3192,12 +3746,6 @@ "properties": { "success": { "type": "boolean" - }, - "status_code": { - "type": "integer" - }, - "response_time_ms": { - "type": "number" } } } @@ -3209,177 +3757,125 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/alerts": { + "/api/mentions": { "get": { "tags": [ - "Alerts" + "Mentions" ], - "summary": "List alert rules", - "operationId": "listAlertRules", - "responses": { - "200": { - "description": "Alert rule list", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "rules": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AlertRule" - } - } - } - } - } - } + "summary": "Get mention autocomplete targets", + "operationId": "getMentionTargets", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + }, + "description": "Search query" }, - "401": { - "$ref": "#/components/responses/Unauthorized" - } - } - }, - "post": { - "tags": [ - "Alerts" - ], - "summary": "Create alert rule or evaluate rules", - "operationId": "createAlertRule", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "oneOf": [ - { - "type": "object", - "title": "CreateRule", - "required": [ - "name", - "entity_type", - "condition_field", - "condition_operator", - "condition_value" - ], - "properties": { - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "entity_type": { - "type": "string", - "enum": [ - "agent", - "task", - "session", - "activity" - ] - }, - "condition_field": { - "type": "string" - }, - "condition_operator": { - "type": "string", - "enum": [ - "equals", - "not_equals", - "greater_than", - "less_than", - "contains", - "count_above", - "count_below", - "age_minutes_above" - ] - }, - "condition_value": { - "type": "string" - }, - "action_type": { - "type": "string", - "default": "notification" - }, - "action_config": { - "type": "object" - }, - "cooldown_minutes": { - "type": "integer", - "default": 60 - } - } - }, - { - "type": "object", - "title": "EvaluateRules", - "required": [ - "action" - ], - "properties": { - "action": { - "type": "string", - "const": "evaluate" - } - } - } - ] - } - } + { + "name": "type", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "user", + "agent" + ] + }, + "description": "Filter by type" + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 20 + }, + "description": "Max results" } - }, + ], "responses": { - "201": { - "description": "Rule created", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "rule": { - "$ref": "#/components/schemas/AlertRule" - } - } - } - } + "200": { + "description": "Mention targets list" + } + } + } + }, + "/api/notifications": { + "get": { + "tags": [ + "Monitoring" + ], + "summary": "List notifications", + "operationId": "listNotifications", + "parameters": [ + { + "name": "recipient", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "unread", + "in": "query", + "schema": { + "type": "boolean" } }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50 + } + } + ], + "responses": { "200": { - "description": "Rules evaluated", + "description": "Notification list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "evaluated": { - "type": "integer" - }, - "triggered": { - "type": "integer" - }, - "results": { + "notifications": { "type": "array", "items": { "type": "object", "properties": { - "rule_id": { + "id": { "type": "integer" }, - "rule_name": { + "recipient": { "type": "string" }, - "triggered": { + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "read": { "type": "boolean" }, - "reason": { + "source_type": { "type": "string" + }, + "source_id": { + "type": "integer" + }, + "created_at": { + "type": "integer" } } } @@ -3389,26 +3885,17 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } }, - "put": { + "post": { "tags": [ - "Alerts" + "Monitoring" ], - "summary": "Update alert rule", - "operationId": "updateAlertRule", + "summary": "Notification actions (mark read, dismiss)", + "operationId": "notificationAction", "requestBody": { "required": true, "content": { @@ -3416,41 +3903,22 @@ "schema": { "type": "object", "required": [ - "id" + "action" ], "properties": { + "action": { + "type": "string", + "enum": [ + "mark_read", + "mark_all_read", + "dismiss" + ] + }, "id": { "type": "integer" }, - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "entity_type": { - "type": "string" - }, - "condition_field": { - "type": "string" - }, - "condition_operator": { - "type": "string" - }, - "condition_value": { - "type": "string" - }, - "action_type": { + "recipient": { "type": "string" - }, - "action_config": { - "type": "object" - }, - "cooldown_minutes": { - "type": "integer" } } } @@ -3459,14 +3927,14 @@ }, "responses": { "200": { - "description": "Rule updated", + "description": "Action applied", "content": { "application/json": { "schema": { "type": "object", "properties": { - "rule": { - "$ref": "#/components/schemas/AlertRule" + "success": { + "type": "boolean" } } } @@ -3476,6 +3944,120 @@ "400": { "$ref": "#/components/responses/BadRequest" }, + "401": { + "$ref": "#/components/responses/Unauthorized" + } + } + } + }, + "/api/agents/{id}/diagnostics": { + "get": { + "tags": [ + "Agents" + ], + "summary": "Get self diagnostics for an agent", + "description": "Self-scoped diagnostics by default. Cross-agent access requires `privileged=1` with admin credentials. Trend alerts are informational signals derived from current-vs-previous window deltas (error spikes, throughput drops, activity stalls).", + "operationId": "getAgentDiagnostics", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Agent numeric ID or name." + }, + { + "name": "hours", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 720, + "default": 24 + }, + "description": "Diagnostics window in hours." + }, + { + "name": "section", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "Comma-separated sections: summary,tasks,errors,activity,trends,tokens." + }, + { + "name": "privileged", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1" + ] + }, + "description": "Set to `1` to allow explicit admin cross-agent diagnostics access." + } + ], + "responses": { + "200": { + "description": "Diagnostics payload", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent": { + "type": "object", + "properties": { + "id": { "type": "integer" }, + "name": { "type": "string" }, + "role": { "type": "string" }, + "status": { "type": "string" } + } + }, + "timeframe": { + "type": "object", + "properties": { + "hours": { "type": "integer" }, + "since": { "type": "integer" }, + "until": { "type": "integer" } + } + }, + "summary": { "type": "object" }, + "tasks": { "type": "object" }, + "errors": { "type": "object" }, + "activity": { "type": "object" }, + "trends": { + "type": "object", + "properties": { + "current_period": { "type": "object" }, + "previous_period": { "type": "object" }, + "change": { "type": "object" }, + "alerts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "level": { "type": "string", "enum": ["info", "warning"] }, + "message": { "type": "string" } + } + } + } + } + }, + "tokens": { "type": "object" } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -3484,18 +4066,17 @@ }, "404": { "$ref": "#/components/responses/NotFound" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } - }, - "delete": { + } + }, + "/api/notifications/deliver": { + "post": { "tags": [ - "Alerts" + "Monitoring" ], - "summary": "Delete alert rule", - "operationId": "deleteAlertRule", + "summary": "Deliver notification to agent", + "operationId": "deliverNotification", "requestBody": { "required": true, "content": { @@ -3503,11 +4084,22 @@ "schema": { "type": "object", "required": [ - "id" + "agent", + "title", + "message" ], "properties": { - "id": { - "type": "integer" + "agent": { + "type": "string" + }, + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "type": { + "type": "string" } } } @@ -3516,13 +4108,13 @@ }, "responses": { "200": { - "description": "Rule deleted", + "description": "Notification delivered", "content": { "application/json": { "schema": { "type": "object", "properties": { - "deleted": { + "success": { "type": "boolean" } } @@ -3538,29 +4130,26 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "429": { - "$ref": "#/components/responses/RateLimited" } } } }, - "/api/workflows": { + "/api/pipelines": { "get": { "tags": [ - "Workflows" + "Pipelines" ], - "summary": "List workflow templates", - "operationId": "listWorkflows", + "summary": "List pipelines", + "operationId": "listPipelines", "responses": { "200": { - "description": "Workflow template list", + "description": "Pipeline list with enriched step data and run counts", "content": { "application/json": { "schema": { "type": "object", "properties": { - "templates": { + "pipelines": { "type": "array", "items": { "type": "object", @@ -3577,7 +4166,22 @@ "steps": { "type": "array", "items": { - "type": "object" + "type": "object", + "properties": { + "template_id": { + "type": "integer" + }, + "template_name": { + "type": "string" + }, + "on_failure": { + "type": "string", + "enum": [ + "stop", + "continue" + ] + } + } } }, "created_by": { @@ -3586,6 +4190,23 @@ "use_count": { "type": "integer" }, + "runs": { + "type": "object", + "properties": { + "total": { + "type": "integer" + }, + "completed": { + "type": "integer" + }, + "failed": { + "type": "integer" + }, + "running": { + "type": "integer" + } + } + }, "created_at": { "type": "integer" }, @@ -3607,10 +4228,10 @@ }, "post": { "tags": [ - "Workflows" + "Pipelines" ], - "summary": "Create workflow template", - "operationId": "createWorkflow", + "summary": "Create pipeline", + "operationId": "createPipeline", "requestBody": { "required": true, "content": { @@ -3632,15 +4253,20 @@ "type": "array", "items": { "type": "object", + "required": [ + "template_id" + ], "properties": { - "agent": { - "type": "string" - }, - "action": { - "type": "string" + "template_id": { + "type": "integer" }, - "params": { - "type": "object" + "on_failure": { + "type": "string", + "enum": [ + "stop", + "continue" + ], + "default": "stop" } } } @@ -3652,13 +4278,13 @@ }, "responses": { "201": { - "description": "Template created", + "description": "Pipeline created", "content": { "application/json": { "schema": { "type": "object", "properties": { - "template": { + "pipeline": { "type": "object" } } @@ -3682,10 +4308,10 @@ }, "put": { "tags": [ - "Workflows" + "Pipelines" ], - "summary": "Update workflow template", - "operationId": "updateWorkflow", + "summary": "Update pipeline", + "operationId": "updatePipeline", "requestBody": { "required": true, "content": { @@ -3718,13 +4344,13 @@ }, "responses": { "200": { - "description": "Template updated", + "description": "Pipeline updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "template": { + "pipeline": { "type": "object" } } @@ -3748,10 +4374,10 @@ }, "delete": { "tags": [ - "Workflows" + "Pipelines" ], - "summary": "Delete workflow template", - "operationId": "deleteWorkflow", + "summary": "Delete pipeline", + "operationId": "deletePipeline", "requestBody": { "required": true, "content": { @@ -3772,7 +4398,7 @@ }, "responses": { "200": { - "description": "Template deleted", + "description": "Pipeline deleted", "content": { "application/json": { "schema": { @@ -3786,116 +4412,25 @@ } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/pipelines": { - "get": { - "tags": [ - "Pipelines" - ], - "summary": "List pipelines", - "operationId": "listPipelines", - "responses": { - "200": { - "description": "Pipeline list with enriched step data and run counts", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "pipelines": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "steps": { - "type": "array", - "items": { - "type": "object", - "properties": { - "template_id": { - "type": "integer" - }, - "template_name": { - "type": "string" - }, - "on_failure": { - "type": "string", - "enum": [ - "stop", - "continue" - ] - } - } - } - }, - "created_by": { - "type": "string" - }, - "use_count": { - "type": "integer" - }, - "runs": { - "type": "object", - "properties": { - "total": { - "type": "integer" - }, - "completed": { - "type": "integer" - }, - "failed": { - "type": "integer" - }, - "running": { - "type": "integer" - } - } - }, - "created_at": { - "type": "integer" - }, - "updated_at": { - "type": "integer" - } - } - } - } - } - } - } - } - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - } - } - }, + "/api/pipelines/run": { "post": { "tags": [ "Pipelines" ], - "summary": "Create pipeline", - "operationId": "createPipeline", + "summary": "Run a pipeline", + "operationId": "runPipeline", "requestBody": { "required": true, "content": { @@ -3903,37 +4438,14 @@ "schema": { "type": "object", "required": [ - "name", - "steps" + "pipeline_id" ], "properties": { - "name": { - "type": "string" - }, - "description": { - "type": "string" + "pipeline_id": { + "type": "integer" }, - "steps": { - "type": "array", - "items": { - "type": "object", - "required": [ - "template_id" - ], - "properties": { - "template_id": { - "type": "integer" - }, - "on_failure": { - "type": "string", - "enum": [ - "stop", - "continue" - ], - "default": "stop" - } - } - } + "params": { + "type": "object" } } } @@ -3941,15 +4453,18 @@ } }, "responses": { - "201": { - "description": "Pipeline created", + "200": { + "description": "Pipeline run started", "content": { "application/json": { "schema": { "type": "object", "properties": { - "pipeline": { - "type": "object" + "run_id": { + "type": "integer" + }, + "status": { + "type": "string" } } } @@ -3965,17 +4480,31 @@ "403": { "$ref": "#/components/responses/Forbidden" }, - "429": { - "$ref": "#/components/responses/RateLimited" + "404": { + "$ref": "#/components/responses/NotFound" + } + } + } + }, + "/api/projects": { + "get": { + "tags": [ + "Projects" + ], + "summary": "List all projects", + "operationId": "listProjects", + "responses": { + "200": { + "description": "Project list" } } }, - "put": { + "post": { "tags": [ - "Pipelines" + "Projects" ], - "summary": "Update pipeline", - "operationId": "updatePipeline", + "summary": "Create a new project", + "operationId": "createProject", "requestBody": { "required": true, "content": { @@ -3983,65 +4512,165 @@ "schema": { "type": "object", "required": [ - "id" + "name" ], "properties": { - "id": { - "type": "integer" - }, "name": { "type": "string" }, "description": { "type": "string" - }, - "steps": { - "type": "array", - "items": { - "type": "object" - } } } } } } }, + "responses": { + "201": { + "description": "Project created" + } + } + } + }, + "/api/projects/{id}": { + "get": { + "tags": [ + "Projects" + ], + "summary": "Get project by ID", + "operationId": "getProject", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], "responses": { "200": { - "description": "Pipeline updated", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "pipeline": { - "type": "object" - } + "description": "Project details" + } + } + }, + "patch": { + "tags": [ + "Projects" + ], + "summary": "Update a project", + "operationId": "updateProject", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" } } } } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" + } + }, + "responses": { + "200": { + "description": "Updated" } } }, "delete": { "tags": [ - "Pipelines" + "Projects" ], - "summary": "Delete pipeline", - "operationId": "deletePipeline", + "summary": "Delete a project", + "operationId": "deleteProject", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Deleted" + } + } + } + }, + "/api/projects/{id}/tasks": { + "get": { + "tags": [ + "Projects" + ], + "summary": "List tasks in a project", + "operationId": "listProjectTasks", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Tasks in project" + } + } + } + }, + "/api/quality-review": { + "get": { + "tags": [ + "Quality" + ], + "summary": "List quality reviews", + "operationId": "listQualityReviews", + "parameters": [ + { + "name": "task_id", + "in": "query", + "schema": { + "type": "integer" + }, + "description": "Filter by task" + } + ], + "responses": { + "200": { + "description": "Quality review list" + } + } + }, + "post": { + "tags": [ + "Quality" + ], + "summary": "Submit a quality review", + "operationId": "submitQualityReview", "requestBody": { "required": true, "content": { @@ -4049,11 +4678,22 @@ "schema": { "type": "object", "required": [ - "id" + "task_id", + "status" ], "properties": { - "id": { + "task_id": { "type": "integer" + }, + "status": { + "type": "string", + "enum": [ + "approved", + "rejected" + ] + }, + "notes": { + "type": "string" } } } @@ -4062,23 +4702,69 @@ }, "responses": { "200": { - "description": "Pipeline deleted", + "description": "Review submitted" + } + } + } + }, + "/api/releases/check": { + "get": { + "tags": [ + "Releases" + ], + "summary": "Check for new releases", + "operationId": "checkReleases", + "security": [], + "responses": { + "200": { + "description": "Release info with version comparison" + } + } + } + }, + "/api/scheduler": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Get scheduler status", + "operationId": "getSchedulerStatus", + "responses": { + "200": { + "description": "Scheduler status and registered tasks", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { + "running": { "type": "boolean" + }, + "tasks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "interval": { + "type": "string" + }, + "last_run": { + "type": "integer" + }, + "next_run": { + "type": "integer" + } + } + } } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -4086,15 +4772,13 @@ "$ref": "#/components/responses/Forbidden" } } - } - }, - "/api/pipelines/run": { + }, "post": { "tags": [ - "Pipelines" + "Admin" ], - "summary": "Run a pipeline", - "operationId": "runPipeline", + "summary": "Trigger scheduled task", + "operationId": "triggerScheduledTask", "requestBody": { "required": true, "content": { @@ -4102,14 +4786,11 @@ "schema": { "type": "object", "required": [ - "pipeline_id" + "task" ], "properties": { - "pipeline_id": { - "type": "integer" - }, - "params": { - "type": "object" + "task": { + "type": "string" } } } @@ -4118,17 +4799,17 @@ }, "responses": { "200": { - "description": "Pipeline run started", + "description": "Task triggered", "content": { "application/json": { "schema": { "type": "object", "properties": { - "run_id": { - "type": "integer" + "success": { + "type": "boolean" }, - "status": { - "type": "string" + "result": { + "type": "object" } } } @@ -4143,95 +4824,75 @@ }, "403": { "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } } }, - "/api/activities": { + "/api/search": { "get": { "tags": [ - "Monitoring" + "Admin" ], - "summary": "List activities", - "operationId": "listActivities", + "summary": "Full-text search", + "operationId": "search", "parameters": [ { - "name": "type", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "actor", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "entity_type", + "name": "q", "in": "query", + "required": true, "schema": { "type": "string" } }, { - "name": "limit", + "name": "type", "in": "query", "schema": { - "type": "integer", - "default": 50 + "type": "string", + "enum": [ + "tasks", + "agents", + "activities", + "all" + ] } }, { - "name": "offset", + "name": "limit", "in": "query", "schema": { "type": "integer", - "default": 0 + "default": 20 } } ], "responses": { "200": { - "description": "Activity list", + "description": "Search results", "content": { "application/json": { "schema": { "type": "object", "properties": { - "activities": { + "results": { "type": "array", "items": { "type": "object", "properties": { - "id": { - "type": "integer" - }, "type": { "type": "string" }, - "entity_type": { - "type": "string" - }, - "entity_id": { + "id": { "type": "integer" }, - "actor": { + "title": { "type": "string" }, - "description": { + "snippet": { "type": "string" }, - "metadata": { - "type": "object" - }, - "created_at": { - "type": "integer" + "score": { + "type": "number" } } } @@ -4244,29 +4905,25 @@ } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" } } } }, - "/api/audit": { + "/api/sessions": { "get": { "tags": [ - "Monitoring" + "Sessions" ], - "summary": "Get audit log", - "operationId": "getAuditLog", + "summary": "List gateway sessions", + "operationId": "listSessions", "parameters": [ { - "name": "action", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "actor", + "name": "agent", "in": "query", "schema": { "type": "string" @@ -4277,60 +4934,43 @@ "in": "query", "schema": { "type": "integer", - "default": 100 - } - }, - { - "name": "offset", - "in": "query", - "schema": { - "type": "integer", - "default": 0 + "default": 50 } } ], "responses": { "200": { - "description": "Audit log entries", + "description": "Session list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "entries": { + "sessions": { "type": "array", "items": { "type": "object", "properties": { - "id": { - "type": "integer" + "key": { + "type": "string" }, - "action": { + "agent": { "type": "string" }, - "actor": { + "model": { "type": "string" }, - "target_type": { + "status": { "type": "string" }, - "target_id": { + "totalTokens": { "type": "integer" }, - "detail": { - "type": "object" - }, - "ip_address": { - "type": "string" - }, - "created_at": { + "updatedAt": { "type": "integer" } } } - }, - "total": { - "type": "integer" } } } @@ -4339,158 +4979,98 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" } } } }, - "/api/logs": { - "get": { + "/api/sessions/{id}/control": { + "post": { "tags": [ - "Monitoring" + "Sessions" ], - "summary": "Get system logs", - "operationId": "getSystemLogs", + "summary": "Control session (pause/resume/kill)", + "operationId": "controlSession", "parameters": [ { - "name": "level", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "info", - "warn", - "error", - "debug" - ] - } - }, - { - "name": "limit", - "in": "query", + "name": "id", + "in": "path", + "required": true, "schema": { - "type": "integer", - "default": 100 + "type": "string" } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "action" + ], + "properties": { + "action": { + "type": "string", + "enum": [ + "pause", + "resume", + "kill" + ] + } + } + } + } + } + }, "responses": { "200": { - "description": "Log entries", + "description": "Action applied", "content": { "application/json": { "schema": { "type": "object", "properties": { - "logs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "timestamp": { - "type": "string" - }, - "level": { - "type": "string" - }, - "message": { - "type": "string" - }, - "source": { - "type": "string" - } - } - } + "success": { + "type": "boolean" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/notifications": { + "/api/settings": { "get": { "tags": [ - "Monitoring" - ], - "summary": "List notifications", - "operationId": "listNotifications", - "parameters": [ - { - "name": "recipient", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "unread", - "in": "query", - "schema": { - "type": "boolean" - } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "default": 50 - } - } + "Admin" ], + "summary": "Get application settings", + "operationId": "getSettings", "responses": { "200": { - "description": "Notification list", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "notifications": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "recipient": { - "type": "string" - }, - "type": { - "type": "string" - }, - "title": { - "type": "string" - }, - "message": { - "type": "string" - }, - "read": { - "type": "boolean" - }, - "source_type": { - "type": "string" - }, - "source_id": { - "type": "integer" - }, - "created_at": { - "type": "integer" - } - } - } + "description": "Current settings", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "settings": { + "type": "object" } } } @@ -4499,47 +5079,31 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } } }, "post": { "tags": [ - "Monitoring" + "Admin" ], - "summary": "Notification actions (mark read, dismiss)", - "operationId": "notificationAction", + "summary": "Update settings", + "operationId": "updateSettings", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object", - "required": [ - "action" - ], - "properties": { - "action": { - "type": "string", - "enum": [ - "mark_read", - "mark_all_read", - "dismiss" - ] - }, - "id": { - "type": "integer" - }, - "recipient": { - "type": "string" - } - } + "type": "object" } } } }, "responses": { "200": { - "description": "Action applied", + "description": "Settings updated", "content": { "application/json": { "schema": { @@ -4553,22 +5117,22 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" } } } }, - "/api/notifications/deliver": { + "/api/spawn": { "post": { "tags": [ - "Monitoring" + "Admin" ], - "summary": "Deliver notification to agent", - "operationId": "deliverNotification", + "summary": "Spawn agent process", + "operationId": "spawnAgent", "requestBody": { "required": true, "content": { @@ -4576,22 +5140,17 @@ "schema": { "type": "object", "required": [ - "agent", - "title", - "message" + "agent" ], "properties": { "agent": { "type": "string" }, - "title": { - "type": "string" - }, - "message": { + "task": { "type": "string" }, - "type": { - "type": "string" + "params": { + "type": "object" } } } @@ -4600,7 +5159,7 @@ }, "responses": { "200": { - "description": "Notification delivered", + "description": "Agent spawned", "content": { "application/json": { "schema": { @@ -4608,6 +5167,9 @@ "properties": { "success": { "type": "boolean" + }, + "session_id": { + "type": "string" } } } @@ -4626,20 +5188,53 @@ } } }, - "/api/events": { + "/api/standup": { "get": { "tags": [ - "Monitoring" + "Admin" + ], + "summary": "Get standup report", + "operationId": "getStandupReport", + "parameters": [ + { + "name": "date", + "in": "query", + "schema": { + "type": "string", + "format": "date" + } + } ], - "summary": "SSE stream for real-time events", - "operationId": "getEventStream", "responses": { "200": { - "description": "Server-Sent Events stream", + "description": "Standup report", "content": { - "text/event-stream": { + "application/json": { "schema": { - "type": "string" + "type": "object", + "properties": { + "date": { + "type": "string" + }, + "agents": { + "type": "array", + "items": { + "type": "object" + } + }, + "tasks_completed": { + "type": "integer" + }, + "tasks_in_progress": { + "type": "integer" + }, + "highlights": { + "type": "array", + "items": { + "type": "string" + } + } + } } } } @@ -4710,23 +5305,55 @@ } } }, - "/api/settings": { + "/api/super/provision-jobs": { "get": { "tags": [ - "Admin" + "Super Admin" ], - "summary": "Get application settings", - "operationId": "getSettings", + "summary": "List provision jobs", + "operationId": "listProvisionJobs", "responses": { "200": { - "description": "Current settings", + "description": "Provision job list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "settings": { - "type": "object" + "jobs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "tenant_id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "pending", + "running", + "completed", + "failed" + ] + }, + "output": { + "type": "string" + }, + "created_at": { + "type": "integer" + }, + "completed_at": { + "type": "integer" + } + } + } } } } @@ -4743,36 +5370,49 @@ }, "post": { "tags": [ - "Admin" + "Super Admin" ], - "summary": "Update settings", - "operationId": "updateSettings", + "summary": "Create provision job", + "operationId": "createProvisionJob", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "required": [ + "tenant_id", + "type" + ], + "properties": { + "tenant_id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "params": { + "type": "object" + } + } } } } }, "responses": { - "200": { - "description": "Settings updated", + "201": { + "description": "Job created", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - } - } + "type": "object" } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -4782,45 +5422,30 @@ } } }, - "/api/scheduler": { + "/api/super/provision-jobs/{id}": { "get": { "tags": [ - "Admin" + "Super Admin" + ], + "summary": "Get provision job details", + "operationId": "getProvisionJob", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], - "summary": "Get scheduler status", - "operationId": "getSchedulerStatus", "responses": { "200": { - "description": "Scheduler status and registered tasks", + "description": "Job details", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "running": { - "type": "boolean" - }, - "tasks": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "interval": { - "type": "string" - }, - "last_run": { - "type": "integer" - }, - "next_run": { - "type": "integer" - } - } - } - } - } + "type": "object" } } } @@ -4830,36 +5455,33 @@ }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } - }, + } + }, + "/api/super/provision-jobs/{id}/run": { "post": { "tags": [ - "Admin" + "Super Admin" ], - "summary": "Trigger scheduled task", - "operationId": "triggerScheduledTask", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "task" - ], - "properties": { - "task": { - "type": "string" - } - } - } + "summary": "Run provision job", + "operationId": "runProvisionJob", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" } } - }, + ], "responses": { "200": { - "description": "Task triggered", + "description": "Job started", "content": { "application/json": { "schema": { @@ -4868,74 +5490,63 @@ "success": { "type": "boolean" }, - "result": { - "type": "object" + "status": { + "type": "string" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/cron": { + "/api/super/tenants": { "get": { "tags": [ - "Admin" - ], - "summary": "Get cron jobs", - "operationId": "getCronJobs", - "parameters": [ - { - "name": "action", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "list", - "logs" - ], - "default": "list" - } - } + "Super Admin" ], + "summary": "List tenants", + "operationId": "listTenants", "responses": { "200": { - "description": "Cron job list or logs", + "description": "Tenant list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "jobs": { + "tenants": { "type": "array", "items": { "type": "object", "properties": { + "id": { + "type": "integer" + }, + "slug": { + "type": "string" + }, "name": { "type": "string" }, - "schedule": { + "status": { "type": "string" }, - "enabled": { - "type": "boolean" + "linux_user": { + "type": "string" }, - "last_run": { + "created_at": { "type": "integer" - }, - "last_status": { - "type": "string" } } } @@ -4955,10 +5566,10 @@ }, "post": { "tags": [ - "Admin" + "Super Admin" ], - "summary": "Manage cron jobs", - "operationId": "manageCronJobs", + "summary": "Create tenant and bootstrap job", + "operationId": "createTenant", "requestBody": { "required": true, "content": { @@ -4966,38 +5577,80 @@ "schema": { "type": "object", "required": [ - "action" + "slug", + "name" ], "properties": { - "action": { - "type": "string", - "enum": [ - "toggle", - "trigger", - "add", - "remove" - ] - }, - "name": { + "slug": { "type": "string" }, - "schedule": { + "name": { "type": "string" }, - "command": { + "linux_user": { "type": "string" }, - "enabled": { - "type": "boolean" + "config": { + "type": "object" } } } } } }, + "responses": { + "201": { + "description": "Tenant created with bootstrap job", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "409": { + "description": "Tenant slug or linux user already exists", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/super/tenants/{id}/decommission": { + "post": { + "tags": [ + "Super Admin" + ], + "summary": "Decommission tenant", + "operationId": "decommissionTenant", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], "responses": { "200": { - "description": "Action applied", + "description": "Tenant decommissioned", "content": { "application/json": { "schema": { @@ -5011,55 +5664,100 @@ } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/gateways": { + "/api/tasks": { "get": { "tags": [ - "Admin" + "Tasks" + ], + "summary": "List tasks", + "operationId": "listTasks", + "parameters": [ + { + "name": "status", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "inbox", + "assigned", + "in_progress", + "quality_review", + "done" + ] + } + }, + { + "name": "assigned_to", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "priority", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "critical", + "high", + "medium", + "low" + ] + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50, + "maximum": 200 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "default": 0 + } + } ], - "summary": "List gateways", - "operationId": "listGateways", "responses": { "200": { - "description": "Gateway list", + "description": "Paginated task list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "gateways": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "url": { - "type": "string" - }, - "status": { - "type": "string" - }, - "last_health_check": { - "type": "integer" - } - } + "tasks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Task" } + }, + "total": { + "type": "integer" + }, + "page": { + "type": "integer" + }, + "limit": { + "type": "integer" } } } @@ -5073,10 +5771,10 @@ }, "post": { "tags": [ - "Admin" + "Tasks" ], - "summary": "Add gateway", - "operationId": "addGateway", + "summary": "Create task", + "operationId": "createTask", "requestBody": { "required": true, "content": { @@ -5084,68 +5782,56 @@ "schema": { "type": "object", "required": [ - "name", - "url" + "title" ], "properties": { - "name": { + "title": { "type": "string" }, - "url": { + "description": { + "type": "string" + }, + "status": { "type": "string", - "format": "uri" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "Gateway added", - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - } - } - }, - "put": { - "tags": [ - "Admin" - ], - "summary": "Update gateway", - "operationId": "updateGateway", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer" + "enum": [ + "inbox", + "assigned", + "in_progress", + "quality_review", + "done" + ], + "default": "inbox" }, - "name": { + "priority": { + "type": "string", + "enum": [ + "critical", + "high", + "medium", + "low" + ], + "default": "medium" + }, + "assigned_to": { "type": "string" }, - "url": { + "created_by": { + "type": "string" + }, + "due_date": { "type": "string" + }, + "estimated_hours": { + "type": "number" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" } } } @@ -5153,96 +5839,85 @@ } }, "responses": { - "200": { - "description": "Gateway updated", + "201": { + "description": "Task created", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "task": { + "$ref": "#/components/schemas/Task" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" }, - "404": { - "$ref": "#/components/responses/NotFound" - } - } - }, - "delete": { - "tags": [ - "Admin" - ], - "summary": "Delete gateway", - "operationId": "deleteGateway", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Gateway deleted", + "409": { + "description": "Task title already exists", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - } - } + "$ref": "#/components/schemas/Error" } } } }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" + "429": { + "$ref": "#/components/responses/RateLimited" } } - } - }, - "/api/gateways/health": { - "post": { + }, + "put": { "tags": [ - "Admin" + "Tasks" ], - "summary": "Probe gateway health", - "operationId": "probeGatewayHealth", + "summary": "Bulk update task statuses", + "operationId": "bulkUpdateTasks", "requestBody": { + "required": true, "content": { "application/json": { "schema": { "type": "object", + "required": [ + "tasks" + ], "properties": { - "gateway_id": { - "type": "integer" + "tasks": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id", + "status" + ], + "properties": { + "id": { + "type": "integer" + }, + "status": { + "type": "string", + "enum": [ + "inbox", + "assigned", + "in_progress", + "quality_review", + "done" + ] + } + } + } } } } @@ -5251,93 +5926,113 @@ }, "responses": { "200": { - "description": "Health check results", + "description": "Tasks updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "healthy": { + "success": { "type": "boolean" }, - "latency_ms": { - "type": "number" - }, - "details": { - "type": "object" + "updated": { + "type": "integer" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } } }, - "/api/gateway-config": { + "/api/tasks/queue": { "get": { "tags": [ - "Admin" - ], - "summary": "Read gateway config", - "operationId": "getGatewayConfig", - "responses": { - "200": { - "description": "Gateway configuration", - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - } - } - }, - "post": { - "tags": [ - "Admin" + "Tasks" ], - "summary": "Update gateway config", - "operationId": "updateGatewayConfig", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object" - } + "summary": "Poll next task for an agent", + "operationId": "pollTaskQueue", + "parameters": [ + { + "name": "agent", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "Agent name. Optional when x-agent-name header is provided." + }, + { + "name": "max_capacity", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "default": 1 } + }, + { + "name": "x-agent-name", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Agent attribution header used when `agent` query param is omitted." } - }, + ], "responses": { "200": { - "description": "Config updated", + "description": "Queue poll result", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "task": { + "oneOf": [ + { "$ref": "#/components/schemas/Task" }, + { "type": "null" } + ] + }, + "reason": { + "type": "string", + "enum": [ + "continue_current", + "assigned", + "at_capacity", + "no_tasks_available" + ] + }, + "agent": { + "type": "string" + }, + "timestamp": { + "type": "integer" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -5347,43 +6042,33 @@ } } }, - "/api/integrations": { + "/api/tasks/{id}": { "get": { "tags": [ - "Admin" + "Tasks" + ], + "summary": "Get task by ID", + "operationId": "getTask", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], - "summary": "List integrations", - "operationId": "listIntegrations", "responses": { "200": { - "description": "Integration list", + "description": "Task details", "content": { "application/json": { "schema": { "type": "object", "properties": { - "integrations": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "config": { - "type": "object" - } - } - } + "task": { + "$ref": "#/components/schemas/Task" } } } @@ -5392,39 +6077,63 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } }, - "post": { + "put": { "tags": [ - "Admin" + "Tasks" + ], + "summary": "Update task", + "operationId": "updateTask", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], - "summary": "Integration actions (enable, disable, test, configure)", - "operationId": "integrationAction", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "action", - "id" - ], "properties": { - "action": { - "type": "string", - "enum": [ - "enable", - "disable", - "test", - "configure" - ] + "title": { + "type": "string" }, - "id": { + "description": { "type": "string" }, - "config": { + "status": { + "type": "string" + }, + "priority": { + "type": "string" + }, + "assigned_to": { + "type": "string" + }, + "due_date": { + "type": "string" + }, + "estimated_hours": { + "type": "number" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { "type": "object" } } @@ -5434,66 +6143,53 @@ }, "responses": { "200": { - "description": "Action applied", + "description": "Task updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "task": { + "$ref": "#/components/schemas/Task" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } - } - }, - "/api/spawn": { - "post": { + }, + "delete": { "tags": [ - "Admin" + "Tasks" ], - "summary": "Spawn agent process", - "operationId": "spawnAgent", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "agent" - ], - "properties": { - "agent": { - "type": "string" - }, - "task": { - "type": "string" - }, - "params": { - "type": "object" - } - } - } + "summary": "Delete task", + "operationId": "deleteTask", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" } } - }, + ], "responses": { "200": { - "description": "Agent spawned", + "description": "Task deleted", "content": { "application/json": { "schema": { @@ -5501,68 +6197,73 @@ "properties": { "success": { "type": "boolean" - }, - "session_id": { - "type": "string" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/standup": { - "get": { + "/api/tasks/{id}/broadcast": { + "post": { "tags": [ - "Admin" + "Tasks" ], - "summary": "Get standup report", - "operationId": "getStandupReport", + "summary": "Broadcast task to agents", + "operationId": "broadcastTask", "parameters": [ { - "name": "date", - "in": "query", + "name": "id", + "in": "path", + "required": true, "schema": { - "type": "string", - "format": "date" + "type": "integer" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agents": { + "type": "array", + "items": { + "type": "string" + } + }, + "message": { + "type": "string" + } + } + } + } + } + }, "responses": { "200": { - "description": "Standup report", + "description": "Task broadcast sent", "content": { "application/json": { "schema": { "type": "object", "properties": { - "date": { - "type": "string" - }, - "agents": { - "type": "array", - "items": { - "type": "object" - } - }, - "tasks_completed": { - "type": "integer" - }, - "tasks_in_progress": { - "type": "integer" + "success": { + "type": "boolean" }, - "highlights": { + "delivered_to": { "type": "array", "items": { "type": "string" @@ -5575,48 +6276,93 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/memory": { + "/api/tasks/{id}/comments": { "get": { "tags": [ - "Admin" + "Tasks" ], - "summary": "Get memory files", - "operationId": "getMemoryFiles", + "summary": "List task comments", + "operationId": "listTaskComments", "parameters": [ { - "name": "path", - "in": "query", + "name": "id", + "in": "path", + "required": true, "schema": { - "type": "string" + "type": "integer" } } ], "responses": { "200": { - "description": "Memory file contents", + "description": "Comment list", "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "properties": { + "comments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "task_id": { + "type": "integer" + }, + "author": { + "type": "string" + }, + "content": { + "type": "string" + }, + "created_at": { + "type": "integer" + } + } + } + } + } } } } }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } }, "post": { "tags": [ - "Admin" + "Tasks" + ], + "summary": "Add comment to task", + "operationId": "addTaskComment", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], - "summary": "Update memory file", - "operationId": "updateMemoryFile", "requestBody": { "required": true, "content": { @@ -5624,14 +6370,13 @@ "schema": { "type": "object", "required": [ - "path", "content" ], "properties": { - "path": { + "content": { "type": "string" }, - "content": { + "author": { "type": "string" } } @@ -5640,103 +6385,176 @@ } }, "responses": { - "200": { - "description": "Memory updated", + "201": { + "description": "Comment added", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" + "comment": { + "type": "object" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } } }, - "/api/search": { + "/api/tokens": { "get": { "tags": [ - "Admin" + "Tokens" ], - "summary": "Full-text search", - "operationId": "search", + "summary": "Query token usage", + "operationId": "getTokenUsage", "parameters": [ { - "name": "q", + "name": "action", "in": "query", - "required": true, "schema": { - "type": "string" + "type": "string", + "enum": [ + "list", + "stats", + "agent-costs", + "export", + "trends" + ], + "default": "list" } }, { - "name": "type", + "name": "timeframe", "in": "query", "schema": { "type": "string", "enum": [ - "tasks", - "agents", - "activities", + "hour", + "day", + "week", + "month", "all" - ] + ], + "default": "all" } }, { - "name": "limit", + "name": "format", "in": "query", + "description": "Export format (only for action=export)", "schema": { - "type": "integer", - "default": 20 + "type": "string", + "enum": [ + "json", + "csv" + ], + "default": "json" } } ], "responses": { "200": { - "description": "Search results", + "description": "Token usage data. Shape varies by action.", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "results": { - "type": "array", - "items": { - "type": "object", - "properties": { - "type": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "title": { - "type": "string" - }, - "snippet": { - "type": "string" - }, - "score": { - "type": "number" + "oneOf": [ + { + "type": "object", + "title": "ListResponse", + "properties": { + "usage": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TokenUsageRecord" } + }, + "total": { + "type": "integer" + }, + "timeframe": { + "type": "string" } } }, - "total": { - "type": "integer" + { + "type": "object", + "title": "StatsResponse", + "properties": { + "summary": { + "$ref": "#/components/schemas/TokenStats" + }, + "models": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/TokenStats" + } + }, + "sessions": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/TokenStats" + } + }, + "agents": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/TokenStats" + } + }, + "timeframe": { + "type": "string" + }, + "recordCount": { + "type": "integer" + } + } + }, + { + "type": "object", + "title": "TrendsResponse", + "properties": { + "trends": { + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string" + }, + "tokens": { + "type": "integer" + }, + "cost": { + "type": "number" + }, + "requests": { + "type": "integer" + } + } + } + }, + "timeframe": { + "type": "string" + } + } } - } + ] } } } @@ -5748,62 +6566,44 @@ "$ref": "#/components/responses/Unauthorized" } } - } - }, - "/api/backup": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Trigger backup", - "operationId": "triggerBackup", - "responses": { - "200": { - "description": "Backup completed", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "path": { - "type": "string" - }, - "size_bytes": { - "type": "integer" - } - } - } - } - } - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - } - } - } - }, - "/api/cleanup": { + }, "post": { "tags": [ - "Admin" + "Tokens" ], - "summary": "Trigger cleanup of old data", - "operationId": "triggerCleanup", + "summary": "Record token usage", + "operationId": "recordTokenUsage", "requestBody": { + "required": true, "content": { "application/json": { "schema": { "type": "object", + "required": [ + "model", + "sessionId", + "inputTokens", + "outputTokens" + ], "properties": { - "older_than_days": { - "type": "integer", - "default": 30 + "model": { + "type": "string" + }, + "sessionId": { + "type": "string" + }, + "inputTokens": { + "type": "integer" + }, + "outputTokens": { + "type": "integer" + }, + "operation": { + "type": "string", + "default": "chat_completion" + }, + "duration": { + "type": "number" } } } @@ -5812,7 +6612,7 @@ }, "responses": { "200": { - "description": "Cleanup results", + "description": "Usage recorded", "content": { "application/json": { "schema": { @@ -5821,14 +6621,17 @@ "success": { "type": "boolean" }, - "deleted": { - "type": "object" + "record": { + "$ref": "#/components/schemas/TokenUsageRecord" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -5838,52 +6641,28 @@ } } }, - "/api/export": { + "/api/webhooks": { "get": { "tags": [ - "Admin" - ], - "summary": "Export data", - "operationId": "exportData", - "parameters": [ - { - "name": "type", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "tasks", - "agents", - "activities", - "all" - ] - } - }, - { - "name": "format", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "json", - "csv" - ], - "default": "json" - } - } + "Webhooks" ], + "summary": "List webhooks", + "operationId": "listWebhooks", "responses": { "200": { - "description": "Exported data", + "description": "Webhook list with delivery stats", "content": { "application/json": { "schema": { - "type": "object" - } - }, - "text/csv": { - "schema": { - "type": "string" + "type": "object", + "properties": { + "webhooks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Webhook" + } + } + } } } } @@ -5895,68 +6674,103 @@ "$ref": "#/components/responses/Forbidden" } } - } - }, - "/api/super/tenants": { - "get": { + }, + "post": { "tags": [ - "Super Admin" + "Webhooks" ], - "summary": "List tenants", - "operationId": "listTenants", + "summary": "Create webhook", + "operationId": "createWebhook", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name", + "url" + ], + "properties": { + "name": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + }, + "events": { + "type": "array", + "items": { + "type": "string" + } + }, + "generate_secret": { + "type": "boolean", + "default": true + } + } + } + } + } + }, "responses": { "200": { - "description": "Tenant list", + "description": "Webhook created. Secret is only shown in full on creation.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "tenants": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "secret": { + "type": "string" + }, + "events": { "type": "array", "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "slug": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": "string" - }, - "linux_user": { - "type": "string" - }, - "created_at": { - "type": "integer" - } - } + "type": "string" } + }, + "enabled": { + "type": "boolean" + }, + "message": { + "type": "string" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Forbidden" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } }, - "post": { + "put": { "tags": [ - "Super Admin" + "Webhooks" ], - "summary": "Create tenant and bootstrap job", - "operationId": "createTenant", + "summary": "Update webhook", + "operationId": "updateWebhook", "requestBody": { "required": true, "content": { @@ -5964,21 +6778,30 @@ "schema": { "type": "object", "required": [ - "slug", - "name" + "id" ], "properties": { - "slug": { - "type": "string" + "id": { + "type": "integer" }, "name": { "type": "string" }, - "linux_user": { - "type": "string" + "url": { + "type": "string", + "format": "uri" + }, + "events": { + "type": "array", + "items": { + "type": "string" + } + }, + "enabled": { + "type": "boolean" }, - "config": { - "type": "object" + "regenerate_secret": { + "type": "boolean" } } } @@ -5986,12 +6809,24 @@ } }, "responses": { - "201": { - "description": "Tenant created with bootstrap job", + "200": { + "description": "Webhook updated", "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "secret": { + "type": "string", + "description": "Only present when regenerate_secret is true" + }, + "message": { + "type": "string" + } + } } } } @@ -6005,39 +6840,41 @@ "403": { "$ref": "#/components/responses/Forbidden" }, - "409": { - "description": "Tenant slug or linux user already exists", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } - } - }, - "/api/super/tenants/{id}/decommission": { - "post": { + }, + "delete": { "tags": [ - "Super Admin" + "Webhooks" ], - "summary": "Decommission tenant", - "operationId": "decommissionTenant", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" + "summary": "Delete webhook", + "operationId": "deleteWebhook", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer" + } + } + } } } - ], + }, "responses": { "200": { - "description": "Tenant decommissioned", + "description": "Webhook deleted", "content": { "application/json": { "schema": { @@ -6045,12 +6882,18 @@ "properties": { "success": { "type": "boolean" + }, + "deleted": { + "type": "integer" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, @@ -6059,26 +6902,46 @@ }, "404": { "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } } }, - "/api/super/provision-jobs": { + "/api/webhooks/deliveries": { "get": { "tags": [ - "Super Admin" + "Webhooks" + ], + "summary": "Get webhook delivery history", + "operationId": "getWebhookDeliveries", + "parameters": [ + { + "name": "webhook_id", + "in": "query", + "schema": { + "type": "integer" + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "default": 50 + } + } ], - "summary": "List provision jobs", - "operationId": "listProvisionJobs", "responses": { "200": { - "description": "Provision job list", + "description": "Delivery history", "content": { "application/json": { "schema": { "type": "object", "properties": { - "jobs": { + "deliveries": { "type": "array", "items": { "type": "object", @@ -6086,29 +6949,20 @@ "id": { "type": "integer" }, - "tenant_id": { + "webhook_id": { "type": "integer" }, - "type": { + "event": { "type": "string" }, - "status": { - "type": "string", - "enum": [ - "pending", - "running", - "completed", - "failed" - ] + "status_code": { + "type": "integer" }, - "output": { + "error": { "type": "string" }, "created_at": { "type": "integer" - }, - "completed_at": { - "type": "integer" } } } @@ -6125,13 +6979,15 @@ "$ref": "#/components/responses/Forbidden" } } - }, + } + }, + "/api/webhooks/retry": { "post": { "tags": [ - "Super Admin" + "Webhooks" ], - "summary": "Create provision job", - "operationId": "createProvisionJob", + "summary": "Retry a failed webhook delivery", + "operationId": "retryWebhookDelivery", "requestBody": { "required": true, "content": { @@ -6139,18 +6995,11 @@ "schema": { "type": "object", "required": [ - "tenant_id", - "type" + "delivery_id" ], "properties": { - "tenant_id": { + "delivery_id": { "type": "integer" - }, - "type": { - "type": "string" - }, - "params": { - "type": "object" } } } @@ -6158,52 +7007,55 @@ } }, "responses": { - "201": { - "description": "Job created", - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" + "200": { + "description": "Delivery retried" } } } }, - "/api/super/provision-jobs/{id}": { - "get": { + "/api/webhooks/test": { + "post": { "tags": [ - "Super Admin" + "Webhooks" ], - "summary": "Get provision job details", - "operationId": "getProvisionJob", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" + "summary": "Test webhook", + "operationId": "testWebhook", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer" + } + } + } } } - ], + }, "responses": { "200": { - "description": "Job details", + "description": "Test result", "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "status_code": { + "type": "integer" + }, + "response_time_ms": { + "type": "number" + } + } } } } @@ -6220,36 +7072,69 @@ } } }, - "/api/super/provision-jobs/{id}/run": { - "post": { + "/api/webhooks/verify-docs": { + "get": { "tags": [ - "Super Admin" + "Webhooks" ], - "summary": "Run provision job", - "operationId": "runProvisionJob", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "integer" - } + "summary": "Get webhook verification documentation", + "operationId": "getWebhookVerifyDocs", + "responses": { + "200": { + "description": "Verification guide and examples" } + } + } + }, + "/api/workflows": { + "get": { + "tags": [ + "Workflows" ], + "summary": "List workflow templates", + "operationId": "listWorkflows", "responses": { "200": { - "description": "Job started", + "description": "Workflow template list", "content": { "application/json": { "schema": { "type": "object", "properties": { - "success": { - "type": "boolean" - }, - "status": { - "type": "string" + "templates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "type": "object" + } + }, + "created_by": { + "type": "string" + }, + "use_count": { + "type": "integer" + }, + "created_at": { + "type": "integer" + }, + "updated_at": { + "type": "integer" + } + } + } } } } @@ -6258,24 +7143,15 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" } } - } - }, - "/api/connect": { + }, "post": { "tags": [ - "Connections" + "Workflows" ], - "summary": "Register a direct CLI connection", - "description": "Registers a CLI tool directly without a gateway. Auto-creates agent if name doesn't exist.", - "operationId": "registerConnection", + "summary": "Create workflow template", + "operationId": "createWorkflow", "requestBody": { "required": true, "content": { @@ -6283,24 +7159,32 @@ "schema": { "type": "object", "required": [ - "tool_name", - "agent_name" + "name", + "steps" ], "properties": { - "tool_name": { - "type": "string" - }, - "tool_version": { - "type": "string" - }, - "agent_name": { + "name": { "type": "string" }, - "agent_role": { + "description": { "type": "string" }, - "metadata": { - "type": "object" + "steps": { + "type": "array", + "items": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "action": { + "type": "string" + }, + "params": { + "type": "object" + } + } + } } } } @@ -6308,37 +7192,15 @@ } }, "responses": { - "200": { - "description": "Connection registered", + "201": { + "description": "Template created", "content": { "application/json": { "schema": { "type": "object", "properties": { - "connection_id": { - "type": "string", - "format": "uuid" - }, - "agent_id": { - "type": "integer" - }, - "agent_name": { - "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "connected" - ] - }, - "sse_url": { - "type": "string" - }, - "heartbeat_url": { - "type": "string" - }, - "token_report_url": { - "type": "string" + "template": { + "type": "object" } } } @@ -6350,79 +7212,87 @@ }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "429": { + "$ref": "#/components/responses/RateLimited" } } }, - "get": { + "put": { "tags": [ - "Connections" + "Workflows" ], - "summary": "List all direct connections", - "operationId": "listConnections", + "summary": "Update workflow template", + "operationId": "updateWorkflow", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, "responses": { "200": { - "description": "List of connections", + "description": "Template updated", "content": { "application/json": { "schema": { "type": "object", "properties": { - "connections": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "agent_id": { - "type": "integer" - }, - "agent_name": { - "type": "string" - }, - "tool_name": { - "type": "string" - }, - "tool_version": { - "type": "string" - }, - "connection_id": { - "type": "string", - "format": "uuid" - }, - "status": { - "type": "string", - "enum": [ - "connected", - "disconnected" - ] - }, - "last_heartbeat": { - "type": "integer" - }, - "created_at": { - "type": "integer" - } - } - } + "template": { + "type": "object" } } } } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" } } }, "delete": { "tags": [ - "Connections" + "Workflows" ], - "summary": "Disconnect a CLI connection", - "operationId": "disconnectConnection", + "summary": "Delete workflow template", + "operationId": "deleteWorkflow", "requestBody": { "required": true, "content": { @@ -6430,12 +7300,11 @@ "schema": { "type": "object", "required": [ - "connection_id" + "id" ], "properties": { - "connection_id": { - "type": "string", - "format": "uuid" + "id": { + "type": "integer" } } } @@ -6444,32 +7313,26 @@ }, "responses": { "200": { - "description": "Disconnected", + "description": "Template deleted", "content": { "application/json": { "schema": { "type": "object", "properties": { - "status": { - "type": "string", - "enum": [ - "disconnected" - ] - }, - "connection_id": { - "type": "string" + "success": { + "type": "boolean" } } } } } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, "401": { "$ref": "#/components/responses/Unauthorized" }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, "404": { "$ref": "#/components/responses/NotFound" } @@ -6822,6 +7685,26 @@ "type": "integer" } } + }, + "Project": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "created_at": { + "type": "integer" + }, + "updated_at": { + "type": "integer" + } + } } }, "responses": { diff --git a/package.json b/package.json index 7cb728938a8ba4d14ed7442bcada0e0959f24d05..91ec7a0e06ef42947a706b17590b7381ea74359c 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,18 @@ "version": "1.3.0", "description": "OpenClaw Mission Control — open-source agent orchestration dashboard", "scripts": { - "dev": "next dev --hostname 127.0.0.1", + "dev": "next dev --hostname 127.0.0.1 --port ${PORT:-3000}", "build": "next build", - "start": "next start --hostname 0.0.0.0 --port 3005", + "start": "next start --hostname 0.0.0.0 --port ${PORT:-3000}", "lint": "eslint .", "typecheck": "tsc --noEmit", "test": "vitest run", "test:watch": "vitest", "test:ui": "vitest --ui", "test:e2e": "playwright test", + "test:e2e:openclaw:local": "E2E_GATEWAY_EXPECTED=0 playwright test -c playwright.openclaw.local.config.ts", + "test:e2e:openclaw:gateway": "E2E_GATEWAY_EXPECTED=1 playwright test -c playwright.openclaw.gateway.config.ts", + "test:e2e:openclaw": "pnpm test:e2e:openclaw:local && pnpm test:e2e:openclaw:gateway", "test:all": "pnpm lint && pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e", "quality:gate": "pnpm test:all" }, @@ -77,4 +80,4 @@ "better-sqlite3" ] } -} \ No newline at end of file +} diff --git a/playwright.config.ts b/playwright.config.ts index 9a9781596815a36b29c6c3e9c6e0ea44bd4b5611..854a1826435be8f487f20c2dba71ad4e1571c1e9 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -2,6 +2,7 @@ import { defineConfig, devices } from '@playwright/test' export default defineConfig({ testDir: 'tests', + testIgnore: /openclaw-harness\.spec\.ts/, timeout: 60_000, expect: { timeout: 10_000 @@ -17,9 +18,23 @@ export default defineConfig({ { name: 'chromium', use: { ...devices['Desktop Chrome'] } } ], webServer: { - command: 'pnpm start', + command: 'node .next/standalone/server.js', url: 'http://127.0.0.1:3005', reuseExistingServer: true, - timeout: 30_000, + timeout: 120_000, + env: { + ...process.env, + HOSTNAME: process.env.HOSTNAME || '127.0.0.1', + PORT: process.env.PORT || '3005', + MC_DISABLE_RATE_LIMIT: process.env.MC_DISABLE_RATE_LIMIT || '1', + MC_WORKLOAD_QUEUE_DEPTH_THROTTLE: process.env.MC_WORKLOAD_QUEUE_DEPTH_THROTTLE || '1000', + MC_WORKLOAD_QUEUE_DEPTH_SHED: process.env.MC_WORKLOAD_QUEUE_DEPTH_SHED || '2000', + MC_WORKLOAD_ERROR_RATE_THROTTLE: process.env.MC_WORKLOAD_ERROR_RATE_THROTTLE || '1', + MC_WORKLOAD_ERROR_RATE_SHED: process.env.MC_WORKLOAD_ERROR_RATE_SHED || '1', + API_KEY: process.env.API_KEY || 'test-api-key-e2e-12345', + AUTH_USER: process.env.AUTH_USER || 'testadmin', + AUTH_PASS: process.env.AUTH_PASS || 'testpass1234!', + OPENCLAW_MEMORY_DIR: process.env.OPENCLAW_MEMORY_DIR || '.data/e2e-memory', + }, } }) diff --git a/playwright.openclaw.gateway.config.ts b/playwright.openclaw.gateway.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..8df49dc0a328500ba27f9cbf7f23d8dcaa2ab684 --- /dev/null +++ b/playwright.openclaw.gateway.config.ts @@ -0,0 +1,26 @@ +import { defineConfig, devices } from '@playwright/test' + +export default defineConfig({ + testDir: 'tests', + testMatch: /openclaw-harness\.spec\.ts/, + timeout: 60_000, + expect: { + timeout: 10_000, + }, + fullyParallel: false, + workers: 1, + reporter: [['list']], + use: { + baseURL: 'http://127.0.0.1:3005', + trace: 'retain-on-failure', + }, + projects: [ + { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, + ], + webServer: { + command: 'node scripts/e2e-openclaw/start-e2e-server.mjs --mode=gateway', + url: 'http://127.0.0.1:3005', + reuseExistingServer: false, + timeout: 120_000, + }, +}) diff --git a/playwright.openclaw.local.config.ts b/playwright.openclaw.local.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec80cf250a36c3c609ea61f1e6ba62f850aebcc8 --- /dev/null +++ b/playwright.openclaw.local.config.ts @@ -0,0 +1,26 @@ +import { defineConfig, devices } from '@playwright/test' + +export default defineConfig({ + testDir: 'tests', + testMatch: /openclaw-harness\.spec\.ts/, + timeout: 60_000, + expect: { + timeout: 10_000, + }, + fullyParallel: false, + workers: 1, + reporter: [['list']], + use: { + baseURL: 'http://127.0.0.1:3005', + trace: 'retain-on-failure', + }, + projects: [ + { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, + ], + webServer: { + command: 'node scripts/e2e-openclaw/start-e2e-server.mjs --mode=local', + url: 'http://127.0.0.1:3005', + reuseExistingServer: false, + timeout: 120_000, + }, +}) diff --git a/scripts/e2e-openclaw/bin/clawdbot b/scripts/e2e-openclaw/bin/clawdbot new file mode 100755 index 0000000000000000000000000000000000000000..0aa1e80b491c33c908ddc46ef92328cce562e926 --- /dev/null +++ b/scripts/e2e-openclaw/bin/clawdbot @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${1:-}" == "--version" ]]; then + echo "clawdbot 2026.3.2" + exit 0 +fi + +if [[ "${1:-}" == "-c" ]]; then + cmd="${2:-}" + if [[ "$cmd" == sessions_spawn* ]]; then + echo "Session created: mock-clawdbot-session" + exit 0 + fi + echo "ok" + exit 0 +fi + +echo "clawdbot mock: unsupported args: $*" >&2 +exit 0 diff --git a/scripts/e2e-openclaw/bin/openclaw b/scripts/e2e-openclaw/bin/openclaw new file mode 100755 index 0000000000000000000000000000000000000000..38c4a1c1b39f444c4c24ab659b2ce7ea12a5b47d --- /dev/null +++ b/scripts/e2e-openclaw/bin/openclaw @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${1:-}" == "--version" ]]; then + echo "openclaw 2026.3.2" + exit 0 +fi + +if [[ "${1:-}" == "-c" ]]; then + cmd="${2:-}" + if [[ "$cmd" == sessions_spawn* ]]; then + echo "Session created: mock-openclaw-session" + exit 0 + fi + echo "ok" + exit 0 +fi + +echo "openclaw mock: unsupported args: $*" >&2 +exit 0 diff --git a/scripts/e2e-openclaw/mock-gateway.mjs b/scripts/e2e-openclaw/mock-gateway.mjs new file mode 100755 index 0000000000000000000000000000000000000000..e3ff06313600dd5de91cd011d35851e108a3602b --- /dev/null +++ b/scripts/e2e-openclaw/mock-gateway.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node +import http from 'node:http' +import { WebSocketServer } from 'ws' + +const host = process.env.OPENCLAW_GATEWAY_HOST || '127.0.0.1' +const port = Number(process.env.OPENCLAW_GATEWAY_PORT || 18789) + +const server = http.createServer((req, res) => { + if (!req.url) { + res.writeHead(404) + res.end() + return + } + + if (req.url === '/health') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ ok: true, service: 'openclaw-mock-gateway' })) + return + } + + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ ok: true })) +}) + +const wss = new WebSocketServer({ noServer: true }) + +wss.on('connection', (ws) => { + ws.send(JSON.stringify({ type: 'status', connected: true, source: 'mock-gateway' })) + ws.on('message', (raw) => { + const text = raw.toString() + if (text.includes('ping')) { + ws.send(JSON.stringify({ type: 'pong', ts: Date.now() })) + return + } + ws.send(JSON.stringify({ type: 'event', message: 'ack', raw: text })) + }) +}) + +server.on('upgrade', (req, socket, head) => { + wss.handleUpgrade(req, socket, head, (ws) => { + wss.emit('connection', ws, req) + }) +}) + +server.listen(port, host, () => { + process.stdout.write(`[openclaw-mock-gateway] listening on ${host}:${port}\n`) +}) + +function shutdown() { + wss.clients.forEach((client) => { + try { + client.close() + } catch { + // noop + } + }) + server.close(() => process.exit(0)) +} + +process.on('SIGINT', shutdown) +process.on('SIGTERM', shutdown) diff --git a/scripts/e2e-openclaw/start-e2e-server.mjs b/scripts/e2e-openclaw/start-e2e-server.mjs new file mode 100755 index 0000000000000000000000000000000000000000..35703b0df2e69cfbe08634fe6607a61006ff0cfd --- /dev/null +++ b/scripts/e2e-openclaw/start-e2e-server.mjs @@ -0,0 +1,99 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' + +const modeArg = process.argv.find((arg) => arg.startsWith('--mode=')) +const mode = modeArg ? modeArg.split('=')[1] : 'local' +if (mode !== 'local' && mode !== 'gateway') { + process.stderr.write(`Invalid mode: ${mode}\n`) + process.exit(1) +} + +const repoRoot = process.cwd() +const fixtureSource = path.join(repoRoot, 'tests', 'fixtures', 'openclaw') +const runtimeRoot = path.join(repoRoot, '.tmp', 'e2e-openclaw', mode) +const dataDir = path.join(runtimeRoot, 'data') +const mockBinDir = path.join(repoRoot, 'scripts', 'e2e-openclaw', 'bin') + +fs.rmSync(runtimeRoot, { recursive: true, force: true }) +fs.mkdirSync(runtimeRoot, { recursive: true }) +fs.mkdirSync(dataDir, { recursive: true }) +fs.cpSync(fixtureSource, runtimeRoot, { recursive: true }) + +const gatewayHost = '127.0.0.1' +const gatewayPort = '18789' + +const baseEnv = { + ...process.env, + API_KEY: process.env.API_KEY || 'test-api-key-e2e-12345', + AUTH_USER: process.env.AUTH_USER || 'admin', + AUTH_PASS: process.env.AUTH_PASS || 'admin', + MC_DISABLE_RATE_LIMIT: '1', + MISSION_CONTROL_DATA_DIR: dataDir, + MISSION_CONTROL_DB_PATH: path.join(dataDir, 'mission-control.db'), + OPENCLAW_STATE_DIR: runtimeRoot, + OPENCLAW_CONFIG_PATH: path.join(runtimeRoot, 'openclaw.json'), + OPENCLAW_GATEWAY_HOST: gatewayHost, + OPENCLAW_GATEWAY_PORT: gatewayPort, + OPENCLAW_BIN: path.join(mockBinDir, 'openclaw'), + CLAWDBOT_BIN: path.join(mockBinDir, 'clawdbot'), + PATH: `${mockBinDir}:${process.env.PATH || ''}`, + E2E_GATEWAY_EXPECTED: mode === 'gateway' ? '1' : '0', +} + +const children = [] + +if (mode === 'gateway') { + const gw = spawn('node', ['scripts/e2e-openclaw/mock-gateway.mjs'], { + cwd: repoRoot, + env: baseEnv, + stdio: 'inherit', + }) + children.push(gw) +} + +const standaloneServerPath = path.join(repoRoot, '.next', 'standalone', 'server.js') +const app = fs.existsSync(standaloneServerPath) + ? spawn('node', [standaloneServerPath], { + cwd: repoRoot, + env: { + ...baseEnv, + HOSTNAME: '127.0.0.1', + PORT: '3005', + }, + stdio: 'inherit', + }) + : spawn('pnpm', ['start'], { + cwd: repoRoot, + env: baseEnv, + stdio: 'inherit', + }) +children.push(app) + +function shutdown(signal = 'SIGTERM') { + for (const child of children) { + if (!child.killed) { + try { + child.kill(signal) + } catch { + // noop + } + } + } +} + +process.on('SIGINT', () => { + shutdown('SIGINT') + process.exit(130) +}) +process.on('SIGTERM', () => { + shutdown('SIGTERM') + process.exit(143) +}) + +app.on('exit', (code) => { + shutdown('SIGTERM') + process.exit(code ?? 0) +}) diff --git a/src/app/[[...panel]]/page.tsx b/src/app/[[...panel]]/page.tsx index ecfd9f0b36930d5564bf4659ceb8638dc772df1d..e7d05dd3818a2365de99773d282be614d48479b6 100644 --- a/src/app/[[...panel]]/page.tsx +++ b/src/app/[[...panel]]/page.tsx @@ -1,7 +1,7 @@ 'use client' import { useEffect, useState } from 'react' -import { usePathname } from 'next/navigation' +import { usePathname, useRouter } from 'next/navigation' import { NavRail } from '@/components/layout/nav-rail' import { HeaderBar } from '@/components/layout/header-bar' import { LiveFeed } from '@/components/layout/live-feed' @@ -42,6 +42,7 @@ import { useServerEvents } from '@/lib/use-server-events' import { useMissionControl } from '@/store' export default function Home() { + const router = useRouter() const { connect } = useWebSocket() const { activeTab, setActiveTab, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable, liveFeedOpen, toggleLiveFeed } = useMissionControl() @@ -62,7 +63,13 @@ export default function Home() { // Fetch current user fetch('/api/auth/me') - .then(res => res.ok ? res.json() : null) + .then(async (res) => { + if (res.ok) return res.json() + if (res.status === 401) { + router.replace(`/login?next=${encodeURIComponent(pathname)}`) + } + return null + }) .then(data => { if (data?.user) setCurrentUser(data.user) }) .catch(() => {}) @@ -120,7 +127,7 @@ export default function Home() { const wsUrl = explicitWsUrl || `${gatewayProto}://${gatewayHost}:${gatewayPort}` connect(wsUrl, wsToken) }) - }, [connect, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable]) + }, [connect, pathname, router, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable]) if (!isClient) { return ( @@ -140,6 +147,9 @@ export default function Home() { return (
+ + Skip to main content + {/* Left: Icon rail navigation (hidden on mobile, shown as bottom bar instead) */} @@ -149,7 +159,7 @@ export default function Home() { -
+
@@ -258,6 +268,8 @@ function ContentRouter({ tab }: { tab: string }) { return case 'super-admin': return + case 'workspaces': + return default: return } diff --git a/src/app/api/agents/[id]/attribution/route.ts b/src/app/api/agents/[id]/attribution/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..53f3456b2cfd9ddc5ce57a9f843c84fdfcdb7ac2 --- /dev/null +++ b/src/app/api/agents/[id]/attribution/route.ts @@ -0,0 +1,356 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { getDatabase } from '@/lib/db'; +import { requireRole } from '@/lib/auth'; +import { logger } from '@/lib/logger'; + +const ALLOWED_SECTIONS = new Set(['identity', 'audit', 'mutations', 'cost']); + +/** + * GET /api/agents/[id]/attribution - Agent-Level Identity & Attribution + * + * Returns a comprehensive audit trail and cost attribution report for + * a specific agent. Enables per-agent observability, debugging, and + * cost analysis in multi-agent environments. + * + * Query params: + * hours - Time window (default: 24, max: 720) + * section - Comma-separated: audit,cost,mutations,identity (default: all) + * + * Response: + * identity - Agent profile, status, and session info + * audit - Full audit trail of agent actions + * mutations - Task/memory/soul changes attributed to this agent + * cost - Token usage and cost breakdown per model + */ +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const auth = requireRole(request, 'viewer'); + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }); + + try { + const db = getDatabase(); + const resolvedParams = await params; + const agentId = resolvedParams.id; + const workspaceId = auth.user.workspace_id ?? 1; + + // Resolve agent + let agent: any; + if (/^\d+$/.test(agentId)) { + agent = db.prepare('SELECT * FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId); + } else { + agent = db.prepare('SELECT * FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId); + } + + if (!agent) { + return NextResponse.json({ error: 'Agent not found' }, { status: 404 }); + } + + const { searchParams } = new URL(request.url); + const privileged = searchParams.get('privileged') === '1'; + const isSelfByHeader = auth.user.agent_name === agent.name; + const isSelfByUsername = auth.user.username === agent.name; + const isSelf = isSelfByHeader || isSelfByUsername; + const isPrivileged = auth.user.role === 'admin' && privileged; + if (!isSelf && !isPrivileged) { + return NextResponse.json( + { error: 'Forbidden: attribution is self-scope by default. Admin can use ?privileged=1 override.' }, + { status: 403 } + ); + } + + const hoursRaw = searchParams.get('hours'); + const hours = parseHours(hoursRaw); + if (!hours) { + return NextResponse.json({ error: 'Invalid hours. Expected integer 1..720.' }, { status: 400 }); + } + + const sections = parseSections(searchParams.get('section')); + if ('error' in sections) { + return NextResponse.json({ error: sections.error }, { status: 400 }); + } + + const now = Math.floor(Date.now() / 1000); + const since = now - hours * 3600; + + const result: Record = { + agent_name: agent.name, + timeframe: { hours, since, until: now }, + access_scope: isSelf ? 'self' : 'privileged', + }; + + if (sections.sections.has('identity')) { + result.identity = buildIdentity(db, agent, workspaceId); + } + + if (sections.sections.has('audit')) { + result.audit = buildAuditTrail(db, agent.name, workspaceId, since); + } + + if (sections.sections.has('mutations')) { + result.mutations = buildMutations(db, agent.name, workspaceId, since); + } + + if (sections.sections.has('cost')) { + result.cost = buildCostAttribution(db, agent.name, workspaceId, since); + } + + return NextResponse.json(result); + } catch (error) { + logger.error({ err: error }, 'GET /api/agents/[id]/attribution error'); + return NextResponse.json({ error: 'Failed to fetch attribution data' }, { status: 500 }); + } +} + +/** Agent identity and profile info */ +function buildIdentity(db: any, agent: any, workspaceId: number) { + const config = safeParseJson(agent.config, {}); + + // Count total tasks ever assigned + const taskStats = db.prepare(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed, + SUM(CASE WHEN status IN ('assigned', 'in_progress') THEN 1 ELSE 0 END) as active + FROM tasks WHERE assigned_to = ? AND workspace_id = ? + `).get(agent.name, workspaceId) as any; + + // Count comments authored + const commentCount = (db.prepare( + `SELECT COUNT(*) as c FROM comments WHERE author = ? AND workspace_id = ?` + ).get(agent.name, workspaceId) as any).c; + + return { + id: agent.id, + name: agent.name, + role: agent.role, + status: agent.status, + last_seen: agent.last_seen, + last_activity: agent.last_activity, + created_at: agent.created_at, + session_key: agent.session_key ? '***' : null, // Masked for security + has_soul: !!agent.soul_content, + config_keys: Object.keys(config), + lifetime_stats: { + tasks_total: taskStats?.total || 0, + tasks_completed: taskStats?.completed || 0, + tasks_active: taskStats?.active || 0, + comments_authored: commentCount, + }, + }; +} + +/** Audit trail — all activities attributed to this agent */ +function buildAuditTrail(db: any, agentName: string, workspaceId: number, since: number) { + // Activities where this agent is the actor + const activities = db.prepare(` + SELECT id, type, entity_type, entity_id, description, data, created_at + FROM activities + WHERE actor = ? AND workspace_id = ? AND created_at >= ? + ORDER BY created_at DESC + LIMIT 200 + `).all(agentName, workspaceId, since) as any[]; + + // Audit log entries (system-wide, may reference agent) + let auditEntries: any[] = []; + try { + auditEntries = db.prepare(` + SELECT id, action, actor, detail, created_at + FROM audit_log + WHERE (actor = ? OR detail LIKE ?) AND created_at >= ? + ORDER BY created_at DESC + LIMIT 100 + `).all(agentName, `%${agentName}%`, since) as any[]; + } catch { + // audit_log table may not exist + } + + // Group activities by type for summary + const byType: Record = {}; + for (const a of activities) { + byType[a.type] = (byType[a.type] || 0) + 1; + } + + return { + total_activities: activities.length, + by_type: byType, + activities: activities.map(a => ({ + ...a, + data: safeParseJson(a.data, null), + })), + audit_log_entries: auditEntries.map(e => ({ + ...e, + detail: safeParseJson(e.detail, null), + })), + }; +} + +/** Mutations — task changes, comments, status transitions */ +function buildMutations(db: any, agentName: string, workspaceId: number, since: number) { + // Task mutations (created, updated, status changes) + const taskMutations = db.prepare(` + SELECT id, type, entity_type, entity_id, description, data, created_at + FROM activities + WHERE actor = ? AND workspace_id = ? AND created_at >= ? + AND entity_type = 'task' + AND type IN ('task_created', 'task_updated', 'task_status_change', 'task_assigned') + ORDER BY created_at DESC + LIMIT 100 + `).all(agentName, workspaceId, since) as any[]; + + // Comments authored + const comments = db.prepare(` + SELECT c.id, c.task_id, c.content, c.created_at, c.mentions, t.title as task_title + FROM comments c + LEFT JOIN tasks t ON c.task_id = t.id AND t.workspace_id = ? + WHERE c.author = ? AND c.workspace_id = ? AND c.created_at >= ? + ORDER BY c.created_at DESC + LIMIT 50 + `).all(workspaceId, agentName, workspaceId, since) as any[]; + + // Agent status changes (by heartbeat or others) + const statusChanges = db.prepare(` + SELECT id, type, description, data, created_at + FROM activities + WHERE entity_type = 'agent' AND workspace_id = ? + AND created_at >= ? + AND (actor = ? OR description LIKE ?) + ORDER BY created_at DESC + LIMIT 50 + `).all(workspaceId, since, agentName, `%${agentName}%`) as any[]; + + return { + task_mutations: taskMutations.map(m => ({ + ...m, + data: safeParseJson(m.data, null), + })), + comments: comments.map(c => ({ + ...c, + mentions: safeParseJson(c.mentions, []), + content_preview: c.content?.substring(0, 200) || '', + })), + status_changes: statusChanges.map(s => ({ + ...s, + data: safeParseJson(s.data, null), + })), + summary: { + task_mutations_count: taskMutations.length, + comments_count: comments.length, + status_changes_count: statusChanges.length, + }, + }; +} + +/** Cost attribution — token usage per model */ +function buildCostAttribution(db: any, agentName: string, workspaceId: number, since: number) { + try { + const byModel = db.prepare(` + SELECT model, + COUNT(*) as request_count, + SUM(input_tokens) as input_tokens, + SUM(output_tokens) as output_tokens + FROM token_usage + WHERE session_id = ? AND workspace_id = ? AND created_at >= ? + GROUP BY model + ORDER BY (input_tokens + output_tokens) DESC + `).all(agentName, workspaceId, since) as Array<{ + model: string; request_count: number; input_tokens: number; output_tokens: number + }>; + + // Also check session IDs that contain the agent name (e.g. "agentname:cli") + const byModelAlt = db.prepare(` + SELECT model, + COUNT(*) as request_count, + SUM(input_tokens) as input_tokens, + SUM(output_tokens) as output_tokens + FROM token_usage + WHERE session_id LIKE ? AND session_id != ? AND workspace_id = ? AND created_at >= ? + GROUP BY model + ORDER BY (input_tokens + output_tokens) DESC + `).all(`${agentName}:%`, agentName, workspaceId, since) as Array<{ + model: string; request_count: number; input_tokens: number; output_tokens: number + }>; + + // Merge results + const merged = new Map(); + for (const row of [...byModel, ...byModelAlt]) { + const existing = merged.get(row.model); + if (existing) { + existing.request_count += row.request_count; + existing.input_tokens += row.input_tokens; + existing.output_tokens += row.output_tokens; + } else { + merged.set(row.model, { ...row }); + } + } + + const models = Array.from(merged.values()); + const total = models.reduce((acc, r) => ({ + input_tokens: acc.input_tokens + r.input_tokens, + output_tokens: acc.output_tokens + r.output_tokens, + requests: acc.requests + r.request_count, + }), { input_tokens: 0, output_tokens: 0, requests: 0 }); + + // Daily breakdown for trend + const daily = db.prepare(` + SELECT (created_at / 86400) * 86400 as day_bucket, + SUM(input_tokens) as input_tokens, + SUM(output_tokens) as output_tokens, + COUNT(*) as requests + FROM token_usage + WHERE (session_id = ? OR session_id LIKE ?) AND workspace_id = ? AND created_at >= ? + GROUP BY day_bucket + ORDER BY day_bucket ASC + `).all(agentName, `${agentName}:%`, workspaceId, since) as any[]; + + return { + by_model: models, + total, + daily_trend: daily.map(d => ({ + date: new Date(d.day_bucket * 1000).toISOString().split('T')[0], + ...d, + })), + }; + } catch { + return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 }, daily_trend: [] }; + } +} + +function parseHours(hoursRaw: string | null): number | null { + if (!hoursRaw || hoursRaw.trim() === '') return 24; + if (!/^\d+$/.test(hoursRaw)) return null; + const hours = Number(hoursRaw); + if (!Number.isInteger(hours) || hours < 1 || hours > 720) return null; + return hours; +} + +function parseSections( + sectionRaw: string | null +): { sections: Set } | { error: string } { + const value = (sectionRaw || 'identity,audit,mutations,cost').trim(); + const parsed = value + .split(',') + .map((section) => section.trim()) + .filter(Boolean); + + if (parsed.length === 0) { + return { error: 'Invalid section. Expected one or more of identity,audit,mutations,cost.' }; + } + + const invalid = parsed.filter((section) => !ALLOWED_SECTIONS.has(section)); + if (invalid.length > 0) { + return { error: `Invalid section value(s): ${invalid.join(', ')}` }; + } + + return { sections: new Set(parsed) }; +} + +function safeParseJson(raw: string | null | undefined, fallback: T): T { + if (!raw) return fallback; + try { + return JSON.parse(raw) as T; + } catch { + return fallback; + } +} diff --git a/src/app/api/agents/[id]/diagnostics/route.ts b/src/app/api/agents/[id]/diagnostics/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..48108437d594c7e8dc79c935b572f34ef1365312 --- /dev/null +++ b/src/app/api/agents/[id]/diagnostics/route.ts @@ -0,0 +1,343 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { getDatabase } from '@/lib/db'; +import { requireRole } from '@/lib/auth'; +import { logger } from '@/lib/logger'; + +const ALLOWED_SECTIONS = ['summary', 'tasks', 'errors', 'activity', 'trends', 'tokens'] as const; +type DiagnosticsSection = (typeof ALLOWED_SECTIONS)[number]; + +function parseHoursParam(raw: string | null): { value?: number; error?: string } { + if (raw === null) return { value: 24 }; + const parsed = Number(raw); + if (!Number.isInteger(parsed)) { + return { error: 'hours must be an integer between 1 and 720' }; + } + if (parsed < 1 || parsed > 720) { + return { error: 'hours must be between 1 and 720' }; + } + return { value: parsed }; +} + +function parseSectionsParam(raw: string | null): { value?: Set; error?: string } { + if (!raw || raw.trim().length === 0) { + return { value: new Set(ALLOWED_SECTIONS) }; + } + + const requested = raw + .split(',') + .map((section) => section.trim()) + .filter(Boolean); + + if (requested.length === 0) { + return { error: 'section must include at least one valid value' }; + } + + const invalid = requested.filter((section) => !ALLOWED_SECTIONS.includes(section as DiagnosticsSection)); + if (invalid.length > 0) { + return { error: `Invalid section value(s): ${invalid.join(', ')}` }; + } + + return { value: new Set(requested as DiagnosticsSection[]) }; +} + +/** + * GET /api/agents/[id]/diagnostics - Agent Self-Diagnostics API + * + * Provides an agent with its own performance metrics, error analysis, + * and trend data so it can self-optimize. + * + * Query params: + * hours - Time window in hours (default: 24, max: 720 = 30 days) + * section - Comma-separated sections to include (default: all) + * Options: summary, tasks, errors, activity, trends, tokens + * + * Response includes: + * summary - High-level KPIs (throughput, error rate, activity count) + * tasks - Task completion breakdown by status and priority + * errors - Error frequency, types, and recent error details + * activity - Activity breakdown by type with hourly timeline + * trends - Multi-period comparison for trend detection + * tokens - Token usage by model with cost estimates + */ +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const auth = requireRole(request, 'viewer'); + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }); + + try { + const db = getDatabase(); + const resolvedParams = await params; + const agentId = resolvedParams.id; + const workspaceId = auth.user.workspace_id ?? 1; + + // Resolve agent by ID or name + let agent: any; + if (/^\d+$/.test(agentId)) { + agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId); + } else { + agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId); + } + + if (!agent) { + return NextResponse.json({ error: 'Agent not found' }, { status: 404 }); + } + + const { searchParams } = new URL(request.url); + const requesterAgentName = (request.headers.get('x-agent-name') || '').trim(); + const privileged = searchParams.get('privileged') === '1'; + const isSelfRequest = (requesterAgentName || auth.user.username) === agent.name; + + // Self-only by default. Cross-agent access requires explicit privileged override. + if (!isSelfRequest && !(privileged && auth.user.role === 'admin')) { + return NextResponse.json( + { error: 'Diagnostics are self-scoped. Use privileged=1 with admin role for cross-agent access.' }, + { status: 403 } + ); + } + + const parsedHours = parseHoursParam(searchParams.get('hours')); + if (parsedHours.error) { + return NextResponse.json({ error: parsedHours.error }, { status: 400 }); + } + + const parsedSections = parseSectionsParam(searchParams.get('section')); + if (parsedSections.error) { + return NextResponse.json({ error: parsedSections.error }, { status: 400 }); + } + + const hours = parsedHours.value as number; + const sections = parsedSections.value as Set; + + const now = Math.floor(Date.now() / 1000); + const since = now - hours * 3600; + + const result: Record = { + agent: { id: agent.id, name: agent.name, role: agent.role, status: agent.status }, + timeframe: { hours, since, until: now }, + }; + + if (sections.has('summary')) { + result.summary = buildSummary(db, agent.name, workspaceId, since); + } + + if (sections.has('tasks')) { + result.tasks = buildTaskMetrics(db, agent.name, workspaceId, since); + } + + if (sections.has('errors')) { + result.errors = buildErrorAnalysis(db, agent.name, workspaceId, since); + } + + if (sections.has('activity')) { + result.activity = buildActivityBreakdown(db, agent.name, workspaceId, since); + } + + if (sections.has('trends')) { + result.trends = buildTrends(db, agent.name, workspaceId, hours); + } + + if (sections.has('tokens')) { + result.tokens = buildTokenMetrics(db, agent.name, workspaceId, since); + } + + return NextResponse.json(result); + } catch (error) { + logger.error({ err: error }, 'GET /api/agents/[id]/diagnostics error'); + return NextResponse.json({ error: 'Failed to fetch diagnostics' }, { status: 500 }); + } +} + +/** High-level KPIs */ +function buildSummary(db: any, agentName: string, workspaceId: number, since: number) { + const tasksDone = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ?` + ).get(agentName, workspaceId, since) as any).c; + + const tasksTotal = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ?` + ).get(agentName, workspaceId) as any).c; + + const activityCount = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ?` + ).get(agentName, workspaceId, since) as any).c; + + const errorCount = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND type LIKE '%error%'` + ).get(agentName, workspaceId, since) as any).c; + + const errorRate = activityCount > 0 ? Math.round((errorCount / activityCount) * 10000) / 100 : 0; + + return { + tasks_completed: tasksDone, + tasks_total: tasksTotal, + activity_count: activityCount, + error_count: errorCount, + error_rate_percent: errorRate, + }; +} + +/** Task completion breakdown */ +function buildTaskMetrics(db: any, agentName: string, workspaceId: number, since: number) { + const byStatus = db.prepare( + `SELECT status, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY status` + ).all(agentName, workspaceId) as Array<{ status: string; count: number }>; + + const byPriority = db.prepare( + `SELECT priority, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY priority` + ).all(agentName, workspaceId) as Array<{ priority: string; count: number }>; + + const recentCompleted = db.prepare( + `SELECT id, title, priority, updated_at FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? ORDER BY updated_at DESC LIMIT 10` + ).all(agentName, workspaceId, since) as any[]; + + // Estimate throughput: tasks completed per day in the window + const windowDays = Math.max((Math.floor(Date.now() / 1000) - since) / 86400, 1); + const completedInWindow = recentCompleted.length; + const throughputPerDay = Math.round((completedInWindow / windowDays) * 100) / 100; + + return { + by_status: Object.fromEntries(byStatus.map(r => [r.status, r.count])), + by_priority: Object.fromEntries(byPriority.map(r => [r.priority, r.count])), + recent_completed: recentCompleted, + throughput_per_day: throughputPerDay, + }; +} + +/** Error frequency and analysis */ +function buildErrorAnalysis(db: any, agentName: string, workspaceId: number, since: number) { + const errorActivities = db.prepare( + `SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') GROUP BY type ORDER BY count DESC` + ).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>; + + const recentErrors = db.prepare( + `SELECT id, type, description, data, created_at FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') ORDER BY created_at DESC LIMIT 20` + ).all(agentName, workspaceId, since) as any[]; + + return { + by_type: errorActivities, + total: errorActivities.reduce((sum, e) => sum + e.count, 0), + recent: recentErrors.map(e => ({ + ...e, + data: e.data ? JSON.parse(e.data) : null, + })), + }; +} + +/** Activity breakdown with hourly timeline */ +function buildActivityBreakdown(db: any, agentName: string, workspaceId: number, since: number) { + const byType = db.prepare( + `SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY type ORDER BY count DESC` + ).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>; + + const timeline = db.prepare( + `SELECT (created_at / 3600) * 3600 as hour_bucket, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY hour_bucket ORDER BY hour_bucket ASC` + ).all(agentName, workspaceId, since) as Array<{ hour_bucket: number; count: number }>; + + return { + by_type: byType, + timeline: timeline.map(t => ({ + timestamp: t.hour_bucket, + hour: new Date(t.hour_bucket * 1000).toISOString(), + count: t.count, + })), + }; +} + +/** Multi-period trend comparison for anomaly/trend detection */ +function buildTrends(db: any, agentName: string, workspaceId: number, hours: number) { + const now = Math.floor(Date.now() / 1000); + + // Compare current period vs previous period of same length + const currentSince = now - hours * 3600; + const previousSince = currentSince - hours * 3600; + + const periodMetrics = (since: number, until: number) => { + const activities = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ?` + ).get(agentName, workspaceId, since, until) as any).c; + + const errors = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ? AND (type LIKE '%error%' OR type LIKE '%fail%')` + ).get(agentName, workspaceId, since, until) as any).c; + + const tasksCompleted = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? AND updated_at < ?` + ).get(agentName, workspaceId, since, until) as any).c; + + return { activities, errors, tasks_completed: tasksCompleted }; + }; + + const current = periodMetrics(currentSince, now); + const previous = periodMetrics(previousSince, currentSince); + + const pctChange = (cur: number, prev: number) => { + if (prev === 0) return cur > 0 ? 100 : 0; + return Math.round(((cur - prev) / prev) * 10000) / 100; + }; + + return { + current_period: { since: currentSince, until: now, ...current }, + previous_period: { since: previousSince, until: currentSince, ...previous }, + change: { + activities_pct: pctChange(current.activities, previous.activities), + errors_pct: pctChange(current.errors, previous.errors), + tasks_completed_pct: pctChange(current.tasks_completed, previous.tasks_completed), + }, + alerts: buildTrendAlerts(current, previous), + }; +} + +/** Generate automatic alerts from trend data */ +function buildTrendAlerts(current: { activities: number; errors: number; tasks_completed: number }, previous: { activities: number; errors: number; tasks_completed: number }) { + const alerts: Array<{ level: string; message: string }> = []; + + // Error rate spike + if (current.errors > 0 && previous.errors > 0) { + const errorIncrease = (current.errors - previous.errors) / previous.errors; + if (errorIncrease > 0.5) { + alerts.push({ level: 'warning', message: `Error count increased ${Math.round(errorIncrease * 100)}% vs previous period` }); + } + } else if (current.errors > 3 && previous.errors === 0) { + alerts.push({ level: 'warning', message: `New error pattern: ${current.errors} errors (none in previous period)` }); + } + + // Throughput drop + if (previous.tasks_completed > 0 && current.tasks_completed === 0) { + alerts.push({ level: 'info', message: 'No tasks completed in current period (possible stall)' }); + } else if (previous.tasks_completed > 2 && current.tasks_completed < previous.tasks_completed * 0.5) { + alerts.push({ level: 'info', message: `Task throughput dropped ${Math.round((1 - current.tasks_completed / previous.tasks_completed) * 100)}%` }); + } + + // Activity drop (possible offline) + if (previous.activities > 5 && current.activities < previous.activities * 0.25) { + alerts.push({ level: 'warning', message: `Activity dropped ${Math.round((1 - current.activities / previous.activities) * 100)}% — agent may be stalled` }); + } + + return alerts; +} + +/** Token usage by model */ +function buildTokenMetrics(db: any, agentName: string, workspaceId: number, since: number) { + try { + // session_id on token_usage may store agent name or session key + const byModel = db.prepare( + `SELECT model, SUM(input_tokens) as input_tokens, SUM(output_tokens) as output_tokens, COUNT(*) as request_count FROM token_usage WHERE session_id = ? AND workspace_id = ? AND created_at >= ? GROUP BY model ORDER BY (input_tokens + output_tokens) DESC` + ).all(agentName, workspaceId, since) as Array<{ model: string; input_tokens: number; output_tokens: number; request_count: number }>; + + const total = byModel.reduce((acc, r) => ({ + input_tokens: acc.input_tokens + r.input_tokens, + output_tokens: acc.output_tokens + r.output_tokens, + requests: acc.requests + r.request_count, + }), { input_tokens: 0, output_tokens: 0, requests: 0 }); + + return { + by_model: byModel, + total, + }; + } catch { + // token_usage table may not exist + return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 } }; + } +} diff --git a/src/app/api/agents/[id]/heartbeat/route.ts b/src/app/api/agents/[id]/heartbeat/route.ts index 7b850496063bb5a29b5a394c966f6d4de7b64b70..3fad96597d954bd26e475c6d9e69dcf7c43a47bc 100644 --- a/src/app/api/agents/[id]/heartbeat/route.ts +++ b/src/app/api/agents/[id]/heartbeat/route.ts @@ -180,7 +180,7 @@ export async function GET( * - connection_id: update direct_connections.last_heartbeat * - status: agent status override * - last_activity: activity description - * - token_usage: { model, inputTokens, outputTokens } for inline token reporting + * - token_usage: { model, inputTokens, outputTokens, taskId? } for inline token reporting */ export async function POST( request: NextRequest, @@ -221,10 +221,35 @@ export async function POST( if (agent) { const sessionId = `${agent.name}:cli`; + const parsedTaskId = + token_usage.taskId != null && Number.isFinite(Number(token_usage.taskId)) + ? Number(token_usage.taskId) + : null + + let taskId: number | null = null + if (parsedTaskId && parsedTaskId > 0) { + const taskRow = db.prepare( + 'SELECT id FROM tasks WHERE id = ? AND workspace_id = ?' + ).get(parsedTaskId, workspaceId) as { id?: number } | undefined + if (taskRow?.id) { + taskId = taskRow.id + } else { + logger.warn({ taskId: parsedTaskId, workspaceId, agent: agent.name }, 'Ignoring token usage with unknown taskId') + } + } + db.prepare( - `INSERT INTO token_usage (model, session_id, input_tokens, output_tokens, created_at) - VALUES (?, ?, ?, ?, ?)` - ).run(token_usage.model, sessionId, token_usage.inputTokens, token_usage.outputTokens, now); + `INSERT INTO token_usage (model, session_id, input_tokens, output_tokens, created_at, workspace_id, task_id) + VALUES (?, ?, ?, ?, ?, ?, ?)` + ).run( + token_usage.model, + sessionId, + token_usage.inputTokens, + token_usage.outputTokens, + now, + workspaceId, + taskId + ); tokenRecorded = true; } } diff --git a/src/app/api/agents/[id]/memory/route.ts b/src/app/api/agents/[id]/memory/route.ts index db5ef30c425378bf6fce9d5ca43e315ef428902e..56277b26fff80954ad0c2257c3cc0605826c389b 100644 --- a/src/app/api/agents/[id]/memory/route.ts +++ b/src/app/api/agents/[id]/memory/route.ts @@ -6,8 +6,8 @@ import { logger } from '@/lib/logger'; /** * GET /api/agents/[id]/memory - Get agent's working memory * - * Working memory is stored as WORKING.md content in the database - * Each agent has their own working memory space for temporary notes + * Working memory is stored in the agents.working_memory DB column. + * This endpoint is per-agent scratchpad memory (not the global Memory Browser filesystem view). */ export async function GET( request: NextRequest, diff --git a/src/app/api/agents/[id]/route.ts b/src/app/api/agents/[id]/route.ts index 55c23efd26cca0bea7d248638228f53ea21a626f..8a0c1f2f50c8a0a3cd0c0d0da6bf9ff9f2f10ae5 100644 --- a/src/app/api/agents/[id]/route.ts +++ b/src/app/api/agents/[id]/route.ts @@ -44,12 +44,12 @@ export async function GET( } /** - * PUT /api/agents/[id] - Update agent config with optional gateway write-back + * PUT /api/agents/[id] - Update agent config with unified MC + gateway save * * Body: { * role?: string * gateway_config?: object - OpenClaw agent config fields to update - * write_to_gateway?: boolean - If true, also write to openclaw.json + * write_to_gateway?: boolean - Defaults to true when gateway_config exists * } */ export async function PUT( @@ -86,56 +86,78 @@ export async function PUT( newConfig = { ...existingConfig, ...gateway_config } } - // Build update - const fields: string[] = ['updated_at = ?'] - const values: any[] = [now] - - if (role !== undefined) { - fields.push('role = ?') - values.push(role) + const shouldWriteToGateway = Boolean( + gateway_config && + (write_to_gateway === undefined || write_to_gateway === null || write_to_gateway === true) + ) + const openclawId = existingConfig.openclawId || agent.name.toLowerCase().replace(/\s+/g, '-') + const getWriteBackPayload = (source: Record) => { + const writeBack: any = { id: openclawId } + if (source.model) writeBack.model = source.model + if (source.identity) writeBack.identity = source.identity + if (source.sandbox) writeBack.sandbox = source.sandbox + if (source.tools) writeBack.tools = source.tools + if (source.subagents) writeBack.subagents = source.subagents + if (source.memorySearch) writeBack.memorySearch = source.memorySearch + return writeBack } - if (gateway_config) { - fields.push('config = ?') - values.push(JSON.stringify(newConfig)) + // Unified save: gateway first, then DB. If DB fails after gateway write, attempt rollback. + if (shouldWriteToGateway) { + try { + await writeAgentToConfig(getWriteBackPayload(gateway_config)) + } catch (err: any) { + return NextResponse.json( + { error: `Save failed: unable to update gateway config: ${err.message}` }, + { status: 502 } + ) + } } - values.push(agent.id, workspaceId) - db.prepare(`UPDATE agents SET ${fields.join(', ')} WHERE id = ? AND workspace_id = ?`).run(...values) + try { + // Build update + const fields: string[] = ['updated_at = ?'] + const values: any[] = [now] - // Write back to openclaw.json if requested - if (write_to_gateway && gateway_config) { - try { - const openclawId = existingConfig.openclawId || agent.name.toLowerCase().replace(/\s+/g, '-') - - // Build the config to write back (full OpenClaw format) - const writeBack: any = { id: openclawId } - if (gateway_config.model) writeBack.model = gateway_config.model - if (gateway_config.identity) writeBack.identity = gateway_config.identity - if (gateway_config.sandbox) writeBack.sandbox = gateway_config.sandbox - if (gateway_config.tools) writeBack.tools = gateway_config.tools - if (gateway_config.subagents) writeBack.subagents = gateway_config.subagents - if (gateway_config.memorySearch) writeBack.memorySearch = gateway_config.memorySearch - - await writeAgentToConfig(writeBack) - - const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown' - logAuditEvent({ - action: 'agent_config_writeback', - actor: auth.user.username, - actor_id: auth.user.id, - target_type: 'agent', - target_id: agent.id, - detail: { agent_name: agent.name, openclaw_id: openclawId, fields: Object.keys(gateway_config) }, - ip_address: ipAddress, - }) - } catch (err: any) { - // Config update succeeded in DB but gateway write failed - return NextResponse.json({ - warning: `Agent updated in MC but gateway write failed: ${err.message}`, - agent: { ...agent, config: newConfig, role: role || agent.role, updated_at: now }, - }) + if (role !== undefined) { + fields.push('role = ?') + values.push(role) } + + if (gateway_config) { + fields.push('config = ?') + values.push(JSON.stringify(newConfig)) + } + + values.push(agent.id, workspaceId) + db.prepare(`UPDATE agents SET ${fields.join(', ')} WHERE id = ? AND workspace_id = ?`).run(...values) + } catch (err: any) { + if (shouldWriteToGateway) { + try { + // Best-effort rollback to preserve consistency if DB update fails after gateway write. + await writeAgentToConfig(getWriteBackPayload(existingConfig)) + } catch (rollbackErr: any) { + logger.error({ err: rollbackErr, agent: agent.name }, 'Failed to rollback gateway config after DB failure') + return NextResponse.json( + { error: `Save failed after gateway update and rollback failed: ${err.message}` }, + { status: 500 } + ) + } + } + return NextResponse.json({ error: `Save failed: ${err.message}` }, { status: 500 }) + } + + if (shouldWriteToGateway) { + const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown' + logAuditEvent({ + action: 'agent_config_writeback', + actor: auth.user.username, + actor_id: auth.user.id, + target_type: 'agent', + target_id: agent.id, + detail: { agent_name: agent.name, openclaw_id: openclawId, fields: Object.keys(gateway_config || {}) }, + ip_address: ipAddress, + }) } // Log activity @@ -144,8 +166,8 @@ export async function PUT( 'agent', agent.id, auth.user.username, - `Config updated for agent ${agent.name}${write_to_gateway ? ' (+ gateway)' : ''}`, - { fields: Object.keys(gateway_config || {}), write_to_gateway }, + `Config updated for agent ${agent.name}${shouldWriteToGateway ? ' (+ gateway)' : ''}`, + { fields: Object.keys(gateway_config || {}), write_to_gateway: shouldWriteToGateway }, workspaceId ) diff --git a/src/app/api/agents/[id]/soul/route.ts b/src/app/api/agents/[id]/soul/route.ts index 061472a4a77cf0238141708d590afc5e83ba9019..5e506ad28ce2e05430405f4a32e8623ae57acd28 100644 --- a/src/app/api/agents/[id]/soul/route.ts +++ b/src/app/api/agents/[id]/soul/route.ts @@ -1,12 +1,18 @@ import { NextRequest, NextResponse } from 'next/server'; import { getDatabase, db_helpers } from '@/lib/db'; import { readFileSync, existsSync, readdirSync, writeFileSync, mkdirSync } from 'fs'; -import { join, dirname } from 'path'; +import { join, dirname, isAbsolute, resolve } from 'path'; import { config } from '@/lib/config'; import { resolveWithin } from '@/lib/paths'; import { requireRole } from '@/lib/auth'; import { logger } from '@/lib/logger'; +function resolveAgentWorkspacePath(workspace: string): string { + if (isAbsolute(workspace)) return resolve(workspace) + if (!config.openclawStateDir) throw new Error('OPENCLAW_STATE_DIR not configured') + return resolveWithin(config.openclawStateDir, workspace) +} + /** * GET /api/agents/[id]/soul - Get agent's SOUL content */ @@ -41,8 +47,8 @@ export async function GET( try { const agentConfig = agent.config ? JSON.parse(agent.config) : {} - if (agentConfig.workspace && config.openclawHome) { - const safeWorkspace = resolveWithin(config.openclawHome, agentConfig.workspace) + if (agentConfig.workspace) { + const safeWorkspace = resolveAgentWorkspacePath(agentConfig.workspace) const safeSoulPath = resolveWithin(safeWorkspace, 'soul.md') if (existsSync(safeSoulPath)) { soulContent = readFileSync(safeSoulPath, 'utf-8') @@ -157,8 +163,8 @@ export async function PUT( let savedToWorkspace = false try { const agentConfig = agent.config ? JSON.parse(agent.config) : {} - if (agentConfig.workspace && config.openclawHome) { - const safeWorkspace = resolveWithin(config.openclawHome, agentConfig.workspace) + if (agentConfig.workspace) { + const safeWorkspace = resolveAgentWorkspacePath(agentConfig.workspace) const safeSoulPath = resolveWithin(safeWorkspace, 'soul.md') mkdirSync(dirname(safeSoulPath), { recursive: true }) writeFileSync(safeSoulPath, newSoulContent || '', 'utf-8') diff --git a/src/app/api/agents/route.ts b/src/app/api/agents/route.ts index 3f835f09b95f1db33e7336635c3a1a096a372f10..1f5263865a10721777ffc3f012e609b38376644a 100644 --- a/src/app/api/agents/route.ts +++ b/src/app/api/agents/route.ts @@ -8,6 +8,10 @@ import { requireRole } from '@/lib/auth'; import { mutationLimiter } from '@/lib/rate-limit'; import { logger } from '@/lib/logger'; import { validateBody, createAgentSchema } from '@/lib/validation'; +import { runOpenClaw } from '@/lib/command'; +import { config as appConfig } from '@/lib/config'; +import { resolveWithin } from '@/lib/paths'; +import path from 'node:path'; /** * GET /api/agents - List all agents with optional filtering @@ -123,6 +127,7 @@ export async function POST(request: NextRequest) { const { name, + openclaw_id, role, session_key, soul_content, @@ -130,9 +135,16 @@ export async function POST(request: NextRequest) { config = {}, template, gateway_config, - write_to_gateway + write_to_gateway, + provision_openclaw_workspace, + openclaw_workspace_path } = body; + const openclawId = (openclaw_id || name || 'agent') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); + // Resolve template if specified let finalRole = role; let finalConfig: Record = { ...config }; @@ -158,6 +170,32 @@ export async function POST(request: NextRequest) { if (existingAgent) { return NextResponse.json({ error: 'Agent name already exists' }, { status: 409 }); } + + if (provision_openclaw_workspace) { + if (!appConfig.openclawStateDir) { + return NextResponse.json( + { error: 'OPENCLAW_STATE_DIR is not configured; cannot provision OpenClaw workspace' }, + { status: 500 } + ); + } + + const workspacePath = openclaw_workspace_path + ? path.resolve(openclaw_workspace_path) + : resolveWithin(appConfig.openclawStateDir, path.join('workspaces', openclawId)); + + try { + await runOpenClaw( + ['agents', 'add', openclawId, '--name', name, '--workspace', workspacePath, '--non-interactive'], + { timeoutMs: 20000 } + ); + } catch (provisionError: any) { + logger.error({ err: provisionError, openclawId, workspacePath }, 'OpenClaw workspace provisioning failed'); + return NextResponse.json( + { error: provisionError?.message || 'Failed to provision OpenClaw agent workspace' }, + { status: 502 } + ); + } + } const now = Math.floor(Date.now() / 1000); @@ -215,7 +253,6 @@ export async function POST(request: NextRequest) { // Write to gateway config if requested if (write_to_gateway && finalConfig) { try { - const openclawId = (name || 'agent').toLowerCase().replace(/\s+/g, '-'); await writeAgentToConfig({ id: openclawId, name, diff --git a/src/app/api/cleanup/route.ts b/src/app/api/cleanup/route.ts index c590ea381bf6382b2da5cbc90b196fcb99ce7dd3..3cd13fc9e34f1342e740b7e26436768275f1d153 100644 --- a/src/app/api/cleanup/route.ts +++ b/src/app/api/cleanup/route.ts @@ -3,6 +3,7 @@ import { requireRole } from '@/lib/auth' import { getDatabase, logAuditEvent } from '@/lib/db' import { config } from '@/lib/config' import { heavyLimiter } from '@/lib/rate-limit' +import { countStaleGatewaySessions, pruneGatewaySessionsOlderThan } from '@/lib/sessions' interface CleanupResult { table: string @@ -59,6 +60,17 @@ export async function GET(request: NextRequest) { preview.push({ table: 'Token Usage (file)', retention_days: ret.tokenUsage, stale_count: 0, note: 'No token data file' }) } + if (ret.gatewaySessions > 0) { + preview.push({ + table: 'Gateway Session Store', + retention_days: ret.gatewaySessions, + stale_count: countStaleGatewaySessions(ret.gatewaySessions), + note: 'Stored under ~/.openclaw/agents/*/sessions/sessions.json', + }) + } else { + preview.push({ table: 'Gateway Session Store', retention_days: 0, stale_count: 0, note: 'Retention disabled (keep forever)' }) + } + return NextResponse.json({ retention: config.retention, preview }) } @@ -137,6 +149,19 @@ export async function POST(request: NextRequest) { } } + if (ret.gatewaySessions > 0) { + const sessionPrune = dryRun + ? { deleted: countStaleGatewaySessions(ret.gatewaySessions), filesTouched: 0 } + : pruneGatewaySessionsOlderThan(ret.gatewaySessions) + results.push({ + table: 'Gateway Session Store', + deleted: sessionPrune.deleted, + cutoff_date: new Date(Date.now() - ret.gatewaySessions * 86400000).toISOString().split('T')[0], + retention_days: ret.gatewaySessions, + }) + totalDeleted += sessionPrune.deleted + } + if (!dryRun && totalDeleted > 0) { const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown' logAuditEvent({ diff --git a/src/app/api/cron/route.ts b/src/app/api/cron/route.ts index 7640199993fc7d7d9e5f5c13af96a9413b0f330f..69e10eea40b7c907d94dca1c3a388716f6e444fa 100644 --- a/src/app/api/cron/route.ts +++ b/src/app/api/cron/route.ts @@ -67,9 +67,9 @@ interface OpenClawCronFile { } function getCronFilePath(): string { - const openclawHome = config.openclawHome - if (!openclawHome) return '' - return path.join(openclawHome, 'cron', 'jobs.json') + const openclawStateDir = config.openclawStateDir + if (!openclawStateDir) return '' + return path.join(openclawStateDir, 'cron', 'jobs.json') } async function loadCronFile(): Promise { diff --git a/src/app/api/docs/content/route.ts b/src/app/api/docs/content/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fea30795e3d9d61d180a701fcffa16814f67d2d --- /dev/null +++ b/src/app/api/docs/content/route.ts @@ -0,0 +1,39 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireRole } from '@/lib/auth' +import { readLimiter } from '@/lib/rate-limit' +import { logger } from '@/lib/logger' +import { readDocsContent } from '@/lib/docs-knowledge' + +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const rateCheck = readLimiter(request) + if (rateCheck) return rateCheck + + try { + const { searchParams } = new URL(request.url) + const path = (searchParams.get('path') || '').trim() + + if (!path) { + return NextResponse.json({ error: 'Path required' }, { status: 400 }) + } + + try { + const doc = await readDocsContent(path) + return NextResponse.json(doc) + } catch (error) { + const message = (error as Error).message || '' + if (message.includes('Path not allowed')) { + return NextResponse.json({ error: 'Path not allowed' }, { status: 403 }) + } + if (message.includes('not configured')) { + return NextResponse.json({ error: 'Docs directory not configured' }, { status: 500 }) + } + return NextResponse.json({ error: 'File not found' }, { status: 404 }) + } + } catch (error) { + logger.error({ err: error }, 'GET /api/docs/content error') + return NextResponse.json({ error: 'Failed to load doc content' }, { status: 500 }) + } +} diff --git a/src/app/api/docs/search/route.ts b/src/app/api/docs/search/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a63ede9462040da5e32f227b8766a2766df2bf0 --- /dev/null +++ b/src/app/api/docs/search/route.ts @@ -0,0 +1,29 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireRole } from '@/lib/auth' +import { readLimiter } from '@/lib/rate-limit' +import { logger } from '@/lib/logger' +import { searchDocs } from '@/lib/docs-knowledge' + +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const rateCheck = readLimiter(request) + if (rateCheck) return rateCheck + + try { + const { searchParams } = new URL(request.url) + const query = (searchParams.get('q') || searchParams.get('query') || '').trim() + const limit = Math.min(parseInt(searchParams.get('limit') || '50', 10), 200) + + if (!query) { + return NextResponse.json({ error: 'Query required' }, { status: 400 }) + } + + const results = await searchDocs(query, limit) + return NextResponse.json({ query, results, count: results.length }) + } catch (error) { + logger.error({ err: error }, 'GET /api/docs/search error') + return NextResponse.json({ error: 'Failed to search docs' }, { status: 500 }) + } +} diff --git a/src/app/api/docs/tree/route.ts b/src/app/api/docs/tree/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf6f5a57c84a144453a08ded7e79bce7cff50ce3 --- /dev/null +++ b/src/app/api/docs/tree/route.ts @@ -0,0 +1,21 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireRole } from '@/lib/auth' +import { readLimiter } from '@/lib/rate-limit' +import { logger } from '@/lib/logger' +import { getDocsTree, listDocsRoots } from '@/lib/docs-knowledge' + +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const rateCheck = readLimiter(request) + if (rateCheck) return rateCheck + + try { + const tree = await getDocsTree() + return NextResponse.json({ roots: listDocsRoots(), tree }) + } catch (error) { + logger.error({ err: error }, 'GET /api/docs/tree error') + return NextResponse.json({ error: 'Failed to load docs tree' }, { status: 500 }) + } +} diff --git a/src/app/api/gateway-config/route.ts b/src/app/api/gateway-config/route.ts index 7fa1e43497fd5dc13b4d38e058b85952fb81c75f..9aac4d00e4e1a05e78806bebf0e99e17d3448198 100644 --- a/src/app/api/gateway-config/route.ts +++ b/src/app/api/gateway-config/route.ts @@ -2,13 +2,11 @@ import { NextRequest, NextResponse } from 'next/server' import { requireRole } from '@/lib/auth' import { logAuditEvent } from '@/lib/db' import { config } from '@/lib/config' -import { join } from 'path' import { validateBody, gatewayConfigUpdateSchema } from '@/lib/validation' import { mutationLimiter } from '@/lib/rate-limit' function getConfigPath(): string | null { - if (!config.openclawHome) return null - return join(config.openclawHome, 'openclaw.json') + return config.openclawConfigPath || null } /** @@ -20,7 +18,7 @@ export async function GET(request: NextRequest) { const configPath = getConfigPath() if (!configPath) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_CONFIG_PATH not configured' }, { status: 404 }) } try { @@ -60,7 +58,7 @@ export async function PUT(request: NextRequest) { const configPath = getConfigPath() if (!configPath) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_CONFIG_PATH not configured' }, { status: 404 }) } const result = await validateBody(request, gatewayConfigUpdateSchema) diff --git a/src/app/api/gateways/connect/route.ts b/src/app/api/gateways/connect/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fdad8fb01f689ccb9a352a4188d1c97a0676284 --- /dev/null +++ b/src/app/api/gateways/connect/route.ts @@ -0,0 +1,76 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireRole } from '@/lib/auth' +import { getDatabase } from '@/lib/db' +import { buildGatewayWebSocketUrl } from '@/lib/gateway-url' + +interface GatewayEntry { + id: number + host: string + port: number + token: string +} + +function ensureTable(db: ReturnType) { + db.exec(` + CREATE TABLE IF NOT EXISTS gateways ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + host TEXT NOT NULL DEFAULT '127.0.0.1', + port INTEGER NOT NULL DEFAULT 18789, + token TEXT NOT NULL DEFAULT '', + is_primary INTEGER NOT NULL DEFAULT 0, + status TEXT NOT NULL DEFAULT 'unknown', + last_seen INTEGER, + latency INTEGER, + sessions_count INTEGER NOT NULL DEFAULT 0, + agents_count INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + updated_at INTEGER NOT NULL DEFAULT (unixepoch()) + ) + `) +} + +/** + * POST /api/gateways/connect + * Resolves websocket URL and token for a selected gateway without exposing tokens in list payloads. + */ +export async function POST(request: NextRequest) { + const auth = requireRole(request, 'operator') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const db = getDatabase() + ensureTable(db) + + let id: number | null = null + try { + const body = await request.json() + id = Number(body?.id) + } catch { + return NextResponse.json({ error: 'Invalid request body' }, { status: 400 }) + } + + if (!id || !Number.isInteger(id) || id < 1) { + return NextResponse.json({ error: 'id is required' }, { status: 400 }) + } + + const gateway = db.prepare('SELECT id, host, port, token FROM gateways WHERE id = ?').get(id) as GatewayEntry | undefined + if (!gateway) { + return NextResponse.json({ error: 'Gateway not found' }, { status: 404 }) + } + + const ws_url = buildGatewayWebSocketUrl({ + host: gateway.host, + port: gateway.port, + browserProtocol: request.nextUrl.protocol, + }) + + const envToken = (process.env.NEXT_PUBLIC_GATEWAY_TOKEN || process.env.NEXT_PUBLIC_WS_TOKEN || '').trim() + const token = (gateway.token || '').trim() || envToken + + return NextResponse.json({ + id: gateway.id, + ws_url, + token, + token_set: token.length > 0, + }) +} diff --git a/src/app/api/gateways/health/route.ts b/src/app/api/gateways/health/route.ts index 6297183b58bb3c6c64b9fefa92dc91f7b8c03e0c..1025b368a6dafd7f47f7ace257ade1ca21ae637f 100644 --- a/src/app/api/gateways/health/route.ts +++ b/src/app/api/gateways/health/route.ts @@ -19,9 +19,33 @@ interface HealthResult { latency: number | null agents: string[] sessions_count: number + gateway_version?: string | null + compatibility_warning?: string error?: string } +function parseGatewayVersion(res: Response): string | null { + const direct = res.headers.get('x-openclaw-version') || res.headers.get('x-clawdbot-version') + if (direct) return direct.trim() + const server = res.headers.get('server') || '' + const m = server.match(/(\d{4}\.\d+\.\d+)/) + return m?.[1] || null +} + +function hasOpenClaw32ToolsProfileRisk(version: string | null): boolean { + if (!version) return false + const m = version.match(/^(\d{4})\.(\d+)\.(\d+)/) + if (!m) return false + const year = Number(m[1]) + const major = Number(m[2]) + const minor = Number(m[3]) + if (year > 2026) return true + if (year < 2026) return false + if (major > 3) return true + if (major < 3) return false + return minor >= 2 +} + function isBlockedUrl(urlStr: string): boolean { try { const url = new URL(urlStr) @@ -77,6 +101,10 @@ export async function POST(request: NextRequest) { const latency = Date.now() - start const status = res.ok ? "online" : "error" + const gatewayVersion = parseGatewayVersion(res) + const compatibilityWarning = hasOpenClaw32ToolsProfileRisk(gatewayVersion) + ? 'OpenClaw 2026.3.2+ defaults tools.profile=messaging; Mission Control should enforce coding profile when spawning.' + : undefined updateOnlineStmt.run(status, latency, gw.id) @@ -87,6 +115,8 @@ export async function POST(request: NextRequest) { latency, agents: [], sessions_count: 0, + gateway_version: gatewayVersion, + compatibility_warning: compatibilityWarning, }) } catch (err: any) { updateOfflineStmt.run("offline", gw.id) diff --git a/src/app/api/integrations/route.ts b/src/app/api/integrations/route.ts index 1a1f4a70a0675bae89e26fd8c488dce3f7c3bce9..921d1c9dbc9db2a247b3eced2c078fdce81d4e1d 100644 --- a/src/app/api/integrations/route.ts +++ b/src/app/api/integrations/route.ts @@ -108,8 +108,8 @@ function serializeEnv(lines: EnvLine[]): string { } function getEnvPath(): string | null { - if (!config.openclawHome) return null - return join(config.openclawHome, '.env') + if (!config.openclawStateDir) return null + return join(config.openclawStateDir, '.env') } async function readEnvFile(): Promise<{ lines: EnvLine[]; raw: string } | null> { @@ -184,7 +184,7 @@ export async function GET(request: NextRequest) { const envData = await readEnvFile() if (!envData) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 }) } const envMap = new Map() @@ -261,7 +261,7 @@ export async function PUT(request: NextRequest) { const envData = await readEnvFile() if (!envData) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 }) } const { lines } = envData @@ -324,7 +324,7 @@ export async function DELETE(request: NextRequest) { const envData = await readEnvFile() if (!envData) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 }) } const removed: string[] = [] @@ -408,7 +408,7 @@ async function handleTest( const envData = await readEnvFile() if (!envData) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 }) } const envMap = new Map() @@ -552,7 +552,7 @@ async function handlePull( // Write to .env const envData = await readEnvFile() if (!envData) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 }) } const { lines } = envData @@ -621,7 +621,7 @@ async function handlePullAll( const envData = await readEnvFile() if (!envData) { - return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 }) + return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 }) } const { lines } = envData diff --git a/src/app/api/memory/route.ts b/src/app/api/memory/route.ts index 6615d359d71ac73f5dccfaacfc081f5ff8dae03d..a7fddce2d09f4452d54d81b4d9de027669e604c3 100644 --- a/src/app/api/memory/route.ts +++ b/src/app/api/memory/route.ts @@ -9,6 +9,7 @@ import { readLimiter, mutationLimiter } from '@/lib/rate-limit' import { logger } from '@/lib/logger' const MEMORY_PATH = config.memoryDir +const MEMORY_ALLOWED_PREFIXES = (config.memoryAllowedPrefixes || []).map((p) => p.replace(/\\/g, '/')) // Ensure memory directory exists on startup if (MEMORY_PATH && !existsSync(MEMORY_PATH)) { @@ -24,6 +25,16 @@ interface MemoryFile { children?: MemoryFile[] } +function normalizeRelativePath(value: string): string { + return String(value || '').replace(/\\/g, '/').replace(/^\/+/, '') +} + +function isPathAllowed(relativePath: string): boolean { + if (!MEMORY_ALLOWED_PREFIXES.length) return true + const normalized = normalizeRelativePath(relativePath) + return MEMORY_ALLOWED_PREFIXES.some((prefix) => normalized === prefix.slice(0, -1) || normalized.startsWith(prefix)) +} + function isWithinBase(base: string, candidate: string): boolean { if (candidate === base) return true return candidate.startsWith(base + sep) @@ -33,17 +44,22 @@ async function resolveSafeMemoryPath(baseDir: string, relativePath: string): Pro const baseReal = await realpath(baseDir) const fullPath = resolveWithin(baseDir, relativePath) - // For non-existent paths, validate containment using the parent directory realpath. - // This also blocks symlinked parent segments that escape the base. - let parentReal: string - try { - parentReal = await realpath(dirname(fullPath)) - } catch (err) { - const code = (err as NodeJS.ErrnoException).code - if (code === 'ENOENT') { - throw new Error('Parent directory not found') + // For non-existent targets, validate containment using the nearest existing ancestor. + // This allows nested creates (mkdir -p) while still blocking symlink escapes. + let current = dirname(fullPath) + let parentReal = '' + while (!parentReal) { + try { + parentReal = await realpath(current) + } catch (err) { + const code = (err as NodeJS.ErrnoException).code + if (code !== 'ENOENT') throw err + const next = dirname(current) + if (next === current) { + throw new Error('Parent directory not found') + } + current = next } - throw err } if (!isWithinBase(baseReal, parentReal)) { throw new Error('Path escapes base directory (symlink)') @@ -137,12 +153,37 @@ export async function GET(request: NextRequest) { if (!MEMORY_PATH) { return NextResponse.json({ tree: [] }) } + if (MEMORY_ALLOWED_PREFIXES.length) { + const tree: MemoryFile[] = [] + for (const prefix of MEMORY_ALLOWED_PREFIXES) { + const folder = prefix.replace(/\/$/, '') + const fullPath = join(MEMORY_PATH, folder) + if (!existsSync(fullPath)) continue + try { + const stats = await stat(fullPath) + if (!stats.isDirectory()) continue + tree.push({ + path: folder, + name: folder, + type: 'directory', + modified: stats.mtime.getTime(), + children: await buildFileTree(fullPath, folder), + }) + } catch { + // Skip unreadable roots + } + } + return NextResponse.json({ tree }) + } const tree = await buildFileTree(MEMORY_PATH) return NextResponse.json({ tree }) } if (action === 'content' && path) { // Return file content + if (!isPathAllowed(path)) { + return NextResponse.json({ error: 'Path not allowed' }, { status: 403 }) + } if (!MEMORY_PATH) { return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 }) } @@ -227,7 +268,16 @@ export async function GET(request: NextRequest) { } } - await searchDirectory(MEMORY_PATH) + if (MEMORY_ALLOWED_PREFIXES.length) { + for (const prefix of MEMORY_ALLOWED_PREFIXES) { + const folder = prefix.replace(/\/$/, '') + const fullPath = join(MEMORY_PATH, folder) + if (!existsSync(fullPath)) continue + await searchDirectory(fullPath, folder) + } + } else { + await searchDirectory(MEMORY_PATH) + } return NextResponse.json({ query, @@ -256,6 +306,9 @@ export async function POST(request: NextRequest) { if (!path) { return NextResponse.json({ error: 'Path is required' }, { status: 400 }) } + if (!isPathAllowed(path)) { + return NextResponse.json({ error: 'Path not allowed' }, { status: 403 }) + } if (!MEMORY_PATH) { return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 }) @@ -316,6 +369,9 @@ export async function DELETE(request: NextRequest) { if (!path) { return NextResponse.json({ error: 'Path is required' }, { status: 400 }) } + if (!isPathAllowed(path)) { + return NextResponse.json({ error: 'Path not allowed' }, { status: 403 }) + } if (!MEMORY_PATH) { return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 }) diff --git a/src/app/api/mentions/route.ts b/src/app/api/mentions/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..288850b0b44dbb94d737600e9e6ad782b6be2c9d --- /dev/null +++ b/src/app/api/mentions/route.ts @@ -0,0 +1,50 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireRole } from '@/lib/auth' +import { getDatabase } from '@/lib/db' +import { getMentionTargets } from '@/lib/mentions' +import { logger } from '@/lib/logger' + +/** + * GET /api/mentions - autocomplete source for @mentions (users + agents) + * Query: q?, limit?, type? + */ +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const { searchParams } = new URL(request.url) + + const q = String(searchParams.get('q') || '').trim().toLowerCase() + const typeFilter = String(searchParams.get('type') || '').trim().toLowerCase() + const limitRaw = Number.parseInt(searchParams.get('limit') || '25', 10) + const limit = Math.max(1, Math.min(Number.isFinite(limitRaw) ? limitRaw : 25, 200)) + + let targets = getMentionTargets(db, workspaceId) + + if (typeFilter === 'user' || typeFilter === 'agent') { + targets = targets.filter((target) => target.type === typeFilter) + } + + if (q) { + targets = targets.filter((target) => ( + target.handle.includes(q) || + target.recipient.toLowerCase().includes(q) || + target.display.toLowerCase().includes(q) + )) + } + + targets = targets.slice(0, limit) + + return NextResponse.json({ + mentions: targets, + total: targets.length, + q, + }) + } catch (error) { + logger.error({ err: error }, 'GET /api/mentions error') + return NextResponse.json({ error: 'Failed to fetch mention targets' }, { status: 500 }) + } +} diff --git a/src/app/api/projects/[id]/route.ts b/src/app/api/projects/[id]/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..3fe1832ec3193deec3c5878d1da940c62ee77059 --- /dev/null +++ b/src/app/api/projects/[id]/route.ts @@ -0,0 +1,177 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getDatabase } from '@/lib/db' +import { requireRole } from '@/lib/auth' +import { mutationLimiter } from '@/lib/rate-limit' +import { logger } from '@/lib/logger' + +function normalizePrefix(input: string): string { + const normalized = input.trim().toUpperCase().replace(/[^A-Z0-9]/g, '') + return normalized.slice(0, 12) +} + +function toProjectId(raw: string): number { + const id = Number.parseInt(raw, 10) + return Number.isFinite(id) ? id : NaN +} + +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const { id } = await params + const projectId = toProjectId(id) + if (Number.isNaN(projectId)) return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 }) + + const project = db.prepare(` + SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at + FROM projects + WHERE id = ? AND workspace_id = ? + `).get(projectId, workspaceId) + if (!project) return NextResponse.json({ error: 'Project not found' }, { status: 404 }) + + return NextResponse.json({ project }) + } catch (error) { + logger.error({ err: error }, 'GET /api/projects/[id] error') + return NextResponse.json({ error: 'Failed to fetch project' }, { status: 500 }) + } +} + +export async function PATCH( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const auth = requireRole(request, 'operator') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const rateCheck = mutationLimiter(request) + if (rateCheck) return rateCheck + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const { id } = await params + const projectId = toProjectId(id) + if (Number.isNaN(projectId)) return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 }) + + const current = db.prepare(`SELECT * FROM projects WHERE id = ? AND workspace_id = ?`).get(projectId, workspaceId) as any + if (!current) return NextResponse.json({ error: 'Project not found' }, { status: 404 }) + if (current.slug === 'general' && current.workspace_id === workspaceId && current.id === projectId) { + const body = await request.json() + if (body?.status === 'archived') { + return NextResponse.json({ error: 'Default project cannot be archived' }, { status: 400 }) + } + } + + const body = await request.json() + const updates: string[] = [] + const paramsList: Array = [] + + if (typeof body?.name === 'string') { + const name = body.name.trim() + if (!name) return NextResponse.json({ error: 'Project name cannot be empty' }, { status: 400 }) + updates.push('name = ?') + paramsList.push(name) + } + if (typeof body?.description === 'string') { + updates.push('description = ?') + paramsList.push(body.description.trim() || null) + } + if (typeof body?.ticket_prefix === 'string' || typeof body?.ticketPrefix === 'string') { + const raw = String(body.ticket_prefix ?? body.ticketPrefix) + const prefix = normalizePrefix(raw) + if (!prefix) return NextResponse.json({ error: 'Invalid ticket prefix' }, { status: 400 }) + const conflict = db.prepare(` + SELECT id FROM projects + WHERE workspace_id = ? AND ticket_prefix = ? AND id != ? + `).get(workspaceId, prefix, projectId) + if (conflict) return NextResponse.json({ error: 'Ticket prefix already in use' }, { status: 409 }) + updates.push('ticket_prefix = ?') + paramsList.push(prefix) + } + if (typeof body?.status === 'string') { + const status = body.status === 'archived' ? 'archived' : 'active' + updates.push('status = ?') + paramsList.push(status) + } + + if (updates.length === 0) return NextResponse.json({ error: 'No fields to update' }, { status: 400 }) + + updates.push('updated_at = unixepoch()') + db.prepare(` + UPDATE projects + SET ${updates.join(', ')} + WHERE id = ? AND workspace_id = ? + `).run(...paramsList, projectId, workspaceId) + + const project = db.prepare(` + SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at + FROM projects + WHERE id = ? AND workspace_id = ? + `).get(projectId, workspaceId) + + return NextResponse.json({ project }) + } catch (error) { + logger.error({ err: error }, 'PATCH /api/projects/[id] error') + return NextResponse.json({ error: 'Failed to update project' }, { status: 500 }) + } +} + +export async function DELETE( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const auth = requireRole(request, 'admin') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const rateCheck = mutationLimiter(request) + if (rateCheck) return rateCheck + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const { id } = await params + const projectId = toProjectId(id) + if (Number.isNaN(projectId)) return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 }) + + const current = db.prepare(`SELECT * FROM projects WHERE id = ? AND workspace_id = ?`).get(projectId, workspaceId) as any + if (!current) return NextResponse.json({ error: 'Project not found' }, { status: 404 }) + if (current.slug === 'general') { + return NextResponse.json({ error: 'Default project cannot be deleted' }, { status: 400 }) + } + + const mode = new URL(request.url).searchParams.get('mode') || 'archive' + if (mode !== 'delete') { + db.prepare(`UPDATE projects SET status = 'archived', updated_at = unixepoch() WHERE id = ? AND workspace_id = ?`).run(projectId, workspaceId) + return NextResponse.json({ success: true, mode: 'archive' }) + } + + const fallback = db.prepare(` + SELECT id FROM projects + WHERE workspace_id = ? AND slug = 'general' + LIMIT 1 + `).get(workspaceId) as { id: number } | undefined + if (!fallback) return NextResponse.json({ error: 'Default project missing' }, { status: 500 }) + + const tx = db.transaction(() => { + db.prepare(` + UPDATE tasks + SET project_id = ? + WHERE workspace_id = ? AND project_id = ? + `).run(fallback.id, workspaceId, projectId) + + db.prepare(`DELETE FROM projects WHERE id = ? AND workspace_id = ?`).run(projectId, workspaceId) + }) + tx() + + return NextResponse.json({ success: true, mode: 'delete' }) + } catch (error) { + logger.error({ err: error }, 'DELETE /api/projects/[id] error') + return NextResponse.json({ error: 'Failed to delete project' }, { status: 500 }) + } +} diff --git a/src/app/api/projects/[id]/tasks/route.ts b/src/app/api/projects/[id]/tasks/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..ada689140b5a99960b5f1fa8bcd49346eaf3ad1f --- /dev/null +++ b/src/app/api/projects/[id]/tasks/route.ts @@ -0,0 +1,55 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getDatabase } from '@/lib/db' +import { requireRole } from '@/lib/auth' +import { logger } from '@/lib/logger' + +function formatTicketRef(prefix?: string | null, num?: number | null): string | undefined { + if (!prefix || typeof num !== 'number' || !Number.isFinite(num) || num <= 0) return undefined + return `${prefix}-${String(num).padStart(3, '0')}` +} + +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const { id } = await params + const projectId = Number.parseInt(id, 10) + if (!Number.isFinite(projectId)) { + return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 }) + } + + const project = db.prepare(` + SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at + FROM projects + WHERE id = ? AND workspace_id = ? + `).get(projectId, workspaceId) + if (!project) return NextResponse.json({ error: 'Project not found' }, { status: 404 }) + + const tasks = db.prepare(` + SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix + FROM tasks t + LEFT JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id + WHERE t.workspace_id = ? AND t.project_id = ? + ORDER BY t.created_at DESC + `).all(workspaceId, projectId) + + return NextResponse.json({ + project, + tasks: tasks.map((task: any) => ({ + ...task, + tags: task.tags ? JSON.parse(task.tags) : [], + metadata: task.metadata ? JSON.parse(task.metadata) : {}, + ticket_ref: formatTicketRef(task.project_prefix, task.project_ticket_no), + })) + }) + } catch (error) { + logger.error({ err: error }, 'GET /api/projects/[id]/tasks error') + return NextResponse.json({ error: 'Failed to fetch project tasks' }, { status: 500 }) + } +} diff --git a/src/app/api/projects/route.ts b/src/app/api/projects/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..177fb83722d997044cb226cbdf90a466e8000c43 --- /dev/null +++ b/src/app/api/projects/route.ts @@ -0,0 +1,94 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getDatabase } from '@/lib/db' +import { requireRole } from '@/lib/auth' +import { mutationLimiter } from '@/lib/rate-limit' +import { logger } from '@/lib/logger' + +function slugify(input: string): string { + return input + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 64) +} + +function normalizePrefix(input: string): string { + const normalized = input.trim().toUpperCase().replace(/[^A-Z0-9]/g, '') + return normalized.slice(0, 12) +} + +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const includeArchived = new URL(request.url).searchParams.get('includeArchived') === '1' + + const projects = db.prepare(` + SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at + FROM projects + WHERE workspace_id = ? + ${includeArchived ? '' : "AND status = 'active'"} + ORDER BY name COLLATE NOCASE ASC + `).all(workspaceId) + + return NextResponse.json({ projects }) + } catch (error) { + logger.error({ err: error }, 'GET /api/projects error') + return NextResponse.json({ error: 'Failed to fetch projects' }, { status: 500 }) + } +} + +export async function POST(request: NextRequest) { + const auth = requireRole(request, 'operator') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + const rateCheck = mutationLimiter(request) + if (rateCheck) return rateCheck + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id ?? 1 + const body = await request.json() + + const name = String(body?.name || '').trim() + const description = typeof body?.description === 'string' ? body.description.trim() : '' + const prefixInput = String(body?.ticket_prefix || body?.ticketPrefix || '').trim() + const slugInput = String(body?.slug || '').trim() + + if (!name) return NextResponse.json({ error: 'Project name is required' }, { status: 400 }) + + const slug = slugInput ? slugify(slugInput) : slugify(name) + const ticketPrefix = normalizePrefix(prefixInput || name.slice(0, 5)) + if (!slug) return NextResponse.json({ error: 'Invalid project slug' }, { status: 400 }) + if (!ticketPrefix) return NextResponse.json({ error: 'Invalid ticket prefix' }, { status: 400 }) + + const exists = db.prepare(` + SELECT id FROM projects + WHERE workspace_id = ? AND (slug = ? OR ticket_prefix = ?) + LIMIT 1 + `).get(workspaceId, slug, ticketPrefix) as { id: number } | undefined + if (exists) { + return NextResponse.json({ error: 'Project slug or ticket prefix already exists' }, { status: 409 }) + } + + const result = db.prepare(` + INSERT INTO projects (workspace_id, name, slug, description, ticket_prefix, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, 'active', unixepoch(), unixepoch()) + `).run(workspaceId, name, slug, description || null, ticketPrefix) + + const project = db.prepare(` + SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at + FROM projects + WHERE id = ? + `).get(Number(result.lastInsertRowid)) + + return NextResponse.json({ project }, { status: 201 }) + } catch (error) { + logger.error({ err: error }, 'POST /api/projects error') + return NextResponse.json({ error: 'Failed to create project' }, { status: 500 }) + } +} diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.ts index a6be8d44b5957b848816cb1b8b0c8610dcb93d6a..d88130fd443d76bfad08673e172ffd87798295d7 100644 --- a/src/app/api/settings/route.ts +++ b/src/app/api/settings/route.ts @@ -23,6 +23,7 @@ const settingDefinitions: Record) { + const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})` + return runClawdbot(['-c', commandArg], { timeoutMs: 10000 }) +} + export async function POST(request: NextRequest) { const auth = requireRole(request, 'operator') if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) @@ -31,15 +40,38 @@ export async function POST(request: NextRequest) { task, model, label, - runTimeoutSeconds: timeout + runTimeoutSeconds: timeout, + tools: { + profile: getPreferredToolsProfile(), + }, } - const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})` try { - // Execute the spawn command - const { stdout, stderr } = await runClawdbot(['-c', commandArg], { - timeoutMs: 10000 - }) + // Execute the spawn command (OpenClaw 2026.3.2+ defaults tools.profile to messaging). + let stdout = '' + let stderr = '' + let compatibilityFallbackUsed = false + try { + const result = await runSpawnWithCompatibility(spawnPayload) + stdout = result.stdout + stderr = result.stderr + } catch (firstError: any) { + const rawErr = String(firstError?.stderr || firstError?.message || '').toLowerCase() + const likelySchemaMismatch = + rawErr.includes('unknown field') || + rawErr.includes('unknown key') || + rawErr.includes('invalid argument') || + rawErr.includes('tools') || + rawErr.includes('profile') + if (!likelySchemaMismatch) throw firstError + + const fallbackPayload = { ...spawnPayload } + delete (fallbackPayload as any).tools + const fallback = await runSpawnWithCompatibility(fallbackPayload) + stdout = fallback.stdout + stderr = fallback.stderr + compatibilityFallbackUsed = true + } // Parse the response to extract session info let sessionInfo = null @@ -63,7 +95,11 @@ export async function POST(request: NextRequest) { timeoutSeconds: timeout, createdAt: Date.now(), stdout: stdout.trim(), - stderr: stderr.trim() + stderr: stderr.trim(), + compatibility: { + toolsProfile: getPreferredToolsProfile(), + fallbackUsed: compatibilityFallbackUsed, + }, }) } catch (execError: any) { diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.ts index 3c286d594e88848123b807429ae93df17865510b..c8cb5366c0f52a7d7e4b766d8a40105cf1404976 100644 --- a/src/app/api/status/route.ts +++ b/src/app/api/status/route.ts @@ -1,6 +1,7 @@ import { NextRequest, NextResponse } from 'next/server' import net from 'node:net' -import { existsSync, readFileSync, statSync } from 'node:fs' +import os from 'node:os' +import { existsSync, statSync } from 'node:fs' import path from 'node:path' import { runCommand, runOpenClaw, runClawdbot } from '@/lib/command' import { config } from '@/lib/config' @@ -9,6 +10,7 @@ import { getAllGatewaySessions, getAgentLiveStatuses } from '@/lib/sessions' import { requireRole } from '@/lib/auth' import { MODEL_CATALOG } from '@/lib/models' import { logger } from '@/lib/logger' +import { detectProviderSubscriptions, getPrimarySubscription } from '@/lib/provider-subscriptions' export async function GET(request: NextRequest) { const auth = requireRole(request, 'viewer') @@ -194,29 +196,48 @@ async function getSystemStatus(workspaceId: number) { } try { - // System uptime - const { stdout: uptimeOutput } = await runCommand('uptime', ['-s'], { - timeoutMs: 3000 - }) - const bootTime = new Date(uptimeOutput.trim()) - status.uptime = Date.now() - bootTime.getTime() + // System uptime (cross-platform) + if (process.platform === 'darwin') { + const { stdout } = await runCommand('sysctl', ['-n', 'kern.boottime'], { + timeoutMs: 3000 + }) + // Output format: { sec = 1234567890, usec = 0 } ... + const match = stdout.match(/sec\s*=\s*(\d+)/) + if (match) { + status.uptime = Date.now() - parseInt(match[1]) * 1000 + } + } else { + const { stdout } = await runCommand('uptime', ['-s'], { + timeoutMs: 3000 + }) + const bootTime = new Date(stdout.trim()) + status.uptime = Date.now() - bootTime.getTime() + } } catch (error) { logger.error({ err: error }, 'Error getting uptime') } try { - // Memory info - const { stdout: memOutput } = await runCommand('free', ['-m'], { - timeoutMs: 3000 - }) - const memLines = memOutput.split('\n') - const memLine = memLines.find(line => line.startsWith('Mem:')) - if (memLine) { - const parts = memLine.split(/\s+/) - status.memory = { - total: parseInt(parts[1]) || 0, - used: parseInt(parts[2]) || 0, - available: parseInt(parts[6]) || 0 + // Memory info (cross-platform) + if (process.platform === 'darwin') { + const totalBytes = os.totalmem() + const freeBytes = os.freemem() + const totalMB = Math.round(totalBytes / (1024 * 1024)) + const usedMB = Math.round((totalBytes - freeBytes) / (1024 * 1024)) + const availableMB = Math.round(freeBytes / (1024 * 1024)) + status.memory = { total: totalMB, used: usedMB, available: availableMB } + } else { + const { stdout: memOutput } = await runCommand('free', ['-m'], { + timeoutMs: 3000 + }) + const memLine = memOutput.split('\n').find(line => line.startsWith('Mem:')) + if (memLine) { + const parts = memLine.split(/\s+/) + status.memory = { + total: parseInt(parts[1]) || 0, + used: parseInt(parts[2]) || 0, + available: parseInt(parts[6]) || 0 + } } } } catch (error) { @@ -413,14 +434,17 @@ async function performHealthCheck() { }) } - // Check disk space + // Check disk space (cross-platform: use df -h / and parse capacity column) try { - const { stdout } = await runCommand('df', ['/', '--output=pcent'], { + const { stdout } = await runCommand('df', ['-h', '/'], { timeoutMs: 3000 }) const lines = stdout.trim().split('\n') const last = lines[lines.length - 1] || '' - const usagePercent = parseInt(last.replace('%', '').trim() || '0') + const parts = last.split(/\s+/) + // On macOS capacity is col 4 ("85%"), on Linux use% is col 4 as well + const pctField = parts.find(p => p.endsWith('%')) || '0%' + const usagePercent = parseInt(pctField.replace('%', '') || '0') health.checks.push({ name: 'Disk Space', @@ -435,15 +459,21 @@ async function performHealthCheck() { }) } - // Check memory usage + // Check memory usage (cross-platform) try { - const { stdout } = await runCommand('free', ['-m'], { timeoutMs: 3000 }) - const lines = stdout.split('\n') - const memLine = lines.find((line) => line.startsWith('Mem:')) - const parts = (memLine || '').split(/\s+/) - const total = parseInt(parts[1] || '0') - const available = parseInt(parts[6] || '0') - const usagePercent = Math.round(((total - available) / total) * 100) + let usagePercent: number + if (process.platform === 'darwin') { + const totalBytes = os.totalmem() + const freeBytes = os.freemem() + usagePercent = Math.round(((totalBytes - freeBytes) / totalBytes) * 100) + } else { + const { stdout } = await runCommand('free', ['-m'], { timeoutMs: 3000 }) + const memLine = stdout.split('\n').find((line) => line.startsWith('Mem:')) + const parts = (memLine || '').split(/\s+/) + const total = parseInt(parts[1] || '0') + const available = parseInt(parts[6] || '0') + usagePercent = Math.round(((total - available) / total) * 100) + } health.checks.push({ name: 'Memory Usage', @@ -475,7 +505,10 @@ async function performHealthCheck() { async function getCapabilities() { const gateway = await isPortOpen(config.gatewayHost, config.gatewayPort) - const openclawHome = !!(config.openclawHome && existsSync(config.openclawHome)) + const openclawHome = Boolean( + (config.openclawStateDir && existsSync(config.openclawStateDir)) || + (config.openclawConfigPath && existsSync(config.openclawConfigPath)) + ) const claudeProjectsPath = path.join(config.claudeHome, 'projects') const claudeHome = existsSync(claudeProjectsPath) @@ -491,25 +524,14 @@ async function getCapabilities() { // claude_sessions table may not exist } - // Detect Claude subscription type from credentials - let subscription: { type: string; rateLimitTier?: string } | null = null - try { - const credsPath = path.join(config.claudeHome, '.credentials.json') - if (existsSync(credsPath)) { - const creds = JSON.parse(readFileSync(credsPath, 'utf-8')) - const oauth = creds.claudeAiOauth - if (oauth?.subscriptionType) { - subscription = { - type: oauth.subscriptionType, - rateLimitTier: oauth.rateLimitTier || undefined, - } - } - } - } catch { - // credentials file may not exist or be unreadable - } + const subscriptions = detectProviderSubscriptions().active + const primary = getPrimarySubscription() + const subscription = primary ? { + type: primary.type, + provider: primary.provider, + } : null - return { gateway, openclawHome, claudeHome, claudeSessions, subscription } + return { gateway, openclawHome, claudeHome, claudeSessions, subscription, subscriptions } } function isPortOpen(host: string, port: number): Promise { diff --git a/src/app/api/tasks/[id]/comments/route.ts b/src/app/api/tasks/[id]/comments/route.ts index ff8a27521c62de59812ef136a2fe20a00ae69ae7..72d19ff83e499e6258afe2e4c6618c270bea76e1 100644 --- a/src/app/api/tasks/[id]/comments/route.ts +++ b/src/app/api/tasks/[id]/comments/route.ts @@ -4,6 +4,7 @@ import { requireRole } from '@/lib/auth'; import { validateBody, createCommentSchema } from '@/lib/validation'; import { mutationLimiter } from '@/lib/rate-limit'; import { logger } from '@/lib/logger'; +import { resolveMentionRecipients } from '@/lib/mentions'; /** * GET /api/tasks/[id]/comments - Get all comments for a task @@ -128,8 +129,13 @@ export async function POST( } } - // Parse @mentions from content - const mentions = db_helpers.parseMentions(content); + const mentionResolution = resolveMentionRecipients(content, db, workspaceId); + if (mentionResolution.unresolved.length > 0) { + return NextResponse.json({ + error: `Unknown mentions: ${mentionResolution.unresolved.map((m) => `@${m}`).join(', ')}`, + missing_mentions: mentionResolution.unresolved + }, { status: 400 }); + } const now = Math.floor(Date.now() / 1000); @@ -145,7 +151,7 @@ export async function POST( content, now, parent_id || null, - mentions.length > 0 ? JSON.stringify(mentions) : null, + mentionResolution.tokens.length > 0 ? JSON.stringify(mentionResolution.tokens) : null, workspaceId ); @@ -166,7 +172,7 @@ export async function POST( task_id: taskId, task_title: task.title, parent_id, - mentions, + mentions: mentionResolution.tokens, content_preview: content.substring(0, 100) }, workspaceId @@ -174,9 +180,9 @@ export async function POST( // Ensure subscriptions for author, mentions, and assignee db_helpers.ensureTaskSubscription(taskId, author, workspaceId); - const uniqueMentions = Array.from(new Set(mentions)); - uniqueMentions.forEach((mentionedAgent) => { - db_helpers.ensureTaskSubscription(taskId, mentionedAgent, workspaceId); + const mentionRecipients = mentionResolution.recipients; + mentionRecipients.forEach((mentionedRecipient) => { + db_helpers.ensureTaskSubscription(taskId, mentionedRecipient, workspaceId); }); if (task.assigned_to) { db_helpers.ensureTaskSubscription(taskId, task.assigned_to, workspaceId); @@ -185,7 +191,7 @@ export async function POST( // Notify subscribers const subscribers = new Set(db_helpers.getTaskSubscribers(taskId, workspaceId)); subscribers.delete(author); - const mentionSet = new Set(uniqueMentions); + const mentionSet = new Set(mentionRecipients); for (const subscriber of subscribers) { const isMention = mentionSet.has(subscriber); diff --git a/src/app/api/tasks/[id]/route.ts b/src/app/api/tasks/[id]/route.ts index 1e5fd47f044811d31ccf244ae4a2896d5f1f4847..40bf44fa32cce704832468b3e81ed74c5fad2b4d 100644 --- a/src/app/api/tasks/[id]/route.ts +++ b/src/app/api/tasks/[id]/route.ts @@ -5,6 +5,22 @@ import { requireRole } from '@/lib/auth'; import { mutationLimiter } from '@/lib/rate-limit'; import { logger } from '@/lib/logger'; import { validateBody, updateTaskSchema } from '@/lib/validation'; +import { resolveMentionRecipients } from '@/lib/mentions'; +import { normalizeTaskUpdateStatus } from '@/lib/task-status'; + +function formatTicketRef(prefix?: string | null, num?: number | null): string | undefined { + if (!prefix || typeof num !== 'number' || !Number.isFinite(num) || num <= 0) return undefined + return `${prefix}-${String(num).padStart(3, '0')}` +} + +function mapTaskRow(task: any): Task & { tags: string[]; metadata: Record } { + return { + ...task, + tags: task.tags ? JSON.parse(task.tags) : [], + metadata: task.metadata ? JSON.parse(task.metadata) : {}, + ticket_ref: formatTicketRef(task.project_prefix, task.project_ticket_no), + } +} function hasAegisApproval( db: ReturnType, @@ -40,7 +56,12 @@ export async function GET( return NextResponse.json({ error: 'Invalid task ID' }, { status: 400 }); } - const stmt = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?'); + const stmt = db.prepare(` + SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix + FROM tasks t + LEFT JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id + WHERE t.id = ? AND t.workspace_id = ? + `); const task = stmt.get(taskId, workspaceId) as Task; if (!task) { @@ -48,11 +69,7 @@ export async function GET( } // Parse JSON fields - const taskWithParsedData = { - ...task, - tags: task.tags ? JSON.parse(task.tags) : [], - metadata: task.metadata ? JSON.parse(task.metadata) : {} - }; + const taskWithParsedData = mapTaskRow(task); return NextResponse.json({ task: taskWithParsedData }); } catch (error) { @@ -99,21 +116,47 @@ export async function PUT( const { title, description, - status, + status: requestedStatus, priority, + project_id, assigned_to, due_date, estimated_hours, actual_hours, + outcome, + error_message, + resolution, + feedback_rating, + feedback_notes, + retry_count, + completed_at, tags, metadata } = body; + const normalizedStatus = normalizeTaskUpdateStatus({ + currentStatus: currentTask.status, + requestedStatus, + assignedTo: assigned_to, + assignedToProvided: assigned_to !== undefined, + }) const now = Math.floor(Date.now() / 1000); + const descriptionMentionResolution = description !== undefined + ? resolveMentionRecipients(description || '', db, workspaceId) + : null; + if (descriptionMentionResolution && descriptionMentionResolution.unresolved.length > 0) { + return NextResponse.json({ + error: `Unknown mentions: ${descriptionMentionResolution.unresolved.map((m) => `@${m}`).join(', ')}`, + missing_mentions: descriptionMentionResolution.unresolved + }, { status: 400 }); + } + + const previousDescriptionMentionRecipients = resolveMentionRecipients(currentTask.description || '', db, workspaceId).recipients; // Build dynamic update query const fieldsToUpdate = []; const updateParams: any[] = []; + let nextProjectTicketNo: number | null = null; if (title !== undefined) { fieldsToUpdate.push('title = ?'); @@ -123,20 +166,50 @@ export async function PUT( fieldsToUpdate.push('description = ?'); updateParams.push(description); } - if (status !== undefined) { - if (status === 'done' && !hasAegisApproval(db, taskId, workspaceId)) { + if (normalizedStatus !== undefined) { + if (normalizedStatus === 'done' && !hasAegisApproval(db, taskId, workspaceId)) { return NextResponse.json( { error: 'Aegis approval is required to move task to done.' }, { status: 403 } ) } fieldsToUpdate.push('status = ?'); - updateParams.push(status); + updateParams.push(normalizedStatus); } if (priority !== undefined) { fieldsToUpdate.push('priority = ?'); updateParams.push(priority); } + if (project_id !== undefined) { + const project = db.prepare(` + SELECT id FROM projects + WHERE id = ? AND workspace_id = ? AND status = 'active' + `).get(project_id, workspaceId) as { id: number } | undefined + if (!project) { + return NextResponse.json({ error: 'Project not found or archived' }, { status: 400 }) + } + if (project_id !== currentTask.project_id) { + db.prepare(` + UPDATE projects + SET ticket_counter = ticket_counter + 1, updated_at = unixepoch() + WHERE id = ? AND workspace_id = ? + `).run(project_id, workspaceId) + const row = db.prepare(` + SELECT ticket_counter FROM projects + WHERE id = ? AND workspace_id = ? + `).get(project_id, workspaceId) as { ticket_counter: number } | undefined + if (!row || !row.ticket_counter) { + return NextResponse.json({ error: 'Failed to allocate project ticket number' }, { status: 500 }) + } + nextProjectTicketNo = row.ticket_counter + } + fieldsToUpdate.push('project_id = ?'); + updateParams.push(project_id); + if (nextProjectTicketNo !== null) { + fieldsToUpdate.push('project_ticket_no = ?'); + updateParams.push(nextProjectTicketNo); + } + } if (assigned_to !== undefined) { fieldsToUpdate.push('assigned_to = ?'); updateParams.push(assigned_to); @@ -153,6 +226,37 @@ export async function PUT( fieldsToUpdate.push('actual_hours = ?'); updateParams.push(actual_hours); } + if (outcome !== undefined) { + fieldsToUpdate.push('outcome = ?'); + updateParams.push(outcome); + } + if (error_message !== undefined) { + fieldsToUpdate.push('error_message = ?'); + updateParams.push(error_message); + } + if (resolution !== undefined) { + fieldsToUpdate.push('resolution = ?'); + updateParams.push(resolution); + } + if (feedback_rating !== undefined) { + fieldsToUpdate.push('feedback_rating = ?'); + updateParams.push(feedback_rating); + } + if (feedback_notes !== undefined) { + fieldsToUpdate.push('feedback_notes = ?'); + updateParams.push(feedback_notes); + } + if (retry_count !== undefined) { + fieldsToUpdate.push('retry_count = ?'); + updateParams.push(retry_count); + } + if (completed_at !== undefined) { + fieldsToUpdate.push('completed_at = ?'); + updateParams.push(completed_at); + } else if (normalizedStatus === 'done' && !currentTask.completed_at) { + fieldsToUpdate.push('completed_at = ?'); + updateParams.push(now); + } if (tags !== undefined) { fieldsToUpdate.push('tags = ?'); updateParams.push(JSON.stringify(tags)); @@ -181,8 +285,8 @@ export async function PUT( // Track changes and log activities const changes: string[] = []; - if (status && status !== currentTask.status) { - changes.push(`status: ${currentTask.status} → ${status}`); + if (normalizedStatus !== undefined && normalizedStatus !== currentTask.status) { + changes.push(`status: ${currentTask.status} → ${normalizedStatus}`); // Create notification for status change if assigned if (currentTask.assigned_to) { @@ -190,7 +294,7 @@ export async function PUT( currentTask.assigned_to, 'status_change', 'Task Status Updated', - `Task "${currentTask.title}" status changed to ${status}`, + `Task "${currentTask.title}" status changed to ${normalizedStatus}`, 'task', taskId, workspaceId @@ -223,6 +327,32 @@ export async function PUT( if (priority && priority !== currentTask.priority) { changes.push(`priority: ${currentTask.priority} → ${priority}`); } + + if (project_id !== undefined && project_id !== currentTask.project_id) { + changes.push(`project: ${currentTask.project_id || 'none'} → ${project_id}`); + } + if (outcome !== undefined && outcome !== currentTask.outcome) { + changes.push(`outcome: ${currentTask.outcome || 'unset'} → ${outcome || 'unset'}`); + } + + if (descriptionMentionResolution) { + const newMentionRecipients = new Set(descriptionMentionResolution.recipients); + const previousRecipients = new Set(previousDescriptionMentionRecipients); + for (const recipient of newMentionRecipients) { + if (previousRecipients.has(recipient)) continue; + db_helpers.ensureTaskSubscription(taskId, recipient, workspaceId); + if (recipient === auth.user.username) continue; + db_helpers.createNotification( + recipient, + 'mention', + 'You were mentioned in a task description', + `${auth.user.username} mentioned you in task "${title || currentTask.title}"`, + 'task', + taskId, + workspaceId + ); + } + } // Log activity if there were meaningful changes if (changes.length > 0) { @@ -240,21 +370,20 @@ export async function PUT( priority: currentTask.priority, assigned_to: currentTask.assigned_to }, - newValues: { title, status, priority, assigned_to } + newValues: { title, status: normalizedStatus ?? currentTask.status, priority, assigned_to } }, workspaceId ); } // Fetch updated task - const updatedTask = db - .prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?') - .get(taskId, workspaceId) as Task; - const parsedTask = { - ...updatedTask, - tags: updatedTask.tags ? JSON.parse(updatedTask.tags) : [], - metadata: updatedTask.metadata ? JSON.parse(updatedTask.metadata) : {} - }; + const updatedTask = db.prepare(` + SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix + FROM tasks t + LEFT JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id + WHERE t.id = ? AND t.workspace_id = ? + `).get(taskId, workspaceId) as Task; + const parsedTask = mapTaskRow(updatedTask); // Broadcast to SSE clients eventBus.broadcast('task.updated', parsedTask); diff --git a/src/app/api/tasks/outcomes/route.ts b/src/app/api/tasks/outcomes/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..67c62c6128f738e52d4e603447aa8f0ae979e988 --- /dev/null +++ b/src/app/api/tasks/outcomes/route.ts @@ -0,0 +1,163 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireRole } from '@/lib/auth' +import { getDatabase } from '@/lib/db' +import { logger } from '@/lib/logger' + +type Outcome = 'success' | 'failed' | 'partial' | 'abandoned' + +function resolveSince(timeframe: string): number { + const now = Math.floor(Date.now() / 1000) + switch (timeframe) { + case 'day': + return now - 24 * 60 * 60 + case 'week': + return now - 7 * 24 * 60 * 60 + case 'month': + return now - 30 * 24 * 60 * 60 + case 'all': + default: + return 0 + } +} + +function outcomeBuckets() { + return { + success: 0, + failed: 0, + partial: 0, + abandoned: 0, + unknown: 0, + } +} + +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + try { + const workspaceId = auth.user.workspace_id ?? 1 + const { searchParams } = new URL(request.url) + const timeframe = (searchParams.get('timeframe') || 'all').trim().toLowerCase() + const since = resolveSince(timeframe) + + const db = getDatabase() + const rows = db.prepare(` + SELECT + id, + assigned_to, + priority, + outcome, + error_message, + retry_count, + created_at, + completed_at + FROM tasks + WHERE workspace_id = ? + AND status = 'done' + AND (? = 0 OR COALESCE(completed_at, updated_at) >= ?) + `).all(workspaceId, since, since) as Array<{ + id: number + assigned_to?: string | null + priority?: string | null + outcome?: string | null + error_message?: string | null + retry_count?: number | null + created_at?: number | null + completed_at?: number | null + }> + + const summary = { + total_done: rows.length, + with_outcome: 0, + by_outcome: outcomeBuckets(), + avg_retry_count: 0, + avg_time_to_resolution_seconds: 0, + success_rate: 0, + } + + const byAgent: Record & { total: number; success_rate: number }> = {} + const byPriority: Record & { total: number; success_rate: number }> = {} + const errorMap = new Map() + + let totalRetryCount = 0 + let totalResolutionSeconds = 0 + let resolutionCount = 0 + + for (const row of rows) { + const outcome = (row.outcome || 'unknown') as Outcome | 'unknown' + const assignedTo = row.assigned_to || 'unassigned' + const priority = row.priority || 'unknown' + const retryCount = Number.isFinite(row.retry_count) ? Number(row.retry_count) : 0 + + if (outcome !== 'unknown') summary.with_outcome += 1 + if (outcome in summary.by_outcome) { + summary.by_outcome[outcome as keyof typeof summary.by_outcome] += 1 + } else { + summary.by_outcome.unknown += 1 + } + + if (!byAgent[assignedTo]) { + byAgent[assignedTo] = { ...outcomeBuckets(), total: 0, success_rate: 0 } + } + byAgent[assignedTo].total += 1 + if (outcome in byAgent[assignedTo]) { + byAgent[assignedTo][outcome as keyof ReturnType] += 1 + } else { + byAgent[assignedTo].unknown += 1 + } + + if (!byPriority[priority]) { + byPriority[priority] = { ...outcomeBuckets(), total: 0, success_rate: 0 } + } + byPriority[priority].total += 1 + if (outcome in byPriority[priority]) { + byPriority[priority][outcome as keyof ReturnType] += 1 + } else { + byPriority[priority].unknown += 1 + } + + totalRetryCount += retryCount + + if (row.completed_at && row.created_at && row.completed_at >= row.created_at) { + totalResolutionSeconds += (row.completed_at - row.created_at) + resolutionCount += 1 + } + + const errorMessage = (row.error_message || '').trim() + if (errorMessage) { + errorMap.set(errorMessage, (errorMap.get(errorMessage) || 0) + 1) + } + } + + summary.avg_retry_count = rows.length > 0 ? totalRetryCount / rows.length : 0 + summary.avg_time_to_resolution_seconds = resolutionCount > 0 ? totalResolutionSeconds / resolutionCount : 0 + summary.success_rate = summary.with_outcome > 0 ? summary.by_outcome.success / summary.with_outcome : 0 + + for (const agent of Object.values(byAgent)) { + const withOutcome = agent.total - agent.unknown + agent.success_rate = withOutcome > 0 ? agent.success / withOutcome : 0 + } + + for (const priority of Object.values(byPriority)) { + const withOutcome = priority.total - priority.unknown + priority.success_rate = withOutcome > 0 ? priority.success / withOutcome : 0 + } + + const commonErrors = [...errorMap.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([error_message, count]) => ({ error_message, count })) + + return NextResponse.json({ + timeframe, + summary, + by_agent: byAgent, + by_priority: byPriority, + common_errors: commonErrors, + record_count: rows.length, + }) + } catch (error) { + logger.error({ err: error }, 'GET /api/tasks/outcomes error') + return NextResponse.json({ error: 'Failed to fetch task outcomes' }, { status: 500 }) + } +} diff --git a/src/app/api/tasks/queue/route.ts b/src/app/api/tasks/queue/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0aa68c0157dc59f26f2c31c8cf4ae7428deba7b --- /dev/null +++ b/src/app/api/tasks/queue/route.ts @@ -0,0 +1,147 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getDatabase } from '@/lib/db' +import { requireRole } from '@/lib/auth' +import { logger } from '@/lib/logger' + +type QueueReason = 'continue_current' | 'assigned' | 'at_capacity' | 'no_tasks_available' + +function safeParseJson(raw: string | null | undefined, fallback: T): T { + if (!raw) return fallback + try { + return JSON.parse(raw) as T + } catch { + return fallback + } +} + +function mapTaskRow(task: any) { + return { + ...task, + tags: safeParseJson(task.tags, [] as string[]), + metadata: safeParseJson(task.metadata, {} as Record), + } +} + +function priorityRankSql() { + return ` + CASE priority + WHEN 'critical' THEN 0 + WHEN 'high' THEN 1 + WHEN 'medium' THEN 2 + WHEN 'low' THEN 3 + ELSE 4 + END + ` +} + +/** + * GET /api/tasks/queue - Poll next task for an agent. + * + * Query params: + * - agent: required agent name (or use x-agent-name header) + * - max_capacity: optional integer 1..20 (default 1) + */ +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'operator') + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) + + try { + const db = getDatabase() + const workspaceId = auth.user.workspace_id + const { searchParams } = new URL(request.url) + + const agent = + (searchParams.get('agent') || '').trim() || + (request.headers.get('x-agent-name') || '').trim() + + if (!agent) { + return NextResponse.json({ error: 'Missing agent. Provide ?agent=... or x-agent-name header.' }, { status: 400 }) + } + + const maxCapacityRaw = searchParams.get('max_capacity') || '1' + if (!/^\d+$/.test(maxCapacityRaw)) { + return NextResponse.json({ error: 'Invalid max_capacity. Expected integer 1..20.' }, { status: 400 }) + } + const maxCapacity = Number(maxCapacityRaw) + if (!Number.isInteger(maxCapacity) || maxCapacity < 1 || maxCapacity > 20) { + return NextResponse.json({ error: 'Invalid max_capacity. Expected integer 1..20.' }, { status: 400 }) + } + + const now = Math.floor(Date.now() / 1000) + + const currentTask = db.prepare(` + SELECT * + FROM tasks + WHERE workspace_id = ? AND assigned_to = ? AND status = 'in_progress' + ORDER BY updated_at DESC + LIMIT 1 + `).get(workspaceId, agent) as any | undefined + + if (currentTask) { + return NextResponse.json({ + task: mapTaskRow(currentTask), + reason: 'continue_current' as QueueReason, + agent, + timestamp: now, + }) + } + + const inProgressCount = (db.prepare(` + SELECT COUNT(*) as c + FROM tasks + WHERE workspace_id = ? AND assigned_to = ? AND status = 'in_progress' + `).get(workspaceId, agent) as { c: number }).c + + if (inProgressCount >= maxCapacity) { + return NextResponse.json({ + task: null, + reason: 'at_capacity' as QueueReason, + agent, + timestamp: now, + }) + } + + // Best-effort atomic pickup loop for race safety. + for (let attempt = 0; attempt < 5; attempt += 1) { + const candidate = db.prepare(` + SELECT * + FROM tasks + WHERE workspace_id = ? + AND status IN ('assigned', 'inbox') + AND (assigned_to IS NULL OR assigned_to = ?) + ORDER BY ${priorityRankSql()} ASC, due_date ASC NULLS LAST, created_at ASC + LIMIT 1 + `).get(workspaceId, agent) as any | undefined + + if (!candidate) break + + const claimed = db.prepare(` + UPDATE tasks + SET status = 'in_progress', assigned_to = ?, updated_at = ? + WHERE id = ? AND workspace_id = ? + AND status IN ('assigned', 'inbox') + AND (assigned_to IS NULL OR assigned_to = ?) + `).run(agent, now, candidate.id, workspaceId, agent) + + if (claimed.changes > 0) { + const task = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?').get(candidate.id, workspaceId) as any + return NextResponse.json({ + task: mapTaskRow(task), + reason: 'assigned' as QueueReason, + agent, + timestamp: now, + }) + } + } + + return NextResponse.json({ + task: null, + reason: 'no_tasks_available' as QueueReason, + agent, + timestamp: now, + }) + } catch (error) { + logger.error({ err: error }, 'GET /api/tasks/queue error') + return NextResponse.json({ error: 'Failed to poll task queue' }, { status: 500 }) + } +} diff --git a/src/app/api/tasks/route.ts b/src/app/api/tasks/route.ts index ec04cc9bcbd8db23aa110749540f6a05693539aa..931d2def3ee5d0583e68e6d2c1e118d79956588b 100644 --- a/src/app/api/tasks/route.ts +++ b/src/app/api/tasks/route.ts @@ -5,6 +5,45 @@ import { requireRole } from '@/lib/auth'; import { mutationLimiter } from '@/lib/rate-limit'; import { logger } from '@/lib/logger'; import { validateBody, createTaskSchema, bulkUpdateTaskStatusSchema } from '@/lib/validation'; +import { resolveMentionRecipients } from '@/lib/mentions'; +import { normalizeTaskCreateStatus } from '@/lib/task-status'; + +function formatTicketRef(prefix?: string | null, num?: number | null): string | undefined { + if (!prefix || typeof num !== 'number' || !Number.isFinite(num) || num <= 0) return undefined + return `${prefix}-${String(num).padStart(3, '0')}` +} + +function mapTaskRow(task: any): Task & { tags: string[]; metadata: Record } { + return { + ...task, + tags: task.tags ? JSON.parse(task.tags) : [], + metadata: task.metadata ? JSON.parse(task.metadata) : {}, + ticket_ref: formatTicketRef(task.project_prefix, task.project_ticket_no), + } +} + +function resolveProjectId(db: ReturnType, workspaceId: number, requestedProjectId?: number): number { + if (typeof requestedProjectId === 'number' && Number.isFinite(requestedProjectId)) { + const project = db.prepare(` + SELECT id FROM projects + WHERE id = ? AND workspace_id = ? AND status = 'active' + LIMIT 1 + `).get(requestedProjectId, workspaceId) as { id: number } | undefined + if (project) return project.id + } + + const fallback = db.prepare(` + SELECT id FROM projects + WHERE workspace_id = ? AND status = 'active' + ORDER BY CASE WHEN slug = 'general' THEN 0 ELSE 1 END, id ASC + LIMIT 1 + `).get(workspaceId) as { id: number } | undefined + + if (!fallback) { + throw new Error('No active project available in workspace') + } + return fallback.id +} function hasAegisApproval(db: ReturnType, taskId: number, workspaceId: number): boolean { const review = db.prepare(` @@ -18,7 +57,7 @@ function hasAegisApproval(db: ReturnType, taskId: number, wo /** * GET /api/tasks - List all tasks with optional filtering - * Query params: status, assigned_to, priority, limit, offset + * Query params: status, assigned_to, priority, project_id, limit, offset */ export async function GET(request: NextRequest) { const auth = requireRole(request, 'viewer'); @@ -33,40 +72,48 @@ export async function GET(request: NextRequest) { const status = searchParams.get('status'); const assigned_to = searchParams.get('assigned_to'); const priority = searchParams.get('priority'); + const projectIdParam = Number.parseInt(searchParams.get('project_id') || '', 10); const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200); const offset = parseInt(searchParams.get('offset') || '0'); // Build dynamic query - let query = 'SELECT * FROM tasks WHERE workspace_id = ?'; + let query = ` + SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix + FROM tasks t + LEFT JOIN projects p + ON p.id = t.project_id AND p.workspace_id = t.workspace_id + WHERE t.workspace_id = ? + `; const params: any[] = [workspaceId]; if (status) { - query += ' AND status = ?'; + query += ' AND t.status = ?'; params.push(status); } if (assigned_to) { - query += ' AND assigned_to = ?'; + query += ' AND t.assigned_to = ?'; params.push(assigned_to); } if (priority) { - query += ' AND priority = ?'; + query += ' AND t.priority = ?'; params.push(priority); } + + if (Number.isFinite(projectIdParam)) { + query += ' AND t.project_id = ?'; + params.push(projectIdParam); + } - query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'; + query += ' ORDER BY t.created_at DESC LIMIT ? OFFSET ?'; params.push(limit, offset); const stmt = db.prepare(query); const tasks = stmt.all(...params) as Task[]; // Parse JSON fields - const tasksWithParsedData = tasks.map(task => ({ - ...task, - tags: task.tags ? JSON.parse(task.tags) : [], - metadata: task.metadata ? JSON.parse(task.metadata) : {} - })); + const tasksWithParsedData = tasks.map(mapTaskRow); // Get total count for pagination let countQuery = 'SELECT COUNT(*) as total FROM tasks WHERE workspace_id = ?'; @@ -83,6 +130,10 @@ export async function GET(request: NextRequest) { countQuery += ' AND priority = ?'; countParams.push(priority); } + if (Number.isFinite(projectIdParam)) { + countQuery += ' AND project_id = ?'; + countParams.push(projectIdParam); + } const countRow = db.prepare(countQuery).get(...countParams) as { total: number }; return NextResponse.json({ tasks: tasksWithParsedData, total: countRow.total, page: Math.floor(offset / limit) + 1, limit }); @@ -113,15 +164,25 @@ export async function POST(request: NextRequest) { const { title, description, - status = 'inbox', + status, priority = 'medium', + project_id, assigned_to, created_by = user?.username || 'system', due_date, estimated_hours, + actual_hours, + outcome, + error_message, + resolution, + feedback_rating, + feedback_notes, + retry_count = 0, + completed_at, tags = [], metadata = {} } = body; + const normalizedStatus = normalizeTaskCreateStatus(status, assigned_to) // Check for duplicate title const existingTask = db.prepare('SELECT id FROM tasks WHERE title = ? AND workspace_id = ?').get(title, workspaceId); @@ -130,44 +191,95 @@ export async function POST(request: NextRequest) { } const now = Math.floor(Date.now() / 1000); - - const stmt = db.prepare(` - INSERT INTO tasks ( - title, description, status, priority, assigned_to, created_by, - created_at, updated_at, due_date, estimated_hours, tags, metadata, workspace_id - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - - const dbResult = stmt.run( - title, - description, - status, - priority, - assigned_to, - created_by, - now, - now, - due_date, - estimated_hours, - JSON.stringify(tags), - JSON.stringify(metadata), - workspaceId - ); + const mentionResolution = resolveMentionRecipients(description || '', db, workspaceId); + if (mentionResolution.unresolved.length > 0) { + return NextResponse.json({ + error: `Unknown mentions: ${mentionResolution.unresolved.map((m) => `@${m}`).join(', ')}`, + missing_mentions: mentionResolution.unresolved + }, { status: 400 }); + } + + const resolvedCompletedAt = completed_at ?? (normalizedStatus === 'done' ? now : null) + + const createTaskTx = db.transaction(() => { + const resolvedProjectId = resolveProjectId(db, workspaceId, project_id) + db.prepare(` + UPDATE projects + SET ticket_counter = ticket_counter + 1, updated_at = unixepoch() + WHERE id = ? AND workspace_id = ? + `).run(resolvedProjectId, workspaceId) + const row = db.prepare(` + SELECT ticket_counter FROM projects + WHERE id = ? AND workspace_id = ? + `).get(resolvedProjectId, workspaceId) as { ticket_counter: number } | undefined + if (!row || !row.ticket_counter) throw new Error('Failed to allocate project ticket number') - const taskId = dbResult.lastInsertRowid as number; + const insertStmt = db.prepare(` + INSERT INTO tasks ( + title, description, status, priority, project_id, project_ticket_no, assigned_to, created_by, + created_at, updated_at, due_date, estimated_hours, actual_hours, + outcome, error_message, resolution, feedback_rating, feedback_notes, retry_count, completed_at, + tags, metadata, workspace_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `) + + const dbResult = insertStmt.run( + title, + description, + normalizedStatus, + priority, + resolvedProjectId, + row.ticket_counter, + assigned_to, + created_by, + now, + now, + due_date, + estimated_hours, + actual_hours, + outcome, + error_message, + resolution, + feedback_rating, + feedback_notes, + retry_count, + resolvedCompletedAt, + JSON.stringify(tags), + JSON.stringify(metadata), + workspaceId + ) + return Number(dbResult.lastInsertRowid) + }) + + const taskId = createTaskTx() // Log activity db_helpers.logActivity('task_created', 'task', taskId, created_by, `Created task: ${title}`, { title, - status, + status: normalizedStatus, priority, - assigned_to + assigned_to, + ...(outcome ? { outcome } : {}) }, workspaceId); if (created_by) { db_helpers.ensureTaskSubscription(taskId, created_by, workspaceId) } + for (const recipient of mentionResolution.recipients) { + db_helpers.ensureTaskSubscription(taskId, recipient, workspaceId); + if (recipient === created_by) continue; + db_helpers.createNotification( + recipient, + 'mention', + 'You were mentioned in a task description', + `${created_by} mentioned you in task "${title}"`, + 'task', + taskId, + workspaceId + ); + } + // Create notification if assigned if (assigned_to) { db_helpers.ensureTaskSubscription(taskId, assigned_to, workspaceId) @@ -183,12 +295,14 @@ export async function POST(request: NextRequest) { } // Fetch the created task - const createdTask = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?').get(taskId, workspaceId) as Task; - const parsedTask = { - ...createdTask, - tags: JSON.parse(createdTask.tags || '[]'), - metadata: JSON.parse(createdTask.metadata || '{}') - }; + const createdTask = db.prepare(` + SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix + FROM tasks t + LEFT JOIN projects p + ON p.id = t.project_id AND p.workspace_id = t.workspace_id + WHERE t.id = ? AND t.workspace_id = ? + `).get(taskId, workspaceId) as Task; + const parsedTask = mapTaskRow(createdTask); // Broadcast to SSE clients eventBus.broadcast('task.created', parsedTask); @@ -224,6 +338,11 @@ export async function PUT(request: NextRequest) { SET status = ?, updated_at = ? WHERE id = ? AND workspace_id = ? `); + const updateDoneStmt = db.prepare(` + UPDATE tasks + SET status = ?, updated_at = ?, completed_at = COALESCE(completed_at, ?) + WHERE id = ? AND workspace_id = ? + `); const actor = auth.user.username @@ -236,7 +355,11 @@ export async function PUT(request: NextRequest) { throw new Error(`Aegis approval required for task ${task.id}`) } - updateStmt.run(task.status, now, task.id, workspaceId); + if (task.status === 'done') { + updateDoneStmt.run(task.status, now, now, task.id, workspaceId); + } else { + updateStmt.run(task.status, now, task.id, workspaceId); + } // Log status change if different if (oldTask && oldTask.status !== task.status) { diff --git a/src/app/api/tokens/route.ts b/src/app/api/tokens/route.ts index 24fefd583f0ee39e68bb40b06871a736712479b7..87e58ccc09b60cd6b14816d092f807b31b7703c2 100644 --- a/src/app/api/tokens/route.ts +++ b/src/app/api/tokens/route.ts @@ -6,6 +6,9 @@ import { requireRole } from '@/lib/auth' import { getAllGatewaySessions } from '@/lib/sessions' import { logger } from '@/lib/logger' import { getDatabase } from '@/lib/db' +import { calculateTokenCost } from '@/lib/token-pricing' +import { getProviderSubscriptionFlags } from '@/lib/provider-subscriptions' +import { buildTaskCostReport, type TaskCostMetadata } from '@/lib/task-costs' const DATA_PATH = config.tokensPath @@ -20,6 +23,8 @@ interface TokenUsageRecord { totalTokens: number cost: number operation: string + taskId?: number | null + workspaceId?: number duration?: number } @@ -38,22 +43,7 @@ interface ExportData { sessions: Record } -// Model pricing (cost per 1K tokens) -const MODEL_PRICING: Record = { - 'anthropic/claude-3-5-haiku-latest': 0.25, - 'claude-3-5-haiku': 0.25, - 'anthropic/claude-sonnet-4-20250514': 3.0, - 'claude-sonnet-4': 3.0, - 'anthropic/claude-opus-4-5': 15.0, - 'claude-opus-4-5': 15.0, - 'groq/llama-3.1-8b-instant': 0.05, - 'groq/llama-3.3-70b-versatile': 0.59, - 'moonshot/kimi-k2.5': 1.0, - 'minimax/minimax-m2.1': 0.3, - 'ollama/deepseek-r1:14b': 0.0, - 'ollama/qwen2.5-coder:7b': 0.0, - 'ollama/qwen2.5-coder:14b': 0.0, -} +interface TaskMetadataRow extends TaskCostMetadata {} function extractAgentName(sessionId: string): string { const trimmed = sessionId.trim() @@ -62,36 +52,30 @@ function extractAgentName(sessionId: string): string { return agent?.trim() || 'unknown' } -function getModelCost(modelName: string): number { - if (MODEL_PRICING[modelName] !== undefined) return MODEL_PRICING[modelName] - for (const [model, cost] of Object.entries(MODEL_PRICING)) { - if (modelName.includes(model.split('/').pop() || '')) return cost - } - return 1.0 -} - interface DbTokenUsageRow { id: number model: string session_id: string input_tokens: number output_tokens: number + task_id?: number | null + workspace_id?: number created_at: number } -function loadTokenDataFromDb(): TokenUsageRecord[] { +function loadTokenDataFromDb(workspaceId: number, providerSubscriptions: Record): TokenUsageRecord[] { try { const db = getDatabase() const rows = db.prepare(` - SELECT id, model, session_id, input_tokens, output_tokens, created_at + SELECT id, model, session_id, input_tokens, output_tokens, task_id, workspace_id, created_at FROM token_usage + WHERE workspace_id = ? ORDER BY created_at DESC, id DESC LIMIT 10000 - `).all() as DbTokenUsageRow[] + `).all(workspaceId) as DbTokenUsageRow[] return rows.map((row) => { const totalTokens = row.input_tokens + row.output_tokens - const costPer1k = getModelCost(row.model) return { id: `db-${row.id}`, model: row.model, @@ -101,8 +85,10 @@ function loadTokenDataFromDb(): TokenUsageRecord[] { inputTokens: row.input_tokens, outputTokens: row.output_tokens, totalTokens, - cost: (totalTokens / 1000) * costPer1k, + cost: calculateTokenCost(row.model, row.input_tokens, row.output_tokens, { providerSubscriptions }), operation: 'heartbeat', + taskId: row.task_id ?? null, + workspaceId: row.workspace_id ?? workspaceId, } }) } catch (error) { @@ -111,7 +97,10 @@ function loadTokenDataFromDb(): TokenUsageRecord[] { } } -function normalizeTokenRecord(record: Partial): TokenUsageRecord | null { +function normalizeTokenRecord( + record: Partial, + providerSubscriptions: Record, +): TokenUsageRecord | null { if (!record.model || !record.sessionId) return null const inputTokens = Number(record.inputTokens ?? 0) const outputTokens = Number(record.outputTokens ?? 0) @@ -126,8 +115,10 @@ function normalizeTokenRecord(record: Partial): TokenUsageReco inputTokens, outputTokens, totalTokens, - cost: Number(record.cost ?? (totalTokens / 1000) * getModelCost(model)), + cost: Number(record.cost ?? calculateTokenCost(model, inputTokens, outputTokens, { providerSubscriptions })), operation: String(record.operation ?? 'chat_completion'), + taskId: record.taskId != null && Number.isFinite(Number(record.taskId)) ? Number(record.taskId) : null, + workspaceId: record.workspaceId != null && Number.isFinite(Number(record.workspaceId)) ? Number(record.workspaceId) : 1, duration: record.duration, } } @@ -145,6 +136,8 @@ function dedupeTokenRecords(records: TokenUsageRecord[]): TokenUsageRecord[] { record.outputTokens, record.totalTokens, record.operation, + record.taskId ?? '', + record.workspaceId ?? 1, record.duration ?? '', ].join('|') if (seen.has(key)) continue @@ -155,7 +148,7 @@ function dedupeTokenRecords(records: TokenUsageRecord[]): TokenUsageRecord[] { return deduped } -async function loadTokenDataFromFile(): Promise { +async function loadTokenDataFromFile(workspaceId: number, providerSubscriptions: Record): Promise { try { ensureDirExists(dirname(DATA_PATH)) await access(DATA_PATH) @@ -164,8 +157,13 @@ async function loadTokenDataFromFile(): Promise { if (!Array.isArray(parsed)) return [] return parsed - .map((record: Partial) => normalizeTokenRecord(record)) + .map((record: Partial) => normalizeTokenRecord(record, providerSubscriptions)) .filter((record): record is TokenUsageRecord => record !== null) + .filter((record) => { + if (record.workspaceId === workspaceId) return true + // Backward compatibility for pre-workspace records + return workspaceId === 1 && (!record.workspaceId || record.workspaceId === 1) + }) } catch { return [] } @@ -174,34 +172,33 @@ async function loadTokenDataFromFile(): Promise { /** * Load token data from persistent file, falling back to deriving from session stores. */ -async function loadTokenData(): Promise { - const dbRecords = loadTokenDataFromDb() - const fileRecords = await loadTokenDataFromFile() +async function loadTokenData(workspaceId: number): Promise { + const providerSubscriptions = getProviderSubscriptionFlags() + const dbRecords = loadTokenDataFromDb(workspaceId, providerSubscriptions) + const fileRecords = await loadTokenDataFromFile(workspaceId, providerSubscriptions) const combined = dedupeTokenRecords([...dbRecords, ...fileRecords]).sort((a, b) => b.timestamp - a.timestamp) if (combined.length > 0) { return combined } // Final fallback: derive from in-memory sessions - return deriveFromSessions() + return deriveFromSessions(workspaceId, providerSubscriptions) } /** * Derive token usage records from OpenClaw session stores. * Each session has totalTokens, inputTokens, outputTokens, model, etc. */ -function deriveFromSessions(): TokenUsageRecord[] { +function deriveFromSessions(workspaceId: number, providerSubscriptions: Record): TokenUsageRecord[] { const sessions = getAllGatewaySessions(Infinity) // Get ALL sessions regardless of age const records: TokenUsageRecord[] = [] for (const session of sessions) { - if (!session.totalTokens && !session.model) continue // Skip empty sessions - - const totalTokens = session.totalTokens || 0 - const inputTokens = session.inputTokens || Math.round(totalTokens * 0.7) - const outputTokens = session.outputTokens || totalTokens - inputTokens - const costPer1k = getModelCost(session.model || '') - const cost = (totalTokens / 1000) * costPer1k + const inputTokens = session.inputTokens || 0 + const outputTokens = session.outputTokens || 0 + const totalTokens = inputTokens + outputTokens + if (totalTokens <= 0 && !session.model) continue // Skip empty sessions + const cost = calculateTokenCost(session.model || '', inputTokens, outputTokens, { providerSubscriptions }) records.push({ id: `session-${session.agent}-${session.key}`, @@ -214,6 +211,8 @@ function deriveFromSessions(): TokenUsageRecord[] { totalTokens, cost, operation: session.chatType || 'chat', + taskId: null, + workspaceId, }) } @@ -275,17 +274,48 @@ function filterByTimeframe(records: TokenUsageRecord[], timeframe: string): Toke return records.filter(record => record.timestamp >= cutoffTime) } +function loadTaskMetadataById(workspaceId: number, taskIds: number[]): Record { + if (taskIds.length === 0) return {} + const db = getDatabase() + const placeholders = taskIds.map(() => '?').join(', ') + const rows = db.prepare(` + SELECT + t.id, + t.title, + t.status, + t.priority, + t.assigned_to, + t.project_id, + p.name as project_name, + p.slug as project_slug, + p.ticket_prefix as project_prefix, + t.project_ticket_no + FROM tasks t + LEFT JOIN projects p + ON p.id = t.project_id AND p.workspace_id = t.workspace_id + WHERE t.workspace_id = ? + AND t.id IN (${placeholders}) + `).all(workspaceId, ...taskIds) as TaskMetadataRow[] + + const out: Record = {} + for (const row of rows) { + out[row.id] = row + } + return out +} + export async function GET(request: NextRequest) { const auth = requireRole(request, 'viewer') if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }) try { const { searchParams } = new URL(request.url) - const action = searchParams.get('action') || 'list' + const action = (searchParams.get('action') || 'list').trim().toLowerCase() const timeframe = searchParams.get('timeframe') || 'all' const format = searchParams.get('format') || 'json' - const tokenData = await loadTokenData() + const workspaceId = auth.user.workspace_id ?? 1 + const tokenData = await loadTokenData(workspaceId) const filteredData = filterByTimeframe(tokenData, timeframe) if (action === 'list') { @@ -399,6 +429,34 @@ export async function GET(request: NextRequest) { }) } + if (action === 'task-costs' || action === 'task_costs' || action === 'taskcosts') { + const attributedTaskIds = [...new Set( + filteredData + .map((record) => record.taskId) + .filter((taskId): taskId is number => Number.isFinite(taskId) && Number(taskId) > 0) + .map((taskId) => Number(taskId)) + )] + const taskMetadataById = loadTaskMetadataById(workspaceId, attributedTaskIds) + const report = buildTaskCostReport( + filteredData.map((record) => ({ + model: record.model, + agentName: record.agentName || extractAgentName(record.sessionId), + timestamp: record.timestamp, + totalTokens: record.totalTokens, + cost: record.cost, + taskId: record.taskId ?? null, + })), + taskMetadataById + ) + + return NextResponse.json({ + ...report, + timeframe, + recordCount: filteredData.length, + attributedRecordCount: filteredData.filter((record) => Number.isFinite(record.taskId)).length, + }) + } + if (action === 'export') { const overallStats = calculateStats(filteredData) const modelStats: Record = {} @@ -490,7 +548,7 @@ export async function GET(request: NextRequest) { return NextResponse.json({ trends, timeframe }) } - return NextResponse.json({ error: 'Invalid action' }, { status: 400 }) + return NextResponse.json({ error: 'Invalid action', action }, { status: 400 }) } catch (error) { logger.error({ err: error }, 'Tokens API error') return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) @@ -503,15 +561,29 @@ export async function POST(request: NextRequest) { try { const body = await request.json() - const { model, sessionId, inputTokens, outputTokens, operation = 'chat_completion', duration } = body + const workspaceId = auth.user.workspace_id ?? 1 + const { model, sessionId, inputTokens, outputTokens, operation = 'chat_completion', duration, taskId } = body if (!model || !sessionId || typeof inputTokens !== 'number' || typeof outputTokens !== 'number') { return NextResponse.json({ error: 'Missing required fields' }, { status: 400 }) } const totalTokens = inputTokens + outputTokens - const costPer1k = getModelCost(model) - const cost = (totalTokens / 1000) * costPer1k + const providerSubscriptions = getProviderSubscriptionFlags() + const cost = calculateTokenCost(model, inputTokens, outputTokens, { providerSubscriptions }) + const parsedTaskId = + taskId != null && Number.isFinite(Number(taskId)) && Number(taskId) > 0 + ? Number(taskId) + : null + + let validatedTaskId: number | null = null + if (parsedTaskId) { + const db = getDatabase() + const taskRow = db.prepare( + 'SELECT id FROM tasks WHERE id = ? AND workspace_id = ?' + ).get(parsedTaskId, workspaceId) as { id?: number } | undefined + if (taskRow?.id) validatedTaskId = taskRow.id + } const record: TokenUsageRecord = { id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, @@ -524,11 +596,13 @@ export async function POST(request: NextRequest) { totalTokens, cost, operation, + taskId: validatedTaskId, + workspaceId, duration, } // Persist only manually posted usage records in the JSON file. - const existingData = await loadTokenDataFromFile() + const existingData = await loadTokenDataFromFile(workspaceId, providerSubscriptions) existingData.unshift(record) if (existingData.length > 10000) { diff --git a/src/app/api/workload/route.ts b/src/app/api/workload/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..516c71e7b12adcbac4dd3c2eeb4565181c8c0443 --- /dev/null +++ b/src/app/api/workload/route.ts @@ -0,0 +1,319 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { getDatabase } from '@/lib/db'; +import { requireRole } from '@/lib/auth'; +import { logger } from '@/lib/logger'; + +/** + * GET /api/workload - Real-Time Workload Signals + * + * Provides system-wide capacity metrics and throttle recommendations + * so agents can make informed decisions about work submission. + * + * Response: + * capacity - Current system capacity metrics + * queue - Task queue depth and breakdown + * agents - Agent availability and load distribution + * recommendation - Actionable signal: normal | throttle | shed | pause + * thresholds - Current threshold configuration + * + * Agents should call this before submitting new work to avoid + * cascading failures and SLO breaches. + */ +export async function GET(request: NextRequest) { + const auth = requireRole(request, 'viewer'); + if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status }); + + try { + const db = getDatabase(); + const workspaceId = auth.user.workspace_id ?? 1; + const now = Math.floor(Date.now() / 1000); + + // --- Capacity metrics --- + const capacity = buildCapacityMetrics(db, workspaceId, now); + + // --- Queue depth --- + const queue = buildQueueMetrics(db, workspaceId); + + // --- Agent availability --- + const agents = buildAgentMetrics(db, workspaceId, now); + + // --- Recommendation --- + const recommendation = computeRecommendation(capacity, queue, agents); + + return NextResponse.json({ + timestamp: now, + workspace_id: workspaceId, + capacity, + queue, + agents, + recommendation, + thresholds: THRESHOLDS, + }); + } catch (error) { + logger.error({ err: error }, 'GET /api/workload error'); + return NextResponse.json({ error: 'Failed to fetch workload signals' }, { status: 500 }); + } +} + +// Configurable thresholds for recommendation engine +function numEnv(name: string, fallback: number): number { + const raw = process.env[name]; + if (!raw || raw.trim().length === 0) return fallback; + const parsed = Number(raw); + return Number.isFinite(parsed) ? parsed : fallback; +} + +function buildThresholds() { + return { + queue_depth_normal: numEnv('MC_WORKLOAD_QUEUE_DEPTH_NORMAL', 20), + queue_depth_throttle: numEnv('MC_WORKLOAD_QUEUE_DEPTH_THROTTLE', 50), + queue_depth_shed: numEnv('MC_WORKLOAD_QUEUE_DEPTH_SHED', 100), + busy_agent_ratio_throttle: numEnv('MC_WORKLOAD_BUSY_RATIO_THROTTLE', 0.8), + busy_agent_ratio_shed: numEnv('MC_WORKLOAD_BUSY_RATIO_SHED', 0.95), + error_rate_throttle: numEnv('MC_WORKLOAD_ERROR_RATE_THROTTLE', 0.1), + error_rate_shed: numEnv('MC_WORKLOAD_ERROR_RATE_SHED', 0.25), + recent_window_seconds: Math.max(1, Math.floor(numEnv('MC_WORKLOAD_RECENT_WINDOW_SECONDS', 300))), + }; +} + +const THRESHOLDS = buildThresholds(); + +interface CapacityMetrics { + active_tasks: number; + tasks_last_5m: number; + errors_last_5m: number; + error_rate_5m: number; + completions_last_hour: number; + avg_completion_rate_per_hour: number; +} + +interface QueueMetrics { + total_pending: number; + by_status: Record; + by_priority: Record; + oldest_pending_age_seconds: number | null; + estimated_wait_seconds: number | null; + estimated_wait_confidence: 'calculated' | 'unknown'; +} + +interface AgentMetrics { + total: number; + online: number; + busy: number; + idle: number; + offline: number; + busy_ratio: number; + load_distribution: Array<{ agent: string; assigned: number; in_progress: number }>; +} + +function buildCapacityMetrics(db: any, workspaceId: number, now: number): CapacityMetrics { + const recentWindow = now - THRESHOLDS.recent_window_seconds; + const hourAgo = now - 3600; + + const activeTasks = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status IN ('assigned', 'in_progress', 'review', 'quality_review')` + ).get(workspaceId) as any).c; + + const tasksLast5m = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ? AND type IN ('task_created', 'task_assigned')` + ).get(workspaceId, recentWindow) as any).c; + + const errorsLast5m = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%')` + ).get(workspaceId, recentWindow) as any).c; + + const totalLast5m = (db.prepare( + `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ?` + ).get(workspaceId, recentWindow) as any).c; + + const completionsLastHour = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?` + ).get(workspaceId, hourAgo) as any).c; + + // Average completion rate over last 24h + const dayAgo = now - 86400; + const completionsLastDay = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?` + ).get(workspaceId, dayAgo) as any).c; + + const safeErrorRate = totalLast5m > 0 ? errorsLast5m / totalLast5m : 0; + + return { + active_tasks: activeTasks, + tasks_last_5m: tasksLast5m, + errors_last_5m: errorsLast5m, + error_rate_5m: Math.max(0, Math.min(1, Math.round(safeErrorRate * 10000) / 10000)), + completions_last_hour: completionsLastHour, + avg_completion_rate_per_hour: Math.round((completionsLastDay / 24) * 100) / 100, + }; +} + +function buildQueueMetrics(db: any, workspaceId: number): QueueMetrics { + const now = Math.floor(Date.now() / 1000); + + const pendingStatuses = ['inbox', 'assigned', 'in_progress', 'review', 'quality_review']; + + const byStatus = db.prepare( + `SELECT status, COUNT(*) as count FROM tasks WHERE workspace_id = ? AND status IN (${pendingStatuses.map(() => '?').join(',')}) GROUP BY status` + ).all(workspaceId, ...pendingStatuses) as Array<{ status: string; count: number }>; + + const byPriority = db.prepare( + `SELECT priority, COUNT(*) as count FROM tasks WHERE workspace_id = ? AND status IN (${pendingStatuses.map(() => '?').join(',')}) GROUP BY priority` + ).all(workspaceId, ...pendingStatuses) as Array<{ priority: string; count: number }>; + + const totalPending = byStatus.reduce((sum, r) => sum + r.count, 0); + + const oldest = db.prepare( + `SELECT MIN(created_at) as oldest FROM tasks WHERE workspace_id = ? AND status IN ('inbox', 'assigned')` + ).get(workspaceId) as any; + + const oldestAge = oldest?.oldest ? now - oldest.oldest : null; + + // Estimate wait: pending tasks / completion rate per hour * 3600 + const hourAgo = now - 3600; + const completionsLastHour = (db.prepare( + `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?` + ).get(workspaceId, hourAgo) as any).c; + + const estimatedWait = completionsLastHour > 0 + ? Math.round((totalPending / completionsLastHour) * 3600) + : null; + + const statusMap = Object.fromEntries(byStatus.map(r => [r.status, r.count])); + for (const status of pendingStatuses) { + if (typeof statusMap[status] !== 'number') statusMap[status] = 0; + } + + const priorityMap = Object.fromEntries(byPriority.map(r => [r.priority, r.count])); + for (const priority of ['low', 'medium', 'high', 'critical', 'urgent']) { + if (typeof priorityMap[priority] !== 'number') priorityMap[priority] = 0; + } + + return { + total_pending: totalPending, + by_status: statusMap, + by_priority: priorityMap, + oldest_pending_age_seconds: oldestAge, + estimated_wait_seconds: estimatedWait, + estimated_wait_confidence: estimatedWait === null ? 'unknown' : 'calculated', + }; +} + +function buildAgentMetrics(db: any, workspaceId: number, now: number): AgentMetrics { + const agentStatuses = db.prepare( + `SELECT status, COUNT(*) as count FROM agents WHERE workspace_id = ? GROUP BY status` + ).all(workspaceId) as Array<{ status: string; count: number }>; + + const statusMap: Record = {}; + let total = 0; + for (const row of agentStatuses) { + statusMap[row.status] = row.count; + total += row.count; + } + + const online = (statusMap['idle'] || 0) + (statusMap['busy'] || 0); + const busy = statusMap['busy'] || 0; + const idle = statusMap['idle'] || 0; + const offline = statusMap['offline'] || 0; + + // Load distribution per agent + const loadDist = db.prepare(` + SELECT a.name as agent, + SUM(CASE WHEN t.status = 'assigned' THEN 1 ELSE 0 END) as assigned, + SUM(CASE WHEN t.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress + FROM agents a + LEFT JOIN tasks t ON t.assigned_to = a.name AND t.workspace_id = a.workspace_id AND t.status IN ('assigned', 'in_progress') + WHERE a.workspace_id = ? AND a.status != 'offline' + GROUP BY a.name + ORDER BY (assigned + in_progress) DESC + `).all(workspaceId) as Array<{ agent: string; assigned: number; in_progress: number }>; + + return { + total, + online, + busy, + idle, + offline, + busy_ratio: online > 0 ? Math.round((busy / online) * 100) / 100 : 0, + load_distribution: loadDist, + }; +} + +type RecommendationLevel = 'normal' | 'throttle' | 'shed' | 'pause'; + +interface Recommendation { + action: RecommendationLevel; + reason: string; + details: string[]; + submit_ok: boolean; + suggested_delay_ms: number; +} + +function computeRecommendation( + capacity: CapacityMetrics, + queue: QueueMetrics, + agents: AgentMetrics +): Recommendation { + const reasons: string[] = []; + let level: RecommendationLevel = 'normal'; + + // Check error rate + if (capacity.error_rate_5m >= THRESHOLDS.error_rate_shed) { + level = escalate(level, 'shed'); + reasons.push(`High error rate: ${(capacity.error_rate_5m * 100).toFixed(1)}%`); + } else if (capacity.error_rate_5m >= THRESHOLDS.error_rate_throttle) { + level = escalate(level, 'throttle'); + reasons.push(`Elevated error rate: ${(capacity.error_rate_5m * 100).toFixed(1)}%`); + } + + // Check queue depth + if (queue.total_pending >= THRESHOLDS.queue_depth_shed) { + level = escalate(level, 'shed'); + reasons.push(`Queue depth critical: ${queue.total_pending} pending tasks`); + } else if (queue.total_pending >= THRESHOLDS.queue_depth_throttle) { + level = escalate(level, 'throttle'); + reasons.push(`Queue depth high: ${queue.total_pending} pending tasks`); + } + + // Check agent saturation + if (agents.busy_ratio >= THRESHOLDS.busy_agent_ratio_shed) { + level = escalate(level, 'shed'); + reasons.push(`Agent saturation critical: ${(agents.busy_ratio * 100).toFixed(0)}% busy`); + } else if (agents.busy_ratio >= THRESHOLDS.busy_agent_ratio_throttle) { + level = escalate(level, 'throttle'); + reasons.push(`Agent saturation high: ${(agents.busy_ratio * 100).toFixed(0)}% busy`); + } + + // No online agents = pause + if (agents.online === 0) { + level = 'pause'; + reasons.push(agents.total > 0 ? 'No agents online' : 'No agents registered'); + } + + const delayMap: Record = { + normal: 0, + throttle: 2000, + shed: 10000, + pause: 30000, + }; + + const actionDescriptions: Record = { + normal: 'System healthy — submit work freely', + throttle: 'System under load — reduce submission rate and defer non-critical work', + shed: 'System overloaded — submit only critical/high-priority work, defer everything else', + pause: 'System unavailable — hold all submissions until capacity returns', + }; + + return { + action: level, + reason: actionDescriptions[level], + details: reasons.length > 0 ? reasons : ['All metrics within normal bounds'], + submit_ok: level === 'normal' || level === 'throttle', + suggested_delay_ms: delayMap[level], + }; +} + +function escalate(current: RecommendationLevel, proposed: RecommendationLevel): RecommendationLevel { + const order: RecommendationLevel[] = ['normal', 'throttle', 'shed', 'pause']; + return order.indexOf(proposed) > order.indexOf(current) ? proposed : current; +} diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx index 176acd28682b5fa669e782ef8e4d6c0c7087baba..ca5f0bf50aed8ded4cfa58166c88f6bd6e782500 100644 --- a/src/components/ErrorBoundary.tsx +++ b/src/components/ErrorBoundary.tsx @@ -1,6 +1,9 @@ 'use client' import { Component, type ErrorInfo, type ReactNode } from 'react' +import { createClientLogger } from '@/lib/client-logger' + +const log = createClientLogger('ErrorBoundary') interface Props { children: ReactNode @@ -23,7 +26,7 @@ export class ErrorBoundary extends Component { } componentDidCatch(error: Error, errorInfo: ErrorInfo) { - console.error('Panel error:', error, errorInfo) + log.error('Panel error:', error, errorInfo) } render() { diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx index 0b239420d4038411615924d5437b1417417d71a1..3584c3bc8285086370b5eeb87cb053dae21d5a7b 100644 --- a/src/components/chat/chat-panel.tsx +++ b/src/components/chat/chat-panel.tsx @@ -3,10 +3,13 @@ import { useEffect, useCallback, useState, useRef } from 'react' import { useMissionControl } from '@/store' import { useSmartPoll } from '@/lib/use-smart-poll' +import { createClientLogger } from '@/lib/client-logger' import { ConversationList } from './conversation-list' import { MessageList } from './message-list' import { ChatInput } from './chat-input' +const log = createClientLogger('ChatPanel') + export function ChatPanel() { const { chatPanelOpen, @@ -52,7 +55,7 @@ export function ChatPanel() { const data = await res.json() if (data.agents) setAgents(data.agents) } catch (err) { - console.error('Failed to load agents:', err) + log.error('Failed to load agents:', err) } } if (chatPanelOpen) loadAgents() @@ -67,7 +70,7 @@ export function ChatPanel() { const data = await res.json() if (data.messages) setChatMessages(data.messages) } catch (err) { - console.error('Failed to load messages:', err) + log.error('Failed to load messages:', err) } }, [activeConversation, setChatMessages]) @@ -145,7 +148,7 @@ export function ChatPanel() { updatePendingMessage(tempId, { pendingStatus: 'failed' }) } } catch (err) { - console.error('Failed to send message:', err) + log.error('Failed to send message:', err) updatePendingMessage(tempId, { pendingStatus: 'failed' }) } } diff --git a/src/components/chat/conversation-list.tsx b/src/components/chat/conversation-list.tsx index ee55a83ff00d2660dfabfdfe714deca2cfaad5e5..5a731d0c2a53974e010668987d02744492e37c6c 100644 --- a/src/components/chat/conversation-list.tsx +++ b/src/components/chat/conversation-list.tsx @@ -3,6 +3,9 @@ import { useState, useCallback } from 'react' import { useMissionControl, Conversation, Agent } from '@/store' import { useSmartPoll } from '@/lib/use-smart-poll' +import { createClientLogger } from '@/lib/client-logger' + +const log = createClientLogger('ConversationList') function timeAgo(timestamp: number): string { const diff = Math.floor(Date.now() / 1000) - timestamp @@ -64,7 +67,7 @@ export function ConversationList({ onNewConversation }: ConversationListProps) { ) } } catch (err) { - console.error('Failed to load conversations:', err) + log.error('Failed to load conversations:', err) } }, [setConversations]) diff --git a/src/components/dashboard/dashboard.tsx b/src/components/dashboard/dashboard.tsx index 38ab1a9808175bc5c0d8199188c5745364a797e0..eab139971f4af3495afd285e20c7cfaa56b4a1e4 100644 --- a/src/components/dashboard/dashboard.tsx +++ b/src/components/dashboard/dashboard.tsx @@ -522,7 +522,7 @@ export function Dashboard() { {isLocal ? ( } onNavigate={navigateToPanel} /> ) : ( - } onNavigate={navigateToPanel} /> + } onNavigate={navigateToPanel} /> )}
diff --git a/src/components/dashboard/sidebar.tsx b/src/components/dashboard/sidebar.tsx index 756caa2c28f5c5f8f5c56982542bbed83d08d829..1b07d72929b3e2b30d110a76cb10af399ddf6764 100644 --- a/src/components/dashboard/sidebar.tsx +++ b/src/components/dashboard/sidebar.tsx @@ -3,6 +3,9 @@ import { useEffect, useState } from 'react' import { useMissionControl } from '@/store' import { useNavigateToPanel } from '@/lib/navigation' +import { createClientLogger } from '@/lib/client-logger' + +const log = createClientLogger('Sidebar') interface MenuItem { id: string @@ -36,7 +39,7 @@ export function Sidebar() { fetch('/api/status?action=overview') .then(res => res.json()) .then(data => setSystemStats(data)) - .catch(err => console.error('Failed to fetch system status:', err)) + .catch(err => log.error('Failed to fetch system status:', err)) }, []) const activeSessions = sessions.filter(s => s.active).length diff --git a/src/components/layout/header-bar.tsx b/src/components/layout/header-bar.tsx index 8d38cfb6938dd34f50e66a61cc03b945101e3514..e0aa3a3b590635d230c625003c01a2727402e3f2 100644 --- a/src/components/layout/header-bar.tsx +++ b/src/components/layout/header-bar.tsx @@ -43,6 +43,7 @@ export function HeaderBar() { alerts: 'Alert Rules', gateways: 'Gateway Manager', users: 'Users', + workspaces: 'Workspaces', 'gateway-config': 'Gateway Config', settings: 'Settings', } diff --git a/src/components/layout/live-feed.tsx b/src/components/layout/live-feed.tsx index dae3c77cd55eadad7bb95a1af5b569dd37bdc5bd..f64420be48f49207bb2e5d6c0096a287259bfcb7 100644 --- a/src/components/layout/live-feed.tsx +++ b/src/components/layout/live-feed.tsx @@ -7,6 +7,7 @@ export function LiveFeed() { const { logs, sessions, activities, connection, dashboardMode, toggleLiveFeed } = useMissionControl() const isLocal = dashboardMode === 'local' const [expanded, setExpanded] = useState(true) + const [hasCollapsed, setHasCollapsed] = useState(false) // Combine logs, activities, and (in local mode) session events into a unified feed const sessionItems = isLocal @@ -70,7 +71,7 @@ export function LiveFeed() { } return ( -
+
{/* Header */}
@@ -80,7 +81,7 @@ export function LiveFeed() {