Client POST /v1/chat/completions
│
▼
┌─────────────────────────────────────┐
│ Shutdown middleware check │
│ (503 if shutdown_token cancelled) │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Generate request_id (UUID) │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Spawn producer task │
│ - Register cancellation token │
│ - Subscribe to progress events │
│ - Subscribe to tool events │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Stream chat with TimeoutHook │
│ - Tool calls set thread context │
│ - Tool results clear context │
└─────────────────────────────────────┘
│
├──────────────────┬──────────────────┐
▼ ▼ ▼
┌────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Normal │ │ Timeout/ │ │ Shutdown │
│ completion │ │ Disconnect │ │ (grace expired) │
└────────────────┘ └──────────────────┘ └──────────────────┘
│ │ │
│ ▼ ▼
│ ┌──────────────────┐ ┌──────────────────┐
│ │ Cancel token │ │ Cancel hook + │
│ │ Send MCP cancel │ │ registry │
│ │ Evict from pool │ │ Send [DONE] │
│ └──────────────────┘ │ Then MCP cleanup │
│ │ │ (no pool evict) │
│ │ └──────────────────┘
└──────────┬───────┴──────────────────┘
▼
┌─────────────────────────────────────┐
│ Cleanup (RAII guard) │
│ - Unregister cancellation │
│ - Unsubscribe progress │
│ - Unsubscribe tool events │
└─────────────────────────────────────┘