feat: Add Pi Coding agent as a provider #3947
Closed1337hero(GitHub profile, opens in a new tab)wants to merge 9 commits into
main fromrefs/pull/3947/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
- @@ -0,0 +205,21 @@205+ event: PiRpcEvent,206+ toolName: string,207+): string {208+ const key = toolName;209+ const pending = context.fallbackToolCallIds.get(key);210+ const explicit =211+ "toolCallId" in event &&212+ typeof event.toolCallId === "string" &&213+ event.toolCallId.trim().length > 0214+ ? event.toolCallId.trim()215+ : undefined;216+ if (event.type === "tool_execution_start") {217+ const itemId = explicit ?? mintToolItemId(context);218+ if (pending) {219+ pending.push(itemId);220+ } else {221+ context.fallbackToolCallIds.set(key, [itemId]);222+ }223+ return itemId;224+ }225+ if (explicit) {@@ -0,0 +139,21 @@139+}140+141+export interface PiRpcResponse {142+ readonly type: "response";143+ readonly id?: string;144+ readonly command: string;145+ readonly success: boolean;146+ readonly error?: string;147+ readonly data?: unknown;148+}149+150+const PiRpcResponseWithId = Schema.Struct({151+ type: Schema.Literal("response"),152+ id: Schema.String,153+ command: Schema.String,154+ success: Schema.Boolean,155+ error: Schema.optionalKey(Schema.String),156+ data: Schema.optionalKey(Schema.Unknown),157+});158+159+const PiContentBlock = Schema.Struct({@@ -0,0 +1364,21 @@1364+ turns.push({ id: TurnId.make(`pi-snapshot-turn-${turns.length}`), items: [message] });1365+ continue;1366+ }1367+ if (turns.length === 0) {1368+ turns.push({ id: TurnId.make(`pi-snapshot-turn-${turns.length}`), items: [] });1369+ }1370+ turns[turns.length - 1]?.items.push(message);1371+ }1372+ return { threadId, turns };1373+ });1374+1375+ const rollbackThread: PiAdapterShape["rollbackThread"] = (threadId) =>1376+ Effect.fail(1377+ new ProviderAdapterRequestError({1378+ provider: PROVIDER,1379+ method: "rollbackThread",1380+ detail: `Pi does not support rolling back thread ${threadId} turns in place. Fork the session from Pi's own UI instead.`,1381+ }),1382+ );1383+1384+ const stopAll: PiAdapterShape["stopAll"] = () =>
- @@ -0,0 +1063,21 @@1063+ threadId: input.threadId,1064+ createdAt,1065+ updatedAt: createdAt,1066+ };1067+ const context: PiSessionContext = {1068+ session,1069+ rpc: started.rpc,1070+ pendingApprovals: new Map(),1071+ pendingDialogs: new Map(),1072+ activeTurnId: undefined,1073+ currentModelSlug: input.modelSelection?.model,1074+ currentThinking: thinkingLevel,1075+ lastStopReason: undefined,1076+ messageSequence: 0,1077+ toolSequence: 0,1078+ compactionSequence: 0,1079+ fallbackToolCallIds: new Map(),1080+ stopped: yield* Ref.make(false),1081+ sessionScope: started.sessionScope,1082+ };1083+ sessions.set(input.threadId, context);@@ -0,0 +1162,21 @@1162+ issue: "Pi model selection must use the 'provider/model' format.",1163+ });1164+ }1165+ yield* context.rpc1166+ .request({1167+ type: "set_model",1168+ provider: parsedModel.provider,1169+ modelId: parsedModel.modelId,1170+ })1171+ .pipe(Effect.mapError(toRequestError));1172+ nextModelSlug = modelSelection.model;1173+ }1174+ const thinkingLevel = getModelSelectionStringOptionValue(modelSelection, "thinking");1175+ if (thinkingLevel && thinkingLevel !== context.currentThinking) {1176+ yield* context.rpc1177+ .request({ type: "set_thinking_level", level: thinkingLevel })1178+ .pipe(Effect.mapError(toRequestError));1179+ nextThinking = thinkingLevel;1180+ }1181+ context.currentModelSlug = nextModelSlug;1182+ context.currentThinking = nextThinking;@@ -0,0 +804,21 @@804+ payload,805+ });806+ break;807+ }808+809+ case "agent_end": {810+ if (!turnId) break;811+ yield* settlePendingRequestsAsCancelled(context);812+ context.activeTurnId = undefined;813+ const failed = context.lastStopReason === "error";814+ context.lastStopReason = undefined;815+ yield* updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });816+ yield* emit({817+ ...(yield* buildEventBase({ threadId, turnId })),818+ type: "turn.completed",819+ payload: failed820+ ? { state: "failed", errorMessage: "Pi reported an error while completing the turn." }821+ : { state: "completed" },822+ });823+ yield* emitTokenUsage(context);824+ break;@@ -0,0 +60,21 @@60+}61+62+export const PI_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"] as const;63+64+export const PI_APPROVAL_TITLE_PREFIX = "T3_APPROVAL ";65+export const PI_APPROVAL_PROTOCOL_VERSION = 1;66+export const PI_APPROVAL_OPTION_ALLOW = "allow";67+export const PI_APPROVAL_OPTION_ALLOW_ALWAYS = "allow-always";68+export const PI_APPROVAL_OPTION_DENY = "deny";69+export const PI_RUNTIME_MODE_ENV = "T3CODE_PI_RUNTIME_MODE";70+71+export const PI_APPROVAL_EXTENSION_SOURCE = `\72+const MODE = process.env["${PI_RUNTIME_MODE_ENV}"] ?? "approval-required";73+74+export default function t3codeApprovals(pi) {75+ const alwaysAllowed = new Set();76+ pi.on("tool_call", async (event, ctx) => {77+ if (MODE === "full-access") return;78+ const tool = event.toolName;79+ const isEditTool = tool === "edit" || tool === "write";80+ const gated = tool === "bash" || (isEditTool && MODE !== "auto-accept-edits");@@ -0,0 +405,21 @@405+ })),406+ );407+408+ yield* Effect.addFinalizer(() =>409+ Effect.gen(function* () {410+ const contexts = [...sessions.values()];411+ sessions.clear();412+ yield* Effect.forEach(413+ contexts,414+ (context) =>415+ Effect.gen(function* () {416+ yield* Effect.ignoreCause(settlePendingRequestsAsCancelled(context));417+ yield* Effect.ignoreCause(stopPiContext(context));418+ }),419+ { concurrency: "unbounded", discard: true },420+ );421+ }).pipe(Effect.ensuring(Queue.shutdown(runtimeEvents))),422+ );423+424+ const emit = (event: ProviderRuntimeEvent) =>425+ Queue.offer(runtimeEvents, event).pipe(Effect.asVoid);
1337hero(GitHub profile, opens in a new tab) closed this
- @@ -0,0 +581,21 @@581+ yield* Effect.logWarning("Dropped non-JSON-encodable Pi RPC notification.");582+ return;583+ }584+ yield* Queue.offer(stdinQueue, `${encodedExit.value}\n`);585+ });586+587+ return { request, notify, events, exitCode, stderr } satisfies PiRpcHandle;588+ });589+590+export interface PiRuntimeShape {591+ readonly runCommand: (input: {592+ readonly binaryPath: string;593+ readonly args: ReadonlyArray<string>;594+ readonly environment?: NodeJS.ProcessEnv;595+ readonly cwd?: string;596+ readonly stdin?: string;597+ }) => Effect.Effect<PiCommandResult, PiRuntimeError>;598+ readonly spawnSession: (599+ input: SpawnPiRpcInput,600+ ) => Effect.Effect<PiRpcHandle, PiRuntimeError, Scope.Scope>;601+}
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
Run ID:
dd009d08-98f7-4789-85bd-4ae108d7338cYou 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