diff --git a/apps/host-daemon/src/app.test.ts b/apps/host-daemon/src/app.test.ts index a477a195094..7837bb15689 100644 --- a/apps/host-daemon/src/app.test.ts +++ b/apps/host-daemon/src/app.test.ts @@ -12,6 +12,7 @@ import { import { hostDaemonEventBatchRequestSchema, hostDaemonInteractiveInterruptRequestSchema, + hostDaemonInteractiveWithdrawRequestSchema, type HostDaemonInteractiveRequestKey, type HostDaemonInteractiveRequestResponse, type HostDaemonContributedEnvEntry, @@ -191,6 +192,9 @@ function createFetchRecorder( }; return Response.json(response); } + if (url.pathname === "/internal/session/interactive-request/withdraw") { + return Response.json({ ok: true, interactionId: "pint_app_test" }); + } if (url.pathname === "/internal/session/interactive-request/interrupt") { const scripted = args.interruptResponses?.[interruptCount]; interruptCount += 1; @@ -1213,7 +1217,10 @@ describe("createHostDaemonApp", () => { if (!options?.onInteractiveRequest) { throw new Error("Expected runtime callbacks to be captured"); } - const pending = options.onInteractiveRequest(request); + const pending = options.onInteractiveRequest( + request, + new AbortController().signal, + ); const rejection = expect(pending).rejects.toMatchObject({ code: "interactive_request_ended", }); @@ -1441,7 +1448,10 @@ describe("createHostDaemonApp", () => { } const request = createCommandApprovalRequest(); - const pending = options.onInteractiveRequest(request); + const pending = options.onInteractiveRequest( + request, + new AbortController().signal, + ); await vi.waitFor(() => { expect( fetchRecorder.requests.filter( @@ -1501,6 +1511,71 @@ describe("createHostDaemonApp", () => { } }); + it("tells the server to close an interactive request the provider withdraws", async () => { + const { app, fetchRecorder, runtimeOptions } = await createAppFixture(); + try { + const workspacePath = await makeTempDir("bb-host-daemon-app-workspace-"); + await app.connection.start(); + await app.runtimeManager.ensureEnvironment({ + environmentId: "env-app-interactive", + workspacePath, + }); + const options = runtimeOptions.current; + if (!options?.onInteractiveRequest) { + throw new Error("Expected runtime callbacks to be captured"); + } + + const request = createCommandApprovalRequest(); + const provider = new AbortController(); + const pending = options.onInteractiveRequest(request, provider.signal); + await vi.waitFor(() => { + expect( + fetchRecorder.requests.filter( + (record) => + record.pathname === "/internal/session/interactive-request", + ), + ).toHaveLength(1); + }); + + provider.abort(); + await expect(pending).rejects.toMatchObject({ + code: "interactive_request_withdrawn", + }); + await vi.waitFor(() => { + expect( + fetchRecorder.requests.filter( + (record) => + record.pathname === + "/internal/session/interactive-request/withdraw", + ), + ).toHaveLength(1); + }); + const withdrawRequest = fetchRecorder.requests.find( + (record) => + record.pathname === "/internal/session/interactive-request/withdraw", + ); + if (!withdrawRequest?.body) { + throw new Error("Expected interactive withdraw request body"); + } + expect( + hostDaemonInteractiveWithdrawRequestSchema.parse( + JSON.parse(withdrawRequest.body), + ), + ).toEqual({ + sessionId: "session-app-test", + request: { + threadId: request.threadId, + providerId: request.providerId, + providerThreadId: request.providerThreadId, + providerRequestId: request.providerRequestId, + }, + reason: "The agent stopped waiting for this answer", + }); + } finally { + await app.daemon.shutdown("test", 0); + } + }); + it("drops an interactive interrupt the server rejects instead of retrying it ahead of later interrupts", async () => { const { app, fetchRecorder, logger, runtimeOptions } = await createAppFixture({ @@ -1718,9 +1793,9 @@ describe("createHostDaemonApp", () => { } const request = createCommandApprovalRequest(); - await expect(options.onInteractiveRequest(request)).rejects.toThrow( - "registration transport failed", - ); + await expect( + options.onInteractiveRequest(request, new AbortController().signal), + ).rejects.toThrow("registration transport failed"); expect(logger.error).toHaveBeenCalledWith( expect.objectContaining({ @@ -1760,9 +1835,9 @@ describe("createHostDaemonApp", () => { } const request = createCommandApprovalRequest(); - await expect(options.onInteractiveRequest(request)).rejects.toThrow( - "Ask User Question feature is disabled", - ); + await expect( + options.onInteractiveRequest(request, new AbortController().signal), + ).rejects.toThrow("Ask User Question feature is disabled"); expect(logger.warn).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/apps/host-daemon/src/app.ts b/apps/host-daemon/src/app.ts index 2292e1e0899..f3e21d58228 100644 --- a/apps/host-daemon/src/app.ts +++ b/apps/host-daemon/src/app.ts @@ -189,11 +189,21 @@ export interface HostDaemonApp { connection: ServerConnection; } -interface PendingInteractiveInterruptRequest { - providerId: string; - reason: string; - threadIds: readonly string[]; -} +type PendingInteractiveInterruptRequest = + | { + kind: "threads"; + providerId: string; + reason: string; + threadIds: readonly string[]; + } + | { + kind: "withdrawn"; + reason: string; + request: HostDaemonInteractiveRequestKey; + }; + +const WITHDRAWN_INTERACTIVE_REQUEST_REASON = + "The agent stopped waiting for this answer"; export function startIdleProviderSessionReaper( args: StartIdleProviderSessionReaperArgs, @@ -352,11 +362,40 @@ export async function createHostDaemonApp( function buildInteractiveInterruptKey( request: PendingInteractiveInterruptRequest, ): string { - return [ - request.providerId, - request.reason, - [...request.threadIds].sort().join(","), - ].join("|"); + switch (request.kind) { + case "threads": + return [ + request.kind, + request.providerId, + request.reason, + [...request.threadIds].sort().join(","), + ].join("|"); + case "withdrawn": + return [ + request.kind, + request.request.threadId, + request.request.providerId, + request.request.providerThreadId, + request.request.providerRequestId, + ].join("|"); + } + } + + function sendInteractiveInterrupt( + request: PendingInteractiveInterruptRequest, + ): Promise { + switch (request.kind) { + case "threads": + return runSessionRequest({ + source: "interruptInteractiveRequests", + request: () => serverClient.interruptInteractiveRequests(request), + }); + case "withdrawn": + return runSessionRequest({ + source: "withdrawInteractiveRequest", + request: () => serverClient.withdrawInteractiveRequest(request), + }); + } } function clearInteractiveInterruptRetry(): void { @@ -411,17 +450,15 @@ export async function createHostDaemonApp( const [key, request] = nextEntry; try { - await runSessionRequest({ - source: "interruptInteractiveRequests", - request: () => serverClient.interruptInteractiveRequests(request), - }); + await sendInteractiveInterrupt(request); pendingInteractiveInterrupts.delete(key); interactiveInterruptRetryDelayMs = INTERACTIVE_INTERRUPT_RETRY_DELAY_MS; } catch (error) { const logFields = { - providerId: request.providerId, - threadIds: request.threadIds, + ...(request.kind === "threads" + ? { providerId: request.providerId, threadIds: request.threadIds } + : request.request), ...runtimeErrorLogFields(error), }; if (isRejectedInteractiveInterrupt(error)) { @@ -479,11 +516,24 @@ export async function createHostDaemonApp( }), onRegistrationFailure: ({ error, request }) => { enqueueInteractiveInterrupt({ + kind: "threads", providerId: request.providerId, reason: `Failed to register interactive request while provider was waiting: ${error.message}`, threadIds: [request.threadId], }); }, + onRequestWithdrawn: (request) => { + enqueueInteractiveInterrupt({ + kind: "withdrawn", + reason: WITHDRAWN_INTERACTIVE_REQUEST_REASON, + request: { + threadId: request.threadId, + providerId: request.providerId, + providerThreadId: request.providerThreadId, + providerRequestId: request.providerRequestId, + }, + }); + }, }); let sendServerMessage = (_message: HostDaemonDaemonWsMessage) => false; @@ -661,10 +711,29 @@ export async function createHostDaemonApp( throw error; } }, - onInteractiveRequest: async (request) => { + onInteractiveRequest: async (request, signal) => { try { - return await interactiveRequestRegistry.registerAndWait(request); + return await interactiveRequestRegistry.registerAndWait( + request, + signal, + ); } catch (error) { + if ( + error instanceof InteractiveRequestRegistryError && + error.code === "interactive_request_withdrawn" + ) { + options.logger.info( + { + threadId: request.threadId, + providerThreadId: request.providerThreadId, + turnId: request.turnId, + providerRequestId: request.providerRequestId, + kind: request.payload.kind, + }, + "Interactive provider request withdrawn by the provider", + ); + throw error; + } if ( error instanceof InteractiveRequestRegistryError && (error.code === "interactive_request_rejected" || @@ -723,6 +792,7 @@ export async function createHostDaemonApp( }); enqueueInteractiveInterrupt({ + kind: "threads", providerId: info.providerId, threadIds, reason, diff --git a/apps/host-daemon/src/interactive-request-registry.test.ts b/apps/host-daemon/src/interactive-request-registry.test.ts index 97f11c927f9..6f51fb6ea38 100644 --- a/apps/host-daemon/src/interactive-request-registry.test.ts +++ b/apps/host-daemon/src/interactive-request-registry.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { PendingInteractionCreate, PendingInteractionResolution, @@ -11,6 +11,7 @@ import { } from "./interactive-request-registry.js"; interface CreateRegistryArgs { + onRequestWithdrawn?: (request: PendingInteractionCreate) => void; registerRequest: ( request: PendingInteractionCreate, ) => Promise; @@ -54,6 +55,7 @@ function createCommandApprovalResolution(): PendingInteractionResolution { function createRegistry(args: CreateRegistryArgs): InteractiveRequestRegistry { return new InteractiveRequestRegistry({ + onRequestWithdrawn: args.onRequestWithdrawn ?? (() => {}), registerRequest: args.registerRequest, }); } @@ -66,7 +68,10 @@ describe("InteractiveRequestRegistry", () => { const registry = createRegistry({ registerRequest: () => registration.promise, }); - const pending = registry.registerAndWait(request); + const pending = registry.registerAndWait( + request, + new AbortController().signal, + ); registry.endRequests( [ @@ -104,8 +109,14 @@ describe("InteractiveRequestRegistry", () => { status: "pending", }), }); - const ended = registry.registerAndWait(request); - const stillOpen = registry.registerAndWait(other); + const ended = registry.registerAndWait( + request, + new AbortController().signal, + ); + const stillOpen = registry.registerAndWait( + other, + new AbortController().signal, + ); const key = { threadId: request.threadId, providerId: request.providerId, @@ -149,8 +160,14 @@ describe("InteractiveRequestRegistry", () => { }, }); - const first = registry.registerAndWait(request); - const second = registry.registerAndWait(request); + const first = registry.registerAndWait( + request, + new AbortController().signal, + ); + const second = registry.registerAndWait( + request, + new AbortController().signal, + ); expect(registrations).toEqual([request]); registration.resolve({ @@ -184,7 +201,10 @@ describe("InteractiveRequestRegistry", () => { }), }); - const pending = registry.registerAndWait(request); + const pending = registry.registerAndWait( + request, + new AbortController().signal, + ); const command = { interactionId: "pint_registry", providerId: request.providerId, @@ -230,7 +250,9 @@ describe("InteractiveRequestRegistry", () => { }), }); - await expect(registry.registerAndWait(request)).rejects.toMatchObject({ + await expect( + registry.registerAndWait(request, new AbortController().signal), + ).rejects.toMatchObject({ code: "interactive_request_rejected", message: "Thread is already awaiting user interaction", name: "InteractiveRequestRegistryError", @@ -247,7 +269,10 @@ describe("InteractiveRequestRegistry", () => { }), }); - const pending = registry.registerAndWait(request); + const pending = registry.registerAndWait( + request, + new AbortController().signal, + ); registry.interruptThreads({ providerId: request.providerId, reason: "Provider exited", @@ -256,4 +281,91 @@ describe("InteractiveRequestRegistry", () => { await expect(pending).rejects.toThrow("Provider exited"); }); + + it("closes a request the provider withdraws only after the server registered it", async () => { + const request = createCommandApprovalRequest(); + const registration = + createDeferredPromise(); + const withdrawn: PendingInteractionCreate[] = []; + const registry = createRegistry({ + onRequestWithdrawn: (closed) => withdrawn.push(closed), + registerRequest: () => registration.promise, + }); + const provider = new AbortController(); + const pending = registry.registerAndWait(request, provider.signal); + + provider.abort(); + await expect(pending).rejects.toMatchObject({ + code: "interactive_request_withdrawn", + }); + expect(registry.listOpenRequests()).toEqual([]); + expect(withdrawn).toEqual([]); + + registration.resolve({ + outcome: "created", + interactionId: "pint_withdrawn", + status: "pending", + }); + await vi.waitFor(() => expect(withdrawn).toEqual([request])); + expect(() => + registry.resolve({ + interactionId: "pint_withdrawn", + providerId: request.providerId, + providerRequestId: request.providerRequestId, + providerThreadId: request.providerThreadId, + resolution: createCommandApprovalResolution(), + threadId: request.threadId, + }), + ).toThrowError(InteractiveRequestRegistryError); + }); + + it("does not report a withdrawal for a request the server never registered", async () => { + const request = createCommandApprovalRequest(); + const withdrawn: PendingInteractionCreate[] = []; + const registry = createRegistry({ + onRequestWithdrawn: (closed) => withdrawn.push(closed), + registerRequest: async () => ({ + outcome: "rejected", + reason: "Thread is already awaiting user interaction", + }), + }); + const provider = new AbortController(); + const pending = registry.registerAndWait(request, provider.signal); + provider.abort(); + + await expect(pending).rejects.toMatchObject({ + code: "interactive_request_withdrawn", + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(withdrawn).toEqual([]); + }); + + it("ignores a withdrawal after the answer reached the provider", async () => { + const request = createCommandApprovalRequest(); + const withdrawn: PendingInteractionCreate[] = []; + const registry = createRegistry({ + onRequestWithdrawn: (closed) => withdrawn.push(closed), + registerRequest: async () => ({ + outcome: "created", + interactionId: "pint_answered", + status: "pending", + }), + }); + const provider = new AbortController(); + const pending = registry.registerAndWait(request, provider.signal); + await new Promise((resolve) => setImmediate(resolve)); + registry.resolve({ + interactionId: "pint_answered", + providerId: request.providerId, + providerRequestId: request.providerRequestId, + providerThreadId: request.providerThreadId, + resolution: createCommandApprovalResolution(), + threadId: request.threadId, + }); + provider.abort(); + + await expect(pending).resolves.toEqual(createCommandApprovalResolution()); + await new Promise((resolve) => setImmediate(resolve)); + expect(withdrawn).toEqual([]); + }); }); diff --git a/apps/host-daemon/src/interactive-request-registry.ts b/apps/host-daemon/src/interactive-request-registry.ts index 413a03417ab..7b3cd6c73a4 100644 --- a/apps/host-daemon/src/interactive-request-registry.ts +++ b/apps/host-daemon/src/interactive-request-registry.ts @@ -28,6 +28,7 @@ interface InteractiveRequestRegistryOptions { onRegistrationFailure?: ( failure: InteractiveRequestRegistrationFailure, ) => void; + onRequestWithdrawn: (request: PendingInteractionCreate) => void; registerRequest: ( request: PendingInteractionCreate, ) => Promise; @@ -42,6 +43,7 @@ interface InterruptInteractiveThreadsArgs { interface PendingInteractiveRequestEntry { interactionId: string | null; promise: Promise; + registered: Promise; reject: (error: Error) => void; resolve: (resolution: PendingInteractionResolution) => void; request: PendingInteractionCreate; @@ -61,6 +63,13 @@ export class InteractiveRequestRegistryError extends Error { } } +function buildWithdrawnError(): InteractiveRequestRegistryError { + return new InteractiveRequestRegistryError( + "interactive_request_withdrawn", + "The provider withdrew this interactive request", + ); +} + function buildInteractiveRequestKey( request: Pick< PendingInteractionCreate, @@ -106,8 +115,9 @@ export class InteractiveRequestRegistry { constructor(private readonly options: InteractiveRequestRegistryOptions) {} - async registerAndWait( + registerAndWait( request: PendingInteractionCreate, + signal: AbortSignal, ): Promise { const key = buildInteractiveRequestKey(request); const existing = this.pendingEntries.get(key); @@ -115,6 +125,10 @@ export class InteractiveRequestRegistry { return existing.promise; } + if (signal.aborted) { + return Promise.reject(buildWithdrawnError()); + } + let resolveEntry: ( resolution: PendingInteractionResolution, ) => void = () => {}; @@ -129,17 +143,34 @@ export class InteractiveRequestRegistry { const entry: PendingInteractiveRequestEntry = { interactionId: null, promise, + registered: Promise.resolve(false), reject: (error) => rejectEntry(error), resolve: (resolution) => resolveEntry(resolution), request, }; this.pendingEntries.set(key, entry); + entry.registered = this.register(key, entry); + const onAbort = (): void => this.withdraw(key, entry); + signal.addEventListener("abort", onAbort, { once: true }); + void promise + .catch(() => undefined) + .finally(() => signal.removeEventListener("abort", onAbort)); + return promise; + } + private async register( + key: string, + entry: PendingInteractiveRequestEntry, + ): Promise { try { - const response = await this.options.registerRequest(request); + const response = await this.options.registerRequest(entry.request); if (this.pendingEntries.get(key) === entry) { this.applyRegistrationResponse(key, entry, response); } + return ( + response.outcome !== "rejected" && + (response.status === "pending" || response.status === "resolving") + ); } catch (error) { if (this.pendingEntries.get(key) === entry) { this.pendingEntries.delete(key); @@ -147,12 +178,24 @@ export class InteractiveRequestRegistry { const registrationError = normalizeCaughtError(error); this.options.onRegistrationFailure?.({ error: registrationError, - request, + request: entry.request, }); entry.reject(registrationError); + return false; } + } - return promise; + private withdraw(key: string, entry: PendingInteractiveRequestEntry): void { + if (this.pendingEntries.get(key) !== entry) { + return; + } + this.pendingEntries.delete(key); + entry.reject(buildWithdrawnError()); + void entry.registered.then((registered) => { + if (registered) { + this.options.onRequestWithdrawn(entry.request); + } + }); } private applyRegistrationResponse( diff --git a/apps/host-daemon/src/runtime-manager.ts b/apps/host-daemon/src/runtime-manager.ts index 4ff596ce1d9..8d38d8e98b3 100644 --- a/apps/host-daemon/src/runtime-manager.ts +++ b/apps/host-daemon/src/runtime-manager.ts @@ -11,13 +11,7 @@ import { } from "@bb/agent-runtime"; import type { Logger } from "@bb/logger"; import { sliceUtf16Tail } from "@bb/text-utils"; -import { - type PendingInteractionCreate, - type PendingInteractionResolution, - type ThreadEvent, - threadScope, - turnScope, -} from "@bb/domain"; +import { type ThreadEvent, threadScope, turnScope } from "@bb/domain"; import type { HostDaemonActiveThread, HostDaemonContributedEnvEntry, @@ -188,9 +182,7 @@ export interface RuntimeManagerOptions { onDataDirSkillsWatchError?: (args: { error: DataDirSkillsWatchError; }) => void; - onInteractiveRequest?: ( - request: PendingInteractionCreate, - ) => Promise; + onInteractiveRequest?: AgentRuntimeOptions["onInteractiveRequest"]; onToolCall?: AgentRuntimeOptions["onToolCall"]; onStderr?: AgentRuntimeOptions["onStderr"]; onProcessExit?: AgentRuntimeOptions["onProcessExit"]; diff --git a/apps/host-daemon/src/server-client.ts b/apps/host-daemon/src/server-client.ts index 99a60c1897d..5870953b58a 100644 --- a/apps/host-daemon/src/server-client.ts +++ b/apps/host-daemon/src/server-client.ts @@ -7,11 +7,15 @@ import { hostDaemonEventBatchResponseSchema, hostDaemonInteractiveInterruptResponseSchema, hostDaemonInteractiveRequestResponseSchema, + hostDaemonInteractiveWithdrawResponseSchema, hostDaemonSessionOpenResponseSchema, hostDaemonSkillTreeManifestSchema, hostDaemonToolCallResponseSchema, type HostDaemonInteractiveInterruptResponse, + type HostDaemonInteractiveRequestKey, type HostDaemonInteractiveRequestResponse, + type HostDaemonInteractiveWithdrawRequest, + type HostDaemonInteractiveWithdrawResponse, type HostDaemonActiveThread, type HostDaemonOpenThreadWork, type HostDaemonEventBatchRequest, @@ -232,6 +236,10 @@ export interface ServerClient { reason: string; threadIds: readonly string[]; }): Promise; + withdrawInteractiveRequest(args: { + reason: string; + request: HostDaemonInteractiveRequestKey; + }): Promise; } const INTERACTIVE_REQUEST_REGISTRATION_RETRIES = 5; @@ -629,5 +637,34 @@ export function createServerClient( await response.json(), ); }, + + async withdrawInteractiveRequest( + args, + ): Promise { + const payload: HostDaemonInteractiveWithdrawRequest = { + sessionId: requireSessionId(), + request: args.request, + reason: args.reason, + }; + const response = await fetchFn( + buildInternalUrl("/session/interactive-request/withdraw"), + { + method: "POST", + headers: headers(), + body: JSON.stringify(payload), + }, + ); + + if (!response.ok) { + throw await createResponseError( + "withdraw interactive request", + response, + ); + } + + return hostDaemonInteractiveWithdrawResponseSchema.parse( + await response.json(), + ); + }, }; } diff --git a/apps/host-daemon/src/server-connection.test.ts b/apps/host-daemon/src/server-connection.test.ts index 61bd9b9db55..138477132b9 100644 --- a/apps/host-daemon/src/server-connection.test.ts +++ b/apps/host-daemon/src/server-connection.test.ts @@ -113,6 +113,7 @@ function createServerClientFixture(args: CreateServerClientFixtureArgs = {}) { callTool: unused, registerInteractiveRequest: unused, interruptInteractiveRequests: unused, + withdrawInteractiveRequest: unused, } satisfies ServerClient; return { diff --git a/apps/host-daemon/src/server-connection.ts b/apps/host-daemon/src/server-connection.ts index 1e2dc2ca3b0..b5e7e680e3e 100644 --- a/apps/host-daemon/src/server-connection.ts +++ b/apps/host-daemon/src/server-connection.ts @@ -61,7 +61,8 @@ export type ServerSessionInvalidationSource = | "fetchPluginHostArtifact" | "interruptInteractiveRequests" | "postEvents" - | "registerInteractiveRequest"; + | "registerInteractiveRequest" + | "withdrawInteractiveRequest"; export interface HandleServerSessionInvalidatedArgs { code: "inactive_session"; diff --git a/apps/server/src/internal/interactive-requests.ts b/apps/server/src/internal/interactive-requests.ts index e4ae508e06d..469ec5cb814 100644 --- a/apps/server/src/internal/interactive-requests.ts +++ b/apps/server/src/internal/interactive-requests.ts @@ -1,6 +1,7 @@ import { hostDaemonInteractiveInterruptRequestSchema, hostDaemonInteractiveRequestSchema, + hostDaemonInteractiveWithdrawRequestSchema, typedRoutes, type HostDaemonInternalSchema, } from "@bb/host-daemon-contract"; @@ -14,6 +15,37 @@ import { } from "../services/lib/entity-lookup.js"; import { requireAuthenticatedDaemonSession } from "./session-state.js"; +function sessionHostThreadExists( + deps: AppDeps, + args: { hostId: string; threadId: string }, +): boolean { + let environmentHostId: string; + try { + const { environment } = requireThreadEnvironmentAllowingDestroyed( + deps.db, + args.threadId, + ); + environmentHostId = environment.hostId; + } catch (error) { + if ( + error instanceof ApiError && + (error.status === 404 || + error.body.code === "thread_environment_unavailable") + ) { + return false; + } + throw error; + } + if (environmentHostId !== args.hostId) { + throw new ApiError( + 403, + "invalid_request", + "Thread does not belong to the session host", + ); + } + return true; +} + export function registerInternalInteractiveRequestRoutes( app: Hono, deps: AppDeps, @@ -96,31 +128,14 @@ export function registerInternalInteractiveRequestRoutes( const interruptibleThreadIds: string[] = []; for (const threadId of payload.threadIds) { - let environmentHostId: string; - try { - const { environment } = requireThreadEnvironmentAllowingDestroyed( - deps.db, + if ( + sessionHostThreadExists(deps, { + hostId: session.hostId, threadId, - ); - environmentHostId = environment.hostId; - } catch (error) { - if ( - error instanceof ApiError && - (error.status === 404 || - error.body.code === "thread_environment_unavailable") - ) { - continue; - } - throw error; + }) + ) { + interruptibleThreadIds.push(threadId); } - if (environmentHostId !== session.hostId) { - throw new ApiError( - 403, - "invalid_request", - "Thread does not belong to the session host", - ); - } - interruptibleThreadIds.push(threadId); } const interrupted = @@ -136,4 +151,35 @@ export function registerInternalInteractiveRequestRoutes( }); }, ); + + post( + "/session/interactive-request/withdraw", + hostDaemonInteractiveWithdrawRequestSchema, + (context, payload) => { + const session = requireAuthenticatedDaemonSession({ + context, + db: deps.db, + sessionId: payload.sessionId, + }); + + if ( + !sessionHostThreadExists(deps, { + hostId: session.hostId, + threadId: payload.request.threadId, + }) + ) { + return context.json({ ok: true, interactionId: null }); + } + + const interrupted = + deps.pendingInteractions.interruptWithdrawnProviderRequest({ + ...payload.request, + reason: payload.reason, + }); + return context.json({ + ok: true, + interactionId: interrupted?.id ?? null, + }); + }, + ); } diff --git a/apps/server/src/services/interactions/pending-interaction-timeline.ts b/apps/server/src/services/interactions/pending-interaction-timeline.ts index f8fae806b15..dbe7f8d7460 100644 --- a/apps/server/src/services/interactions/pending-interaction-timeline.ts +++ b/apps/server/src/services/interactions/pending-interaction-timeline.ts @@ -136,9 +136,12 @@ function approvalItemWriteFor(interaction: PendingInteraction): { return item === null ? null : { interaction, item }; } +type PendingInteractionSubjectItemOwner = "server" | "provider"; + function buildPendingInteractionTimelineWrites( db: Pick["db"] | DbTransaction, interaction: PendingInteraction, + subjectItemOwner: PendingInteractionSubjectItemOwner, ): AppendStoredThreadEventArgs[] { const environmentId = getThread(db, interaction.threadId)?.environmentId ?? null; @@ -151,7 +154,8 @@ function buildPendingInteractionTimelineWrites( data: { interaction: toInteractionLifecycle(interaction) }, }, ]; - const write = approvalItemWriteFor(interaction); + const write = + subjectItemOwner === "server" ? approvalItemWriteFor(interaction) : null; if (write !== null) { const { providerThreadId, turnId } = write.interaction; writes.push({ @@ -169,10 +173,12 @@ function buildPendingInteractionTimelineWrites( export function appendPendingInteractionTimelineEvent( deps: Pick, interaction: PendingInteraction, + subjectItemOwner: PendingInteractionSubjectItemOwner, ): void { for (const write of buildPendingInteractionTimelineWrites( deps.db, interaction, + subjectItemOwner, )) { appendThreadEvent(deps, write); } @@ -182,7 +188,11 @@ export function appendPendingInteractionTimelineEventInTransaction( deps: PendingInteractionTimelineTransactionDeps, interaction: PendingInteraction, ): void { - const writes = buildPendingInteractionTimelineWrites(deps.db, interaction); + const writes = buildPendingInteractionTimelineWrites( + deps.db, + interaction, + "server", + ); for (const write of writes) { appendThreadEventInTransaction(deps.db, write); } diff --git a/apps/server/src/services/interactions/pending-interactions.ts b/apps/server/src/services/interactions/pending-interactions.ts index 2548f1f48b9..e86582daad5 100644 --- a/apps/server/src/services/interactions/pending-interactions.ts +++ b/apps/server/src/services/interactions/pending-interactions.ts @@ -263,6 +263,14 @@ interface InterruptPendingInteractionsForThreadsLifecycleArgs { threadIds: readonly string[]; } +interface InterruptWithdrawnProviderRequestArgs { + providerId: string; + providerRequestId: string; + providerThreadId: string; + reason: string; + threadId: string; +} + interface InterruptPendingInteractionsForThreadIdsLifecycleArgs { reason: string; threadIds: readonly string[]; @@ -646,7 +654,7 @@ export class PendingInteractionLifecycle { thread: Thread, interaction: PendingInteraction, ): void { - appendPendingInteractionTimelineEvent(this.deps, interaction); + appendPendingInteractionTimelineEvent(this.deps, interaction, "server"); notifyInteractionChanged({ deps: this.deps, threadId: interaction.threadId, @@ -931,6 +939,30 @@ export class PendingInteractionLifecycle { ); } + interruptWithdrawnProviderRequest( + args: InterruptWithdrawnProviderRequestArgs, + ): PendingInteraction | null { + const row = getPendingInteractionByProviderRequest(this.deps.db, args); + if (!row || row.threadId !== args.threadId) { + return null; + } + const updated = setPendingInteractionInterrupted(this.deps.db, { + id: row.id, + statusReason: args.reason, + }); + if (!updated) { + return null; + } + const interaction = toPendingInteraction(updated); + appendPendingInteractionTimelineEvent(this.deps, interaction, "provider"); + notifyInteractionChanged({ + deps: this.deps, + threadId: interaction.threadId, + }); + this.notifyInteractionSettled(interaction.threadId); + return interaction; + } + interruptPendingInteractionsForThreadIds( args: InterruptPendingInteractionsForThreadIdsLifecycleArgs, ): PendingInteraction[] { @@ -1171,7 +1203,7 @@ export class PendingInteractionLifecycle { interaction: PendingInteraction, ): void { this.endProviderWaitForInterruptedInteraction(interaction); - appendPendingInteractionTimelineEvent(this.deps, interaction); + appendPendingInteractionTimelineEvent(this.deps, interaction, "server"); notifyInteractionChanged({ deps: this.deps, threadId: interaction.threadId, diff --git a/apps/server/test/internal/internal-interactive-requests.test.ts b/apps/server/test/internal/internal-interactive-requests.test.ts index 35931b5552e..d1e779332a2 100644 --- a/apps/server/test/internal/internal-interactive-requests.test.ts +++ b/apps/server/test/internal/internal-interactive-requests.test.ts @@ -670,6 +670,93 @@ describe("internal interactive request lifecycle", () => { }); }); + it("interrupts only the interaction whose provider request was withdrawn", async () => { + await withTestHarness(async (harness) => { + const { host, session } = seedHostSession(harness.deps, { + id: "host-interaction-withdraw", + }); + const { project } = seedProjectWithSource(harness.deps, { + hostId: host.id, + }); + const environment = seedEnvironment(harness.deps, { + hostId: host.id, + projectId: project.id, + }); + const thread = seedThread(harness.deps, { + projectId: project.id, + environmentId: environment.id, + }); + const body = buildCommandApprovalInteractiveRequest({ + sessionId: session.id, + suffix: "withdraw", + threadId: thread.id, + }); + const registered = await registerInteractiveRequest({ body, harness }); + expect(registered.status).toBe(200); + const interactionId = await waitForPendingInteractionId({ + harness, + threadId: thread.id, + }); + const key = { + threadId: thread.id, + providerId: body.interaction.providerId, + providerThreadId: body.interaction.providerThreadId, + providerRequestId: body.interaction.providerRequestId, + }; + const withdraw = (providerRequestId: string) => + harness.app.request("/internal/session/interactive-request/withdraw", { + method: "POST", + headers: internalAuthHeaders(harness), + body: JSON.stringify({ + sessionId: session.id, + request: { ...key, providerRequestId }, + reason: "The agent withdrew this request", + }), + }); + + const unrelated = await withdraw("request-someone-else"); + expect(unrelated.status).toBe(200); + await expect(readJson(unrelated)).resolves.toEqual({ + ok: true, + interactionId: null, + }); + expect( + harness.deps.pendingInteractions.listPendingThreadInteractions( + thread.id, + ), + ).toEqual([expect.objectContaining({ id: interactionId })]); + + const withdrawn = await withdraw(key.providerRequestId); + expect(withdrawn.status).toBe(200); + await expect(readJson(withdrawn)).resolves.toEqual({ + ok: true, + interactionId, + }); + expect( + listPendingInteractionsByThread(harness.db, { + threadId: thread.id, + }).map(toPendingInteraction), + ).toEqual([ + expect.objectContaining({ + id: interactionId, + status: "interrupted", + statusReason: "The agent withdrew this request", + }), + ]); + expect( + harness.deps.pendingInteractions.listPendingThreadInteractions( + thread.id, + ), + ).toEqual([]); + + const repeated = await withdraw(key.providerRequestId); + await expect(readJson(repeated)).resolves.toEqual({ + ok: true, + interactionId: null, + }); + }); + }); + it("skips deleted threads in interrupt batches and still interrupts live threads", async () => { await withTestHarness(async (harness) => { const { host, session } = seedHostSession(harness.deps, { diff --git a/apps/server/test/services/pending-interactions.test.ts b/apps/server/test/services/pending-interactions.test.ts index 695b0044fc8..89c8834ceed 100644 --- a/apps/server/test/services/pending-interactions.test.ts +++ b/apps/server/test/services/pending-interactions.test.ts @@ -1878,6 +1878,77 @@ describe("pending interaction lifecycle", () => { }); }); + it("leaves a withdrawn approval's item for the provider to settle", async () => { + await withTestHarness(async (harness) => { + const { host } = seedHostSession(harness.deps, { + id: "host-pending-interaction-withdrawn", + }); + const { project } = seedProjectWithSource(harness.deps, { + hostId: host.id, + }); + const environment = seedEnvironment(harness.deps, { + hostId: host.id, + projectId: project.id, + }); + const thread = seedThread(harness.deps, { + projectId: project.id, + environmentId: environment.id, + }); + const writes = () => + harness.db + .select() + .from(eventTable) + .where(eq(eventTable.threadId, thread.id)) + .orderBy(eventTable.sequence) + .all() + .filter( + (row) => + row.type === "system/interaction/lifecycle" || + row.type.startsWith("item/"), + ) + .map((row) => row.type); + const request = { + threadId: thread.id, + turnId: "turn-withdrawn", + providerId: "codex", + providerThreadId: "provider-thread-withdrawn", + providerRequestId: "request-withdrawn", + }; + const created = registerPendingInteraction( + harness.deps, + harness.deps.pendingInteractions, + { + ...request, + payload: createCommandApprovalPayload({ itemId: "item-withdrawn" }), + }, + ); + if (created.outcome === "rejected") { + throw new Error(`Expected registration to succeed: ${created.reason}`); + } + + const withdrawn = + harness.deps.pendingInteractions.interruptWithdrawnProviderRequest({ + ...request, + reason: "The agent stopped waiting for this answer", + }); + + expect(withdrawn).toMatchObject({ + id: created.interaction.id, + status: "interrupted", + }); + expect(writes()).toEqual([ + "system/interaction/lifecycle", + "item/started", + "system/interaction/lifecycle", + ]); + expect( + harness.deps.pendingInteractions.listPendingThreadInteractions( + thread.id, + ), + ).toEqual([]); + }); + }); + it("carries a provider's plugin-defined request to the plugin form and its answer back as a request answer", async () => { await withTestHarness(async (harness) => { const { host } = seedHostSession(harness.deps, { diff --git a/docs/provider-bridge-protocol.md b/docs/provider-bridge-protocol.md index d2be595d9dc..b91739775a5 100644 --- a/docs/provider-bridge-protocol.md +++ b/docs/provider-bridge-protocol.md @@ -161,6 +161,13 @@ deltas and owns every timeline invariant: `interaction/request` carries an approval, a user question, or a plugin-defined request (`"/"`); the resolution pairs with the payload kind ([provider-plugin-api.md](provider-plugin-api.md) §4). +- **Withdrawn requests.** A bridge that stops waiting on an + `interaction/request` or `item/tool/call` it sent (the provider answered + or cancelled it, it timed out, or the session ended) sends + `notifications/cancelled { requestId }` with that request's JSON-RPC id. + The runtime then never answers it: a withdrawn tool call is aborted, and a + withdrawn interaction is closed on the server as interrupted, so its card + no longer holds back the thread's next message. - **Turn lifecycle.** Only `turn.open`, a claiming `turn.boundary` (`claimIfIdle`), and accepted-input lifecycle settlement ever open a turn; item/stream deltas never do. Accepted input queues until a turn diff --git a/docs/provider-plugin-api.md b/docs/provider-plugin-api.md index 9fc3f1b5b52..3b7f5d99111 100644 --- a/docs/provider-plugin-api.md +++ b/docs/provider-plugin-api.md @@ -271,8 +271,8 @@ bridge published as `bb/session-options` **Bridge → runtime**: notifications `thread/delta` (one streaming dialect, one usage dialect), `thread/identity`, `session/replaced`, `provider/recovery`, -`provider/raw`, and `error`, plus the request channels `item/tool/call` and -`interaction/request`. +`provider/raw`, `notifications/cancelled`, and `error`, plus the request +channels `item/tool/call` and `interaction/request`. Recovery is typed, never text-matched: @@ -422,8 +422,13 @@ back as `{ kind: "request_answer", value }` — the form's submitted value, capped at 64 KiB (`PLUGIN_INTERACTION_MAX_PAYLOAD_BYTES`, the same cap on the request's `data`). The server accepts a request only while the plugin named by the prefix is loaded; a request for an unknown plugin is refused with an -error the bridge sees. A provider's request has no cancel; backing out stops -the turn, as with a provider's question. `value` is untrusted input to the +error the bridge sees. The user cannot cancel a provider's request; backing out +stops the turn, as with a provider's question. When the provider stops waiting +on its own (a hook answered it, it timed out, or the provider resolved it), the +bridge sends `notifications/cancelled` (`BRIDGE_NOTIFICATION_METHODS.requestCancelled`) +with `{ requestId }`, the JSON-RPC id of its `interaction/request`, and +does not expect a response. bb closes the card as interrupted, and the next +queued message can dispatch. `value` is untrusted input to the bridge: no form schema exists for the server to validate it against, so a bridge parses it as it would any client-supplied JSON. diff --git a/packages/agent-runtime/src/permission-matrix.test.ts b/packages/agent-runtime/src/permission-matrix.test.ts index 70f9cbe2181..d3a74b59502 100644 --- a/packages/agent-runtime/src/permission-matrix.test.ts +++ b/packages/agent-runtime/src/permission-matrix.test.ts @@ -1,4 +1,4 @@ -import { RuntimeToolCalls } from "./runtime-provider-requests.js"; +import { RuntimeProviderRequests } from "./runtime-provider-requests.js"; import { spawn, type ChildProcess } from "node:child_process"; import readline from "node:readline"; import type { @@ -385,7 +385,8 @@ async function runCell( }; const rawRequest = interactionRequest(requestId, payload); handleRuntimeProviderRequest({ - toolCalls: new RuntimeToolCalls(), + interactiveRequests: new RuntimeProviderRequests(), + toolCalls: new RuntimeProviderRequests(), getActiveTurnId: () => "turn-1", getThreadExecutionOptions: () => executionOptions, onInteractiveRequest, diff --git a/packages/agent-runtime/src/runtime-provider-requests.ts b/packages/agent-runtime/src/runtime-provider-requests.ts index b7ef2c47bd6..376ef17ecda 100644 --- a/packages/agent-runtime/src/runtime-provider-requests.ts +++ b/packages/agent-runtime/src/runtime-provider-requests.ts @@ -20,7 +20,13 @@ import { } from "@bb/provider-bridge-protocol/bridge-kit"; import { shouldAutoDenyInteractiveRequest } from "@bb/provider-bridge-protocol/bridge-kit"; -export class RuntimeToolCalls { +interface RuntimeProviderRequestOwner { + requestId: string | number; + threadId: string; + turnId: string; +} + +export class RuntimeProviderRequests { private readonly pending = new Map< string, Map< @@ -33,7 +39,10 @@ export class RuntimeToolCalls { > >(); - start(scope: string, request: ToolCallRequest): AbortController | null { + start( + scope: string, + request: RuntimeProviderRequestOwner, + ): AbortController | null { let calls = this.pending.get(scope); if (!calls) { calls = new Map(); @@ -60,11 +69,12 @@ export class RuntimeToolCalls { if (calls?.size === 0) this.pending.delete(scope); } - cancel(scope: string, requestId: string | number): void { + cancel(scope: string, requestId: string | number): boolean { const call = this.pending.get(scope)?.get(requestId); - if (!call) return; + if (!call) return false; this.finish(scope, requestId, call.controller); call.controller.abort(); + return true; } cancelThread(threadId: string, turnId?: string): void { @@ -110,7 +120,8 @@ interface HandleRuntimeProviderRequestArgs extends RuntimeProviderRequestArgs { ) => AgentRuntimeExecutionOptions | undefined; onInteractiveRequest: AgentRuntimeOptions["onInteractiveRequest"]; onToolCall: AgentRuntimeOptions["onToolCall"]; - toolCalls: RuntimeToolCalls; + interactiveRequests: RuntimeProviderRequests; + toolCalls: RuntimeProviderRequests; resolveThreadId: ( args: ResolveRuntimeProviderRequestThreadIdArgs, ) => string | null; @@ -342,9 +353,17 @@ function handleInteractiveProviderRequest( return true; } + const scope = args.providerProcess.interactiveRequestScope; + const controller = args.interactiveRequests.start(scope, { + requestId: interactiveReq.requestId, + threadId: resolvedThreadId, + turnId: resolvedTurnId, + }); + if (!controller) return true; void args - .onInteractiveRequest(scopedInteractiveReq) + .onInteractiveRequest(scopedInteractiveReq, controller.signal) .then((resolution) => { + if (controller.signal.aborted) return; const result = buildInteractiveResponse({ request: resolvedInteractiveReq, resolution, @@ -356,6 +375,7 @@ function handleInteractiveProviderRequest( }); }) .catch((err) => { + if (controller.signal.aborted) return; if ( sendProviderResponseEncodeErrorIfKnown({ child: args.providerProcess.child, @@ -370,7 +390,14 @@ function handleInteractiveProviderRequest( id: args.parsedId, message: err instanceof Error ? err.message : String(err), }); - }); + }) + .finally(() => + args.interactiveRequests.finish( + scope, + interactiveReq.requestId, + controller, + ), + ); return true; } diff --git a/packages/agent-runtime/src/runtime-tool-cancellation.test.ts b/packages/agent-runtime/src/runtime-tool-cancellation.test.ts index bf83ee8ad2e..5286e83eb09 100644 --- a/packages/agent-runtime/src/runtime-tool-cancellation.test.ts +++ b/packages/agent-runtime/src/runtime-tool-cancellation.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { RuntimeToolCalls } from "./runtime-provider-requests.js"; +import { RuntimeProviderRequests } from "./runtime-provider-requests.js"; const request = { requestId: 1, @@ -12,7 +12,7 @@ const request = { describe("runtime tool cancellation ownership", () => { it("scopes cancellation to the requesting process and preserves JSON-RPC id types", () => { - const calls = new RuntimeToolCalls(); + const calls = new RuntimeProviderRequests(); const first = calls.start("process-a", request)!; const otherProcess = calls.start("process-b", request)!; const stringId = calls.start("process-a", { ...request, requestId: "1" })!; @@ -28,7 +28,7 @@ describe("runtime tool cancellation ownership", () => { }); it("cancels only the finishing turn and cancels all requests on thread detach", () => { - const calls = new RuntimeToolCalls(); + const calls = new RuntimeProviderRequests(); const old = calls.start("process", request)!; const next = calls.start("process", { ...request, diff --git a/packages/agent-runtime/src/runtime.interactive-requests.test.ts b/packages/agent-runtime/src/runtime.interactive-requests.test.ts index dfef78f8271..19f7a7d7d53 100644 --- a/packages/agent-runtime/src/runtime.interactive-requests.test.ts +++ b/packages/agent-runtime/src/runtime.interactive-requests.test.ts @@ -1,4 +1,4 @@ -import { RuntimeToolCalls } from "./runtime-provider-requests.js"; +import { RuntimeProviderRequests } from "./runtime-provider-requests.js"; import { spawn, type ChildProcess } from "node:child_process"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -105,7 +105,8 @@ async function answerDirectRequest(args: { } try { handleRuntimeProviderRequest({ - toolCalls: new RuntimeToolCalls(), + interactiveRequests: new RuntimeProviderRequests(), + toolCalls: new RuntimeProviderRequests(), getActiveTurnId: args.getActiveTurnId ?? (() => "bb-turn-1"), getThreadExecutionOptions: args.getThreadExecutionOptions ?? (() => undefined), @@ -205,6 +206,52 @@ describe("createAgentRuntime interactive requests", () => { await runtime.shutdown(); }); + it("aborts the pending interactive request when the bridge withdraws it", async () => { + const signals: AbortSignal[] = []; + const events: ThreadEvent[] = []; + const runtime = createScriptedEchoRuntime({ + runtime: { + workspacePath: tmpDir, + onEvent: (event) => events.push(event), + onInteractiveRequest: (_request, signal) => { + signals.push(signal); + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }); + }, + }, + }); + + await runtime.startThread({ + environmentId: "env-1", + threadId: "t1", + projectId: "p1", + providerId: "fake", + options: fullRuntimeOptions, + }); + await runtime.runTurn({ + clientRequestId: "creq_222222224w", + threadId: "t1", + input: [ + promptTextInput({ text: "approve:command withdraw_approval delay:20" }), + ], + options: fullRuntimeOptions, + }); + await waitForThreadAgentMessageText({ + events, + providerId: "fake", + runtime, + text: "Approval withdrawn", + threadId: "t1", + }); + + expect(signals).toHaveLength(1); + expect(signals[0]?.aborted).toBe(true); + await runtime.shutdown(); + }); + it("completes the turn with Denied when the user denies the approval", async () => { const requests: PendingInteractionCreate[] = []; const events: ThreadEvent[] = []; @@ -538,6 +585,7 @@ describe("createAgentRuntime interactive requests", () => { turnId: expectedTurnId, payload: expect.objectContaining({ kind: "secrets/secret-request" }), }), + expect.any(AbortSignal), ); expect(answer).toMatchObject({ jsonrpc: "2.0", diff --git a/packages/agent-runtime/src/runtime.tool-calls.test.ts b/packages/agent-runtime/src/runtime.tool-calls.test.ts index 5588e873708..0f08adc6c30 100644 --- a/packages/agent-runtime/src/runtime.tool-calls.test.ts +++ b/packages/agent-runtime/src/runtime.tool-calls.test.ts @@ -7,7 +7,7 @@ import type { ThreadEvent, ToolCallResponse } from "@bb/domain"; import { createProviderForId } from "./provider-registry.js"; import { handleRuntimeProviderRequest, - RuntimeToolCalls, + RuntimeProviderRequests, } from "./runtime-provider-requests.js"; import { parseJsonRpcLine, @@ -246,7 +246,8 @@ describe("createAgentRuntime tool calls", () => { try { handleRuntimeProviderRequest({ - toolCalls: new RuntimeToolCalls(), + interactiveRequests: new RuntimeProviderRequests(), + toolCalls: new RuntimeProviderRequests(), getActiveTurnId: () => null, getThreadExecutionOptions: () => undefined, onInteractiveRequest: async () => ({ @@ -310,7 +311,8 @@ describe("createAgentRuntime tool calls", () => { try { handleRuntimeProviderRequest({ - toolCalls: new RuntimeToolCalls(), + interactiveRequests: new RuntimeProviderRequests(), + toolCalls: new RuntimeProviderRequests(), getActiveTurnId: () => "turn-1", getThreadExecutionOptions: () => undefined, onInteractiveRequest: async () => ({ diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts index 622431f453d..0ccd9a0b09a 100644 --- a/packages/agent-runtime/src/runtime.ts +++ b/packages/agent-runtime/src/runtime.ts @@ -9,19 +9,19 @@ import type { DynamicTool, InstructionMode, ThreadEvent } from "@bb/domain"; import type { AdapterCommand } from "./provider-adapter.js"; import { BRIDGE_JSON_RPC_ERRORS, + BRIDGE_NOTIFICATION_METHODS, commandListResultSchema, providerHealthResultSchema, providerInstallationRunResultSchema, providerInstallationStatusSchema, providerUsageResultSchema, + requestCancelledNotificationSchema, ThreadEventGrammar, threadIdentityResultSchema, } from "@bb/provider-bridge-protocol"; import { JsonRpcRequestTimeoutError, JsonRpcResponseError, - PROVIDER_TOOL_CALL_CANCELLED_METHOD, - providerToolCallCancellationSchema, getJsonRpcStringParam, ignoredJsonRpcResultSchema, parseJsonRpcLine, @@ -41,7 +41,7 @@ import { } from "./execution-options.js"; import { handleRuntimeProviderRequest, - RuntimeToolCalls, + RuntimeProviderRequests, type ResolveRuntimeProviderRequestThreadIdArgs, type RuntimeProviderRequestKind, } from "./runtime-provider-requests.js"; @@ -310,7 +310,8 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { const suppressedThreadEventIds = new Set(); const threadGoalState = new RuntimeThreadGoalState(); const turnState = new RuntimeTurnState(); - const toolCalls = new RuntimeToolCalls(); + const toolCalls = new RuntimeProviderRequests(); + const interactiveRequests = new RuntimeProviderRequests(); const backgroundWorkState = new RuntimeBackgroundWorkState(); const threadEventGrammar = new ThreadEventGrammar(); const bridgeNodeEnv = defaultBridgeNodeEnv(); @@ -1313,15 +1314,16 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { } function handleProviderNotification(args: RuntimeParsedMessageArgs): void { - if (args.parsed.method === PROVIDER_TOOL_CALL_CANCELLED_METHOD) { - const cancellation = providerToolCallCancellationSchema.safeParse( + if (args.parsed.method === BRIDGE_NOTIFICATION_METHODS.requestCancelled) { + const cancellation = requestCancelledNotificationSchema.safeParse( args.parsed.params, ); if (cancellation.success) { - toolCalls.cancel( - args.proc.interactiveRequestScope, - cancellation.data.requestId, - ); + const scope = args.proc.interactiveRequestScope; + const { requestId } = cancellation.data; + if (!toolCalls.cancel(scope, requestId)) { + interactiveRequests.cancel(scope, requestId); + } } return; } @@ -1383,6 +1385,7 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { threadRuntimeConfigs.get(threadId)?.options, onInteractiveRequest: options.onInteractiveRequest, onToolCall: options.onToolCall, + interactiveRequests, toolCalls, parsedId: parsedLine.parsedId, parsedMethod: parsedLine.parsedMethod, diff --git a/packages/agent-runtime/src/types.ts b/packages/agent-runtime/src/types.ts index 88fce964e8a..4dfc4035b54 100644 --- a/packages/agent-runtime/src/types.ts +++ b/packages/agent-runtime/src/types.ts @@ -83,6 +83,7 @@ export interface AgentRuntimeOptions { onInteractiveRequest?: ( request: PendingInteractionCreate, + signal: AbortSignal, ) => Promise; onStderr?: (line: string, threadId?: string) => void; diff --git a/packages/domain/src/plugin-sdk-version.ts b/packages/domain/src/plugin-sdk-version.ts index 45adcc2bcf6..b1832abd476 100644 --- a/packages/domain/src/plugin-sdk-version.ts +++ b/packages/domain/src/plugin-sdk-version.ts @@ -1,3 +1,3 @@ -export const PLUGIN_SDK_VERSION = "0.6.160"; +export const PLUGIN_SDK_VERSION = "0.6.161"; export const PLUGIN_SDK_MAJOR = Number(PLUGIN_SDK_VERSION.split(".", 1)[0]); diff --git a/packages/host-daemon-contract/src/protocol.ts b/packages/host-daemon-contract/src/protocol.ts index 78208c1e6ee..2d2515ed7a7 100644 --- a/packages/host-daemon-contract/src/protocol.ts +++ b/packages/host-daemon-contract/src/protocol.ts @@ -1,4 +1,4 @@ -export const HOST_DAEMON_PROTOCOL_VERSION = 268 as const; +export const HOST_DAEMON_PROTOCOL_VERSION = 269 as const; export const HOST_DAEMON_CONNECT_NEXT_PROTOCOL_VERSION = 247 as const; diff --git a/packages/host-daemon-contract/src/session.ts b/packages/host-daemon-contract/src/session.ts index cc191b3751f..1cbf4bbd2de 100644 --- a/packages/host-daemon-contract/src/session.ts +++ b/packages/host-daemon-contract/src/session.ts @@ -1007,6 +1007,23 @@ export type HostDaemonInteractiveInterruptResponse = z.infer< typeof hostDaemonInteractiveInterruptResponseSchema >; +export const hostDaemonInteractiveWithdrawRequestSchema = z.object({ + sessionId: z.string().min(1), + request: hostDaemonInteractiveRequestKeySchema, + reason: z.string().min(1), +}); +export type HostDaemonInteractiveWithdrawRequest = z.infer< + typeof hostDaemonInteractiveWithdrawRequestSchema +>; + +export const hostDaemonInteractiveWithdrawResponseSchema = z.object({ + ok: z.literal(true), + interactionId: z.string().min(1).nullable(), +}); +export type HostDaemonInteractiveWithdrawResponse = z.infer< + typeof hostDaemonInteractiveWithdrawResponseSchema +>; + const sha256HexSchema = z.string().regex(/^[a-f0-9]{64}$/u); const hostDaemonSkillTreeFileSchema = z .object({ @@ -1105,6 +1122,12 @@ export type HostDaemonInternalSchema = { HostDaemonInteractiveInterruptResponse >; }; + "/session/interactive-request/withdraw": { + $post: Endpoint< + { json: HostDaemonInteractiveWithdrawRequest }, + HostDaemonInteractiveWithdrawResponse + >; + }; }; function parseProtocolHeader(protocolHeader: string | undefined): string[] { diff --git a/packages/host-daemon-contract/test/contract.test.ts b/packages/host-daemon-contract/test/contract.test.ts index 452e15eb785..5b4a5a64974 100644 --- a/packages/host-daemon-contract/test/contract.test.ts +++ b/packages/host-daemon-contract/test/contract.test.ts @@ -1070,7 +1070,7 @@ describe("host-daemon command schemas", () => { }); it("uses the current host-daemon protocol version", () => { - expect(HOST_DAEMON_PROTOCOL_VERSION).toBe(268); + expect(HOST_DAEMON_PROTOCOL_VERSION).toBe(269); expect(HOST_ARTIFACT_MAX_BYTES).toBe(256 * 1024 * 1024); }); @@ -1098,7 +1098,8 @@ describe("host-daemon command schemas", () => { expect(contract.isCompatibleHostDaemonProtocolVersion(265)).toBe(false); expect(contract.isCompatibleHostDaemonProtocolVersion(266)).toBe(false); expect(contract.isCompatibleHostDaemonProtocolVersion(267)).toBe(false); - expect(contract.isCompatibleHostDaemonProtocolVersion(268)).toBe(true); + expect(contract.isCompatibleHostDaemonProtocolVersion(268)).toBe(false); + expect(contract.isCompatibleHostDaemonProtocolVersion(269)).toBe(true); expect(contract.hostDaemonSupportsConnectNext(246)).toBe(false); expect(contract.hostDaemonSupportsConnectNext(247)).toBe(true); expect(contract.hostDaemonSupportsDesktopBrokerProof(247)).toBe(false); diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index fe43762d2fe..59db3b6d7a0 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@get-bb/plugin-sdk", - "version": "0.6.160", + "version": "0.6.161", "license": "MIT", "homepage": "https://github.com/get-bb/bb#readme", "bugs": { diff --git a/packages/provider-bridge-acp/src/bridge/bridge.test.ts b/packages/provider-bridge-acp/src/bridge/bridge.test.ts index 7507061a9e1..e411b070afa 100644 --- a/packages/provider-bridge-acp/src/bridge/bridge.test.ts +++ b/packages/provider-bridge-acp/src/bridge/bridge.test.ts @@ -3358,6 +3358,37 @@ describe("acp bridge", () => { expect(agentMessageTexts()).toContain("permission:no"); }); + it("tells the runtime it stopped waiting on a forwarded permission when the session stops", async () => { + const { providerThreadId } = await startThread({ + permissionMode: "accept-edits", + permissionEscalation: "ask", + }); + const turnId = sendTurnRequest("turn/start", providerThreadId, { + options: executionOptions({ permissionMode: "accept-edits" }), + input: [{ type: "text", text: "request-permission", mentions: [] }], + }); + await waitForResponse(turnId); + const forwarded = await waitFor( + () => + output.messages.find( + (message) => + message.method === "interaction/request" && + message.id !== undefined, + ), + "forwarded permission request", + ); + + await stopThread(providerThreadId); + + expect( + output.messages.filter( + (message) => message.method === "notifications/cancelled", + ), + ).toEqual([ + expect.objectContaining({ params: { requestId: forwarded.id } }), + ]); + }); + it("presents an external-directory write permission as a file-change approval", async () => { const { bbThreadId, providerThreadId } = await startThread({ permissionMode: "accept-edits", diff --git a/packages/provider-bridge-acp/src/bridge/bridge.ts b/packages/provider-bridge-acp/src/bridge/bridge.ts index 3b7f24f161f..cb4f9f1c748 100644 --- a/packages/provider-bridge-acp/src/bridge/bridge.ts +++ b/packages/provider-bridge-acp/src/bridge/bridge.ts @@ -30,7 +30,6 @@ import type { ThreadDelta, } from "@bb/provider-bridge-protocol"; import { - PROVIDER_TOOL_CALL_CANCELLED_METHOD, BridgeRecoveryError, bridgeRequestEnvelopeSchema, createBridgeIo, @@ -194,6 +193,7 @@ interface AcpSessionPolicy { interface PendingAcpPermission { responder: AcpAgentRequestResponder; options: AcpPermissionOption[]; + withdrawal: AbortController; } interface AcpPendingTurnInput { @@ -247,7 +247,7 @@ interface AcpThreadSession { turnSettled: Promise | undefined; pendingPermissions: Set; sessionGrants: Set; - pendingElicitations: Set; + pendingElicitations: Map; pendingToolCalls: Set; cursorMcpApproval: CursorMcpApproval | undefined; deferStartEmit: AcpDeferredStartEmitter | undefined; @@ -346,8 +346,10 @@ function sendRuntimeRequest( const responsePromise = new Promise( (resolveResponse, rejectResponse) => { abort = () => { - pendingRuntimeRequests.delete(requestId); - sendNotification(PROVIDER_TOOL_CALL_CANCELLED_METHOD, { requestId }); + if (!pendingRuntimeRequests.delete(requestId)) return; + sendNotification(BRIDGE_NOTIFICATION_METHODS.requestCancelled, { + requestId, + }); rejectResponse(new Error("ACP dynamic tool call cancelled")); }; signal?.addEventListener("abort", abort, { once: true }); @@ -1961,25 +1963,33 @@ function withdrawPendingQuestions( detail: string, ): void { const cause: UnansweredInteractionCause = { kind: "withdrawn", detail }; - for (const pending of session.pendingPermissions) { + const permissions = [...session.pendingPermissions]; + const elicitations = [...session.pendingElicitations]; + session.pendingPermissions.clear(); + session.pendingElicitations.clear(); + for (const pending of permissions) { answerWithoutUser(session, pending.responder, cause); + pending.withdrawal.abort(); } - session.pendingPermissions.clear(); - for (const responder of session.pendingElicitations) { + for (const [responder, withdrawal] of elicitations) { answerWithoutUser(session, responder, cause); + withdrawal.abort(); } - session.pendingElicitations.clear(); } function cancelPendingPermissions(session: AcpThreadSession): void { - for (const pending of session.pendingPermissions) { + const permissions = [...session.pendingPermissions]; + const elicitations = [...session.pendingElicitations]; + session.pendingPermissions.clear(); + session.pendingElicitations.clear(); + for (const pending of permissions) { pending.responder.result({ outcome: { outcome: "cancelled" } }); + pending.withdrawal.abort(); } - session.pendingPermissions.clear(); - for (const responder of session.pendingElicitations) { + for (const [responder, withdrawal] of elicitations) { responder.result({ action: "cancel" }); + withdrawal.abort(); } - session.pendingElicitations.clear(); } const COMPACTION_QUESTION_CAUSE: UnansweredInteractionCause = { @@ -2011,13 +2021,18 @@ function handleElicitationRequest( if (session.activePromptKind === null) { openAgentTurn(session); } - session.pendingElicitations.add(responder); - void sendRuntimeRequest(BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, { - providerThreadId: session.providerThreadId, - threadId: session.bbThreadId, - turnId: null, - payload: plan.payload, - }) + const withdrawal = new AbortController(); + session.pendingElicitations.set(responder, withdrawal); + void sendRuntimeRequest( + BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, + { + providerThreadId: session.providerThreadId, + threadId: session.bbThreadId, + turnId: null, + payload: plan.payload, + }, + withdrawal.signal, + ) .then((result) => { if (!session.pendingElicitations.delete(responder)) { return; @@ -2092,6 +2107,7 @@ function handlePermissionRequest( const pending: PendingAcpPermission = { responder, options: parsed.data.options, + withdrawal: new AbortController(), }; if (session.policy.permissionMode === "full") { @@ -2140,12 +2156,16 @@ function handlePermissionRequest( openAgentTurn(session); } session.pendingPermissions.add(pending); - void sendRuntimeRequest(BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, { - providerThreadId: session.providerThreadId, - threadId: session.bbThreadId, - turnId: null, - payload, - }) + void sendRuntimeRequest( + BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, + { + providerThreadId: session.providerThreadId, + threadId: session.bbThreadId, + turnId: null, + payload, + }, + pending.withdrawal.signal, + ) .then((result) => { if (!session.pendingPermissions.delete(pending)) { return; @@ -2517,7 +2537,7 @@ async function startAgentSession( turnSettled: undefined, pendingPermissions: new Set(), sessionGrants: new Set(), - pendingElicitations: new Set(), + pendingElicitations: new Map(), pendingToolCalls: new Set(), cursorMcpApproval: undefined, deferStartEmit: emitStartNotification, diff --git a/packages/provider-bridge-protocol/src/contract-tests/provider-bridge-grammar.v2.snapshot.json b/packages/provider-bridge-protocol/src/contract-tests/provider-bridge-grammar.v2.snapshot.json index 243caae58bc..92461827a24 100644 --- a/packages/provider-bridge-protocol/src/contract-tests/provider-bridge-grammar.v2.snapshot.json +++ b/packages/provider-bridge-protocol/src/contract-tests/provider-bridge-grammar.v2.snapshot.json @@ -339,6 +339,7 @@ ], "notificationMethods": [ "error", + "notifications/cancelled", "provider/raw", "provider/recovery", "session/replaced", diff --git a/packages/provider-bridge-protocol/src/notifications.ts b/packages/provider-bridge-protocol/src/notifications.ts index e5760dda399..de0fe73df40 100644 --- a/packages/provider-bridge-protocol/src/notifications.ts +++ b/packages/provider-bridge-protocol/src/notifications.ts @@ -7,8 +7,15 @@ export const BRIDGE_NOTIFICATION_METHODS = { providerRaw: "provider/raw", providerRecovery: "provider/recovery", error: "error", + requestCancelled: "notifications/cancelled", } as const; +export const requestCancelledNotificationSchema = z + .object({ + requestId: z.union([z.string(), z.number().int()]), + }) + .passthrough(); + export const threadIdentityNotificationSchema = z .object({ threadId: z.string().min(1), diff --git a/packages/thread-view/src/event-projection-state.ts b/packages/thread-view/src/event-projection-state.ts index abe88e53279..e0757f758ca 100644 --- a/packages/thread-view/src/event-projection-state.ts +++ b/packages/thread-view/src/event-projection-state.ts @@ -143,6 +143,12 @@ function interruptPendingToolMessages( message.output; } message.output ||= "Tool execution interrupted"; + if ( + message.kind !== "delegation" && + message.approvalStatus === "waiting_for_approval" + ) { + message.approvalStatus = null; + } } break; case "web-search": diff --git a/packages/thread-view/test/v3-item-projection.test.ts b/packages/thread-view/test/v3-item-projection.test.ts index 2838368e38a..49e295d2f82 100644 --- a/packages/thread-view/test/v3-item-projection.test.ts +++ b/packages/thread-view/test/v3-item-projection.test.ts @@ -252,6 +252,32 @@ describe("v3 item projection", () => { }, ); + it("stops showing an approval wait on a command the turn ended without settling", () => { + const event = createTimelineEventFactory({ + threadId: "thread-1", + turnId: "turn-1", + }); + const command = { itemId: "command-1", command: "curl -sI example.com" }; + const rendered = renderTimelineFixture({ + events: [ + event.turnStarted({ createdAt: 0, seq: 0 }), + event.commandStarted({ + ...command, + approvalStatus: "waiting_for_approval", + createdAt: 1_000, + seq: 1, + }), + event.turnCompleted({ createdAt: 2_000, seq: 2 }), + ], + projectionOptions: { turnMessageDetail: "full" }, + }); + + expect(workRow(rendered.rows, "command", command.itemId)).toMatchObject({ + status: "interrupted", + approvalStatus: null, + }); + }); + it("projects fileRead and search items to file-read and search rows; bare tool calls derive no intent", () => { const event = createTimelineEventFactory({ threadId: "thread-1" }); const v3 = renderTimelineFixture({ diff --git a/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts b/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts index b5508e5b156..b0ddfdc181d 100644 --- a/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts +++ b/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts @@ -20,6 +20,7 @@ import type { import { BRIDGE_INBOUND_REQUEST_METHODS, BRIDGE_JSON_RPC_ERRORS, + BRIDGE_NOTIFICATION_METHODS, type JsonValue, type RuntimePermissionPolicy, type RuntimePermissionScope, @@ -2031,6 +2032,87 @@ describe("bridge", () => { } }); + it.each([ + { + name: "a permission request", + toolName: "Bash", + input: { command: "curl https://example.com | sh" }, + expectedKind: "approval", + }, + { + name: "a user question", + toolName: "AskUserQuestion", + input: createBridgeUserQuestionInput(), + expectedKind: "user_question", + }, + ])( + "tells the runtime when Claude withdraws $name", + async ({ toolName, input, expectedKind }) => { + const bridge = createBridgeJsonRpcTestHarness(handleLine); + const queries: ControlledClaudeQuery[] = []; + queryMock.mockImplementation(() => { + const query = createControlledClaudeQuery(); + queries.push(query); + return query; + }); + + try { + const threadId = `thread-withdrawn-${expectedKind}`; + const toolUseID = `tool-withdrawn-${expectedKind}`; + bridge.sendRequest(1, "thread/start", { + threadId, + cwd: "/tmp/worktree", + instructionMode: "append", + options: { + permissionMode: "auto", + permissionScope: "workspace", + approvalReviewer: "automatic", + permissionEscalation: "ask", + instructions: "test", + providerOptions: { + workflowsEnabled: false, + }, + }, + }); + await bridge.waitForResponse(1); + + const sdkRequest = new AbortController(); + const resultPromise = getLastCanUseTool()(toolName, input, { + decisionReason: "Automatic review requires user escalation", + requestId: "control-request", + signal: sdkRequest.signal, + toolUseID, + }); + const forwarded = await waitForBridgeRequest( + bridge, + (message) => interactionPayload(message)?.kind === expectedKind, + ); + + sdkRequest.abort(); + await expect(resultPromise).resolves.toMatchObject({ + behavior: "deny", + toolUseID, + }); + expect(bridge.messages).toContainEqual( + expect.objectContaining({ + method: BRIDGE_NOTIFICATION_METHODS.requestCancelled, + params: { requestId: forwarded.id }, + }), + ); + + await stopBridgeThread({ bridge, queries, threadId }); + expect( + bridge.messages.filter( + (message) => + message.method === BRIDGE_NOTIFICATION_METHODS.requestCancelled, + ), + ).toHaveLength(1); + } finally { + bridge.restore(); + } + }, + ); + it("forwards a sandbox network ask with a grantable network permission", async () => { const bridge = createBridgeJsonRpcTestHarness(handleLine); const queries: ControlledClaudeQuery[] = []; diff --git a/plugins/provider-claude-code/src/bridge/bridge.ts b/plugins/provider-claude-code/src/bridge/bridge.ts index a1b49fc6b94..145fa63c1e9 100644 --- a/plugins/provider-claude-code/src/bridge/bridge.ts +++ b/plugins/provider-claude-code/src/bridge/bridge.ts @@ -1779,12 +1779,27 @@ function findSessionByPendingInteractiveRequest( return undefined; } +function withdrawInteractiveRequest( + threadSession: ThreadSession, + requestId: string | number, +): boolean { + if (!threadSession.pendingInteractiveRequests.delete(requestId)) { + return false; + } + send({ + jsonrpc: "2.0", + method: BRIDGE_NOTIFICATION_METHODS.requestCancelled, + params: { requestId }, + }); + return true; +} + function resolvePendingInteractiveRequests( threadSession: ThreadSession, message: string, ): void { for (const [requestId, pending] of threadSession.pendingInteractiveRequests) { - threadSession.pendingInteractiveRequests.delete(requestId); + withdrawInteractiveRequest(threadSession, requestId); pending.resolve({ behavior: "deny", interrupt: true, @@ -2045,7 +2060,7 @@ function createForwardInteractiveRequest( }; const onAbort = (): void => { - if (!threadSession.pendingInteractiveRequests.delete(requestId)) { + if (!withdrawInteractiveRequest(threadSession, requestId)) { return; } finish({ @@ -2109,7 +2124,7 @@ function createForwardUserQuestionRequest( }; const onAbort = (): void => { - if (!threadSession.pendingInteractiveRequests.delete(requestId)) { + if (!withdrawInteractiveRequest(threadSession, requestId)) { return; } finish({ diff --git a/plugins/provider-codex/src/bridge/app-server-connection.ts b/plugins/provider-codex/src/bridge/app-server-connection.ts index 08f47bb02be..43c5836e653 100644 --- a/plugins/provider-codex/src/bridge/app-server-connection.ts +++ b/plugins/provider-codex/src/bridge/app-server-connection.ts @@ -18,6 +18,7 @@ const CLOSED_STDIN_ERROR_CODES = new Set([ ]); export interface CodexAppServerRequestResponder { + readonly requestId: string | number; result(value: unknown): void; error(code: number, message: string): void; } @@ -299,6 +300,7 @@ export function createCodexAppServerConnection( if (typeof id === "string" || typeof id === "number") { let settled = false; options.onRequest(message.method, message.params, { + requestId: id, result(value) { if (settled || finalized) return; settled = true; diff --git a/plugins/provider-codex/src/bridge/bridge.ts b/plugins/provider-codex/src/bridge/bridge.ts index 6aed006bd1f..0a50291d4b5 100644 --- a/plugins/provider-codex/src/bridge/bridge.ts +++ b/plugins/provider-codex/src/bridge/bridge.ts @@ -273,12 +273,23 @@ let runtimeRequestIdCounter = 0; function sendRuntimeRequest( method: string, params: Record, + signal: AbortSignal, ): Promise { + signal.throwIfAborted(); runtimeRequestIdCounter += 1; const requestId = runtimeRequestIdCounter; const responsePromise = new Promise( (resolveResponse, rejectResponse) => { + const abort = (): void => { + if (!pendingRuntimeRequests.delete(requestId)) return; + sendNotification(BRIDGE_NOTIFICATION_METHODS.requestCancelled, { + requestId, + }); + rejectResponse(new Error("codex withdrew the request")); + }; + signal.addEventListener("abort", abort, { once: true }); pendingRuntimeRequests.set(requestId, (response) => { + signal.removeEventListener("abort", abort); if ("error" in response) { rejectResponse( new Error(response.error.message ?? "Runtime request failed"), @@ -503,6 +514,7 @@ interface CodexBridgeSession { releasePromise: Promise | null; goalStatus: CodexGoalStatus | null; stopsRequested: number; + pendingChildRequests: Map; } const sessionsByBbThreadId = new Map(); @@ -536,6 +548,7 @@ function releaseSession(session: CodexBridgeSession): Promise { if (sessionsByBbThreadId.get(session.bbThreadId) === session) { sessionsByBbThreadId.delete(session.bbThreadId); } + withdrawChildRequests(session, session.pendingChildRequests.keys()); const previousChildExit = session.previousChildExit; session.previousChildExit = null; const currentChildExit = session.connection?.kill() ?? Promise.resolve(); @@ -718,6 +731,10 @@ function toProviderRuntimeEvent( } as ProviderRuntimeEvent; } +const codexServerRequestResolvedSchema = z + .object({ requestId: z.union([z.string(), z.number()]) }) + .passthrough(); + async function handleChildNotification( bbThreadId: string, serial: number, @@ -737,6 +754,12 @@ async function handleChildNotification( if (method === "thread/status/changed") { settleCompactionDispatchesWhenCodexIsNotRunning(session, params); } + if (method === "serverRequest/resolved") { + const parsed = codexServerRequestResolvedSchema.safeParse(params); + if (parsed.success) { + withdrawChildRequests(session, [parsed.data.requestId]); + } + } if (method === "turn/started") { const parsed = codexTurnNotificationPeekSchema.safeParse(params); if (parsed.success && parsed.data.threadId === session.codexThreadId) { @@ -849,23 +872,30 @@ function handleChildRequest( ); return; } - void sendRuntimeRequest(BRIDGE_INBOUND_REQUEST_METHODS.toolCall, { - providerThreadId: session.codexThreadId ?? parsed.data.threadId, - threadId: session.bbThreadId, - turnId: parsed.data.turnId, - callId: parsed.data.callId, - tool: parsed.data.tool, - arguments: parsed.data.arguments ?? {}, - }) + const signal = trackChildRequest(session, responder.requestId); + void sendRuntimeRequest( + BRIDGE_INBOUND_REQUEST_METHODS.toolCall, + { + providerThreadId: session.codexThreadId ?? parsed.data.threadId, + threadId: session.bbThreadId, + turnId: parsed.data.turnId, + callId: parsed.data.callId, + tool: parsed.data.tool, + arguments: parsed.data.arguments ?? {}, + }, + signal, + ) .then((result) => { responder.result(result); }) .catch((error: unknown) => { + if (signal.aborted) return; responder.error( BRIDGE_JSON_RPC_ERRORS.BRIDGE_ERROR, error instanceof Error ? error.message : String(error), ); - }); + }) + .finally(() => untrackChildRequest(session, responder.requestId, signal)); return; } @@ -940,6 +970,7 @@ function handleChildRequest( ); return; } + const signal = trackChildRequest(session, responder.requestId); void resolveCodexMcpElicitationAppIcon(decoded) .then(async (request) => { if (currentSession(bbThreadId, serial) !== session) { @@ -950,13 +981,18 @@ function handleChildRequest( return; } const [runtimeResult] = await Promise.allSettled([ - sendRuntimeRequest(BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, { - providerThreadId: session.codexThreadId ?? request.providerThreadId, - threadId: session.bbThreadId, - turnId: request.turnId, - payload: request.payload, - }), + sendRuntimeRequest( + BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, + { + providerThreadId: session.codexThreadId ?? request.providerThreadId, + threadId: session.bbThreadId, + turnId: request.turnId, + payload: request.payload, + }, + signal, + ), ]); + if (signal.aborted) return; const result = buildCodexInteractiveResult( request.payload, runtimeResult, @@ -968,6 +1004,7 @@ function handleChildRequest( responder.result(result.response); }) .catch((error: unknown) => { + if (signal.aborted) return; answerWithoutUser( { kind: "runtime-error", @@ -975,7 +1012,39 @@ function handleChildRequest( }, null, ); - }); + }) + .finally(() => untrackChildRequest(session, responder.requestId, signal)); +} + +function trackChildRequest( + session: CodexBridgeSession, + requestId: string | number, +): AbortSignal { + const controller = new AbortController(); + session.pendingChildRequests.set(requestId, controller); + return controller.signal; +} + +function untrackChildRequest( + session: CodexBridgeSession, + requestId: string | number, + signal: AbortSignal, +): void { + if (session.pendingChildRequests.get(requestId)?.signal === signal) { + session.pendingChildRequests.delete(requestId); + } +} + +function withdrawChildRequests( + session: CodexBridgeSession, + requestIds: Iterable, +): void { + for (const requestId of [...requestIds]) { + const controller = session.pendingChildRequests.get(requestId); + if (!controller) continue; + session.pendingChildRequests.delete(requestId); + controller.abort(); + } } function buildMacOsPermissionItemDelta( @@ -1009,6 +1078,7 @@ function handleChildExit( return; } session.connection = null; + withdrawChildRequests(session, session.pendingChildRequests.keys()); const openTurnIds = [...session.openCodexTurnIds]; const message = `codex app-server exited unexpectedly (code ${info.code ?? "null"}, signal ${info.signal ?? "null"})${info.stderrTail ? `: ${info.stderrTail}` : ""}`; @@ -1337,6 +1407,7 @@ async function constructThreadSession( options: decoded.sessionOptions, }), openCodexTurnIds: new Set(), + pendingChildRequests: new Map(), responseOpenedTurns: new Map(), unopenedCompactionDispatches: [], turnSettledWaiters: new Map(), @@ -1592,6 +1663,7 @@ function registerResumableSession(session: CodexBridgeSession): void { environmentHash: session.environmentHash, turnPermissionSettings: session.turnPermissionSettings, openCodexTurnIds: new Set(), + pendingChildRequests: new Map(), responseOpenedTurns: new Map(), unopenedCompactionDispatches: [], turnSettledWaiters: new Map(), diff --git a/plugins/provider-codex/src/bridge/bridge.withdrawn-request.test.ts b/plugins/provider-codex/src/bridge/bridge.withdrawn-request.test.ts new file mode 100644 index 00000000000..75ae83214ed --- /dev/null +++ b/plugins/provider-codex/src/bridge/bridge.withdrawn-request.test.ts @@ -0,0 +1,131 @@ +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { BRIDGE_NOTIFICATION_METHODS } from "@get-bb/plugin-sdk/provider-bridge"; +import { experimental_createBridgeJsonRpcTestHarness as createBridgeJsonRpcTestHarness } from "@get-bb/plugin-sdk/provider-bridge/testing"; +import { handleLine } from "./bridge.js"; +import { + FULL_ACCESS_SESSION_OPTIONS, + stubFakeCodexAppServer, +} from "./fake-codex-app-server-harness.js"; + +afterEach(() => vi.unstubAllEnvs()); + +it("tells the runtime when Codex resolves a request bb has not answered", async () => { + const workspace = mkdtempSync(join(tmpdir(), "bb-codex-withdrawn-")); + const scriptPath = join(workspace, "script.json"); + const responseLogPath = join(workspace, "responses.jsonl"); + const threadId = "thr_withdrawn_request"; + writeFileSync( + scriptPath, + JSON.stringify({ + responseLogPath, + turns: [ + [ + { + method: "turn/started", + params: { + threadId: "codex-thread", + turn: { id: "turn-1", status: "inProgress" }, + }, + }, + { + kind: "request", + withdrawAfterMs: 50, + method: "item/tool/requestUserInput", + params: { + threadId: "codex-thread", + turnId: "turn-1", + itemId: "item-1", + isBlocking: true, + autoResolutionMs: null, + questions: [ + { id: "notes", header: "Notes", question: "Any notes?" }, + ], + }, + }, + { + method: "turn/completed", + params: { + threadId: "codex-thread", + turn: { id: "turn-1", status: "completed" }, + }, + }, + ], + ], + }), + ); + stubFakeCodexAppServer(scriptPath); + const bridge = createBridgeJsonRpcTestHarness(handleLine); + try { + bridge.sendRequest(1, "thread/start", { + threadId, + cwd: workspace, + instructionMode: "append", + options: FULL_ACCESS_SESSION_OPTIONS, + }); + const start = await bridge.waitForResponse(1); + const providerThreadId = (start.result as { providerThreadId: string }) + .providerThreadId; + bridge.sendRequest(2, "turn/start", { + threadId, + providerThreadId, + input: [{ type: "text", text: "Ask", mentions: [] }], + clientRequestId: "creq_w2b3c4d5e6", + options: FULL_ACCESS_SESSION_OPTIONS, + }); + + const request = await vi.waitFor(() => { + const found = bridge.messages.find( + (message) => message.method === "interaction/request", + ); + if (found?.id === undefined) { + throw new Error("Expected a forwarded interaction request"); + } + return found; + }); + await vi.waitFor(() => { + expect(bridge.messages).toContainEqual( + expect.objectContaining({ + method: BRIDGE_NOTIFICATION_METHODS.requestCancelled, + params: { requestId: request.id }, + }), + ); + }); + await bridge.waitForResponse(2); + + handleLine( + JSON.stringify({ + jsonrpc: "2.0", + id: request.id, + result: { + kind: "user_answer", + answers: { notes: { selected: [], freeText: "too late" } }, + }, + }), + ); + await bridge.flushWork(); + expect( + existsSync(responseLogPath) + ? readFileSync(responseLogPath, "utf8").trim() + : "", + ).toBe(""); + } finally { + bridge.sendRequest(999, "thread/stop", { + threadId, + providerThreadId: "codex-thread", + intent: "release", + activeTurnId: null, + }); + await bridge.waitForResponse(999).catch(() => undefined); + bridge.restore(); + rmSync(workspace, { recursive: true, force: true }); + } +}, 30_000); diff --git a/plugins/provider-codex/src/bridge/fake-codex-app-server.mjs b/plugins/provider-codex/src/bridge/fake-codex-app-server.mjs index ec98fc71c06..5622a3cf13a 100644 --- a/plugins/provider-codex/src/bridge/fake-codex-app-server.mjs +++ b/plugins/provider-codex/src/bridge/fake-codex-app-server.mjs @@ -378,6 +378,21 @@ function requestFromClient(method, params) { }); } +async function withdrawnRequestFromClient(method, params, withdrawAfterMs) { + outboundRequestCounter += 1; + const id = `fx-req-${outboundRequestCounter}`; + pendingOutboundRequests.set(id, () => {}); + send({ jsonrpc: "2.0", id, method, params }); + await new Promise((resolve) => setTimeout(resolve, withdrawAfterMs)); + if (!pendingOutboundRequests.delete(id)) { + return; + } + notify("serverRequest/resolved", { + threadId: params.threadId, + requestId: id, + }); +} + const turnCursorPath = script?.turnCursorPath ?? null; const goalsByThreadId = new Map(); @@ -415,6 +430,14 @@ async function runScriptFileTurn(threadId) { for (const entry of turn) { const params = withThreadId(entry.params ?? {}, threadId); if (entry.kind === "request") { + if (typeof entry.withdrawAfterMs === "number") { + await withdrawnRequestFromClient( + entry.method, + params, + entry.withdrawAfterMs, + ); + continue; + } await requestFromClient(entry.method, params); continue; } diff --git a/plugins/provider-pi/src/bridge/bridge.ts b/plugins/provider-pi/src/bridge/bridge.ts index e2c78d70b08..732f3cc43fa 100644 --- a/plugins/provider-pi/src/bridge/bridge.ts +++ b/plugins/provider-pi/src/bridge/bridge.ts @@ -216,6 +216,12 @@ const { forwardToolCall, handleToolCallResponse, resolvePendingToolCalls } = const extensionUi: ExtensionUiCoordinator = createExtensionUiCoordinator({ sendInteractionRequest: send, sendThreadDeltas: (threadId, deltas) => sendThreadDeltas(threadId, deltas), + sendRequestCancelled: (requestId) => + send({ + jsonrpc: "2.0", + method: BRIDGE_NOTIFICATION_METHODS.requestCancelled, + params: { requestId }, + }), }); let configuredSkillPaths: string[] | null = null; diff --git a/plugins/provider-pi/src/bridge/extension-ui-coordinator.test.ts b/plugins/provider-pi/src/bridge/extension-ui-coordinator.test.ts index 4c8d7144bd1..5eef4e226b5 100644 --- a/plugins/provider-pi/src/bridge/extension-ui-coordinator.test.ts +++ b/plugins/provider-pi/src/bridge/extension-ui-coordinator.test.ts @@ -1,33 +1,41 @@ import { PLUGIN_INTERACTION_MAX_TITLE_LENGTH } from "@get-bb/plugin-sdk/provider-bridge"; -import { expect, it } from "vitest"; +import { afterEach, expect, it, vi } from "vitest"; import type { InteractionUiRequest, PiExtensionUiResponseFields, } from "../extension-ui-contract.js"; import { createExtensionUiCoordinator } from "./extension-ui.js"; -function forward(title: string) { +function forward(title: string, extra: { timeout?: number } = {}) { const sent: InteractionUiRequest[] = []; const responses: PiExtensionUiResponseFields[] = []; + const cancelled: string[] = []; + const scope = {}; const coordinator = createExtensionUiCoordinator({ sendInteractionRequest: (request) => sent.push(request), sendThreadDeltas: () => {}, + sendRequestCancelled: (requestId) => cancelled.push(requestId), }); coordinator.handle({ - scope: {}, + scope, request: { id: "ui-1", method: "select", title, options: ["Allow", "Deny"], + ...extra, }, threadId: "thr_ui", providerThreadId: "pi_ui", respond: (_id, fields) => responses.push(fields), }); - return { sent, responses }; + return { cancelled, coordinator, scope, sent, responses }; } +afterEach(() => { + vi.useRealTimers(); +}); + it.each([160, 161, 200, 201, 4096])( "forwards a %i-character title within core's limit and keeps the full title for the card (#4264)", (length) => { @@ -49,3 +57,50 @@ it.each([160, 161, 200, 201, 4096])( } }, ); + +it("withdraws the card when Pi's dialog timeout elapses", () => { + vi.useFakeTimers(); + const { cancelled, coordinator, sent, responses } = forward("Continue?", { + timeout: 5_000, + }); + const interactionId = sent[0]!.id; + + vi.advanceTimersByTime(4_999); + expect(cancelled).toEqual([]); + vi.advanceTimersByTime(1); + expect(cancelled).toEqual([interactionId]); + expect(responses).toEqual([]); + expect( + coordinator.handleRuntimeResponse({ + id: interactionId, + result: { kind: "request_answer", value: "Allow" }, + }), + ).toBe(false); +}); + +it("keeps an answered card from being withdrawn by its timeout", () => { + vi.useFakeTimers(); + const { cancelled, coordinator, sent, responses } = forward("Continue?", { + timeout: 5_000, + }); + + expect( + coordinator.handleRuntimeResponse({ + id: sent[0]!.id, + result: { kind: "request_answer", value: "Allow" }, + }), + ).toBe(true); + vi.advanceTimersByTime(10_000); + expect(cancelled).toEqual([]); + expect(responses).toEqual([{ value: "Allow" }]); +}); + +it("withdraws the card when the Pi session closes", () => { + const { cancelled, coordinator, scope, sent, responses } = + forward("Continue?"); + + coordinator.cancelPendingForScope(scope); + + expect(cancelled).toEqual([sent[0]!.id]); + expect(responses).toEqual([{ cancelled: true }]); +}); diff --git a/plugins/provider-pi/src/bridge/extension-ui.ts b/plugins/provider-pi/src/bridge/extension-ui.ts index 4ac97179b1b..6c2d461e268 100644 --- a/plugins/provider-pi/src/bridge/extension-ui.ts +++ b/plugins/provider-pi/src/bridge/extension-ui.ts @@ -29,6 +29,7 @@ interface PendingExtensionUiRequest { scope: object; threadId: string; request: PiExtensionUiRequest; + expiry: ReturnType | null; respond: ( requestId: string | number, fields: PiExtensionUiResponseFields, @@ -38,6 +39,7 @@ interface PendingExtensionUiRequest { export interface ExtensionUiCoordinatorOptions { sendInteractionRequest: (request: InteractionUiRequest) => void; sendThreadDeltas: (threadId: string, deltas: ThreadDelta[]) => void; + sendRequestCancelled: (interactionId: string) => void; } export interface HandleExtensionUiRequestArgs { @@ -112,6 +114,28 @@ export function createExtensionUiCoordinator( args.respond(args.requestId, { cancelled: true }); } + const take = (interactionId: string): PendingExtensionUiRequest | null => { + const entry = pending.get(interactionId); + if (!entry) { + return null; + } + pending.delete(interactionId); + if (entry.expiry !== null) { + clearTimeout(entry.expiry); + } + return entry; + }; + + const withdraw = ( + interactionId: string, + ): PendingExtensionUiRequest | null => { + const entry = take(interactionId); + if (entry) { + options.sendRequestCancelled(interactionId); + } + return entry; + }; + return { handle(args) { if (FIRE_AND_FORGET_METHODS.has(String(rawMethod(args.request)))) { @@ -152,6 +176,10 @@ export function createExtensionUiCoordinator( scope: args.scope, threadId: args.threadId, request, + expiry: + request.timeout === undefined + ? null + : setTimeout(() => withdraw(interactionId), request.timeout), respond: args.respond, }); try { @@ -171,7 +199,7 @@ export function createExtensionUiCoordinator( }, }); } catch (error) { - pending.delete(interactionId); + take(interactionId); cancelWithoutUser({ threadId: args.threadId, requestId: request.id, @@ -185,11 +213,10 @@ export function createExtensionUiCoordinator( }, handleRuntimeResponse(response) { - const entry = pending.get(String(response.id)); + const entry = take(String(response.id)); if (!entry) { return false; } - pending.delete(String(response.id)); const unanswered = { threadId: entry.threadId, requestId: entry.request.id, @@ -229,11 +256,11 @@ export function createExtensionUiCoordinator( }, cancelPendingForScope(scope) { - for (const [interactionId, entry] of pending) { + for (const [interactionId, entry] of [...pending]) { if (entry.scope !== scope) { continue; } - pending.delete(interactionId); + withdraw(interactionId); entry.respond(entry.request.id, { cancelled: true }); } }, diff --git a/tests/integration/fake/smoke/withdrawn-approvals.test.ts b/tests/integration/fake/smoke/withdrawn-approvals.test.ts new file mode 100644 index 00000000000..0dc98294318 --- /dev/null +++ b/tests/integration/fake/smoke/withdrawn-approvals.test.ts @@ -0,0 +1,89 @@ +import type { TimelineRow } from "@bb/server-contract"; +import { describe, expect, it } from "vitest"; +import { + getThreadTimeline, + listThreadInteractions, + sendTextMessage, +} from "../../helpers/api.js"; +import { + waitForEventType, + waitForThreadOutputContaining, + waitForThreadStatus, +} from "../../helpers/assertions.js"; +import { withHarness } from "../../helpers/harness.js"; +import { + createProjectFixture, + createReadyThread, + TURN_TIMEOUT_MS, +} from "./shared.js"; + +function collectWorkRows(rows: readonly TimelineRow[]): TimelineRow[] { + return rows.flatMap((row) => [ + ...(row.kind === "work" ? [row] : []), + ...(row.kind === "turn" && row.children + ? collectWorkRows(row.children) + : []), + ]); +} + +describe.sequential("fake provider withdrawn approvals", () => { + it("closes an approval the provider withdraws and dispatches the next message", () => + withHarness(async (harness) => { + const project = await createProjectFixture( + harness, + "Withdrawn Approval Smoke", + ); + const { thread } = await createReadyThread(harness, { + projectId: project.id, + workspace: { + type: "unmanaged", + path: harness.repoDir, + }, + }); + + await sendTextMessage(harness.api, thread.id, { + text: "approve:command withdraw_approval delay:300", + }); + await waitForEventType( + harness.api, + thread.id, + "system/interaction/lifecycle", + TURN_TIMEOUT_MS, + ); + await waitForThreadOutputContaining( + harness.api, + thread.id, + "Approval withdrawn", + TURN_TIMEOUT_MS, + ); + await waitForThreadStatus( + harness.api, + thread.id, + "idle", + TURN_TIMEOUT_MS, + ); + await expect + .poll(() => listThreadInteractions(harness.api, thread.id), { + timeout: TURN_TIMEOUT_MS, + }) + .toEqual([]); + const timeline = await getThreadTimeline(harness.api, thread.id, { + includeNestedRows: true, + }); + expect(collectWorkRows(timeline.rows)).toEqual([ + expect.objectContaining({ + workKind: "command", + status: "interrupted", + approvalStatus: null, + }), + ]); + + await sendTextMessage(harness.api, thread.id, { text: "follow up" }); + await waitForThreadOutputContaining( + harness.api, + thread.id, + "Response to: follow up", + TURN_TIMEOUT_MS, + ); + })); +}); diff --git a/tests/scripted-echo-provider/README.md b/tests/scripted-echo-provider/README.md index 794a2183762..ed8795c6bad 100644 --- a/tests/scripted-echo-provider/README.md +++ b/tests/scripted-echo-provider/README.md @@ -11,6 +11,9 @@ Prompt directives: - `delay:` holds the turn open before it settles. - `approve:` raises an approval on `interaction/request`; a denied approval answers `Denied`. +- `withdraw_approval` (with `approve:`) withdraws the approval after + `delay:` with `notifications/cancelled`, as a provider does when a hook + answers it, and answers `Approval withdrawn`. - `ask_user` raises a user question and echoes the answer. - `call_tool:` / `call_tool_unresolved:` calls a dynamic tool with a resolved or an unresolved turn id and answers `Tool called: `. diff --git a/tests/scripted-echo-provider/src/provider-bridge.ts b/tests/scripted-echo-provider/src/provider-bridge.ts index 795e318f1ee..b3553e7e8bc 100644 --- a/tests/scripted-echo-provider/src/provider-bridge.ts +++ b/tests/scripted-echo-provider/src/provider-bridge.ts @@ -245,6 +245,7 @@ const APPROVAL_KINDS: readonly ApprovalKind[] = [ interface TurnPlan { approvalKind: ApprovalKind | null; + withdrawApproval: boolean; delayMs: number; questionRequested: boolean; responseText: string; @@ -301,6 +302,7 @@ function parseTurnPlan(inputText: string): TurnPlan { backgroundTask: /(?:^|\s)bg_task(?:\s|$)/u.test(inputText), settleBackgroundTasks: /(?:^|\s)bg_task_done(?:\s|$)/u.test(inputText), approvalKind, + withdrawApproval: /(?:^|\s)withdraw_approval(?:\s|$)/u.test(inputText), delayMs: delayMatch?.[1] === undefined ? 0 : Number(delayMatch[1]), questionRequested: questionMatch !== null, responseText: @@ -693,6 +695,13 @@ function beginTurn(args: { responseText: plan.responseText, delayMs: plan.delayMs, }); + if (plan.withdrawApproval) { + setTimeout(() => { + if (!pendingReplies.delete(requestId)) return; + notify(BRIDGE_NOTIFICATION_METHODS.requestCancelled, { requestId }); + scheduleCompletion(session, "Approval withdrawn", 0); + }, plan.delayMs); + } return; } if (plan.questionRequested) {