Skip to content

ACP steer applies a changed environment during an active turn #8512

Backlog

Description

@GusevV1987

ACP steer applies a changed environment during an active turn

Summary

In a synthetic ACP bridge reproduction, a steer carrying changed environment values restarts the provider process during an active turn. Expected: keep the active environment for that turn and apply the environment supplied with the next genuine turn start. Explicit permission and model transitions should retain their existing behavior.

Versions and environment

Source checkout: get-bb/bb 864cff5e877bab6be3b26ebe38d0afeb93445b30, Linux 6.8, Node 22.23.5, pnpm 9.15.0. The affected bridge is unchanged at commit 5b6a9962635b96a87b2c354d0a03d28caa1b78f3. A tiny local ACP fixture is used, without any vendor account or model calls.

Steps to reproduce

  1. In a checkout of that source commit, save the two files below at the indicated repository-relative paths.
  2. Run corepack pnpm install --frozen-lockfile.
  3. Run corepack pnpm exec turbo run test --filter=@bb/provider-bridge-acp -- -t 'keeps.*environment'.

The fixture resumes an existing synthetic native ID under marker A, starts a pending prompt, and steers it with B. It records process launches, prompts and session-load IDs. It then starts a new turn with B. Cases also cover an unsolicited agent turn, stacked steers and a permission change.

Expected vs actual

Expected first-turn launch list: ['A'] (or ['A', 'A'] when an explicit permission change requires rebuilding). Only the next genuine turn should launch B. Actual unpatched ordinary case: ['A', 'B'].

No new native session should be created; the fixture asserts all loads use the original synthetic ID. This is an isolated source reproduction, not evidence of a production deployment.

Evidence and proposed correction

Reconciliation code merges newly requested environment values and can rebuild the process. Preserve session.construction.envVars for the internal pending inputs originating from turn/steer, including unsolicited agent activity; leave ordinary turn/start reconciliation unchanged.

The corrected candidate passes 650 package tests, with 4 existing skips, and type checking. Eight environment-boundary cases pass. The permission-restart failure fixture uses a file set up in the original environment so its error injection does not depend on changing environment values during a steer.

What was ruled out

