> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pingdotgg/t3code/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> Understanding T3 Code's system architecture and component interactions

T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web application.

## System Overview

The application follows a three-tier architecture:

```
┌─────────────────────────────────┐
│  Browser (React + Vite)         │
│  Connected via WebSocket        │
└──────────┬──────────────────────┘
           │ ws://localhost:3773
┌──────────▼──────────────────────┐
│  apps/server (Node.js)          │
│  WebSocket + HTTP static server │
│  ProviderManager                │
│  CodexAppServerManager          │
└──────────┬──────────────────────┘
           │ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│  codex app-server               │
└─────────────────────────────────┘
```

<Note>
  T3 Code is currently **Codex-first**. Support for additional providers like Claude Code is reserved in the contracts and UI layer.
</Note>

## Core Components

### Browser Layer (React + Vite)

The web application manages:

* Session UX and conversation rendering
* Client-side state management
* Real-time event streaming from server
* WebSocket connection lifecycle

**Location**: `apps/web`

### Server Layer (Node.js)

The Node.js server orchestrates:

<CardGroup cols={2}>
  <Card title="WebSocket Server" icon="broadcast-tower">
    Routes RPC methods and pushes domain events to connected clients
  </Card>

  <Card title="Provider Management" icon="plug">
    Manages provider sessions and dispatches commands through adapters
  </Card>

  <Card title="Event Store" icon="database">
    Persists orchestration events and maintains read-model projections
  </Card>

  <Card title="Static Assets" icon="file">
    Serves the compiled React application
  </Card>
</CardGroup>

**Location**: `apps/server`

### Provider Layer (Codex App Server)

The provider layer handles:

* Agent execution and tool calls
* File system operations
* Command execution approvals
* Thread state management

## Package Structure

T3 Code uses a monorepo structure with clear separation of concerns:

<Accordion title="apps/server - Node.js WebSocket Server">
  Wraps Codex app-server via JSON-RPC over stdio, serves the React web app, and manages provider sessions.

  **Key Responsibilities:**

  * WebSocket protocol handling
  * Provider session lifecycle
  * Event store and projections
  * Checkpoint management
</Accordion>

<Accordion title="apps/web - React/Vite UI">
  Owns session UX, conversation/event rendering, and client-side state. Connects to server via WebSocket.

  **Key Responsibilities:**

  * Conversation UI rendering
  * Real-time event display
  * User input handling
  * Session state management
</Accordion>

<Accordion title="packages/contracts - Shared Schemas">
  Effect/Schema contracts for provider events, WebSocket protocol, and model/session types. **Schema-only — no runtime logic.**

  **Key Exports:**

  * `orchestration.ts` - Event sourcing schemas
  * `provider.ts` - Provider session contracts
  * `model.ts` - Model configuration types
</Accordion>

<Accordion title="packages/shared - Runtime Utilities">
  Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g., `@t3tools/shared/git`) — no barrel index.

  **Key Utilities:**

  * Git operations
  * Model normalization
  * Validation helpers
</Accordion>

## Communication Protocol

The web app communicates with the server via WebSocket using a JSON-RPC-style protocol:

### Request/Response Pattern

```typescript theme={null}
// Request
{ id: "123", method: "providers.startSession", params: {...} }

// Response
{ id: "123", result: {...} }

// Error
{ id: "123", error: {...} }
```

### Push Events

```typescript theme={null}
{
  type: "push",
  channel: "orchestration.domainEvent",
  data: {...}
}
```

<Note>
  Provider runtime activity is projected into orchestration events server-side, then pushed to clients via `orchestration.domainEvent` channel.
</Note>

## Key Interfaces

The `NativeApi` interface defines available WebSocket methods:

```typescript theme={null}
// Provider Operations
providers.startSession
providers.sendTurn
providers.interruptTurn
providers.respondToRequest
providers.stopSession

// Shell Integration
shell.openInEditor

// Server Configuration
server.getConfig
```

## Event Sourcing Architecture

T3 Code uses event sourcing for state management:

<Steps>
  <Step title="Command Dispatch">
    Client sends commands via `orchestration.dispatchCommand`
  </Step>

  <Step title="Event Generation">
    Commands generate immutable domain events stored in the event store
  </Step>

  <Step title="Projection Updates">
    Events update read-model projections (threads, messages, activities)
  </Step>

  <Step title="Client Notification">
    Events are pushed to clients via WebSocket on `orchestration.domainEvent`
  </Step>
</Steps>

### Orchestration Methods

```typescript theme={null}
const ORCHESTRATION_WS_METHODS = {
  getSnapshot: "orchestration.getSnapshot",
  dispatchCommand: "orchestration.dispatchCommand",
  getTurnDiff: "orchestration.getTurnDiff",
  getFullThreadDiff: "orchestration.getFullThreadDiff",
  replayEvents: "orchestration.replayEvents",
};
```

## Provider Architecture

The provider layer uses an adapter pattern for extensibility:

```typescript theme={null}
ProviderService
  ↓
ProviderAdapterRegistry
  ↓
CodexAdapter ← implements ProviderAdapterShape
```

### Provider Session Lifecycle

<CodeGroup>
  ```typescript apps/server/src/codexAppServerManager.ts theme={null}
  export class CodexAppServerManager extends EventEmitter {
    async startSession(input: CodexAppServerStartSessionInput) {
      // 1. Spawn codex app-server process
      const child = spawn(codexBinaryPath, ["app-server"], {...});
      
      // 2. Initialize JSON-RPC connection
      await this.sendRequest(context, "initialize", {...});
      
      // 3. Start or resume thread
      const response = await this.sendRequest(
        context,
        resumeThreadId ? "thread/resume" : "thread/start",
        {...}
      );
      
      // 4. Emit session ready event
      this.emitLifecycleEvent(context, "session/ready", ...);
      
      return session;
    }
  }
  ```

  ```typescript Session States theme={null}
  type SessionStatus =
    | "connecting"    // Spawning process
    | "ready"         // Idle, accepting turns
    | "running"       // Turn in progress
    | "error"         // Recoverable error
    | "closed";       // Session terminated
  ```
</CodeGroup>

## Design Principles

<CardGroup cols={2}>
  <Card title="Performance First" icon="gauge-high">
    Optimized for low latency and high throughput
  </Card>

  <Card title="Reliability First" icon="shield-check">
    Predictable behavior under load and failures
  </Card>

  <Card title="Maintainability" icon="code">
    Extract shared logic, avoid duplication
  </Card>

  <Card title="Correctness" icon="check">
    Choose robustness over short-term convenience
  </Card>
</CardGroup>

<Warning>
  **Core Priority**: When tradeoffs are required, always choose correctness and robustness over convenience. Keep behavior predictable during session restarts, reconnects, and partial streams.
</Warning>

## Data Flow

The complete data flow through the system:

```mermaid theme={null}
sequenceDiagram
    participant U as User (Browser)
    participant W as WebSocket Server
    participant P as ProviderService
    participant C as Codex App Server
    participant E as Event Store

    U->>W: orchestration.dispatchCommand
    W->>E: Store command
    W->>P: Route to provider
    P->>C: JSON-RPC request
    C-->>P: Events stream
    P->>E: Store events
    E->>W: Project read model
    W-->>U: Push orchestration.domainEvent
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Sessions" icon="plug" href="/concepts/sessions">
    Learn about session lifecycle and management
  </Card>

  <Card title="Runtime Modes" icon="shield" href="/concepts/runtime-modes">
    Understand approval policies and sandbox modes
  </Card>

  <Card title="Providers" icon="robot" href="/concepts/providers">
    Explore provider adapter architecture
  </Card>

  <Card title="Getting Started" icon="rocket" href="/getting-started">
    Set up your development environment
  </Card>
</CardGroup>
