# AI Engine And Token Billing Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Add administrator-managed large-model configuration, user-facing AI analysis actions, and AI token billing through redemption codes. **Architecture:** Extend the existing JSON store with `aiSettings`, `aiTokens`, and `aiTokenLogs`. Add an OpenAI-compatible AI client abstraction so official providers and proxy/base-url providers all use one request path. Admins configure model access; users consume AI actions through server endpoints that estimate/charge AI tokens. **Tech Stack:** Node.js HTTP server, JSON store, OpenAI-compatible chat completions over `fetch`, vanilla HTML/CSS/JS frontend, Node test runner. --- ### Task 1: Server Tests **Files:** - Modify: `tests/server.test.js` - [ ] Add tests for admin-only AI settings. - [ ] Add tests for AI token redemption codes. - [ ] Add tests for AI analysis using a fake AI client and token deduction. - [ ] Add tests for insufficient AI tokens. ### Task 2: AI Core Module **Files:** - Create: `src/ai.js` - [ ] Add `DEFAULT_AI_SETTINGS`. - [ ] Add settings normalization and public masking. - [ ] Add OpenAI-compatible request handling. - [ ] Add prompt builders for item analysis, procurement reports, and rule generation. - [ ] Add token estimation helpers. ### Task 3: Store Extensions **Files:** - Modify: `src/store.js` - Modify: `src/auth.js` - [ ] Add `aiTokens` to users and public users. - [ ] Extend credit codes to include `aiTokens`. - [ ] Add `aiSettings` and encrypted API key storage. - [ ] Add AI token deduction logs. ### Task 4: API Routes **Files:** - Modify: `src/server.js` - [ ] Add admin routes for AI settings and connection testing. - [ ] Add user route `/api/ai/analyze`. - [ ] Require AI token balance before calling the model. - [ ] Deduct AI tokens after successful model use. ### Task 5: Frontend UI **Files:** - Modify: `public/index.html` - Modify: `public/app.js` - Modify: `public/styles.css` - [ ] Add admin AI configuration panel in management center. - [ ] Extend redemption code UI with AI token amount. - [ ] Show AI token balance on account/admin user rows. - [ ] Add AI analysis actions in item detail. - [ ] Keep visual language aligned with jade/paper/brass product UI. ### Task 6: Verification - [ ] Run `npm test`. - [ ] Run JS syntax checks. - [ ] Restart local service. - [ ] Verify AI settings UI and item detail AI action with browser screenshots.