packages/provider-bridge-acp/src/bridge/steer-environment.test.ts
import { mkdtempSync, readFileSync, existsSync, rmSync } from "node:fs";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { it, expect, vi } from "vitest";
import { createBridgeJsonRpcTestHarness } from "@bb/provider-bridge-protocol/testing";
import { handleLine } from "./bridge.js";
it.each([
  ["options", "turn"],
  ["launch", "turn"],
  ["inherited", "turn"],
  ["options", "agent"],
  ["launch", "agent"],
  ["inherited", "agent"],
  ["options", "permission"],
  ["options", "stacked"],
] as const)(
  "keeps %s environment during %s steering and applies its change at the next turn",
  async (source, origin) => {
    const root = mkdtempSync(join(tmpdir(), "bb-steer-env-")),
      log = join(root, "events.jsonl");
    vi.stubEnv("XDG_CONFIG_HOME", join(root, "config"));
    vi.stubEnv("CURSOR_CONFIG_DIR", join(root, "config/cursor"));
    vi.stubEnv("CURSOR_DATA_DIR", join(root, "data"));
    const h = createBridgeJsonRpcTestHarness(handleLine),
      threadId = "thr_env_boundary",
      providerThreadId = "26cf6e5d-a6f3-4c77-8823-803da50d6bd4";
    if (source === "inherited") vi.stubEnv("ENV_ACCOUNT", "A");
    const options = (
      account: string,
      permissionMode: "full" | "accept-edits" = "full",
    ) => {
      const envVars: Record<string, string> = {};
      const launchEnv: Record<string, string> = {};
      if (source === "options" || (source === "inherited" && account === "B"))
        envVars.ENV_ACCOUNT = account;
      if (source === "launch") {
        envVars.ENV_UNCHANGED = "yes";
        launchEnv.ENV_ACCOUNT = account;
      }
      return {
        permissionMode,
        ...(permissionMode === "full"
          ? {
              permissionScope: "full" as const,
              approvalReviewer: null,
              permissionEscalation: null,
            }
          : {
              permissionScope: "workspace" as const,
              approvalReviewer: "user" as const,
              permissionEscalation: "ask" as const,
            }),
        envVars,
        providerOptions: {
          acpDialect: "cursor",
          acpLaunchSpec: {
            displayName: "Synthetic ACP",
            command: process.execPath,
            args: [resolve(import.meta.dirname, "env-boundary-agent.mjs"), log],
            env: launchEnv,
            permissionCli: {
              full: ["--full"],
              workspaceWrite: ["--workspace"],
              insertAfterArgs: 2,
            },
          },
        },
      };
    };
    const completed = () =>
      h.messages.reduce((n, m) => {
        if (
          !("method" in m) ||
          m.method !== "thread/delta" ||
          !("params" in m) ||
          typeof m.params !== "object" ||
          m.params === null ||
          !("deltas" in m.params)
        )
          return n;
        const ds = m.params.deltas;
        return (
          n +
          (Array.isArray(ds)
            ? ds.filter(
                (d) =>
                  d &&
                  typeof d === "object" &&
                  !Array.isArray(d) &&
                  d.kind === "turn.boundary" &&
                  d.status === "completed",
              ).length
            : 0)
        );
      }, 0);
    const events = () =>
      existsSync(log)
        ? readFileSync(log, "utf8")
            .trim()
            .split("\n")
            .map((x) => JSON.parse(x))
        : [];
    try {
      h.sendRequest(1, "thread/resume", {
        threadId,
        providerThreadId,
        cwd: root,
        instructionMode: "append",
        options: options("A"),
      });
      expect((await h.waitForResponse(1)).error).toBeUndefined();
      h.sendRequest(2, "turn/start", {
        threadId,
        providerThreadId,
        clientRequestId: "creq_abcdefghjk",
        input: [
          {
            type: "text",
            text: origin === "agent" ? "AGENT_WAIT" : "HOLD_FIRST",
          },
        ],
        options: options("A"),
      });
      expect((await h.waitForResponse(2)).error).toBeUndefined();
      await vi.waitFor(() =>
        expect(events().filter((x) => x.kind === "prompt")).toHaveLength(1),
      );
      if (origin === "agent")
        await vi.waitFor(() =>
          expect(
            h.messages.some((x) =>
              JSON.stringify(x).includes("background-tool"),
            ),
          ).toBe(true),
        );
      h.sendRequest(3, "turn/steer", {
        threadId,
        providerThreadId,
        expectedTurnId: "turn-1",
        clientRequestId: "creq_abcdefghjm",
        input: [{ type: "text", text: "finish" }],
        options: options(
          "B",
          origin === "permission" ? "accept-edits" : "full",
        ),
      });
      if (origin === "stacked") {
        h.sendRequest(5, "turn/steer", {
          threadId,
          providerThreadId,
          expectedTurnId: "turn-1",
          clientRequestId: "creq_abcdefghjp",
          input: [{ type: "text", text: "second steer", mentions: [] }],
          options: options("C"),
        });
        expect((await h.waitForResponse(5)).error).toBeUndefined();
      }
      expect((await h.waitForResponse(3)).error).toBeUndefined();
      await vi.waitFor(() =>
        expect(completed()).toBe(origin === "agent" ? 2 : 1),
      );
      expect(
        events()
          .filter((x) => x.kind === "launch")
          .map((x) => x.account),
      ).toEqual(origin === "permission" ? ["A", "A"] : ["A"]);
      if (origin === "permission")
        expect(
          events()
            .filter((x) => x.kind === "launch")
            .at(-1).args,
        ).toContain("--workspace");
      expect(
        events()
          .filter((x) => x.kind === "prompt")
          .map((x) => x.account),
      ).toEqual(origin === "stacked" ? ["A", "A", "A"] : ["A", "A"]);
      h.sendRequest(4, "turn/start", {
        threadId,
        providerThreadId,
        clientRequestId: "creq_abcdefghjn",
        input: [{ type: "text", text: "next turn", mentions: [] }],
        options: options(
          "B",
          origin === "permission" ? "accept-edits" : "full",
        ),
      });
      expect((await h.waitForResponse(4)).error).toBeUndefined();
      await vi.waitFor(() =>
        expect(events().filter((x) => x.kind === "prompt")).toHaveLength(
          origin === "stacked" ? 4 : 3,
        ),
      );
      expect(
        events()
          .filter((x) => x.kind === "launch")
          .map((x) => x.account),
      ).toEqual(origin === "permission" ? ["A", "A", "B"] : ["A", "B"]);
      expect(
        events()
          .filter((x) => x.kind === "prompt")
          .map((x) => x.account),
      ).toEqual(origin === "stacked" ? ["A", "A", "A", "B"] : ["A", "A", "B"]);
      expect(
        events()
          .filter((x) => x.method === "session/load")
          .map((x) => x.sessionId),
      ).toEqual(Array(origin === "permission" ? 3 : 2).fill(providerThreadId));
      expect(events().some((x) => x.method === "session/new")).toBe(false);
    } finally {
      h.sendRequest(99, "thread/stop", {
        threadId,
        providerThreadId,
        intent: "release",
        activeTurnId: null,
      });
      await h.waitForResponse(99).catch(() => {});
      h.restore();
      vi.unstubAllEnvs();
      rmSync(root, { recursive: true, force: true });
    }
  },
  30000,
);
packages/provider-bridge-acp/src/bridge/env-boundary-agent.mjs
import { appendFileSync } from "node:fs";
import { createInterface } from "node:readline";
const account = process.env.ENV_ACCOUNT,
  log = process.argv[2];
