Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(pi): add first-class agent provider #5882

ClosedPJalv(GitHub profile, opens in a new tab)wants to merge 20 commits intomain fromrefs/pull/5882/headopened View on GitHub

Note

Draft/reference implementation. Maintainers previously said that new providers are not being accepted right now (context). This draft is not requesting an immediate merge. It keeps a current, Pi-only implementation and its review findings available for when provider additions are reconsidered.

Relates to #402.

What Changed

Adds Pi as a first-class provider through Pi's native JSONL RPC mode and the current T3 provider/orchestration model.

  • Discovers the configured Pi binary and its live model catalog. No fallback model list is hard-coded.
  • Exposes only the reasoning levels reported for the selected Pi model.
  • Starts one scoped Pi process per T3 thread, persists the exact Pi session cursor, and resumes it with containment, header, and symlink validation.
  • Maps assistant text, reasoning, tools, extension input, usage, retries, compaction, steering, subagents, and workflows into existing T3 runtime events.
  • Refreshes Pi's authoritative context usage at native assistant-response boundaries, matching the live mid-turn updates supplied by Codex and Claude without adding a timer or Pi-only UI path.
  • Keeps automatic threshold compaction and native Pi steering inside one T3 turn while preserving separate assistant responses.
  • Uses Pi for commit messages, PR text, branch names, and thread titles through the existing text-generation service.
  • Registers Pi in the existing web, desktop, and mobile provider surfaces. It does not add a Pi-only client flow.

MCP and subagents

Pi core intentionally keeps MCP and subagents in extensions, so the provider supports those modules explicitly instead of pretending they are built in:

  • MCP: the provider detects pi-mcp-adapter, reports an actionable warning when it is missing, classifies proxy and direct calls as MCP activity, and forwards T3's thread-private browser MCP endpoint through a private mode-0600 config. The adapter's --mcp-config path is used when available; older or missing adapters fall back without preventing Pi from starting.
  • Subagents: the adapter projects Pi's current subagent single, parallel, and chained result format into the existing task and Agents-panel lifecycle. It also accepts the older subagent_spawn and workflow formats, including model, token, duration, terminal, stopped, and interrupted states.

The user still installs Pi and the desired Pi extensions. T3 does not rewrite the user's permanent Pi or project MCP configuration.

Why

Pi has had several community implementations and reviews: #2211, #2748, #2800, #2812, #2831, #2856, #3818, #3947, #4355, #4445, #5688, and the broader open harness work in #5505. I reviewed those attempts and their inline findings before preparing this branch.

This version is based on the current post-#2829 orchestration architecture. It incorporates the lifecycle, transport, cleanup, model, extension-input, session-resume, process-exit, and concurrency lessons reported on the earlier RPC implementations. Unlike multi-provider attempts, this is a Pi-only vertical slice.

The branch was rebuilt directly from current main. It intentionally excludes the provider-native file-diff viewer, file-browser work, release changes, branding changes, and all other fork-only features.

UI Changes

There is no new UI system. Pi reuses the existing provider settings, model and reasoning pickers, chat timeline, Work Log, user-input panel, context meter, and Agents panel. Before this change, Pi is not an available provider. After it passes its binary/model probe, it appears in those existing surfaces.

The following automated-test captures are cropped to remove the unrelated thread sidebar and private conversations.

Parallel Pi subagents in the existing Agents panel

Pi subagents in the Agents panel

A steering message handled after the active tool call, with separate assistant responses

Pi steering responses remain separate

Verification

Focused verification on this Pi-only branch:

  • 135 server provider/adapter/RPC/session/text-generation tests passed.
  • 143 focused contracts, web, settings, and client-runtime tests passed.
  • Targeted lint and formatting checks passed without warnings.
  • Server, web, contracts, and mobile package typechecks passed. Server output contains only pre-existing Effect suggestions outside this diff.
  • Server and production web bundles built successfully.
  • The repository's Macroscope correctness and Effect-service convention checks passed on the latest head.
  • A real Pi 0.84.1 process accepted the standard pi-mcp-adapter 2.21.1 --mcp-config path and completed an RPC state request.
  • A live Pi tool-use turn returned get_session_stats.contextUsage before agent_settled, confirming that T3 can refresh the context meter between native response cycles.

