feat(pi): add first-class agent provider #5882
ClosedPJalv(GitHub profile, opens in a new tab)wants to merge 20 commits into
main fromrefs/pull/5882/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 lines 1863 to 1865OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1845,21 @@1845+ }),1846+ ),1847+ );1848+ };1849+1850+ const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (1851+ threadId,1852+ turnId,1853+ ) =>1854+ Effect.gen(function* () {1855+ const ctx = yield* requireSession(threadId);1856+ const turn = ctx.activeTurn;1857+ const hasBackgroundTasks =1858+ Array.from(ctx.agentTasksById.values()).length > 0 ||1859+ Array.from(ctx.workflowTasks.values()).some((task) => task.state === "running") ||1860+ Array.from(ctx.extensionSubagentTasks.values()).some((task) => task.state === "running");1861+ if (!turn && !hasBackgroundTasks)1862+ return yield* validation("interruptTurn", "No active Pi work to interrupt.");1863+ if (turnId && turn && turn.id !== turnId)1864+ return yield* validation("interruptTurn", "No matching active Pi turn.");1865+ if (turn) turn.interruptRequested = true;apps/server/src/provider/Layers/PiAdapter.ts line 1975Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1706,21 @@1706+ data: Buffer.from(bytes).toString("base64"),1707+ mimeType: attachment.mimeType,1708+ })),1709+ Effect.mapError((cause) => request("prompt", cause)),1710+ );1711+ },1712+ { concurrency: 1 },1713+ );1714+ const selection = input.modelSelection;1715+ if (selection && selection.instanceId !== options.providerInstanceId)1716+ return yield* validation(1717+ "sendTurn",1718+ "Model selection belongs to another provider instance.",1719+ );1720+ const selectedModel = selection?.model ?? ctx.session.model;1721+ if (!selectedModel)1722+ return yield* validation("sendTurn", "A valid Pi model selection is required.");1723+ const parsed = decodePiModelSlug(selectedModel);1724+ if (!parsed)1725+ return yield* validation("sendTurn", "A valid Pi model selection is required.");1726+ if (steeringTurn && ctx.activeTurn === steeringTurn) {apps/server/src/provider/pi/PiRpcClient.ts lines 162 to 171Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +148,21 @@148+ const decodeModel = (data: unknown) =>149+ decodePiRpcModel(data).pipe(150+ Effect.mapError(151+ (cause) => new PiRpcProtocolError({ detail: "invalid set_model response data", cause }),152+ ),153+ );154+155+ const remove = (id: string) =>156+ Ref.update(pending, (current) => {157+ const next = new Map(current);158+ next.delete(id);159+ return next;160+ });161+162+ const end = (error: PiRpcProcessExitedError) =>163+ Ref.modify(pending, (current) => [Array.from(current.values()), new Map()] as const).pipe(164+ Effect.flatMap((waiters) =>165+ Effect.forEach(waiters, (waiter) => Deferred.fail(waiter, error), { discard: true }),166+ ),167+ Effect.andThen(Queue.shutdown(events)),168+ );apps/server/src/provider/Layers/PiAdapter.ts line 2030Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1743,21 @@1743+ if (deferredSettlement)1744+ yield* handleEvent(ctx, deferredSettlement).pipe(Effect.orDie);1745+ }),1746+ ),1747+ Effect.uninterruptible,1748+ Effect.as({1749+ threadId: input.threadId,1750+ turnId: steeringTurn.id,1751+ resumeCursor: ctx.cursor,1752+ }),1753+ ),1754+ };1755+ }1756+ const available = yield* ctx.client1757+ .getAvailableModels()1758+ .pipe(Effect.mapError((cause) => request("get_available_models", cause)));1759+ if (1760+ !available.models.some((m) => m.provider === parsed.provider && m.id === parsed.modelId)1761+ )1762+ return yield* validation("sendTurn", "Selected Pi model is not currently available.");1763+ yield* ctx.clientapps/web/src/components/chat/MessagesTimeline.tsx lines 2182 to 2188Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2174,4 +2177,10 @@21742177 // One steady in-flight presentation (monitoring-pill rule): waiting and21752178 // stalled agents read as working; only settled states differentiate.21762179 const working = running + waiting;2177- const dotClass = live ? "bg-info" : failed > 0 ? "bg-destructive" : "bg-success";2180+ const dotClass = live2181+ ? "bg-info"2182+ : failed > 02183+ ? "bg-destructive"2184+ : stopped > 02185+ ? "bg-muted-foreground"2186+ : "bg-success";packages/client-runtime/src/state/subagentRuntime.ts lines 512 to 515Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -507,4 +507,7 @@507507 const existed = agents.has(taskId);508508 if (!existed && isBackgroundTaskActivity(payload)) break;509509 const agent = getOrCreate(agents, taskId, payload, at);510+ const previousAttempt = agent.attempt;510511 fillMetadata(agent, payload);512+ const isNewAttempt =513+ previousAttempt !== null && agent.attempt !== null && agent.attempt > previousAttempt;
- apps/server/src/provider/Drivers/PiDriver.ts lines 76 to 81Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+ instanceId,62+ driver: DRIVER_KIND,63+ ...(displayName ? { displayName } : {}),64+ ...(accentColor ? { accentColor } : {}),65+ continuation: { groupKey: continuationIdentity.continuationKey },66+ });67+ const adapter = yield* makePiAdapter({68+ binaryPath: effectiveConfig.binaryPath,69+ providerInstanceId: instanceId,70+ stateDir: serverConfig.stateDir,71+ attachmentsDir: serverConfig.attachmentsDir,72+ environment: processEnv,73+ }).pipe(74+ Effect.mapError(75+ (cause) =>76+ new ProviderDriverError({77+ driver: DRIVER_KIND,78+ instanceId,79+ detail: cause.message,80+ cause,81+ }),apps/server/src/provider/pi/PiSessionFile.ts lines 19 to 27Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +2,21 @@2+import * as Exit from "effect/Exit";3+import * as FileSystem from "effect/FileSystem";4+import * as Option from "effect/Option";5+import * as Path from "effect/Path";6+import * as Schema from "effect/Schema";7+8+export const PiSessionCursor = Schema.Struct({9+ schemaVersion: Schema.Literal(1),10+ sessionFile: Schema.String,11+ sessionId: Schema.String.check(12+ Schema.makeFilter((value) => value.length > 0 && value.trim() === value),13+ ),14+});15+export type PiSessionCursor = typeof PiSessionCursor.Type;16+17+const decodePiSessionHeader = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));18+19+export class PiSessionFileError extends Schema.TaggedErrorClass<PiSessionFileError>()(20+ "PiSessionFileError",21+ { operation: Schema.String, sessionFile: Schema.String, cause: Schema.Defect() },22+) {}apps/server/src/provider/Layers/PiAdapter.ts lines 407 to 416Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +380,21 @@380+ Effect.map((lock) => [lock, new Map(locks).set(threadId, lock)] as const),381+ );382+ });383+ const withThreadLock = <A, E, R>(threadId: ThreadId, effect: Effect.Effect<A, E, R>) =>384+ Effect.flatMap(getThreadLock(threadId), (lock) => lock.withPermit(effect));385+ const events = yield* Queue.unbounded<ProviderRuntimeEvent>();386+ const now = Effect.map(DateTime.now, DateTime.formatIso);387+ const uuid = crypto.randomUUIDv4.pipe(388+ Effect.mapError((cause) => request("crypto/randomUUIDv4", cause)),389+ );390+391+ function validation(operation: string, issue: string, cause?: unknown) {392+ return new ProviderAdapterValidationError({ provider: PROVIDER, operation, issue, cause });393+ }394+ function request(method: string, cause: unknown) {395+ return new ProviderAdapterRequestError({396+ provider: PROVIDER,397+ method,398+ detail: isRecord(cause) && typeof cause.detail === "string" ? cause.detail : String(cause),399+ cause,400+ });apps/server/src/provider/Drivers/PiDriver.ts lines 104 to 109Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +89,21 @@89+ const source = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);90+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({91+ maintenanceCapabilities,92+ getSettings: source.getSettings,93+ streamSettings: source.streamSettings,94+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,95+ initialSnapshot: (settings) =>96+ makePendingPiProvider(settings.provider).pipe(Effect.map(stamp)),97+ checkProvider: checkPiProviderStatus(effectiveConfig, processEnv).pipe(98+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),99+ Effect.map(stamp),100+ ),101+ }).pipe(102+ Effect.mapError(103+ (cause) =>104+ new ProviderDriverError({105+ driver: DRIVER_KIND,106+ instanceId,107+ detail: `Failed to build Pi snapshot: ${String(cause)}`,108+ cause,109+ }),
- @@ -0,0 +1819,21 @@1819+ });1820+ createdTurn = turn;1821+ const turnId = turn.id;1822+ const prompted = yield* ctx.client.prompt(input.input ?? "", images).pipe(Effect.result);1823+ if (Result.isFailure(prompted)) {1824+ const reusable = isPiRpcCommandError(prompted.failure);1825+ yield* failActive(ctx, "Pi prompt failed.", undefined, !reusable);1826+ if (!reusable) yield* close(ctx);1827+ return yield* request("prompt", prompted.failure);1828+ }1829+ if (ctx.closing || ctx.stopped || sessions.get(input.threadId) !== ctx) {1830+ return yield* new ProviderAdapterSessionNotFoundError({1831+ provider: PROVIDER,1832+ threadId: input.threadId,1833+ });1834+ }1835+ if (input.input?.trimStart().startsWith("/")) {1836+ const state = yield* ctx.client.getState().pipe(1837+ Effect.mapError((cause) => request("get_state", cause)),1838+ Effect.option,1839+ );
- apps/server/src/textGeneration/PiTextGeneration.ts lines 115 to 116OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +96,21 @@96+ Effect.mapError(97+ (cause) =>98+ new TextGenerationError({99+ operation: input.operation,100+ detail: "Failed to start Pi RPC text generation.",101+ cause,102+ }),103+ ),104+ );105+ const output = yield* Ref.make("");106+ const currentDeltas = yield* Ref.make("");107+ const settled = yield* Deferred.make<void, TextGenerationError>();108+ yield* client.events.pipe(109+ Stream.runForEach((native) => {110+ if ("_tag" in native && native._tag === "PiRpcProtocolFailureEvent")111+ return Deferred.fail(112+ settled,113+ new TextGenerationError({114+ operation: input.operation,115+ detail:116+ typeof native.detail === "string" ? native.detail : "Pi RPC protocol failed.",
- @@ -0,0 +112,21 @@112+ });113+ return yield* Effect.all({114+ inventory: client.getAvailableModels(),115+ state: client.getState(),116+ commands: client.getCommands(),117+ });118+ }),119+ ).pipe(Effect.exit);120+ if (discovery._tag === "Failure") {121+ const error = Cause.squash(discovery.cause);122+ return buildServerProvider({123+ presentation: PRESENTATION,124+ enabled: true,125+ checkedAt,126+ models: models(settings),127+ probe: {128+ installed: !isPiCommandMissingCause(error),129+ version: null,130+ status: "error",131+ auth: { status: "unknown" },132+ message: `Pi model discovery failed: ${String(error)}`,
- @@ -0,0 +1417,21 @@1417+ const handleEvent = Effect.fn("PiAdapter.handleEvent")(function* (1418+ ctx: SessionContext,1419+ native: PiRpcEvent,1420+ ) {1421+ if ("_tag" in native && native._tag === "PiRpcProtocolFailureEvent") {1422+ yield* failActive(ctx, String(native.detail), native);1423+ yield* close(ctx);1424+ return;1425+ }1426+ if ("_tag" in native && native._tag === "PiRpcOutputLineEvent") {1427+ yield* Effect.logDebug("Ignored non-JSON Pi output").pipe(1428+ Effect.annotateLogs({ provider: "pi", output: native.line }),1429+ );1430+ return;1431+ }1432+ const event = native as Record<string, unknown>;1433+ const type = string(event.type);1434+ if (type === "extension_ui_request") {1435+ yield* handleExtensionUiRequest(ctx, event);1436+ return;1437+ }@@ -0,0 +608,21 @@608+ ) {609+ return yield* Effect.uninterruptible(610+ Effect.gen(function* () {611+ if (ctx.activeTurn !== expected || expected.terminal) return false;612+ expected.terminal = true;613+ ctx.activeTurn = undefined;614+ yield* Effect.forEach(terminalEvents, offer, { discard: true });615+ const { activeTurnId: _, ...session } = ctx.session;616+ ctx.session = {617+ ...session,618+ status,619+ ...(status === "ready" ? { resumeCursor: ctx.cursor } : {}),620+ ...(errorMessage ? { lastError: errorMessage } : {}),621+ updatedAt: yield* now,622+ };623+ return true;624+ }),625+ );626+ });627+628+ const close = Effect.fn("PiAdapter.close")(function* (ctx: SessionContext) {@@ -0,0 +2147,21 @@2147+ const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (2148+ threadId,2149+ requestId,2150+ answers,2151+ ) =>2152+ Effect.gen(function* () {2153+ // Prompt preflight can wait on extension UI while sendTurn owns the2154+ // thread lock, so responses must use Pi's own serialized RPC writer.2155+ const ctx = yield* requireSession(threadId);2156+ const pending = ctx.pendingUserInputs.get(requestId);2157+ if (!pending)2158+ return yield* requestMessage("extension_ui_response", "Unknown Pi input request.");2159+ const rawAnswer = answers[pending.questionId];2160+ const answer = (Array.isArray(rawAnswer) ? rawAnswer[0] : rawAnswer)?.trim();2161+ if (!answer) return yield* validation("respondToUserInput", "Pi requires an answer.");2162+ const response =2163+ pending.method === "confirm"2164+ ? {2165+ confirmed: ["yes", "true", "confirm", "confirmed"].includes(answer.toLowerCase()),2166+ }2167+ : { value: answer };
t3dotgg(GitHub profile, opens in a new tab) 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:
750d5dc7-1f19-4b90-b605-d86487470d11You 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