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

overview.md

171 lines10.3 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, cleans up attachments, and publishes committed events
77 to subscribers. Attachment cleanup failures are logged and do not reject committed commands.
78​
79Because persistence and projection share a transaction, the read model cannot durably disagree with
80the event log. On dispatch failure the engine rereads persisted events past the starting sequence and
81reconciles.
82​
83Command and event names live in [`orchestration.ts`][contracts]. Some commands are client
84dispatchable (`thread.create`, `thread.turn.start`, `thread.approval.respond`); others are internal
85and produced only by server-side reactors (`thread.message.assistant.delta`,
86`thread.turn.diff.complete`).
87​
88A turn is complete when its session leaves `running` status, projected by
89`settledTurnStateForSessionStatus` in [`projector.ts`][projector]. Checkpoint work settling later
90does not define turn end.
91​
92Thread settlement is server-owned. Each server's own settings control PR and inactivity
93settlement. Those keys are user preferences, so clients write them to every connected environment
94(`SHARED_SERVER_SETTING_KEYS` in `packages/client-runtime/src/state/sharedSettings.ts`) and warn
95when a connected environment drifts.
96[`ThreadSettlementReactor`][settlement] checks threads at startup, when those settings change, and
97once per minute, including when no client is connected. It dispatches the guarded internal
98`thread.auto-settle` command, which uses the existing settlement event lifecycle. Automatic
99settlement excludes live background work and requires a comparable PR timestamp for immediate PR
100settlement. The command carries the latest activity timestamp and rejects any later event for its
101thread after the reactor's snapshot.
102Clients render the persisted settlement state and do not derive settlement from PR or inactivity
103state. A committed `thread.settled` event also lets `ProviderCommandReactor` stop an idle provider
104session.
105​
106## Drainable workers
107​
108Follow-up work runs asynchronously in queue-backed workers built on [`DrainableWorker`][worker]:
109[`ProviderRuntimeIngestion`][ingest] normalizes provider runtime streams into orchestration commands,
110[`ProviderCommandReactor`][cmd] dispatches provider calls in response to intent events,
111[`CheckpointReactor`][checkpoint] captures and reverts workspace checkpoints, and
112[`ThreadSettlementReactor`][settlement] evaluates server-owned automatic settlement rules.
113​
114`DrainableWorker` pairs a transactional queue with a transactional count of outstanding items.
115`enqueue` atomically offers and increments; processing always decrements. `drain` retries until the
116count reaches zero, so a test can await "queue empty and current item finished" instead of sleeping.
117Each of these four services exposes `drain` for exactly this.
118​
119Runtime receipts are a test-only mechanism. `RuntimeReceiptBusLive` in
120[`RuntimeReceiptBus.ts`][receipts] publishes nothing; only the test layer is PubSub-backed. Do not
121build production behavior on receipts.
122​
123## Provider drivers
124​
125Five drivers ship built in, registered in [`builtInDrivers.ts`][drivers] as `BUILT_IN_DRIVERS`:
126Codex, Claude, Cursor, Grok, and OpenCode. A driver declares its kind and config schema and creates a
127scoped adapter; `ProviderInstanceRegistry` owns live instances and `ProviderAdapterRegistry` resolves
128an instance to its adapter, so `ProviderService` routes session and turn operations without knowing
129which agent is behind them. See [providers.md](./providers.md).
130​
131## Checkpointing
132​
133Each turn is bracketed by workspace checkpoints so diffs and reverts are exact. `CheckpointStore`
134captures state as hidden Git refs through the VCS driver's checkpoint operations;
135`CheckpointDiffQuery` answers turn and full-thread diff requests; `CheckpointReactor` coordinates
136baseline capture, completed-turn capture, diff projection, and reverting both the workspace and the
137provider conversation. The storage contract is `VcsCheckpointOps` in
138[`VcsDriver.ts`](../../apps/server/src/vcs/VcsDriver.ts), implemented for Git in the same directory.
139​
140## Startup
141​
142[`serverRuntimeStartup.ts`][startup] runs a fixed lifecycle: start keybindings, settings, and
143reactors; publish welcome; signal command readiness (logged as `Accepting commands`); wait for the
144HTTP listener via `markHttpListening`; publish ready; fork the heartbeat; then either print headless
145output or open the browser. Command readiness precedes the listener, so a socket that opens can
146already dispatch.
147​
148## Related
149​
150- [Workspace layout](./workspace-layout.md), [Glossary](./glossary.md)
151- [Mobile navigation headers](./mobile-navigation.md)
152- [Remote environments](./remote.md), [Server updates](./server-updates.md)
153- [Resource telemetry](./resource-telemetry.md)
154- [Product analytics](./product-analytics.md)
155- [Scripts](./scripts.md), [CI gates](./ci.md)
156​
157[rpc]: ../../packages/contracts/src/rpc.ts
158[contracts]: ../../packages/contracts/src/orchestration.ts
159[ws]: ../../apps/server/src/ws.ts
160[session]: ../../packages/client-runtime/src/rpc/session.ts
161[startup]: ../../apps/server/src/serverRuntimeStartup.ts
162[engine]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
163[decider]: ../../apps/server/src/orchestration/decider.ts
164[projector]: ../../apps/server/src/orchestration/projector.ts
165[worker]: ../../packages/shared/src/DrainableWorker.ts
166[ingest]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
167[cmd]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
168[checkpoint]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
169[settlement]: ../../apps/server/src/orchestration/ThreadSettlementReactor.ts
170[receipts]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
171[drivers]: ../../apps/server/src/provider/builtInDrivers.ts