feat(server): add Pi provider #13777
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 19 commits into
main fromt3code/pi-provider-v1opened 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/provider/Layers/PiAdapter.ts line 492Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +463,21 @@463+ ctx: PiSessionContext,464+ record: PiRpcRecord,465+ timeoutMs = PI_REQUEST_TIMEOUT_MS,466+ ) => ctx.connection.request(record, timeoutMs);467+468+ /**469+ * A local timeout does not cancel Pi's lifecycle hook. Retire the process470+ * before a later request can race its eventual session change.471+ */472+ const lifecycleRequest = (ctx: PiSessionContext, record: PiRpcRecord) =>473+ request(ctx, record, PI_SESSION_TIMEOUT_MS).pipe(474+ Effect.catchTags({475+ PiRpcTimeoutError: (error) =>476+ Effect.sync(() => {477+ ctx.stopRequested = true;478+ }).pipe(Effect.andThen(ctx.connection.terminate), Effect.andThen(Effect.fail(error))),479+ }),480+ Effect.onInterrupt(() => ctx.connection.terminate),481+ );482+483+ const cursorFor = (ctx: PiSessionContext): PiResumeCursor => ({@@ -0,0 +293,21 @@293+ pendingRequests.delete(key);294+ yield* Deferred.fail(pending.deferred, error);295+ }296+ // Closing `outgoing` is what makes `send` non-racy: once the writer is297+ // gone every later offer is refused rather than silently buffered.298+ yield* Queue.fail(outgoing, error);299+ yield* Queue.fail(events, error);300+ });301+302+ const routeRecord = (record: PiRpcRecord) =>303+ Effect.gen(function* () {304+ if (record["type"] === "response" && typeof record["id"] === "string") {305+ const pending = pendingRequests.get(record["id"]);306+ if (pending !== undefined) {307+ pendingRequests.delete(record["id"]);308+ if (record["success"] === true) {309+ yield* Deferred.succeed(pending.deferred, record["data"]);310+ } else {311+ yield* Deferred.fail(312+ pending.deferred,313+ new PiRpcError({
- apps/server/src/provider/Layers/PiAdapter.ts line 1027Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +990,21 @@990+ if (pendingCompact?.kind === "steer") {991+ yield* Effect.logWarning("Pi rejected a compact steer.", {992+ errorLength: recordString(event, "error")?.length,993+ });994+ return;995+ }996+ if (!compactTurn.sawCompaction) {997+ compactTurn.failure = nonEmpty(recordString(event, "error")) ?? "Pi compact failed.";998+ yield* finalizeTurn(ctx);999+ return;1000+ }1001+ if (!compactTurn.sawAgentActivity) yield* scheduleSettleProbe(ctx, compactTurn);1002+ return;1003+ }1004+ const pendingPrompt = command === "prompt" ? ctx.pendingPromptResponses.shift() : undefined;1005+ const responseTurn = pendingPrompt?.turnId === turn?.turnId ? turn : null;1006+ if (event["success"] === true) {1007+ // Command-only prompts (pure extension slash commands) never start an1008+ // agent run and never emit `agent_settled`, so probe for idleness.1009+ if (1010+ pendingPrompt?.kind === "turn_start" &&apps/server/src/provider/PiCommands.ts lines 141 to 143Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ found.push({ name, start: tokenStart, end: tokenStart + name.length + 1 });107+ }108+ if (found.length === 0) return text;109+110+ const orderedNames: string[] = [];111+ const seen = new Set<string>();112+ for (const token of found) {113+ if (seen.has(token.name)) continue;114+ seen.add(token.name);115+ orderedNames.push(token.name);116+ }117+118+ let body = text;119+ for (let index = found.length - 1; index >= 0; index -= 1) {120+ const token = found[index];121+ if (token === undefined) continue;122+ body = `${body.slice(0, token.start)}${body.slice(token.end)}`;123+ }124+ body = body.trim();125+ const prefix = orderedNames.map((name) => `/skill:${name}`).join(" ");126+ return body.length === 0 ? prefix : `${prefix} ${body}`;apps/server/src/provider/PiRpc.ts lines 251 to 251OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +231,21 @@231+ .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));232+233+ let childExited = false;234+ let diagnosingStdoutClose = false;235+236+ const killProcessGroup = (signal: NodeJS.Signals): boolean => {237+ try {238+ if (platform === "win32") {239+ process.kill(Number(child.pid), signal);240+ } else {241+ process.kill(-Number(child.pid), signal);242+ }243+ return true;244+ } catch {245+ return false;246+ }247+ };248+249+ /** Signal 0 probes liveness without delivering anything. */250+ const hasExited = (): boolean => {251+ if (childExited) return true;apps/server/src/provider/Layers/PiProvider.ts line 178Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +145,21 @@145+ });146+ yield* Stream.fromQueue(connection.events).pipe(147+ Stream.runDrain,148+ Effect.ignore,149+ Effect.forkScoped,150+ );151+ const stateData = yield* connection.request({ type: "get_state" });152+ const modelsData = yield* connection.request({ type: "get_available_models" });153+ const commandsData = yield* connection154+ .request({ type: "get_commands" })155+ .pipe(Effect.orElseSucceed(() => undefined));156+ const discoveredModels = parseDiscoveredModels(157+ modelsData,158+ recordString(stateData, "thinkingLevel"),159+ );160+ const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);161+ return {162+ models: discoveredModels,163+ slashCommands: withPiBuiltinSlashCommands(slashCommands),164+ skills,165+ authenticated: discoveredModels.length > 0,apps/server/src/provider/piT3McpExtensionSource.ts lines 111 to 111OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +91,21 @@91+ if (typeof unsafe === "function" && schema !== undefined) {92+ return unsafe(schema);93+ }94+ return Type.Object({}, { additionalProperties: true });95+}96+97+function formatMcpContent(result: unknown): string {98+ if (result === null || result === undefined) return "";99+ if (typeof result !== "object") return String(result);100+ const record = result as {101+ readonly content?: ReadonlyArray<{ readonly type?: string; readonly text?: string }>;102+ readonly structuredContent?: unknown;103+ readonly isError?: boolean;104+ };105+ const texts: string[] = [];106+ if (Array.isArray(record.content)) {107+ for (const part of record.content) {108+ if (part?.type === "text" && typeof part.text === "string") texts.push(part.text);109+ }110+ }111+ if (record.structuredContent !== undefined) {apps/server/src/provider/PiCommands.ts lines 117 to 117Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ ...(scope === undefined ? {} : { scope }),81+ ...(displayName === undefined ? {} : { displayName }),82+ ...(shortDescription === undefined ? {} : { shortDescription }),83+ });84+ continue;85+ }86+ slashCommands.push({87+ name: commandName,88+ ...(description === undefined ? {} : { description }),89+ });90+ }91+ return { slashCommands, skills };92+}93+94+/**95+ * Pi expands skills only through leading `/skill:name` commands. T3 stores96+ * skill chips as `$name`, so hoist every known `$skill` to that native97+ * command position while preserving the rest of the user's prompt.98+ */99+export function expandPiSkillReference(text: string, skillNames: ReadonlySet<string>): string {100+ const references = /(^|\s)\$([^\s]+)(?=\s|$)/g;apps/web/src/components/settings/customModelEditor.logic.ts line 115Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -101,3 +101,15 @@101101 ],102102 },103103 ],104+ [ProviderDriverKind.make("pi")]: [105+ {106+ id: "thinking",107+ label: "Thinking",108+ type: "select",109+ choices: [110+ { id: "off", label: "Off" },111+ { id: "minimal", label: "Minimal" },112+ { id: "low", label: "Low" },113+ { id: "medium", label: "Medium", isDefault: true },114+ { id: "high", label: "High" },115+ { id: "xhigh", label: "Extra High" },apps/server/src/provider/Drivers/PiDriver.ts line 114Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ continuationGroupKey: continuationIdentity.continuationKey,94+ });95+ const effectiveConfig = { ...config, enabled } satisfies PiSettings;96+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(97+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {98+ binaryPath: effectiveConfig.binaryPath,99+ env: processEnv,100+ }).pipe(101+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),102+ Effect.provideService(FileSystem.FileSystem, fileSystem),103+ Effect.provideService(Path.Path, pathService),104+ ),105+ );106+107+ const adapter = yield* makePiAdapter(effectiveConfig, {108+ environment: processEnv,109+ instanceId,110+ });111+ const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);112+113+ const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(apps/server/src/textGeneration/PiTextGeneration.ts line 101Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +79,21 @@79+ command: piSettings.binaryPath || "pi",80+ // Extensions and tools are disabled because no user is present to81+ // answer a dialog and background text generation is read-only. User82+ // model config and auth still apply.83+ args: launch.args,84+ cwd,85+ env: launch.env,86+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));87+88+ if (modelSelection.model !== "default") {89+ // `customModels` accepts arbitrary strings, so an unusable slug is90+ // rejected rather than skipped: running Pi's default model here would91+ // report success for a model the caller never asked for.92+ const parsed = parsePiModelSlug(modelSelection.model);93+ if (parsed === null) {94+ return yield* new TextGenerationError({95+ operation,96+ detail: `Pi model '${modelSelection.model}' must use provider/model format.`,97+ });98+ }99+ yield* connection.request({apps/server/src/provider/piT3McpExtensionSource.ts line 329Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +277,21 @@277+ for (const tool of tools) {278+ const name = tool.name;279+ const registeredName = \`mcp__t3-code__\${name}\`;280+ const description = tool.description ?? name;281+ pi.registerTool({282+ name: registeredName,283+ label: name,284+ description,285+ promptSnippet: description.split("\\n")[0] ?? name,286+ promptGuidelines: [287+ \`Use \${registeredName} from the t3-code MCP server when the user asks for T3 orchestration that this tool covers.\`,288+ ],289+ parameters: jsonSchemaToTypebox(tool.inputSchema),290+ async execute(_toolCallId, params, signal) {291+ const result = await client.callTool(292+ name,293+ (params ?? {}) as Record<string, unknown>,294+ signal,295+ );296+ const text = formatMcpContent(result);297+ return {
- apps/server/src/provider/Layers/PiAdapter.ts line 467Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +438,21 @@438+ });439+440+ /** A replacement session for the same thread must survive the old one's teardown. */441+ const forgetSession = (ctx: PiSessionContext) => {442+ if (sessions.get(ctx.threadId) === ctx) sessions.delete(ctx.threadId);443+ };444+445+ const requireSession = (446+ threadId: ThreadId,447+ ): Effect.Effect<PiSessionContext, ProviderAdapterSessionNotFoundError> => {448+ const ctx = sessions.get(threadId);449+ return ctx === undefined || ctx.stopped450+ ? Effect.fail(new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }))451+ : Effect.succeed(ctx);452+ };453+454+ const requestError = (method: string) => (cause: { readonly message: string }) =>455+ new ProviderAdapterRequestError({456+ provider: PROVIDER,457+ method,458+ detail: cause.message,
- apps/server/src/provider/PiRpc.ts lines 254 to 262Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +238,21 @@238+ if (platform === "win32") {239+ process.kill(Number(child.pid), signal);240+ } else {241+ process.kill(-Number(child.pid), signal);242+ }243+ return true;244+ } catch {245+ return false;246+ }247+ };248+249+ /** Signal 0 probes liveness without delivering anything. */250+ const hasExited = (): boolean => {251+ if (childExited) return true;252+ try {253+ process.kill(platform === "win32" ? Number(child.pid) : -Number(child.pid), 0);254+ return false;255+ } catch {256+ return true;257+ }258+ };apps/server/src/textGeneration/PiTextGeneration.ts lines 218 to 221Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +194,21 @@194+ changeRequestTemplate: input.changeRequestTemplate,195+ });196+ const generated = yield* runPiJson({197+ operation: "generatePrContent",198+ cwd: input.cwd,199+ prompt,200+ outputSchemaJson: outputSchema,201+ modelSelection: input.modelSelection,202+ });203+ return {204+ title: sanitizePrTitle(generated.title),205+ body: generated.body.trim(),206+ };207+ });208+209+ const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =210+ Effect.fn("PiTextGeneration.generateBranchName")(function* (input) {211+ const { prompt, outputSchema } = buildBranchNamePrompt({212+ message: input.message,213+ attachments: input.attachments,214+ });
- apps/server/src/provider/Layers/PiAdapter.ts line 1010Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +973,21 @@973+ if (command === "compact") {974+ const pendingCompact = ctx.pendingCompactResponses.shift();975+ const compactTurn = pendingCompact?.turnId === turn?.turnId ? turn : null;976+ if (compactTurn !== null) compactTurn.manualCompactInFlight = false;977+ if (event["success"] === true) {978+ if (979+ pendingCompact?.kind === "turn_start" &&980+ compactTurn !== null &&981+ compactTurn.promptMayBeCommandOnly &&982+ !compactTurn.sawAgentActivity983+ ) {984+ yield* scheduleSettleProbe(ctx, compactTurn);985+ }986+ return;987+ }988+ if (event["success"] !== false || compactTurn === null) return;989+ if (compactTurn.compactionRunning) return;990+ if (pendingCompact?.kind === "steer") {991+ yield* Effect.logWarning("Pi rejected a compact steer.", {992+ errorLength: recordString(event, "error")?.length,993+ });
- apps/server/src/provider/Layers/PiProvider.ts line 331Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +311,21 @@311+ });312+ }313+314+ if (Option.isNone(versionResult.success)) {315+ return buildServerProvider({316+ presentation: PI_PRESENTATION,317+ enabled: piSettings.enabled,318+ checkedAt,319+ models: fallbackModels,320+ probe: {321+ installed: true,322+ version: null,323+ status: "error",324+ auth: { status: "unknown" },325+ message: "Pi CLI is installed but timed out while running `pi --version`.",326+ },327+ });328+ }329+330+ const versionOutput = versionResult.success.value;331+ const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
- apps/server/src/provider/Layers/PiProvider.ts line 460Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +440,21 @@440+ const models = piModelsFromSettings(piSettings.customModels, discovery.models);441+ return buildServerProvider({442+ presentation: PI_PRESENTATION,443+ enabled: piSettings.enabled,444+ checkedAt,445+ models,446+ slashCommands: discovery.slashCommands,447+ skills: discovery.skills,448+ probe: {449+ installed: true,450+ version,451+ status: discovery.authenticated ? "ready" : "warning",452+ auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },453+ ...(discovery.authenticated454+ ? {}455+ : {456+ message:457+ "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",458+ }),459+ },460+ });
- apps/server/src/provider/Layers/PiAdapter.ts line 1743OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1723,21 @@1723+ ctx.turns.push({ id: turnId, items: [] });1724+ yield* updateSession(ctx, { status: "running", activeTurnId: turnId });1725+ yield* emit(ctx, {1726+ type: "turn.started",1727+ turnId,1728+ payload: ctx.session.model === undefined ? {} : { model: ctx.session.model },1729+ });1730+ return turnId;1731+ }),1732+ )1733+ .pipe(Effect.mapError(requestError("prompt")));1734+ return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor };1735+ }),1736+ );1737+1738+ const interruptTurn: PiAdapterShape["interruptTurn"] = (threadId, turnId) =>1739+ Effect.gen(function* () {1740+ const ctx = yield* requireSession(threadId);1741+ const turn = ctx.activeTurn;1742+ if (turn === null || (turnId !== undefined && turn.turnId !== turnId)) return;1743+ turn.interrupted = true;
- apps/server/src/provider/Layers/PiAdapter.ts line 1652OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1632,21 @@1632+ const attachments = input.attachments ?? [];1633+ if (text.trim().length === 0 && attachments.length === 0) {1634+ return yield* new ProviderAdapterValidationError({1635+ provider: PROVIDER,1636+ operation: "sendTurn",1637+ issue: "Turn requires non-empty text or attachments.",1638+ });1639+ }1640+ const compactCommand = parsePiCompactCommand(text);1641+ // Resolved before a turn is installed: a failure here (an unreadable1642+ // attachment) must not leave a turn active.1643+ const payload =1644+ compactCommand === null ? yield* resolvePromptPayload(ctx, text, attachments) : null;1645+ // Model changes apply only between turns. They run outside the event1646+ // permit so a dialog raised by set_model can still be answered.1647+ if (ctx.activeTurn === null || ctx.activeTurn.interrupted) {1648+ yield* applySelection(ctx, input.modelSelection).pipe(1649+ Effect.mapError((cause) =>1650+ cause._tag === "ProviderAdapterValidationError"1651+ ? cause1652+ : requestError("set_model")(cause),
- apps/server/src/provider/Layers/PiAdapter.ts line 1733OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1713,21 @@1713+ } else if (payload !== null) {1714+ yield* ctx.connection.send({1715+ type: "prompt",1716+ message: payload.message,1717+ ...(payload.images.length === 0 ? {} : { images: payload.images }),1718+ });1719+ ctx.pendingPromptResponses.push({ turnId, kind: "turn_start" });1720+ }1721+ ctx.activeTurn = turn;1722+ ctx.turnEntryIds.push(null);1723+ ctx.turns.push({ id: turnId, items: [] });1724+ yield* updateSession(ctx, { status: "running", activeTurnId: turnId });1725+ yield* emit(ctx, {1726+ type: "turn.started",1727+ turnId,1728+ payload: ctx.session.model === undefined ? {} : { model: ctx.session.model },1729+ });1730+ return turnId;1731+ }),1732+ )1733+ .pipe(Effect.mapError(requestError("prompt")));
- apps/server/src/provider/Layers/PiAdapter.ts lines 367 to 371Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +345,21 @@345+ nonEmpty(recordString(event, "placeholder")) ??346+ title;347+ return {348+ id: questionId,349+ header: title,350+ question:351+ prefill === undefined || prefill.length === 0352+ ? question353+ : `${question}\n\nCurrent value:\n${prefill.slice(0, 2_000)}`,354+ options,355+ // A select dialog only accepts one of its own options.356+ ...(method === "select" ? { allowCustomAnswer: false } : {}),357+ multiSelect: false,358+ };359+}360+361+function piApprovalResponse(decision: ProviderApprovalDecision): PiRpcRecord {362+ if (decision === "accept" || decision === "acceptForSession") return { confirmed: true };363+ if (decision === "decline") return { confirmed: false };364+ return { cancelled: true };365+}
- apps/server/src/provider/Layers/PiAdapter.ts line 1547OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1527,21 @@1527+ sessionFile: resumeCursor?.sessionFile ?? "",1528+ turnEntryIds: [...(resumeCursor?.turnEntryIds ?? [])],1529+ lastKnownLeaf: null,1530+ leafCursorStale: false,1531+ appliedModel: null,1532+ appliedThinking: null,1533+ baselineModel: null,1534+ baselineThinking: null,1535+ contextWindow: null,1536+ skillNames: null,1537+ stopRequested: false,1538+ unsolicitedActivityDetected: false,1539+ stopped: false,1540+ };1541+ // Startup can raise extension dialogs (for example project trust),1542+ // so the pump runs and the session is reachable before Pi answers.1543+ ctx.pumpFiber = yield* runEventPump(ctx).pipe(Effect.forkIn(sessionScope));1544+ sessions.set(input.threadId, ctx);1545+1546+ yield* Effect.gen(function* () {1547+ const stateData = yield* request(ctx, { type: "get_state" }, PI_SESSION_TIMEOUT_MS);
- apps/server/src/provider/Layers/PiAdapter.ts line 1477Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1451,21 @@1451+ provider: PROVIDER,1452+ threadId: input.threadId,1453+ detail,1454+ cause,1455+ });1456+ // The extension owns both the optional MCP bridge and Pi's1457+ // permission hook. Materialize it even when this session has no MCP1458+ // credential so Supervised never degrades to unrestricted tools.1459+ const extensionPath = yield* materializePiT3McpExtension(1460+ serverConfig.providerStatusCacheDir,1461+ ).pipe(1462+ Effect.provideService(FileSystem.FileSystem, fileSystem),1463+ Effect.mapError(processError("Failed to write the T3 Pi extension.")),1464+ );1465+1466+ // A missing session file cannot be resumed. Continue in a fresh Pi1467+ // session instead of leaving the thread unusable, and say so.1468+ const requestedCursor = Option.getOrUndefined(decodePiResumeCursor(input.resumeCursor));1469+ const resumeCursor =1470+ requestedCursor !== undefined &&1471+ (yield* fileSystemapps/server/src/provider/Layers/PiAdapter.ts lines 1252 to 1258Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1234,21 @@1234+ }1235+ return;1236+ default:1237+ return;1238+ }1239+ });1240+1241+ /**1242+ * Transport death completes any live turn and ends the session. Stop and1243+ * a failed settle close the stream on purpose; only an unexpected death1244+ * is reported as an error.1245+ */1246+ const handleTransportClosed = (ctx: PiSessionContext) =>1247+ Effect.gen(function* () {1248+ // stopSession already tore this session down.1249+ if (ctx.stopped) return;1250+ const turn = ctx.activeTurn;1251+ if (turn !== null) {1252+ turn.failure = turn.interrupted ? null : "Pi process exited unexpectedly.";1253+ yield* finalizeTurn(ctx, false);1254+ }apps/server/src/provider/Layers/PiAdapter.ts lines 1298 to 1298OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1278,21 @@1278+ }1279+ // Closing the scope interrupts this pump fiber, so it goes last.1280+ yield* Scope.close(ctx.scope, Exit.void).pipe(Effect.forkDetach);1281+ });1282+1283+ const runEventPump = (ctx: PiSessionContext) =>1284+ Effect.gen(function* () {1285+ while (true) {1286+ const event = yield* Queue.take(ctx.connection.events);1287+ yield* ctx.eventPermit.withPermits(1)(handleSessionEvent(ctx, event));1288+ }1289+ }).pipe(Effect.catchCause(() => ctx.eventPermit.withPermits(1)(handleTransportClosed(ctx))));1290+1291+ /** Tears down the process without reporting an exit. */1292+ const closeSession = (ctx: PiSessionContext) =>1293+ Effect.gen(function* () {1294+ ctx.stopped = true;1295+ ctx.stopRequested = true;1296+ forgetSession(ctx);1297+ if (ctx.pumpFiber !== undefined) yield* Fiber.interrupt(ctx.pumpFiber);1298+ yield* cancelPendingRequests(ctx);
- apps/server/src/provider/Layers/PiAdapter.ts line 1091Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1070,21 @@1070+ turn.compactionRunning1071+ ) {1072+ return;1073+ }1074+ if (event["probeFailed"] === true) {1075+ if (!settleAfterAgentActivity) {1076+ yield* finalizeTurn(ctx);1077+ return;1078+ }1079+ if (attempt < SETTLE_PROBE_MAX_ATTEMPTS) {1080+ yield* Effect.sleep(SETTLE_PROBE_RETRY_DELAY).pipe(1081+ Effect.andThen(scheduleSettleProbe(ctx, turn, true, attempt + 1)),1082+ Effect.forkIn(ctx.scope),1083+ );1084+ return;1085+ }1086+ ctx.stopRequested = true;1087+ yield* ctx.connection.terminate;1088+ return;1089+ }1090+ if (apps/server/src/provider/Layers/PiAdapter.ts lines 1604 to 1604OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1584,21 @@1584+ );1585+ ctx.lastKnownLeaf = recordString(baselineEntries, "leafId") ?? null;1586+ ctx.leafCursorStale = baselineEntries === undefined;1587+ // Mirror the thread title into Pi's session name so the session1588+ // stays identifiable in Pi's own /resume listing. Best-effort.1589+ if (input.title !== undefined) {1590+ yield* request(ctx, { type: "set_session_name", name: input.title }).pipe(1591+ Effect.ignore,1592+ );1593+ }1594+ }).pipe(Effect.onError(() => closeSession(ctx)));1595+1596+ // Discovery can invoke extension code and raise a blocking dialog,1597+ // so it never holds session start.1598+ yield* discoverSkillNames(ctx).pipe(1599+ Effect.tap((names) => Effect.sync(() => (ctx.skillNames = names))),1600+ Effect.ignore,1601+ Effect.forkIn(sessionScope),1602+ );1603+1604+ yield* updateSession(ctx, { status: "ready" });
- @@ -2443,3 +2444,12 @@24432444 ),24442445 { "rpc.aggregate": "provider" },24452446 ),2447+ [WS_METHODS.providerSessionCommand]: (input) =>2448+ observeRpcEffect(2449+ WS_METHODS.providerSessionCommand,2450+ providerService.sessionCommand(input).pipe(2451+ Effect.mapError(2452+ (cause) =>2453+ new ProviderSessionCommandError({2454+ threadId: input.threadId,2455+ detail: cause.message,
- @@ -0,0 +1868,21 @@1868+ });1869+ }1870+ if (ctx.activeTurn !== null) {1871+ return yield* new ProviderAdapterValidationError({1872+ provider: PROVIDER,1873+ operation: "rollbackThread",1874+ issue: "Cannot roll back while a Pi turn is active.",1875+ });1876+ }1877+ const keptTurns = Math.max(0, ctx.turnEntryIds.length - numTurns);1878+ // `fork(entryId)` re-roots the active branch before that user1879+ // message, so the boundary is the first discarded user message.1880+ const forkEntryId = piRollbackForkEntry(ctx.turnEntryIds.slice(keptTurns));1881+ if (forkEntryId === undefined) {1882+ return yield* new ProviderAdapterRequestError({1883+ provider: PROVIDER,1884+ method: "fork",1885+ detail: "The Pi rollback boundary was not recorded for this thread.",1886+ });1887+ }1888+ if (forkEntryId !== null) {@@ -10031,3 +10153,4 @@1003110153 ? openUsageLimits1003210154 : undefined1003310155 }10156+ onProviderCommand={
- @@ -0,0 +54,21 @@54+ // using the server's gh authentication rather than the client's credentials.55+ const launch = yield* resolveSpawnCommand(56+ "gh",57+ ["gist", "create", "--public=false", outputPath],58+ {59+ env: environment,60+ },61+ );62+ const result = yield* spawnAndCollect(63+ "gh",64+ ChildProcess.make(launch.command, launch.args, {65+ env: environment,66+ shell: launch.shell,67+ cwd,68+ }),69+ ).pipe(Effect.timeout("60 seconds"));70+ if (result.code !== 0) {71+ return yield* new PiRpcError({72+ operation: "share",73+ detail:74+ result.stderr.trim() || "GitHub CLI sharing failed. Run 'gh auth login' on the server.",
juliusmarminge added labelsmacroscope-review
Sign in to join this conversation.





macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed