# hbai-ltd/toonflow-app architecture

> Architecture diagram of the GitHub repository hbai-ltd/toonflow-app, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hbai-ltd/toonflow-app
- Repository: https://github.com/hbai-ltd/toonflow-app

## Overview

1. **What this repo is**
   Toonflow is a Node.js/TypeScript backend for an AI short-drama production system, packaged with a built-in web UI and an Electron desktop shell. The backend is the core product; the front-end source lives elsewhere, but compiled UI assets are shipped in `data/web`.

2. **Top-level runtime shape**
   The application starts from `src/app.ts`, with shared bootstrapping in `src/core.ts`, routing in `src/router.ts`, environment parsing in `src/env.ts`, and error/logging helpers in `src/err.ts` and `src/logger.ts`. The server is an Express 5 API serving both JSON endpoints and static assets.

3. **Primary user-facing domains**
   The API is organized by business areas under `src/routes/`: `project`, `novel`, `script`, `production`, `assets`, `artStyle`, `task`, `modelSelect`, `setting`, `login`, and `migrate`. These map directly to the product workflow: create a project, ingest a novel, derive script/event structure, generate storyboard/assets, and assemble output video.

4. **Creative pipeline**
   The main data flow is:
   novel import → chapter/event extraction → script generation/adaptation → production planning/storyboard → asset generation → video assembly/export.
   The repo supports this through dedicated routes such as `novel/getNovelData`, `novel/event/generateEvents`, `script/extractAssets`, `production/storyboard/*`, and `production/workbench/*`.

5. **Agent architecture**
   There are two agent subsystems in `src/agents/`: `scriptAgent` and `productionAgent`. Each has its own `index.ts` and `tools.ts`, and the README describes a three-layer pattern: decision, execution, and supervision. The routes under `src/routes/scriptAgent` and `src/routes/agents` expose agent plan/state and memory operations to the UI.

6. **Persistent agent memory**
   Agent memory is not just chat history; it is a long-lived retrieval layer backed by local embeddings and SQLite. The ONNX model bundle in `data/models/all-MiniLM-L6-v2` supports semantic recall via `src/utils/agent/embedding.ts` and `src/utils/agent/memory.ts`, with database setup in `src/lib/initDB.ts` and repair/migration helpers in `src/lib/fixDB.ts`.

7. **Skill and prompt system**
   Prompt logic is externalized into Markdown skill files under `data/skills/`. There are separate skill collections for story genres and art styles, plus common production/script skill docs. This makes the behavior of the agents configurable without changing source code, and it is surfaced by settings routes such as `setting/skillManagement/*` and prompt-management endpoints.

8. **Asset and media handling**
   Assets are a first-class subsystem, with routes for uploading, saving, generating, polling, deleting, and batch operations under `src/routes/assets` and `src/routes/assetsGenerate`. The repo also includes a video asset (`data/assets/ending.mp4`) and a static OSS-oriented storage pattern, suggesting generated media is persisted locally and/or exposed via a configured base URL.

9. **Model/vendor integration**
   Model access is abstracted through settings and selection endpoints rather than hardcoded providers. The repo uses Vercel AI SDK to support multiple LLM vendors, plus a local ONNX path for embeddings and a video provider wrapper under `src/utils/ai/video/owned/volcengine.ts`. The `setting/vendorConfig` routes indicate vendors can be added, enabled, tested, and even configured with editable TypeScript logic.

10. **Real-time coordination**
   `src/socket/` contains Socket.IO handlers for live updates, especially for agent workflows. This is likely used for progress reporting, memory/chat state, and long-running production tasks such as image generation or video generation, which would otherwise be too slow for simple request/response polling alone.

11. **Data and persistence boundary**
   SQLite is the main local persistence layer, wrapped by utilities in `src/utils/db.ts` and typed via `src/types/database.d.ts`. The repository stores durable runtime data under `data/` rather than relying on external infrastructure: databases, model files, web assets, skills, and generated media are all local filesystem concerns.

12. **Packaging and deployment**
   The repo is designed to run in three modes: development backend, Electron desktop app, or server/Docker deployment. `Dockerfile`, `electron-builder.yml`, `scripts/build.ts`, and the GitHub Actions workflows show a dual packaging model: a server artifact under `data/serve/` for headless deployment, and a desktop distributable for end users.

13. **Important architectural boundary**
   The key boundary is between the orchestration layer and the content-generation layer. Express routes and sockets manage state, persistence, and user actions; agents, prompt skills, embeddings, and vendor adapters perform the AI work. That separation is what allows the same backend to support both local desktop use and remote server deployment.

14. **Diagramming hint**
   For an architecture diagram, place `data/skills`, `data/models`, `data/web`, and SQLite/filesystem storage as internal resources; place LLM/image/video providers as external services; and center the workflow around `project → novel → scriptAgent → productionAgent → assets/video export`, with Socket.IO as the real-time control channel.

Main entry points: [`src/router.ts`](https://github.com/hbai-ltd/toonflow-app/blob/master/src/router.ts) (Router), [`src/core.ts`](https://github.com/hbai-ltd/toonflow-app/blob/master/src/core.ts) (Core boot), [`src/routes/setting`](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/setting) (Settings API), [`src/routes/production`](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/production) (Production API)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_grp_runtime["Runtime & API"]
  node_src_app(("App entry<br/>bootstrap<br/>[app.ts]"))
  node_src_core["Core boot<br/>bootstrap<br/>[core.ts]"]
  node_src_router["Router<br/>http routing<br/>[router.ts]"]
  node_src_env["Env config<br/>config parsing<br/>[env.ts]"]
  node_src_err["Errors<br/>error handling<br/>[err.ts]"]
  node_src_logger["Logger<br/>logging<br/>[logger.ts]"]
end

subgraph group_grp_agents["AI Agents"]
  node_routes_agents["Agents API<br/>memory routes"]
  node_routes_script_agent["Script agent API<br/>agent routes"]
  node_agent_script{{"Script agent<br/>planner/executor<br/>[index.ts]"}}
  node_agent_production{{"Production agent<br/>planner/executor<br/>[index.ts]"}}
  node_agent_memory[("Agent memory<br/>retrieval store<br/>[memory.ts]")]
  node_utils_embedding["Embeddings<br/>onnx recall<br/>[embedding.ts]"]
end

subgraph group_grp_workflow["Creative Workflow"]
  node_routes_project["Project API<br/>domain routes"]
  node_routes_novel["Novel API<br/>domain routes"]
  node_routes_script["Script API<br/>domain routes"]
  node_routes_production["Production API<br/>domain routes"]
  node_routes_assets["Assets API<br/>media routes"]
  node_routes_assets_gen["Asset gen<br/>generation routes"]
  node_routes_task["Task API<br/>task routes"]
end

subgraph group_grp_ops["Settings & Ops"]
  node_setting_routes["Settings API<br/>admin routes"]
end

subgraph group_grp_data["Local Data"]
  node_db_init[("DB init<br/>sqlite bootstrap<br/>[initDB.ts]")]
  node_utils_db[("SQLite utils<br/>db access<br/>[db.ts]")]
  node_data_skills["Skill docs<br/>prompt assets"]
  node_data_models["Embedding model<br/>onnx bundle"]
  node_data_web["Web UI bundle<br/>static assets"]
  node_data_assets["Media assets<br/>runtime media"]
end

subgraph group_grp_ext["External Services"]
  node_vendor_llm(("LLM vendors<br/>external AI"))
  node_vendor_video(("Video provider<br/>external AI"))
  node_storage_fs[("Filesystem<br/>local storage")]
end

node_src_app -->|"starts"| node_src_core
node_src_core -->|"loads"| node_src_env
node_src_core -->|"initializes"| node_src_logger
node_src_core -->|"wires"| node_src_err
node_src_core -->|"mounts"| node_src_router
node_src_router -->|"serves"| node_data_web
node_src_router -->|"routes"| node_routes_project
node_src_router -->|"routes"| node_routes_novel
node_src_router -->|"routes"| node_routes_script
node_src_router -->|"routes"| node_routes_production
node_src_router -->|"routes"| node_routes_assets
node_src_router -->|"routes"| node_routes_assets_gen
node_src_router -->|"routes"| node_routes_task
node_src_router -->|"routes"| node_routes_agents
node_src_router -->|"routes"| node_routes_script_agent
node_src_router -->|"routes"| node_setting_routes
node_routes_novel -->|"feeds"| node_routes_script
node_routes_script -->|"hands off"| node_routes_production
node_routes_production -->|"uses"| node_routes_assets
node_routes_assets -->|"stores"| node_data_assets
node_routes_assets_gen -->|"requests"| node_vendor_llm
node_routes_production -->|"renders"| node_vendor_video
node_routes_agents -->|"manages"| node_agent_memory
node_routes_script_agent -->|"controls"| node_agent_script
node_setting_routes -->|"edits"| node_data_skills
node_setting_routes -->|"configures"| node_vendor_llm
node_setting_routes -->|"administers"| node_db_init
node_agent_script -->|"uses"| node_data_skills
node_agent_production -->|"uses"| node_data_skills
node_agent_script -->|"recalls"| node_agent_memory
node_agent_production -->|"recalls"| node_agent_memory
node_agent_memory -->|"indexes"| node_utils_embedding
node_utils_embedding -->|"loads"| node_data_models
node_db_init -->|"wraps"| node_utils_db
node_utils_db -->|"persists"| node_storage_fs
node_data_web -->|"served from"| node_storage_fs
node_data_skills -->|"stored on"| node_storage_fs
node_data_models -->|"stored on"| node_storage_fs
node_data_assets -->|"stored on"| node_storage_fs

click node_src_app "https://github.com/hbai-ltd/toonflow-app/blob/master/src/app.ts"
click node_src_core "https://github.com/hbai-ltd/toonflow-app/blob/master/src/core.ts"
click node_src_router "https://github.com/hbai-ltd/toonflow-app/blob/master/src/router.ts"
click node_src_env "https://github.com/hbai-ltd/toonflow-app/blob/master/src/env.ts"
click node_src_err "https://github.com/hbai-ltd/toonflow-app/blob/master/src/err.ts"
click node_src_logger "https://github.com/hbai-ltd/toonflow-app/blob/master/src/logger.ts"
click node_routes_project "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/project"
click node_routes_novel "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/novel"
click node_routes_script "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/script"
click node_routes_production "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/production"
click node_routes_assets "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/assets"
click node_routes_assets_gen "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/assetsGenerate"
click node_routes_task "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/task"
click node_routes_agents "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/agents"
click node_routes_script_agent "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/scriptAgent"
click node_agent_script "https://github.com/hbai-ltd/toonflow-app/blob/master/src/agents/scriptAgent/index.ts"
click node_agent_production "https://github.com/hbai-ltd/toonflow-app/blob/master/src/agents/productionAgent/index.ts"
click node_agent_memory "https://github.com/hbai-ltd/toonflow-app/blob/master/src/utils/agent/memory.ts"
click node_utils_embedding "https://github.com/hbai-ltd/toonflow-app/blob/master/src/utils/agent/embedding.ts"
click node_setting_routes "https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/setting"
click node_db_init "https://github.com/hbai-ltd/toonflow-app/blob/master/src/lib/initDB.ts"
click node_utils_db "https://github.com/hbai-ltd/toonflow-app/blob/master/src/utils/db.ts"
click node_data_skills "https://github.com/hbai-ltd/toonflow-app/tree/master/data/skills"
click node_data_models "https://github.com/hbai-ltd/toonflow-app/tree/master/data/models/all-MiniLM-L6-v2"
click node_data_web "https://github.com/hbai-ltd/toonflow-app/tree/master/data/web"
click node_data_assets "https://github.com/hbai-ltd/toonflow-app/tree/master/data/assets"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_src_app,node_src_core,node_src_router,node_src_env,node_src_err,node_src_logger toneBlue
class node_routes_agents,node_routes_script_agent,node_agent_script,node_agent_production,node_agent_memory,node_utils_embedding toneAmber
class node_routes_project,node_routes_novel,node_routes_script,node_routes_production,node_routes_assets,node_routes_assets_gen,node_routes_task toneMint
class node_setting_routes toneRose
class node_db_init,node_utils_db,node_data_skills,node_data_models,node_data_web,node_data_assets toneIndigo
class node_vendor_llm,node_vendor_video,node_storage_fs toneTeal
```

## Components

### Runtime & API

Express server bootstrap, routing, and request lifecycle.

- [App entry](https://github.com/hbai-ltd/toonflow-app/blob/master/src/app.ts): bootstrap · Main process entrypoint that starts the application. · `src/app.ts`
- [Core boot](https://github.com/hbai-ltd/toonflow-app/blob/master/src/core.ts): bootstrap · Shared startup and wiring logic. · `src/core.ts`
- [Router](https://github.com/hbai-ltd/toonflow-app/blob/master/src/router.ts): http routing · Top-level Express route composition. · `src/router.ts`
- [Env config](https://github.com/hbai-ltd/toonflow-app/blob/master/src/env.ts): config parsing · Environment and runtime configuration loading. · `src/env.ts`
- [Errors](https://github.com/hbai-ltd/toonflow-app/blob/master/src/err.ts): error handling · Central error utilities and normalization. · `src/err.ts`
- [Logger](https://github.com/hbai-ltd/toonflow-app/blob/master/src/logger.ts): logging · Application logging helpers. · `src/logger.ts`

### AI Agents

Script and production agent orchestration and memory.

- [Agents API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/agents): memory routes · Shared agent memory and cleanup endpoints. · `src/routes/agents`
- [Script agent API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/scriptAgent): agent routes · Script agent plan/state endpoints for the UI. · `src/routes/scriptAgent`
- [Script agent](https://github.com/hbai-ltd/toonflow-app/blob/master/src/agents/scriptAgent/index.ts): planner/executor · Script reasoning, adaptation, and supervision loop. · `src/agents/scriptAgent/index.ts`
- [Production agent](https://github.com/hbai-ltd/toonflow-app/blob/master/src/agents/productionAgent/index.ts): planner/executor · Storyboard and production planning loop. · `src/agents/productionAgent/index.ts`
- [Agent memory](https://github.com/hbai-ltd/toonflow-app/blob/master/src/utils/agent/memory.ts): retrieval store · Embedding-backed long-lived agent memory layer. · `src/utils/agent/memory.ts`
- [Embeddings](https://github.com/hbai-ltd/toonflow-app/blob/master/src/utils/agent/embedding.ts): onnx recall · Local semantic embedding utilities for memory search. · `src/utils/agent/embedding.ts`

### Creative Workflow

Project, novel, script, production, and asset domains.

- [Project API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/project): domain routes · Project setup, manuals, and project metadata. · `src/routes/project`
- [Novel API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/novel): domain routes · Novel import, indexing, and event extraction. · `src/routes/novel`
- [Script API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/script): domain routes · Script generation, updates, exports, and asset extraction. · `src/routes/script`
- [Production API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/production): domain routes · Storyboard, image flow, and workbench/video assembly. · `src/routes/production`
- [Assets API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/assets): media routes · Asset CRUD, upload, polling, and material management. · `src/routes/assets`
- [Asset gen](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/assetsGenerate): generation routes · Batch image generation and prompt polishing endpoints. · `src/routes/assetsGenerate`
- [Task API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/task): task routes · Task categories, task details, and project-linked task views. · `src/routes/task`

### Settings & Ops

Model/vendor config, prompts, skills, login, migration, and maintenance.

- [Settings API](https://github.com/hbai-ltd/toonflow-app/tree/master/src/routes/setting): admin routes · Model, prompt, skill, login, deploy, and maintenance settings. · `src/routes/setting`

### Local Data

Shipped assets, skill docs, model bundles, and runtime storage.

- [DB init](https://github.com/hbai-ltd/toonflow-app/blob/master/src/lib/initDB.ts): sqlite bootstrap · Database initialization and repair helpers. · `src/lib/initDB.ts`
- [SQLite utils](https://github.com/hbai-ltd/toonflow-app/blob/master/src/utils/db.ts): db access · Shared database access wrapper. · `src/utils/db.ts`
- [Skill docs](https://github.com/hbai-ltd/toonflow-app/tree/master/data/skills): prompt assets · Markdown skill collections for story, art, production, and agents. · `data/skills`
- [Embedding model](https://github.com/hbai-ltd/toonflow-app/tree/master/data/models/all-MiniLM-L6-v2): onnx bundle · Local MiniLM ONNX model used for recall embeddings. · `data/models/all-MiniLM-L6-v2`
- [Web UI bundle](https://github.com/hbai-ltd/toonflow-app/tree/master/data/web): static assets · Compiled browser UI served by the backend. · `data/web`
- [Media assets](https://github.com/hbai-ltd/toonflow-app/tree/master/data/assets): runtime media · Local persisted media such as shipped or generated assets. · `data/assets`

### External Services

Third-party AI and delivery services used by the backend.

- **LLM vendors**: external AI · Configured model providers accessed through the vendor layer.
- **Video provider**: external AI · Video generation provider integration.
- **Filesystem**: local storage · Durable local storage for DB, assets, skills, models, and served files.

## Connections

- App entry → Core boot: starts · Application entry calls shared boot logic.
- Core boot → Env config: loads · Bootstrapping reads runtime configuration.
- Core boot → Logger: initializes · Sets up logging during startup.
- Core boot → Errors: wires · Registers centralized error handling.
- Core boot → Router: mounts · Attaches the HTTP router and middleware stack.
- Router → Web UI bundle: serves · Express serves the compiled UI bundle.
- Router → Project API: routes · Project endpoints are mounted under the API.
- Router → Novel API: routes · Novel workflow endpoints are mounted.
- Router → Script API: routes · Script workflow endpoints are mounted.
- Router → Production API: routes · Production workflow endpoints are mounted.
- Router → Assets API: routes · Asset management endpoints are mounted.
- Router → Asset gen: routes · Asset generation endpoints are mounted.
- Router → Task API: routes · Task endpoints are mounted.
- Router → Agents API: routes · Shared agent memory endpoints are mounted.
- Router → Script agent API: routes · Script agent UI endpoints are mounted.
- Router → Settings API: routes · Administrative and configuration endpoints are mounted.
- Novel API → Script API: feeds · Novel ingestion flows into script generation.
- Script API → Production API: hands off · Script outputs become production planning inputs.
- Production API → Assets API: uses · Production work produces and manages media assets.
- Assets API → Media assets: stores · Asset endpoints persist media locally.
- Asset gen → LLM vendors: requests · Prompt polishing and image generation can call model vendors.
- Production API → Video provider: renders · Video workbench integrates with a video provider.
- Agents API → Agent memory: manages · Memory endpoints read and clear long-lived agent memory.
- Script agent API → Script agent: controls · UI endpoints expose script-agent planning state.
- Settings API → Skill docs: edits · Skill management reads and updates prompt assets.
- Settings API → LLM vendors: configures · Vendor settings manage provider configuration and tests.
- Settings API → DB init: administers · DB and migration settings act on local persistence.
- Script agent → Skill docs: uses · Script agent behavior is driven by skill prompts.
- Production agent → Skill docs: uses · Production agent behavior is driven by skill prompts.
- Script agent → Agent memory: recalls · Script agent persists and retrieves memory.
- Production agent → Agent memory: recalls · Production agent persists and retrieves memory.
- Agent memory → Embeddings: indexes · Memory search relies on embedding generation.
- Embeddings → Embedding model: loads · Embedding utilities load the local ONNX model bundle.
- DB init → SQLite utils: wraps · Database lifecycle helpers sit on top of the DB utility.
- SQLite utils → Filesystem: persists · SQLite data lives in local filesystem storage.
- Web UI bundle → Filesystem: served from · UI assets are packaged on disk.
- Skill docs → Filesystem: stored on · Prompt skill docs are local filesystem assets.
- Embedding model → Filesystem: stored on · Embedding model bundle is a local filesystem asset.
- Media assets → Filesystem: stored on · Generated and shipped media persist locally.