The integration was also exercised extensively by human trial and Playwright MCP automation in a packaged T3 build with real Pi sessions. The covered flows include:

  • dynamic model and reasoning selection;
  • durable session resume and current-context usage, including Playwright verification that the context meter updates between tool cycles while the Pi turn is still running;
  • commands, skills, and RPC-safe extension input;
  • injected T3 browser MCP plus proxy and direct MCP calls;
  • single, parallel, chained, background, stopped, and interrupted subagents;
  • workflow and Agents-panel projection, including long lists and scrolling;
  • automatic compaction continuation;
  • normal interruption and process cleanup;
  • mid-run steering while active tool calls continue, with the later Pi response rendered separately.

Current Limits

  • Pi sessions use Full access. This change does not invent approval behavior that Pi does not provide.
  • Pi, pi-mcp-adapter, and a subagent extension remain user-managed dependencies.
  • T3 checkpoint rollback is not exposed for Pi.
  • This PR does not add provider-native file-diff viewing.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • I included cropped UI evidence for the existing surfaces changed by this provider
  • I included a video for animation/interaction changes

The implementation is large because a safe provider must include contracts, process lifecycle, event mapping, clients, tests, and documentation together. It remains one provider concern and does not include unrelated fork work.

Built with GPT-5.6 Sol in Pi.

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 750d5dc7-1f19-4b90-b605-d86487470d11

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    3. Reviewed the new Pi provider modules against the Effect service conventions. Service/layer structure, namespace imports, dependency acquisition from the environment, and Foo["Service"] usage all look correct. Four error-modeling issues are flagged inline: wrapper detail/message derived from cause (or a stringified cause), plain message strings passed as cause, and a required Schema.Defect() cause used to carry offending domain values on pure validation failures.

      Posted via Macroscope — Effect Service Conventions
    4. @@ -0,0 +1819,21 @@
      1819+ });
      1820+ createdTurn = turn;
      1821+ const turnId = turn.id;
      1822+ const prompted = yield* ctx.client.prompt(input.input ?? "", images).pipe(Effect.result);
      1823+ if (Result.isFailure(prompted)) {
      1824+ const reusable = isPiRpcCommandError(prompted.failure);
      1825+ yield* failActive(ctx, "Pi prompt failed.", undefined, !reusable);
      1826+ if (!reusable) yield* close(ctx);
      1827+ return yield* request("prompt", prompted.failure);
      1828+ }
      1829+ if (ctx.closing || ctx.stopped || sessions.get(input.threadId) !== ctx) {
      1830+ return yield* new ProviderAdapterSessionNotFoundError({
      1831+ provider: PROVIDER,
      1832+ threadId: input.threadId,
      1833+ });
      1834+ }
      1835+ if (input.input?.trimStart().startsWith("/")) {
      1836+ const state = yield* ctx.client.getState().pipe(
      1837+ Effect.mapError((cause) => request("get_state", cause)),
      1838+ Effect.option,
      1839+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAdapter.ts:1836

      In sendTurn, when a slash command is sent and the follow-up ctx.client.getState() call fails, the failure is swallowed by Effect.option and treated as Option.none(). The code then skips the publishTerminal call, returns a successful Started result, and leaves ctx.activeTurn in a non-terminal state with ctx.session.status set to running. The session is permanently stuck — every subsequent sendTurn is rejected because ctx.session.status !== "ready". Consider propagating the getState failure (e.g. with Effect.mapError) instead of converting it to Option.none(), so the error surfaces rather than leaving the turn hanging.

                 const state = yield* ctx.client.getState().pipe(
      -            Effect.mapError((cause) => request("get_state", cause)),
      -            Effect.option,
      +            Effect.mapError((cause) => request("get_state", cause)),
                );
      -          if (
      -            Option.isSome(state) &&
      -            state.value.isStreaming !== true &&
      +          if (
      +            state.isStreaming !== true &&
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around lines 1836-1839:
      
      In `sendTurn`, when a slash command is sent and the follow-up `ctx.client.getState()` call fails, the failure is swallowed by `Effect.option` and treated as `Option.none()`. The code then skips the `publishTerminal` call, returns a successful `Started` result, and leaves `ctx.activeTurn` in a non-terminal state with `ctx.session.status` set to `running`. The session is permanently stuck — every subsequent `sendTurn` is rejected because `ctx.session.status !== "ready"`. Consider propagating the `getState` failure (e.g. with `Effect.mapError`) instead of converting it to `Option.none()`, so the error surfaces rather than leaving the turn hanging.
    5. One finding: a TextGenerationError built from a Pi RPC protocol-failure event copies that event's free-form detail text instead of a stable detail plus the event as cause.

      Posted via Macroscope — Effect Service Conventions
    6. Reviewed the new Pi provider/service modules against the Effect service conventions. Previously flagged error-shape issues (PiDriver wrapper details, PiTextGeneration protocol failure, PiSessionFileError cause/detail, requestMessage for validation-only adapter failures) are resolved. One remaining finding on the provider status message.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +112,21 @@
      112+ });
      113+ return yield* Effect.all({
      114+ inventory: client.getAvailableModels(),
      115+ state: client.getState(),
      116+ commands: client.getCommands(),
      117+ });
      118+ }),
      119+ ).pipe(Effect.exit);
      120+ if (discovery._tag === "Failure") {
      121+ const error = Cause.squash(discovery.cause);
      122+ return buildServerProvider({
      123+ presentation: PRESENTATION,
      124+ enabled: true,
      125+ checkedAt,
      126+ models: models(settings),
      127+ probe: {
      128+ installed: !isPiCommandMissingCause(error),
      129+ version: null,
      130+ status: "error",
      131+ auth: { status: "unknown" },
      132+ message: `Pi model discovery failed: ${String(error)}`,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      String(error) stringifies an arbitrary squashed defect (Pi RPC error detail, spawn errors carrying the binary path/args) into a caller-visible provider status message. Sibling providers keep a stable message and log the normalized category instead (CursorProvider.ts:1092, GrokProvider.ts:259). Consider a stable message plus causeErrorTag, keeping the full cause in a log:

      -        message: `Pi model discovery failed: ${String(error)}`,
      +        message: `Pi model discovery failed: ${causeErrorTag(discovery.cause)}`,

      This needs import { causeErrorTag } from "@t3tools/shared/observability";, and Effect.logWarning("Pi model discovery failed", { cause: discovery.cause }) preserves the detail for diagnostics.

      Posted via Macroscope — Effect Service Conventions
    7. @@ -0,0 +1417,21 @@
      1417+ const handleEvent = Effect.fn("PiAdapter.handleEvent")(function* (
      1418+ ctx: SessionContext,
      1419+ native: PiRpcEvent,
      1420+ ) {
      1421+ if ("_tag" in native && native._tag === "PiRpcProtocolFailureEvent") {
      1422+ yield* failActive(ctx, String(native.detail), native);
      1423+ yield* close(ctx);
      1424+ return;
      1425+ }
      1426+ if ("_tag" in native && native._tag === "PiRpcOutputLineEvent") {
      1427+ yield* Effect.logDebug("Ignored non-JSON Pi output").pipe(
      1428+ Effect.annotateLogs({ provider: "pi", output: native.line }),
      1429+ );
      1430+ return;
      1431+ }
      1432+ const event = native as Record<string, unknown>;
      1433+ const type = string(event.type);
      1434+ if (type === "extension_ui_request") {
      1435+ yield* handleExtensionUiRequest(ctx, event);
      1436+ return;
      1437+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiAdapter.ts:1437

      Background subagent and workflow task events that arrive after the originating turn has ended are silently discarded. When handleEvent receives a tool_execution_* event and there is no active turn (ctx.activeTurn is undefined or terminal), line 1448 returns early, so handleSubagentToolEvent, handleExtensionSubagentToolEvent, and handleWorkflowToolEvent never run. Their task entries stay in agentTasksById/workflowTasks/extensionSubagentTasks as perpetually running, and interruptTurn keeps reporting background work that already finished. If a new turn is active when the late result arrives, the event is processed but attributed to the unrelated new turn rather than the originating one. Background task events need linkage to their originating turn instead of requiring ctx.activeTurn.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around line 1437:
      
      Background subagent and workflow task events that arrive after the originating turn has ended are silently discarded. When `handleEvent` receives a `tool_execution_*` event and there is no active turn (`ctx.activeTurn` is `undefined` or terminal), line 1448 returns early, so `handleSubagentToolEvent`, `handleExtensionSubagentToolEvent`, and `handleWorkflowToolEvent` never run. Their task entries stay in `agentTasksById`/`workflowTasks`/`extensionSubagentTasks` as perpetually `running`, and `interruptTurn` keeps reporting background work that already finished. If a new turn is active when the late result arrives, the event is processed but attributed to the unrelated new turn rather than the originating one. Background task events need linkage to their originating turn instead of requiring `ctx.activeTurn`.
      @@ -0,0 +608,21 @@
      608+ ) {
      609+ return yield* Effect.uninterruptible(
      610+ Effect.gen(function* () {
      611+ if (ctx.activeTurn !== expected || expected.terminal) return false;
      612+ expected.terminal = true;
      613+ ctx.activeTurn = undefined;
      614+ yield* Effect.forEach(terminalEvents, offer, { discard: true });
      615+ const { activeTurnId: _, ...session } = ctx.session;
      616+ ctx.session = {
      617+ ...session,
      618+ status,
      619+ ...(status === "ready" ? { resumeCursor: ctx.cursor } : {}),
      620+ ...(errorMessage ? { lastError: errorMessage } : {}),
      621+ updatedAt: yield* now,
      622+ };
      623+ return true;
      624+ }),
      625+ );
      626+ });
      627+
      628+ const close = Effect.fn("PiAdapter.close")(function* (ctx: SessionContext) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiAdapter.ts:628

      When close runs during an active subagent or workflow task, it terminates the Pi process without emitting task.completed events for entries still in agentTasksById, workflowTasks, or extensionSubagentTasks. Consumers see those tasks stuck in the running state permanently because the process can never produce the completion event. The close function should emit terminal task.completed events for all in-flight tasks before shutting down the session.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around line 628:
      
      When `close` runs during an active subagent or workflow task, it terminates the Pi process without emitting `task.completed` events for entries still in `agentTasksById`, `workflowTasks`, or `extensionSubagentTasks`. Consumers see those tasks stuck in the `running` state permanently because the process can never produce the completion event. The `close` function should emit terminal `task.completed` events for all in-flight tasks before shutting down the session.
      @@ -0,0 +2147,21 @@
      2147+ const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
      2148+ threadId,
      2149+ requestId,
      2150+ answers,
      2151+ ) =>
      2152+ Effect.gen(function* () {
      2153+ // Prompt preflight can wait on extension UI while sendTurn owns the
      2154+ // thread lock, so responses must use Pi's own serialized RPC writer.
      2155+ const ctx = yield* requireSession(threadId);
      2156+ const pending = ctx.pendingUserInputs.get(requestId);
      2157+ if (!pending)
      2158+ return yield* requestMessage("extension_ui_response", "Unknown Pi input request.");
      2159+ const rawAnswer = answers[pending.questionId];
      2160+ const answer = (Array.isArray(rawAnswer) ? rawAnswer[0] : rawAnswer)?.trim();
      2161+ if (!answer) return yield* validation("respondToUserInput", "Pi requires an answer.");
      2162+ const response =
      2163+ pending.method === "confirm"
      2164+ ? {
      2165+ confirmed: ["yes", "true", "confirm", "confirmed"].includes(answer.toLowerCase()),
      2166+ }
      2167+ : { value: answer };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiAdapter.ts:2159

      respondToUserInput trims the user's answer and sends the trimmed value to Pi, so for editor and input requests leading/trailing whitespace and final newlines are silently stripped. The extension receives content different from what the user submitted — for example, an indented code fragment loses its indentation. Trimming should only be used to check the answer is non-empty; the original untrimmed value should be preserved for non-confirm responses.

      -      const rawAnswer = answers[pending.questionId];
      -      const answer = (Array.isArray(rawAnswer) ? rawAnswer[0] : rawAnswer)?.trim();
      -      if (!answer) return yield* validation("respondToUserInput", "Pi requires an answer.");
      -      const response =
      -        pending.method === "confirm"
      -          ? {
      -              confirmed: ["yes", "true", "confirm", "confirmed"].includes(answer.toLowerCase()),
      -            }
      -          : { value: answer };
      +      const rawAnswer = answers[pending.questionId];
      +      const rawValue = Array.isArray(rawAnswer) ? rawAnswer[0] : rawAnswer;
      +      if (!rawValue?.trim()) return yield* validation("respondToUserInput", "Pi requires an answer.");
      +      const response =
      +        pending.method === "confirm"
      +          ? {
      +              confirmed: ["yes", "true", "confirm", "confirmed"].includes(rawValue.trim().toLowerCase()),
      +            }
      +          : { value: rawValue };
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around lines 2159-2167:
      
      `respondToUserInput` trims the user's answer and sends the trimmed value to Pi, so for `editor` and `input` requests leading/trailing whitespace and final newlines are silently stripped. The extension receives content different from what the user submitted — for example, an indented code fragment loses its indentation. Trimming should only be used to check the answer is non-empty; the original untrimmed value should be preserved for non-confirm responses.
    8. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Closing this PR after an automated pass over open pull requests. The author says maintainers are not accepting providers and the draft does not request a merge.

Sign in to join this conversation.