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