📅
🕵️‍♂️ อ่าน ~3 นาที

คดีที่ 25: ผ่าพิมพ์เขียว OmniRoute — ถอดรหัสสถาปัตยกรรม AI ยุคใหม่ (65k Stars)


🕵️‍♂️ ปมคดีและที่มา: ทำไมวงการถึงต้องจับตามอง?

ทำไมโปรเจกต์ diegosouzapw/OmniRoute ถึงได้รับความนิยมและมียอดกด Star ทะลุ 65k บน GitHub?

เบื้องหลังความสำเร็จนี้ไม่ใช่แค่การเป็นเครื่องมือสำเร็จรูป แต่คือการแก้ปัญหาทางวิศวกรรมที่เจ็บปวด: สถาปัตยกรรมโอเพ่นซอร์สเทคโนโลยี AI ยุคใหม่


📊 ตารางเปรียบเทียบเชิงลึก: วิธีดั้งเดิม vs สถาปัตยกรรมสมัยใหม่

มิติการเปรียบเทียบ สถาปัตยกรรมเดิม (Traditional Approaches) สถาปัตยกรรม {clean_name}
ความยืดหยุ่น ผูกติดกับ Cloud Provider รายใหญ่ Modular Engine รองรับทั้ง Local และ API มาตรฐาน
ประสิทธิภาพ Token บริโภค Context สูง ขาดการแคชที่ดี ออกแบบ Layer แยก Context และ Execution ออกจากกัน
ความง่ายในการ Integrate ต้องเขียน Custom Glue Code มหาศาล เชื่อมต่อผ่าน Standardized Protocols (MCP/REST)

🔍 แกะรอยสถาปัตยกรรมระบบ (Deep Architecture Breakdown)

พิมพ์เขียวสถาปัตยกรรมเบื้องหลังระบบนี้ ถูกออกแบบมาเพื่อแก้ปัญหาคอขวดด้านประสิทธิภาพและความปลอดภัย:

flowchart TD
    subgraph 👤 User & Agent Layer
        User["👨‍💻 Developer / AI Agent"] -->|"Task / Intent"| Router["⚡ Protocol Router (MCP / CLI)"]
    end

    subgraph 🧠 Core Intelligence Engine
        Router --> Engine["⚙️ OmniRoute Engine"]
        Engine --> Decision["🎯 Intelligent Decision Core"]
        Engine --> Memory["💾 Persistent Session & Cache"]
    end

    subgraph 🛠️ Execution & Tooling
        Decision --> Tools["🔧 Specialized Execution Modules"]
        Tools --> Output["📊 Filtered & Optimized Results"]
    end

    Output -->|"Clean Context"| User

3 เสาหลักของการออกแบบระบบ (System Design Pillars):

  1. Decoupled Execution & Protocol-First: สื่อสารผ่านโปรโตคอลมาตรฐาน ทำให้ถอดเปลี่ยนสมองกล (LLM) ได้อิสระโดยไม่ต้องเขียน Logic การเชื่อมต่อ Tool ใหม่
  2. Context & Token Economy: ป้องกันไม่ให้ Output ดิบขนาดมหึมาทะลักเข้าสู่หน้าต่างบริบท ช่วยลดอาการ Hallucination และประหยัดค่าใช้จ่าย
  3. Resilience & State Continuity: มีกลไก Handle Exception และบันทึก State ความคืบหน้า เพื่อให้การทำงานแบบ Multi-step สามารถรันต่อได้จนจบภารกิจ

💻 ผ่ารหัสลับของจริง (Source Code Autopsy)

จากการผ่าโครงสร้าง Repo ของจริง เราพบชิ้นส่วนโค้ดสำคัญที่เป็นหัวใจของการขับเคลื่อนระบบ:

📄 ผ่าไฟล์จริง: package.json

{
  "name": "omniroute",
  "version": "3.8.50",
  "description": "Unified AI router with 352 providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.",
  "type": "module",
  "bin": {
    "omniroute": "bin/omniroute.mjs",
    "omniroute-reset-password": "bin/reset-password.mjs"
  },
  "files": [
    "bin/",
    "dist/",
    "@omniroute/",
    "open-sse/",
    "src/domain/",
    "src/lib/",
    "src/models/",
    "src/mitm/",
    "src/server/",
    "src/shared/",
    "src/sse/",
    "src/types/",
    ".env.example",
    "scripts/build/postinstall.mjs",
    "scripts/build/fixTlsClientNodeBinary.mjs",
    "scripts/build/fixPlaywrightAndroid.mjs",
    "bin/cli/runtime/",
    "scripts/postinstall.mjs",
    "scripts/build/postinstallSupport.mjs",
    "scripts/build/runtime-env.mjs",
    "scripts/build/colocateOptionals.mjs",
    "scripts/build/sync-env.mjs",
    "scripts/dev/responses-ws-proxy.mjs",
    "scripts/dev/tls-options.mjs",
    "scripts/check/check-supported-node-runtime.ts",
    "scripts/dev/sync-env.mjs",
    "scripts/build/assembleStandalone.mjs",
    "scripts/build/backendOnlyPages.mjs",
    "scripts/build/build-tproxy-native.mjs",
    "scripts/build/native-binary-compat.mjs",
    "scripts/build/build-next-isolated.mjs",
    "scripts/build/runtime-env.mjs",
    "scripts/packs/optionalPackManifest.mjs",
    "scripts/packs/optionalPackInstaller.mjs",
    "README.md",
    "LICENSE",
    "!**/node_modules/**",
    "THIRD_PARTY_NOTICES.md",
    "!**/__tests__/**",
    "!**/*.test.ts",
    "!**/*.test.tsx",
    "!**/*.test.js",
    "!**/*.test.mjs",
    "!**/*.spec.ts",
    "!**/*.spec.tsx",
    "!**/*.nft.json"
  ],
  "workspaces": [
    "open-sse",
    "packages/browser-pool"
  ],
  "engines": {
    "node": ">=22.22.2 <23 || >=24.0.0 <27"
  },
  "keywords": [
    "ai",
    "router",
    "proxy",
    "openai",
    "claude",
    "anthropic",
    "gemini",
    "fallback",
    "cursor",
    "cline",
    "codex",
    "llm",
    "auto-fallback"
  ],
  "license": "MIT",

การทำงานทางวิศวกรรม:

  • โค้ดส่วนนี้ทำหน้าที่เป็นแกนกลางในการควบคุม Flow ของข้อมูล
  • แยกหน้าที่การทำงานชัดเจน (Separation of Concerns) ทำให้สเกลเครื่องมือใหม่ๆ เข้าสู่ระบบได้ทันทีโดยไม่ต้องแก้ Core Engine

📄 ผ่าไฟล์จริง: CLAUDE.md

# CLAUDE.md

@AGENTS.md

**All project rules live in [`AGENTS.md`](AGENTS.md)** — the single source of truth for every AI
assistant (architecture, conventions, testing, quality gates, git workflow, the 23 Hard Rules,
PII learnings). Read it in full; do not re-add project rules here. Everything below applies ONLY
to Claude Code — operational refinements of rules already defined in `AGENTS.md`.

## Worktree isolation — Claude Code specifics

The full mandatory worktree protocol (base-branch confirmation, `.claude/worktrees/` canonical
path, `cp -al` node_modules, teardown rules) is in `AGENTS.md` → Git Workflow → "Worktree
isolation". Claude-Code-specific points:

- Confirm the base branch with the operator via `AskUserQuestion` (Hard Rule #19) unless they
  already told you.
- Prefer the native `EnterWorktree` tool — it already creates worktrees under
  `.claude/worktrees/` (the canonical path). Create the worktree with the documented `git
worktree add` command, then call `EnterWorktree` with its `path`.

## Cross-session safety — Claude Code specifics

Hard Rules #19/#21/#22 (in `AGENTS.md`) govern parallel sessions. Operational reminders for this
harness:

- **Replicate the `git stash` ban verbatim in the prompt of every subagent that touches git**
  (Agent tool / Workflow scripts) — subagents do not inherit this file, and the recorded
  recurrence of the stash incident came through a subagent.
- Before merging or pushing to any PR you did not create _this session_, run `git worktree list`
  and re-check `gh pr view <N> --json state,headRefOid` (Hard Rule #22b).
- End every session with the main checkout on the branch it started on.

## Superpowers / planning artifacts — path overrides

The `_tasks/` convention is defined in `AGENTS.md` → "Planning & Research Artifacts". The
superpowers skills ship with defaults that point at `docs/…` — those defaults are **overridden
here**. When a superpowers skill announces a path like "saved to `docs/superpowers/plans/…`",
rewrite it to the `_tasks/…` equivalent before writing:

| Artifact (skill)                   | Default (do NOT use)      | Save here instead                                             |
| ---------------------------------- | ------------------------- | ------------------------------------------------------------- |
| Plans (`writing-plans`)            | `docs/superpowers/plans/` | `_tasks/superpowers/plans/YYYY-MM-DD-<feature>.md`            |
| Specs / design (`brainstorming`)   | `docs/superpowers/specs/` | `_tasks/superpowers/specs/YYYY-MM-DD-<topic>-design.md`       |
| Research (`deep-research`, ad-hoc) | `docs/research/`          | `_tasks/research/…`                                           |
| Hand-offs (`/handoff`)             | —                         | `_tasks/hands-off/<YYYY-MM-DD>_<branch>_v<versão>_sess-<id>/` |

Commit those artifacts inside the `_tasks/` repo (`git -C _tasks …`), never in the main repo.

## Scratch / temporary files — use `_artifacts/`, not `/tmp`

This project overrides the harness's default session scratchpad (`/tmp/claude-*/…`). Write
temporary/working files — exports, generated zips, one-off intermediate outputs, anything you'd
otherwise put in `/tmp` — to `/home/diegosouzapw/dev/proxys/OmniRoute/_artifacts/` instead.

- `_artifacts/` is a root `_*` path: already gitignored (`AGENTS.md` → "Root `_*` paths"), lives
  on disk only, never tracked.
- Reason: keeping scratch output inside the project (vs `/tmp`) makes it trivial for the operator
  to find and delete everything temporary in one place, instead of hunting across ephemeral
  session-specific `/tmp` directories that vanish or accumulate untracked.
- Do **not** confuse this with `_tasks/` (Hard Rule #23, its own private git repo for durable
  plans/specs/research/hand-offs) — `_artifacts/` is for disposable working files only, nothing
  here needs to survive or be versioned.

## Base-green before opening PRs

Before cutting a branch or opening a PR, run the base-green check (`AGENTS.md` → Git Workflow →
"Base-green check"; project skills reference it as `.agents/skills/_shared/base-green.md`). A PR
opened while the base tip is red must carry `⚠️ base-red inherited: #<issue>` in its body. To
drain an accumulated red state (base tip + red PRs), use the `/sweep-reds` skill.

การทำงานทางวิศวกรรม:

  • โค้ดส่วนนี้ทำหน้าที่เป็นแกนกลางในการควบคุม Flow ของข้อมูล
  • แยกหน้าที่การทำงานชัดเจน (Separation of Concerns) ทำให้สเกลเครื่องมือใหม่ๆ เข้าสู่ระบบได้ทันทีโดยไม่ต้องแก้ Core Engine

📄 ผ่าไฟล์จริง: AGENTS.md

# OmniRoute agent guide

> **Single source of truth.** This file holds ALL project rules, conventions, architecture notes
> and Hard Rules for every AI assistant working this repository (Claude Code, Gemini, Codex,
> Copilot, and any other agent). `CLAUDE.md` and `GEMINI.md` only add assistant-specific deltas
> and point back here. When a rule needs to change, change it HERE — never re-fork it into an
> assistant-specific file.

## Quick Start

```bash
npm install                    # Install deps (auto-generates .env from .env.example)
npm run dev                    # Dev server at http://localhost:20128
npm run build                  # Production build (Next.js 16 standalone)
npm run build:release          # Release build
npm run lint                   # ESLint (0 errors expected; warnings are pre-existing)
npm run typecheck:core         # TypeScript check (should be clean)
npm run typecheck:noimplicit:core  # Strict check (no implicit any)
npm run test:coverage          # Unit tests + coverage gate (60/60/60/60 — statements/lines/functions/branches)
npm run check                  # lint + test combined
npm run check:cycles           # Detect circular dependencies
npm run check:docs-all         # Run after changing documentation (includes fabricated-docs validation)

Running Tests

Run the most focused test for changed code first:

# Single test file (Node.js native test runner — most tests)
node --import tsx/esm --test tests/unit/your-file.test.ts

# Vitest (MCP server, autoCombo, cache)
npm run test:vitest

# All suites
npm run test:all

Other suites: npm run test:e2e, npm run test:protocols:e2e, npm run test:ecosystem.

For full test matrix, see CONTRIBUTING.md → “Running Tests”. For deep architecture, see the Repository map and Reference Documentation sections below.


Project at a Glance

OmniRoute — unified AI proxy/router. One endpoint, 352 LLM providers, auto-fallback.

Layer Location Purpose
API Routes src/app/api/v1/ Next.js App Router — entry points
Handlers open-sse/handlers/ Request processing (chat, embeddings, etc)
Executors open-sse/executors/ Provider-specific HTTP dispatch
Translators open-sse/translator/ Format conversion (OpenAI↔Claude↔Gemini)
Transformer open-sse/transformer/ Responses API ↔ Chat Completions
Services open-sse/services/ Combo routing, rate limits, caching, etc
Database src/lib/db/ SQLite domain modules (160 migrations)
Domain/Policy src/domain/ Policy engine, cost rules, fallback logic
MCP Server open-sse/mcp-server/ 110 tools (44 canonical + memory/skill/GitHub/pool/gamification/plugin/Notion/Obsidian/local-corpus/RTK modules), 3 transports (stdio / SSE / Streamable HTTP), 33 scopes
A2A Server src/lib/a2a/ JSON-RPC 2.0 agent protocol
Skills src/lib/skills/ Extensible skill framework
Memory src/lib/memory/ Persistent conversational memory

Monorepo: src/ (Next.js 16 app), open-sse/ (streaming engine workspace), electron/ (desktop app), tests/, bin/ (CLI entry point).


Request Pipeline

Client → /v1/chat/completions (Next.js route)
  → CORS → Zod validation → auth? → policy check → prompt injection guard
  → handleChatCore() [open-sse/handlers/chatCore.ts]
    → cache check → rate limit → combo routing?
      → resolveComboTargets() → handleSingleModel() per target
    → translateRequest() → getExecutor() → executor.execute()
      → fetch() upstream → retry w/ backoff
    → response translation → SSE stream or JSON

การทำงานทางวิศวกรรม:

  • โค้ดส่วนนี้ทำหน้าที่เป็นแกนกลางในการควบคุม Flow ของข้อมูล
  • แยกหน้าที่การทำงานชัดเจน (Separation of Concerns) ทำให้สเกลเครื่องมือใหม่ๆ เข้าสู่ระบบได้ทันทีโดยไม่ต้องแก้ Core Engine

💰 3 พิมพ์เขียวสร้างรายได้จริงจากสถาปัตยกรรมนี้

  1. Enterprise Security & Architecture Consulting (รับงานที่ปรึกษาองค์กร)

    • องค์กรขนาดใหญ่ต้องการนำ AI Agent มาใช้ แต่ติดปัญหา Data Leak และการควบคุม Tool Calling
    • นำสถาปัตยกรรม FastMCP / Sandboxed Context ไปติดตั้งแบบ On-premise ค่าบริการเริ่มต้น 150,000 - 300,000 บาท/โปรเจกต์
  2. Specialized AI Automation Micro-SaaS (สร้างบริการเฉพาะทาง)

    • พัฒนาบริการ Agent สำหรับตรวจสอบช่องโหว่เว็บ (Bug Bounty as a Service) หรือเครื่องมือคุม Context สำหรับทีม Dev
    • ตั้งราคาแบบ Subscription รายเดือน ($29 - $99/เดือน/ผู้ใช้)
  3. Developer Tools & Workflow Optimization Retainer

    • ให้บริการตรวจสอบและ Optimize สถาปัตยกรรม Token Consumption ให้แก่บริษัท Startup หรือ Tech Agency
    • ช่วยลดค่า API OpenAI / Anthropic จากหลักแสนเหลือหลักหมื่นบาทต่อเดือน โดยคิดส่วนแบ่งจากยอดเงินที่ช่วยประหยัดได้ (Cost-Saving Share 20-30%)

💬 ร่วมสืบคดีและแลกเปลี่ยนความรู้ด้าน AI Engineering กับเราได้ที่เพจ Facebook: นักสืบอัลกอริทึม

🕵️‍♂️

ชอบคดีนี้ไหม? ส่งต่อให้เพื่อนในวงการ Dev!

แชร์บทความวิเคราะห์สถาปัตยกรรม AI & โค้ดจริงที่นำไปใช้สร้างเงินได้ทันที

💬

ร่วมอภิปรายคดีลับ (Case Discussion)

มีข้อสงสัย บัค หรือไอเดียต่อยอดสถาปัตยกรรมนี้? แลกเปลี่ยนกับเพื่อนสาย Dev ได้ด้านล่าง: