Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(providers): add Pi coding agent #6319

Closedquasarea(GitHub profile, opens in a new tab)wants to merge 223 commits intot3code/codex-turn-mapping fromrefs/pull/6319/headopened View on GitHub

Summary

Adds Pi as a first-class, disabled-by-default coding-agent provider for the Orchestrator V2 architecture.

This is a stacked draft targeting the head branch of #2829 (t3code/codex-turn-mapping); it can be retargeted to main after that PR lands.

  • adds a scoped Pi JSONL RPC transport with correlated requests, strict LF framing, process cleanup, and Windows command resolution
  • projects Pi streaming text, reasoning, tools, retries, compaction, terminal state, approvals, and user-input requests into Orchestrator V2 events
  • persists Pi session identity and resumes existing sessions with switch_session
  • discovers account-specific provider/model slugs and exposes Pi's seven thinking levels
  • forwards image attachments for prompts and steering
  • adds isolated RPC-backed text generation for commit messages, PR content, branch names, and task titles
  • registers Pi across provider settings, model selection, web icons, and mobile icons

Why

T3 currently has first-party Codex, Claude, Cursor, Grok, OpenCode, and ACP integrations, but no Orchestrator V2 driver for Pi. Pi's official RPC mode provides the session, streaming, model-selection, tool, and extension UI primitives needed for a native adapter without scraping terminal output.

The implementation intentionally stays inside T3 because the provider, orchestration, settings, and presentation contracts are currently internal. Repository coordination and Forgejo authentication remain outside this driver; Pi can invoke the shared forgejo-bridge CLI through its normal shell tools without duplicating API or credential logic.

User impact

After enabling Pi in provider settings, users can select discovered Pi models, choose supported thinking levels, run persistent coding sessions, resume them after T3 runtime restarts, steer or interrupt active work, answer extension prompts, attach images, and use Pi for T3's generated Git metadata.

Pi remains disabled by default and is marked Early Access.

Intentional limitations

  • provider-native conversation rollback and fork are disabled until Pi session entry IDs are projected safely; T3 filesystem checkpoints remain available
  • Pi usage is decoded and validated, but Orchestrator V2 does not currently expose a provider usage-accounting event surface
  • this branch was validated with deterministic RPC process fixtures because the Pi CLI was not installed on the development host

Validation

  • pnpm exec vp test run src/orchestration-v2/Adapters/PiRpcTransport.test.ts src/orchestration-v2/Adapters/PiRpcProtocol.test.ts src/provider/Layers/PiProvider.test.ts src/provider/Drivers/PiDriver.test.ts src/orchestration-v2/Adapters/PiAdapterV2.test.ts src/textGeneration/PiTextGeneration.test.ts — 20 tests passed
  • pnpm exec vp test run --project unit src/components/settings/ProviderSettingsForm.test.ts — 13 tests passed
  • pnpm exec vp test run src/settings.test.ts — 34 tests passed
  • server, web, contracts, and mobile typechecks passed
  • focused lint, formatting, and whitespace checks passed

References

Note

Add Pi coding agent as a new provider with orchestration, text generation, and settings UI

  • Introduces the pi provider driver backed by the @earendil-works/pi-coding-agent npm package, disabled by default with binaryPath: 'pi'.
  • Adds PiAdapterV2 implementing the full orchestration V2 interface: streaming text/tool events, interrupt/steer, extension UI approvals, thread snapshots, and image attachments via base64 encoding.
  • Adds PiTextGeneration for structured RPC-backed generation of thread titles, commit messages, PR content, and branch names.
  • Adds PiProvider with CLI health probing, RPC-based model discovery, and thinking-level capability descriptors for reasoning models.
  • Registers the provider across contracts (settings schema, display name, model slug aliases), server driver registry, orchestration V2 adapter registry, and web/mobile UI (icon, picker badge, settings form).