let active = null,
  session,
  background = false;
const note = (kind, extra = {}) =>
  appendFileSync(
    log,
    JSON.stringify({ kind, account, pid: process.pid, ...extra }) + "\n",
  );
const send = (m) => process.stdout.write(JSON.stringify(m) + "\n");
note("launch", { args: process.argv.slice(3) });
createInterface({ input: process.stdin }).on("line", (line) => {
  const m = JSON.parse(line);
  note("request", { method: m.method, sessionId: m.params?.sessionId });
  if (m.method === "initialize")
    send({
      jsonrpc: "2.0",
      id: m.id,
      result: {
        protocolVersion: 1,
        agentCapabilities: { loadSession: true },
        authMethods: [],
      },
    });
  else if (m.method === "session/load") {
    session = m.params.sessionId;
    send({ jsonrpc: "2.0", id: m.id, result: {} });
  } else if (m.method === "session/prompt") {
    const text = m.params.prompt
      .filter((x) => x.type === "text")
      .map((x) => x.text)
      .join("\n");
    note("prompt", { text });
    if (text.includes("HOLD_FIRST")) active = m.id;
    else if (text.includes("AGENT_WAIT")) {
      send({ jsonrpc: "2.0", id: m.id, result: { stopReason: "end_turn" } });
      setTimeout(() => {
        background = true;
        send({
          jsonrpc: "2.0",
          method: "session/update",
          params: {
            sessionId: session,
            update: {
              sessionUpdate: "tool_call",
              toolCallId: "background",
              title: "background-tool",
              kind: "execute",
              status: "in_progress",
              content: [],
            },
          },
        });
      }, 30);
    } else {
      send({
        jsonrpc: "2.0",
        method: "session/update",
        params: {
          sessionId: session,
          update: {
            sessionUpdate: "agent_message_chunk",
            content: { type: "text", text: "ACCOUNT_" + account },
          },
        },
      });
      if (background) {
        background = false;
        send({
          jsonrpc: "2.0",
          method: "session/update",
          params: {
            sessionId: session,
            update: {
              sessionUpdate: "tool_call_update",
              toolCallId: "background",
              status: "completed",
            },
          },
        });
      }
      send({ jsonrpc: "2.0", id: m.id, result: { stopReason: "end_turn" } });
    }
  } else if (m.method === "session/cancel" && active !== null) {
    send({ jsonrpc: "2.0", id: active, result: { stopReason: "cancelled" } });
    active = null;
  } else if (m.id !== undefined)
    send({
      jsonrpc: "2.0",
      id: m.id,
      error: { code: -32601, message: "Unsupported fixture method" },
    });
});

AGENT GENERATED

Activity

  1. added theissue type on Dec 1, 2026
  2. added
    providers
    provider-acp
    on Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    provider-acpproviders

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions