> ## 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.

# Services

> Core server service contracts and orchestration interfaces

## Overview

T3 Code server architecture is built on Effect's service layer pattern, providing composable, type-safe service contracts for orchestration, provider management, and persistence.

## Orchestration Services

### OrchestrationEngineService

Command and event orchestration engine that owns command validation, dispatch, and read-model management.

**Service Tag:** `t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService`

**Source:** `apps/server/src/orchestration/Services/OrchestrationEngine.ts:77`

#### Methods

<ParamField path="getReadModel" type="() => Effect<OrchestrationReadModel>">
  Read the current in-memory orchestration read model

  **Returns:** Latest read model snapshot containing projects, threads, turns, and messages.

  **Errors:** Never fails
</ParamField>

<ParamField path="readEvents" type="(fromSequenceExclusive: number) => Stream<OrchestrationEvent, OrchestrationEventStoreError>">
  Replay persisted orchestration events from an exclusive sequence cursor

  **Parameters:**

  * `fromSequenceExclusive`: Sequence cursor (exclusive start)

  **Returns:** Stream of ordered events starting after the specified sequence

  **Errors:** `OrchestrationEventStoreError` on persistence failures
</ParamField>

<ParamField path="dispatch" type="(command: OrchestrationCommand) => Effect<{ sequence: number }, OrchestrationDispatchError>">
  Dispatch a validated orchestration command

  Dispatch is serialized through an internal queue and deduplicated via command receipts.

  **Parameters:**

  * `command`: Valid orchestration command

  **Returns:** Sequence number of the persisted event

  **Errors:** `OrchestrationDispatchError` on validation or persistence failures
</ParamField>

<ParamField path="streamDomainEvents" type="Stream<OrchestrationEvent>">
  Stream persisted domain events in dispatch order

  This is a hot runtime stream (new events only), not a historical replay.

  **Returns:** Live stream of orchestration events
</ParamField>

#### Example Usage

```typescript theme={null}
import { Effect } from "effect";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";

const program = Effect.gen(function* () {
  const engine = yield* OrchestrationEngineService;
  
  // Read current state
  const readModel = yield* engine.getReadModel();
  console.log(`Active threads: ${readModel.threads.length}`);
  
  // Dispatch a command
  const result = yield* engine.dispatch({
    _tag: "OrchestrationCommand.CreateThread",
    commandId: "cmd-123",
    // ... command payload
  });
  console.log(`Event persisted at sequence: ${result.sequence}`);
});
```

### ProjectionSnapshotQuery

Read-model snapshot query service for retrieving the latest orchestration projection state.

**Service Tag:** `t3/orchestration/Services/ProjectionSnapshotQuery`

**Source:** `apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts:31`

#### Methods

<ParamField path="getSnapshot" type="() => Effect<OrchestrationReadModel, ProjectionRepositoryError>">
  Read the latest orchestration projection snapshot

  Rehydrates from projection tables and derives snapshot sequence from projector cursor state.

  **Returns:** Complete read model with projects, threads, turns, messages, and checkpoints

  **Errors:** `ProjectionRepositoryError` on database failures
</ParamField>

#### Example Usage

```typescript theme={null}
const program = Effect.gen(function* () {
  const query = yield* ProjectionSnapshotQuery;
  const snapshot = yield* query.getSnapshot();
  
  console.log(`Sequence: ${snapshot.sequence}`);
  console.log(`Projects: ${snapshot.projects.length}`);
  console.log(`Threads: ${snapshot.threads.length}`);
});
```

### OrchestrationProjectionPipeline

Event projection pipeline that coordinates projection bootstrap and per-event projection updates.

**Service Tag:** `t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline`

**Source:** `apps/server/src/orchestration/Services/ProjectionPipeline.ts:39`

#### Methods

<ParamField path="bootstrap" type="Effect<void, ProjectionRepositoryError>">
  Bootstrap projections by replaying persisted events

  Resumes each projector from its stored projection-state cursor.

  **Errors:** `ProjectionRepositoryError` on database failures
</ParamField>

<ParamField path="projectEvent" type="(event: OrchestrationEvent) => Effect<void, ProjectionRepositoryError>">
  Project a single orchestration event into projection repositories

  Projectors are executed sequentially to preserve deterministic ordering.

  **Parameters:**

  * `event`: Orchestration event to project

  **Errors:** `ProjectionRepositoryError` on database failures
</ParamField>

### ProviderRuntimeIngestionService

