# Project export: TokenWatcher – AI Cost & Observability Platform

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: OpenAI Build Week
- Tagline: Enterprise AI observability platform that helps developers monitor token usage, costs, latency, and AI performance across OpenAI and other LLM providers—with real-time analytics and an AI Copilot.
- Devpost: https://devpost.com/software/tokenwatcher-ai-cost-observability-platform
- GitHub: https://github.com/ZainabTravadi/Token-Watcher-AI-API-Cost-Tracker
- Demo: https://token-watcher-ai-api-cost-tracker-f.vercel.app/
- Video: https://www.youtube.com/embed/_pTjGToKCVg?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — Zainab Travadi (5 commits)

## Devpost submission (written by the team)

### Overview

The Problem As AI applications move into production, developers often know how much they're spending only after receiving their monthly invoice. They lack visibility into which models, endpoints, users, or features are driving costs, increasing latency, or generating failures. Existing dashboards expose raw API metrics, but they rarely provide actionable insights that help engineering teams understand, optimize, and control AI infrastructure. Our Solution TokenWatcher is an AI observability platform that helps developers monitor, analyze, and optimize production AI applications. It provides a unified dashboard for AI telemetry across multiple providers, allowing teams to: Monitor token usage and API costs Track latency and request failures Analyze model and endpoint performance Forecast future AI spending Detect anomalies Receive AI-powered optimization recommendations Instead of manually combining logs, spreadsheets, and invoices, developers get real-time visibility into how their AI systems behave. Key Features Real-time AI telemetry dashboard Multi-workspace support Token, cost, latency, and request analytics Model and endpoint performance dashboards Cost forecasting AI-powered insights and recommendations SDK for telemetry instrumentation Secure API key management Telegram integration through OpenClaw Live updates using Server-Sent Events (SSE) Built with GPT-5.6 and Codex For OpenAI Build Week, GPT-5.6 and Codex became an integral part of our development workflow. We used Codex extensively to accelerate implementation by: Debugging backend services Refactoring TypeScript modules Improving project architecture Implementing new dashboard functionality Resolving integration issues Generating and refining documentation Speeding up testing and development iterations GPT-5.6 also helped with architecture decisions, implementation planning, debugging strategies, documentation, and feature refinement throughout development. Rather than simply generating code, Codex acted as a collaborative engineering assistant that significantly accelerated the development of a production-ready platform. Technical Architecture TokenWatcher consists of four major components: TypeScript SDK for telemetry collection Express + PostgreSQL backend React analytics dashboard OpenClaw-powered Telegram interface Telemetry collected by the SDK is securely ingested by the backend, processed into analytics, and streamed to the dashboard in real time. The same analytics layer powers forecasting, reports, recommendations, and conversational Telegram interactions. Challenges Building an observability platform required balancing performance with flexibility. Some of the biggest challenges included: Designing a scalable telemetry ingestion pipeline Handling workspace isolation securely Maintaining real-time dashboard updates Building reliable analytics and forecasting Integrating Telegram workflows without compromising security What We Learned Building TokenWatcher reinforced how quickly AI infrastructure complexity grows in production. Observability is no longer optional—teams need visibility into token usage, costs, latency, and reliability from day one. Combining traditional analytics with AI-powered recommendations creates a much better developer experience than static dashboards alone. What's Next Our roadmap includes: Support for additional LLM providers Advanced anomaly detection Deeper forecasting models More conversational AI workflows Expanded reporting and export capabilities Enterprise deployment improvements

## README (from the GitHub repository)

<p align="center">
  <img src="logo.png" alt="TokenWatcher Satellite" width="300">
</p>

<h1 align="center">TokenWatcher</h1>

<p align="center">
  <em>Every request has a story.</em>
</p>

TokenWatch is a production telemetry, analytics, and Telegram delivery platform for AI applications.
It instruments your application directly, stores request telemetry in PostgreSQL, and turns raw usage data into dashboards, forecasts, reports, and Telegram replies.

## What problem it solves

Many AI products know their model invoices before they know their product behavior.
TokenWatch closes that gap by showing:

▪️ what each request costs
▪️ which models and endpoints are driving spend
▪️ how latency and errors change over time
▪️ what should be optimized next
▪️ how to surface the same data in Telegram

## Solution

TokenWatch keeps the instrumentation simple:

▪️ the SDK captures telemetry at the source
▪️ the backend authenticates, normalizes, and stores `requests`
▪️ the analytics engine derives dashboards, forecasts, reports, and recommendations from the same table
▪️ the dashboard and Telegram bot read the same workspace-scoped data
▪️ OpenClaw bridges Telegram traffic back to TokenWatch safely

## Key Features

▪️ workspace-isolated telemetry and analytics
▪️ bounded SDK queueing, batching, retries, and shutdown flush
▪️ live dashboard updates over SSE
▪️ request log search, filters, and exports
▪️ forecasts, reports, recommendations, anomalies, and Copilot tools
▪️ Telegram bot integration through BotFather and OpenClaw
▪️ production-ready auth, API keys, and secret handling

## Architecture Overview

```mermaid
flowchart LR
  App[Developer Application]
  SDK[TokenWatch SDK]
  API[Backend API]
  DB[(PostgreSQL)]
  Engine[Analytics Engine]
  Dash[Dashboard]
  TG[Telegram Integration]
  OC[OpenClaw Agent]
  User[User]

  App --> SDK --> API --> DB --> Engine --> Dash --> TG --> OC --> User
```

The detailed system guide lives in [`docs/architecture.md`](docs/architecture.md).

## Technology Stack

| Layer | Stack |
|---|---|
| Backend | Node.js, Express, TypeScript, PostgreSQL |
| Frontend | React 18, Vite, React Query, Tailwind, shadcn/ui |
| SDK | TypeScript, fetch-based transport, bounded queue, retries |
| Telegram bridge | OpenClaw, Telegram Bot API |
| Realtime | Server-Sent Events |

## Folder Structure

| Folder | Responsibility |
|---|---|
| `backend/` | API, auth, ingest, analytics, storage, notifications |
| `frontend/` | Dashboard, settings, docs pages, charts, and SSE client |
| `sdk/` | Public telemetry SDK published to npm |
| `openclaw/` | Stateless Telegram bridge and intent router |
| `docs/` | Canonical product, platform, and contributor documentation |
| `backend/src/db/` | Database schema and startup schema application |

## Installation

Install the workspace packages you need:

```bash
cd backend
npm install

cd ../frontend
npm install

cd ../sdk
npm install

cd ../openclaw
npm install
```

## Environment Variables

The full environment matrix is documented in [`docs/deployment.md`](docs/deployment.md). The most important variables are:

| Component | Variables |
|---|---|
| Backend | `DATABASE_URL`, `JWT_SECRET`, `CORS_ORIGIN`, `TOKENWATCHER_SECRET_ENCRYPTION_KEY`, `OPENCLAW_INTERNAL_SECRET`, `OPENCLAW_PUBLIC_URL`, `RESEND_API_KEY`, `RESEND_FROM_EMAIL`, `X402_ENABLED`, `X402_MODE`, `X402_GATEWAY_URL`, `X402_API_KEY`, `X402_API_SECRET`, `X402_MERCHANT_ID`, `X402_NETWORK`, `X402_CHAIN_ID`, `X402_PAYMENT_TOKEN`, `X402_RECEIVING_WALLET`, `X402_ANALYZE_COST_PRICE_USD`, `X402_MOCK_PAYMENT_TOKEN` |
| Frontend | `VITE_TOKENWATCH_API_URL` |
| OpenClaw | `TOKENWATCHER_API_URL`, `OPENCLAW_INTERNAL_SECRET`, `OPENCLAW_PORT`, `OPENCLAW_HOST`, `TOKENWATCHER_TIMEOUT_MS`, `TOKENWATCHER_USER_AGENT` |

## Running Locally

```bash
# Backend
cd backend
npm run dev

# Frontend
cd frontend
npm run dev

# OpenClaw
cd openclaw
npm run build
npm start
```

The backend listens on `http://localhost:3001` by default.
The frontend runs on Vite's dev server.
OpenClaw listens on `http://localhost:3300` by default.

## Running with Docker

No official Docker workflow is committed yet.
Use the local commands above or add Docker assets if your deployment strategy needs them.

## SDK Usage

```ts
import { TokenWatch } from "@zn_/tokenwatch";

TokenWatch.init({
  apiUrl: "http://localhost:3001",
  apiKey: process.env.TOKENWATCH_API_KEY!,
});

await TokenWatch.track("llm.request.completed", {
  route: "/api/chat",
  provider: "openai",
  model: "gpt-4o",
  input_tokens: 120,
  output_tokens: 80,
  cost_usd: 0.0042,
  latency_ms: 640,
});

await TokenWatch.flush();
```

The full SDK guide is in [`docs/sdk.md`](docs/sdk.md).

## Telemetry Flow

1. The developer application emits telemetry through the SDK.
2. The SDK batches and sends the payload to the backend ingest API.
3. The backend authenticates the workspace and stores telemetry in `requests`.
4. Analytics, forecasts, reports, and recommendations are derived from the same source table.
5. The dashboard refreshes through SSE and workspace-scoped queries.
6. Telegram and OpenClaw read the same workspace data to answer user requests.

See [`docs/architecture.md`](docs/architecture.md) for the full lifecycle.

## ERC-8004 And x402

TokenWatcher is registered externally as ERC-8004 Agent #80 on GOAT Mainnet.
The application exposes that public identity at `GET /api/agent` and publishes three paid capabilities:

- `POST /api/agent/analyze-cost`
- `POST /api/agent/optimize-cost`
- `POST /api/agent/health`

Each paid capability uses x402 payment protection:

- the server returns a `402 Payment Required` challenge when no payment proof is present,
- the client submits payment using the configured GOAT merchant path,
- the backend binds the payment to the requested capability before executing its logic,
- the backend verifies the payment server-side, rejects expired or mismatched payments, and reuses the canonical telemetry pipeline for analytics and intelligence results.

Local development can use `X402_MODE=mock` together with `X402_MOCK_PAYMENT_TOKEN`.
Production must use real x402 verification and must not enable mock mode.

The paid capabilities remain workspace-scoped and still use the existing auth and ownership rules after payment verification.

## Dashboard Overview

The dashboard is documented in [`docs/frontend.md`](docs/frontend.md). The main screens are:

▪️ Overview
▪️ Requests
▪️ Models
▪️ Endpoints
▪️ Settings
▪️ Agent & payments

Each screen is backed by the same telemetry source of truth.

## Telegram Integration

Telegram setup lives in [`docs/telegram.md`](docs/telegram.md).
In short:

▪️ create a bot in BotFather
▪️ paste the token into `Settings -> Telegram Integration`
▪️ connect the bot
▪️ send the bot one message
▪️ use Test to confirm delivery

## OpenClaw Integration

OpenClaw is the stateless Telegram bridge used by TokenWatch.
Read the guide in [`docs/openclaw.md`](docs/openclaw.md) for the webhook flow, intent routing, and tool execution model.

## Built with GPT-5.6 & Codex

TokenWatcher was developed and refined with the help of **GPT-5.6 and Codex** throughout the project lifecycle.

Codex served as an AI pair programmer, accelerating development by helping with:

- Debugging backend and frontend issues
- Refactoring TypeScript modules for better maintainability
- Implementing new features and production-ready workflows
- Resolving API integration and SDK issues
- Improving project architecture and code organization
- Generating and refining technical documentation
- Assisting with testing, code reviews, and optimization

During development, Codex was used across numerous engineering tasks, including production readiness audits, telemetry pipeline improvements, SDK stabilization, onboarding enhancements, Telegram integration, adapter verification, bug fixes, and documentation updates.

