feat(codex): wake threads from background monitoring events #10183
Closedtris203(GitHub profile, opens in a new tab)wants to merge 17 commits into
main fromrefs/pull/10183/headopened 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:XL
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2466OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2299,10 +2456,11 @@22992456 yield* client.request("thread/compact/start", { threadId: providerThreadId });23002457 }),23012458 sendTurn: (input) =>2302- Effect.gen(function* () {2303- const providerThreadId = yield* readProviderThreadId;2304- if (hasConfiguredMcpServer(options.appServerArgs)) {2305- yield* client.request("config/mcpServer/reload", undefined).pipe(2306- Effect.catch((cause) =>2307- Effect.logWarning("Failed to refresh Codex MCP tool catalog before turn.", {2308- cause,2459+ Effect.acquireUseRelease(2460+ Effect.sync(() => {2461+ pendingUserSends += 1;2462+ }),2463+ () =>2464+ turnLock.withPermit(2465+ Effect.gen(function* () {2466+ suppressMonitorWakes = false;
- apps/server/src/mcp/MonitorSession.ts lines 4 to 7OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,7 @@1+import * as Effect from "effect/Effect";2+import * as Schema from "effect/Schema";3+4+export class MonitorUnavailableError extends Schema.TaggedErrorClass<MonitorUnavailableError>()(5+ "MonitorUnavailableError",6+ { message: Schema.String },7+) {}apps/server/src/mcp/MonitorSession.ts lines 14 to 26OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +6,21 @@6+ { message: Schema.String },7+) {}8+9+export interface MonitorSession {10+ readonly subscribe: (processId: string) => Effect.Effect<void, MonitorUnavailableError>;11+ readonly unsubscribe: (processId: string) => Effect.Effect<void, MonitorUnavailableError>;12+}13+14+// Like McpProviderSession, the bridge lives only for the provider session.15+// Keying by credential session ID prevents a replaced runtime receiving calls16+// authenticated for its predecessor.17+const sessions = new Map<string, MonitorSession>();18+19+export const registerMonitorSession = (sessionId: string, session: MonitorSession) =>20+ Effect.acquireRelease(21+ Effect.sync(() => sessions.set(sessionId, session)),22+ () =>23+ Effect.sync(() => {24+ if (sessions.get(sessionId) === session) sessions.delete(sessionId);25+ }),26+ );apps/server/src/mcp/toolkits/monitor/handlers.ts lines 2 to 10OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,10 @@1+import * as Effect from "effect/Effect";2+import { McpInvocationContext } from "../../McpInvocationContext.ts";3+import { invokeMonitorSession, MonitorUnavailableError } from "../../MonitorSession.ts";4+import { MonitorToolkit } from "./tools.ts";5+6+const invoke = Effect.fn("MonitorToolkit.invoke")(function* (7+ operation: "subscribe" | "unsubscribe",8+ processId: string,9+) {10+ const scope = yield* McpInvocationContext;
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2599OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2390,0 +2579,21 @@2579+ .pipe(2580+ Effect.timeoutOrElse({2581+ duration: "10 seconds",2582+ orElse: () =>2583+ Effect.fail(2584+ CodexErrors.CodexAppServerRequestError.internalError(2585+ "Timed out stopping Codex background terminals.",2586+ ),2587+ ),2588+ }),2589+ );2590+ yield* decodeBackgroundCleanResponse(raw).pipe(2591+ Effect.mapError((error) =>2592+ CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(2593+ "decode-response-payload",2594+ error,2595+ { method: "thread/backgroundTerminals/clean" },2596+ ),2597+ ),2598+ );2599+ for (const task of backgroundTasks.stop()) {
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2505OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2308,0 +2485,21 @@2485+ ...(input.effort ? { effort: input.effort } : {}),2486+ ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),2487+ // Derived from the session's own MCP configuration rather than the2488+ // setting, so the prompt describes the tools this turn actually2489+ // has even if the setting changed after the session started.2490+ browserToolsAvailable:2491+ options.browserToolsAvailable ?? hasConfiguredMcpServer(options.appServerArgs),2492+ });2493+ const rawResponse = yield* client.raw.request("turn/start", params);2494+ const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(2495+ Effect.mapError((error) =>2496+ CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(2497+ "decode-response-payload",2498+ error,2499+ { method: "turn/start" },2500+ ),2501+ ),2502+ );2503+ const turnId = TurnId.make(response.turn.id);2504+ suppressMonitorWakes = false;2505+ queuedUserTurns.add(turnId);
- apps/server/src/mcp/McpProviderSession.ts line 8OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5,3 +5,4 @@55 readonly threadId: ThreadId;66 readonly providerSessionId: string;77 readonly providerInstanceId: ProviderInstanceId;8+ readonly capabilities?: ReadonlyArray<"preview" | "monitor">;
- apps/server/src/mcp/MonitorSession.ts line 34OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+}15+16+export class MonitorCapabilityError extends Schema.TaggedErrorClass<MonitorCapabilityError>()(17+ "MonitorCapabilityError",18+ {},19+) {20+ override get message() {21+ return "Monitoring is unavailable for this provider session.";22+ }23+}24+25+export class MonitorStoppedError extends Schema.TaggedErrorClass<MonitorStoppedError>()(26+ "MonitorStoppedError",27+ {},28+) {29+ override get message() {30+ return "Monitoring is unavailable or was stopped. Start a new turn to resume.";31+ }32+}33+34+export class MonitorProcessMissingError extends Schema.TaggedErrorClass<MonitorProcessMissingError>()(apps/server/src/provider/Layers/ProviderService.ts line 716OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -724,4 +710,7 @@724710 ),725711 );726712727- const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>713+ const prepareMcpSession = (714+ threadId: ThreadId,715+ providerInstanceId: ProviderInstanceId,716+ provider: string,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2427OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2299,0 +2407,21 @@2407+ const raw = yield* client.raw.request("turn/start", params).pipe(2408+ Effect.timeout("10 seconds"),2409+ Effect.tapError((error) =>2410+ Effect.sync(() => {2411+ // An explicit rejection is safe to retry. A timeout may have2412+ // been accepted, so preserve its evidence without replaying it.2413+ if (!suppressMonitorWakes && isCodexRequestError(error))2414+ backgroundTasks.restoreWake(wake);2415+ }),2416+ ),2417+ );2418+ const response = yield* decodeV2TurnStartResponse(raw).pipe(2419+ Effect.mapError((error) =>2420+ CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(2421+ "decode-response-payload",2422+ error,2423+ { method: "turn/start" },2424+ ),2425+ ),2426+ );2427+ yield* updateSession(sessionRef, (current) => ({
- apps/server/src/mcp/McpSessionRegistry.ts line 132OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -128,4 +129,4 @@128129 threadId: ThreadId.make(request.threadId),129130 providerSessionId,130131 providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),131- capabilities: new Set(["preview"]),132+ capabilities: new Set(request.capabilities ?? ["preview"]),
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2668OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2405,0 +2648,21 @@2648+ }),2649+ ),2650+ Effect.forkIn(runtimeScope, { startImmediately: true }),2651+ );2652+ return { monitorId, status: "scheduled" as const };2653+ }),2654+ )2655+ .pipe(2656+ Effect.mapError((cause) =>2657+ isMonitorStoppedError(cause)2658+ ? cause2659+ : new MonitorSession.MonitorStartError({ cause }),2660+ ),2661+ ),2662+ subscribe: Effect.fn("CodexSessionRuntime.subscribeMonitor")(function* (processId) {2663+ if (!monitoringAvailable || suppressMonitorWakes || (yield* Ref.get(closedRef)))2664+ return yield* new MonitorSession.MonitorStoppedError({});2665+ if (!backgroundTasks.subscribe(processId))2666+ return yield* new MonitorSession.MonitorProcessMissingError({ processId });2667+ }),2668+ unsubscribe: (processId) => Effect.sync(() => backgroundTasks.unsubscribe(processId)),
- apps/server/src/provider/Layers/CodexSessionRuntime.ts lines 2356 to 2360Resolvedby tris203(GitHub profile, opens in a new tab)@@ -2282,3 +2349,12 @@22822349 Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)),22832350 );228423512352+ yield* client.handleServerNotification("command/exec/outputDelta", (payload) =>2353+ Effect.gen(function* () {2354+ const decoders = monitorCommands.get(payload.processId);2355+ if (!decoders) return;2356+ backgroundTasks.output(2357+ payload.processId,2358+ decoders[payload.stream].decode(Buffer.from(payload.deltaBase64, "base64"), {2359+ stream: true,2360+ }),
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 2772Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2441,0 +2752,21 @@2752+ if (lastCompletedTurnId !== turnId) {2753+ queuedUserTurns.add(turnId);2754+ yield* updateSession(sessionRef, (session) => ({2755+ status: "running",2756+ // Codex accepts follow-ups while the current turn is still2757+ // running. The response contains the queued turn id, but2758+ // turn/interrupt only accepts the id that is active now.2759+ activeTurnId: session.activeTurnId ?? turnId,2760+ ...(normalizedModel ? { model: normalizedModel } : {}),2761+ }));2762+ }2763+ const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));2764+ return {2765+ threadId: options.threadId,2766+ turnId,2767+ ...(resumedProviderThreadId2768+ ? { resumeCursor: { threadId: resumedProviderThreadId } }2769+ : {}),2770+ } satisfies ProviderTurnStartResult;2771+ }).pipe(2772+ Effect.timeoutOrElse({
juliusmarminge closed this
Sign in to join this conversation.
Bugbot is paused — on-demand spend limit reached
Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.
A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.