sailfork / t3code-github / apps/ server/ src/ orchestration-v2/ Adapters/ AcpAdapterV2.test.ts

import {
  extractCopilotSubagentUpdate,
  makeCopilotSubagentRouting,
  normalizeDevinSessionUpdate,
  normalizeDevinToolCall,
  extractDevinSubagentUpdate,
  makeAcpRegistryAdapterV2,
} from "@t3tools/provider-acp-registry/testing";
import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings";
import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";

import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as DocumentText from "../../provider/DocumentText.ts";
import { assert, describe, it } from "@effect/vitest";
import {
  CheckpointId,
  EnvironmentId,
  type ModelSelection,
  ProviderDriverKind,
  ProviderInstanceId,
  ProviderSessionId,
  ThreadId,
  type OrchestrationV2ProviderThread,
  type OrchestrationV2TurnItem,
  type ProviderOptionDescriptor,
  type ProviderUserInputAnswers,
} from "@t3tools/contracts";
import { GrokSettings } from "@t3tools/provider-grok/settings";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { deriveBlockedOnThreadWait } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Scope from "effect/Scope";
import * as TestClock from "effect/testing/TestClock";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpProtocol from "effect-acp/protocol";
import type * as EffectAcpSchema from "effect-acp/compat";

import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import {
  ACP_EMPTY_OPTION_VALUE,
  ACP_SESSION_MODE_OPTION_ID,
  acpProviderOptionDescriptors,
} from "@t3tools/provider-acp/server/sessionConfig";
import {
  extractXAiAcpSubagentUpdate,
  makeGrokAdapterV2,
  makeXAiPromptCompletionRuntime,
  normalizeXAiAcpToolCallState,
  registerXAiBackgroundTaskTracking,
} from "@t3tools/provider-grok/testing";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { makeTurnInput } from "./AcpAdapterV2.testkit.ts";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
  AcpProviderCapabilitiesV2,
  acpPerTurnPromptUsage,
  acpScopedNativeId,
  acpPostSettleContinuationOfferEvidence,
  acpPostSettleWakeEvidence,
  acpToolCallDiffPatch,
  acpToolCallSnippetEdit,
  makeAcpAdapterV2,
  type AcpAdapterV2ExtensionContext,
  type AcpAdapterV2Flavor,
  type AcpAdapterV2RuntimeInput,
  type AcpAdapterV2SubagentUpdate,
} from "@t3tools/provider-acp/server/adapter";

import { appendUserInputAttachmentPaths } from "../../provider/userInputAttachments.ts";

import { makeGrokAcpAdapterFlavor } from "@t3tools/provider-grok/testing";
import {
  acpRegistryPromptFailure,
  registerMistralVibeAcpExtensions,
} from "@t3tools/provider-acp-registry/testing";

const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
const DROID_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "factory-droid" });

const layerHost = TestProviderHost.layer().pipe(
  Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);

const layerTest = Layer.mergeAll(
  DocumentText.layer.pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
  NodeServices.layer,
  NodeCrypto.layer,
  IdAllocator.layer,
  McpProviderSessions.layer,
  layerHost,
);
const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test");
const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));

describe("acpPerTurnPromptUsage", () => {
  it("maps a per-turn sample straight onto TurnTokenUsage", () => {
    assert.deepEqual(
      acpPerTurnPromptUsage(
        {
          inputTokens: 2453,
          outputTokens: 4,
          totalTokens: 2457,
          cachedReadTokens: 512,
          cachedWriteTokens: 32,
          thoughtTokens: 3,
        },
        false,
        "completed",
      ),
      {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 2453,
        outputTokens: 4,
        cachedInputTokens: 512,
        cacheCreationTokens: 32,
        reasoningTokens: 3,
      },
    );
    // Antigravity 1.4.5: its harness reports prompt tokens without the 24 cached ones.
    assert.deepEqual(
      acpPerTurnPromptUsage(
        {
          inputTokens: 42,
          outputTokens: 3,
          totalTokens: 54,
          cachedReadTokens: 24,
          cachedWriteTokens: 0,
          thoughtTokens: 9,
        },
        false,
        "completed",
        true,
      ),
      {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 66,
        outputTokens: 12,
        cachedInputTokens: 24,
        cacheCreationTokens: 0,
        reasoningTokens: 9,
      },
    );
  });

  it("clamps subsets that exceed their parents and drops unset counters", () => {
    assert.deepEqual(
      acpPerTurnPromptUsage(
        {
          inputTokens: 100,
          outputTokens: 10,
          totalTokens: 110,
          cachedReadTokens: 150,
          cachedWriteTokens: 120,
          thoughtTokens: 30,
        },
        false,
        "completed",
      ),
      {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 100,
        outputTokens: 10,
        cachedInputTokens: 100,
        cacheCreationTokens: 0,
        reasoningTokens: 10,
      },
    );
    assert.deepEqual(
      acpPerTurnPromptUsage(
        { inputTokens: 100, outputTokens: 10, totalTokens: 110 },
        false,
        "completed",
      ),
      {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 100,
        outputTokens: 10,
      },
    );
  });

  it("caps cache writes at the input left over after cache reads", () => {
    // Each counter fits under input alone, but together they exceed it.
    assert.deepEqual(
      acpPerTurnPromptUsage(
        {
          inputTokens: 100,
          outputTokens: 10,
          totalTokens: 110,
          cachedReadTokens: 80,
          cachedWriteTokens: 80,
        },
        false,
        "completed",
      ),
      {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 100,
        outputTokens: 10,
        cachedInputTokens: 80,
        cacheCreationTokens: 20,
      },
    );
  });

  it("marks present usage partial on a non-completed terminal and missing usage unavailable", () => {
    assert.deepEqual(
      acpPerTurnPromptUsage(
        { inputTokens: 100, outputTokens: 10, totalTokens: 110 },
        true,
        "interrupted",
      ),
      {
        usageScope: "main_agent",
        usageStatus: "partial",
        hasSubagents: true,
        inputTokens: 100,
        outputTokens: 10,
      },
    );
    assert.deepEqual(acpPerTurnPromptUsage(undefined, false, "completed"), {
      usageScope: "main_agent",
      usageStatus: "unavailable",
      hasSubagents: false,
    });
  });
});

describe("acpToolCallDiffPatch", () => {
  it("keeps an unplaced snippet as recorded text instead of numbering it from line 1", () => {
    const content = [
      {
        type: "diff",
        path: "/repo/a.ts",
        oldText: "const target = 10;",
        newText: "const target = 100;",
        patch: { format: "snippet", text: "@@ -1,1 +1,1 @@ snippet, line unknown\n" },
      },
    ];
    assert.isUndefined(acpToolCallDiffPatch(content));
    // An omitted preview is not re-diffed from the bare snippets either.
    assert.isUndefined(acpToolCallDiffPatch([{ ...content[0], patch: { format: "omitted" } }]));
    // A status block beside the snippet must not hide it.
    for (const blocks of [
      content,
      [{ type: "content", content: { type: "text", text: "Edited." } }, ...content],
    ]) {
      assert.isUndefined(acpToolCallDiffPatch(blocks));
      assert.deepEqual(acpToolCallSnippetEdit(blocks), {
        oldStr: "const target = 10;",
        newStr: "const target = 100;",
      });
    }
    // Beside another diff, the snippet is neither a patch nor a placed edit.
    const twoDiffs = [
      ...content,
      {
        type: "diff",
        path: "/repo/b.ts",
        oldText: "b\n",
        newText: "B\n",
        patch: { text: "@@ -1 +1 @@\n-b\n+B\n" },
      },
    ];
    assert.isUndefined(acpToolCallDiffPatch(twoDiffs));
    assert.isUndefined(acpToolCallSnippetEdit(twoDiffs));
  });

  it("builds per-file patches from ACP hunks and recorded old/new text", () => {
    for (const operation of ["add", "delete"]) {
      const text = operation === "add" ? "@@ -0,0 +1 @@\n+content\n" : "@@ -1 +0,0 @@\n-content\n";
      assert.equal(
        acpToolCallDiffPatch([
          {
            type: "diff",
            changes: [{ operation, path: "/repo/a.ts" }],
            patch: { format: "git_patch", text },
          },
        ]),
        [
          'diff --git "a//repo/a.ts" "b//repo/a.ts"',
          operation === "add" ? "--- /dev/null" : '--- "a//repo/a.ts"',
          operation === "delete" ? "+++ /dev/null" : '+++ "b//repo/a.ts"',
          text,
        ].join("\n"),
      );
    }
    assert.equal(
      acpToolCallDiffPatch([
        { type: "diff", path: "/repo/new.txt", oldText: null, newText: "hello\n" },
        { type: "diff", path: "/repo/a.ts", oldText: "a\nb\nc\n", newText: "a\nB\nc\n" },
        { type: "diff", path: "/repo/same.ts", oldText: "x\n", newText: "x\n" },
      ]),
      [
        "--- /dev/null",
        "+++ /repo/new.txt",
        "@@ -0,0 +1,1 @@",
        "+hello",
        "",
        "--- /repo/a.ts",
        "+++ /repo/a.ts",
        "@@ -1,3 +1,3 @@",
        " a",
        "-b",
        "+B",
        " c",
        "",
      ].join("\n"),
    );
    assert.equal(
      acpToolCallDiffPatch([
        {
          type: "diff",
          changes: [{ operation: "modify", path: "/repo/a.ts" }],
          patch: {
            format: "git_patch",
            text: "diff --git a/repo/a.ts b/repo/a.ts\n@@ -1 +1 @@\n-a\n+A\n",
          },
        },
        {
          type: "diff",
          changes: [{ operation: "modify", path: "/repo/b.ts" }],
          patch: {
            format: "git_patch",
            text: "diff --git a/repo/b.ts b/repo/b.ts\n@@ -1 +1 @@\n-b\n+B\n",
          },
        },
        { type: "diff", path: "/repo/c.ts", oldText: "c\n", newText: "C\n" },
      ]),
      [
        "diff --git a/repo/a.ts b/repo/a.ts",
        "@@ -1 +1 @@",
        "-a",
        "+A",
        "",
        "diff --git a/repo/b.ts b/repo/b.ts",
        "@@ -1 +1 @@",
        "-b",
        "+B",
        "",
        'diff --git "a//repo/c.ts" "b//repo/c.ts"',
        "--- /repo/c.ts",
        "+++ /repo/c.ts",
        "@@ -1,1 +1,1 @@",
        "-c",
        "+C",
        "",
      ].join("\n"),
    );
    assert.equal(
      acpToolCallDiffPatch([
        { type: "diff", path: "/repo/new.txt", oldText: null, newText: "hello\n" },
        {
          type: "diff",
          changes: [{ operation: "modify", path: "/repo/a.ts" }],
          patch: { format: "git_patch", text: "@@ -1 +1 @@\n-a\n+A\n" },
        },
      ]),
      [
        'diff --git "a//repo/new.txt" "b//repo/new.txt"',
        "--- /dev/null",
        "+++ /repo/new.txt",
        "@@ -0,0 +1,1 @@",
        "+hello",
        "",
        'diff --git "a//repo/a.ts" "b//repo/a.ts"',
        '--- "a//repo/a.ts"',
        '+++ "b//repo/a.ts"',
        "@@ -1 +1 @@",
        "-a",
        "+A",
        "",
      ].join("\n"),
    );
  });
});

function makeMockRuntime(input: {
  readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
  readonly mockAgentPath: string;
  readonly environment?:
    | Readonly<Record<string, string>>
    | ((runtimeOrdinal: number) => Readonly<Record<string, string>>);
  readonly protocolEvents?: Queue.Queue<EffectAcpProtocol.AcpProtocolLogEvent>;
  readonly cancelBehavior?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelBehavior"];
  readonly ownDescendantProcessGroups?: boolean;
  readonly ownDetachedProcessGroup?: boolean;
  readonly processGroupPlatform?: NodeJS.Platform;
  readonly processGroupTerminationGrace?: Duration.Input;
  readonly linuxCgroupController?: AcpSessionRuntime.AcpSessionRuntimeOptions["linuxCgroupController"];
  readonly posixProcessTreeController?: AcpSessionRuntime.AcpSessionRuntimeOptions["posixProcessTreeController"];
  readonly windowsProcessTreeTerminator?: AcpSessionRuntime.AcpSessionRuntimeOptions["windowsProcessTreeTerminator"];
  readonly wrapCancel?: (
    cancel: AcpSessionRuntime.AcpSessionRuntime["Service"]["cancel"],
  ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["cancel"];
  readonly wrapOutgoingResponse?: (
    onOutgoingResponse: NonNullable<AcpAdapterV2RuntimeInput["onOutgoingResponse"]>,
  ) => NonNullable<AcpAdapterV2RuntimeInput["onOutgoingResponse"]>;
  readonly wrapRuntime?: (
    runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
    runtimeOrdinal: number,
  ) => AcpSessionRuntime.AcpSessionRuntime["Service"];
}): AcpAdapterV2Flavor["makeRuntime"] {
  let runtimeOrdinal = 0;
  return (runtimeInput) =>
    Effect.gen(function* () {
      runtimeOrdinal += 1;
      const protocolEvents = input.protocolEvents;
      const protocolLogging =
        protocolEvents === undefined
          ? runtimeInput.protocolLogging
          : {
              ...runtimeInput.protocolLogging,
              logIncoming: true,
              logOutgoing: true,
              logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
                Queue.offer(protocolEvents, event).pipe(
                  Effect.andThen(runtimeInput.protocolLogging.logger?.(event) ?? Effect.void),
                  Effect.asVoid,
                ),
            };
      const context = yield* Layer.build(
        AcpSessionRuntime.layer({
          ...runtimeInput,
          ...(input.cancelBehavior === undefined ? {} : { cancelBehavior: input.cancelBehavior }),
          ...(input.ownDetachedProcessGroup === undefined
            ? {}
            : { ownDetachedProcessGroup: input.ownDetachedProcessGroup }),
          ...(input.ownDescendantProcessGroups === undefined
            ? {}
            : { ownDescendantProcessGroups: input.ownDescendantProcessGroups }),
          ...(input.ownDetachedProcessGroup === true
            ? { processGroupPlatform: input.processGroupPlatform ?? "linux" }
            : {}),
          ...(input.processGroupTerminationGrace === undefined
            ? {}
            : { processGroupTerminationGrace: input.processGroupTerminationGrace }),
          ...(input.linuxCgroupController === undefined
            ? {}
            : { linuxCgroupController: input.linuxCgroupController }),
          ...(input.posixProcessTreeController === undefined
            ? {}
            : { posixProcessTreeController: input.posixProcessTreeController }),
          ...(input.windowsProcessTreeTerminator === undefined
            ? {}
            : { windowsProcessTreeTerminator: input.windowsProcessTreeTerminator }),
          protocolLogging,
          spawn: {
            command: process.execPath,
            args: [input.mockAgentPath],
            cwd: runtimeInput.cwd,
            env: {
              T3_ACP_SESSION_LIFECYCLE: "1",
              ...(typeof input.environment === "function"
                ? input.environment(runtimeOrdinal)
                : input.environment),
            },
          },
          authMethodId: "test",
          ...(input.wrapOutgoingResponse === undefined ||
          runtimeInput.onOutgoingResponse === undefined
            ? {}
            : {
                onOutgoingResponse: input.wrapOutgoingResponse(runtimeInput.onOutgoingResponse),
              }),
        }).pipe(
          Layer.provide(
            Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
          ),
        ),
      );
      const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
        Effect.provide(context),
      );
      const wrapped = {
        ...runtime,
        ...(input.wrapCancel === undefined ? {} : { cancel: input.wrapCancel(runtime.cancel) }),
      };
      return input.wrapRuntime?.(wrapped, runtimeOrdinal) ?? wrapped;
    });
}

const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);

const makePromptInactivityHarness = Effect.fnUntraced(function* (input: {
  readonly environment: (runtimeOrdinal: number) => Readonly<Record<string, string>>;
  readonly runtimeMode?: "full-access" | "approval-required";
}) {
  const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
  const path = yield* Path.Path;
  const natives: Array<AcpSessionRuntime.AcpSessionRuntime["Service"]> = [];
  const instanceId = ProviderInstanceId.make("acp-prompt-inactivity");
  const adapter = yield* makeAcpAdapterV2({
    instanceId,
    flavor: {
      driver: ACP_TEST_DRIVER,
      capabilities: AcpProviderCapabilitiesV2,
      promptInactivityTimeout: "15 minutes",
      makeRuntime: makeMockRuntime({
        childProcessSpawner,
        mockAgentPath: yield* path.fromFileUrl(
          new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
        ),
        environment: input.environment,
        wrapRuntime: (runtime) => {
          natives.push(runtime);
          return runtime;
        },
      }),
    },
    selfInvocation: yield* resolveSelfInvocation(),
  });
  const threadId = ThreadId.make("thread-acp-prompt-inactivity");
  const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
    runtimeMode: input.runtimeMode ?? "full-access",
    interactionMode: "default",
    cwd: process.cwd(),
  });
  const modelSelection = { instanceId, model: "default" } as const;
  const runtime = yield* adapter.openSession({
    threadId,
    providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-inactivity"),
    modelSelection,
    runtimePolicy,
  });
  const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
  const startTurn = (ordinal: number) =>
    DateTime.now.pipe(
      Effect.flatMap((now) =>
        runtime.startTurn(
          makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),
        ),
      ),
    );
  return {
    runtime,
    natives,
    startTurn,
    /** A turn still running makes the next start fail, without waiting on time. */
    nextTurnRejected: (ordinal: number) =>
      startTurn(ordinal).pipe(
        Effect.flip,
        Effect.map(
          (error) =>
            isProviderAdapterProtocolError(error.cause) &&
            error.cause.reason === "previous_turn_active",
        ),
        Effect.catchCause(() => Effect.succeed(false)),
      ),
    emitUpdate: (notification: EffectAcpSchema.SessionNotification) =>
      natives.at(-1)!.request("_test/emit-update", notification),
    terminals: (count: number) =>
      runtime.events.pipe(
        Stream.filter((event) => event.type === "turn.terminal"),
        Stream.take(count),
        Stream.runCollect,
        Effect.map((events) =>
          Array.from(events, (event) => {
            if (event.type !== "turn.terminal") throw new Error("Expected a turn terminal");
            return event;
          }),
        ),
      ),
  };
});

