feat: add Pi provider integration via RPC #4355
Closedoussamadouhou(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/4355/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/textGeneration/PiTextGeneration.ts lines 142 to 150OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +130,21 @@130+131+ const rawResult = yield* runPiPrompt({132+ message:133+ `${prompt}\n\nRespond ONLY with minified JSON matching this schema. ` +134+ `No markdown, no code fences, no prose:\n${schemaJson}`,135+ cwd,136+ modelSelection,137+ operation,138+ });139+140+ const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));141+ return yield* decodeOutput(extractJsonObject(rawResult)).pipe(142+ Effect.catchTag("SchemaError", (cause) =>143+ Effect.fail(144+ new TextGenerationError({145+ operation,146+ detail: "Pi returned invalid structured output.",147+ cause,148+ }),149+ ),150+ ),
- apps/server/src/provider/Layers/PiAdapter.ts line 176Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +154,21 @@154+ // whole-token match (split camelCase/separators) so "recommend" isn't read as "command"155+ const tokens = new Set(156+ toolName157+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")158+ .replace(/[._/-]/g, " ")159+ .toLowerCase()160+ .split(/\s+/)161+ .filter((token) => token.length > 0),162+ );163+ const has = (...words: ReadonlyArray<string>): boolean => words.some((word) => tokens.has(word));164+165+ if (has("agent", "subagent", "task", "skill")) return "collab_agent_tool_call";166+ if (has("bash", "shell", "command", "terminal", "exec")) return "command_execution";167+ if (has("edit", "write", "patch", "apply", "file")) return "file_change";168+ if (has("mcp")) return "mcp_tool_call";169+ if (has("search", "web")) return "web_search";170+ if (has("image")) return "image_view";171+ return "dynamic_tool_call";172+}173+174+export function classifyPiApprovalRequestType(toolHint: string): CanonicalRequestType {apps/server/src/provider/Layers/PiAdapter.ts line 168OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +148,21 @@148+149+// ---------------------------------------------------------------------------150+// Pure classification helpers151+// ---------------------------------------------------------------------------152+153+export function classifyPiToolItemType(toolName: string): CanonicalItemType {154+ // whole-token match (split camelCase/separators) so "recommend" isn't read as "command"155+ const tokens = new Set(156+ toolName157+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")158+ .replace(/[._/-]/g, " ")159+ .toLowerCase()160+ .split(/\s+/)161+ .filter((token) => token.length > 0),162+ );163+ const has = (...words: ReadonlyArray<string>): boolean => words.some((word) => tokens.has(word));164+165+ if (has("agent", "subagent", "task", "skill")) return "collab_agent_tool_call";166+ if (has("bash", "shell", "command", "terminal", "exec")) return "command_execution";167+ if (has("edit", "write", "patch", "apply", "file")) return "file_change";168+ if (has("mcp")) return "mcp_tool_call";apps/server/src/provider/Layers/PiAdapter.ts line 1263Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1194,21 @@1194+ `pi-new-session-${yield* nextUuid}`,1195+ PI_FORK_TIMEOUT_MS,1196+ );1197+ if (!piForkSucceeded(rollbackResponse)) {1198+ return yield* new ProviderAdapterRequestError({1199+ provider: PROVIDER,1200+ method: target.kind === "fork" ? "fork" : "new_session",1201+ detail: "Pi rejected or cancelled the rollback.",1202+ });1203+ }1204+1205+ // CRITICAL: fork/new_session rebinds to a new session file — refresh the1206+ // resume cursor or a later reconnect resumes the stale pre-rollback branch1207+ const stateResponse = yield* context.transport.request(1208+ { type: "get_state" },1209+ `pi-get-state-${yield* nextUuid}`,1210+ PI_STATE_TIMEOUT_MS,1211+ );1212+ const sessionFile = extractSessionFile(stateResponse);1213+ const updatedAt = yield* nowIso;1214+ context.session = {apps/server/src/textGeneration/PiTextGeneration.ts line 123Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+ readonly operation: TextGenOperation;49+ }): Effect.Effect<string, TextGenerationError> =>50+ Effect.gen(function* () {51+ const transport = yield* makePiRpcTransport({52+ binaryPath: piSettings.binaryPath || "pi",53+ args: [54+ "--mode",55+ "rpc",56+ "--no-session",57+ "--no-tools",58+ "--no-extensions",59+ "--thinking",60+ "off",61+ ...(input.modelSelection.model ? ["--model", input.modelSelection.model] : []),62+ ],63+ cwd: input.cwd,64+ env: environment,65+ onExit: Effect.void,66+ });67+ yield* transport.writeCommand({ type: "prompt", message: input.message });68+ yield* Stream.fromQueue(transport.messages).pipe(apps/server/src/provider/Layers/PiAdapter.ts line 1059OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1039,21 @@1039+ operation: "sendTurn",1040+ issue: "Pi turns require non-empty text or at least one attachment.",1041+ });1042+ }1043+1044+ // a message mid-turn steers the running turn; otherwise it opens a fresh one1045+ const isMidTurn = context.turnState !== undefined;1046+1047+ // only on a fresh turn — changing options mid-stream would race the active turn1048+ if (!isMidTurn) {1049+ yield* maybeSwitchPiModel(context, requestedModel);1050+ yield* applyThinkingLevel(context, input.modelSelection);1051+ }1052+1053+ if (!context.turnState) {1054+ yield* openTurn(context);1055+ }1056+1057+ const turnId = context.turnState!.turnId;1058+1059+ yield* context.transport
- apps/server/src/textGeneration/PiTextGeneration.ts line 124Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +49,21 @@49+ }): Effect.Effect<string, TextGenerationError> =>50+ Effect.gen(function* () {51+ const transport = yield* makePiRpcTransport({52+ binaryPath: piSettings.binaryPath || "pi",53+ args: [54+ "--mode",55+ "rpc",56+ "--no-session",57+ "--no-tools",58+ "--no-extensions",59+ "--thinking",60+ "off",61+ ...(input.modelSelection.model ? ["--model", input.modelSelection.model] : []),62+ ],63+ cwd: input.cwd,64+ env: environment,65+ onExit: Effect.void,66+ });67+ yield* transport.writeCommand({ type: "prompt", message: input.message });68+ yield* Stream.fromQueue(transport.messages).pipe(69+ Stream.takeUntil(
- apps/server/src/provider/Layers/PiRpcClient.ts line 255Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +235,21 @@235+ (entry as Record<string, unknown>)["name"] === commandName,236+ );237+}238+239+export function extractLastAssistantText(response: RpcResponse | undefined): string | null {240+ const text = piResponseData(response)?.["text"];241+ return typeof text === "string" ? text : null;242+}243+244+// fail-closed: a timeout (undefined) or mismatched command counts as failure245+export function piResponseSucceeded(response: RpcResponse | undefined, command: string): boolean {246+ return (247+ response !== undefined &&248+ response.type === "response" &&249+ response.success === true &&250+ (response as { command?: unknown }).command === command251+ );252+}253+254+// branch-scoped user messages (each with entryId) — the only valid fork targets255+export function extractForkMessages(apps/server/src/provider/Layers/PiAdapter.ts line 478Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +456,21 @@456+ ...(argsObj ? { data: { toolName: event.toolName, input: argsObj } } : {}),457+ },458+ });459+ return;460+ }461+462+ case "tool_execution_update": {463+ if (!context.turnState) return;464+ const partial = (event as { partialResult?: unknown }).partialResult;465+ if (partial === undefined) return;466+ const itemId = RuntimeItemId.make(event.toolCallId);467+ const itemType = classifyPiToolItemType(event.toolName);468+ const delta = typeof partial === "string" ? partial : String(partial);469+ if (delta.length === 0) return;470+ yield* offerRuntimeEvent({471+ ...base,472+ turnId: context.turnState.turnId,473+ itemId,474+ type: "content.delta",475+ payload: {476+ streamKind:apps/server/src/textGeneration/PiTextGeneration.ts line 92Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +24,21 @@24+} from "./TextGenerationUtils.ts";25+26+const PI_TIMEOUT_MS = 180_000;27+const PI_LAST_TEXT_TIMEOUT_MS = 5_000;28+29+type TextGenOperation =30+ | "generateCommitMessage"31+ | "generatePrContent"32+ | "generateBranchName"33+ | "generateThreadTitle";34+35+const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);36+const isTextGenerationError = Schema.is(TextGenerationError);37+38+export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (39+ piSettings: PiSettings,40+ environment: NodeJS.ProcessEnv = process.env,41+) {42+ const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;43+44+ const runPiPrompt = (input: {
- apps/server/src/provider/Layers/PiAdapter.ts line 1071OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1051,21 @@1051+ const requestedModel =1052+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined;1053+ const promptText = typeof input.input === "string" ? input.input : "";1054+ // resolve before mutating turn state so a bad attachment fails cleanly1055+ const images = yield* resolvePromptImages(input.attachments);1056+1057+ if (promptText.length === 0 && images.length === 0) {1058+ return yield* new ProviderAdapterValidationError({1059+ provider: PROVIDER,1060+ operation: "sendTurn",1061+ issue: "Pi turns require non-empty text or at least one attachment.",1062+ });1063+ }1064+1065+ // a message mid-turn steers the running turn; otherwise it opens a fresh one1066+ const isMidTurn = context.turnState !== undefined;1067+1068+ // only on a fresh turn — changing options mid-stream would race the active turn1069+ if (!isMidTurn) {1070+ yield* maybeSwitchPiModel(context, requestedModel);1071+ yield* applyThinkingLevel(context, input.modelSelection);apps/server/src/provider/Layers/PiAdapter.ts line 1128OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1108,21 @@1108+ const interruptTurn: PiAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(1109+ function* (threadId) {1110+ const context = yield* requireSession(threadId);1111+ yield* Effect.ignore(context.transport.writeCommand({ type: "abort" }));1112+ // settle bridged requests so Pi isn't left blocked (matches Cursor)1113+ yield* cancelPendingExtensionRequests(context);1114+ },1115+ );1116+1117+ const respondToRequest: PiAdapterShape["respondToRequest"] = Effect.fn("respondToRequest")(1118+ function* (threadId, requestId, decision: ProviderApprovalDecision) {1119+ const context = yield* requireSession(threadId);1120+ const pending = context.pendingApprovals.get(requestId);1121+ if (!pending) {1122+ return yield* new ProviderAdapterRequestError({1123+ provider: PROVIDER,1124+ method: "respondToRequest",1125+ detail: `Unknown pending approval request: ${requestId}.`,1126+ });1127+ }1128+ context.pendingApprovals.delete(requestId);
- apps/server/src/provider/Layers/PiAdapter.ts line 1067OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1047,21 @@1047+1048+ const sendTurn: PiAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {1049+ const context = yield* requireSession(input.threadId);1050+1051+ const modelSelection =1052+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;1053+ const requestedModel = modelSelection?.model;1054+ const promptText = typeof input.input === "string" ? input.input : "";1055+ // resolve before mutating turn state so a bad attachment fails cleanly1056+ const images = yield* resolvePromptImages(input.attachments);1057+1058+ if (promptText.length === 0 && images.length === 0) {1059+ return yield* new ProviderAdapterValidationError({1060+ provider: PROVIDER,1061+ operation: "sendTurn",1062+ issue: "Pi turns require non-empty text or at least one attachment.",1063+ });1064+ }1065+1066+ // a message mid-turn steers the running turn; otherwise it opens a fresh one1067+ const isMidTurn = context.turnState !== undefined;
juliusmarminge closed this
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
ec5b583a-09f5-4c4c-9130-4149e96a9a4dYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
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