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

overview.md

179 lines11.1 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 (6 built-in drivers) │
22│ checkpointing, VCS, terminals, filesystem │
23└──────────────────┬─────────────────────────────┘
24 │ per-driver transport
25┌──────────────────▼─────────────────────────────┐
26│ Agent CLIs: Codex, Claude, Cursor, Grok, │
27│ OpenCode, Antigravity │
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 shared-settings sync
94target (`SHARED_SERVER_SETTING_KEYS` in `packages/client-runtime/src/state/sharedSettings.ts`) and
95warn when another target drifts. A target must have an active connection and advertise the
96`threadAutoSettlement` capability, which signals that the server can hold every shared key.
97[`ThreadSettlementReactor`][settlement] checks threads at startup, when those settings change, and
98once per minute, including when no client is connected. It dispatches the guarded internal
99`thread.auto-settle` command, which uses the existing settlement event lifecycle. Automatic
100settlement excludes live background work and requires a comparable PR timestamp for immediate PR
101settlement. The command carries the latest activity timestamp and rejects any later event for its
102thread after the reactor's snapshot. The sweep looks a branch up from the thread's worktree when it
103still exists, so it shares the per-cwd PR cache the sidebar polls instead of spending a second host
104request. Clients render the persisted settlement state and do not derive settlement from PR or
105inactivity state. A committed `thread.settled` event also lets `ProviderCommandReactor` stop an idle
106provider session.
107​
108At turn completion, `CheckpointReactor` refreshes PR discovery when the checkout matches the
109thread's non-default branch. `VcsStatusBroadcaster` requires loaded remote status and permission
110from background policy. `GitManager` retries only a successful "no PR" cache entry for the current
111branch, preserving known PRs and failure backoff without fetching remotes. Remote status reads
112that write the broadcaster cache share a lock per cwd, including the initial status load.
113​
114## Drainable workers
115​
116Follow-up work runs asynchronously in queue-backed workers built on [`DrainableWorker`][worker]:
117[`ProviderRuntimeIngestion`][ingest] normalizes provider runtime streams into orchestration commands,
118[`ProviderCommandReactor`][cmd] dispatches provider calls in response to intent events,
119[`CheckpointReactor`][checkpoint] captures and reverts workspace checkpoints, and
120[`ThreadSettlementReactor`][settlement] evaluates server-owned automatic settlement rules.
121​
122`DrainableWorker` pairs a transactional queue with a transactional count of outstanding items.
123`enqueue` atomically offers and increments; processing always decrements. `drain` retries until the
124count reaches zero, so a test can await "queue empty and current item finished" instead of sleeping.
125Each of these four services exposes `drain` for exactly this.
126​
127Runtime receipts are a test-only mechanism. `RuntimeReceiptBusLive` in
128[`RuntimeReceiptBus.ts`][receipts] publishes nothing; only the test layer is PubSub-backed. Do not
129build production behavior on receipts.
130​
131## Provider drivers
132​
133Six drivers ship built in, registered in [`builtInDrivers.ts`][drivers] as `BUILT_IN_DRIVERS`:
134Codex, Claude, Cursor, Grok, OpenCode, and Antigravity. A driver declares its kind and config schema and creates a
135scoped adapter; `ProviderInstanceRegistry` owns live instances and `ProviderAdapterRegistry` resolves
136an instance to its adapter, so `ProviderService` routes session and turn operations without knowing
137which agent is behind them. See [providers.md](./providers.md).
138​
139## Checkpointing
140​
141Each turn is bracketed by workspace checkpoints so diffs and reverts are exact. `CheckpointStore`
142captures state as hidden Git refs through the VCS driver's checkpoint operations;
143`CheckpointDiffQuery` answers turn and full-thread diff requests; `CheckpointReactor` coordinates
144baseline capture, completed-turn capture, diff projection, and reverting both the workspace and the
145provider conversation. The storage contract is `VcsCheckpointOps` in
146[`VcsDriver.ts`](../../apps/server/src/vcs/VcsDriver.ts), implemented for Git in the same directory.
147​
148## Startup
149​
150[`serverRuntimeStartup.ts`][startup] runs a fixed lifecycle: start keybindings, settings, and
151reactors; publish welcome; signal command readiness (logged as `Accepting commands`); wait for the
152HTTP listener via `markHttpListening`; publish ready; fork the heartbeat; then either print headless
153output or open the browser. Command readiness precedes the listener, so a socket that opens can
154already dispatch.
155​
156## Related
157​
158- [Workspace layout](./workspace-layout.md), [Glossary](./glossary.md)
159- [Mobile navigation headers](./mobile-navigation.md)
160- [Remote environments](./remote.md), [Server updates](./server-updates.md)
161- [Resource telemetry](./resource-telemetry.md)
162- [Product analytics](./product-analytics.md)
163- [Scripts](./scripts.md), [CI gates](./ci.md)
164​
165[rpc]: ../../packages/contracts/src/rpc.ts
166[contracts]: ../../packages/contracts/src/orchestration.ts
167[ws]: ../../apps/server/src/ws.ts
168[session]: ../../packages/client-runtime/src/rpc/session.ts
169[startup]: ../../apps/server/src/serverRuntimeStartup.ts
170[engine]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
171[decider]: ../../apps/server/src/orchestration/decider.ts
172[projector]: ../../apps/server/src/orchestration/projector.ts
173[worker]: ../../packages/shared/src/DrainableWorker.ts
174[ingest]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
175[cmd]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
176[checkpoint]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
177[settlement]: ../../apps/server/src/orchestration/ThreadSettlementReactor.ts
178[receipts]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
179[drivers]: ../../apps/server/src/provider/builtInDrivers.ts