GPT-5.6 was also used to reason through architecture decisions, implementation strategies, debugging appro

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 259 recognized source files, 1242 KB.
- CSS (language) — detected in the code
- Express (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- PostgreSQL (technology) — detected in the code
- React (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Node.js (technology) — claimed on Devpost, not found in the code
- AI coding agent: Codex — evidence: config files committed to the repository

## Codebase structure (from repository index)

### Files (120 of 288)

```
.env.example
.github/workflows/ci.yml
.gitignore
AGENTS.md
backend/.gitignore
backend/HEROKU_DEPLOY.md
backend/package.json
backend/Procfile
backend/scripts/db_check.ts
backend/scripts/reset_and_seed.ts
backend/scripts/run_ai_insights.ts
backend/scripts/seedAiInsightsData.ts
backend/scripts/seedAiInsightsInsert.ts
backend/scripts/testGemini.ts
backend/scripts/verify_seed.ts
backend/src/config/agentIdentity.ts
backend/src/config/cookies.ts
backend/src/config/env.ts
backend/src/core/app.ts
backend/src/core/server.ts
backend/src/db/database.ts
backend/src/db/schema.ts
backend/src/main.ts
backend/src/middleware/auth.ts
backend/src/routes/agent.ts
backend/src/routes/ai.ts
backend/src/routes/analytics.ts
backend/src/routes/auth.ts
backend/src/routes/copilot.ts
backend/src/routes/forecast.ts
backend/src/routes/health.ts
backend/src/routes/index.ts
backend/src/routes/ingest.ts
backend/src/routes/intelligence.ts
backend/src/routes/me.ts
backend/src/routes/reports.ts
backend/src/routes/requests.ts
backend/src/routes/telegramIntegrations.ts
backend/src/routes/telemetry.ts
backend/src/routes/workspaces.ts
backend/src/scripts/backup.ts
backend/src/scripts/init_postgres.ts
backend/src/scripts/load_test.ts
backend/src/scripts/retention.ts
backend/src/scripts/seed_ai_telemetry.ts
backend/src/scripts/seed.ts
backend/src/services/agentCapabilityService.ts
backend/src/services/aiInsightsService.ts
backend/src/services/analyticsCache.ts
backend/src/services/analyticsService.ts
backend/src/services/anomalyService.ts
backend/src/services/auditService.ts
backend/src/services/authService.ts
backend/src/services/copilotService.ts
backend/src/services/demoRunner.ts
backend/src/services/efficiencyScoreService.ts
backend/src/services/emailService.ts
backend/src/services/emailTemplates.ts
backend/src/services/forecastService.ts
backend/src/services/geminiService.ts
backend/src/services/ingestService.ts
backend/src/services/notificationService.ts
backend/src/services/pdfGeneratorService.ts
backend/src/services/realtimeStreamService.ts
backend/src/services/recommendationService.ts
backend/src/services/reportService.ts
backend/src/services/requestService.ts
backend/src/services/retentionService.ts
backend/src/services/rootCauseService.ts
backend/src/services/simulatorService.ts
backend/src/services/telegramIntegrationService.ts
backend/src/services/telemetryBus.ts
backend/src/services/telemetryGenerator.ts
backend/src/services/telemetryPdfService.ts
backend/src/services/telemetryRepository.ts
backend/src/services/workspaceSimulatorManager.ts
backend/src/services/x402Repository.ts
backend/src/services/x402Service.ts
backend/src/test/agent-x402.test.ts
backend/src/test/api-key-permissions.test.ts
backend/src/test/copilot-service.test.stub.ts
backend/src/test/intelligence-services.test.stub.ts
backend/src/test/report-forecast-services.test.stub.ts
backend/src/test/x402-config.test.ts
backend/src/types/ingest.ts
backend/src/types/requests.ts
backend/src/types/telemetry.ts
backend/src/utils/auth.ts
backend/src/utils/http.ts
backend/src/utils/random.ts
backend/src/utils/sdkAuth.ts
backend/src/utils/secrets.ts
backend/test-gemini.ts
backend/test-workspace-system.ts
backend/tsconfig.json
docs/api.md
docs/architecture.md
docs/backend.md
docs/contributing.md
docs/database.md
docs/deployment.md
docs/frontend.md
docs/openclaw.md
docs/operations.md
docs/ownership.md
docs/playbooks.md
docs/project-structure.md
docs/README.md
docs/sdk.md
docs/security.md
docs/telegram.md
docs/troubleshooting.md
frontend/.gitignore
frontend/bun.lockb
frontend/components.json
frontend/eslint.config.js
frontend/index.html
frontend/package.json
frontend/postcss.config.js
frontend/public/robots.txt
[168 more files omitted for size]
```

### Dependencies

- backend/package.json: @google/genai@^2.8.0, @types/cookie-parser@^1.4.7, @types/express@^5.0.1, @types/node@^24.0.15, @types/pg@^8.15.5, cookie-parser@^1.4.7, dotenv@^16.6.1, express@^5.1.0, pg@^8.16.3, tsx@^4.20.3, typescript@^5.8.3
- frontend/package.json: @eslint/js@^9.32.0, @hookform/resolvers@^3.10.0, @radix-ui/react-accordion@^1.2.11, @radix-ui/react-alert-dialog@^1.1.14, @radix-ui/react-aspect-ratio@^1.1.7, @radix-ui/react-avatar@^1.1.10, @radix-ui/react-checkbox@^1.3.2, @radix-ui/react-collapsible@^1.1.11, @radix-ui/react-context-menu@^2.2.15, @radix-ui/react-dialog@^1.1.14, @radix-ui/react-dropdown-menu@^2.1.15, @radix-ui/react-hover-card@^1.1.14, @radix-ui/react-label@^2.1.7, @radix-ui/react-menubar@^1.1.15, @radix-ui/react-navigation-menu@^1.2.13, @radix-ui/react-popover@^1.1.14, @radix-ui/react-progress@^1.1.7, @radix-ui/react-radio-group@^1.3.7, @radix-ui/react-scroll-area@^1.2.9, @radix-ui/react-select@^2.2.5, @radix-ui/react-separator@^1.1.7, @radix-ui/react-slider@^1.3.5, @radix-ui/react-slot@^1.2.3, @radix-ui/react-switch@^1.2.5, @radix-ui/react-tabs@^1.1.12, @radix-ui/react-toast@^1.2.14, @radix-ui/react-toggle@^1.1.9, @radix-ui/react-toggle-group@^1.1.10, @radix-ui/react-tooltip@^1.2.7, @tailwindcss/typography@^0.5.16, @tanstack/react-query@^5.83.0, @testing-library/jest-dom@^6.6.0, @testing-library/react@^16.0.0, @types/node@^22.16.5, @types/react@^18.3.23, @types/react-dom@^18.3.7, @vitejs/plugin-react-swc@^3.11.0, autoprefixer@^10.4.21, class-variance-authority@^0.7.1, clsx@^2.1.1, cmdk@^1.1.1, date-fns@^3.6.0, embla-carousel-react@^8.6.0, eslint@^9.32.0, eslint-plugin-react-hooks@^5.2.0, eslint-plugin-react-refresh@^0.4.20, globals@^15.15.0, input-otp@^1.4.2, jsdom@^20.0.3, lovable-tagger@^1.1.13, lucide-react@^0.462.0, next-themes@^0.3.0, postcss@^8.5.6, react@^18.3.1, react-day-picker@^8.10.1, react-dom@^18.3.1, react-hook-form@^7.61.1, react-resizable-panels@^2.1.9, react-router-dom@^6.30.1, recharts@^2.15.4, sonner@^1.7.4, tailwind-merge@^2.6.0, tailwindcss@^3.4.17, tailwindcss-animate@^1.0.7, typescript@^5.8.3, typescript-eslint@^8.38.0, vaul@^0.9.9, vite@^5.4.19, vitest@^3.2.4, zod@^3.25.76
- openclaw/package.json: @types/node@^20.10.0, typescript@^5.5.0
- sdk/package.json: typescript@^5.8.3

### Recent commits (newest first)

- Readme update
- feat: add x402 paid agent capabilities
- Update README.md
- Update README.md
- Add files via upload
- Read me update
- Telegram bot instructions
- Update telegram.md
- Docs cleanup
- Final Documentation
- Final working prototype
- Telegram message fix
- Fix sdk issue 1
- Polishing
- Polish
- feat: complete OpenClaw integration and Heroku deployment support
- feat: complete OpenClaw integration and production verification
- feat: polish dashboard and implement email notification system
- feat: add AI intelligence, forecasting, reporting and dashboard improvements
- feat: add Gemini-powered AI Insights engine

## Key source files (fetched from GitHub, selected and truncated for size)

### AGENTS.md

```markdown
# CLAUDE.md

Permanent project memory for TokenWatch. This file is the fast index. Load deeper docs only when the current task requires them.

## Memorize These Facts

- `requests` table is the source of truth for telemetry, analytics, exports, forecasts, reports, and intelligence.
- `backend/src/services/telemetryRepository.ts` owns all request SQL, analytics aggregation, request filters, dimensions, and exports. Whenever analytics, request logs, filters, or exports are mentioned, assume this is the first backend stop.
- `backend/src/services/authService.ts` owns users, workspaces, API keys, workspace settings persistence, and API key permissions.
- `backend/src/middleware/auth.ts` owns cookie auth, API-key auth, workspace enforcement, and permission gates.
- `backend/src/db/schema.ts` owns database shape. `backend/src/db/database.ts` applies schema and ALTER updates on startup. There is no migrations folder.
- `backend/src/services/ingestService.ts` owns ingest validation, normalization, cache invalidation, SSE event emission, and alert evaluation trigger.
- `frontend/src/contexts/StatusContext.tsx` owns the single dashboard SSE `EventSource`.
- `frontend/src/contexts/AuthContext.tsx` owns user/session/workspace selection and `tokenwatch.currentWorkspaceId`.
- `frontend/src/lib/api.ts` owns frontend API contracts, fetch wrappers, query hooks, and shared frontend API types.
- `sdk/src/transport.ts` owns SDK queueing, batching, retries, signing, identity lookup, and shutdown flush.
- `sdk/src/security.ts` and `backend/src/utils/sdkAuth.ts` are paired. Change signed ingest protocol on both sides or neither.
- OpenClaw is an API client bridge only. It never writes the TokenWatch database directly.

## Search Budget

Default maximum files to inspect before stopping:

| Task type | File budget | Rule |
|---|---:|---|
| Simple bug | 5 | Stop when owning file is found and edit there. |
| Feature | 8 | Route/service/page/API-client only unless schema/auth is involved. |
| Refactor | 15 | Continue only with a clear dependency chain. |
| Security/auth/db/SDK transport | 12 | Spend budget cautiously; verify invariants. |
| Architecture/docs audit | unlimited | Only when explicitly requested. |

If the budget is exceeded, stop and explain: files read, what is still unknown, and why more exploration is needed.

Never inspect `node_modules`, `dist`, `build`, `coverage`, `.git`, lockfiles, or generated output for normal feature work.

## Which Doc To Load

| Need | Load |
|---|---|
| High-level flow/lifecycles/connections | `docs/architecture.md` |
| Backend routes/services/auth/notifications/AI | `docs/backend.md` |
| Frontend pages/components/context/data flow | `docs/frontend.md` |
| SDK behavior, batching, retries, signing | `docs/sdk.md` |
| Tables, columns, indexes, schema rules | `docs/database.md` |
| Endpoint auth/request/response ownership | `docs/api.md` |
| Common tasks and exact edit locations | `docs/playbooks.md` |
| Ownership, risk, cost, heatm
[truncated — 17456 more characters]
```

### backend/HEROKU_DEPLOY.md

```markdown
# Backend Deployment to Heroku

This file is kept for backward compatibility.

The canonical deployment guide lives in [`../docs/deployment.md`](../docs/deployment.md).

```

### openclaw/package.json

```
{
  "name": "tokenwatcher-openclaw",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "test": "npm run build && node --test dist/router/intentRouter.test.js",
    "start": "node dist/main.js",
    "verify:phase3a": "node scripts/verify-phase3a.mjs",
    "verify:live": "node scripts/verify-live.mjs",
    "lint": "tsc -p tsconfig.json --noEmit"
  },
  "devDependencies": {
    "typescript": "^5.5.0",
    "@types/node": "^20.10.0"
  }
}

```

### backend/package.json

```
{
  "name": "tokenwatch-backend",
  "version": "1.0.0",
  "private": true,
  "description": "Backend foundation for TokenWatch",
  "main": "dist/main.js",
  "scripts": {
    "dev": "tsx watch src/main.ts",
    "seed": "tsx src/scripts/seed.ts",
    "seed:synthetic": "tsx src/scripts/seed_synthetic.ts",
    "db:init": "tsx src/scripts/init_postgres.ts",
    "build": "tsc -p tsconfig.json",
    "lint": "tsc -p tsconfig.json --noEmit",
    "test:auth": "tsx test-workspace-system.ts",
    "test:permissions": "tsx src/test/api-key-permissions.test.ts",
    "test:agent-x402": "tsx src/test/agent-x402.test.ts",
    "test:x402-config": "tsx src/test/x402-config.test.ts",
    "start": "node dist/main.js"
  },
  "dependencies": {
    "@google/genai": "^2.8.0",
    "cookie-parser": "^1.4.7",
    "dotenv": "^16.6.1",
    "express": "^5.1.0",
    "pg": "^8.16.3",
    "tsx": "^4.20.3"
  },
  "devDependencies": {
    "@types/cookie-parser": "^1.4.7",
    "@types/express": "^5.0.1",
    "@types/node": "^24.0.15",
    "@types/pg": "^8.15.5",
    "typescript": "^5.8.3"
  }
}

```

### sdk/package.json

```
{
  "name": "@zn_/tokenwatch",
  "version": "0.1.7",
  "private": false,
  "description": "Lightweight SDK for sending application telemetry to TokenWatch.",
  "type": "module",
  "sideEffects": false,
  "keywords": [
    "telemetry",
    "observability",
    "ai",
    "llm",
    "monitoring"
  ],
  "license": "MIT",
  "author": "Zainab Travadi",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ZainabTravadi/Token-Watcher-AI-API-Cost-Tracker.git"
  },
  "bugs": {
    "url": "https://github.com/ZainabTravadi/Token-Watcher-AI-API-Cost-Tracker/issues"
  },
  "homepage": "https://github.com/ZainabTravadi/Token-Watcher-AI-API-Cost-Tracker#readme",
  "main": "./dist/cjs/index.js",
  "module": "./dist/esm/index.js",
  "types": "./dist/types/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/types/index.d.ts",
      "import": "./dist/esm/index.js",
      "require": "./dist/cjs/index.js"
    }
  },
  "files": [
    "dist",
    "README.md"
  ],
  "devDependencies": {
    "typescript": "^5.8.3"
  },
  "scripts": {
    "clean": "node -e \"const fs=require('fs'); fs.rmSync('dist', { recursive: true, force: true });\"",
    "build:esm": "tsc -p tsconfig.esm.json",
    "build:cjs": "tsc -p tsconfig.cjs.json && node -e \"const fs=require('fs'); fs.writeFileSync('dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }, null, 2) + '\\n');\"",
    "build": "npm run clean && npm run build:esm && npm run build:cjs && npm run postbuild",
    "lint": "tsc -p tsconfig.esm.json --noEmit && tsc -p tsconfig.cjs.json --noEmit",
    "postbuild": "node ./scripts/fix-dts-extensions.cjs",
    "test": "npm run build:esm && node --test test/sdk.test.js test/phase2-validation.test.js"
  }
}

```

### frontend/package.json

```
{
  "name": "vite_react_shadcn_ts",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "build:dev": "vite build --mode development",
    "lint": "eslint .",
    "preview": "vite preview",
    "test": "vitest run",
    "test:watch": "vitest"
  },
  "dependencies": {
    "@hookform/resolvers": "^3.10.0",
    "@radix-ui/react-accordion": "^1.2.11",
    "@radix-ui/react-alert-dialog": "^1.1.14",
    "@radix-ui/react-aspect-ratio": "^1.1.7",
    "@radix-ui/react-avatar": "^1.1.10",
    "@radix-ui/react-checkbox": "^1.3.2",
    "@radix-ui/react-collapsible": "^1.1.11",
    "@radix-ui/react-context-menu": "^2.2.15",
    "@radix-ui/react-dialog": "^1.1.14",
    "@radix-ui/react-dropdown-menu": "^2.1.15",
    "@radix-ui/react-hover-card": "^1.1.14",
    "@radix-ui/react-label": "^2.1.7",
    "@radix-ui/react-menubar": "^1.1.15",
    "@radix-ui/react-navigation-menu": "^1.2.13",
    "@radix-ui/react-popover": "^1.1.14",
    "@radix-ui/react-progress": "^1.1.7",
    "@radix-ui/react-radio-group": "^1.3.7",
    "@radix-ui/react-scroll-area": "^1.2.9",
    "@radix-ui/react-select": "^2.2.5",
    "@radix-ui/react-separator": "^1.1.7",
    "@radix-ui/react-slider": "^1.3.5",
    "@radix-ui/react-slot": "^1.2.3",
    "@radix-ui/react-switch": "^1.2.5",
    "@radix-ui/react-tabs": "^1.1.12",
    "@radix-ui/react-toast": "^1.2.14",
    "@radix-ui/react-toggle": "^1.1.9",
    "@radix-ui/react-toggle-group": "^1.1.10",
    "@radix-ui/react-tooltip": "^1.2.7",
    "@tanstack/react-query": "^5.83.0",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "cmdk": "^1.1.1",
    "date-fns": "^3.6.0",
    "embla-carousel-react": "^8.6.0",
    "input-otp": "^1.4.2",
    "lucide-react": "^0.462.0",
    "next-themes": "^0.3.0",
    "react": "^18.3.1",
    "react-day-picker": "^8.10.1",
    "react-dom": "^18.3.1",
    "react-hook-form": "^7.61.1",
    "react-resizable-panels": "^2.1.9",
    "react-router-dom": "^6.30.1",
    "recharts": "^2.15.4",
    "sonner": "^1.7.4",
    "tailwind-merge": "^2.6.0",
    "tailwindcss-animate": "^1.0.7",
    "vaul": "^0.9.9",
    "zod": "^3.25.76"
  },
  "devDependencies": {
    "@eslint/js": "^9.32.0",
    "@tailwindcss/typography": "^0.5.16",
    "@testing-library/jest-dom": "^6.6.0",
    "@testing-library/react": "^16.0.0",
    "@types/node": "^22.16.5",
    "@types/react": "^18.3.23",
    "@types/react-dom": "^18.3.7",
    "@vitejs/plugin-react-swc": "^3.11.0",
    "autoprefixer": "^10.4.21",
    "eslint": "^9.32.0",
    "eslint-plugin-react-hooks": "^5.2.0",
    "eslint-plugin-react-refresh": "^0.4.20",
    "globals": "^15.15.0",
    "jsdom": "^20.0.3",
    "lovable-tagger": "^1.1.13",
    "postcss": "^8.5.6",
    "tailwindcss": "^3.4.17",
    "typescript": "^5.8.3",
    "typescript-eslint": "^8.38.0",
    "vite": "^5.4.19",
    "vitest": "^3.2.4"
  }
}

```

### backend/src/main.ts

```typescript
import { startServer } from "./core/server";

void startServer();
```

### frontend/src/main.tsx

```typescript
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

createRoot(document.getElementById("root")!).render(<App />);

```

### sdk/src/index.ts

```typescript
export type {
  TokenWatchIdentity,
  TokenWatchInitOptions,
  TokenWatchProvider,
  TokenWatchSimulationController,
  TokenWatchSimulationOptions,
  TokenWatchStateSnapshot,
  TokenWatchTelemetryRecord,
  TokenWatchTransportStats,
  TokenWatchTrackInput,
  TokenWatchTrackOptions
} from "./types.js";

export { flush, identify, init, setEndpoint, simulate, startSimulation, stats, stopSimulation, track } from "./client.js";
export { TokenWatch } from "./namespace.js";
export { flushAndShutdown, getQueueSize, getTransportStats } from "./transport.js";
export { default } from "./namespace.js";

```

### openclaw/src/main.ts

```typescript
import { getConfig } from "./config/env";
import { createLogger } from "./logger";
import { createOpenClawServer } from "./server";
import { TelegramTransport } from "./telegram/transport";
import { TokenWatcherClient } from "./tokenwatcher/client";

async function bootstrap(): Promise<void> {
  const config = getConfig();
  const logger = createLogger(config.logLevel);
  const client = new TokenWatcherClient(config, logger);
  const telegram = new TelegramTransport(config, logger);
  const server = createOpenClawServer(config, logger, client, telegram);

  server.listen(config.port, config.host, () => {
    logger.info("server.started", {
      host: config.host,
      port: config.port,
      tokenWatcherApiUrl: config.tokenWatcherApiUrl,
      authMode: "per_integration"
    });
  });

  const shutdown = (signal: string) => {
    logger.info("server.stopping", { signal });
    server.close(() => {
      logger.info("server.stopped", { signal });
      process.exit(0);
    });
  };

  process.on("SIGINT", () => shutdown("SIGINT"));
  process.on("SIGTERM", () => shutdown("SIGTERM"));
}

bootstrap().catch((error) => {
  const logger = createLogger(process.env.OPENCLAW_LOG_LEVEL === "debug" ? "debug" : "error");
  logger.error("server.start_failed", { error: error instanceof Error ? error.message : String(error) });
  process.exit(1);
});

```

[249 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]