Skip to main content

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

getReadModel
() => Effect<OrchestrationReadModel>
Read the current in-memory orchestration read modelReturns: Latest read model snapshot containing projects, threads, turns, and messages.Errors: Never fails
readEvents
(fromSequenceExclusive: number) => Stream<OrchestrationEvent, OrchestrationEventStoreError>
Replay persisted orchestration events from an exclusive sequence cursorParameters:
  • fromSequenceExclusive: Sequence cursor (exclusive start)
Returns: Stream of ordered events starting after the specified sequenceErrors: OrchestrationEventStoreError on persistence failures
dispatch
(command: OrchestrationCommand) => Effect<{ sequence: number }, OrchestrationDispatchError>
Dispatch a validated orchestration commandDispatch is serialized through an internal queue and deduplicated via command receipts.Parameters:
  • command: Valid orchestration command
Returns: Sequence number of the persisted eventErrors: OrchestrationDispatchError on validation or persistence failures
streamDomainEvents
Stream<OrchestrationEvent>
Stream persisted domain events in dispatch orderThis is a hot runtime stream (new events only), not a historical replay.Returns: Live stream of orchestration events

Example Usage

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

getSnapshot
() => Effect<OrchestrationReadModel, ProjectionRepositoryError>
Read the latest orchestration projection snapshotRehydrates from projection tables and derives snapshot sequence from projector cursor state.Returns: Complete read model with projects, threads, turns, messages, and checkpointsErrors: ProjectionRepositoryError on database failures

Example Usage

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

bootstrap
Effect<void, ProjectionRepositoryError>
Bootstrap projections by replaying persisted eventsResumes each projector from its stored projection-state cursor.Errors: ProjectionRepositoryError on database failures
projectEvent
(event: OrchestrationEvent) => Effect<void, ProjectionRepositoryError>
Project a single orchestration event into projection repositoriesProjectors are executed sequentially to preserve deterministic ordering.Parameters:
  • event: Orchestration event to project
Errors: ProjectionRepositoryError on database failures

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

start
Effect<void, never, Scope>
Start ingesting provider runtime events into orchestration commandsMust 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

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

start
Effect<void, never, Scope>
Start the checkpoint reactorMust 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

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

start
Effect<void, never, Scope>
Start reacting to provider-intent orchestration domain eventsMust 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

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

startSession
(threadId: ThreadId, input: ProviderSessionStartInput) => Effect<ProviderSession, ProviderServiceError>
Start a provider sessionParameters:
  • threadId: Thread identifier
  • input: Session configuration including provider, model, and runtime settings
Returns: Active provider session detailsErrors: ProviderServiceError on adapter resolution or session startup failures
sendTurn
(input: ProviderSendTurnInput) => Effect<ProviderTurnStartResult, ProviderServiceError>
Send a provider turnParameters:
  • input: Turn configuration including thread ID, messages, and sampling parameters
Returns: Turn start result with turn ID and initial stateErrors: ProviderServiceError on session not found or turn dispatch failures
interruptTurn
(input: ProviderInterruptTurnInput) => Effect<void, ProviderServiceError>
Interrupt a running provider turnParameters:
  • input: Thread ID and optional turn ID
Errors: ProviderServiceError on session not found or interrupt failures
respondToRequest
(input: ProviderRespondToRequestInput) => Effect<void, ProviderServiceError>
Respond to a provider approval requestParameters:
  • input: Request ID, thread ID, and approval decision
Errors: ProviderServiceError on session not found or response failures
respondToUserInput
(input: ProviderRespondToUserInputInput) => Effect<void, ProviderServiceError>
Respond to a provider structured user-input requestParameters:
  • input: Request ID, thread ID, and user input answers
Errors: ProviderServiceError on session not found or response failures
stopSession
(input: ProviderStopSessionInput) => Effect<void, ProviderServiceError>
Stop a provider sessionParameters:
  • input: Thread ID to stop
Errors: ProviderServiceError on session not found or stop failures
listSessions
() => Effect<ReadonlyArray<ProviderSession>>
List active provider sessionsAggregates runtime session lists from all registered adapters.Returns: Array of active provider sessions
getCapabilities
(provider: ProviderKind) => Effect<ProviderAdapterCapabilities, ProviderServiceError>
Read static capabilities for a provider adapterParameters:
  • provider: Provider kind (e.g., "codex")
Returns: Adapter capabilities including model switch supportErrors: ProviderServiceError on unsupported provider
rollbackConversation
(input: { threadId: ThreadId, numTurns: number }) => Effect<void, ProviderServiceError>
Roll back provider conversation state by a number of turnsParameters:
  • threadId: Thread identifier
  • numTurns: Number of turns to roll back
Errors: ProviderServiceError on session not found or rollback failures
streamEvents
Stream<ProviderRuntimeEvent>
Canonical provider runtime event streamFan-out is owned by ProviderService (not by a standalone event-bus service).Returns: Live stream of provider runtime events

Example Usage

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

sessionModelSwitch
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

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
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
import { makeServerRuntimeServicesLayer } from "./serverLayers";

const runtimeLayer = makeServerRuntimeServicesLayer();
Provides:
  • OrchestrationReactor
  • GitCore
  • GitManager
  • TerminalManager
  • Keybindings

Service Composition

Services are composed using Effect’s Layer API:
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));