Add Pi coding-agent provider #3818
Closedahmadaccino(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/3818/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/provider/Layers/PiAdapter.ts line 1152Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1176,21 @@1176+ threadId: context.session.threadId,1177+ turnId,1178+ payload: {},1179+ });1180+ }1181+1182+ const turnId = context.turnState.turnId;1183+1184+ yield* context.transport1185+ .writeCommand(buildPiTurnCommand({ isMidTurn, message: promptText, images }))1186+ .pipe(1187+ Effect.catchCause(() => completeTurn(context, "failed", "Failed to send message to Pi.")),1188+ );1189+1190+ return {1191+ threadId: context.session.threadId,1192+ turnId,1193+ ...(context.session.resumeCursor !== undefined1194+ ? { resumeCursor: context.session.resumeCursor }1195+ : {}),1196+ };apps/server/src/provider/Layers/PiAdapter.ts line 1276Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1289,21 @@1289+1290+ // Forking mid-stream is undefined; abort and finalize any live turn first.1291+ if (context.turnState) {1292+ yield* Effect.ignore(context.transport.writeCommand({ type: "abort" }));1293+ yield* completeTurn(context, "interrupted", "Turn interrupted for rollback.");1294+ }1295+1296+ // Resolve real fork targets from Pi's branch (durable across restart).1297+ const forkResponse = yield* context.transport.request(1298+ { type: "get_fork_messages" },1299+ `pi-fork-messages-${yield* nextUuid}`,1300+ PI_MESSAGES_TIMEOUT_MS,1301+ );1302+ const userMessages = extractForkMessages(forkResponse);1303+ const target = resolveForkTargetEntryId(userMessages, numTurns);1304+1305+ if (target === null) {1306+ // Nothing to roll back against Pi (no known history); keep the in-memory1307+ // bookkeeping consistent and return the current snapshot.1308+ context.turns.splice(Math.max(0, context.turns.length - numTurns));1309+ return yield* readThread(threadId);apps/server/src/provider/Layers/PiAdapter.ts line 1164Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1186,21 @@1186+ .pipe(1187+ Effect.catchCause(() => completeTurn(context, "failed", "Failed to send message to Pi.")),1188+ );1189+1190+ return {1191+ threadId: context.session.threadId,1192+ turnId,1193+ ...(context.session.resumeCursor !== undefined1194+ ? { resumeCursor: context.session.resumeCursor }1195+ : {}),1196+ };1197+ });1198+1199+ const interruptTurn: PiAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(1200+ function* (threadId) {1201+ const context = yield* requireSession(threadId);1202+ yield* Effect.ignore(context.transport.writeCommand({ type: "abort" }));1203+ // Aborting tears down the agent loop; settle any bridged extension-UI1204+ // requests so Pi is not left blocked awaiting a response (matches Cursor).1205+ yield* cancelPendingExtensionRequests(context);1206+ },apps/server/src/textGeneration/PiTextGeneration.ts line 87Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +77,21 @@77+ "--thinking",78+ "off",79+ ...(input.modelSelection.model ? ["--model", input.modelSelection.model] : []),80+ ],81+ cwd: input.cwd,82+ env: environment,83+ onExit: Effect.void,84+ });85+ yield* transport.writeCommand({ type: "prompt", message: input.message });86+ yield* Stream.fromQueue(transport.messages).pipe(87+ Stream.takeUntil(88+ (message) => message._tag === "event" && message.event.type === "agent_end",89+ ),90+ Stream.runDrain,91+ );92+ const response = yield* transport.request(93+ { type: "get_last_assistant_text" },94+ "pi-textgen-last-text",95+ PI_LAST_TEXT_TIMEOUT_MS,96+ );97+ return extractLastAssistantText(response) ?? "";apps/server/src/provider/Layers/PiAdapter.ts line 729Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +738,21 @@738+ for (const [, pending] of context.pendingApprovals) {739+ yield* Effect.ignore(740+ context.transport.writeExtensionResponse({741+ type: "extension_ui_response",742+ id: pending.piId,743+ confirmed: false,744+ }),745+ );746+ }747+ context.pendingApprovals.clear();748+ for (const [, pending] of context.pendingUserInputs) {749+ yield* Effect.ignore(750+ context.transport.writeExtensionResponse({751+ type: "extension_ui_response",752+ id: pending.piId,753+ cancelled: true,754+ }),755+ );756+ }757+ context.pendingUserInputs.clear();758+ });apps/server/src/provider/Layers/PiProvider.ts line 237Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +236,21 @@236+ // `~/.pi/agent`. Mirrors OpenCode (OpenCodeProvider.ts), which derives its237+ // verdict from the discovered-connection count.238+ const authenticated = models.length > 0;239+240+ return buildServerProvider({241+ presentation: PI_PRESENTATION,242+ enabled: piSettings.enabled,243+ checkedAt,244+ models,245+ probe: {246+ installed: true,247+ version: parsedVersion,248+ status: authenticated ? "ready" : "warning",249+ auth: { status: authenticated ? "authenticated" : "unknown", type: "pi" },250+ ...(authenticated251+ ? {}252+ : {253+ message:254+ "Pi is installed but no models are available. Configure a provider or API key in ~/.pi/agent (e.g. run `pi`) so models appear.",255+ }),256+ },apps/server/src/provider/Layers/PiAdapter.ts line 1122Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1159,21 @@1159+1160+ if (!context.turnState) {1161+ const turnId = TurnId.make(yield* nextUuid);1162+ const startedAt = yield* nowIso;1163+ context.turnState = { turnId, startedAt, items: [] };1164+ context.session = {1165+ ...context.session,1166+ status: "running",1167+ activeTurnId: turnId,1168+ updatedAt: startedAt,1169+ };1170+ const stamp = yield* makeEventStamp();1171+ yield* offerRuntimeEvent({1172+ ...stamp,1173+ type: "turn.started",1174+ provider: PROVIDER,1175+ providerInstanceId: boundInstanceId,1176+ threadId: context.session.threadId,1177+ turnId,1178+ payload: {},1179+ });
- apps/server/src/provider/assets/pi/t3-approvals.ts line 5Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +6,21 @@6+ * `auto-accept-edits`). Pi has no per-tool approval in its event stream, so this7+ * extension hooks the `tool_call` event (which runs *before* a tool executes and8+ * can veto it) and asks T3 Code to approve any tool that is not auto-approved9+ * (default-deny) via `ctx.ui.confirm(...)`.10+ *11+ * In RPC mode `ctx.ui.confirm` emits an `extension_ui_request` on stdout and12+ * awaits a matching `extension_ui_response` from T3 Code (the adapter bridges13+ * these to the canonical approval request/resolution runtime events). When the14+ * user declines — or there is no UI to ask — the tool call is blocked.15+ *16+ * This file is executed by the user's installed `pi` runtime, not bundled into17+ * the server. It imports types only.18+ */19+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";20+21+/**22+ * Read-only tools that never mutate the workspace and so run without approval.23+ * Everything NOT in this allowlist is gated (default-deny) — including unknown24+ * or custom tools, which must be approved rather than silently trusted.25+ */26+const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls", "glob"]);apps/server/src/provider/Layers/PiRpcClient.ts lines 53 to 56Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +70,21 @@70+ } catch {71+ return null;72+ }73+}74+75+/**76+ * Discriminate a decoded stdout object into a response, an extension-UI77+ * request, or an agent event.78+ */79+export function classifyPiStdoutMessage(msg: Record<string, unknown>): PiStdoutMessage | null {80+ const type = msg["type"];81+ if (type === "response") {82+ return {83+ _tag: "response",84+ id: typeof msg["id"] === "string" ? (msg["id"] as string) : undefined,85+ response: msg as unknown as RpcResponse,86+ };87+ }88+ if (type === "extension_ui_request") {89+ return { _tag: "extension-ui", request: msg as unknown as RpcExtensionUIRequest };90+ }apps/server/src/provider/Layers/PiProvider.ts line 238OutdatedResolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +218,21 @@218+ checkedAt,219+ models: fallbackModels,220+ probe: {221+ installed: true,222+ version: parsedVersion,223+ status: "error",224+ auth: { status: "unknown" },225+ message: detail ?? "Pi CLI returned an error during health check.",226+ },227+ });228+ }229+230+ const discovered = yield* discoverPiModelsViaRpc(piSettings, cwd, environment);231+ const models = modelsFromSettings(piSettings, discovered);232+233+ // Auth is inferred from live model discovery over the same RPC transport234+ // used for prompts: Pi has no login/auth query, and `get_available_models`235+ // only returns models once a provider/API key is configured in236+ // `~/.pi/agent`. Mirrors OpenCode (OpenCodeProvider.ts), which derives its237+ // verdict from the discovered-connection count.238+ const authenticated = models.length > 0;apps/server/src/provider/Layers/PiAdapter.ts line 1253Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1272,21 @@1272+ return {1273+ threadId,1274+ turns: context.turns.map((turn) => ({ id: turn.id, items: [...turn.items] })),1275+ };1276+ });1277+1278+ const rollbackThread: PiAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(1279+ function* (threadId, numTurns) {1280+ const context = yield* requireSession(threadId);1281+1282+ if (!Number.isInteger(numTurns) || numTurns < 1) {1283+ return yield* new ProviderAdapterValidationError({1284+ provider: PROVIDER,1285+ operation: "rollbackThread",1286+ issue: "numTurns must be an integer >= 1.",1287+ });1288+ }1289+1290+ // Forking mid-stream is undefined; abort and finalize any live turn first.1291+ if (context.turnState) {1292+ yield* Effect.ignore(context.transport.writeCommand({ type: "abort" }));apps/server/scripts/cli.ts lines 190 to 192Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -180,3 +180,17 @@180180 const webDist = path.join(repoRoot, "apps/web/dist");181181 const clientTarget = path.join(serverDir, "dist/client");182182183+ // The Pi approval-gate extension is loaded at runtime via a184+ // `import.meta.url`-relative path rather than bundled, so `vp pack` never185+ // emits it. Copy it next to the bundle at `dist/assets/pi` so the packaged186+ // server (and the desktop artifact, which ships `dist` verbatim) can187+ // resolve `./assets/pi/t3-approvals.ts` from `dist/bin.mjs`.188+ const piExtensionSource = path.join(serverDir, "src/provider/assets/pi/t3-approvals.ts");189+ const piAssetTargetDir = path.join(serverDir, "dist/assets/pi");190+ if (yield* fs.exists(piExtensionSource)) {191+ yield* fs.makeDirectory(piAssetTargetDir, { recursive: true });192+ yield* fs.copyFile(piExtensionSource, path.join(piAssetTargetDir, "t3-approvals.ts"));193+ yield* Effect.log("[cli] Bundled Pi approval extension into dist/assets/pi");194+ } else {195+ yield* Effect.logWarning("[cli] Pi approval extension not found — skipping asset copy.");196+ }apps/server/src/provider/Layers/PiRpcClient.ts line 379Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +477,21 @@477+ const deferred = pendingRequests.get(message.id);478+ if (deferred) {479+ pendingRequests.delete(message.id);480+ yield* Deferred.succeed(deferred, message.response);481+ }482+ }483+ return;484+ }485+ yield* Queue.offer(messages, message);486+ });487+488+ // Signal in-flight requests on process exit, then run the caller's onExit.489+ const onProcessExit = Deferred.succeed(closed, undefined).pipe(490+ Effect.andThen(Effect.sync(() => pendingRequests.clear())),491+ Effect.andThen(options.onExit),492+ );493+494+ // stdin writer495+ yield* Stream.fromQueue(outgoing).pipe(496+ Stream.run(child.stdin),497+ Effect.ignore,apps/server/src/provider/Layers/PiAdapter.ts line 1308Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1324,21 @@1324+ `pi-new-session-${yield* nextUuid}`,1325+ PI_FORK_TIMEOUT_MS,1326+ );1327+ if (!piForkSucceeded(rollbackResponse)) {1328+ return yield* new ProviderAdapterRequestError({1329+ provider: PROVIDER,1330+ method: target.kind === "fork" ? "fork" : "new_session",1331+ detail: "Pi rejected or cancelled the rollback.",1332+ });1333+ }1334+1335+ // CRITICAL: fork/new_session rebinds the session to a NEW session file.1336+ // Refresh the resume cursor via get_state, otherwise a later reconnect1337+ // would resume the stale pre-rollback branch and silently undo this.1338+ const stateResponse = yield* context.transport.request(1339+ { type: "get_state" },1340+ `pi-get-state-${yield* nextUuid}`,1341+ PI_STATE_TIMEOUT_MS,1342+ );1343+ const sessionFile = extractSessionFile(stateResponse);1344+ const updatedAt = yield* nowIso;apps/server/src/provider/Layers/PiRpcClient.ts line 255OutdatedResolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +235,21 @@235+ readonly provider: string;236+ readonly modelId: string;237+ readonly slug: string;238+ };239+240+/**241+ * Decide whether/how to switch the Pi model for a turn. Returns `noop` when no242+ * model is requested or it already matches the running one, `invalid` for a243+ * malformed slug, or `switch` with the split `provider`/`modelId`.244+ */245+export function planPiModelSwitch(246+ currentModel: string | undefined,247+ requestedModel: string | undefined,248+): PiModelSwitchPlan {249+ if (requestedModel === undefined || requestedModel === currentModel) return { kind: "noop" };250+ const parts = splitPiModelSlug(requestedModel);251+ if (!parts) return { kind: "invalid", slug: requestedModel };252+ return { kind: "switch", provider: parts.provider, modelId: parts.id, slug: requestedModel };253+}254+255+/** Capabilities descriptor for a Pi model — reasoning models expose thinking. */@@ -132,3 +132,4 @@132132 const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");133133 const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");134134 const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");135+const PI_DRIVER_KIND = ProviderDriverKind.make("pi");apps/server/src/provider/Layers/PiAdapter.ts line 227Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +253,21 @@253+ * Parse a numbered-list prompt (Pi's RPC multi-select fallback encodes options254+ * as `Title\n1. A\n2. B`). Returns the title + option labels, or `null`.255+ */256+export function parseNumberedList(257+ text: string,258+): { title: string; items: ReadonlyArray<string> } | null {259+ const lines = text.split("\n");260+ const items: string[] = [];261+ for (const line of lines.slice(1)) {262+ const match = /^\d+\.\s+(.+)$/.exec(line.trim());263+ if (match?.[1]) items.push(match[1]);264+ }265+ return items.length >= 2 ? { title: lines[0] ?? text, items } : null;266+}267+268+/**269+ * Map an approval decision onto the boolean `confirmed` flag that Pi's270+ * `confirm` extension-UI response expects. Accept / accept-for-session both271+ * confirm the gated tool call; everything else rejects it.272+ */273+export function isPiApprovalConfirmed(decision: ProviderApprovalDecision): boolean {
- apps/server/src/textGeneration/PiTextGeneration.ts lines 23 to 12OutdatedResolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1,12 @@1+/**2+ * PiTextGeneration - stateless one-shot text generation via Pi's RPC mode.3+ *4+ * Runs a stateless `pi --mode rpc --no-session --no-tools --no-extensions`5+ * completion, waits for `agent_end`, then reads the clean final answer via the6+ * `get_last_assistant_text` RPC (instead of scraping `--print` stdout). The7+ * returned text is decoded with the shared `extractJsonObject` helper, sharing8+ * the common prompt builders and sanitizers with the sibling providers.9+ *10+ * @module textGeneration/PiTextGeneration11+ */12+import * as Effect from "effect/Effect";apps/server/src/textGeneration/PiTextGeneration.ts lines 160 to 168OutdatedResolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +148,21 @@148+149+ const rawResult = yield* runPiPrompt({150+ message:151+ `${prompt}\n\nRespond ONLY with minified JSON matching this schema. ` +152+ `No markdown, no code fences, no prose:\n${schemaJson}`,153+ cwd,154+ modelSelection,155+ operation,156+ });157+158+ const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));159+ return yield* decodeOutput(extractJsonObject(rawResult)).pipe(160+ Effect.catchTag("SchemaError", (cause) =>161+ Effect.fail(162+ new TextGenerationError({163+ operation,164+ detail: "Pi returned invalid structured output.",165+ cause,166+ }),167+ ),168+ ),
- apps/server/src/provider/Layers/PiRpcClient.ts lines 226 to 237Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +292,21 @@292+ return data !== null && typeof data === "object" ? (data as Record<string, unknown>) : null;293+}294+295+/**296+ * Read the `sessionFile` path from a `get_state` response, for use as a resume297+ * cursor. Returns `undefined` when the response is missing or unsuccessful.298+ */299+export function extractSessionFile(response: RpcResponse | undefined): string | undefined {300+ const sessionFile = piResponseData(response)?.["sessionFile"];301+ return typeof sessionFile === "string" && sessionFile.trim().length > 0302+ ? sessionFile.trim()303+ : undefined;304+}305+306+/** Read the `models` array from a `get_available_models` response. */307+export function extractAvailableModels(308+ response: RpcResponse | undefined,309+): ReadonlyArray<ModelInfo> {310+ const models = piResponseData(response)?.["models"];311+ return Array.isArray(models) ? (models as ReadonlyArray<ModelInfo>) : [];312+}apps/server/src/textGeneration/PiTextGeneration.ts line 73Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +66,21 @@66+ readonly operation: TextGenOperation;67+ }): Effect.Effect<string, TextGenerationError> =>68+ Effect.gen(function* () {69+ const transport = yield* makePiRpcTransport({70+ binaryPath: piSettings.binaryPath || "pi",71+ args: [72+ "--mode",73+ "rpc",74+ "--no-session",75+ "--no-tools",76+ "--no-extensions",77+ "--thinking",78+ "off",79+ ...(input.modelSelection.model ? ["--model", input.modelSelection.model] : []),80+ ],81+ cwd: input.cwd,82+ env: environment,83+ onExit: Effect.void,84+ });85+ yield* transport.writeCommand({ type: "prompt", message: input.message });86+ yield* Stream.fromQueue(transport.messages).pipe(apps/server/src/provider/Layers/PiAdapter.ts lines 210 to 213OutdatedResolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +193,21 @@193+// ---------------------------------------------------------------------------194+// Pure classification helpers195+// ---------------------------------------------------------------------------196+197+export function classifyPiToolItemType(toolName: string): CanonicalItemType {198+ // Match on whole tokens (split on camelCase / separators) rather than raw199+ // substrings, so e.g. "recommend" is not misread as a "command" tool.200+ const tokens = new Set(201+ toolName202+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")203+ .replace(/[._/-]/g, " ")204+ .toLowerCase()205+ .split(/\s+/)206+ .filter((token) => token.length > 0),207+ );208+ const has = (...words: ReadonlyArray<string>): boolean => words.some((word) => tokens.has(word));209+210+ if (has("agent", "subagent", "task", "skill")) return "collab_agent_tool_call";211+ if (has("bash", "shell", "command", "terminal", "exec")) return "command_execution";212+ if (has("edit", "write", "patch", "apply", "file")) return "file_change";213+ if (has("mcp")) return "mcp_tool_call";apps/server/src/provider/Layers/PiAdapter.ts line 215Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +236,21 @@236+ if (!args || typeof args !== "object") return undefined;237+ const input = args as Record<string, unknown>;238+ const command = input["command"] ?? input["cmd"];239+ if (typeof command === "string" && command.trim().length > 0) return command.trim().slice(0, 400);240+ const path = input["file_path"] ?? input["path"] ?? input["filePath"];241+ if (typeof path === "string" && path.trim().length > 0) return path.trim().slice(0, 400);242+ const pattern = input["pattern"] ?? input["query"] ?? input["description"];243+ if (typeof pattern === "string" && pattern.trim().length > 0) return pattern.trim().slice(0, 400);244+ try {245+ const serialized = JSON.stringify(input);246+ return serialized.length <= 400 ? serialized : `${serialized.slice(0, 397)}...`;247+ } catch {248+ return undefined;249+ }250+}251+252+/**253+ * Parse a numbered-list prompt (Pi's RPC multi-select fallback encodes options254+ * as `Title\n1. A\n2. B`). Returns the title + option labels, or `null`.255+ */256+export function parseNumberedList(
- apps/server/src/provider/Layers/PiAdapter.ts line 1314Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1330,21 @@1330+ method: target.kind === "fork" ? "fork" : "new_session",1331+ detail: "Pi rejected or cancelled the rollback.",1332+ });1333+ }1334+1335+ // CRITICAL: fork/new_session rebinds the session to a NEW session file.1336+ // Refresh the resume cursor via get_state, otherwise a later reconnect1337+ // would resume the stale pre-rollback branch and silently undo this.1338+ const stateResponse = yield* context.transport.request(1339+ { type: "get_state" },1340+ `pi-get-state-${yield* nextUuid}`,1341+ PI_STATE_TIMEOUT_MS,1342+ );1343+ const sessionFile = extractSessionFile(stateResponse);1344+ const updatedAt = yield* nowIso;1345+ context.session = {1346+ ...context.session,1347+ status: "ready",1348+ updatedAt,1349+ ...(sessionFile !== undefined ? { resumeCursor: { sessionFile } } : {}),1350+ };apps/server/src/provider/Layers/PiAdapter.ts line 1330Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1335,21 @@1335+ // CRITICAL: fork/new_session rebinds the session to a NEW session file.1336+ // Refresh the resume cursor via get_state, otherwise a later reconnect1337+ // would resume the stale pre-rollback branch and silently undo this.1338+ const stateResponse = yield* context.transport.request(1339+ { type: "get_state" },1340+ `pi-get-state-${yield* nextUuid}`,1341+ PI_STATE_TIMEOUT_MS,1342+ );1343+ const sessionFile = extractSessionFile(stateResponse);1344+ const updatedAt = yield* nowIso;1345+ context.session = {1346+ ...context.session,1347+ status: "ready",1348+ updatedAt,1349+ ...(sessionFile !== undefined ? { resumeCursor: { sessionFile } } : {}),1350+ };1351+1352+ // Trim the in-memory turn skeleton to match Pi's now-shorter branch.1353+ context.turns.splice(Math.max(0, context.turns.length - numTurns));1354+1355+ return yield* readThread(threadId);
- apps/server/src/provider/Layers/PiAdapter.ts line 1127Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1164,21 @@1164+ context.session = {1165+ ...context.session,1166+ status: "running",1167+ activeTurnId: turnId,1168+ updatedAt: startedAt,1169+ };1170+ const stamp = yield* makeEventStamp();1171+ yield* offerRuntimeEvent({1172+ ...stamp,1173+ type: "turn.started",1174+ provider: PROVIDER,1175+ providerInstanceId: boundInstanceId,1176+ threadId: context.session.threadId,1177+ turnId,1178+ payload: {},1179+ });1180+ }1181+1182+ const turnId = context.turnState.turnId;1183+1184+ yield* context.transport
- apps/server/src/provider/Layers/PiAdapter.ts line 584Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +626,21 @@626+ ): Effect.Effect<void> =>627+ Effect.gen(function* () {628+ // Fire-and-forget UI side-effects — Pi does not await a response.629+ if (630+ request.method === "notify" ||631+ request.method === "setStatus" ||632+ request.method === "setWidget" ||633+ request.method === "setTitle" ||634+ request.method === "set_editor_text"635+ ) {636+ return;637+ }638+639+ const stamp = yield* makeEventStamp();640+ const requestId = ApprovalRequestId.make(yield* nextUuid);641+ const runtimeRequestId = RuntimeRequestId.make(requestId);642+ const turnId = context.turnState?.turnId;643+644+ // `confirm` → approval request (respondToRequest bridges the decision).645+ if (request.method === "confirm") {646+ const requestType = classifyPiApprovalRequestType(request.title);
- apps/server/src/provider/Layers/PiProvider.ts line 44Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +23,21 @@23+import {24+ extractAvailableModels,25+ makePiRpcTransport,26+ piModelInfoToServerModel,27+} from "./PiRpcClient.ts";28+29+const PROVIDER = ProviderDriverKind.make("pi");30+31+const PI_PRESENTATION = {32+ displayName: "Pi",33+ badgeLabel: "Early Access",34+ showInteractionModeToggle: true,35+} as const;36+37+const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [] });38+39+const PI_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;40+41+const nowIso = Effect.map(DateTime.now, DateTime.formatIso);42+43+const runPiVersion = (piSettings: PiSettings, environment: NodeJS.ProcessEnv) =>apps/server/src/textGeneration/PiTextGeneration.ts line 59OutdatedResolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+ piSettings: PiSettings,40+ environment: NodeJS.ProcessEnv = process.env,41+) {42+ const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;43+44+ const runPiPrompt = (input: {45+ readonly message: string;46+ readonly cwd: string;47+ readonly modelSelection: ModelSelection;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",
- apps/server/src/provider/Layers/PiAdapter.ts line 704Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +684,21 @@684+ // settle+clear pending extension-UI requests so Pi is never left blocked685+ const cancelPendingExtensionRequests = (context: PiSessionContext): Effect.Effect<void> =>686+ Effect.gen(function* () {687+ for (const [requestId, pending] of context.pendingApprovals) {688+ yield* Effect.ignore(689+ context.transport.writeExtensionResponse({690+ type: "extension_ui_response",691+ id: pending.piId,692+ confirmed: false,693+ }),694+ );695+ const stamp = yield* makeEventStamp();696+ yield* offerRuntimeEvent({697+ ...stamp,698+ type: "request.resolved",699+ provider: PROVIDER,700+ providerInstanceId: boundInstanceId,701+ threadId: context.session.threadId,702+ ...(context.turnState ? { turnId: context.turnState.turnId } : {}),703+ requestId: RuntimeRequestId.make(requestId),704+ payload: { requestType: pending.requestType, decision: "decline" },apps/server/src/provider/Layers/PiAdapter.ts lines 1309 to 1314Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1294,21 @@1294+ provider: PROVIDER,1295+ method: target.kind === "fork" ? "fork" : "new_session",1296+ detail: "Pi rejected or cancelled the rollback.",1297+ });1298+ }1299+1300+ // CRITICAL: fork/new_session rebinds to a new session file — refresh the1301+ // resume cursor or a later reconnect resumes the stale pre-rollback branch1302+ const stateResponse = yield* context.transport.request(1303+ { type: "get_state" },1304+ `pi-get-state-${yield* nextUuid}`,1305+ PI_STATE_TIMEOUT_MS,1306+ );1307+ const sessionFile = extractSessionFile(stateResponse);1308+ const updatedAt = yield* nowIso;1309+ context.session = {1310+ ...context.session,1311+ status: "ready",1312+ updatedAt,1313+ resumeCursor: sessionFile !== undefined ? { sessionFile } : undefined,1314+ };apps/server/src/provider/Layers/PiAdapter.ts line 489Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +469,21 @@469+ ...(detail ? { detail } : {}),470+ ...(argsObj ? { data: { toolName: event.toolName, input: argsObj } } : {}),471+ },472+ });473+ return;474+ }475+476+ case "tool_execution_update": {477+ if (!context.turnState) return;478+ const partial = (event as { partialResult?: unknown }).partialResult;479+ if (partial === undefined) return;480+ const itemId = RuntimeItemId.make(event.toolCallId);481+ const itemType = classifyPiToolItemType(event.toolName);482+ const delta = typeof partial === "string" ? partial : String(partial);483+ if (delta.length === 0) return;484+ yield* offerRuntimeEvent({485+ ...base,486+ turnId: context.turnState.turnId,487+ itemId,488+ type: "content.delta",489+ payload: {apps/server/src/provider/assets/pi/t3-approvals.ts lines 8 to 11Resolvedby ahmadaccino(GitHub profile, opens in a new tab)@@ -0,0 +1,11 @@1+// Default-deny tool-approval gate, loaded into `pi --mode rpc` via `--extension`.2+// Runs in the user's `pi` runtime (types-only import).3+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";4+5+const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls", "glob"]);6+const EDIT_TOOLS = ["write", "edit", "multi_edit", "apply_patch"];7+8+function autoApprovedTools(approvalMode: string | undefined): ReadonlySet<string> {9+ if (approvalMode !== "auto-accept-edits") return new Set();10+ return new Set([...READ_ONLY_TOOLS, ...EDIT_TOOLS]);11+}
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:
a613f2cf-319d-4d4a-bd8d-c4c7e409b6a4You 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