Skip to content

Provider Authoring

How to add a new AgentProvider adapter (Gemini, …) and prove it's done: implement the seam, then pass the two-tier conformance bar (issue #80 / ADR-0036). Two adapters ship today — claude-code and codex (internal/provider/claudecode/, internal/provider/codex/) — and both are working reference implementations of everything below.

Hard requirements — no escape hatch

  • A durable, locatable transcript. LocateTranscript must find a real file — verified available for Codex's rollout JSONLs and Gemini CLI's session recording. An adapter may not ship without one.
  • The lab-owned .local context-file name. SeedMeta.ContextFileName is a bare .local-suffixed name, never a repo-tracked one (issue #79 / ADR-0035). Making the CLI actually read it is the adapter's own SeedWorkspace job, live-verified — never solved by declaring a tracked name.
  • Live verification before merge. Tier 2 below is required, not optional, even though it never runs in CI.
  • Core stays adapter-agnostic. No provider names or markers outside the adapter package — enforced by internal/provider/neutrality_test.go and web/src/providerNeutral.test.ts.

Author path

  1. Implement the seam in internal/provider/<id>/ — the full AgentProvider interface (internal/provider/provider.go).
  2. Declare SeedMeta(): context-file name (.local-suffixed), skills dir, exclude entries, and ScrubPatterns/SeededPathPatterns in the BRE∩RE2 common dialect (issue #75 / ADR-0033).
  3. Wire host config from the generic -provider-bin/-provider-config maps, with the adapter owning its own defaults (issue #78 / ADR-0034) — no provider-named field goes into internal/config.
  4. Add the one entry to the registration table in internal/provider/conformance_test.go (TestConformance, package provider_test), constructing the adapter hermetically (temp dirs, a fake runner) with its providertest.Fixture. Get Tier 1 green.
  5. Run the Tier-2 live spikes below on a host with the real CLI (spikes 1–4 always; spike 5 where the adapter implements the override).
  6. Commit the compat record at internal/compat/<providerID>/compat.md.
  7. Verify core neutrality: internal/provider/neutrality_test.go and web/src/providerNeutral.test.ts must both stay clean.
  8. Register the provider in cmd/lab/main.go.

Definition of done: Tier 1 green in CI, Tier 2 evidenced in the committed compat record (ADR-0036). Both shipped adapters passed this bar; internal/compat/codex/compat.md (issue #2 / ADR-0037) is the reference example of a compat record.

Beyond the required interface there are optional capability interfaces (internal/provider/provider.go): AuthPeeker, ConnectingReporter, DeepLinker, LiveSignals, LoginCodeReporter, RemoteCapable. Implement one only when the CLI genuinely supports the behavior — core detects each by type assertion and degrades gracefully when absent (ADR-0017).

AuthPeeker (LastAuthStatus(), issue #61 / ADR-0073). It feeds the agent-login line of a repo's readiness report, which is read with every repo list and every repo home and must start nothing. AuthStatus may run the CLI's status command — a process, and on a container-mode server a podman container (ADR-0057) — so readiness never calls it. LastAuthStatus returns the status the adapter's most recent completed AuthStatus check produced, whatever its age, with true; or the zero status with false when no check has completed since the process started. A check that failed (the status command missing, its output unreadable) or was cut off by its caller's context is not completed and never moves the peek: the logged-out stand-in AuthStatus returns for it is a spawn-safety default, not evidence of a logout, and publishing it would turn every repo's agent check red. The rule: it never runs the CLI, never touches the network or the filesystem, never refreshes the cache, and never blocks behind a check in flight — it reports the previous result until that check lands, and CheckedAt says how old it is. Both shipped adapters implement it the same way: the refresh path stores the status of each completed check (no error, the caller's context still live) into an atomic.Pointer[provider.AuthStatus] while it holds the auth mutex, and LastAuthStatus loads that pointer without taking the mutex, because the mutex is held for the whole status command. The providertest fake mirrors that: it reports the status its last AuthStatus call returned, not its live scripted state, and the peek is not counted as a check. Without the capability, the agent-login check is simply left out of the report.

Conversational state (ReadChat, LiveSignals, Chat.StateDetail, ADR-0038 / ADR-0078). The adapter owns "what state is my agent in"; core only forwards it and applies the ended-run override. ReadChat receives a provider.ReadSpec: besides RunID, RuntimeDir and TranscriptPath, it carries Home (the run's private instance HOME) and Worktree (the run's worktree path, the one cwd unique to the session). Core fills RuntimeDir and Home only for an active run and leaves both "" for an ended one, so a terminal read never consults live signals. Both are opaque locations: use them to read whatever state your CLI keeps itself, and ignore them if it keeps none (codex). Claude Code composes its state from the CLI's own session-registry status (under Home, matched by Worktree) layered over the transcript fold; that precedence is the worked example (internal/provider/claudecode/chat.go, ADR-0078). Rules for an adapter that does this:

  • Prefer the CLI's own status over a guess from the transcript tail, and never map an "idle" status straight to needs-input: idle cannot tell a turn that just ended from a fresh session, so let the transcript decide that case.
  • An unusable status (entry missing, empty or unknown value) must fall back to the transcript alone, never to an error.
  • Set Chat.StateDetail to the CLI's human reason when it gives one (Claude: waitingFor, "permission prompt"). It is free text for display, forwarded verbatim to the status line, state dot and needs-input push; core never branches on it, so State stays the contract.
  • If LocateTranscript can name a new conversation before its file exists (Claude after /clear), an active read of that missing file must be an idle empty chat, not ErrTranscriptGone; an ended read of a missing file is still ErrTranscriptGone.
  • LiveSignals.SpoolSig(runID, dir, home) is the cheap change digest the tailer compares so it republishes while the transcript is byte-frozen. Digest everything ReadChat reads outside the transcript, the spool under dir and the state registry under home; an empty dir or home skips that half.
  • LiveSignals.Setup arms only what you need for dialog capture. Claude's per-run settings file carries the PreToolUse/PostToolUse dialog hooks and env and nothing else; there is no Notification hook, because its idle_prompt fires after every turn even while background agents run.

Transcript retention (RetainTranscript, issue #81). Every teardown wipes the run's private HOME, and your transcript lives in it. Just before the wipe, core calls RetainTranscript(ctx, worktree, home, transcriptPath, destDir) with the run's stored transcript path and an empty, core-created destDir (<state>/transcripts/<runID>/). Move into destDir whatever an ended ReadChat needs, and return the path core should store; core later reads it with an ended spec (no Home, no RuntimeDir). For a single-file transcript the whole implementation is one call:

func (p *Provider) RetainTranscript(ctx context.Context, _, home, transcriptPath, destDir string) (string, error) {
    if err := ctx.Err(); err != nil {
        return "", err
    }
    return provider.RetainFile(home, transcriptPath, destDir, p.rename) // p.rename nil → os.Rename
}

provider.RetainFile renames on the same filesystem and copies (0600, fsynced, then removes the source) on a cross-device EXDEV. It returns ("", nil) for an empty or missing source and refuses anything outside home (including through a symlinked parent), any symlink or non-regular file, and any existing destination. Keep the file byte-for-byte: no rewriting, no lab-owned format (ADR-0016). Only the current transcript is retained; earlier /clear segments are not. Never touch destDir's siblings. If your ReadChat also reads files beside the transcript, move those too. Claude Code's ReadChat doesn't, so it leaves its <sessionId>/ sidecar dir behind; Codex moves its rollout without the date dirs. Keep the rename function in an unexported field so your tests can return an EXDEV *os.LinkError and exercise the copy path.

"Chat about this" (DialogAnswer.Chat / QuestionAnswer.Chat, issue #58). AnswerDialog carries one more answer shape: the operator chose to talk about a question instead of answering it. It carries no text. The agent is expected to ask what the operator wants to know, and the operator answers through Reply once the dialog is gone. On a single-question dialog Chat is set on the DialogAnswer and every answer field is empty. On a multi-question dialog Answers holds the operator's answers to the questions before the chat, in order, and ends with one entry whose Chat is set. An adapter with answerable question dialogs must reproduce exactly that path on its own dialog — enter the earlier answers as given, then make the "chat about this" choice on the question it was made on — inside the one AnswerDialog call, so the caller's per-session lock covers it. Validate before any key plays: a non-question dialog is ErrDialogNotAnswerable; a chat entry combined with an option, followed by another entry, or preceded by an invalid answer is ErrInvalidReply. Render a dialog set aside this way through its dismissed outcome, never as a mismatch — but if the adapter drives the dialog blind, do flag a recorded answer the operator never gave. An adapter without answerable dialogs (codex today) simply keeps returning ErrDialogNotAnswerable — the UI offers the action only on an answerable question dialog, so it never appears there. Claude Code's implementation and its live-verification status are in internal/compat/compat.md §7 ("Chat about this").

Tier 1 — the conformance suite (CI, every adapter)

Entry point: providertest.Conformance(t *testing.T, p provider.AgentProvider, fx providertest.Fixture) (internal/provider/providertest/conformance.go). Fixture.AttributionSamples (required, ≥1) are real single-line marker strings the CLI writes into commits/PRs — your adapter's ground-truth test vectors; Fixture.CleanSamples (optional) must NOT match, guarding against an over-broad pattern. Fixture.SeedTranscript (required, issue #81) writes one minimal native session for a worktree under a given HOME (plus whatever registry your LocateTranscript keys on), so that the locate hits and an ended ReadChat yields at least one message. The suite drives the retain round-trip through it and never learns your layout.

Subtests assert:

  • patterns-dialect — ScrubPatterns/SeededPathPatterns compile via provider.CompileScrubPatterns (issue #75 / ADR-0033); ScrubPatterns non-empty.
  • context-file-lab-owned — ContextFileName is a bare .local-suffixed name (issue #79 / ADR-0035).
  • seedmeta-clone — SeedMeta/Models/Efforts/SpawnOptions return defensively-cloned slices.
  • catalogs — model/effort catalogs are non-empty with unique non-empty values; spawn-option specs are typed with valid defaults.
  • spawn-argv — argv(prompt) == argv(no prompt) + [prompt]; every declared spawn option round-trips.
  • spawn-remote — a RemoteCapable adapter's argv differs between remote on/off exactly as its interface declares; a non-RemoteCapable adapter produces an IDENTICAL argv for both values (no undeclared coupling).
  • auth-flow — AuthFlow().Kind is a recognized AuthFlow* constant.
  • login-session — the id charset and tmuxx.IsLoginSession(tmuxx.LoginSessionName(ID())) hold (issue #77 / ADR-0034).
  • read-chat — ReadChat on a fresh spawn (empty transcript path, runtime dir absent or empty) yields an idle read, never an error; a transcript path that no longer exists, read as an ended run (no runtime dir, no home), surfaces provider.ErrTranscriptGone, not a raw error. An active read of a missing file is not pinned.
  • locate-homeless — LocateTranscript with no per-run instance HOME is a miss ("", nil) — never an error, never a fall back to the machine's master store (issue #202).
  • retain-transcript — the round-trip: seed via Fixture.SeedTranscript, then locate, read as an ended run, RetainTranscript into an empty destDir, RemoveAll the HOME, and read the retained path as an ended run. That read must return the same messages and cursor as the first one, and the retained path must lie under destDir. A sibling of destDir stays untouched. An empty or vanished transcript path returns ("", nil) and leaves destDir empty (issue #81).
  • inject-credentials — with no master credential present, InjectCredentials returns nil and writes nothing to the master store; the injector only ever copies FROM the master, never into it.
  • credential-authority — the credential-authority obligations (CredentialsSig, AdoptCredentials, …; internal/provider/provider.go) hold against a genuinely absent master store. RefreshCredentials shells out to the live CLI, so it's pinned in adapter-side unit tests, not here. So is the logged-out rule (issue #101): a credential file that exists but holds no usable tokens — unparseable, or with its tokens emptied the way claude clears them after a failed refresh — must read as "" from CredentialsSig and be refused by AdoptCredentials with an error wrapping provider.ErrCredentialsLoggedOut, both decided by one shared adapter-side check. Otherwise lab adopts a dead file into the master store and fans it out to every live run.
  • master-store-spec — MasterStoreSpec returns a non-empty absolute HostDir, resolved freshly per call and honoring its declared EnvVar override (issue #211).
  • seeding-exclude-coverage — in a real temp linked worktree, the provider's SeedWorkspace plus the real internal/seeder run, in production order, leave git status --porcelain empty; the context file/skills dir exist; every seeded path matches a SeededPathPattern.
  • seeding-incogni — same, with SeedOpts{Incogni: true}: no tracked-file writes.
  • seed-home-containment — seeding against a temp instance Home leaves the machine's master store untouched: HOME-global trust grants (claude's ~/.claude.json, codex's config.toml + AGENTS.md) land under the run's private Home.
  • scrub-markers — every AttributionSample is stripped by the adapter's own ScrubPatterns through both real engines (RE2 via provider.CompileScrubPatterns, POSIX BRE via a real grep -i, skipped when absent) and by provider.NewRegistry(p).ScrubRegexps() — the union path the agent-API sanitizer actually runs (ADR-0033).

A deliberately-broken fake adapter lives in the suite's own tests; failures name the obligation they broke.

Tier 2 — live spikes (required, documented, not CI-run)

Held to the ADR-0008 live-verification bar: real CLI, real host, no credentials in CI. Evidenced by the committed compat record, not by a test that runs on every push.

  1. transcript — locate by cwd, read/map to the universal schema, confirm a NEW transcript identity on context clear (native rotation or a synthesized epoch — see LocateTranscript's doc); and confirm when the transcript is born — at session init, or lazily at the first turn (an idle interactive session may then have no transcript file at all, so nothing may gate first-message delivery on its existence — codex 0.133.0 is the precedent, issue #96).
  2. reply / dialog-answer / interrupt — hazard-check the send-keys recipes against the real TUI; double-Esc/Ctrl-C must never be able to kill the session.
  3. context-file discovery — prove the CLI actually READS the lab-owned context file (e.g. Codex ↔ AGENTS.local.md via project config).
  4. incogni attribution ground truth — capture what the CLI actually writes into commits/PRs and reconcile it against the adapter's ScrubPatterns; these live samples become Fixture.AttributionSamples.
  5. dialog auto-dismiss defeat — conditional: only for adapters that override their CLI's unattended dialog timeout (claude: CLAUDE_AFK_TIMEOUT_MS via the per-run settings env block, compat §11; codex has no equivalent knob today). Live-verify the override actually reaches the dialog timer — a small value self-resolves an undriven dialog early — AND that the effectively-never max holds: the dialog survives well past the CLI's default, with no immediate-fire hazard at the cap.

Compat record convention

Follow claude-code's worked example, internal/compat/compat.md: numbered sections, each carrying a provenance tag (live / fixture / schema extraction); captured fixtures under testdata/ tagged with the CLI version (e.g. -2.1.198); opt-in live tests gated by LAB_COMPAT_LIVE=1 (internal/compat/live_recipes_test.go, no build tags). A new adapter's record lives at internal/compat/<providerID>/compat.md, same shape; claude-code's stays where it is.