Background workers that consume provider runtime streams and emit orchestration commands/events.

**Service Tag:** `t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService`

**Source:** `apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts:31`

#### Methods

<ParamField path="start" type="Effect<void, never, Scope>">
  Start ingesting provider runtime events into orchestration commands

  Must be run in a scope so all worker fibers can be finalized on shutdown. Uses an internal queue and continues after non-interrupt failures by logging warnings.

  **Requires:** `Scope.Scope` context
</ParamField>

### CheckpointReactor

Background workers that react to orchestration checkpoint lifecycle events and apply checkpoint side effects.

**Service Tag:** `t3/orchestration/Services/CheckpointReactor`

**Source:** `apps/server/src/orchestration/Services/CheckpointReactor.ts:31`

#### Methods

<ParamField path="start" type="Effect<void, never, Scope>">
  Start the checkpoint reactor

  Must be run in a scope so all worker fibers can be finalized on shutdown. Consumes both orchestration-domain and provider-runtime events via an internal queue.

  **Requires:** `Scope.Scope` context
</ParamField>

### ProviderCommandReactor

Background workers that react to orchestration intent events and dispatch provider-side command execution.

**Service Tag:** `t3/orchestration/Services/ProviderCommandReactor`

**Source:** `apps/server/src/orchestration/Services/ProviderCommandReactor.ts:31`

#### Methods

<ParamField path="start" type="Effect<void, never, Scope>">
  Start reacting to provider-intent orchestration domain events

  Must be run in a scope so all worker fibers can be finalized on shutdown. Filters orchestration domain events to provider-intent types before processing.

  **Requires:** `Scope.Scope` context
</ParamField>

## Provider Services

### ProviderService

Cross-provider facade for provider sessions, turns, and checkpoints. Routes session-scoped calls via `ProviderSessionDirectory` and exposes one unified provider event stream.

**Service Tag:** `t3/provider/Services/ProviderService`

**Source:** `apps/server/src/provider/Services/ProviderService.ts:113`

#### Methods

<ParamField path="startSession" type="(threadId: ThreadId, input: ProviderSessionStartInput) => Effect<ProviderSession, ProviderServiceError>">
  Start a provider session

  **Parameters:**

  * `threadId`: Thread identifier
  * `input`: Session configuration including provider, model, and runtime settings

  **Returns:** Active provider session details

  **Errors:** `ProviderServiceError` on adapter resolution or session startup failures
</ParamField>

<ParamField path="sendTurn" type="(input: ProviderSendTurnInput) => Effect<ProviderTurnStartResult, ProviderServiceError>">
  Send a provider turn

  **Parameters:**

  * `input`: Turn configuration including thread ID, messages, and sampling parameters

  **Returns:** Turn start result with turn ID and initial state

  **Errors:** `ProviderServiceError` on session not found or turn dispatch failures
</ParamField>

<ParamField path="interruptTurn" type="(input: ProviderInterruptTurnInput) => Effect<void, ProviderServiceError>">
  Interrupt a running provider turn

  **Parameters:**

  * `input`: Thread ID and optional turn ID

  **Errors:** `ProviderServiceError` on session not found or interrupt failures
</ParamField>

<ParamField path="respondToRequest" type="(input: ProviderRespondToRequestInput) => Effect<void, ProviderServiceError>">
  Respond to a provider approval request

  **Parameters:**

  * `input`: Request ID, thread ID, and approval decision

  **Errors:** `ProviderServiceError` on session not found or response failures
</ParamField>

<ParamField path="respondToUserInput" type="(input: ProviderRespondToUserInputInput) => Effect<void, ProviderServiceError>">
  Respond to a provider structured user-input request

  **Parameters:**

  * `input`: Request ID, thread ID, and user input answers

  **Errors:** `ProviderServiceError` on session not found or response failures
</ParamField>

<ParamField path="stopSession" type="(input: ProviderStopSessionInput) => Effect<void, ProviderServiceError>">
  Stop a provider session

  **Parameters:**

  * `input`: Thread ID to stop

  **Errors:** `ProviderServiceError` on session not found or stop failures
</ParamField>

<ParamField path="listSessions" type="() => Effect<ReadonlyArray<ProviderSession>>">
  List active provider sessions

  Aggregates runtime session lists from all registered adapters.

  **Returns:** Array of active provider sessions
</ParamField>

<ParamField path="getCapabilities" type="(provider: ProviderKind) => Effect<ProviderAdapterCapabilities, ProviderServiceError>">
  Read static capabilities for a provider adapter

  **Parameters:**

  * `provider`: Provider kind (e.g., `"codex"`)

  **Returns:** Adapter capabilities including model switch support

  **Errors:** `ProviderServiceError` on unsupported provider
</ParamField>

<ParamField path="rollbackConversation" type="(input: { threadId: ThreadId, numTurns: number }) => Effect<void, ProviderServiceError>">
  Roll back provider conversation state by a number of turns

  **Parameters:**

  * `threadId`: Thread identifier
  * `numTurns`: Number of turns to roll back

  **Errors:** `ProviderServiceError` on session not found or rollback failures
</ParamField>

<ParamField path="streamEvents" type="Stream<ProviderRuntimeEvent>">
  Canonical provider runtime event stream

  Fan-out is owned by ProviderService (not by a standalone event-bus service).

  **Returns:** Live stream of provider runtime events
</ParamField>

#### Example Usage

```typescript theme={null}
import { Effect, Stream } from "effect";
import { ProviderService } from "./provider/Services/ProviderService";

const program = Effect.gen(function* () {
  const provider = yield* ProviderService;
  
  // Start a session
  const session = yield* provider.startSession(threadId, {
    provider: "codex",
    model: "o3-mini",
    mode: "streaming",
    // ... other options
  });
  
  // Send a turn
  const turn = yield* provider.sendTurn({
    threadId,
    messages: [{ role: "user", content: "Hello" }],
  });
  
  // Stream events
  yield* Stream.runForEach(provider.streamEvents, (event) =>
    Effect.log(`Event: ${event._tag}`)
  );
});
```

### ProviderAdapter

Provider-specific runtime adapter contract defining session and protocol operations.

**Source:** `apps/server/src/provider/Services/ProviderAdapter.ts`

#### ProviderAdapterCapabilities

<ResponseField name="sessionModelSwitch" type="ProviderSessionModelSwitchMode">
  Declares whether changing the model on an existing session is supported

  * `"in-session"`: Model can be changed without restarting
  * `"restart-session"`: Model change requires session restart
  * `"unsupported"`: Model switching not supported
</ResponseField>

#### ProviderAdapterShape Interface

Provider adapters must implement:

* `startSession`: Start a provider-backed session
* `sendTurn`: Send a turn to an active session
* `interruptTurn`: Interrupt an active turn
* `respondToRequest`: Respond to an approval request
* `respondToUserInput`: Respond to a user-input request
* `stopSession`: Stop one provider session
* `listSessions`: List active sessions for this adapter
* `hasSession`: Check if adapter owns a session
* `readThread`: Read provider thread snapshot
* `rollbackThread`: Roll back thread by N turns
* `stopAll`: Stop all sessions owned by adapter
* `streamEvents`: Canonical runtime event stream

## Layer Construction

### makeServerProviderLayer

Constructs the provider service layer with adapter registry and session management.

**Source:** `apps/server/src/serverLayers.ts:39`

```typescript theme={null}
import { makeServerProviderLayer } from "./serverLayers";

const providerLayer = makeServerProviderLayer();
```

**Dependencies:**

* `SqlClient.SqlClient`
* `ServerConfig`
* `FileSystem.FileSystem`
* `AnalyticsService`

**Provides:** `ProviderService`

**May Error:** `ProviderUnsupportedError`

### makeServerRuntimeServicesLayer

Constructs all runtime service layers including orchestration, git, terminal, and keybindings.

**Source:** `apps/server/src/serverLayers.ts:70`

```typescript theme={null}
import { makeServerRuntimeServicesLayer } from "./serverLayers";

const runtimeLayer = makeServerRuntimeServicesLayer();
```

**Provides:**

* `OrchestrationReactor`
* `GitCore`
* `GitManager`
* `TerminalManager`
* `Keybindings`

## Service Composition

Services are composed using Effect's Layer API:

```typescript theme={null}
import { Layer } from "effect";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";

const fullServerLayer = Layer.empty.pipe(
  Layer.provideMerge(makeServerRuntimeServicesLayer()),
  Layer.provideMerge(makeServerProviderLayer()),
  Layer.provideMerge(SqlitePersistenceMemory),
);

const program = Effect.gen(function* () {
  const engine = yield* OrchestrationEngineService;
  const provider = yield* ProviderService;
  // Use services...
}).pipe(Effect.provide(fullServerLayer));
```
