feat(pi): add first-class Pi provider support #5688
Closeddarjss(GitHub profile, opens in a new tab)wants to merge 8 commits into
main fromrefs/pull/5688/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 +194,21 @@194+ }).pipe(195+ Effect.mapError((cause) =>196+ isTextGenerationError(cause)197+ ? cause198+ : 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+ ),@@ -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),@@ -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)}` })),
darjss(GitHub profile, opens in a new tab) closed this
- @@ -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] ?? "";@@ -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;@@ -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.client1348+ .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@@ -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) {@@ -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));@@ -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"] = (
- @@ -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;@@ -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+ }
- @@ -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;@@ -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+ });@@ -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] ?? "";@@ -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.");
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:
b93860e5-8e64-450a-b144-7bc340d6f1c7You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
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