Open History to see the last commit
1# Provider architecture
2
3> For maintainers. Using T3 Code? See [docs/user](../user/).
4
5A provider is the agent runtime that does the actual work. T3 Code supports several, and the
6orchestration layer does not know which one is behind a thread.
7
8## Built-in drivers
9
10[`builtInDrivers.ts`][drivers] exports `BUILT_IN_DRIVERS` with six entries:
11
12| Driver kind | Driver source |
13| ------------- | --------------------------------------------- |
14| `codex` | [`Drivers/CodexDriver.ts`][codex] |
15| `claudeAgent` | [`Drivers/ClaudeDriver.ts`][claude] |
16| `cursor` | [`Drivers/CursorDriver.ts`][cursor] |
17| `grok` | [`Drivers/GrokDriver.ts`][grok] |
18| `opencode` | [`Drivers/OpenCodeDriver.ts`][opencode] |
19| `antigravity` | [`Drivers/AntigravityDriver.ts`][antigravity] |
20
21Each driver declares its `driverKind`, a `configSchema`, and a `create` function that builds an
22adapter in a child scope. Adapter implementations live beside them in
23`apps/server/src/provider/Layers/` (`CodexAdapter.ts`, `ClaudeAdapter.ts`, and so on) and conform to
24[`ProviderAdapter.ts`][adapter]. Read the driver plus its adapter to see how a specific agent's
25transport, config, and event shapes are mapped.
26
27## Registry and routing
28
29Two registries separate configuration from live processes:
30
31- [`ProviderInstanceRegistry`][instances] keys configured instances by `ProviderInstanceId`. Creating
32 one looks up the driver by `driverKind`, decodes `entry.config` with that driver's schema, opens a
33 child scope, and calls `driver.create`.
34- [`ProviderAdapterRegistry`][registry] resolves an instance ID to its live adapter via
35 `getByInstance`.
36
37[`ProviderService`][service] sits on top. It combines the adapter registry with the provider session
38directory to route session and turn operations for a thread, so callers name a thread, not an agent.
39
40`ProviderService.sendTurn` expands [assistant citations](./assistant-citations.md) into quoted
41reference data before dispatching to any adapter. Bound user comments remain distinct from the quoted
42assistant text. Persisted messages keep their serialized links.
43
44Adding a driver means writing the driver plus adapter and adding it to `BUILT_IN_DRIVERS`. No
45orchestration, contract, or client change is required for the common case.
46
47### Grok health check
48
49`checkGrokProviderStatus` never opens an ACP session. It runs `grok --version`, then `grok models`
50for login state and model slugs, then a single ACP `initialize` and reads models from
51`_meta.modelState`. `authenticate` and `session/new` are skipped on purpose: `authenticate` can open
52a browser login and `session/new` boots every configured MCP server, both of which made background
53probes hang or surprise the user. A failed `initialize` degrades to `warning` with the CLI's model
54list instead of persisting `error` over a working install. The built-in `grok-build` slug is the
55CLI's product name, not an ACP model id. `applyGrokAcpModelSelection` treats it as "keep the
56session's current model" and never sends it in `session/set_model`.
57
58## Antigravity ownership and protocol
59
60[`AntigravityDriver`][antigravity] uses Google's official ACP executable. The instance config
61selects the ACP auth method: `oauth-personal` (default), `oauth-business`, `gemini-api-key`, or
62`agent-platform`. The two OAuth methods share the loopback sign-in flow below. The API key
63methods pass the configured key to the agent as `GEMINI_API_KEY` or `GOOGLE_API_KEY` and never
64open a browser. A GCP project and location are written to the profile's `settings.json` on each
65launch. The driver never reuses CLI credentials or ambient `GOOGLE_*` variables and never falls
66back to another method. Antigravity is disabled by default and supports multiple provider
67instances. The open driver and instance identifiers require no database migration.
68
69### Runtime installation
70
71[`AntigravityInstallation`][antigravity-installation] belongs to the environment, outside
72WebSocket and provider-instance scopes. Instances share an explicit download operation and the
73completed runtime. Client disconnects and instance rebuilds do not cancel installation.
74
75The fixed [release table][antigravity-release] contains official Google URLs, SHA-256 hashes,
76archive sizes, and the exact executable pair for each published host. Downloads stream to disk.
77Lazy `yauzl` entry streams extract only that pair, with member names, types, duplicates, and
78sizes checked. Validation runs ACP `initialize` in a temporary profile without authentication
79or a session. Progress updates are bounded, not sent for every network chunk.
80
81Complete releases live in immutable version directories under the T3 home
82`tools/antigravity-acp/<platform>-<arch>/versions`. An atomic `active.json` change selects the
83release for new processes. Each process holds a version lease until it exits. Updates do not
84replace running executables. Removal refuses active leases or explicit binary paths that still
85reference the managed files. Failure or cancellation removes owned partial files, not the
86previous release or account data.
87
88Resolution order is explicit `binaryPath`, active managed release, then the instance's `PATH`.
89An invalid explicit path fails without fallback. Manual installations are never changed by the
90installer. Every launch pins `ANTIGRAVITY_HARNESS_PATH` to the selected executable's sibling.
91
92### Google profiles and sign-in
93
94Each instance owns a stable profile at
95`<stateDir>/providers/antigravity/<sha256(instanceId)>`.
96[`antigravityAuthSupport.ts`][antigravity-auth-support] sets `GEMINI_HOME` to this directory and
97`AGY_ACP_FORCE_FILE_STORAGE=1` after merging instance environment variables. File storage avoids
98the official macOS keychain entry being shared across instances. Profile directories use mode
99`0700` on POSIX. This is file storage, not an encrypted keychain. Windows uses the host profile's
100filesystem permissions.
101
102The launch environment removes API-key and cloud-billing variables, disables inherited
103environment extension, sets `PYTHONUNBUFFERED=1`, and controls `BROWSER`. A tested Node or
104Electron-as-Node helper prevents the official agent from opening a browser on the environment.
105The same launch factory serves setup, health checks, chat, and text generation.
106
107The official agent prints a non-JSON OAuth line on stderr in version 1.1.1. Earlier versions
108print it on stdout. T3 accepts the exact native prefix on either stream and its browser-helper
109marker on stderr. Fragmented lines are joined and bounded. Other malformed protocol output
110remains fatal. Authorization URLs are validated before use. Other stderr is discarded because
111it can contain OAuth data. Normal work rejects an interactive login request with a
112sign-in-required error instead of waiting for consent. A rejected stderr callback fails pending
113ACP requests and closes the owned process.
114
115[`AntigravityAuth`][antigravity-auth] owns each sign-in process and deadline in the instance
116scope. Only the initiating T3 auth session receives its URL and flow ID or can complete or
117cancel it. Other clients receive busy state without those values. Subscriptions follow
118controller replacement when settings rebuild an instance.
119
120For remote completion, the client sends the full return URL through the typed setup RPC.
121The server validates the pending loopback origin, port, root path, and single matching state
122before forwarding once to the owned listener. It does not probe the listener or follow
123redirects. Google's process owns PKCE, token exchange, refresh, and storage. Callback HTTP
124success is not authentication success. The controller waits for authenticated session setup
125and catalog discovery. Cancellation closes the process instead of sending a synthetic denial.
126
127Auth RPCs `provider.auth.start`, `complete`, `cancel`, `logout`, and `subscribe` require
128`orchestration:operate`. Install `start`, `cancel`, and `remove` use that scope too.
129`provider.install.subscribe` and public provider snapshots require `orchestration:read`.
130[`providerSetup.ts`][provider-setup] defines the operation IDs, states, and safe errors.
131
132Sign-out closes process admission for the instance, stops provider bindings through
133[`ProviderAuthService`][provider-auth-service], then stops owned startup and helper processes.
134A fresh official process calls `initialize` and native `logout` without authenticating.
135Only then does the provider clear auth, models, commands, skills, and workspace metadata.
136Thread history and native session files remain. Settings sign-out and a text-only `/logout`
137use this same path. The command is handled before model prompting or title generation.
138Disabling an instance closes its processes but keeps credentials. Account replacement is
139explicit sign-out followed by sign-in.
140
141### Sessions, models, and client capabilities
142
143[`AntigravityAdapter`][antigravity-adapter] owns one ACP process per active thread. It uses
144native `session/resume` without transcript replay and reapplies the persisted model and
145permission mode after new or resumed setup. An unavailable explicit model fails instead of
146accepting the native default. Steering cancels the previous prompt, waits for its result and
147event drain, then sends the replacement. Native background commands use T3's existing
148background-task state.
149
150The permission mapping is `approval-required` and `auto` to `default`, `auto-accept-edits` to
151`auto_edit`, and `full-access` to `yolo`. Native requests still need replies in `yolo`.
152`interaction_` requests are user questions, not approvals. T3 keeps opaque option IDs in
153`UserInputQuestion.options[].value` and sets `allowCustomAnswer=false`. Both clients preserve
154these values. Ordinary approval replies use only offered option IDs, including `allow_always`
155only when present. Existing providers keep their prior behavior when the optional fields are
156absent.
157
158`showInteractionModeToggle=false` keeps native `/plan` separate from T3 Plan mode.
159`supportsConversationRollback=false` hides unsupported client actions and makes checkpoint
160revert fail before filesystem changes. Checkpoint capture and diffs remain supported.
161
162Automatic status refreshes, reconnects, and workspace checks do not open catalog sessions.
163Health probes use `initialize` only. Disabled instances do not run background probes.
164An explicit `serverRefreshProviders` request with `refreshModels: true` calls the driver's
165optional `refreshModels` operation. Antigravity opens a short-lived catalog session under the
166instance's process admission guard, uses saved credentials, publishes models and commands,
167then closes the process. An interactive login request fails with sign-in required. Web's
168**Refresh provider status** and mobile's **Refresh models** actions request this operation.
169Account access starts unknown and becomes authenticated after successful session setup,
170including an explicit model refresh.
171The [provider snapshot][antigravity-provider] takes models and commands from setup and native
172updates. It preserves returned Gemini model IDs, labels, order, and thinking-level choices.
173ACP `config_option_update` notifications and `session/set_config_option` responses replace
174the instance's model catalog. Child session notifications do not change the root catalog.
175The registry treats a successful empty catalog as authoritative and clears cached metadata
176after sign-out. It must not retain a previous account's models. Cached models do not prove
177current access. The auth response does not supply an email, plan tier, or reliable quota.
178
179Some upstream failures arrive as assistant text followed by `end_turn`. Preserve that message
180without treating model-written text as a structured error or successful task completion.
181
182### Text generation
183
184[`AntigravityTextGeneration`][antigravity-text] implements titles, branch names, commit text,
185and PR text through the same instance and Google sign-in. Each helper uses a temporary empty
186workspace, no injected MCP servers, native `default` mode, and explicit denial of tools and
187questions. Output is bounded, parsed against the existing schemas, and sanitized. Cancellation,
188timeout, and sign-out close the process. Cleanup removes only that helper's verified temporary
189native session files.
190
191The official agent has no verified hard no-tools setting. Global hooks and MCP configuration
192can run before a prompt. Helpers check the profile's `config/hooks.json` and
193`config/mcp_config.json` before launch and reject nonempty, malformed, or oversized
194configuration. `supportsTextGeneration=false` keeps such an instance out of system-model
195pickers. Empty managed profiles are supported. Do not describe prompt-time denial as a native
196sandbox.
197
198## OpenCode server ownership and catalog
199
200Each OpenCode provider instance owns one lazy local server for catalog discovery and
201text-generation helpers through [`OpenCodeServerOwner.ts`][opencode-server-owner]. Concurrent
202borrowers share startup. The server closes 30 seconds after the last borrower releases it, or
203when the provider instance closes. A failed or exited process can be started again on the next
204use. An externally configured OpenCode server remains externally owned.
205
206The local server and its SDK clients use one resolved password. An explicit provider password
207overrides `OPENCODE_SERVER_PASSWORD` in the spawned environment. Without an explicit password,
208the client uses the password from the environment that the process inherits. External servers use
209only their explicit provider password and never inherit the host's local password.
210
211Every server connection must pass the authenticated `/global/health` check before inventory or
212session operations start. The response must contain a valid version at or above 1.14.19. Local
213owners cache this result for the lifetime of the spawned process. External actions check once when
214they create their server connection, not for each model or SDK request.
215
216Chat adapters keep their own server per thread. They register a thread-specific `t3-code` MCP
217connection, while OpenCode stores MCP connections by directory. Sharing these chat servers
218without changing MCP routing would let two threads in one directory replace each other's
219connection.
220
221Chat adapters send the runtime mode as a session ruleset, but upstream OpenCode evaluates
222doom-loop and subagent asks against the agent ruleset only. In full access the adapter answers
223those asks itself so the user never sees an approval they already granted. It replies `once`
224rather than `always` because OpenCode stores `always` grants per directory, and on a shared
225external server that would widen what a supervised thread in the same directory may do.
226
227OpenCode loads its catalog through the HTTP API when an enabled provider instance starts. The
228provider registry keeps the snapshot in memory and persists it in the existing per-instance cache.
229Each `subscribeServerConfig` connection refreshes all providers, so a client reconnect reloads the
230OpenCode catalog from the current helper. The `serverRefreshProviders` request also refreshes it.
231Periodic OpenCode probes remain disabled. OpenCode reads credentials for each inventory request,
232but its native configuration files can remain cached for the lifetime of the helper process. The
233helper closes 30 seconds after its last inventory or text-generation borrower releases it. A
234refresh after that idle period starts a new helper and reads file changes. Repeated refreshes and
235active text-generation work can extend process reuse. Changes to the provider configuration or
236environment replace the instance and start a new discovery. Changes to unrelated settings only
237update snapshot enrichment. Other providers retain their existing refresh policy.
238
239T3 Code does not own an external OpenCode process. Native configuration changes there can require
240an external reload or restart before T3 Code's next refresh sees them.
241
242The shared server's idle shutdown does not clear the catalog. Failed discovery keeps the last
243known models, slash commands, and skills through the registry's existing merge rules. A successful
244empty inventory is authoritative. Existing threads keep their explicit model identifier and
245options when catalog metadata is missing; the catalog is not permission to choose a different
246model for a thread.
247
248## Model manifest
249
250The model picker's legacy section is driven by `apps/server/src/provider/model-manifest.json`, which
251lists the current (non-legacy) model slugs per driver kind. The `ModelManifest` service
252(`apps/server/src/provider/ModelManifest.ts`) refreshes that data from the same file on `main` via
253raw.githubusercontent.com, so moving a model in or out of the legacy section is a commit, not a
254release. Preference order is remote fetch, then the on-disk copy of the last successful fetch (in
255the state directory), then the bundled copy. Fetches are TTL-gated, run concurrently with provider
256probes, respect the `enableProviderUpdateChecks` setting, and never fail a provider check. The
257Codex and Claude drivers apply the classification to every snapshot with `applyModelManifest`;
258driver kinds absent from the manifest have no legacy concept.
259
260## Attachment access
261
262The server stores uploaded attachments in its attachment directory, outside the project workspace.
263`ProviderService` adds the absolute path of each attachment to the turn text, then passes every
264attachment to the provider adapter. Each adapter decides what its provider ingests natively:
265
266- Codex, Claude, Cursor, and Grok send images as native image inputs and skip generic files. For
267 these providers, generic files reach the agent only as file paths in the turn text.
268- Antigravity sends BMP, JPEG, PNG, and WebP images and common audio formats as native blocks,
269 text files as embedded resources, and PDFs as resource links. Other files are rejected with an
270 error instead of being dropped. The session advertises the ACP client file system capability,
271 so workspace reads and writes come back through `fs/read_text_file` and `fs/write_text_file`
272 and are confined to the workspace and the attachments directory.
273- OpenCode sends PNG/JPEG/GIF/WebP images, text files, and PDFs up to 20 MB as native file parts
274 with their real mime type. Everything else (ZIP and other binaries, image formats model APIs
275 reject, oversized files) falls back to the file path in the turn text, like the other providers.
276- Antigravity sends BMP/JPEG/PNG/WebP images as native image blocks, UTF-8 text as embedded
277 resources, and PDFs as local resource links. Text is limited to 1 MiB per file, images to
278 10 MiB each, and all attachments to 50 MiB per turn. Unsupported formats or oversized inputs
279 fail explicitly. Native path permissions still apply to PDFs.
280
281Claude receives the attachment directory as an allowed additional directory. Codex keeps its
282configured sandbox policy, so access depends on that policy and the selected runtime mode. OpenCode
283allows all paths in full-access mode and requests approval for directories outside the workspace in
284restricted modes. Cursor and Grok use their own provider permission rules.
285
286The server does not copy attachments into a project or bypass provider approval rules. If an agent
287cannot read an attachment, the user must approve the access or select a runtime mode that permits it.
288
289Updated attachment schemas tolerate unknown attachment members, but old image-only clients still
290cannot decode messages that contain file attachments. Client file-picking rollouts must account for
291this limit.
292
293Do not run an old image-only server against state that contains file attachments. Replay decodes
294each persisted event before projection. A file-bearing event can make `ProjectionPipeline` bootstrap
295and `OrchestrationEngine` startup fail for the entire environment, not only the affected thread.
296
297## How provider work is requested
298
299Clients never call a provider directly. They dispatch orchestration commands over the RPC method
300`orchestration.dispatchCommand`, defined with the rest of the orchestration surface in
301[`orchestration.ts`][contracts]. The client-dispatchable provider-facing commands are
302`thread.turn.start`, `thread.turn.interrupt`, `thread.approval.respond`,
303`thread.user-input.respond`, `thread.checkpoint.revert`, and `thread.session.stop`, plus the mode
304setters `thread.runtime-mode.set` and `thread.interaction-mode.set`.
305
306The engine persists an event for the command, and a server-side reactor performs the provider call.
307Provider output comes back as internal commands such as `thread.message.assistant.delta` and
308`thread.session.set`, which clients observe through `orchestration.subscribeThread`. See
309[overview.md](./overview.md) for the command/event loop.
310
311## Server-side workers
312
313Provider work flows through three queue-backed workers. All three are built with
314`makeDrainableWorker` from [`DrainableWorker.ts`][worker] and expose `drain` for deterministic test
315synchronization.
316
3171. [`ProviderRuntimeIngestion`][ingest] consumes provider runtime streams and emits orchestration
318 commands.
3192. [`ProviderCommandReactor`][cmd] reacts to orchestration intent events and dispatches provider
320 calls.
3213. [`CheckpointReactor`][checkpoint] captures workspace checkpoints on turn start and completion, and
322 performs reverts.
323
324### Buffered assistant delivery
325
326A thread in `buffered` assistant delivery mode accumulates assistant text instead of streaming each
327delta. The buffer is not held until turn completion. In [`ProviderRuntimeIngestion`][ingest],
328`MAX_BUFFERED_ASSISTANT_CHARS` is 24,000: the append that would exceed it invalidates the buffer and
329spills the whole accumulated text as one delta. The buffer also flushes at interaction boundaries,
330when a request opens (approval) or user input is requested, via
331`flushBufferedAssistantMessagesForTurn`.
332
333[drivers]: ../../apps/server/src/provider/builtInDrivers.ts
334[codex]: ../../apps/server/src/provider/Drivers/CodexDriver.ts
335[claude]: ../../apps/server/src/provider/Drivers/ClaudeDriver.ts
336[cursor]: ../../apps/server/src/provider/Drivers/CursorDriver.ts
337[grok]: ../../apps/server/src/provider/Drivers/GrokDriver.ts
338[opencode]: ../../apps/server/src/provider/Drivers/OpenCodeDriver.ts
339[antigravity]: ../../apps/server/src/provider/Drivers/AntigravityDriver.ts
340[antigravity-adapter]: ../../apps/server/src/provider/Layers/AntigravityAdapter.ts
341[antigravity-provider]: ../../apps/server/src/provider/Layers/AntigravityProvider.ts
342[antigravity-installation]: ../../apps/server/src/provider/AntigravityInstallation.ts
343[antigravity-release]: ../../apps/server/src/provider/antigravityRelease.ts
344[antigravity-auth]: ../../apps/server/src/provider/AntigravityAuth.ts
345[antigravity-auth-support]: ../../apps/server/src/provider/antigravityAuthSupport.ts
346[antigravity-text]: ../../apps/server/src/textGeneration/AntigravityTextGeneration.ts
347[provider-auth-service]: ../../apps/server/src/provider/Layers/ProviderAuthService.ts
348[provider-setup]: ../../packages/contracts/src/providerSetup.ts
349[opencode-server-owner]: ../../apps/server/src/provider/OpenCodeServerOwner.ts
350[adapter]: ../../apps/server/src/provider/Services/ProviderAdapter.ts
351[instances]: ../../apps/server/src/provider/Services/ProviderInstanceRegistry.ts
352[registry]: ../../apps/server/src/provider/Services/ProviderAdapterRegistry.ts
353[service]: ../../apps/server/src/provider/Layers/ProviderService.ts
354[contracts]: ../../packages/contracts/src/orchestration.ts
355[worker]: ../../packages/shared/src/DrainableWorker.ts
356[ingest]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
357[cmd]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
358[checkpoint]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts