From 32d274dabc79546a29b7d9c2695c54f7d5a3e7a0 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Mon, 23 Nov 2026 17:07:41 -0800 Subject: [PATCH] Stop non-user messages from revoking a running user turn's approvals A message that is not from the user (another thread's tell, a system notice) resolves to permission escalation "deny". bb steered it into the running turn with those options, so a turn the user started lost its approvals mid-flight: Codex interrupted the turn to apply approvalPolicy "never", and runtime-enforced bridges such as Pi auto-declined the turn's later approval requests without asking. The dispatch checkpoint now queues a deny-escalation message behind a running "ask" turn (thread-busy), so it runs as its own turn afterwards, in order, with its own permissions. As a backstop the runtime never lets a steer lower the running turn's escalation, and it logs every approval request it declines without asking, with the reason and request/turn ids. Fixes #7040 Co-Authored-By: Claude Opus 5.5 --- .../src/services/threads/dispatch-attempt.ts | 29 ++++ .../src/services/threads/thread-events.ts | 20 +++ apps/server/test/helpers/seed.ts | 4 +- .../test/threads/dispatcher-paths.test.ts | 127 ++++++++++++++++++ .../parent-system-message-dispatch.test.ts | 1 + .../threads/system-notice-dispatch.test.ts | 60 ++++++++- .../test/threads/thread-send-dispatch.test.ts | 6 + .../agent-runtime/src/execution-options.ts | 17 +++ .../src/permission-matrix.test.ts | 1 + .../src/runtime-provider-requests.ts | 19 ++- .../src/runtime.interactive-requests.test.ts | 72 ++++++++++ .../src/runtime.tool-calls.test.ts | 2 + packages/agent-runtime/src/runtime.ts | 18 ++- .../templates/bb-guide-thread-messaging.md | 8 +- plugins/bb-guide/skills/bb-cli/SKILL.md | 5 +- .../src/provider-bridge.ts | 50 ++++--- 16 files changed, 408 insertions(+), 31 deletions(-) diff --git a/apps/server/src/services/threads/dispatch-attempt.ts b/apps/server/src/services/threads/dispatch-attempt.ts index 21475faa90e..a4744b844c5 100644 --- a/apps/server/src/services/threads/dispatch-attempt.ts +++ b/apps/server/src/services/threads/dispatch-attempt.ts @@ -69,10 +69,12 @@ import { runThreadLifecycleInTransaction } from "./lifecycle/run.js"; import { buildExecutionOptions } from "./thread-commands.js"; import { getActiveTurnId, + getActiveTurnInitiator, isActiveTurnMainRunIdle, isManualCompactionActive, } from "./thread-events.js"; import { requireThreadCommandEnvironment } from "./thread-command-environment.js"; +import { resolvePermissionEscalation } from "./thread-runtime-config.js"; import { assertThreadHostAcceptsWork } from "./thread-host-admission.js"; import { requestThreadProvision, @@ -594,6 +596,33 @@ async function runDispatchAttempt( return; } + if ( + thread.status === "active" && + attempt === "join-turn" && + !isActiveTurnMainRunIdle(deps, currentThread) + ) { + const runningTurnInitiator = getActiveTurnInitiator(deps, currentThread); + if ( + runningTurnInitiator !== null && + resolvePermissionEscalation({ initiator: author.initiator }) === + "deny" && + resolvePermissionEscalation({ initiator: runningTurnInitiator }) === + "ask" + ) { + deps.logger.info( + { + threadId: thread.id, + initiator: author.initiator, + runningTurnInitiator, + senderThreadId: author.senderThreadId, + }, + "Queued a message behind the running turn instead of steering it in: its approval policy is deny and would revoke the running turn's approvals", + ); + continued.outcome = waitOn({ kind: "thread-busy" }); + return; + } + } + if ( dispatchEnvironment !== null && goneThreadEnvironmentDetails(dispatchEnvironment) === null && diff --git a/apps/server/src/services/threads/thread-events.ts b/apps/server/src/services/threads/thread-events.ts index d78069e8e2b..5595626a12b 100644 --- a/apps/server/src/services/threads/thread-events.ts +++ b/apps/server/src/services/threads/thread-events.ts @@ -919,6 +919,26 @@ export function isManualCompactionActive( ); } +export function getActiveTurnInitiator( + deps: ThreadEventReadDeps, + thread: Pick, +): ThreadTurnInitiator | null { + if (thread.status !== "active") { + return null; + } + const activeTurnId = getActiveStoredTurnId(deps.db, thread.id); + const requestRow = + (activeTurnId === null + ? null + : getStoredTurnRequestEventForTurn(deps.db, { + threadId: thread.id, + turnId: activeTurnId, + })) ?? getLastStoredTurnRequestEvent(deps.db, thread.id); + return requestRow === null + ? null + : parseStoredTurnRequestEvent(requestRow).initiator; +} + export function getLastProviderThreadId( deps: ThreadEventReadDeps, threadId: string, diff --git a/apps/server/test/helpers/seed.ts b/apps/server/test/helpers/seed.ts index deaad81b58b..3a9fd67c26a 100644 --- a/apps/server/test/helpers/seed.ts +++ b/apps/server/test/helpers/seed.ts @@ -40,6 +40,7 @@ import type { ThreadOriginKind, ThreadStatus, ThreadParentNotifications, + ThreadTurnInitiator, ThreadVisibility, } from "@bb/domain"; import type { AppDeps } from "../../src/types.js"; @@ -382,6 +383,7 @@ export function seedThreadRuntimeState( deps: Pick, args: { environmentId: string | null; + initiator?: ThreadTurnInitiator; inputText?: string; model?: string; providerThreadId: string; @@ -426,7 +428,7 @@ export function seedThreadRuntimeState( permissionMode: args.permissionMode ?? "full", source: "client/turn/requested", }, - initiator: "user", + initiator: args.initiator ?? "user", senderThreadId: null, request: { method: "turn/start", diff --git a/apps/server/test/threads/dispatcher-paths.test.ts b/apps/server/test/threads/dispatcher-paths.test.ts index eef2d6a70fe..02ab40a0c14 100644 --- a/apps/server/test/threads/dispatcher-paths.test.ts +++ b/apps/server/test/threads/dispatcher-paths.test.ts @@ -1,5 +1,6 @@ import { getQueuedThreadMessage, + getThread, listQueuedThreadMessages, setQueuedThreadMessageGroupBoundary, } from "@bb/db"; @@ -531,3 +532,129 @@ describe("queue intent after the dispatch hook", () => { }); }); }); + +describe("an agent message sent while a turn runs", () => { + async function sendFromSender( + harness: TestAppHarness, + args: { threadId: string; senderThreadId: string; text: string }, + ) { + const thread = getThread(harness.db, args.threadId); + if (thread === null) throw new Error("expected a thread"); + return acceptThreadSendRequest(harness.deps, { + payload: { + input: textInput(args.text), + mode: "auto", + senderThreadId: args.senderThreadId, + }, + thread, + }); + } + + function runDispatchedTurn( + harness: TestAppHarness, + fixture: ReturnType, + turnId: string, + ) { + moveThreadStatus(harness.deps, { + move: "run.started", + threadId: fixture.thread.id, + }); + seedTurnStarted(harness.deps, { + environmentId: fixture.environment.id, + threadId: fixture.thread.id, + turnId, + providerThreadId: `provider-${fixture.host.id}`, + }); + } + + it("waits behind a turn the user is running, then runs every message in order", async () => { + await withTestHarness(async (harness) => { + const fixture = seedRunnableThread(harness, { + hostId: "host-agent-behind-user-turn", + status: "active", + }); + const { thread } = fixture; + const sender = seedThread(harness.deps, { + projectId: fixture.project.id, + title: "Sender", + }); + + for (const text of ["Notice 1", "Notice 2", "Notice 3"]) { + const response = await sendFromSender(harness, { + threadId: thread.id, + senderThreadId: sender.id, + text, + }); + expect(response).toMatchObject({ + delivery: "queued", + queuedMessage: { waitingOn: { kind: "thread-busy" } }, + }); + } + expect( + listQueuedThreadCommands(harness, "turn.submit", thread.id), + ).toHaveLength(0); + + for (let turn = 1; queuedRows(harness, thread.id).length > 0; turn += 1) { + if (turn > 3) throw new Error("the queue did not drain"); + moveThreadStatus(harness.deps, { + move: "run.succeeded", + threadId: thread.id, + }); + await runQueuedMessageDispatch(harness.deps, { + kind: "thread-ready", + threadId: thread.id, + }); + runDispatchedTurn(harness, fixture, `turn-notice-${turn}`); + } + + const agentRequests = turnRequests(harness, thread.id).filter( + (request) => request.initiator === "agent", + ); + expect( + agentRequests.flatMap((request) => [ + request.target.kind, + ...(firstText(request).match(/Notice \d/gu) ?? []), + ]), + ).toEqual([ + "new-turn", + "Notice 1", + "new-turn", + "Notice 2", + "new-turn", + "Notice 3", + ]); + }); + }); + + it("still steers into a turn an agent message started", async () => { + await withTestHarness(async (harness) => { + const fixture = seedRunnableThread(harness, { + hostId: "host-agent-into-agent-turn", + status: "idle", + }); + const sender = seedThread(harness.deps, { + projectId: fixture.project.id, + title: "Sender", + }); + await sendFromSender(harness, { + threadId: fixture.thread.id, + senderThreadId: sender.id, + text: "First notice", + }); + runDispatchedTurn(harness, fixture, "turn-first-notice"); + + const response = await sendFromSender(harness, { + threadId: fixture.thread.id, + senderThreadId: sender.id, + text: "Second notice", + }); + + expect(response).toMatchObject({ delivery: "sent" }); + expect( + turnRequests(harness, fixture.thread.id).map( + (request) => request.target.kind, + ), + ).toEqual(["new-turn", "new-turn", "auto"]); + }); + }); +}); diff --git a/apps/server/test/threads/parent-system-message-dispatch.test.ts b/apps/server/test/threads/parent-system-message-dispatch.test.ts index 38660417116..f84776c54a4 100644 --- a/apps/server/test/threads/parent-system-message-dispatch.test.ts +++ b/apps/server/test/threads/parent-system-message-dispatch.test.ts @@ -46,6 +46,7 @@ describe("parent system message dispatch", () => { }); seedThreadRuntimeState(harness.deps, { environmentId: environment.id, + initiator: "agent", providerThreadId: "provider-parent-notice", threadId: thread.id, }); diff --git a/apps/server/test/threads/system-notice-dispatch.test.ts b/apps/server/test/threads/system-notice-dispatch.test.ts index cf663f3b2e5..9caf49162de 100644 --- a/apps/server/test/threads/system-notice-dispatch.test.ts +++ b/apps/server/test/threads/system-notice-dispatch.test.ts @@ -6,6 +6,7 @@ import { } from "@bb/db"; import { turnRequestEventDataSchema, + type ThreadTurnInitiator, type TurnRequestEventData, } from "@bb/domain"; import type { @@ -41,6 +42,7 @@ import { createUserQuestionPayload, } from "../helpers/pending-interactions.js"; import { textInput } from "../helpers/prompt-input.js"; +import { moveThreadStatus } from "../helpers/thread-status.js"; import { seedEnvironment, seedHostSession, @@ -85,7 +87,12 @@ afterEach(() => { function seedRunnableThread( harness: TestAppHarness, - args: { hostId: string; status: "idle" | "active"; title?: string }, + args: { + hostId: string; + status: "idle" | "active"; + title?: string; + runningTurnInitiator?: ThreadTurnInitiator; + }, ) { const { host, session } = seedHostSession(harness.deps, { id: args.hostId, @@ -107,6 +114,9 @@ function seedRunnableThread( }); seedThreadRuntimeState(harness.deps, { environmentId: environment.id, + ...(args.runningTurnInitiator !== undefined + ? { initiator: args.runningTurnInitiator } + : {}), providerThreadId: `provider-${args.hostId}`, threadId: thread.id, }); @@ -440,6 +450,7 @@ describe("coalesced notices", () => { const { project, thread: parent } = seedRunnableThread(harness, { hostId: "host-waiting-notice", status: "active", + runningTurnInitiator: "agent", }); const registered = harness.deps.pendingInteractions.registerPendingInteraction({ @@ -553,6 +564,7 @@ describe("notice recovery", () => { const { thread: parent } = seedRunnableThread(harness, { hostId: "host-notice-recovery", status: "active", + runningTurnInitiator: "agent", }); const blocker = await createQueuedMessageForThread(harness.deps, { thread: parent, @@ -604,6 +616,7 @@ describe("notices to a parent mid-turn", () => { const { thread: parent } = seedRunnableThread(harness, { hostId: "host-steer-running", status: "active", + runningTurnInitiator: "agent", }); await expect(queueChildCompletedNotice(harness, parent.id)).resolves.toBe( @@ -617,6 +630,47 @@ describe("notices to a parent mid-turn", () => { }); }); + it("wait behind a turn the user started, then run as their own turn", async () => { + await withTestHarness(async (harness) => { + const { thread: parent } = seedRunnableThread(harness, { + hostId: "host-behind-user-turn", + status: "active", + runningTurnInitiator: "user", + }); + + await expect(queueChildCompletedNotice(harness, parent.id)).resolves.toBe( + true, + ); + expect(turnSubmitTargets(harness, parent.id)).toEqual([]); + expect(queuedRows(harness, parent.id)).toEqual([ + expect.objectContaining({ waitingOn: { kind: "thread-busy" } }), + ]); + + moveThreadStatus(harness.deps, { + move: "run.succeeded", + threadId: parent.id, + }); + await runQueuedMessageDispatch(harness.deps, { + kind: "thread-ready", + threadId: parent.id, + }); + + expect(turnSubmitTargets(harness, parent.id)).toEqual([ + { mode: "auto", expectedTurnId: null }, + ]); + expect( + turnRequests(harness, parent.id).map((request) => [ + request.initiator, + request.target.kind, + ]), + ).toEqual([ + ["user", "new-turn"], + ["system", "new-turn"], + ]); + expect(queuedRows(harness, parent.id)).toEqual([]); + }); + }); + it("pass a limiter at its cap as a join-turn attempt", async () => { await withTestHarness(async (harness) => { const attempts: MessageDispatchHookContext["attempt"][] = []; @@ -629,6 +683,7 @@ describe("notices to a parent mid-turn", () => { const { thread: parent } = seedRunnableThread(harness, { hostId: "host-steer-at-cap", status: "active", + runningTurnInitiator: "agent", }); await queueChildCompletedNotice(harness, parent.id); @@ -650,6 +705,7 @@ describe("notices to a parent mid-turn", () => { const { thread: parent } = seedRunnableThread(harness, { hostId: "host-steer-held", status: "active", + runningTurnInitiator: "agent", }); await queueChildCompletedNotice(harness, parent.id); @@ -675,6 +731,7 @@ describe("notices to a parent mid-turn", () => { const { thread: parent } = seedRunnableThread(harness, { hostId: "host-steer-question", status: "active", + runningTurnInitiator: "agent", }); const registered = harness.deps.pendingInteractions.registerPendingInteraction({ @@ -728,6 +785,7 @@ describe("notices to a parent mid-turn", () => { } = seedRunnableThread(harness, { hostId: "host-steer-offline", status: "active", + runningTurnInitiator: "agent", }); handleDaemonSocketClosed(harness.deps, { sessionId: session.id }); harness.hub.cancelPendingDaemonDisconnect(session.id); diff --git a/apps/server/test/threads/thread-send-dispatch.test.ts b/apps/server/test/threads/thread-send-dispatch.test.ts index 70677370476..938e74b210c 100644 --- a/apps/server/test/threads/thread-send-dispatch.test.ts +++ b/apps/server/test/threads/thread-send-dispatch.test.ts @@ -22,6 +22,7 @@ import { type Thread, type ThreadChangedMessage, type ThreadEvent, + type ThreadTurnInitiator, } from "@bb/domain"; import { groupHostDaemonEvents } from "@bb/host-daemon-contract"; import { @@ -87,6 +88,7 @@ interface SeedIdleThreadFixtureArgs { interface SeedProviderThreadFixtureArgs extends SeedIdleThreadFixtureArgs { status?: "active" | "idle" | "starting"; serviceTier?: ServiceTier; + runningTurnInitiator?: ThreadTurnInitiator; } afterEach(() => vi.restoreAllMocks()); @@ -114,6 +116,9 @@ function seedProviderThreadFixture( }); seedThreadRuntimeState(args.harness.deps, { environmentId: environment.id, + ...(args.runningTurnInitiator !== undefined + ? { initiator: args.runningTurnInitiator } + : {}), providerThreadId: `provider-send-dispatch-${args.value}`, serviceTier: args.serviceTier, threadId: thread.id, @@ -992,6 +997,7 @@ describe("startup queue waits", () => { await withTestHarness(async (harness) => { const { sessionId, thread } = seedProviderThreadFixture({ harness, + runningTurnInitiator: "agent", status: "active", value: 62, }); diff --git a/packages/agent-runtime/src/execution-options.ts b/packages/agent-runtime/src/execution-options.ts index eb5d00352c0..b286086a72f 100644 --- a/packages/agent-runtime/src/execution-options.ts +++ b/packages/agent-runtime/src/execution-options.ts @@ -40,6 +40,23 @@ export function assertProviderSupportsExecutionOptions( } } +interface KeepRunningTurnApprovalsArgs { + requested: AgentRuntimeExecutionOptions; + running: AgentRuntimeExecutionOptions; +} + +export function keepRunningTurnApprovals( + args: KeepRunningTurnApprovalsArgs, +): AgentRuntimeExecutionOptions { + if ( + args.requested.permissionEscalation !== "deny" || + args.running.permissionEscalation !== "ask" + ) { + return args.requested; + } + return { ...args.requested, permissionEscalation: "ask" }; +} + export function toProviderExecutionContext( args: ToProviderExecutionContextArgs, ): ProviderExecutionContext { diff --git a/packages/agent-runtime/src/permission-matrix.test.ts b/packages/agent-runtime/src/permission-matrix.test.ts index e11c11d0e89..4c429e267c1 100644 --- a/packages/agent-runtime/src/permission-matrix.test.ts +++ b/packages/agent-runtime/src/permission-matrix.test.ts @@ -388,6 +388,7 @@ async function runCell( toolCalls: new RuntimeProviderRequests(), getActiveTurnId: () => "turn-1", getThreadExecutionOptions: () => executionOptions, + onStderr: undefined, onInteractiveRequest, onToolCall: async () => ({ contentItems: [{ type: "inputText", text: "unused" }], diff --git a/packages/agent-runtime/src/runtime-provider-requests.ts b/packages/agent-runtime/src/runtime-provider-requests.ts index 376ef17ecda..51b6e375643 100644 --- a/packages/agent-runtime/src/runtime-provider-requests.ts +++ b/packages/agent-runtime/src/runtime-provider-requests.ts @@ -119,6 +119,7 @@ interface HandleRuntimeProviderRequestArgs extends RuntimeProviderRequestArgs { threadId: string, ) => AgentRuntimeExecutionOptions | undefined; onInteractiveRequest: AgentRuntimeOptions["onInteractiveRequest"]; + onStderr: AgentRuntimeOptions["onStderr"]; onToolCall: AgentRuntimeOptions["onToolCall"]; interactiveRequests: RuntimeProviderRequests; toolCalls: RuntimeProviderRequests; @@ -304,13 +305,21 @@ function handleInteractiveProviderRequest( const executionOptions = runtimeOwnsApprovalPolicy ? args.getThreadExecutionOptions(resolvedThreadId) : undefined; - const shouldAutoDenyApprovalRequest = - isApprovalRequest && - ((runtimeOwnsApprovalPolicy && executionOptions + const deniedByPolicy = + runtimeOwnsApprovalPolicy && executionOptions ? shouldAutoDenyInteractiveRequest(executionOptions) - : false) || - !args.onInteractiveRequest); + : false; + const shouldAutoDenyApprovalRequest = + isApprovalRequest && (deniedByPolicy || !args.onInteractiveRequest); if (shouldAutoDenyApprovalRequest) { + args.onStderr?.( + `Declined approval request "${String(interactiveReq.requestId)}" on turn "${resolvedTurnId}" for thread "${resolvedThreadId}" without asking: ${ + deniedByPolicy + ? 'the turn runs with permission escalation "deny"' + : "no interactive request handler is configured" + }.`, + resolvedThreadId, + ); try { const resolution = buildDeniedInteractiveResolution( interactiveReq.payload, diff --git a/packages/agent-runtime/src/runtime.interactive-requests.test.ts b/packages/agent-runtime/src/runtime.interactive-requests.test.ts index a5f7acf71d9..5986d1670b9 100644 --- a/packages/agent-runtime/src/runtime.interactive-requests.test.ts +++ b/packages/agent-runtime/src/runtime.interactive-requests.test.ts @@ -75,6 +75,14 @@ const deniedEscalationOptions = { permissionEscalation: "deny", } as const; +const askEscalationOptions = { + ...fullRuntimeOptions, + permissionMode: "accept-edits", + permissionScope: "workspace", + approvalReviewer: "user", + permissionEscalation: "ask", +} as const; + async function answerDirectRequest(args: { rawRequest: JsonRpcMessage; handshake?: Record; @@ -110,6 +118,7 @@ async function answerDirectRequest(args: { getThreadExecutionOptions: args.getThreadExecutionOptions ?? (() => undefined), onInteractiveRequest: args.onInteractiveRequest, + onStderr: undefined, onToolCall: async () => ({ contentItems: [{ type: "inputText", text: "tool result" }], success: true, @@ -334,10 +343,12 @@ describe("createAgentRuntime interactive requests", () => { it("denies interactive requests when permission escalation is deny", async () => { const requests: string[] = []; const events: ThreadEvent[] = []; + const stderr: string[] = []; const runtime = createScriptedEchoRuntime({ runtime: { workspacePath: tmpDir, onEvent: (event) => events.push(event), + onStderr: (line) => stderr.push(line), onInteractiveRequest: async (request) => { requests.push(request.providerRequestId); return { decision: "allow_once", grantedPermissions: null }; @@ -368,6 +379,67 @@ describe("createAgentRuntime interactive requests", () => { }); expect(requests).toEqual([]); + expect(stderr).toContainEqual( + expect.stringMatching( + /^Declined approval request ".+" on turn ".+" for thread "t1" without asking: the turn runs with permission escalation "deny"\.$/u, + ), + ); + await runtime.shutdown(); + }); + + it("keeps asking for a running turn's approvals after a deny-escalation steer joins it", async () => { + const requests: string[] = []; + const events: ThreadEvent[] = []; + const runtime = createScriptedEchoRuntime({ + runtime: { + workspacePath: tmpDir, + onEvent: (event) => events.push(event), + onInteractiveRequest: async (request) => { + requests.push(request.providerRequestId); + return { decision: "allow_once", grantedPermissions: null }; + }, + }, + }); + + await runtime.startThread({ + environmentId: "env-1", + threadId: "t1", + projectId: "p1", + providerId: "fake", + options: askEscalationOptions, + }); + await runtime.runTurn({ + additionalWorkspaceWriteRoots: [], + clientRequestId: "creq_222222225a", + threadId: "t1", + input: [promptTextInput({ text: "hold_turn" })], + options: askEscalationOptions, + }); + const { turnId } = await waitForThreadTurnStarted({ + events, + providerId: "fake", + runtime, + threadId: "t1", + }); + await expect( + runtime.steerTurn({ + additionalWorkspaceWriteRoots: [], + threadId: "t1", + expectedTurnId: turnId, + clientRequestId: "creq_222222225b", + input: [promptTextInput({ text: "approve:command steered" })], + options: { ...askEscalationOptions, permissionEscalation: "deny" }, + }), + ).resolves.toEqual({ status: "steered" }); + await waitForThreadAgentMessageText({ + events, + providerId: "fake", + runtime, + text: "Response to: approve:command steered", + threadId: "t1", + }); + + expect(requests).toHaveLength(1); await runtime.shutdown(); }); diff --git a/packages/agent-runtime/src/runtime.tool-calls.test.ts b/packages/agent-runtime/src/runtime.tool-calls.test.ts index aa76e78a69d..0c46e87537f 100644 --- a/packages/agent-runtime/src/runtime.tool-calls.test.ts +++ b/packages/agent-runtime/src/runtime.tool-calls.test.ts @@ -252,6 +252,7 @@ describe("createAgentRuntime tool calls", () => { toolCalls: new RuntimeProviderRequests(), getActiveTurnId: () => null, getThreadExecutionOptions: () => undefined, + onStderr: undefined, onInteractiveRequest: async () => ({ decision: "deny", }), @@ -317,6 +318,7 @@ describe("createAgentRuntime tool calls", () => { toolCalls: new RuntimeProviderRequests(), getActiveTurnId: () => "turn-1", getThreadExecutionOptions: () => undefined, + onStderr: undefined, onInteractiveRequest: async () => ({ decision: "deny", }), diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts index 629f0bccab8..9205f441723 100644 --- a/packages/agent-runtime/src/runtime.ts +++ b/packages/agent-runtime/src/runtime.ts @@ -37,6 +37,7 @@ import type { } from "@bb/provider-bridge-protocol/bridge-kit"; import { assertProviderSupportsExecutionOptions, + keepRunningTurnApprovals, toProviderExecutionContext, } from "./execution-options.js"; import { @@ -1384,6 +1385,7 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { getThreadExecutionOptions: (threadId) => threadRuntimeConfigs.get(threadId)?.options, onInteractiveRequest: options.onInteractiveRequest, + onStderr: options.onStderr, onToolCall: options.onToolCall, interactiveRequests, toolCalls, @@ -2164,7 +2166,7 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { expectedTurnId, input, clientRequestId, - options: execOpts, + options: requestedOptions, contributedEnv, instructions, }) { @@ -2175,7 +2177,7 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { const currentProc = requireProviderProcessForThread(threadId); assertProviderSupportsExecutionOptions({ adapter: currentProc.adapter, - options: execOpts, + options: requestedOptions, providerId: pid, }); @@ -2192,7 +2194,7 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { await restartThreadBridgeIfRecommended({ threadId, - options: execOpts, + options: requestedOptions, instructions, }); const proc = requireProviderProcessForThread(threadId); @@ -2200,6 +2202,16 @@ export function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime { if (!currentConfig) { throw new Error(`No runtime configuration for thread ${threadId}`); } + const execOpts = keepRunningTurnApprovals({ + requested: requestedOptions, + running: currentConfig.options, + }); + if (execOpts !== requestedOptions) { + options.onStderr?.( + `Steer for thread "${threadId}" on turn "${expectedTurnId}" asked for permission escalation "deny"; keeping the running turn's "ask" so the steer cannot revoke that turn's approvals.`, + threadId, + ); + } const resolvedContributedEnv = contributedEnv ?? currentConfig.contributedEnv; const resolvedEnvironment = resolveRuntimeThreadEnvironment({ diff --git a/packages/templates/src/templates/bb-guide-thread-messaging.md b/packages/templates/src/templates/bb-guide-thread-messaging.md index e8dd052f0af..fdb858bf146 100644 --- a/packages/templates/src/templates/bb-guide-thread-messaging.md +++ b/packages/templates/src/templates/bb-guide-thread-messaging.md @@ -30,8 +30,12 @@ Messaging: is free; --mode auto steers a live turn and starts a new one on an idle thread. Input sent while a turn is starting stays in the queue with `waitingOn: turn-starting`; `turn/started` wakes it and steers it into that - turn. A target that is awaiting user interaction (an open question or - approval) cannot take a prompt; tell then adds the message to the thread's + turn. A tell from another thread (or a system notice) never steers into a + turn the user started: it may not ask for approvals, and joining would take + that turn's approvals away. It queues with `waitingOn: thread-busy` and runs + as its own turn after the user's turn ends, in order. A target that is + awaiting user interaction (an open question or approval) cannot take a + prompt; tell then adds the message to the thread's queue and dispatches it once the interaction settles. That outcome is not a failure, so do not resend. `--json` reports `delivery` as `sent` or `queued`. A sent answer carries `messageSequence`, the thread event sequence of the diff --git a/plugins/bb-guide/skills/bb-cli/SKILL.md b/plugins/bb-guide/skills/bb-cli/SKILL.md index 62554d2c198..bf3980f95de 100644 --- a/plugins/bb-guide/skills/bb-cli/SKILL.md +++ b/plugins/bb-guide/skills/bb-cli/SKILL.md @@ -75,8 +75,9 @@ A plugin's commands and settings are documented in that plugin's own skill. reads; use `bb thread wait ` when you must block. - `bb thread tell` steers the active turn by default. Steer for a wrong direction, a hard stop, or a critical clarification; use `--mode queue` for - non-urgent follow-ups. A send reported as `queued` is not a failure; do not - resend it. + non-urgent follow-ups. A tell into a turn the user started always queues + until that turn ends, so it cannot revoke the user's approvals. A send + reported as `queued` is not a failure; do not resend it. - For a review or fix pipeline, spawn the follow-up with `--environment ` from `bb thread show --json` so it sees the same files. diff --git a/tests/scripted-echo-provider/src/provider-bridge.ts b/tests/scripted-echo-provider/src/provider-bridge.ts index b3553e7e8bc..e831f892a7c 100644 --- a/tests/scripted-echo-provider/src/provider-bridge.ts +++ b/tests/scripted-echo-provider/src/provider-bridge.ts @@ -327,6 +327,29 @@ function parseTurnPlan(inputText: string): TurnPlan { }; } +function requestApproval( + session: Session, + providerTurnId: string, + plan: TurnPlan & { approvalKind: ApprovalKind }, +): JsonRpcId { + const requestId = sendRequest( + BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, + { + providerThreadId: session.providerThreadId, + threadId: session.threadId, + turnId: providerTurnId, + payload: approvalPayload(plan.approvalKind, `approval-${providerTurnId}`), + }, + ); + pendingReplies.set(requestId, { + kind: "approval", + threadId: session.threadId, + responseText: plan.responseText, + delayMs: plan.delayMs, + }); + return requestId; +} + function approvalPayload( kind: ApprovalKind, itemId: string, @@ -677,23 +700,9 @@ function beginTurn(args: { } if (plan.approvalKind !== null) { - const requestId = sendRequest( - BRIDGE_INBOUND_REQUEST_METHODS.interactionRequest, - { - providerThreadId: session.providerThreadId, - threadId: session.threadId, - turnId: providerTurnId, - payload: approvalPayload( - plan.approvalKind, - `approval-${providerTurnId}`, - ), - }, - ); - pendingReplies.set(requestId, { - kind: "approval", - threadId: session.threadId, - responseText: plan.responseText, - delayMs: plan.delayMs, + const requestId = requestApproval(session, providerTurnId, { + ...plan, + approvalKind: plan.approvalKind, }); if (plan.withdrawApproval) { setTimeout(() => { @@ -1229,6 +1238,7 @@ const handlers: Record = { return; } const providerTurnId = session.activeTurn.providerTurnId; + const steerPlan = parseTurnPlan(promptText(parsed.data.input)); const acceptSteer = (): void => { emitDeltas(session.threadId, [ { @@ -1238,6 +1248,12 @@ const handlers: Record = { }, ]); io.sendResult(id, {}); + if (steerPlan.approvalKind !== null) { + requestApproval(session, providerTurnId, { + ...steerPlan, + approvalKind: steerPlan.approvalKind, + }); + } }; if (options.steerResponseDelayMs === undefined) { acceptSteer();