📊 Macroscope summarized 5c2ce2b. 16 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. 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: 51996517-1b64-46fd-80a9-fc343c40c304

      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. @@ -0,0 +999,21 @@
      999+ nativeTurnRef: null,
      1000+ ordinal: turnInput.providerTurnOrdinal,
      1001+ status: "running",
      1002+ startedAt,
      1003+ completedAt: null,
      1004+ };
      1005+ state.providerTurns.set(String(providerTurn.id), providerTurn);
      1006+ state.activeTurn = {
      1007+ input: turnInput,
      1008+ providerTurn,
      1009+ nextItemOrdinal: 0,
      1010+ itemOrdinals: new Map(),
      1011+ content: new Map(),
      1012+ startedAt,
      1013+ interrupted: false,
      1014+ };
      1015+ yield* updateThread(state, {
      1016+ status: "active",
      1017+ firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
      1018+ });
      1019+ yield* updateSession("running");
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/PiAdapterV2.ts:1019

      After startTurn calls set_model, providerSession.model is never updated, so updateSession("running") keeps the model from openSession and providerSession.model misreports the model actually running the turn. Consider updating providerSession.model to turnInput.modelSelection.model before or during updateSession("running") so session snapshots reflect the switch.

                    yield* updateThread(state, {
                      status: "active",
                      firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
                    });
      -             yield* updateSession("running");
      +             yield* updateSession("running", null, turnInput.modelSelection.model);
      
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts around line 1019:
      
      After `startTurn` calls `set_model`, `providerSession.model` is never updated, so `updateSession("running")` keeps the model from `openSession` and `providerSession.model` misreports the model actually running the turn. Consider updating `providerSession.model` to `turnInput.modelSelection.model` before or during `updateSession("running")` so session snapshots reflect the switch.
      @@ -0,0 +223,21 @@
      223+ }
      224+
      225+ const versionExit = versionResult.success.value;
      226+ const version = parseGenericCliVersion(`${versionExit.stdout}\n${versionExit.stderr}`);
      227+ if (versionExit.code !== 0) {
      228+ return buildServerProvider({
      229+ presentation: PI_PRESENTATION,
      230+ enabled: true,
      231+ checkedAt,
      232+ models: fallbackModels,
      233+ probe: {
      234+ installed: true,
      235+ version,
      236+ status: "error",
      237+ auth: { status: "unknown" },
      238+ message: detailFromResult(versionExit) ?? "Pi CLI returned an error during health check.",
      239+ },
      240+ });
      241+ }
      242+
      243+ const models = modelsFromSettings(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiProvider.ts:243

      authenticated is derived from the merged models list, which includes settings.customModels via providerModelsFromSettings. When RPC discovery fails or returns no models but the user has configured custom models, the provider is incorrectly reported as ready and authenticated, suppressing the warning that no models are available. Authentication should be determined from the discovered RPC models before merging custom settings.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiProvider.ts around line 243:
      
      `authenticated` is derived from the merged `models` list, which includes `settings.customModels` via `providerModelsFromSettings`. When RPC discovery fails or returns no models but the user has configured custom models, the provider is incorrectly reported as `ready` and `authenticated`, suppressing the warning that no models are available. Authentication should be determined from the discovered RPC models before merging custom settings.
      @@ -0,0 +205,21 @@
      205+ }
      206+ yield* Queue.offer(messages, message);
      207+ });
      208+
      209+ yield* Stream.fromQueue(outgoing).pipe(
      210+ Stream.run(child.stdin),
      211+ Effect.mapError((cause) => new PiRpcTransportError({ operation: "write", cause })),
      212+ Effect.catch((error) => Queue.fail(messages, error)),
      213+ Effect.forkScoped,
      214+ );
      215+
      216+ yield* child.stderr.pipe(Stream.runDrain, Effect.ignore, Effect.forkScoped);
      217+
      218+ yield* decodePiRpcStdout(child.stdout).pipe(
      219+ Stream.runForEach(routeMessage),
      220+ Effect.catch((error) => Queue.fail(messages, error)),
      221+ Effect.ensuring(markClosed()),
      222+ Effect.forkScoped,
      223+ );
      224+
      225+ const request = Effect.fn("PiRpcTransport.request")(function* (
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/PiRpcTransport.ts:225

      If a request fiber is interrupted after it registers its deferred in pendingRequests but before it completes, the map entry is never removed. A later response for that orphaned id is silently consumed by the abandoned deferred instead of being exposed on messages, and repeated cancelled requests leak entries until transport shutdown. The cleanup at the end of request only runs on normal completion — interruption skips it. Wrap the body in Effect.ensuring(() => Effect.sync(() => pendingRequests.delete(id))) so the entry is removed regardless of how the fiber terminates.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiRpcTransport.ts around line 225:
      
      If a `request` fiber is interrupted after it registers its deferred in `pendingRequests` but before it completes, the map entry is never removed. A later response for that orphaned `id` is silently consumed by the abandoned deferred instead of being exposed on `messages`, and repeated cancelled requests leak entries until transport shutdown. The cleanup at the end of `request` only runs on normal completion — interruption skips it. Wrap the body in `Effect.ensuring(() => Effect.sync(() => pendingRequests.delete(id)))` so the entry is removed regardless of how the fiber terminates.
      @@ -0,0 +552,21 @@
      552+ });
      553+ } else {
      554+ yield* emit({
      555+ type: "turn_item.updated",
      556+ driver: PI_DRIVER_KIND,
      557+ turnItem: { ...base, type: "reasoning", text, streaming: false },
      558+ });
      559+ }
      560+ }
      561+ });
      562+
      563+ const emitTool = Effect.fnUntraced(function* (
      564+ state: PiThreadState,
      565+ turn: ActivePiTurn,
      566+ projected: Extract<
      567+ PiProjectedEvent,
      568+ { type: "tool.started" | "tool.updated" | "tool.completed" }
      569+ >,
      570+ ) {
      571+ const now = yield* DateTime.now;
      572+ const nativeItemId = projected.toolCallId;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/PiAdapterV2.ts:572

      On tool.completed, emitTool overwrites the tool call's input with {}, so the final turn_item.updated event drops the arguments that were emitted on tool.started/tool.updated. Persisted completed tool calls end up with empty input. This is because projected.args is absent in the completion projection, and the code uses projected.type === "tool.completed" ? {} : projected.args. Track the last emitted args per toolCallId and reuse it on completion instead of resetting to {}.

      Suggested change
      572- const nativeItemId = projected.toolCallId;
      572+ const nativeItemId = projected.toolCallId;
      573+ const lastArgs = turn.toolArgs.get(nativeItemId) ?? projected.args ?? {};
      574+ if (projected.type !== "tool.completed") turn.toolArgs.set(nativeItemId, projected.args ?? {});
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts around line 572:
      
      On `tool.completed`, `emitTool` overwrites the tool call's `input` with `{}`, so the final `turn_item.updated` event drops the arguments that were emitted on `tool.started`/`tool.updated`. Persisted completed tool calls end up with empty input. This is because `projected.args` is absent in the completion projection, and the code uses `projected.type === "tool.completed" ? {} : projected.args`. Track the last emitted `args` per `toolCallId` and reuse it on completion instead of resetting to `{}`.
      @@ -0,0 +790,21 @@
      790+ status,
      791+ failure: {
      792+ class: "provider_error",
      793+ message: projected.errorMessage ?? "Pi run failed.",
      794+ code: null,
      795+ retryable: null,
      796+ },
      797+ threadDisposition: "reusable",
      798+ }
      799+ : {
      800+ type: "turn.terminal",
      801+ driver: PI_DRIVER_KIND,
      802+ providerThreadId: state.providerThread.id,
      803+ providerTurnId: turn.providerTurn.id,
      804+ runOrdinal: turn.input.runOrdinal,
      805+ status,
      806+ failure: null,
      807+ threadDisposition: "reusable",
      808+ },
      809+ );
      810+ delete state.activeTurn;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/PiAdapterV2.ts:810

      When a Pi turn reaches terminal status, any pending runtime requests (extension UI prompts) for that turn are left in pendingPrompts and state.runtimeRequests with status "pending" forever. The corresponding nodes and turn items also remain "waiting". This means an interrupted or failed turn leaves stale approval/user-input requests that never resolve, and respondToRuntimeRequest will still accept and send responses for them afterward.

      In handleProjected for run.terminal, the code finalizes content and deletes state.activeTurn but never iterates pendingPrompts to cancel or resolve entries belonging to the terminal turn. Consider resolving all pending prompts for that turn (emitting terminal node/turn-item/runtime-request updates and sending extension_ui_response with cancelled: true to the transport) before clearing state.activeTurn.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts around line 810:
      
      When a Pi turn reaches terminal status, any pending runtime requests (extension UI prompts) for that turn are left in `pendingPrompts` and `state.runtimeRequests` with status `"pending"` forever. The corresponding nodes and turn items also remain `"waiting"`. This means an interrupted or failed turn leaves stale approval/user-input requests that never resolve, and `respondToRuntimeRequest` will still accept and send responses for them afterward.
      
      In `handleProjected` for `run.terminal`, the code finalizes content and deletes `state.activeTurn` but never iterates `pendingPrompts` to cancel or resolve entries belonging to the terminal turn. Consider resolving all pending prompts for that turn (emitting terminal node/turn-item/runtime-request updates and sending `extension_ui_response` with `cancelled: true` to the transport) before clearing `state.activeTurn`.
      @@ -0,0 +194,21 @@
      194+ ) {
      195+ if (message._tag === "response") {
      196+ const id = message.response.id;
      197+ if (id !== undefined) {
      198+ const pending = pendingRequests.get(id);
      199+ if (pending !== undefined) {
      200+ pendingRequests.delete(id);
      201+ yield* Deferred.succeed(pending, message.response);
      202+ return;
      203+ }
      204+ }
      205+ }
      206+ yield* Queue.offer(messages, message);
      207+ });
      208+
      209+ yield* Stream.fromQueue(outgoing).pipe(
      210+ Stream.run(child.stdin),
      211+ Effect.mapError((cause) => new PiRpcTransportError({ operation: "write", cause })),
      212+ Effect.catch((error) => Queue.fail(messages, error)),
      213+ Effect.forkScoped,
      214+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/PiRpcTransport.ts:209

      When Stream.run(child.stdin) fails, only messages is failed — closed is never completed and outgoing is never ended. As a result, subsequent send calls still enqueue data and report success even though nothing is writing to the child, and request calls block until their full timeout instead of detecting the broken transport. The write-failure path should call markClosed (or at least complete closed and end outgoing) so callers see the transport is dead.

        yield* Stream.fromQueue(outgoing).pipe(
          Stream.run(child.stdin),
          Effect.mapError((cause) => new PiRpcTransportError({ operation: "write", cause })),
      -    Effect.catch((error) => Queue.fail(messages, error)),
      +    Effect.catch((error) =>
      +      Effect.gen(function* () {
              yield* Queue.fail(messages, error);
              yield* markClosed();
            }),
          ),
          Effect.forkScoped,
        );
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiRpcTransport.ts around lines 209-214:
      
      When `Stream.run(child.stdin)` fails, only `messages` is failed — `closed` is never completed and `outgoing` is never ended. As a result, subsequent `send` calls still enqueue data and report success even though nothing is writing to the child, and `request` calls block until their full timeout instead of detecting the broken transport. The write-failure path should call `markClosed` (or at least complete `closed` and end `outgoing`) so callers see the transport is dead.
      @@ -0,0 +87,21 @@
      87+ Schema.Struct({ type: Schema.Literal("start") }),
      88+ Schema.Struct({ type: Schema.Literal("done") }),
      89+ Schema.Struct({ type: Schema.Literal("error") }),
      90+]);
      91+
      92+const PiKnownEvent = Schema.Union([
      93+ Schema.Struct({ type: Schema.Literal("agent_start") }),
      94+ Schema.Struct({
      95+ type: Schema.Literal("agent_end"),
      96+ messages: Schema.Array(PiMessage),
      97+ willRetry: Schema.Boolean,
      98+ }),
      99+ Schema.Struct({ type: Schema.Literal("agent_settled") }),
      100+ Schema.Struct({ type: Schema.Literal("turn_start") }),
      101+ Schema.Struct({ type: Schema.Literal("turn_end"), message: PiMessage }),
      102+ Schema.Struct({ type: Schema.Literal("message_start"), message: PiMessage }),
      103+ Schema.Struct({
      104+ type: Schema.Literal("message_update"),
      105+ message: PiMessage,
      106+ assistantMessageEvent: PiAssistantMessageEvent,
      107+ }),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/PiRpcProtocol.ts:103

      The message_update schema requires a message field, but Pi's RPC protocol omits message from message_update events and sends only assistantMessageEvent. Every normal streaming update therefore fails decodeKnownEvent and is converted to PiRpcProtocolError, so text_delta and thinking_delta deltas are never projected. Making message optional (or removing it) aligns the schema with the actual protocol.

      Suggested change
      103- Schema.Struct({
      104- type: Schema.Literal("message_update"),
      105- message: PiMessage,
      106- assistantMessageEvent: PiAssistantMessageEvent,
      107- }),
      103+ Schema.Struct({
      104+ type: Schema.Literal("message_update"),
      105+ message: Schema.optional(PiMessage),
      106+ assistantMessageEvent: PiAssistantMessageEvent,
      107+ }),
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiRpcProtocol.ts around lines 103-107:
      
      The `message_update` schema requires a `message` field, but Pi's RPC protocol omits `message` from `message_update` events and sends only `assistantMessageEvent`. Every normal streaming update therefore fails `decodeKnownEvent` and is converted to `PiRpcProtocolError`, so `text_delta` and `thinking_delta` deltas are never projected. Making `message` optional (or removing it) aligns the schema with the actual protocol.
      @@ -0,0 +447,21 @@
      447+ return {
      448+ type: "user-input",
      449+ requestId: id,
      450+ method,
      451+ title,
      452+ options,
      453+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
      454+ };
      455+ }
      456+ if (method === "input") {
      457+ const placeholder = request["placeholder"];
      458+ return {
      459+ type: "user-input",
      460+ requestId: id,
      461+ method,
      462+ title,
      463+ ...(Predicate.isString(placeholder) ? { placeholder } : {}),
      464+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
      465+ };
      466+ }
      467+ if (method === "editor") {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/PiRpcProtocol.ts:467

      projectPiExtensionUiRequest drops the validated timeout for editor requests, even though the user-input prompt type supports timeoutMs and the select and input branches preserve it. An editor request carrying a timeout is returned without its deadline, so the runtime can keep accepting input after Pi has already timed out the request. The editor branch is missing the conditional timeoutMs property that the other branches include.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiRpcProtocol.ts around line 467:
      
      `projectPiExtensionUiRequest` drops the validated `timeout` for `editor` requests, even though the `user-input` prompt type supports `timeoutMs` and the `select` and `input` branches preserve it. An editor request carrying a timeout is returned without its deadline, so the runtime can keep accepting input after Pi has already timed out the request. The `editor` branch is missing the conditional `timeoutMs` property that the other branches include.
      @@ -0,0 +986,21 @@
      986+ thinking === "max"
      987+ ) {
      988+ yield* requestData(transport, { type: "set_thinking_level", level: thinking });
      989+ }
      990+ const startedAt = yield* DateTime.now;
      991+ const providerTurn: OrchestrationV2ProviderTurn = {
      992+ id: options.idAllocator.derive.providerTurn({
      993+ driver: PI_DRIVER_KIND,
      994+ nativeTurnId: `${state.providerThread.nativeThreadRef?.nativeId ?? state.providerThread.id}:${turnInput.runOrdinal}:${turnInput.attemptId}`,
      995+ }),
      996+ providerThreadId: state.providerThread.id,
      997+ nodeId: turnInput.rootNodeId,
      998+ runAttemptId: turnInput.attemptId,
      999+ nativeTurnRef: null,
      1000+ ordinal: turnInput.providerTurnOrdinal,
      1001+ status: "running",
      1002+ startedAt,
      1003+ completedAt: null,
      1004+ };
      1005+ state.providerTurns.set(String(providerTurn.id), providerTurn);
      1006+ state.activeTurn = {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/PiAdapterV2.ts:1006

      startTurn emits active thread, running session, and running provider-turn updates and installs state.activeTurn before sending the prompt RPC. When requestData for the prompt rejects or times out, the function fails with ProviderAdapterTurnStartError, but the already-emitted active/running state and state.activeTurn are never rolled back and no terminal event is emitted — leaving the session and thread stuck running indefinitely. Move the state mutations and emissions to after the prompt RPC succeeds, or roll back state.activeTurn, reset the thread/session status, and emit a terminal event in the error path.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts around line 1006:
      
      `startTurn` emits `active` thread, `running` session, and `running` provider-turn updates and installs `state.activeTurn` *before* sending the `prompt` RPC. When `requestData` for the `prompt` rejects or times out, the function fails with `ProviderAdapterTurnStartError`, but the already-emitted `active`/`running` state and `state.activeTurn` are never rolled back and no terminal event is emitted — leaving the session and thread stuck running indefinitely. Move the state mutations and emissions to after the `prompt` RPC succeeds, or roll back `state.activeTurn`, reset the thread/session status, and emit a terminal event in the error path.
      @@ -0,0 +326,21 @@
      326+ case "tool_execution_update":
      327+ return [
      328+ {
      329+ type: "tool.updated",
      330+ toolCallId: event.toolCallId,
      331+ toolName: event.toolName,
      332+ args: event.args,
      333+ partialResult: event.partialResult,
      334+ },
      335+ ];
      336+ case "tool_execution_end":
      337+ return [
      338+ {
      339+ type: "tool.completed",
      340+ toolCallId: event.toolCallId,
      341+ toolName: event.toolName,
      342+ result: event.result,
      343+ isError: event.isError,
      344+ },
      345+ ];
      346+ case "agent_end": {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/PiRpcProtocol.ts:346

      projectPiEvent emits run.terminal on agent_end when willRetry is false, but agent_end only signals the end of one low-level run — compaction retries or queued continuations can still follow. Because consumers finalize and delete the active turn on run.terminal, any subsequent compaction or follow-up continuation output is silently dropped and the turn is reported complete prematurely. The terminal projection should be deferred to agent_settled (which means no continuation remains), while still carrying the final stop/error state from the last assistant message.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/PiRpcProtocol.ts around line 346:
      
      `projectPiEvent` emits `run.terminal` on `agent_end` when `willRetry` is false, but `agent_end` only signals the end of one low-level run — compaction retries or queued continuations can still follow. Because consumers finalize and delete the active turn on `run.terminal`, any subsequent compaction or follow-up continuation output is silently dropped and the turn is reported complete prematurely. The terminal projection should be deferred to `agent_settled` (which means no continuation remains), while still carrying the final stop/error state from the last assistant message.
    4. Effect service conventions review of the new Pi provider modules. Three mechanical convention issues found in PiAdapterV2.ts / PiAdapterV2.test.ts; the transport, protocol, driver, provider-snapshot, and text-generation modules otherwise follow the repo's Effect conventions (subpath namespace imports, Schema.TaggedErrorClass failures with structural attributes and preserved cause, dependencies acquired with yield* Service in PiAdapterV2Driver.create / PiDriver.create / makePiTextGeneration, no ManagedRuntime/runPromise outside test boundaries).

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +315,21 @@
      315+ command: options.settings.binaryPath || "pi",
      316+ args: ["--mode", "rpc", ...launchArgs],
      317+ cwd,
      318+ env: options.environment,
      319+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, options.spawner));
      320+ const now = yield* DateTime.now;
      321+ let providerSession: OrchestrationV2ProviderSession = {
      322+ id: input.providerSessionId,
      323+ driver: PI_DRIVER_KIND,
      324+ providerInstanceId: options.instanceId,
      325+ status: "ready",
      326+ cwd,
      327+ model: input.modelSelection.model,
      328+ capabilities: PiProviderCapabilitiesV2,
      329+ createdAt: now,
      330+ updatedAt: now,
      331+ lastError: null,
      332+ };
      333+ const events = yield* Queue.unbounded<
      334+ ProviderAdapterV2Event,
      335+ import("../ProviderAdapter.ts").ProviderAdapterV2Error | Cause.Done<void>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Inline import("...") type expressions bypass the module's import list. ../ProviderAdapter.ts and @t3tools/contracts are already imported at the top of this file, so it would be more consistent to add ProviderAdapterV2Error (here), ProviderAdapterV2EnsureThreadInput (line 846), ProviderAdapterV2RuntimePolicy, ThreadId, and ModelSelection (lines 928-930) to those existing type imports and reference them directly.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +157,21 @@
      157+ },
      158+ checkpointing: {
      159+ appCanCheckpointFilesystem: true,
      160+ supportsNestedCheckpointScopes: true,
      161+ providerCanRollbackConversation: false,
      162+ providerRollbackReturnsSnapshot: false,
      163+ providerCanReadConversationSnapshot: true,
      164+ },
      165+ identity: {
      166+ nativeThreadIds: "strong",
      167+ nativeTurnIds: "weak",
      168+ nativeItemIds: "strong",
      169+ nativeRequestIds: "strong",
      170+ },
      171+} satisfies OrchestrationV2ProviderCapabilities;
      172+
      173+interface PiAdapterV2Options {
      174+ readonly instanceId: ProviderInstanceId;
      175+ readonly settings: PiSettings;
      176+ readonly environment: NodeJS.ProcessEnv;
      177+ readonly idAllocator: IdAllocatorV2Shape;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      IdAllocatorV2Shape is the legacy standalone shape type. Consider referring to the inferred service interface instead — readonly idAllocator: IdAllocatorV2["Service"]; (as GrokAdapterV2Options already does) — and dropping the then-unused type IdAllocatorV2Shape from the import on line 33.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +9,21 @@
      9+ ProviderInstanceId,
      10+ ProviderSessionId,
      11+ RunAttemptId,
      12+ RunId,
      13+ RuntimeRequestId,
      14+ ThreadId,
      15+ type OrchestrationV2AppThread,
      16+} from "@t3tools/contracts";
      17+import * as Cause from "effect/Cause";
      18+import * as Deferred from "effect/Deferred";
      19+import * as Effect from "effect/Effect";
      20+import * as Fiber from "effect/Fiber";
      21+import * as FileSystem from "effect/FileSystem";
      22+import * as Layer from "effect/Layer";
      23+import * as Queue from "effect/Queue";
      24+import * as Schema from "effect/Schema";
      25+import * as Sink from "effect/Sink";
      26+import * as Stream from "effect/Stream";
      27+import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
      28+
      29+import { IdAllocatorV2, layer as idAllocatorLayer } from "../IdAllocator.ts";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      layer as idAllocatorLayer erases the service module namespace. Consider import * as IdAllocator from "../IdAllocator.ts"; and using IdAllocator.IdAllocatorV2 / IdAllocator.layer at the two use sites instead of the renamed layer export.

      Posted via Macroscope — Effect Service Conventions

Sign in to join this conversation.