function rawProtocolMethod(event: EffectAcpProtocol.AcpProtocolLogEvent): string | undefined {
  if (event.stage !== "raw" || typeof event.payload !== "string") return undefined;
  for (const line of event.payload.split("\n")) {
    const trimmed = line.trim();
    if (trimmed.length === 0) continue;
    const decoded = Option.getOrUndefined(decodeUnknownJson(trimmed));
    if (typeof decoded === "object" && decoded !== null && "method" in decoded) {
      const method = (decoded as { readonly method?: unknown }).method;
      if (typeof method === "string") return method;
    }
  }
  return undefined;
}

function rawProtocolRequest(
  event: EffectAcpProtocol.AcpProtocolLogEvent,
): { readonly method?: unknown; readonly params?: unknown } | undefined {
  if (event.stage !== "raw" || typeof event.payload !== "string") return undefined;
  for (const line of event.payload.split("\n")) {
    const trimmed = line.trim();
    if (trimmed.length === 0) continue;
    const decoded = Option.getOrUndefined(decodeUnknownJson(trimmed));
    if (typeof decoded === "object" && decoded !== null && "method" in decoded) {
      return decoded;
    }
  }
  return undefined;
}

function rawProtocolRequestParam(
  event: EffectAcpProtocol.AcpProtocolLogEvent,
  key: string,
): unknown {
  const params = rawProtocolRequest(event)?.params;
  return typeof params === "object" && params !== null ? Reflect.get(params, key) : undefined;
}

function rawProtocolPromptTextBlocks(
  event: EffectAcpProtocol.AcpProtocolLogEvent,
): Array<{ type: "text"; text: string }> {
  const prompt = rawProtocolRequestParam(event, "prompt");
  if (!Array.isArray(prompt)) return [];
  return prompt.flatMap((block) =>
    typeof block === "object" &&
    block !== null &&
    Reflect.get(block, "type") === "text" &&
    typeof Reflect.get(block, "text") === "string"
      ? [{ type: "text" as const, text: Reflect.get(block, "text") as string }]
      : [],
  );
}

const pollProtocolMethods = (events: Queue.Queue<EffectAcpProtocol.AcpProtocolLogEvent>) =>
  Effect.gen(function* () {
    const methods: string[] = [];
    let polled = 0;
    let event = yield* Queue.poll(events);
    while (Option.isSome(event) && polled < 256) {
      polled += 1;
      const method = rawProtocolMethod(event.value);
      if (method !== undefined) methods.push(method);
      event = yield* Queue.poll(events);
    }
    return methods;
  });

const makeInstructionCompactionHarness = Effect.fnUntraced(function* (
  environment: Readonly<Record<string, string>>,
) {
  const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
  const path = yield* Path.Path;
  const selfInvocation = yield* resolveSelfInvocation();
  const mockAgentPath = yield* path.fromFileUrl(
    new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
  );
  const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
  const instanceId = ProviderInstanceId.make("acp-test-instruction-compaction");
  const threadId = ThreadId.make("thread-acp-instruction-compaction");
  yield* (yield* McpProviderSessions.McpProviderSessions).set({
    environmentId: EnvironmentId.make("environment-acp-instruction-compaction"),
    threadId,
    providerSessionId: "mcp-session-acp-instruction-compaction",
    providerInstanceId: instanceId,
    endpoint: "http://127.0.0.1:43123/mcp",
    authorizationHeader: "Bearer instruction-compaction-token",
    browserToolsAvailable: true,
  });
  const adapter = yield* makeAcpAdapterV2({
    instanceId,
    flavor: {
      driver: ACP_TEST_DRIVER,
      capabilities: AcpProviderCapabilitiesV2,
      supportsCompaction: true,
      makeRuntime: makeMockRuntime({
        childProcessSpawner,
        mockAgentPath,
        protocolEvents,
        environment,
        wrapRuntime: (runtime) => ({
          ...runtime,
          // Make compaction during prompt completion deterministic at the adapter boundary.
          prompt: (payload, options) =>
            runtime.prompt(payload, options).pipe(Effect.tap(() => runtime.drainEvents)),
        }),
      }),
    },
    selfInvocation,
  });
  const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
    runtimeMode: "full-access",
    interactionMode: "default",
    cwd: process.cwd(),
  });
  const modelSelection = { instanceId, model: "default" } as const;
  const runtime = yield* adapter.openSession({
    threadId,
    providerSessionId: ProviderSessionId.make("provider-session-acp-instruction-compaction"),
    modelSelection,
    runtimePolicy,
  });
  const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
  const now = yield* DateTime.now;
  let ordinal = 0;
  return Effect.fnUntraced(function* (messageText: string, expectedStatus = "completed") {
    yield* runtime.startTurn(
      makeTurnInput({
        threadId,
        providerThread,
        instanceId,
        runtimePolicy,
        now,
        ordinal: ++ordinal,
        messageText,
      }),
    );
    const terminal = yield* runtime.events.pipe(
      Stream.filter((event) => event.type === "turn.terminal"),
      Stream.runHead,
    );
    assert.equal(Option.getOrThrow(terminal).status, expectedStatus);
    while (true) {
      const event = yield* Queue.take(protocolEvents);
      if (event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt") {
        return rawProtocolPromptTextBlocks(event);
      }
    }
  });
});

function assertReinjectedInstructions(
  blocks: Array<{ type: "text"; text: string }>,
  request: string,
) {
  const text = blocks[0]?.text ?? "";
  assert.include(text, "T3 Code interaction mode: Default");
  assert.include(text, "## T3 Code browser");
  assert.include(text, "T3 Code orchestration");
  assert.include(text, `<user_request>\n${request}\n</user_request>`);
}

