A full-stack AI training platform built in TypeScript from first principles — covering system design, architectural decisions, data models, and the engineering rationale behind every major choice.
Agent Forge is a monorepo with a shared TypeScript codebase. The frontend and backend run as a single Node.js process in production, with Vite handling the client bundle. All API traffic flows through tRPC procedures — there are no REST endpoints for feature logic.
Browser (React 19 + Tailwind 4)
│
├── tRPC Client (TanStack Query) ──────────────────────────────┐
│ └── trpc.*.useQuery / useMutation │
│ ▼
├── Web Speech API (real-time STT) Express Server (Node.js)
│ └── SpeechRecognition → interim text │
│ ├── tRPC Router
└── Audio playback (base64 MP3) │ ├── auth.* (OAuth, session)
│ ├── simulation.* (scenarios, sessions)
│ ├── courses.* (AI authoring)
│ ├── sandbox.* (flags, personas)
│ ├── agentic.* (5-agent system)
│ └── coaching.* (personas, chat, TTS, report)
│
├── LLM (GPT-4 class)
│ └── invokeLLM()
│
├── ElevenLabs TTS
│ └── elevenLabsTTS() → MP3 buffer
│
├── Drizzle ORM
│ └── TiDB Serverless (MySQL)
│
└── AWS S3
└── storagePut() / storageGet()
The voice simulation loop was redesigned from a 4-step manual process (record → stop → transcribe → send) to a fully automatic cycle. The user speaks; the AI responds. No buttons, no waiting, no decisions.
User speaks
Web Speech API captures audio in real time, streaming interim results to a live transcript bubble in the UI.
Silence detected
After 1.5s of silence, the final transcript is sent to the tRPC speakText procedure via a useMutation call.
AI generates response
The server calls invokeLLM() with the scenario system prompt, conversation history, and user message. The LLM returns a text response.
TTS synthesis
The response text is passed to elevenLabsTTS() with the persona-matched voice ID. The server returns an MP3 buffer as a base64 data URL.
Audio playback
The client decodes the base64 URL into an Audio object and plays it. The animated orb transitions to 'speaking' state with sound-wave animation.
Auto-restart
When audio ends, the orb returns to 'listening' state and the Web Speech API restarts automatically — no user action required.
Real-time scoring
In parallel, the server calls the scoring LLM with the user's message and appends a score object to the session's messages array in TiDB.
Every dependency was chosen for a specific reason — not defaults or familiarity. The table below maps each library to the problem it solves.
The decisions below reflect deliberate trade-off analysis — each one had a clear problem, a considered solution, and an acknowledged downside. This is the kind of reasoning that distinguishes architecture from assembly.
Traditional REST APIs require duplicated type definitions on client and server, leading to runtime type mismatches and verbose boilerplate.
tRPC 11 with Superjson serialisation provides end-to-end TypeScript inference. Procedures defined in server/routers.ts are consumed directly in React components via trpc.*.useQuery/useMutation — no shared contract files, no Axios wrappers, no manual type casting.
Tighter client-server coupling. Acceptable for a single-team product where both layers evolve together.
The original voice flow required four manual steps: tap Record → speak → tap Stop → tap Send. This created cognitive friction that broke the simulation immersion.
The browser-native Web Speech API provides continuous real-time transcription with zero upload latency. A 1.5-second silence detector automatically submits the transcript, creating a zero-decision voice loop. Whisper API is used as a fallback for Safari and Firefox.
Web Speech API is Chrome/Edge-only for full support. The fallback path preserves functionality across all browsers at the cost of higher latency.
Browser-native TTS (SpeechSynthesis API) produces flat, robotic output that undermines the realism of a sales or interview simulation.
ElevenLabs eleven_turbo_v2_5 model is called server-side, returning MP3 audio streamed to the client. Voice IDs are mapped to scenario personas by name and category — Sarah Chen gets Bella (warm female), board executives get Arnold (crisp male). The model handles all 32 supported languages automatically based on text content.
API cost per character. Mitigated by a 500-character cap per response and server-side fallback to built-in TTS when quota is exhausted.
Prisma's query engine is a native binary that does not run in Cloud Run's Node-only build image without additional configuration.
Drizzle ORM is a pure TypeScript/JavaScript library with no native binary dependency. It compiles to raw SQL, is fully compatible with TiDB's MySQL wire protocol, and produces typed query results that flow directly into tRPC procedures without additional mapping.
Drizzle's migration tooling is less mature than Prisma's. Migrations are applied manually via webdev_execute_sql to maintain explicit control over schema changes.
A training platform used episodically (not 24/7) would waste cost on always-on reserved instances.
Cloud Run Autoscale with min-instances=0 means the platform costs nothing when idle and scales to handle concurrent users during active sessions. The 180-second request timeout is sufficient for all LLM and TTS operations.
Cold starts of 2–4 seconds on first request after idle. Acceptable for a training tool; not suitable for real-time financial or safety-critical systems.
Admin features (scenario creation, user management, agentic dashboard) must be gated without introducing a separate auth service.
The users table includes a role enum (user | admin). Every protected tRPC procedure checks ctx.user.role before executing. adminProcedure is a middleware layer that throws FORBIDDEN before any business logic runs. Frontend conditionally renders admin nav items based on useAuth().user?.role.
Role promotion requires a direct SQL update. Intentional — it prevents accidental privilege escalation and keeps the permission model auditable.
19 tables in TiDB Serverless (MySQL-compatible), defined in drizzle/schema.ts with full TypeScript inference. All timestamps are stored as UTC; all scores are stored as floats to support fractional precision.
| Table | Purpose |
|---|---|
| users | Auth identity, role, streak tracking, aggregate stats |
| scenarios | Simulation blueprints — persona, system prompt, channel, language lock, folder |
| sessions | Practice session lifecycle — status, per-dimension scores, feedback summary |
| messages | Individual conversation turns with per-message scores and AI feedback |
| walkthroughs | Step-by-step product walkthrough definitions |
| walkthrough_completions | Per-user walkthrough progress tracking |
| courses | AI-generated eLearning courses from uploaded documents |
| lessons | Ordered lesson units within a course |
| content_blocks | Atomic content units — text, key-concept, quiz, summary |
| course_enrollments | Learner progress and completion state per course |
| sandbox_instances | Product sandbox environments with status and preview URLs |
| feature_flags | Rollout percentage, targeting rules, kill switches |
| test_runs | Synthetic conversation test scripts and pass/fail results |
| personas | Reusable AI persona definitions with version history |
| sandbox_events | Full event stream per sandbox for replay and audit |
| agent_events | Agentic system events — nudges, interventions, orchestration logs |
| coaching_nudges | AI-generated coaching interventions per learner |
| learning_paths | Adaptive learning path recommendations per user |
| difficulty_adjustments | Dynamic difficulty tuning records per session |
Agent Forge is composed of 7 independent product modules, each with its own routes, tRPC router, and database tables. Modules are loosely coupled — a user can use the course builder without ever touching the simulation engine.
5 scenario categories, 5 AI personas, real-time scoring across 5 dimensions, session replay.
Document upload → AI course generation → block editor → SCORM export → public learner view.
Guided spotlight walkthrough with step tooltips, progress tracking, and completion certificates.
Engineering control plane — feature flags, AI behaviour tester, synthetic test runner, persona lab, event log.
5-agent orchestration system — Readiness Predictor, Coaching Nudge, Difficulty Adjuster, Content Curator, Engagement Monitor.
Recharts radar/trend/bar visualisations, streak tracking, leaderboard, readiness predictions.
4 coach personas (Socratic, GROW, Solution-Focused, Directive) — voice-enabled 1:1 sessions, session arc tracking, post-session coaching report. Beta.
All server-side logic is covered by Vitest unit tests. TypeScript strict mode is enabled across the entire monorepo. The CI check runs tsc --noEmit and vitest run before every deployment.
12 / 12 tests passing
Vitest — simulation, auth, ElevenLabs
0 TypeScript errors
strict mode, noImplicitAny, strictNullChecks
50-criterion QA scoring
Automated per-message evaluation by LLM
No password storage
Authentication is delegated entirely to OAuth 2.0 SSO. The platform stores only an openId reference — never a password hash.
Server-side API keys
ElevenLabs, LLM, and S3 credentials are injected as server-side environment variables. No API key is ever sent to the browser.
JWT session cookies
Sessions are signed with HS256 using a platform-injected JWT_SECRET. Cookies are HttpOnly and SameSite=Lax.
Role-gated procedures
Every admin operation is wrapped in adminProcedure middleware that throws FORBIDDEN before executing any business logic.
S3 path randomisation
File keys include nanoid random suffixes to prevent enumeration attacks on uploaded assets.
Zod input validation
All tRPC procedure inputs are validated with Zod schemas before reaching any database or LLM call.
Agent Forge includes a 5-agent orchestration layer that operates autonomously on learner data. Each agent has a single responsibility and writes its outputs to dedicated database tables, which the Agentic Dashboard reads in real time.
Readiness Predictor
Analyses session history and score trends to predict whether a learner is ready to advance to the next difficulty tier. Writes to difficulty_adjustments.
Coaching Nudge Agent
Detects learners who have not practised in 48+ hours or whose scores are declining. Generates personalised coaching messages. Writes to coaching_nudges.
Difficulty Adjuster
Dynamically modifies the AI persona's behaviour mid-session based on real-time scoring — making the simulation harder or easier without interrupting the conversation.
Content Curator
Recommends scenarios and walkthroughs based on a learner's weakest scoring dimensions. Writes to learning_paths.
Engagement Monitor
Tracks session abandonment patterns, time-to-first-message, and response latency to identify at-risk learners. Writes to agent_events.
Agent Forge's architecture is grounded in three evidence-based learning science frameworks. Each framework directly informs a distinct technical component — the connection between pedagogy and engineering is explicit, not incidental.
Ericsson's Deliberate Practice Theory
Informs: Unlimited Repetition with Immediate Feedback
Expert-level performance is not the result of innate talent but of sustained, focused practice with immediate feedback. Agent Forge implements this through unlimited repetition of targeted scenarios with real-time coaching interventions — the digital equivalent of Rapid Cycle Deliberate Practice (RCDP) used in medical simulation training.
Vygotsky's Zone of Proximal Development
Informs: Adaptive Difficulty Calibration
Learning occurs most effectively in the zone between what a learner can accomplish independently and what they can achieve with guidance. The Adaptive Difficulty Agent functions as a digital scaffold, continuously calibrating challenge levels to maintain each learner within their personal ZPD — never so easy that learning stalls, never so difficult that confidence collapses.
Bloom's Revised Taxonomy
Informs: Higher-Order Assessment Design
Rather than testing recall (Level 1) or comprehension (Level 2), Agent Forge evaluates at the higher-order levels: Application, Analysis, and Evaluation. This ensures training transfers to production performance rather than merely testing memorisation of procedures. Most platforms assess at Bloom's Level 1–2 via multiple-choice quizzes; Agent Forge assesses at Levels 3–6 through authentic performance.
Every simulation session is automatically scored across 6 competency domains by the Evaluation Agent. The rubric satisfies three requirements simultaneously: pedagogical validity (scores reflect genuine competency), production alignment (categories map to enterprise QA frameworks), and predictive power (simulation scores correlate with real-world performance).
Scoring uses a criterion-referenced approach — scores reflect absolute competency against defined standards, not relative performance against peers. The rubric deliberately targets Bloom's Levels 3–6 (Apply, Analyse, Evaluate, Create) — not recall or comprehension.
| Domain | Points | Weight | Bloom's Level | Example Assessment |
|---|---|---|---|---|
| Decision Quality | 15 | 30% | Analyse / Evaluate (L4–L5) | Did the agent identify root cause from multiple symptoms? |
| Process Adherence | 10 | 20% | Apply (L3) | Did the agent apply the correct verification procedure? |
| Communication | 10 | 20% | Evaluate / Create (L5–L6) | Did the agent synthesise a coherent case summary? |
| Tool Proficiency | 5 | 10% | Apply (L3) | Did the agent use the CRM tools correctly and efficiently? |
| Documentation | 5 | 10% | Create (L6) | Did the agent produce accurate, complete case notes? |
| Time Efficiency | 5 | 10% | Apply (L3) | Did the agent resolve the issue within the target handle time? |
Kirkpatrick 4-Level Alignment
The evaluation framework maps to all four levels of Kirkpatrick's training evaluation model — a distinction from most platforms that only measure Levels 1 and 2. Level 1 (Reaction): post-session satisfaction score. Level 2 (Learning): 50-point rubric domain breakdown. Level 3 (Behaviour): score trajectory and coaching dependency reduction over time. Level 4 (Results): Predictive Readiness Score estimating time-to-production-threshold.
The Coaching Agent monitors learner actions in real time and delivers contextual interventions calibrated to avoid disrupting simulation flow. Research shows that forced scaffolding creates dependency — so interventions are severity-tiered and non-intrusive by design.
Tier
Hint
Trigger
Missed opportunity
UX Pattern
Non-blocking notification badge
Tier
Warning
Trigger
Procedural error
UX Pattern
Slide-in panel, requires acknowledgement
Tier
Critical
Trigger
Compliance violation
UX Pattern
Full overlay, requires correction before continuing
The orchestration layer manages a shared state bus where agents publish events and subscribe to relevant signals. A single learner action can trigger a coordinated cascade across all five agents simultaneously. The example below shows what happens when a critical compliance error is detected.
Submits response
LearnerThe learner's message is sent to the tRPC speakText procedure.
Generates customer reply
Simulation AgentProduces the AI customer's next response within persona constraints.
Evaluates for intervention triggers
Coaching AgentAnalyses the response against compliance rules and best-practice benchmarks.
Publishes CRITICAL_ERROR event
Coaching AgentIf a critical error is detected, broadcasts to the shared state bus.
Reduces persona complexity by 0.2
Adaptive Difficulty AgentSubscribes to CRITICAL_ERROR — softens the customer persona to prevent confidence collapse.
Logs error with timestamp
Evaluation AgentRecords the error for post-session 50-point rubric scoring.
Updates competency map
Planning AgentReceives session-end summary and adjusts the learner's personalised learning path.
The AI Coaching module is a distinct pillar from simulation — where simulation trains performance through repetition, coaching develops the person through reflection. The module is built on four coach personas, each grounded in a real coaching framework, with a voice-first session experience and a structured post-session report.
| Coach | Style | Framework | Focus | ElevenLabs Voice |
|---|---|---|---|---|
| Maya Chen | Socratic / Reflective | Clean Language + Appreciative Inquiry | Leadership identity, self-awareness, values | Bella (warm female) |
| James Whitfield | GROW Model | Goal → Reality → Options → Will | Sales performance, career targets, goals | Adam (deep male) |
| Priya Sharma | Solution-Focused | SFBC + Narrative Coaching | Career transitions, confidence, imposter syndrome | Grace (calm female) |
| Marcus Reid | Directive / Challenge | Gestalt + Ontological Coaching | Executive presence, stakeholder influence | Arnold (crisp male) |
Every coaching session follows a 5-phase arc tracked implicitly through conversation history. The LLM system prompt instructs the coach to move through phases naturally — no explicit state machine required.
At session end, the full conversation transcript is passed to the LLM with a structured JSON schema. The report is personalised — it references specific things the coachee said, not generic feedback.
sessionSummary
2–3 sentence essence of the session
keyInsight
The single most important realisation
breakthroughMoment
The exchange that created most movement
commitment
Specific action with timeframe
strengthsObserved
Array of strengths the coach noticed
growthEdge
One area most ripe for development
reflectionQuestions
3 questions to sit with before next session
nextSessionFocus
Recommended focus for next session
coachNote
Personal note from the coach to the coachee
Agent Forge occupies a unique position — combining multi-agent AI simulation with adaptive difficulty, a 50-point automated rubric, and zero license cost. No existing commercial platform implements all of these capabilities in a single product.
| Platform | Approach | Limitation vs Agent Forge |
|---|---|---|
| Second Nature | AI role-play for sales | Single-agent, sales-only, no CRM simulation or multi-agent orchestration |
| Solidroad | AI conversation practice | No multi-agent orchestration, no adaptive difficulty, no 50-point rubric |
| Mindtickle | Revenue enablement | Sales-focused, no customer service depth, no real-time coaching tiers |
| WalkMe | Digital adoption platform | Guidance overlays only, not simulation-based training — no AI roleplay or scoring |
| Articulate Rise | eLearning authoring | Static content, no AI, no real-time interaction or adaptive difficulty |
Every architectural decision described on this page is visible in the running product. No login required to explore scenarios, walkthroughs, or the agentic dashboard.
Built by Samir Das · agentforge.org.uk