feat(providers): add Pi coding agent #7211
MergedStiensWout(GitHub profile, opens in a new tab)merged 79 commits into
t3code/codex-turn-mapping fromrefs/pull/7211/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/Adapters/PiRpc.ts lines 298 to 302OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +158,21 @@158+ yield* Stream.fromQueue(outgoing).pipe(159+ Stream.run(child.stdin),160+ Effect.catchCause((cause) => failTransport(new PiRpcError({ operation: "write", cause }))),161+ Effect.forkIn(scope),162+ );163+164+ const routeRecord = (record: PiRpcRecord) =>165+ Effect.gen(function* () {166+ if (record["type"] === "response" && typeof record["id"] === "string") {167+ const pending = pendingRequests.get(record["id"]);168+ if (pending !== undefined) {169+ pendingRequests.delete(record["id"]);170+ if (record["success"] === true) {171+ yield* Deferred.succeed(pending.deferred, record["data"]);172+ } else {173+ yield* Deferred.fail(174+ pending.deferred,175+ new PiRpcError({176+ operation: String(record["command"] ?? "request"),177+ detail: String(record["error"] ?? "unknown error"),178+ }),apps/server/src/provider/Drivers/PiDriver.ts lines 163 to 163OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +143,21 @@143+ getSettings: snapshotSettings.getSettings,144+ streamSettings: snapshotSettings.streamSettings,145+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,146+ initialSnapshot: (settings) =>147+ buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),148+ checkProvider,149+ enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>150+ enrichPiSnapshot({151+ snapshot: currentSnapshot,152+ maintenanceCapabilities,153+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,154+ publishSnapshot,155+ httpClient,156+ }),157+ }).pipe(158+ Effect.mapError(159+ (cause) =>160+ new ProviderDriverError({161+ driver: DRIVER_KIND,162+ instanceId,163+ detail: `Failed to build Pi snapshot: ${cause.message ?? String(cause)}`,
- apps/web/src/components/chat/providerIconUtils.ts line 20OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -8,3 +8,4 @@88 [ProviderDriverKind.make("opencode")]: OpenCodeIcon,99 [ProviderDriverKind.make("cursor")]: CursorIcon,1010 [ProviderDriverKind.make("grok")]: GrokIcon,11+ [ProviderDriverKind.make("pi")]: PiAgentIcon,
- apps/server/src/provider/Layers/PiProvider.ts lines 76 to 77OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+});58+59+/**60+ * Reasoning-capable Pi models expose Pi's thinking levels. "Inherit" leaves61+ * the user's settings.json `defaultThinkingLevel` untouched.62+ */63+const THINKING_CAPABILITIES: ModelCapabilities = createModelCapabilities({64+ optionDescriptors: [65+ {66+ id: "thinking",67+ label: "Thinking",68+ type: "select",69+ options: [70+ { id: "inherit", label: "Pi default", isDefault: true },71+ { id: "off", label: "Off" },72+ { id: "minimal", label: "Minimal" },73+ { id: "low", label: "Low" },74+ { id: "medium", label: "Medium" },75+ { id: "high", label: "High" },76+ { id: "xhigh", label: "Extra high" },77+ { id: "max", label: "Max" },apps/server/src/textGeneration/PiTextGeneration.ts line 91OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +47,21 @@47+ modelSelection,48+ }: {49+ operation:50+ | "generateCommitMessage"51+ | "generatePrContent"52+ | "generateBranchName"53+ | "generateThreadTitle";54+ cwd: string;55+ prompt: string;56+ outputSchemaJson: S;57+ modelSelection: ModelSelection;58+ }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>59+ Effect.gen(function* () {60+ const connection = yield* makePiRpcConnection({61+ command: piSettings.binaryPath || "pi",62+ args: ["--mode", "rpc", "--no-session", ...tokenizeCliArgs(piSettings.launchArgs)],63+ cwd,64+ env: environment,65+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));66+67+ if (modelSelection.model !== "default") {apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 2458OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1340,21 @@1340+ Effect.mapError(1341+ (cause) =>1342+ new ProviderAdapterInterruptError({1343+ driver: PI_PROVIDER,1344+ providerThreadId: interruptInput.providerThread.id,1345+ providerTurnId: interruptInput.providerTurnId,1346+ cause,1347+ }),1348+ ),1349+ ),1350+ respondToRuntimeRequest: (requestInput) =>1351+ Effect.gen(function* () {1352+ const pending = pendingPrompts.get(String(requestInput.requestId));1353+ if (pending === undefined) {1354+ return yield* protocolError(1355+ `No pending Pi extension request ${requestInput.requestId}`,1356+ );1357+ }1358+ pendingPrompts.delete(String(requestInput.requestId));1359+ const response = piUiResponse(pending, requestInput.decision, requestInput.answers);1360+ yield* connection.send({apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts lines 1358 to 1364OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1344,21 @@1344+ providerThreadId: interruptInput.providerThread.id,1345+ providerTurnId: interruptInput.providerTurnId,1346+ cause,1347+ }),1348+ ),1349+ ),1350+ respondToRuntimeRequest: (requestInput) =>1351+ Effect.gen(function* () {1352+ const pending = pendingPrompts.get(String(requestInput.requestId));1353+ if (pending === undefined) {1354+ return yield* protocolError(1355+ `No pending Pi extension request ${requestInput.requestId}`,1356+ );1357+ }1358+ pendingPrompts.delete(String(requestInput.requestId));1359+ const response = piUiResponse(pending, requestInput.decision, requestInput.answers);1360+ yield* connection.send({1361+ type: "extension_ui_response",1362+ id: pending.nativeRequestId,1363+ ...response,1364+ });apps/server/src/provider/Layers/PiProvider.ts lines 166 to 136OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ return typeof value === "string" ? value : undefined;117+}118+119+function parseDiscoveredModels(data: unknown): ReadonlyArray<ServerProviderModel> {120+ const models = recordField(data, "models");121+ if (!Array.isArray(models)) return [];122+ const seen = new Set<string>();123+ const parsed: Array<ServerProviderModel> = [];124+ for (const model of models) {125+ const provider = recordString(model, "provider");126+ const id = recordString(model, "id");127+ if (provider === undefined || id === undefined) continue;128+ const slug = `${provider}/${id}`;129+ if (seen.has(slug)) continue;130+ seen.add(slug);131+ parsed.push({132+ slug,133+ name: recordString(model, "name") ?? slug,134+ isCustom: false,135+ capabilities:136+ recordField(model, "reasoning") === true ? THINKING_CAPABILITIES : EMPTY_CAPABILITIES,apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1269OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1249,21 @@1249+ itemOrdinals: new Map(),1250+ nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1,1251+ messageOrdinal: 0,1252+ streamItems: new Map(),1253+ toolArgs: new Map(),1254+ interrupted: false,1255+ failure: null,1256+ };1257+ yield* emit({1258+ type: "provider_turn.updated",1259+ driver: PI_PROVIDER,1260+ threadId: turnInput.threadId,1261+ providerTurn,1262+ });1263+ yield* updateProviderThread(state, {1264+ status: "active",1265+ firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,1266+ lastRunOrdinal: turnInput.runOrdinal,1267+ });1268+ yield* updateProviderSession("running", null);1269+ const payload = yield* resolvePromptPayload(apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1120OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1100,21 @@1100+ status: "idle",1101+ firstRunOrdinal: null,1102+ lastRunOrdinal: null,1103+ handoffIds: [],1104+ forkedFrom: null,1105+ pendingBackgroundTasks: [],1106+ createdAt,1107+ updatedAt: createdAt,1108+ };1109+ threadState = { providerThread, activeTurn: null };1110+ yield* emit({1111+ type: "provider_thread.updated",1112+ driver: PI_PROVIDER,1113+ providerThread,1114+ });1115+ return providerThread;1116+ });1117+1118+ const applySelection = Effect.fnUntraced(function* (modelSelection: ModelSelection) {1119+ if (1120+ modelSelection.model !== PI_INHERIT_MODEL_SLUG &&
- apps/web/src/components/Icons.tsx lines 691 to 691OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -686,5 +686,6 @@686686 );687687688688 export const PiAgentIcon: Icon = ({ className, ...props }) => (689- <svg {...props} viewBox="0 0 800 800" className={cn("fill-none", className)}>690- <rect width="800" height="800" rx="160" fill="#000" />689+ <svg690+ {...props}691+ viewBox="0 0 800 800"
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts lines 1074 to 1077OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1057,21 @@1057+ driver: PI_PROVIDER,1058+ providerSessionId: input.providerSessionId,1059+ cause,1060+ }),1061+ );1062+ }),1063+ ),1064+ Effect.forkIn(scope),1065+ );1066+1067+ // ── session runtime ───────────────────────────────────1068+1069+ const registerThread = Effect.fnUntraced(function* (1070+ threadInput: ProviderAdapterV2EnsureThreadInput,1071+ ) {1072+ const existing = threadInput.existingProviderThread;1073+ if (existing?.nativeThreadRef?.nativeId != null) {1074+ yield* request({1075+ type: "switch_session",1076+ sessionPath: existing.nativeThreadRef.nativeId,1077+ });apps/server/src/orchestration-v2/Adapters/PiRpc.ts line 268OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +248,21 @@248+ Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),249+ onSuccess: (code) => Deferred.succeed(exitDeferred, Number(code)),250+ }),251+ Effect.forkIn(scope),252+ );253+254+ yield* Scope.addFinalizer(255+ scope,256+ terminatePiProcess(Number(child.pid), killProcessGroup).pipe(257+ Effect.ignore,258+ Effect.uninterruptible,259+ ),260+ );261+262+ const send = (record: PiRpcRecord): Effect.Effect<void, PiRpcError> =>263+ Effect.gen(function* () {264+ const down = yield* Deferred.isDone(transportDown);265+ if (down) {266+ return yield* Deferred.await(transportDown);267+ }268+ yield* Queue.offer(outgoing, new TextEncoder().encode(`${encodeJsonLine(record)}\n`));apps/server/src/orchestration-v2/Adapters/PiRpc.ts line 206OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ return undefined;105+ }106+}107+108+/** Kill the pi process group: SIGTERM, short grace, then SIGKILL. */109+const terminatePiProcess = (pid: number, kill: (signal: NodeJS.Signals) => boolean) =>110+ Effect.gen(function* () {111+ if (!kill("SIGTERM")) return;112+ yield* Effect.sleep(TERMINATION_GRACE);113+ kill("SIGKILL");114+ });115+116+export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {117+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;118+ const platform = yield* HostProcessPlatform;119+ const scope = yield* Effect.scope;120+121+ const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {122+ env: options.env,123+ }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));124+ const child = yield* spawner
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 2013OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1068,21 @@1068+1069+ const registerThread = Effect.fnUntraced(function* (1070+ threadInput: ProviderAdapterV2EnsureThreadInput,1071+ ) {1072+ const existing = threadInput.existingProviderThread;1073+ if (existing?.nativeThreadRef?.nativeId != null) {1074+ yield* request({1075+ type: "switch_session",1076+ sessionPath: existing.nativeThreadRef.nativeId,1077+ });1078+ }1079+ const stateData = yield* request({ type: "get_state" });1080+ if (baselineModel === null && baselineThinking === null) {1081+ const stateModel = recordField(stateData, "model");1082+ const provider = recordString(stateModel, "provider");1083+ const modelId = recordString(stateModel, "id");1084+ if (provider !== undefined && modelId !== undefined) {1085+ baselineModel = { provider, modelId };1086+ }1087+ baselineThinking = recordString(stateData, "thinkingLevel") ?? null;1088+ }apps/server/src/orchestration-v2/Adapters/PiRpc.ts line 301OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +168,21 @@168+ // silently queueing into a dead pipe.169+ yield* Stream.fromQueue(outgoing).pipe(170+ Stream.run(child.stdin),171+ Effect.catchCause((cause) => failTransport(new PiRpcError({ operation: "write", cause }))),172+ Effect.forkIn(scope),173+ );174+175+ const routeRecord = (record: PiRpcRecord) =>176+ Effect.gen(function* () {177+ if (record["type"] === "response" && typeof record["id"] === "string") {178+ const pending = pendingRequests.get(record["id"]);179+ if (pending !== undefined) {180+ pendingRequests.delete(record["id"]);181+ if (record["success"] === true) {182+ yield* Deferred.succeed(pending.deferred, record["data"]);183+ } else {184+ yield* Deferred.fail(185+ pending.deferred,186+ new PiRpcError({187+ operation: String(record["command"] ?? "request"),188+ ...(record["error"] === undefined ? {} : { cause: record["error"] }),
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1842OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1026,21 @@1026+ case "agent_settled": {1027+ if (state !== null) yield* finalizeTurn(state);1028+ return;1029+ }1030+ case "response": {1031+ // Correlated responses never reach the pump; an id-less response1032+ // is the deferred ack of a fire-and-forget prompt/steer. A1033+ // rejection here means the turn never started on the Pi side.1034+ const command = recordString(event, "command");1035+ if (1036+ turn !== null &&1037+ event["success"] === false &&1038+ (command === "prompt" || command === "steer" || command === "parse")1039+ ) {1040+ turn.failure = makeProviderFailure({1041+ message: recordString(event, "error") ?? "Pi rejected the prompt.",1042+ class: "provider_error",1043+ });1044+ if (state !== null) yield* finalizeTurn(state);1045+ }1046+ return;
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 614OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +594,21 @@594+ // ── tools ─────────────────────────────────────────────595+596+ const emitToolItem = Effect.fnUntraced(function* (597+ turn: ActivePiTurn,598+ event: PiRpcRecord,599+ phase: "start" | "update" | "end",600+ ) {601+ const toolCallId = recordString(event, "toolCallId");602+ const toolName = recordString(event, "toolName") ?? "tool";603+ if (toolCallId === undefined) return;604+ if (phase === "start") {605+ turn.toolArgs.set(toolCallId, event["args"]);606+ }607+ const args = event["args"] ?? turn.toolArgs.get(toolCallId);608+ const emittedAt = yield* DateTime.now;609+ const completed = phase === "end";610+ const isError = event["isError"] === true;611+ const resultRecord = completed ? event["result"] : event["partialResult"];612+ const outputText = contentText(recordField(resultRecord, "content"));613+ const status = completed ? (isError ? "failed" : "completed") : "running";614+ const base = baseItemFields(turn, toolCallId, emittedAt, emittedAt);
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1066OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1046,21 @@1046+ });1047+ return;1048+ }1049+ case "agent_settled": {1050+ if (state !== null) yield* finalizeTurn(state);1051+ return;1052+ }1053+ case "response": {1054+ // Correlated responses never reach the pump; an id-less response1055+ // is the deferred ack of a fire-and-forget prompt/steer. A1056+ // rejection here means the turn never started on the Pi side.1057+ const command = recordString(event, "command");1058+ if (event["success"] === true) {1059+ // Deferred success ack. Command-only prompts (pure extension1060+ // slash commands) never start an agent run and never emit1061+ // `agent_settled`, so probe for idleness. The probe result is1062+ // re-queued behind any events Pi emitted before answering1063+ // get_state, which keeps the check stream-ordered.1064+ if (command === "prompt" && turn !== null && !turn.sawAgentActivity) {1065+ const providerTurnId = turn.providerTurn.id;1066+ yield* request({ type: "get_state" }).pipe(
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1076OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1056,21 @@1056+ // rejection here means the turn never started on the Pi side.1057+ const command = recordString(event, "command");1058+ if (event["success"] === true) {1059+ // Deferred success ack. Command-only prompts (pure extension1060+ // slash commands) never start an agent run and never emit1061+ // `agent_settled`, so probe for idleness. The probe result is1062+ // re-queued behind any events Pi emitted before answering1063+ // get_state, which keeps the check stream-ordered.1064+ if (command === "prompt" && turn !== null && !turn.sawAgentActivity) {1065+ const providerTurnId = turn.providerTurn.id;1066+ yield* request({ type: "get_state" }).pipe(1067+ Effect.flatMap((data) =>1068+ Queue.offer(connection.events, {1069+ type: "t3.settle_probe",1070+ providerTurnId,1071+ data,1072+ }),1073+ ),1074+ Effect.ignore,1075+ Effect.forkIn(scope),1076+ );
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1988OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1212,21 @@1212+ }),1213+ ),1214+ Effect.forkIn(scope),1215+ );1216+1217+ // ── session runtime ───────────────────────────────────1218+1219+ const registerThread = Effect.fnUntraced(function* (1220+ threadInput: ProviderAdapterV2EnsureThreadInput,1221+ ) {1222+ const existing = threadInput.existingProviderThread;1223+ if (existing?.nativeThreadRef?.nativeId != null) {1224+ yield* request({1225+ type: "switch_session",1226+ sessionPath: existing.nativeThreadRef.nativeId,1227+ });1228+ // The applied-selection cache describes the session we just left.1229+ // Clearing it stops the next `applySelection` from treating this1230+ // session as already configured and skipping set_model.1231+ appliedModel = null;1232+ appliedThinking = null;
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1373OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +885,21 @@885+ ...(lastKnownLeaf === null ? {} : { since: lastKnownLeaf }),886+ }).pipe(Effect.orElseSucceed(() => undefined));887+ if (data === undefined) return null;888+ const entries = recordField(data, "entries");889+ const leafId = recordString(data, "leafId");890+ if (leafId !== undefined) lastKnownLeaf = leafId;891+ const firstUserEntryId = Array.isArray(entries)892+ ? entries893+ .filter(894+ (entry) =>895+ recordField(entry, "type") === "message" &&896+ recordString(recordField(entry, "message"), "role") === "user",897+ )898+ .map((entry) => recordString(entry, "id"))899+ .find((id) => id !== undefined)900+ : undefined;901+ return {902+ turnStartEntryId: firstUserEntryId ?? null,903+ leafId: leafId ?? null,904+ };905+ });
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts lines 1312 to 1316OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1296,21 @@1296+ appThreadId: threadInput.threadId,1297+ ownerNodeId: null,1298+ nativeThreadRef: providerRef(nativeId),1299+ nativeConversationHeadRef: null,1300+ status: "idle",1301+ firstRunOrdinal: null,1302+ lastRunOrdinal: null,1303+ handoffIds: [],1304+ forkedFrom: null,1305+ pendingBackgroundTasks: [],1306+ createdAt,1307+ updatedAt: createdAt,1308+ };1309+ threadState = { providerThread, activeTurn: null };1310+ // Baseline the session-tree leaf so the first turn's user entry can1311+ // be located with a `since` cursor instead of a full entry scan.1312+ lastKnownLeaf =1313+ recordString(1314+ yield* request({ type: "get_entries" }).pipe(Effect.orElseSucceed(() => undefined)),1315+ "leafId",1316+ ) ?? null;
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 510OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +363,21 @@363+ // events. Pi can settle immediately after `extension_ui_response`, so364+ // serialize the two paths to stop `turn.terminal` from overtaking the365+ // dialog's own resolution updates.366+ const sessionEventPermit = yield* Semaphore.make(1);367+ let threadState: PiThreadState | null = null;368+ let appliedModel: string | null = null;369+ let appliedThinking: string | null = null;370+ /** Last thread title synced into pi's session name (`/resume` listing). */371+ let appliedSessionName: string | null = null;372+ /**373+ * Leaf entry id of the pi session tree as of the last turn boundary.374+ * Turn-start user entries are located relative to it, giving each375+ * provider turn a durable native ref for session-tree rollback.376+ */377+ let lastKnownLeaf: string | null = null;378+ /**379+ * Set when a `get_entries` capture failed. Pi may have advanced past380+ * `lastKnownLeaf` since, so the cursor no longer bounds a single turn381+ * and the next capture re-syncs it instead of trusting it.382+ */383+ let leafCursorStale = false;
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1851OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1831,21 @@1831+ .filter((turn) => turn.ordinal > boundaryOrdinal)1832+ .sort((a, b) => a.ordinal - b.ordinal);1833+ const boundary = discarded[0];1834+ if (boundary === undefined) return null;1835+ const ref = boundary.nativeTurnRef;1836+ if (ref === null || ref.strength !== "strong" || ref.nativeId === null) return undefined;1837+ return ref.nativeId;1838+}1839+1840+/**1841+ * Human-readable output for one subagent-extension task result: the last1842+ * assistant text from its transcript, or the error/stderr when it failed.1843+ */1844+function piSubagentOutput(result: unknown): string {1845+ const stopReason = recordString(result, "stopReason");1846+ const failed =1847+ (recordNumber(result, "exitCode") ?? 0) !== 0 ||1848+ stopReason === "error" ||1849+ stopReason === "aborted";1850+ if (failed) {1851+ const failure = recordString(result, "errorMessage") ?? recordString(result, "stderr");
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts lines 1211 to 1215OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1195,21 @@1195+ return;1196+ }1197+ case "auto_retry_end": {1198+ if (turn === null) return;1199+ if (event["success"] === true) return;1200+ turn.failure = makeProviderFailure({1201+ message: recordString(event, "finalError") ?? "Pi auto-retry failed.",1202+ class: "provider_error",1203+ retryable: false,1204+ });1205+ return;1206+ }1207+ case "extension_ui_request":1208+ yield* handleExtensionUiRequest(event);1209+ return;1210+ case "extension_error": {1211+ yield* Effect.logWarning("Pi extension error.", {1212+ extensionPath: recordString(event, "extensionPath"),1213+ event: recordString(event, "event"),1214+ error: recordString(event, "error"),1215+ });apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts lines 1824 to 1826OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1246,21 @@1246+ onFailure: () =>1247+ Queue.offer(connection.events, {1248+ type: "t3.settle_probe",1249+ providerTurnId,1250+ probeFailed: true,1251+ }),1252+ }),1253+ Effect.ignore,1254+ Effect.forkIn(scope),1255+ );1256+ }1257+ return;1258+ }1259+ if (event["success"] !== false) return;1260+ if (command === "steer") {1261+ // A rejected steer only means that one message was refused. The1262+ // turn it was aimed at is still running on Pi, so terminalizing1263+ // here would report a failure while output keeps streaming.1264+ yield* Effect.logWarning("Pi rejected a steer message.", {1265+ error: recordString(event, "error"),1266+ });
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 738OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +718,21 @@718+ ) {719+ const results = recordField(recordField(resultRecord, "details"), "results");720+ if (!Array.isArray(results)) return;721+ const emittedAt = yield* DateTime.now;722+ for (const [index, result] of results.entries()) {723+ const agent = recordString(result, "agent");724+ const task = recordString(result, "task");725+ if (agent === undefined || task === undefined) continue;726+ const nativeTaskId = `${toolCallId}:subagent:${recordNumber(result, "step") ?? index}`;727+ const subagentId = idAllocator.derive.nodeFromProviderItem({728+ driver: PI_PROVIDER,729+ nativeItemId: nativeTaskId,730+ });731+ const startedAt = turn.toolStartedAt.get(nativeTaskId) ?? emittedAt;732+ turn.toolStartedAt.set(nativeTaskId, startedAt);733+ const stopReason = recordString(result, "stopReason");734+ const exitCode = recordNumber(result, "exitCode") ?? 0;735+ const failed =736+ (completed && exitCode !== 0) || stopReason === "error" || stopReason === "aborted";737+ const finished = completed || failed || stopReason !== undefined;738+ const status = failed ? "failed" : finished ? "completed" : "running";
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts lines 1238 to 1238OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1218,21 @@1218+ status: "completed",1219+ title: null,1220+ completedAt: emittedAt,1221+ type: "compaction",1222+ driver: PI_PROVIDER,1223+ ...(recordString(result, "summary") === undefined1224+ ? {}1225+ : { summary: recordString(result, "summary") }),1226+ ...(recordNumber(result, "tokensBefore") === undefined1227+ ? {}1228+ : { beforeTokenCount: recordNumber(result, "tokensBefore") }),1229+ ...(recordNumber(result, "estimatedTokensAfter") === undefined1230+ ? {}1231+ : { afterTokenCount: recordNumber(result, "estimatedTokensAfter") }),1232+ },1233+ });1234+ return;1235+ }1236+ case "auto_retry_end": {1237+ if (turn === null) return;1238+ if (event["success"] === true) return;apps/server/src/orchestration-v2/Adapters/PiRpc.ts line 224OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +138,21 @@138+ const scope = yield* Effect.scope;139+140+ const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {141+ env: options.env,142+ }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));143+ const child = yield* spawner144+ .spawn(145+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {146+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),147+ env: options.env,148+ extendEnv: false,149+ shell: spawnCommand.shell,150+ detached: platform !== "win32",151+ }),152+ )153+ .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));154+155+ const killProcessGroup = (signal: NodeJS.Signals): boolean => {156+ try {157+ if (platform === "win32") {158+ process.kill(Number(child.pid), signal);apps/server/src/orchestration-v2/Adapters/PiRpc.ts line 195OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +112,21 @@112+ : text;113+}114+115+function parsePiRecord(line: string): PiRpcRecord | undefined {116+ try {117+ const parsed: unknown = decodeJsonLine(line);118+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {119+ return parsed as PiRpcRecord;120+ }121+ return undefined;122+ } catch {123+ return undefined;124+ }125+}126+127+/** Kill the pi process group: SIGTERM, short grace, then SIGKILL. */128+const terminatePiProcess = (pid: number, kill: (signal: NodeJS.Signals) => boolean) =>129+ Effect.gen(function* () {130+ if (!kill("SIGTERM")) return;131+ yield* Effect.sleep(TERMINATION_GRACE);132+ kill("SIGKILL");apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 2220OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1575,21 @@1575+ modelSelection: threadInput.modelSelection ?? input.modelSelection,1576+ runtimePolicy: threadInput.runtimePolicy ?? input.runtimePolicy,1577+ existingProviderThread: threadInput.providerThread,1578+ }).pipe(1579+ Effect.mapError(1580+ (cause) =>1581+ new ProviderAdapterResumeThreadError({1582+ driver: PI_PROVIDER,1583+ providerSessionId: input.providerSessionId,1584+ providerThreadId: threadInput.providerThread.id,1585+ cause,1586+ }),1587+ ),1588+ ),1589+ startTurn: (turnInput) =>1590+ Effect.gen(function* () {1591+ const state = threadState;1592+ if (state === null) {1593+ return yield* protocolError("Pi session has no registered thread");1594+ }1595+ if (state.activeTurn !== null) {
- apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1586OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1153,21 @@1153+ yield* completeStreamItem(1154+ turn,1155+ item,1156+ recordString(delta, "content") ?? recordString(delta, "thinking"),1157+ );1158+ return;1159+ }1160+ return;1161+ }1162+ case "message_end": {1163+ if (turn === null) return;1164+ const message = event["message"];1165+ if (recordString(message, "role") !== "assistant") return;1166+ yield* completeOpenStreamItems(turn);1167+ if (recordString(message, "stopReason") === "error" && turn.failure === null) {1168+ turn.failure = makeProviderFailure({1169+ message: recordString(message, "errorMessage") ?? "Pi reported a model error.",1170+ class: "provider_error",1171+ });1172+ }1173+ return;apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 1673OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1653,21 @@1653+ type: "provider_turn.updated",1654+ driver: PI_PROVIDER,1655+ threadId: turnInput.threadId,1656+ providerTurn,1657+ });1658+ yield* updateProviderThread(state, {1659+ status: "active",1660+ firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,1661+ lastRunOrdinal: turnInput.runOrdinal,1662+ });1663+ yield* updateProviderSession("running", null);1664+ // Fire-and-forget: pi acks `prompt` only after slash-command1665+ // expansion completes, and extension commands may block on user1666+ // dialogs indefinitely, so turn start must never await the ack.1667+ // Rejections come back as an id-less response record and are1668+ // handled by the event pump.1669+ yield* connection.send({1670+ type: "prompt",1671+ message: payload.message,1672+ ...(payload.images.length === 0 ? {} : { images: payload.images }),1673+ });apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts line 2013OutdatedResolvedby StiensWout(GitHub profile, opens in a new tab)@@ -0,0 +1396,21 @@1396+ // stops the next turn from treating this session as already1397+ // configured and skipping set_model or set_session_name.1398+ appliedModel = null;1399+ appliedThinking = null;1400+ appliedSessionName = null;1401+ }1402+ const stateData = yield* request({ type: "get_state" });1403+ // Each baseline is captured independently, and only while nothing has1404+ // been applied yet, so a `get_state` that omits one field still lets1405+ // the other be picked up later without recording our own selection.1406+ if (baselineModel === null && appliedModel === null) {1407+ const stateModel = recordField(stateData, "model");1408+ const provider = recordString(stateModel, "provider");1409+ const modelId = recordString(stateModel, "id");1410+ if (provider !== undefined && modelId !== undefined) {1411+ baselineModel = { provider, modelId };1412+ }1413+ }1414+ if (baselineThinking === null && appliedThinking === null) {1415+ baselineThinking = recordString(stateData, "thinkingLevel") ?? null;1416+ }
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: Team
Run ID:
c00ad526-8b4c-49ef-904e-cc074f248b93You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Warning
Your free Security trial is over. An organization admin can upgrade to Advanced for continuous pull request security review or dismiss this notice.
Comment `@coderabbitai help` to get the list of available commands.