describe("AcpAdapterV2", () => {
  it.live("reports per-turn usage unavailable on a continuation turn that never prompts", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-usage-continuation");
      const threadId = ThreadId.make("thread-acp-usage-continuation");
      let promptOrdinal = 0;
      const promptUsages = [
        { inputTokens: 60, outputTokens: 15, totalTokens: 75 },
        { inputTokens: 130, outputTokens: 30, totalTokens: 160 },
      ];
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        continuationRequests: { offer: () => Effect.void },
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          reportsPerTurnPromptUsage: true,
          enablePostSettleContinuation: true,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime) => ({
              ...runtime,
              prompt: () => {
                promptOrdinal += 1;
                const usage = promptUsages[promptOrdinal - 1];
                if (usage === undefined) return Effect.die("Unexpected prompt");
                return Effect.succeed({ stopReason: "end_turn" as const, usage });
              },
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-usage-continuation"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      const now = yield* DateTime.now;
      const completedUsage = (ordinal: number) =>
        Effect.gen(function* () {
          yield* runtime.startTurn(
            makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),
          );
          const events = Array.from(
            yield* runtime.events.pipe(
              Stream.takeUntil((event) => event.type === "turn.terminal"),
              Stream.runCollect,
            ),
          );
          const completed = events.find(
            (event) =>
              event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
          );
          return completed?.type === "provider_turn.updated"
            ? completed.providerTurn.turnTokenUsage
            : null;
        });
      assert.deepEqual(yield* completedUsage(1), {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 60,
        outputTokens: 15,
      });
      // Continuation attach: drains wake traffic and finalizes without ever
      // dispatching session/prompt, so it must report unavailable usage.
      yield* runtime.startTurn(
        makeTurnInput({
          threadId,
          providerThread,
          instanceId,
          runtimePolicy,
          now,
          ordinal: 2,
          messageCreatedBy: "agent",
          messageCreationSource: "provider",
          messageText: "Background task completed.",
        }),
      );
      const continuationEvents = Array.from(
        yield* runtime.events.pipe(
          Stream.takeUntil((event) => event.type === "turn.terminal"),
          Stream.runCollect,
        ),
      );
      const continuation = continuationEvents.find(
        (event) =>
          event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
      );
      assert.deepEqual(
        continuation?.type === "provider_turn.updated"
          ? continuation.providerTurn.turnTokenUsage
          : null,
        { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents: false },
      );
      // The continuation must not disturb the next real prompt's sample.
      assert.deepEqual(yield* completedUsage(3), {
        usageScope: "main_agent",
        usageStatus: "complete",
        hasSubagents: false,
        inputTokens: 130,
        outputTokens: 30,
      });
      assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt");
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );
  it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome");
      const threadId = ThreadId.make("thread-acp-prompt-outcome");
      const quota = {
        class: "usage_limit",
        message: "Quota reached.",
        code: "RESOURCE_EXHAUSTED",
        retryable: true,
        resetAt: "2030-01-01T00:00:00.000Z",
      } as const;
      // The runtime ordinal of each prompt, and the session each check watched.
      const promptRuntimes: Array<number> = [];
      const watchedSessions: Array<string> = [];
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          watchPromptOutcome: (sessionId) =>
            Effect.sync(() => {
              watchedSessions.push(sessionId);
              const failed = watchedSessions.length === 1;
              return () => Effect.succeed(failed ? quota : undefined);
            }),
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime, runtimeOrdinal) => ({
              ...runtime,
              prompt: () =>
                Effect.sync(() => {
                  promptRuntimes.push(runtimeOrdinal);
                  return { stopReason: "end_turn" as const };
                }),
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      const runTurn = (ordinal: number) =>
        Effect.gen(function* () {
          yield* runtime.startTurn(
            makeTurnInput({
              threadId,
              providerThread,
              instanceId,
              runtimePolicy,
              now: yield* DateTime.now,
              ordinal,
            }),
          );
          const events = yield* runtime.events.pipe(
            Stream.takeUntil((event) => event.type === "turn.terminal"),
            Stream.runCollect,
          );
          return events.at(-1);
        });

      const failed = yield* runTurn(1);
      if (failed?.type !== "turn.terminal" || failed.status !== "failed") {
        return assert.fail("expected a failed terminal");
      }
      assert.deepEqual(failed.failure, quota);
      const completed = yield* runTurn(2);
      assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed");
      assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime");
      assert.equal(watchedSessions.length, 2);
      assert.equal(watchedSessions[0], watchedSessions[1]);
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );
  it.live("retains returned usage when Stop finalizes before the prompt callback", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-prompt-usage-stop");
      const threadId = ThreadId.make("thread-acp-prompt-usage-stop");
      const wireSettled = yield* Deferred.make<void>();
      const releaseCompletion = yield* Deferred.make<void>();
      const idAllocator = yield* IdAllocator.IdAllocatorV2;
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        testHooks: {
          afterPromptWireSettled: () =>
            Deferred.succeed(wireSettled, undefined).pipe(
              Effect.andThen(Deferred.await(releaseCompletion)),
            ),
        },
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          reportsPerTurnPromptUsage: true,
          preserveRuntimeOnSettledInterrupt: true,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime) => ({
              ...runtime,
              prompt: () =>
                Effect.succeed({
                  stopReason: "end_turn" as const,
                  usage: { inputTokens: 60, outputTokens: 15, totalTokens: 75 },
                }),
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-usage-stop"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      yield* runtime.startTurn(
        makeTurnInput({
          threadId,
          providerThread,
          instanceId,
          runtimePolicy,
          now: yield* DateTime.now,
        }),
      );
      yield* Deferred.await(wireSettled);
      const providerTurnId = idAllocator.derive.providerTurn({
        driver: ACP_TEST_DRIVER,
        nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
      });
      yield* runtime.interruptTurn({ providerThread, providerTurnId });
      const completed = Array.from(
        yield* runtime.events.pipe(
          Stream.takeUntil((event) => event.type === "turn.terminal"),
          Stream.runCollect,
        ),
      ).find(
        (event) =>
          event.type === "provider_turn.updated" && event.providerTurn.status === "interrupted",
      );
      assert.deepEqual(
        completed?.type === "provider_turn.updated" ? completed.providerTurn.turnTokenUsage : null,
        {
          usageScope: "main_agent",
          usageStatus: "partial",
          hasSubagents: false,
          inputTokens: 60,
          outputTokens: 15,
        },
      );
      yield* Deferred.succeed(releaseCompletion, undefined);
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  it.live("drops a late prompt response that lands after the turn finalized", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-prompt-usage-late");
      const threadId = ThreadId.make("thread-acp-prompt-usage-late");
      const dispatched = yield* Deferred.make<void>();
      const gate = yield* Deferred.make<void>();
      const wireSettled = yield* Deferred.make<void>();
      const idAllocator = yield* IdAllocator.IdAllocatorV2;
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        testHooks: {
          afterPromptWireSettled: () =>
            Deferred.succeed(wireSettled, undefined).pipe(Effect.asVoid),
        },
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          reportsPerTurnPromptUsage: true,
          terminateRuntimeProcessGroupOnInterrupt: true,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            ownDetachedProcessGroup: true,
            processGroupTerminationGrace: 0,
            wrapRuntime: (runtime) => ({
              ...runtime,
              // The response only leaves the agent after the turn has been
              // force stopped and finalized: teardown does not interrupt this fiber.
              prompt: () =>
                Deferred.succeed(dispatched, undefined).pipe(
                  Effect.andThen(Deferred.await(gate)),
                  Effect.andThen(
                    Effect.succeed({
                      stopReason: "cancelled" as const,
                      usage: { inputTokens: 60, outputTokens: 15, totalTokens: 75 },
                    }),
                  ),
                ),
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-usage-late"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      let stopCollector = false;
      const events: Array<Record<string, unknown>> = [];
      const usageRecorded = yield* Deferred.make<void>();
      const collector = yield* Stream.runForEach(
        runtime.events.pipe(Stream.takeUntil(() => stopCollector)),
        (event) =>
          Effect.suspend(() => {
            const record = event as Record<string, unknown>;
            events.push(record);
            return record.type === "provider_turn.updated" &&
              (record.providerTurn as Record<string, unknown>).turnTokenUsage !== undefined
              ? Deferred.succeed(usageRecorded, undefined)
              : Effect.void;
          }),
      ).pipe(Effect.forkScoped);
      yield* runtime.startTurn(
        makeTurnInput({
          threadId,
          providerThread,
          instanceId,
          runtimePolicy,
          now: yield* DateTime.now,
          messageText: "Say hi.",
        }),
      );
      yield* Deferred.await(dispatched);
      const providerTurnId = idAllocator.derive.providerTurn({
        driver: ACP_TEST_DRIVER,
        nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
      });
      // Force stop finalizes the turn without waiting for the gated prompt response.
      yield* runtime.interruptTurn({
        providerThread,
        providerTurnId,
        requestRuntimeRestart: true,
      });
      yield* Deferred.await(usageRecorded);
      const usageAt = () => {
        const turns = events.filter(
          (event) =>
            event.type === "provider_turn.updated" &&
            (event.providerTurn as Record<string, unknown>).turnTokenUsage !== undefined,
        );
        const last = turns[turns.length - 1] as
          | { providerTurn: Record<string, unknown> }
          | undefined;
        return last?.providerTurn.turnTokenUsage as Record<string, unknown>;
      };
      assert.deepEqual(usageAt(), {
        usageScope: "main_agent",
        usageStatus: "unavailable",
        hasSubagents: false,
      });
      // The response lands now; the finalized turn must not adopt its counters.
      yield* Deferred.succeed(gate, undefined);
      yield* Deferred.await(wireSettled);
      assert.deepEqual(usageAt(), {
        usageScope: "main_agent",
        usageStatus: "unavailable",
        hasSubagents: false,
      });
      stopCollector = true;
      yield* Fiber.interrupt(collector);
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  it.live("passes per-turn usage samples through", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-per-turn-usage");
      const threadId = ThreadId.make("thread-acp-per-turn-usage");
      let promptOrdinal = 0;
      // Fixture shaped after the live glm-acp-agent probe: three sequential
      // prompts whose inputTokens grow by tens, not by a context per turn.
      // GLM never sends cachedWriteTokens; those values are added here to
      // exercise the clamp path.
      const promptUsages = [
        {
          inputTokens: 2432,
          outputTokens: 3,
          totalTokens: 2435,
          cachedReadTokens: 1024,
          cachedWriteTokens: 64,
          thoughtTokens: 2,
        },
        {
          inputTokens: 2453,
          outputTokens: 4,
          totalTokens: 2457,
          cachedReadTokens: 1045,
          cachedWriteTokens: 85,
          thoughtTokens: 3,
        },
        {
          inputTokens: 2475,
          outputTokens: 25,
          totalTokens: 2500,
          cachedReadTokens: 1067,
          cachedWriteTokens: 107,
          thoughtTokens: 20,
        },
      ];
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          reportsPerTurnPromptUsage: true,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime) => ({
              ...runtime,
              prompt: () => {
                const usage = promptUsages[promptOrdinal++];
                if (usage === undefined) return Effect.die("Unexpected prompt");
                return Effect.succeed({ stopReason: "end_turn" as const, usage });
              },
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-per-turn-usage"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      const now = yield* DateTime.now;
      for (const [index, sample] of promptUsages.entries()) {
        yield* runtime.startTurn(
          makeTurnInput({
            threadId,
            providerThread,
            instanceId,
            runtimePolicy,
            now,
            ordinal: index + 1,
          }),
        );
        const events = Array.from(
          yield* runtime.events.pipe(
            Stream.takeUntil((event) => event.type === "turn.terminal"),
            Stream.runCollect,
          ),
        );
        const completed = events.find(
          (event) =>
            event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
        );
        // Per-turn: each response's own sample maps straight onto its turn.
        assert.deepEqual(
          completed?.type === "provider_turn.updated"
            ? completed.providerTurn.turnTokenUsage
            : null,
          {
            usageScope: "main_agent",
            usageStatus: "complete",
            hasSubagents: false,
            inputTokens: sample.inputTokens,
            outputTokens: sample.outputTokens,
            cachedInputTokens: sample.cachedReadTokens,
            cacheCreationTokens: sample.cachedWriteTokens,
            reasoningTokens: sample.thoughtTokens,
          },
        );
      }
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  it.live("clamps per-turn subsets that exceed their parent counters", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-per-turn-clamp");
      const threadId = ThreadId.make("thread-acp-per-turn-clamp");
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          reportsPerTurnPromptUsage: true,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime) => ({
              ...runtime,
              prompt: () =>
                Effect.succeed({
                  stopReason: "end_turn" as const,
                  usage: {
                    inputTokens: 100,
                    outputTokens: 10,
                    totalTokens: 110,
                    cachedReadTokens: 150,
                    cachedWriteTokens: 120,
                    thoughtTokens: 30,
                  },
                }),
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-per-turn-clamp"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      yield* runtime.startTurn(
        makeTurnInput({
          threadId,
          providerThread,
          instanceId,
          runtimePolicy,
          now: yield* DateTime.now,
        }),
      );
      const events = Array.from(
        yield* runtime.events.pipe(
          Stream.takeUntil((event) => event.type === "turn.terminal"),
          Stream.runCollect,
        ),
      );
      const completed = events.find(
        (event) =>
          event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
      );
      // TurnTokenUsage contract: input includes cache read + write and
      // reasoning is a subset of output. Reads clamp to input, writes clamp
      // to what reads leave of it (100 - 100 = 0 here).
      assert.deepEqual(
        completed?.type === "provider_turn.updated" ? completed.providerTurn.turnTokenUsage : null,
        {
          usageScope: "main_agent",
          usageStatus: "complete",
          hasSubagents: false,
          inputTokens: 100,
          outputTokens: 10,
          cachedInputTokens: 100,
          cacheCreationTokens: 0,
          reasoningTokens: 10,
        },
      );
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  it.live("reports per-turn usage unavailable when the agent omits usage", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-per-turn-missing");
      const threadId = ThreadId.make("thread-acp-per-turn-missing");
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          reportsPerTurnPromptUsage: true,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime) => ({
              ...runtime,
              prompt: () => Effect.succeed({ stopReason: "end_turn" as const }),
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-per-turn-missing"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      yield* runtime.startTurn(
        makeTurnInput({
          threadId,
          providerThread,
          instanceId,
          runtimePolicy,
          now: yield* DateTime.now,
        }),
      );
      const events = Array.from(
        yield* runtime.events.pipe(
          Stream.takeUntil((event) => event.type === "turn.terminal"),
          Stream.runCollect,
        ),
      );
      const completed = events.find(
        (event) =>
          event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
      );
      assert.deepEqual(
        completed?.type === "provider_turn.updated" ? completed.providerTurn.turnTokenUsage : null,
        { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents: false },
      );
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  it.live("keeps usage unavailable for undeclared agents even when they report usage", () =>
    Effect.gen(function* () {
      const path = yield* Path.Path;
      const instanceId = ProviderInstanceId.make("acp-test-usage-undeclared");
      const threadId = ThreadId.make("thread-acp-usage-undeclared");
      const adapter = yield* makeAcpAdapterV2({
        instanceId,
        selfInvocation: yield* resolveSelfInvocation(),
        flavor: {
          driver: ACP_TEST_DRIVER,
          capabilities: AcpProviderCapabilitiesV2,
          makeRuntime: makeMockRuntime({
            childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
            mockAgentPath: yield* path.fromFileUrl(
              new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
            ),
            wrapRuntime: (runtime) => ({
              ...runtime,
              prompt: () =>
                Effect.succeed({
                  stopReason: "end_turn" as const,
                  usage: { inputTokens: 60, outputTokens: 15, totalTokens: 75 },
                }),
            }),
          }),
        },
      });
      const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
        runtimeMode: "full-access",
        interactionMode: "default",
        cwd: process.cwd(),
      });
      const modelSelection = { instanceId, model: "default" } as const;
      const runtime = yield* adapter.openSession({
        threadId,
        providerSessionId: ProviderSessionId.make("provider-session-acp-usage-undeclared"),
        modelSelection,
        runtimePolicy,
      });
      const providerThread = yield* runtime.ensureThread({
        threadId,
        modelSelection,
        runtimePolicy,
      });
      const now = yield* DateTime.now;
      for (const ordinal of [1, 2]) {
        yield* runtime.startTurn(
          makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),
        );
        const events = Array.from(
          yield* runtime.events.pipe(
            Stream.takeUntil((event) => event.type === "turn.terminal"),
            Stream.runCollect,
          ),
        );
        const completed = events.find(
          (event) =>
            event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
        );
        // Usage semantics are unverified for an undeclared agent, so its
        // counters are never trusted, on any turn.
        assert.deepEqual(
          completed?.type === "provider_turn.updated"
            ? completed.providerTurn.turnTokenUsage
            : null,
          { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents: false },
        );
      }
    }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  it.live.each(["details", "none"] as const)(
    "fails the turn on an ACP v2 idle error with %s, settles its open tool, and accepts the next prompt",
    (details) =>
      Effect.gen(function* () {
        const path = yield* Path.Path;
        const instanceId = ProviderInstanceId.make(`idle-error-${details}`);
        const threadId = ThreadId.make(`thread-idle-error-${details}`);
        const childSessionId = "mock-child-session-idle-error";
        const adapter = yield* makeAcpAdapterV2({
          instanceId,
          selfInvocation: yield* resolveSelfInvocation(),
          flavor: {
            driver: ACP_TEST_DRIVER,
            capabilities: AcpProviderCapabilitiesV2,
            extractBackgroundTaskId: (toolCall) =>
              toolCall.toolCallId === "tool-call-idle-error-monitor"
                ? "idle-error-monitor"
                : undefined,
            extractSubagentUpdate: (toolCall) =>
              toolCall.toolCallId === "tool-call-idle-error-subagent"
                ? {
                    nativeTaskId: "task-idle-error",
                    prompt: "child work",
                    title: "child work",
                    model: null,
                    status: toolCall.status === "completed" ? "completed" : "running",
                    childSessionId,
                    result: null,
                    suppressNormalTool: true,
                  }
                : undefined,
            makeRuntime: makeMockRuntime({
              childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
              mockAgentPath: yield* path.fromFileUrl(
                new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
              ),
              environment: { T3_ACP_IDLE_ERROR: details },
            }),
          },
        });
        const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
          runtimeMode: "full-access",
          interactionMode: "default",
          cwd: process.cwd(),
        });
        const modelSelection = { instanceId, model: "default" } as const;
        const runtime = yield* adapter.openSession({
          threadId,
          providerSessionId: ProviderSessionId.make(`session-idle-error-${details}`),
          modelSelection,
          runtimePolicy,
        });
        const providerThread = yield* runtime.ensureThread({
          threadId,
          modelSelection,
          runtimePolicy,
        });
        const runTurn = (ordinal: number) =>
          Effect.gen(function* () {
            yield* runtime.startTurn(
              makeTurnInput({
                threadId,
                providerThread,
                instanceId,
                runtimePolicy,
                now: yield* DateTime.now,
                ordinal,
              }),
            );
            return yield* runtime.events.pipe(
              Stream.takeUntil((event) => event.type === "turn.terminal"),
              Stream.runCollect,
            );
          });

        const failedEvents = yield* runTurn(1);
        const failed = failedEvents.at(-1);
        assert.equal(failed?.type, "turn.terminal");
        if (failed?.type !== "turn.terminal" || failed.status !== "failed") {
          return assert.fail("expected a failed terminal");
        }
        assert.isTrue(
          failed.childTurnsContinue,
          "the run keeps ingesting work that outlives the failed prompt",
        );
        const lateSubagent = yield* runtime.events.pipe(
          Stream.filter(
            (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
          ),
          Stream.runHead,
          Effect.timeoutOption("2 seconds"),
        );
        assert.isTrue(
          Option.isSome(lateSubagent) && Option.isSome(lateSubagent.value),
          "a subagent finishing after the failed prompt still reports to the run",
        );
        assert.deepEqual(
          failed.failure,
          details === "details"
            ? {
                class: "provider_error",
                message: "Missing Authentication header",
                code: "-32000",
                retryable: null,
              }
            : {
                class: "provider_error",
                message: "Provider turn failed.",
                code: null,
                retryable: null,
              },
        );
        const toolItems = (nativeId: string) =>
          failedEvents.flatMap((event) =>
            event.type === "turn_item.updated" &&
            event.turnItem.nativeItemRef?.nativeId === nativeId
              ? [event.turnItem]
              : [],
          );
        const toolStatuses = toolItems("tool-call-idle-error-1").map((item) => item.status);
        assert.include(toolStatuses, "running");
        assert.equal(toolStatuses.at(-1), "failed");
        assert.deepEqual(
          toolItems("tool-call-idle-error-monitor").map((item) => item.status),
          ["running"],
          "a background monitor outlives the failed turn and keeps its running row",
        );
        const childItems = toolItems("task-idle-error:tool:tool-call-idle-error-child");
        assert.deepEqual(
          childItems.map((item) => item.status),
          ["running"],
          "a child-session tool keeps running in its own thread",
        );
        assert.isTrue(childItems.every((item) => item.threadId !== threadId));
        assert.isEmpty(
          toolItems("tool-call-idle-error-child"),
          "the failed turn must not reproject the child tool as a root tool",
        );

        const nextEvents = yield* runTurn(2);
        const next = nextEvents.at(-1);
        assert.equal(next?.type === "turn.terminal" ? next.status : undefined, "completed");
      }).pipe(Effect.provide(layerTest), Effect.scoped),
  );

  // Factory Droid 0.243.0 sends an optional text companion for every AskUser choice.
  const droidChoice = {
    type: "string",
    title: "Format",
    description: "Which reply format?",
    oneOf: [
      { const: "option_0", title: "JSON" },
      { const: "option_1", title: "Plain text" },
      { const: "other", title: "Other answer" },
    ],
  };
  const droidSchema = {
    type: "object",
    properties: {
      question_1: droidChoice,
      question_1_other: { type: "string" },
      question_2: { ...droidChoice, title: "Alternative" },
      question_2_other: { type: "string" },
    },
    required: ["question_1", "question_2"],
  };
  const droidQuestions = ["question_1", "question_2"].map((id, index) => ({
    id,
    header: index === 0 ? "Format" : "Alternative",
    question: "Which reply format?",
    options: [
      { label: "JSON", description: "JSON", value: "option_0" },
      { label: "Plain text", description: "Plain text", value: "option_1" },
    ],
  }));

  // regression: #20417 Droid AskUser answers were sent as a cancel
  it.live.each([
    {
      scenario: "preserves selected IDs and encodes custom answers",
      schema: droidSchema,
      questions: droidQuestions,
      answers: { question_1: "option_1", question_2: "Markdown" },
      result: {
        action: "accept",
        content: { question_1: "option_1", question_2: "other", question_2_other: "Markdown" },
      },
    },
    {
      scenario: "preserves selected labels and attachment paths in custom answers",
      schema: droidSchema,
      questions: droidQuestions,
      withAttachments: true,
      answers: {
        question_1: "option_1",
        question_2: "option_1\n\nAttached notes: keep this custom text",
      },
      result: (directory: string) => ({
        action: "accept",
        content: {
          question_1: "other",
          question_1_other: `Plain text\n\nAttached image "shot.png": ${JSON.stringify(NodePath.join(directory, "droid-shot.png"))}\nAttached file "spec.txt": ${JSON.stringify(NodePath.join(directory, "droid-spec.txt"))}`,
          question_2: "other",
          question_2_other: "option_1\n\nAttached notes: keep this custom text",
        },
      }),
    },
    {
      scenario: "cancels without accepting answers",
      schema: droidSchema,
      questions: droidQuestions,
      answers: undefined,
      result: { action: "cancel" },
    },
    {
      scenario: "falls back for an unrelated form",
      schema: { type: "object", properties: { name: { type: "string" } } },
      questions: [{ id: "name", header: "Question 1", question: "Your answer?", options: [] }],
      answers: { name: "Ada" },
      result: { action: "accept", content: { name: "Ada" } },
    },
  ])("Droid elicitation $scenario", ({ schema, questions, answers, result, withAttachments }) =>
    Effect.gen(function* () {
      const fileSystem = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-droid-form-" });
      const statusPath = path.join(directory, "status.json");
      const expectedResult = typeof result === "function" ? result(directory) : result;
      let preparedAnswers: ProviderUserInputAnswers | undefined = answers;
      if (withAttachments && answers !== undefined) {