Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(pi): add first-class Pi provider support #5688

Closeddarjss(GitHub profile, opens in a new tab)wants to merge 8 commits intomain fromrefs/pull/5688/headopened View on GitHub

Closes #402.

What Changed

Adds Pi as a first-class provider through Pi's RPC mode. T3 now discovers the installed Pi binary and its real models, starts and resumes Pi session files, maps Pi output and tools into the existing provider event model, and exposes Pi on web, desktop, and mobile.

The provider also reads Pi's command and skill catalog, bridges RPC-safe extension questions into T3's user-input panel, and projects Pi subagents and workflows into the existing Agents panel. Pi keeps ownership of its models, accounts, tools, extensions, skills, config, and session files.

This does not add an Executor or MCP path.

Why

#402 asks for a provider that fits T3's current provider and orchestration layers without a Pi-only client flow. This implementation keeps the process and protocol details at the Pi adapter boundary and reuses the current model picker, composer, task lifecycle, Agents panel, and provider settings.

The full vertical slice is large because a provider needs contracts, health checks, model discovery, session lifecycle, event mapping, clients, and tests to work safely. Splitting those pieces would leave branches that register a provider which cannot complete a turn.

UI Changes

No new UI system or provider-only screen was added. Pi uses the current provider picker, model and reasoning controls, composer command and skill menus, user-input panel, and Agents panel. Before this change Pi is absent from those existing surfaces; after it is shown when its configured binary passes the health check.

Verification

  • 65 focused Pi provider tests pass
  • Server, contracts, web, and mobile typechecks pass
  • Tested against Pi 0.84.0 in the real web app:
    • dynamic model and reasoning selection
    • / extension commands and $ skills
    • extension Ask User request and response
    • extension slash-command settlement
    • background subagent completion and parent follow-up
    • workflow phase, model, token, and duration data in the Agents panel

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • I included before/after screenshots for any UI changes
  • I included a video for animation/interaction changes

Built with GPT-5.4 in Pi.


Note

Medium Risk Large new provider path with child-process RPC, durable session files, and complex turn/settlement concurrency; mistakes could break threads or leak sessions, but it does not change auth or billing.

Overview Pi is registered as a built-in provider driver that spawns the Pi CLI in RPC mode, probes models/commands/skills for snapshots, and wires adapter + text generation like other agents.

The Pi adapter owns durable session files (allocate, resume cursor validation, per-file leasing), full-access-only threads, and maps Pi RPC stream events into T3 turns, tool items (bash/edit/agents), user-input for extension UI, and task lifecycle for subagents and workflows—including steer prompts, settlement on agent_settled, and interrupt/close edge cases.

Supporting pieces include an NDJSON RPC client, URL-encoded model slugs with thinking-level options, PiTextGeneration for commit/PR/branch/title helpers, plus a Pi icon and "Pi" display label on mobile.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f3eb5d0f6779059aa463ee5e7b54439f7eea4aa2. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add first-class Pi provider support with RPC client, session management, and text generation

  • Introduces PiDriver, PiAdapter, and makePiTextGeneration to register Pi as a full built-in provider with adapter, text generation, and managed snapshot capabilities.
  • Adds makePiRpcTransport and makePiRpcClient in PiRpcClient.ts for NDJSON-framed RPC communication with the Pi binary, including request correlation, timeouts, and graceful shutdown.
  • Implements PiSessionFile utilities for secure per-instance session file allocation with strict containment, permission, and symlink validation.
  • Adds checkPiProviderStatus in PiProvider.ts to probe the Pi binary, discover models and commands, and build provider snapshots distinguishing missing-binary from other errors.
  • Exposes Pi in server settings (PiSettings/PiSettingsPatch), the session provider picker (marked 'new'), and web/mobile UI with the Pi icon and display label.
📊 Macroscope summarized f3eb5d0. 20 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. 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: b93860e5-8e64-450a-b144-7bc340d6f1c7

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. Reviewed the new Pi provider modules (PiDriver, PiAdapter, PiProvider, PiRpcClient, PiSessionFile, PiTextGeneration) against the Effect service conventions. Dependency acquisition, namespace imports, and layer/factory shapes look consistent with the existing provider modules. Three error-modeling/handling violations are noted inline.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +194,21 @@
      194+ }).pipe(
      195+ Effect.mapError((cause) =>
      196+ isTextGenerationError(cause)
      197+ ? cause
      198+ : new TextGenerationError({
      199+ operation: input.operation,
      200+ detail: "Pi text generation failed.",
      201+ cause,
      202+ }),
      203+ ),
      204+ ),
      205+ ).pipe(
      206+ Effect.timeout(Duration.millis(options.timeoutMs ?? PI_TEXT_GENERATION_TIMEOUT_MS)),
      207+ Effect.catchTag(
      208+ "TimeoutError",
      209+ () =>
      210+ new TextGenerationError({
      211+ operation: input.operation,
      212+ detail: "Pi text generation timed out.",
      213+ }),
      214+ ),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Statically known tagged failures should be recovered with Effect.catchTags({ ... }), including when only one tag is handled; Effect.catchTag is not used by this convention.

      Suggested change
      207- Effect.catchTag(
      208- "TimeoutError",
      209- () =>
      210- new TextGenerationError({
      211- operation: input.operation,
      212- detail: "Pi text generation timed out.",
      213- }),
      214- ),
      207+ Effect.catchTags({
      208+ TimeoutError: () =>
      209+ new TextGenerationError({
      210+ operation: input.operation,
      211+ detail: "Pi text generation timed out.",
      212+ }),
      213+ }),
      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +80,21 @@
      80+ Effect.scoped(
      81+ Effect.gen(function* () {
      82+ const selected = decodePiModelSlug(input.modelSelection.model);
      83+ if (!selected)
      84+ return yield* new TextGenerationError({
      85+ operation: input.operation,
      86+ detail: "Pi model selection must use the 'provider/model' format.",
      87+ });
      88+ const client = yield* makeRpcClient({
      89+ command: settings.binaryPath,
      90+ args: DETERMINISTIC_ARGS,
      91+ cwd: input.cwd,
      92+ env: environment,
      93+ }).pipe(
      94+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
      95+ Effect.mapError(
      96+ (cause) =>
      97+ new TextGenerationError({
      98+ operation: input.operation,
      99+ detail: "Failed to start Pi RPC text generation.",
      100+ cause: String(cause),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      String(cause) erases the underlying PiRpcError (tag, fields, stack) so the error chain is no longer inspectable. TextGenerationError.cause is Schema.Defect(), so the failure itself can be preserved directly — consider passing it through as sibling text-generation modules do (OpenCode2TextGeneration uses cause).

      Suggested change
      100- cause: String(cause),
      100+ cause,
      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +205,21 @@
      205+ input = input.slice(newline + 1);
      206+ }
      207+ const lines = input.split("\n");
      208+ remainder = lines.pop() ?? "";
      209+ const effects: Array<Effect.Effect<void>> = lines.map(parseLine);
      210+ if (maxLineLength !== undefined && remainder.length > maxLineLength) {
      211+ remainder = "";
      212+ discardingOversizedLine = true;
      213+ effects.push(
      214+ Queue.offer(events, {
      215+ _tag: "PiRpcProtocolFailureEvent",
      216+ reason: "LineTooLong",
      217+ detail: `Pi RPC remainder exceeded ${String(maxLineLength)} characters`,
      218+ }).pipe(Effect.asVoid),
      219+ );
      220+ }
      221+ return Effect.forEach(effects, (effect) => effect, { discard: true });
      222+ }),
      223+ Effect.matchEffect({
      224+ onFailure: (cause) =>
      225+ end(new PiRpcProcessExitedError({ detail: `Pi RPC stdout failed: ${String(cause)}` })),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This stringifies the stdout failure into detail and drops the failure itself: PiRpcProcessExitedError (lines 40-43) has no cause field, so the immediate underlying error and its stack are lost, and the caller-visible message becomes arbitrary defect text. Consider adding cause: Schema.optional(Schema.Defect()) to the error class and constructing it with a stable detail (for example "Pi RPC stdout failed") plus cause, keeping the exact value only in cause.

      Posted via Macroscope — Effect Service Conventions
    4. @@ -0,0 +59,21 @@
      59+ const sessionFile = canonicalContainedPath(path, rootReal, input.cursor.sessionFile);
      60+ if (!sessionFile || sessionFile !== input.cursor.sessionFile || !path.isAbsolute(sessionFile)) {
      61+ return yield* new PiSessionFileError({
      62+ operation: "containment",
      63+ sessionFile: input.cursor.sessionFile,
      64+ cause: rootReal,
      65+ });
      66+ }
      67+ const fileReal = yield* fs.realPath(sessionFile);
      68+ if (fileReal !== sessionFile || canonicalContainedPath(path, rootReal, fileReal) !== fileReal) {
      69+ return yield* new PiSessionFileError({ operation: "symlink", sessionFile, cause: fileReal });
      70+ }
      71+ const info = yield* fs.stat(sessionFile);
      72+ if (info.type !== "File")
      73+ return yield* new PiSessionFileError({
      74+ operation: "regularFile",
      75+ sessionFile,
      76+ cause: info.type,
      77+ });
      78+ yield* fs.access(sessionFile, { readable: true });
      79+ const firstLine = (yield* fs.readFileString(sessionFile)).split(/\r?\n/, 1)[0] ?? "";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High pi/PiSessionFile.ts:79

      validatePiResumeSessionFile calls fs.readFileString(sessionFile) and only then takes the first line, so resuming a long-running session loads the entire JSONL transcript into memory even though only the header is needed. A large session file can cause a major memory spike or OOM. Consider reading a bounded prefix of the file (for example via a stream or a fixed-size read) and parsing the first line from that instead.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/pi/PiSessionFile.ts around line 79:
      
      `validatePiResumeSessionFile` calls `fs.readFileString(sessionFile)` and only then takes the first line, so resuming a long-running session loads the entire JSONL transcript into memory even though only the header is needed. A large session file can cause a major memory spike or OOM. Consider reading a bounded prefix of the file (for example via a stream or a fixed-size read) and parsing the first line from that instead.
      @@ -0,0 +321,21 @@
      321+ threadId: ctx.session.threadId,
      322+ ...(turn ? { turnId: turn.id } : {}),
      323+ } as const;
      324+ });
      325+ const raw = (event: PiRpcEvent) => ({
      326+ source: "pi.rpc.notification" as const,
      327+ method: isRecord(event) ? string(event.type) : undefined,
      328+ payload: event,
      329+ });
      330+
      331+ const resolveExtensionInput = Effect.fn("PiAdapter.resolveExtensionInput")(function* (
      332+ ctx: SessionContext,
      333+ requestId: ApprovalRequestId,
      334+ pending: PendingExtensionInput,
      335+ answers: ProviderUserInputAnswers,
      336+ response:
      337+ | { readonly value: string }
      338+ | { readonly confirmed: boolean }
      339+ | { readonly cancelled: true },
      340+ ) {
      341+ if (ctx.pendingUserInputs.get(requestId) !== pending) return false;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAdapter.ts:341

      resolveExtensionInput deletes the pending request from ctx.pendingUserInputs and emits user-input.resolved before calling ctx.client.respondToExtensionUi. If that RPC call fails (e.g., the Pi process exited), the error propagates to the caller, but the UI has already been told the request was resolved and the map entry is gone — so the user cannot retry and Pi never receives the answer. The pending entry should be retained (or restored) and the resolved event published only after respondToExtensionUi succeeds.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around line 341:
      
      `resolveExtensionInput` deletes the pending request from `ctx.pendingUserInputs` and emits `user-input.resolved` *before* calling `ctx.client.respondToExtensionUi`. If that RPC call fails (e.g., the Pi process exited), the error propagates to the caller, but the UI has already been told the request was resolved and the map entry is gone — so the user cannot retry and Pi never receives the answer. The pending entry should be retained (or restored) and the resolved event published only after `respondToExtensionUi` succeeds.
      @@ -0,0 +1334,21 @@
      1334+ if (deferredSettlement)
      1335+ yield* handleEvent(ctx, deferredSettlement).pipe(Effect.orDie);
      1336+ }),
      1337+ ),
      1338+ Effect.uninterruptible,
      1339+ Effect.as({
      1340+ threadId: input.threadId,
      1341+ turnId: steeringTurn.id,
      1342+ resumeCursor: ctx.cursor,
      1343+ }),
      1344+ ),
      1345+ };
      1346+ }
      1347+ const available = yield* ctx.client
      1348+ .getAvailableModels()
      1349+ .pipe(Effect.mapError((cause) => request("get_available_models", cause)));
      1350+ if (
      1351+ !available.models.some((m) => m.provider === parsed.provider && m.id === parsed.modelId)
      1352+ )
      1353+ return yield* validation("sendTurn", "Selected Pi model is not currently available.");
      1354+ yield* ctx.client
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiAdapter.ts:1354

      After setModel succeeds, ctx.session.model is never updated, so listSessions() keeps returning the model from startSession even when a later turn selects a different one. This means the advertised in-session model switch is not reflected in session state. Consider assigning ctx.session.model (and any related fields) from the parsed selection after the setModel call, as other in-session adapters do.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around line 1354:
      
      After `setModel` succeeds, `ctx.session.model` is never updated, so `listSessions()` keeps returning the model from `startSession` even when a later turn selects a different one. This means the advertised in-session model switch is not reflected in session state. Consider assigning `ctx.session.model` (and any related fields) from the parsed selection after the `setModel` call, as other in-session adapters do.
      @@ -0,0 +1002,21 @@
      1002+ const snapshot = yield* ctx.client.getState().pipe(
      1003+ Effect.mapError((cause) => request("get_state", cause)),
      1004+ Effect.exit,
      1005+ );
      1006+ if (ctx.steeringGeneration === steeringGeneration) return snapshot;
      1007+ }
      1008+ return undefined;
      1009+ });
      1010+ if (state === undefined) {
      1011+ ctx.deferredSettlement = native;
      1012+ return;
      1013+ }
      1014+ if (ctx.activeTurn !== turn || turn.terminal || ctx.closing || ctx.stopped) return;
      1015+ if (Exit.isFailure(state) || !piStateMatchesCursor(state.value, ctx.cursor)) {
      1016+ yield* failActive(ctx, "Pi session identity drifted during settlement.", native);
      1017+ yield* close(ctx);
      1018+ return;
      1019+ }
      1020+ if (state.value.isStreaming === true) return;
      1021+ const terminalEvents: ProviderRuntimeEvent[] = [];
      1022+ if (turn.assistantText.trim().length > 0) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiAdapter.ts:1022

      When a Pi response contains only whitespace deltas, the assistant message item is left permanently inProgress even after the turn completes. turn.assistantStarted is set to true on the first delta, but the settlement logic at agent_settled only emits item.completed when turn.assistantText.trim().length > 0, so a whitespace-only response never closes the item. The reasoning branch correctly uses turn.reasoningStarted for this decision — the assistant branch should use turn.assistantStarted instead of re-checking the trimmed text length.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around line 1022:
      
      When a Pi response contains only whitespace deltas, the assistant message item is left permanently `inProgress` even after the turn completes. `turn.assistantStarted` is set to `true` on the first delta, but the settlement logic at `agent_settled` only emits `item.completed` when `turn.assistantText.trim().length > 0`, so a whitespace-only response never closes the item. The reasoning branch correctly uses `turn.reasoningStarted` for this decision — the assistant branch should use `turn.assistantStarted` instead of re-checking the trimmed text length.
      @@ -0,0 +237,21 @@
      237+ encodeJson(value).pipe(
      238+ Effect.mapError(
      239+ (cause) => new PiRpcProtocolError({ detail: "failed to encode Pi RPC command", cause }),
      240+ ),
      241+ Effect.flatMap((json) =>
      242+ Stream.fromIterable([encoder.encode(`${json}\n`)]).pipe(Stream.run(io.stdin)),
      243+ ),
      244+ ),
      245+ );
      246+
      247+ const request = <A>(
      248+ command: string,
      249+ payload: object,
      250+ decode: (data: unknown) => Effect.Effect<A, PiRpcError>,
      251+ ) =>
      252+ Effect.gen(function* () {
      253+ const id = yield* Ref.getAndUpdate(nextId, (value) => value + 1).pipe(
      254+ Effect.map((value) => `t3-pi-${String(value)}`),
      255+ );
      256+ const waiter = yield* Deferred.make<PiRpcResponse, PiRpcError>();
      257+ yield* Ref.update(pending, (current) => new Map(current).set(id, waiter));
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High pi/PiRpcClient.ts:257

      After the transport has ended (stdout exits or client.close() runs), new request calls still register a waiter and block until the 120-second timeout instead of failing immediately with PiRpcProcessExitedError. The end function clears the pending map once, so any request added afterward is stranded with no response or future end to complete it.

      This happens because request checks neither the closed ref nor whether the transport is still alive before inserting into pending. Consider failing the request up front when closed is true, or having end also reject late additions via a shared flag.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/pi/PiRpcClient.ts around line 257:
      
      After the transport has ended (stdout exits or `client.close()` runs), new `request` calls still register a waiter and block until the 120-second timeout instead of failing immediately with `PiRpcProcessExitedError`. The `end` function clears the pending map once, so any request added afterward is stranded with no response or future `end` to complete it.
      
      This happens because `request` checks neither the `closed` ref nor whether the transport is still alive before inserting into `pending`. Consider failing the request up front when `closed` is `true`, or having `end` also reject late additions via a shared flag.
      @@ -0,0 +1412,21 @@
      1412+ }
      1413+ }
      1414+ return {
      1415+ _tag: "Started" as const,
      1416+ result: { threadId: input.threadId, turnId, resumeCursor: ctx.cursor },
      1417+ };
      1418+ }),
      1419+ ).pipe(
      1420+ Effect.flatMap((action) =>
      1421+ action._tag === "Steer" ? action.effect : Effect.succeed(action.result),
      1422+ ),
      1423+ Effect.onInterrupt(() =>
      1424+ Effect.suspend(() => {
      1425+ const ctx = sessions.get(input.threadId);
      1426+ return ctx && ctx.activeTurn === createdTurn ? close(ctx) : Effect.void;
      1427+ }),
      1428+ ),
      1429+ );
      1430+ };
      1431+
      1432+ const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAdapter.ts:1432

      interruptTurn calls withThreadLock, but sendTurn already holds that lock while ctx.client.prompt can be blocked waiting for extension UI input. The interrupt request deadlocks on the lock and the abort RPC is never sent, so the turn cannot be cancelled while it is waiting on user input. The same deadlock affects stopSession (and stopAll during finalization): it blocks on the lock held by sendTurn and hangs indefinitely when the extension UI has no timeout. Consider not serializing interruptTurn and stopSession behind the same lock, or having sendTurn release the lock while awaiting extension UI, so abort/close can proceed.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAdapter.ts around line 1432:
      
      `interruptTurn` calls `withThreadLock`, but `sendTurn` already holds that lock while `ctx.client.prompt` can be blocked waiting for extension UI input. The interrupt request deadlocks on the lock and the abort RPC is never sent, so the turn cannot be cancelled while it is waiting on user input. The same deadlock affects `stopSession` (and `stopAll` during finalization): it blocks on the lock held by `sendTurn` and hangs indefinitely when the extension UI has no timeout. Consider not serializing `interruptTurn` and `stopSession` behind the same lock, or having `sendTurn` release the lock while awaiting extension UI, so abort/close can proceed.
    5. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f3eb5d0f6779059aa463ee5e7b54439f7eea4aa2. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +998,21 @@
      998+ }
      999+ const state = yield* Effect.gen(function* () {
      1000+ while (ctx.steeringPromptsInFlight === 0) {
      1001+ const steeringGeneration = ctx.steeringGeneration;
      1002+ const snapshot = yield* ctx.client.getState().pipe(
      1003+ Effect.mapError((cause) => request("get_state", cause)),
      1004+ Effect.exit,
      1005+ );
      1006+ if (ctx.steeringGeneration === steeringGeneration) return snapshot;
      1007+ }
      1008+ return undefined;
      1009+ });
      1010+ if (state === undefined) {
      1011+ ctx.deferredSettlement = native;
      1012+ return;
      1013+ }
      1014+ if (ctx.activeTurn !== turn || turn.terminal || ctx.closing || ctx.stopped) return;
      1015+ if (Exit.isFailure(state) || !piStateMatchesCursor(state.value, ctx.cursor)) {
      1016+ yield* failActive(ctx, "Pi session identity drifted during settlement.", native);
      1017+ yield* close(ctx);
      1018+ return;

      Settlement errors misread as drift

      Medium Severity

      During agent_settled handling, a failed get_state Exit is treated the same as a cursor mismatch. That fails the turn with an identity-drift message and closes the session, so a transient RPC/get_state error tears down an otherwise healthy Pi session.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f3eb5d0f6779059aa463ee5e7b54439f7eea4aa2. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +1014,21 @@
      1014+ if (ctx.activeTurn !== turn || turn.terminal || ctx.closing || ctx.stopped) return;
      1015+ if (Exit.isFailure(state) || !piStateMatchesCursor(state.value, ctx.cursor)) {
      1016+ yield* failActive(ctx, "Pi session identity drifted during settlement.", native);
      1017+ yield* close(ctx);
      1018+ return;
      1019+ }
      1020+ if (state.value.isStreaming === true) return;
      1021+ const terminalEvents: ProviderRuntimeEvent[] = [];
      1022+ if (turn.assistantText.trim().length > 0) {
      1023+ terminalEvents.push({
      1024+ type: "item.completed",
      1025+ ...(yield* base(ctx, turn)),
      1026+ itemId: turn.assistantItemId,
      1027+ payload: {
      1028+ itemType: "assistant_message",
      1029+ status: "completed",
      1030+ title: "Assistant message",
      1031+ },
      1032+ raw: raw(native),
      1033+ });
      1034+ }

      Whitespace leaves assistant item open

      Medium Severity

      Assistant text_delta events start an assistant item whenever the delta is non-empty, including whitespace. Settlement only emits item.completed when trimmed assistant text is non-empty, so whitespace-only replies leave an in-progress assistant item after turn.completed.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f3eb5d0f6779059aa463ee5e7b54439f7eea4aa2. Configure [here](https://www.cursor.com/dashboard/bugbot).
    6. 💡 Codex Review

      Here are some automated review suggestions for this pull request.

      Reviewed commit: f3eb5d0f67

      ℹ️ About Codex in GitHub

      Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

      • Open a pull request for review
      • Mark a draft as ready
      • Comment "@codex review".

      If Codex has suggestions, it will comment; otherwise it will react with 👍.

      Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

      @@ -0,0 +941,21 @@
      941+ type: "content.delta",
      942+ ...(yield* base(ctx, turn)),
      943+ itemId,
      944+ payload: {
      945+ streamKind: isAssistant ? "assistant_text" : "reasoning_text",
      946+ delta,
      947+ },
      948+ raw: raw(native),
      949+ });
      950+ } else if (updateType === "error") {
      951+ yield* failActive(
      952+ ctx,
      953+ string(update?.reason) ?? string(update?.error) ?? "Pi assistant failed.",
      954+ native,
      955+ );
      956+ }
      957+ return;
      958+ }
      959+ if (type === "message_end") {
      960+ yield* handleSubagentResultMessage(ctx, turn, event, native);
      961+ return;

      P1 Badge Treat failed Pi messages as failed turns

      When Pi ends an assistant message with stopReason: "error" or "aborted", this branch ignores that status and the later agent_settled handler publishes a successful turn.completed. API, authentication, and model failures can therefore appear to users as successful blank turns; handle terminal assistant-message stop reasons here, as PiTextGeneration already does.

      AGENTS.md reference: AGENTS.md:L139-L142

      Useful? React with 👍 / 👎.

      @@ -0,0 +91,21 @@
      91+ ? "Pi provider status has not been checked in this session yet."
      92+ : "Pi is disabled in T3 Code settings.",
      93+ },
      94+ }),
      95+ ),
      96+ );
      97+
      98+export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
      99+ settings: PiSettings,
      100+ environment: NodeJS.ProcessEnv = process.env,
      101+ makeRpcClient: PiRpcClientFactory = makePiRpcClient,
      102+): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
      103+ const checkedAt = DateTime.formatIso(yield* DateTime.now);
      104+ if (!settings.enabled) return yield* makePendingPiProvider(settings);
      105+ const discovery = yield* Effect.scoped(
      106+ Effect.gen(function* () {
      107+ const client = yield* makeRpcClient({
      108+ command: settings.binaryPath,
      109+ args: DETERMINISTIC_ARGS,
      110+ env: environment,
      111+ });

      P2 Badge Discover Pi commands from the project working directory

      The health probe launches Pi without a cwd, so getCommands() loads commands, extensions, and skills relative to the T3 server process rather than the user's project. For projects with project-scoped Pi configuration, those commands will be absent from the composer catalog, while commands from the server's own directory may be advertised instead; command discovery needs project/session context or must avoid presenting this process-global snapshot as the project catalog.

      Useful? React with 👍 / 👎.

      @@ -0,0 +59,21 @@
      59+ const sessionFile = canonicalContainedPath(path, rootReal, input.cursor.sessionFile);
      60+ if (!sessionFile || sessionFile !== input.cursor.sessionFile || !path.isAbsolute(sessionFile)) {
      61+ return yield* new PiSessionFileError({
      62+ operation: "containment",
      63+ sessionFile: input.cursor.sessionFile,
      64+ cause: rootReal,
      65+ });
      66+ }
      67+ const fileReal = yield* fs.realPath(sessionFile);
      68+ if (fileReal !== sessionFile || canonicalContainedPath(path, rootReal, fileReal) !== fileReal) {
      69+ return yield* new PiSessionFileError({ operation: "symlink", sessionFile, cause: fileReal });
      70+ }
      71+ const info = yield* fs.stat(sessionFile);
      72+ if (info.type !== "File")
      73+ return yield* new PiSessionFileError({
      74+ operation: "regularFile",
      75+ sessionFile,
      76+ cause: info.type,
      77+ });
      78+ yield* fs.access(sessionFile, { readable: true });
      79+ const firstLine = (yield* fs.readFileString(sessionFile)).split(/\r?\n/, 1)[0] ?? "";

      P2 Badge Read only the session header during resume validation

      For every resumed Pi thread, this reads the entire append-only JSONL session merely to inspect its first line. Long-running sessions can contain large tool outputs and attachments, so resume cost and peak memory grow with the complete conversation and can stall or exhaust the server; stream or bound the read to the first newline instead.

      AGENTS.md reference: AGENTS.md:L15-L17

      Useful? React with 👍 / 👎.

      @@ -0,0 +1296,21 @@
      1296+ return Effect.fail(request("prompt", `Invalid attachment id '${attachment.id}'.`));
      1297+ return provideFiles(fs.readFile(attachmentPath)).pipe(
      1298+ Effect.map((bytes) => ({
      1299+ type: "image" as const,
      1300+ data: Buffer.from(bytes).toString("base64"),
      1301+ mimeType: attachment.mimeType,
      1302+ })),
      1303+ Effect.mapError((cause) => request("prompt", cause)),
      1304+ );
      1305+ },
      1306+ { concurrency: 1 },
      1307+ );
      1308+ const selection = input.modelSelection;
      1309+ if (selection && selection.instanceId !== options.providerInstanceId)
      1310+ return yield* validation(
      1311+ "sendTurn",
      1312+ "Model selection belongs to another provider instance.",
      1313+ );
      1314+ const parsed = selection ? decodePiModelSlug(selection.model) : undefined;
      1315+ if (!parsed)
      1316+ return yield* validation("sendTurn", "A valid Pi model selection is required.");

      P2 Badge Fall back to the session model when a turn omits selection

      ThreadTurnStartCommand.modelSelection is optional, and the orchestration layer deliberately passes it through as absent for in-session-switching providers, but Pi rejects every such turn even when ctx.session.model already identifies the active model. Compatible clients or API callers that omit the redundant selection on a follow-up therefore fail with “A valid Pi model selection is required”; use the stored session model and keep it updated after model switches.

      AGENTS.md reference: AGENTS.md:L67-L74

      Useful? React with 👍 / 👎.

    7. Approvability

      Verdict: Needs human review

      6 blocking correctness issues found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).

Sign in to join this conversation.