Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

overview.md

152 lines8.9 KB

1# Architecture
2​
3> For maintainers. Using T3 Code? See [docs/user](../user/).
4​
5T3 Code is a server runtime that owns agent sessions, workspaces, and version control, plus clients
6(web, desktop, mobile) that talk to it over one authenticated Effect RPC WebSocket. The server is the
7execution boundary: every provider process, terminal, git operation, and filesystem read happens
8there, never in the client.
9​
10```
11┌────────────────────────────────────────────────┐
12│ Clients: apps/web, apps/desktop, apps/mobile │
13│ shared runtime: packages/client-runtime │
14│ connection supervisor, RPC session, Atom state│
15└──────────────────┬─────────────────────────────┘
16 │ Effect RPC over WebSocket (/ws)
17 │ contract: packages/contracts
18┌──────────────────▼─────────────────────────────┐
19│ apps/server │
20│ orchestration engine (event-sourced) │
21│ provider driver registry (5 built-in drivers) │
22│ checkpointing, VCS, terminals, filesystem │
23└──────────────────┬─────────────────────────────┘
24 │ per-driver transport
25┌──────────────────▼─────────────────────────────┐
26│ Agent CLIs: Codex, Claude, Cursor, Grok, │
27│ OpenCode │
28└────────────────────────────────────────────────┘
29```
30​
31## The RPC boundary
32​
33The client/server contract is an Effect RPC group, not a hand-rolled push protocol. [`rpc.ts`][rpc]
34declares `WS_METHODS` and assembles `WsRpcGroup`; each member is either unary or a server stream
35(`stream: true`). Streaming members such as `orchestration.subscribeShell`,
36`orchestration.subscribeThread`, `subscribeServerConfig`, and `terminal.attach` replace what used to
37be a broadcast push bus: a client subscribes to what it needs and the server pushes only on that
38subscription.
39​
40[`ws.ts`][ws] serves the group. `websocketRpcRouteLayer` mounts `GET /ws`, authenticates the upgrade
41through `EnvironmentAuth.authenticateWebSocketUpgrade`, then hands the socket to
42`RpcServer.toHttpEffectWebsocket`. Authorization is per method: `RPC_REQUIRED_SCOPE` maps each method
43to a scope, and `authorizeEffect`/`authorizeStream` enforce it. Holding a valid socket is not
44authorization to call everything on it. See [environment-auth.md](./environment-auth.md).
45​
46On the client, [`session.ts`][session] opens the socket and builds the typed client.
47`RpcSessionFactory` is the service; a session exposes `client`, `initialConfig`, `ready`, `probe`,
48and `closed`. It performs one attempt and does not retry. Retry, backoff, and offline policy belong
49to the connection supervisor.
50​
51## Shared client runtime
52​
53`packages/client-runtime` holds every non-visual client concern: connection lifecycle,
54authentication, RPC, cached environment data, and domain state as Atom factories. Web and mobile
55compose it the same way (`apps/web/src/connection/runtime.ts` and
56`apps/mobile/src/connection/runtime.ts` mirror each other, differing only in platform-specific
57background-activity layers) and differ beyond that only in the platform layer they supply and the
58UI they build on top. React components never construct transports, retry loops,
59or RPC clients. See [connection-runtime.md](./connection-runtime.md).
60​
61## Orchestration is event-sourced
62​
63The server does not mutate app state directly. Clients dispatch typed commands; the engine turns them
64into persisted events; projections derive the read model.
65​
66[`OrchestrationEngine.ts`][engine] serializes this. `dispatch` offers a `CommandEnvelope` onto
67`commandQueue` and awaits its result; a single worker fiber takes envelopes one at a time, so command
68processing is totally ordered. For each envelope `processEnvelope`:
69​
701. checks the durable command receipt, making retries idempotent;
712. runs `decideOrchestrationCommand` ([`decider.ts`][decider]) to produce events from command plus
72 current state, pure and side-effect free;
733. inside one SQL transaction, appends events to the event store, applies them to the in-memory read
74 model via [`projector.ts`][projector], projects them into persisted tables, and writes the
75 accepted receipt;
764. after commit, swaps in the new read model and publishes committed events to subscribers.
77​
78Because persistence and projection share a transaction, the read model cannot durably disagree with
79the event log. On dispatch failure the engine rereads persisted events past the starting sequence and
80reconciles.
81​
82Command and event names live in [`orchestration.ts`][contracts]. Some commands are client
83dispatchable (`thread.create`, `thread.turn.start`, `thread.approval.respond`); others are internal
84and produced only by server-side reactors (`thread.message.assistant.delta`,
85`thread.turn.diff.complete`).
86​
87A turn is complete when its session leaves `running` status, projected by
88`settledTurnStateForSessionStatus` in [`projector.ts`][projector]. Checkpoint work settling later
89does not define turn end.
90​
91## Drainable workers
92​
93Follow-up work runs asynchronously in queue-backed workers built on [`DrainableWorker`][worker]:
94[`ProviderRuntimeIngestion`][ingest] normalizes provider runtime streams into orchestration commands,
95[`ProviderCommandReactor`][cmd] dispatches provider calls in response to intent events, and
96[`CheckpointReactor`][checkpoint] captures and reverts workspace checkpoints.
97​
98`DrainableWorker` pairs a transactional queue with a transactional count of outstanding items.
99`enqueue` atomically offers and increments; processing always decrements. `drain` retries until the
100count reaches zero, so a test can await "queue empty and current item finished" instead of sleeping.
101Each of the three services exposes `drain` for exactly this.
102​
103Runtime receipts are a test-only mechanism. `RuntimeReceiptBusLive` in
104[`RuntimeReceiptBus.ts`][receipts] publishes nothing; only the test layer is PubSub-backed. Do not
105build production behavior on receipts.
106​
107## Provider drivers
108​
109Five drivers ship built in, registered in [`builtInDrivers.ts`][drivers] as `BUILT_IN_DRIVERS`:
110Codex, Claude, Cursor, Grok, and OpenCode. A driver declares its kind and config schema and creates a
111scoped adapter; `ProviderInstanceRegistry` owns live instances and `ProviderAdapterRegistry` resolves
112an instance to its adapter, so `ProviderService` routes session and turn operations without knowing
113which agent is behind them. See [providers.md](./providers.md).
114​
115## Checkpointing
116​
117Each turn is bracketed by workspace checkpoints so diffs and reverts are exact. `CheckpointStore`
118captures state as hidden Git refs through the VCS driver's checkpoint operations;
119`CheckpointDiffQuery` answers turn and full-thread diff requests; `CheckpointReactor` coordinates
120baseline capture, completed-turn capture, diff projection, and reverting both the workspace and the
121provider conversation. The storage contract is `VcsCheckpointOps` in
122[`VcsDriver.ts`](../../apps/server/src/vcs/VcsDriver.ts), implemented for Git in the same directory.
123​
124## Startup
125​
126[`serverRuntimeStartup.ts`][startup] runs a fixed lifecycle: start keybindings, settings, and
127reactors; publish welcome; signal command readiness (logged as `Accepting commands`); wait for the
128HTTP listener via `markHttpListening`; publish ready; fork the heartbeat; then either print headless
129output or open the browser. Command readiness precedes the listener, so a socket that opens can
130already dispatch.
131​
132## Related
133​
134- [Workspace layout](./workspace-layout.md), [Glossary](./glossary.md)
135- [Remote environments](./remote.md), [Server updates](./server-updates.md)
136- [Resource telemetry](./resource-telemetry.md)
137- [Scripts](./scripts.md), [CI gates](./ci.md)
138​
139[rpc]: ../../packages/contracts/src/rpc.ts
140[contracts]: ../../packages/contracts/src/orchestration.ts
141[ws]: ../../apps/server/src/ws.ts
142[session]: ../../packages/client-runtime/src/rpc/session.ts
143[startup]: ../../apps/server/src/serverRuntimeStartup.ts
144[engine]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
145[decider]: ../../apps/server/src/orchestration/decider.ts
146[projector]: ../../apps/server/src/orchestration/projector.ts
147[worker]: ../../packages/shared/src/DrainableWorker.ts
148[ingest]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
149[cmd]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
150[checkpoint]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
151[receipts]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
152[drivers]: ../../apps/server/src/provider/builtInDrivers.ts