Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

48.3 KB
Raw Blame
import { describe, expect, it, vi } from "vitest";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Type } from "typebox";
import type { AgentEventEnvelope, SubagentDefinition } from "@pi-desktop/shared";
import {
  createAssistantMessageEventStream, createFauxCore, fauxAssistantMessage, type Message, type TextContent,
} from "@earendil-works/pi-ai";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
  composeSubagentSystemPrompt,
  MAX_SUBAGENT_REPORT_CHARS,
  SubagentRun,
  type SubagentRunOptions,
  type SubagentRunStatus,
} from "./subagent.js";
import type { RuntimeProviderConfig } from "./provider-binding.js";
import { classifyAgentError } from "./agent-errors.js";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
import {
  PROVIDER_RATE_LIMIT_MAX_RETRIES,
  PROVIDER_TRANSIENT_MAX_RETRIES,
} from "./provider-retry.js";

/** Terminal statuses a run can report (ADR 0253 removed `truncated`). */
const RUN_STATUSES: SubagentRunStatus[] = [
  "completed",
  "aborted",
  "failed",
  "timed_out",
];

describe("delegate execution policy", () => {
  it("keeps the upstream pi attribution disabled for delegated model requests", () => {
    const { run } = createRun();
    expect(run.agent.identity).toEqual(DESKTOP_AGENT_IDENTITY);
  });

  it.each(["Read", "Write", "Edit"])("preserves sequential policy for a same-name dynamic %s", (name) => {
    const { run } = createRun({ tools: [{
      name, label: "extension", description: "dynamic", parameters: Type.Object({}),
      executionMode: "sequential", execute: async () => ({ content: [], details: {} }),
    }] });
    expect(run.agent.state.tools[0].executionMode).toBe("sequential");
  });
  it("runs file tools in parallel batches but fails closed for Bash and unknown tools", () => {
    const { run } = createRun({ tools: ["Read", "Glob", "Grep", "Write", "Edit", "Bash", "plugin_unknown"].map((name) => ({
      name, label: name, description: name, parameters: Type.Object({}),
      executionMode: "parallel", execute: async () => ({ content: [], details: {} }),
    })) });
    expect(run.agent.toolExecution).toBe("parallel");
    expect(run.agent.state.tools.map((tool: any) => [tool.name, tool.executionMode])).toEqual([
      ["Read", "parallel"], ["Glob", "parallel"], ["Grep", "parallel"],
      ["Write", "parallel"], ["Edit", "parallel"], ["Bash", "sequential"], ["plugin_unknown", "sequential"],
    ]);
    run.setSystemPrompt("child-only path rules");
    expect(run.agent.state.systemPrompt).toBe("child-only path rules");
  });
  it("inherits the parent's mixed Task/read batch policy", () => {
    const { run } = createRun({
      tools: ["Read", "Glob", "Grep", "Task"].map((name) => ({
        name, label: name, description: name, parameters: Type.Object({}),
        executionMode: "parallel",
        execute: async () => ({ content: [], details: {} }),
      })),
    });
    const taskTool = run.agent.state.tools.find((tool: any) => tool.name === "Task");
    const toolCall = (id: string, name: string) => ({
      type: "toolCall", id, name, arguments: {},
    });
    // A delegate runs the same batch policy, so a nested Task mixed with a
    // file read stays sequential there too.
    run.agent.state.messages = [
      ...run.agent.state.messages,
      assistantMessage({ content: [toolCall("a", "Task"), toolCall("b", "Read")] }),
    ];
    expect(taskTool.executionMode).toBe("sequential");
    run.agent.state.messages = [
      ...run.agent.state.messages.slice(0, -1),
      assistantMessage({ content: [toolCall("a", "Read"), toolCall("b", "Glob")] }),
    ];
    expect(taskTool.executionMode).toBe("parallel");
    run.agent.state.messages = [
      ...run.agent.state.messages.slice(0, -1),
      assistantMessage({ content: [toolCall("a", "Task"), toolCall("b", "Task")] }),
    ];
    expect(taskTool.executionMode).toBe("parallel");
  });
});

const provider: RuntimeProviderConfig = {
  id: "local",
  name: "Local",
  baseUrl: "http://127.0.0.1:11434/v1",
  modelId: "local-model",
  apiKey: "",
  authKind: "none",
  supportsReasoning: false,
  supportedThinkingLevels: ["off"],
};

function definition(
  overrides: Partial<SubagentDefinition> = {},
): SubagentDefinition {
  return {
    name: "explorer",
    description: "Search the workspace and report findings.",
    tools: ["Read", "Glob", "Grep"],
    prompt: "Find the answer and report it.",
    source: "builtin",
    ...overrides,
  };
}

function createRun(overrides: Partial<SubagentRunOptions> = {}) {
  const events: AgentEventEnvelope[] = [];
  const run = new SubagentRun({
    definition: overrides.definition ?? definition(),
    sessionId: "session-1",
    turnId: "turn-1",
    parentToolCallId: "task-1",
    task: "Find where the permission dialog is rendered.",
    provider,
    thinkingLevel: "off",
    systemPrompt: "system",
    tools: [],
    onEvent: (envelope) => events.push(envelope),
    ...overrides,
  });
  return { run: run as unknown as Record<string, any>, events };
}

/** Minimal pi-ai assistant message shaped like the ones the loop emits. */
function assistantMessage(overrides: {
  content: unknown[];
  stopReason?: string;
  usage?: Record<string, unknown>;
}) {
  return {
    role: "assistant",
    api: "openai-completions",
    provider: "local",
    model: "local-model",
    stopReason: overrides.stopReason ?? "stop",
    timestamp: 1,
    usage: overrides.usage ?? {
      input: 10,
      output: 5,
      cacheRead: 0,
      cacheWrite: 0,
      totalTokens: 15,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
    },
    content: overrides.content,
  };
}

describe("composeSubagentSystemPrompt", () => {
  it("states the read-only boundary and keeps project guidance last", () => {
    const prompt = composeSubagentSystemPrompt({
      definition: definition(),
      guidance: ["Follow the project rules."],
    });

    expect(prompt).toContain('You are the "explorer" subagent');
    expect(prompt).toContain("Read, Glob, Grep");
    expect(prompt).toContain("no tools that change files");
    expect(prompt).toContain("Find the answer and report it.");
    expect(prompt.indexOf("Find the answer and report it.")).toBeLessThan(
      prompt.indexOf("Follow the project rules."),
    );
  });

  it("tells a mutating delegate to stay inside its task", () => {
    const prompt = composeSubagentSystemPrompt({
      definition: definition({ tools: ["Read", "Edit"] }),
    });

    expect(prompt).toContain("You may change files");
    expect(prompt).not.toContain("no tools that change files");
    expect(prompt).toContain("If the final report would exceed ~8,000 characters, write the full report to a file yourself");
  });

  it("does not instruct read-only delegates to write reports to a file", () => {
    const prompt = composeSubagentSystemPrompt({
      definition: definition({ tools: ["Read", "Glob"] }),
    });

    expect(prompt).not.toContain("write the full report to a file yourself");
  });

  it("lists resolved inherit tools and treats them as mutating when they write", () => {
    const prompt = composeSubagentSystemPrompt({
      definition: definition({ tools: [], inheritTools: true }),
      toolNames: ["Read", "Skill", "Edit"],
    });

    expect(prompt).toContain("Read, Skill, Edit");
    expect(prompt).toContain("You may change files");
    expect(prompt).not.toContain("no tools that change files");
    expect(prompt).not.toContain("inherit (parent tools)");
  });
});

describe("SubagentRun event forwarding", () => {
  it("resumes a malformed-call history without executing its old tools", async () => {
    const { run } = createRun({ initialMessages: [assistantMessage({ content: [
      { type: "text", text: "Retained findings." },
      { type: "toolCall", id: "bad-call", name: "", arguments: {} },
    ] })] as AgentMessage[] });
    const requests: Message[][] = [];
    run.agent.streamFunction = (_model: unknown, context: { messages: Message[] }) => {
      requests.push(context.messages);
      const message = assistantMessage({ content: [{ type: "text", text: "Finished the review." }], stopReason: "stop" });
      const stream = createAssistantMessageEventStream();
      queueMicrotask(() => {
        stream.push({ type: "start", partial: message } as never);
        stream.push({ type: "done", reason: "stop", message } as never);
        stream.end(message as never);
      });
      return stream;
    };
    const result = await run.run();
    expect(result.status).toBe("completed");
    expect(requests).toHaveLength(1);
    expect(JSON.stringify(requests)).toContain("Retained findings.");
    expect(JSON.stringify(requests)).not.toContain("bad-call");
  });

  it("keeps the no-pass selection out of the agent's canonical state", () => {
    const { run } = createRun({ thinkingLevel: "omit" });

    expect(run.agent.state.thinkingLevel).toBe("off");
    expect(run.agent.streamFunction.toString()).toContain(
      "models.stream(omitThinkingModel, requestContext, retryOptions)",
    );
  });
  it("retains completed same-id rounds in a resumed subagent request", () => {
    const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
    try {
      const { run } = createRun({
        initialMessages: [
          assistantMessage({
            content: [
              { type: "toolCall", id: "child-read", name: "Read", arguments: {} },
            ],
          }),
          {
            role: "toolResult",
            toolCallId: "child-read",
            toolName: "Read",
            content: [{ type: "text", text: "first" }],
            isError: false,
            timestamp: 2,
          },
          assistantMessage({
            content: [
              { type: "toolCall", id: "child-read", name: "Read", arguments: {} },
            ],
          }),
          {
            role: "toolResult",
            toolCallId: "child-read",
            toolName: "Read",
            content: [{ type: "text", text: "retry" }],
            isError: false,
            timestamp: 3,
          },
        ] as unknown as NonNullable<SubagentRunOptions["initialMessages"]>,
      });
      const outgoing = run.agent.convertToLlm(run.agent.state.messages) as Message[];
      const toolCalls = outgoing.flatMap((message) =>
        message.role === "assistant"
          ? message.content.filter((block) => block.type === "toolCall")
          : [],
      );

      expect(toolCalls.map((call) => call.id)).toEqual(["child-read", "call_pi_repeat_1"]);
      expect(outgoing.filter((message) => message.role === "toolResult")).toHaveLength(2);
      expect(
        outgoing.filter(
          (message) => message.role === "assistant" && message.content.length === 0,
        ),
      ).toHaveLength(0);
      expect(stderr.mock.calls.map(([chunk]) => String(chunk)).join(""))
        .toBe("");
    } finally {
      stderr.mockRestore();
    }
  });

  it("does not synthesize a Responses reasoning setting when omitted", async () => {
    const responseProvider: RuntimeProviderConfig = {
      ...provider,
      id: "responses",
      name: "Responses",
      apiStyle: "responses",
      baseUrl: "https://example.invalid/v1",
      apiKey: "test-key",
      supportsReasoning: true,
      supportedThinkingLevels: ["off", "high"],
      modelConfig: {
        source: "generic",
        name: "Responses model",
        baseUrl: "https://example.invalid/v1",
        reasoning: true,
        thinkingLevelMap: { off: "none", high: "high" },
        input: ["text"],
        contextWindow: 128_000,
        maxTokens: 8_192,
      },
    };
    const { run } = createRun({
      provider: responseProvider,
      thinkingLevel: "omit",
    });
    const requests: Record<string, unknown>[] = [];
    const fetch = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
      requests.push(
        JSON.parse(typeof init?.body === "string" ? init.body : "{}"),
      );
      return new Response("bad request", { status: 400 });
    });

    const stream = run.agent.streamFunction(
      run.agent.state.model,
      { systemPrompt: "system", messages: [], tools: [] },
      { fetch },
    );
    await stream.result();

    expect(requests).toHaveLength(1);
    expect(requests[0].reasoning).toBeUndefined();
  });

  it("tags every forwarded row with the Task call and the agent name", () => {
    const { run, events } = createRun();

    run.handleEvent({
      type: "message_start",
      message: assistantMessage({ content: [{ type: "text", text: "Look" }] }),
    });
    run.handleEvent({
      type: "message_update",
      message: assistantMessage({
        content: [{ type: "text", text: "Looking at" }],
      }),
    });
    run.handleEvent({
      type: "tool_execution_start",
      toolCallId: "child-read",
      toolName: "Read",
      args: { path: "a.ts" },
    });
    run.handleEvent({
      type: "tool_execution_end",
      toolCallId: "child-read",
      result: { content: [{ type: "text", text: "ok" }] },
      isError: false,
    });

    expect(events.map((event) => event.event.type)).toEqual([
      "message_start",
      "message_update",
      "tool_start",
      "tool_end",
    ]);
    for (const event of events) {
      expect(event.parentToolCallId).toBe("task-1");
      expect(event.agentName).toBe("explorer");
      expect(event.turnId).toBe("turn-1");
    }
    const started = events[0].event as { message: Record<string, unknown> };
    expect(started.message.parentToolCallId).toBe("task-1");
    expect(started.message.agentName).toBe("explorer");
    const update = events[1].event as { deltaText: string };
    expect(update.deltaText).toBe("ing at");
  });

  it("keeps turn and agent lifecycle events inside the delegate", () => {
    const { run, events } = createRun();

    run.handleEvent({ type: "turn_start" });
    run.handleEvent({ type: "turn_end" });
    run.handleEvent({ type: "agent_end", messages: [] });

    expect(events).toEqual([]);
    expect(run.turns).toBe(1);
  });

  it("hands each finished turn's assistant message to onTurnEnd", () => {
    const onTurnEnd = vi.fn();
    const { run, events } = createRun({ onTurnEnd });
    const message = assistantMessage({ content: [] });

    run.handleEvent({ type: "turn_end", message, toolResults: [] });

    expect(onTurnEnd).toHaveBeenCalledExactlyOnceWith(message);
    expect(events).toEqual([]);
  });
});

describe("SubagentRun Responses reports", () => {
  const commentary: TextContent = {
    type: "text", text: "I found the dialog.\n",
    textSignature: JSON.stringify({ v: 1, id: "msg_progress", phase: "commentary" }),
  };

  function runWithText(...content: TextContent[]) {
    const { run } = createRun({ provider: { ...provider, apiStyle: "responses" } });
    const faux = createFauxCore({ api: "openai-responses", provider: provider.id });
    faux.setResponses([fauxAssistantMessage(content)]);
    run.agent.streamFunction = faux.streamSimple;
    return (run as unknown as SubagentRun).run();
  }

  it("returns only the final answer in the parent's report", async () => {
    const report = "PermissionDialog.tsx:17 renders the dialog.";
    const result = await runWithText(commentary, {
      type: "text", text: report,
      textSignature: JSON.stringify({ v: 1, id: "msg_report", phase: "final_answer" }),
    });
    expect(result).toMatchObject({ status: "completed", report });
  });

  it("fails without a report when the only text is commentary", async () => {
    const result = await runWithText(commentary);
    expect(result).toMatchObject({ status: "failed", error: { code: "SUBAGENT_NO_REPORT" } });
    expect(result.report).not.toContain(commentary.text.trim());
  });
});

describe("SubagentRun reporting", () => {
  it("keeps the last non-empty assistant text as the report", () => {
    const { run } = createRun();

    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "text", text: "First pass done." }],
      }),
    });
    // A tool-call-only turn has no text and must not clear the report.
    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "toolCall", name: "Read", id: "child-read" }],
      }),
    });

    expect(run.lastReportText).toBe("First pass done.");
    expect(run.usage.totalTokens).toBe(30);
  });

  it("bounds a runaway report", () => {
    const { run } = createRun();
    const report = "x".repeat(MAX_SUBAGENT_REPORT_CHARS * 2);

    const result = run.result("completed", report);

    expect(result.report.length).toBeLessThanOrEqual(MAX_SUBAGENT_REPORT_CHARS);
    expect(result.report).toContain("[subagent report truncated]");
  });

  it("records the effective model and thinking selection", () => {
    const { run } = createRun({
      provider: { ...provider, modelId: "child-model" },
      thinkingLevel: "max",
    });

    expect(run.result("completed", "Done.")).toMatchObject({
      modelId: "child-model",
      thinkingLevel: "max",
    });
  });

  it("explains an aborted or failed run in the parent's text", () => {
    const { run } = createRun();
    run.turns = 3;

    expect(run.result("aborted", "").report).toContain("was aborted after 3 turn");
    expect(
      run.result("failed", "Half of the files checked.", {
        code: "NETWORK_ERROR",
        message: "no route",
      }).report,
    ).toContain("Half of the files checked.");
    expect(
      run.result("failed", "", { code: "NETWORK_ERROR", message: "no route" })
        .report,
    ).toContain("no route");
  });

  it("reports no-report as a failure rather than an empty success", async () => {
    const { run } = createRun();
    run.agent = {
      prompt: vi.fn().mockResolvedValue(undefined),
      waitForIdle: vi.fn().mockResolvedValue(undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("failed");
    expect(result.error?.code).toBe("SUBAGENT_NO_REPORT");
  });

  it("reports truncated output as a failure rather than a clean completion", async () => {
    const { run } = createRun();
    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "text", text: "Analysis report cut off mid-sentence..." }],
        stopReason: "length",
      }),
    });
    run.agent = {
      prompt: vi.fn().mockResolvedValue(undefined),
      waitForIdle: vi.fn().mockResolvedValue(undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("failed");
    expect(result.error?.code).toBe("SUBAGENT_OUTPUT_TRUNCATED");
    expect(result.outputTruncated).toBe(true);
    expect(result.report).toContain("The explorer subagent failed");
    expect(result.report).toContain(
      "The subagent response exceeded the model's output token limit and was truncated",
    );
    expect(result.report).toContain("Analysis report cut off mid-sentence...");
  });

  it("includes resume hint and size stats in truncated output when delegationId is provided", async () => {
    const { run } = createRun({ delegationId: "del-resume-123" });
    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "text", text: "Partial text here..." }],
        stopReason: "length",
      }),
    });
    run.agent = {
      prompt: vi.fn().mockResolvedValue(undefined),
      waitForIdle: vi.fn().mockResolvedValue(undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("failed");
    expect(result.error?.code).toBe("SUBAGENT_OUTPUT_TRUNCATED");
    expect(result.error?.message).toContain('Resume this delegation with Task(resume: "del-resume-123").');
    expect(result.error?.message).toContain("characters produced before truncation");
    expect(result.error?.resumeId).toBe("del-resume-123");
    expect(result.error?.charactersProduced).toBe("Partial text here...".length);
  });

  it("spills oversized reports to session scratch directory (ADR 0062)", async () => {
    const tmp = mkdtempSync(join(tmpdir(), "pi-subagent-scratch-"));
    try {
      const { run } = createRun({
        scratchDir: tmp,
        parentToolCallId: "call-99",
      });
      const largeReport = "A".repeat(MAX_SUBAGENT_REPORT_CHARS + 500);
      run.handleEvent({
        type: "message_end",
        message: assistantMessage({
          content: [{ type: "text", text: largeReport }],
          stopReason: "stop",
        }),
      });
      run.agent = {
        prompt: vi.fn().mockResolvedValue(undefined),
        waitForIdle: vi.fn().mockResolvedValue(undefined),
        abort: vi.fn(),
      };

      const result = await (run as unknown as SubagentRun).run();

      expect(result.status).toBe("completed");
      expect(result.scratchReportPath).toBeDefined();
      expect(result.report).toContain("Complete subagent report");
      expect(result.report).toContain("was saved to:");
      expect(result.report).toContain(result.scratchReportPath!);
      expect(existsSync(result.scratchReportPath!)).toBe(true);
      expect(readFileSync(result.scratchReportPath!, "utf8")).toBe(largeReport);
    } finally {
      rmSync(tmp, { recursive: true, force: true });
    }
  });

  it("keeps an opaque tool-call id inside the scratch directory", async () => {
    const tmp = mkdtempSync(join(tmpdir(), "pi-subagent-scratch-"));
    try {
      const { run } = createRun({
        scratchDir: tmp,
        parentToolCallId: "../../outside",
      });
      run.handleEvent({
        type: "message_end",
        message: assistantMessage({
          content: [{ type: "text", text: "A".repeat(MAX_SUBAGENT_REPORT_CHARS + 1) }],
          stopReason: "stop",
        }),
      });
      run.agent = {
        prompt: vi.fn().mockResolvedValue(undefined),
        waitForIdle: vi.fn().mockResolvedValue(undefined),
        abort: vi.fn(),
      };

      const result = await (run as unknown as SubagentRun).run();

      expect(result.scratchReportPath?.startsWith(join(tmp, "delegations"))).toBe(true);
      expect(readFileSync(result.scratchReportPath!, "utf8")).toHaveLength(
        MAX_SUBAGENT_REPORT_CHARS + 1,
      );
    } finally {
      rmSync(tmp, { recursive: true, force: true });
    }
  });

  it("falls back to bounded clipping when scratch write is unavailable or fails", async () => {
    const { run } = createRun({
      scratchDir: undefined,
      parentToolCallId: "call-no-scratch",
    });
    const largeReport = "A".repeat(MAX_SUBAGENT_REPORT_CHARS + 500);
    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "text", text: largeReport }],
        stopReason: "stop",
      }),
    });
    run.agent = {
      prompt: vi.fn().mockResolvedValue(undefined),
      waitForIdle: vi.fn().mockResolvedValue(undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("completed");
    expect(result.scratchReportPath).toBeUndefined();
    expect(result.report.length).toBeLessThanOrEqual(MAX_SUBAGENT_REPORT_CHARS);
    expect(result.report).toContain("[subagent report truncated]");
  });

  it("clears truncated output state if a subsequent turn finishes cleanly", async () => {
    const { run } = createRun();
    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "text", text: "Initial attempt" }],
        stopReason: "length",
      }),
    });
    run.handleEvent({
      type: "message_end",
      message: assistantMessage({
        content: [{ type: "text", text: "Complete final report." }],
        stopReason: "stop",
      }),
    });
    run.agent = {
      prompt: vi.fn().mockResolvedValue(undefined),
      waitForIdle: vi.fn().mockResolvedValue(undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("completed");
    expect(result.outputTruncated).toBeUndefined();
    expect(result.report).toBe("Complete final report.");
  });

  it("returns aborted without prompting when the parent call is already aborted", async () => {
    const controller = new AbortController();
    controller.abort();
    const { run } = createRun({ signal: controller.signal });
    const prompt = vi.fn();
    run.agent = { prompt, waitForIdle: vi.fn(), abort: vi.fn() };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("aborted");
    expect(prompt).not.toHaveBeenCalled();
  });
});

describe("SubagentRun provider rate-limit recovery", () => {
  it("does not switch models or continue after an explicitly local failure", async () => {
    const { run } = createRun({ fallbackModels: [{
      key: "fallback/model", provider: { ...provider, id: "fallback", modelId: "model" },
    }] });
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage: "local preparation failed",
      errorDetails: {
        code: "LOCAL_REQUEST_ERROR", phase: "request-preparation", message: "failed",
      },
    };
    const continueRun = vi.fn(async () => undefined);
    run.agent = {
      state: { messages: [failure] },
      prompt: vi.fn(async () => {
        run.handleEvent({ type: "message_start", message: failure });
        run.handleEvent({ type: "message_end", message: failure });
      }),
      waitForIdle: vi.fn(async () => undefined), continue: continueRun, abort: vi.fn(),
    };
    // Isolate fallback from the retry check covered below.
    vi.spyOn(run, "claimProviderRetry").mockReturnValue(undefined);
    const result = await run.run();
    expect(continueRun).not.toHaveBeenCalled();
    expect(result).toMatchObject({ status: "failed", error: { code: "INTERNAL" } });
    expect(run.provider.id).toBe("local");
  });

  it("keeps local message metadata terminal even with infinite retries and stale 429 state", () => {
    const { run, events } = createRun({ infiniteProviderRetry: true });
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage: "fetch failed: private prompt api_key=test-secret",
      errorDetails: {
        code: "LOCAL_REQUEST_ERROR", phase: "context-estimation",
        message: "private payload", causeName: "TypeError",
      },
    };
    run.retryState.status = 429;
    const claim = vi.spyOn(run, "claimProviderRetry");
    run.handleEvent({ type: "message_start", message: failure });
    run.handleEvent({ type: "message_end", message: failure });
    expect(claim).not.toHaveBeenCalled();
    expect(run.pendingProviderRetry).toBeUndefined();
    expect(run.providerTransientRetryAttempt).toBe(0);
    expect(run.providerRateLimitRetryAttempt).toBe(0);
    expect(run.streamError).toMatchObject({ code: "INTERNAL" });
    expect(events.at(-1)?.event).toMatchObject({
      type: "message_end",
      message: {
        status: "error", isError: true,
        error: {
          code: "INTERNAL", retriable: false,
          details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
        },
      },
    });
    expect(JSON.stringify(events)).not.toMatch(/private|test-secret|stack/);
  });

  it("reads a local AbortError marker as an abort without retrying or an error row", async () => {
    // pi-ai wraps an AbortError that fired before the parent signal flipped in
    // a local marker; the preserved cause name is the only trace of the Stop,
    // so the run has to report the same abort the session runtime would.
    const controller = new AbortController();
    const { run, events } = createRun({
      signal: controller.signal,
      infiniteProviderRetry: true,
      fallbackModels: [{
        key: "fallback/model",
        provider: { ...provider, id: "fallback", modelId: "model" },
      }],
    });
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage: "local request preparation failed",
      errorDetails: {
        code: "LOCAL_REQUEST_ERROR",
        phase: "request-preparation",
        causeName: "AbortError",
      },
    };
    const continueRun = vi.fn(async () => undefined);
    run.agent = {
      state: { messages: [failure] },
      prompt: vi.fn(async () => {
        run.handleEvent({ type: "message_start", message: failure });
        run.handleEvent({ type: "message_end", message: failure });
      }),
      waitForIdle: vi.fn(async () => undefined),
      continue: continueRun,
      abort: vi.fn(),
    };
    const claim = vi.spyOn(run, "claimProviderRetry");

    const result = await run.run();

    // The synthetic message reports the abort while the parent signal is still
    // open, so nothing but the marker can explain the terminal status.
    expect(controller.signal.aborted).toBe(false);
    expect(result.status).toBe("aborted");
    expect(result.error).toBeUndefined();
    expect(claim).not.toHaveBeenCalled();
    expect(run.pendingProviderRetry).toBeUndefined();
    expect(run.streamError).toBeUndefined();
    expect(continueRun).not.toHaveBeenCalled();
    expect(run.provider.id).toBe("local");
    expect(events.map((event) => event.event.type)).toEqual([
      "message_start",
      "message_end",
    ]);
    const row = (events[1].event as { message: Record<string, unknown> }).message;
    expect(row.status).toBe("aborted");
    expect(row.isError).toBeUndefined();
    expect(row.error).toBeUndefined();
  });


  it("retries ten 429s silently and reuses one assistant row", async () => {
    const { run, events } = createRun();
    const failure = {
      ...assistantMessage({
        content: [{ type: "text", text: "partial" }],
        stopReason: "error",
      }),
      errorMessage: "upstream unavailable",
    };
    run.retryState.status = 429;
    const state = {
      messages: [] as Array<Record<string, unknown>>,
    };
    const continueRun = vi.fn(async () => {
      state.messages = [...state.messages, failure];
      run.handleEvent({ type: "message_start", message: { ...failure, content: [] } });
      run.handleEvent({ type: "message_end", message: failure });
    });
    run.agent = {
      state,
      prompt: vi.fn(async () => {
        state.messages = [{ role: "user", content: "task" }, failure];
        run.handleEvent({ type: "message_start", message: failure });
        run.handleEvent({ type: "message_end", message: failure });
      }),
      waitForIdle: vi.fn(async () => undefined),
      continue: continueRun,
      abort: vi.fn(),
    };

    vi.useFakeTimers();
    try {
      const resultPromise = run.run();
      await vi.runAllTimersAsync();
      const result = await resultPromise;

      expect(continueRun).toHaveBeenCalledTimes(PROVIDER_RATE_LIMIT_MAX_RETRIES);
      expect(result.status).toBe("failed");
      expect(result.error?.code).toBe("PROVIDER_RATE_LIMITED");
      expect(events.filter((event) => event.event.type === "message_start")).toHaveLength(1);
      expect(events.filter((event) => event.event.type === "message_end")).toHaveLength(1);
      expect(events).toContainEqual(
        expect.objectContaining({
          event: expect.objectContaining({
            type: "message_end",
            message: expect.objectContaining({
              status: "error",
              isError: true,
            }),
          }),
        }),
      );
    } finally {
      vi.useRealTimers();
    }
  });
});

describe("SubagentRun turn accounting", () => {
  it("runs past the old turn ceiling and still completes", async () => {
    const { run } = createRun();
    // The removed cap topped out at 80 turns; a delegate that keeps calling
    // tools for longer than that is no longer killed mid-task (ADR 0253).
    const turns = 120;
    run.agent = {
      prompt: vi.fn(async () => {
        for (let turn = 0; turn < turns; turn += 1) {
          run.handleEvent({ type: "turn_start" });
          run.handleEvent({
            type: "tool_execution_start",
            toolCallId: `child-${turn}`,
            toolName: "Read",
            args: { path: "a.ts" },
          });
          run.handleEvent({
            type: "tool_execution_end",
            toolCallId: `child-${turn}`,
            result: { content: [{ type: "text", text: "ok" }] },
            isError: false,
          });
        }
        run.handleEvent({
          type: "message_end",
          message: assistantMessage({
            content: [{ type: "text", text: "Checked every file." }],
          }),
        });
      }),
      waitForIdle: vi.fn(async () => undefined),
      abort: vi.fn(),
    };

    const result = await run.run();

    // A delegate ends by finishing, by aborting or by failing; there is no
    // turn-count termination and `truncated` is not a status any more.
    expect(RUN_STATUSES).toContain(result.status);
    expect(result.status).toBe("completed");
    expect(result.report).toBe("Checked every file.");
    expect(result.turns).toBe(turns);
    expect(result.toolCalls).toBe(turns);
    expect("cappedTurns" in run).toBe(false);
  });

  it("passes a parent tool failure through to the delegate", async () => {
    const { run } = createRun({
      resolveToolOutcome: () => ({ isError: true }),
    });

    await expect(
      run.afterToolCall({ toolCall: { id: "child-1" } }),
    ).resolves.toEqual({ isError: true });
  });
});

describe("SubagentRun watchdogs", () => {
  function holdAgent(
    run: Record<string, any>,
    onPrompt: () => void,
  ): { abort: ReturnType<typeof vi.fn> } {
    let release!: () => void;
    const pending = new Promise<void>((resolve) => {
      release = resolve;
    });
    const abort = vi.fn(() => release());
    run.agent = {
      prompt: vi.fn(async () => {
        onPrompt();
        await pending;
      }),
      waitForIdle: vi.fn(async () => undefined),
      abort,
    };
    return { abort };
  }

  it("does not idle- or duration-timeout a silent or long-running delegate", async () => {
    vi.useFakeTimers();
    try {
      const { run } = createRun({
        definition: definition({
          idleTimeoutSeconds: 10,
          maxDurationSeconds: 20,
        }),
      });
      const { abort } = holdAgent(run, () => {
        run.handleEvent({ type: "turn_start" });
        run.handleEvent({
          type: "tool_execution_start",
          toolCallId: "long-tool",
          toolName: "Bash",
          args: { command: "long-running" },
        });
      });

      const resultPromise = run.run();
      await vi.advanceTimersByTimeAsync(60_000);
      expect(abort).not.toHaveBeenCalled();
      (abort as unknown as () => void)();
      const result = await resultPromise;
      expect(result.status).not.toBe("timed_out");
    } finally {
      vi.useRealTimers();
    }
  });

  it("retries a gateway 502 in either phase from one bounded budget", () => {
    const { run } = createRun();
    const claim = (error: unknown, phase: string) =>
      (run as any).claimProviderRetry(error, phase);
    const gateway502 = classifyAgentError(
      'OpenAI API error (502): {"type":"api_error","message":"Upstream API request failed."}',
    );

    // The stream phase used to be refused outright for a delegate.
    for (let attempt = 1; attempt <= PROVIDER_TRANSIENT_MAX_RETRIES; attempt += 1) {
      expect(claim(gateway502, attempt % 2 === 1 ? "stream" : "request")).toBe(
        attempt,
      );
    }
    expect(claim(gateway502, "stream")).toBeUndefined();

    const { run: fresh } = createRun();
    const freshClaim = (error: unknown, phase: string) =>
      (fresh as any).claimProviderRetry(error, phase);
    // Rate limits keep their own separate ten-retry budget.
    const rateLimited = classifyAgentError("429: too many requests");
    expect(freshClaim(gateway502, "request")).toBe(1);
    for (let attempt = 1; attempt <= PROVIDER_RATE_LIMIT_MAX_RETRIES; attempt += 1) {
      expect(freshClaim(rateLimited, "stream")).toBe(attempt);
    }
    expect(freshClaim(rateLimited, "stream")).toBeUndefined();
    // Permanent failures stay terminal.
    expect(freshClaim(classifyAgentError("401: invalid api key"), "request")).toBeUndefined();

    const { run: infinite } = createRun({ infiniteProviderRetry: true });
    const infiniteClaim = (error: unknown, phase: string) =>
      (infinite as any).claimProviderRetry(error, phase);
    for (let attempt = 1; attempt <= PROVIDER_TRANSIENT_MAX_RETRIES + 2; attempt += 1) {
      expect(infiniteClaim(gateway502, "stream")).toBe(attempt);
    }
  });

  it("never terminates the delegate on a turn count", async () => {
    const { run } = createRun();
    // 80 was the highest value the removed clamp ever allowed.
    run.turns = 80;

    await expect(
      run.afterToolCall({ toolCall: { id: "child-1" } }),
    ).resolves.toBeUndefined();
    // No `cappedTurns` flag exists to record a termination that cannot happen.
    expect("cappedTurns" in run).toBe(false);
  });
});

describe("SubagentRun context budget (ADR 0299)", () => {
  it("wires the delegate's turn boundary through prepareNextTurnWithContext", () => {
    const { run } = createRun();

    expect(typeof run.agent.prepareNextTurnWithContext).toBe("function");
  });

  it("preflights the first request with system and tool-schema overhead", async () => {
    const smallProvider: RuntimeProviderConfig = {
      ...provider,
      id: "small",
      modelId: "small-model",
      modelConfig: {
        source: "generic",
        name: "Small model",
        baseUrl: provider.baseUrl ?? "",
        reasoning: false,
        input: ["text"],
        contextWindow: 4_096,
        maxTokens: 1_024,
      },
    };
    const tools = [{
      name: "Read",
      label: "Read",
      description: "t".repeat(2_200),
      parameters: Type.Object({}),
      execute: async () => ({
        content: [{ type: "text" as const, text: "unused" }],
        details: {},
      }),
    }];
    const { run } = createRun({
      provider: smallProvider,
      systemPrompt: "s".repeat(6_200),
      tools,
    });
    const prompt = vi.spyOn(run.agent, "prompt").mockResolvedValue(undefined);
    vi.spyOn(run.agent, "waitForIdle").mockResolvedValue(undefined);

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("failed");
    expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");
    expect(prompt).not.toHaveBeenCalled();
  });

  it("remaps a provider context overflow no fallback could absorb", async () => {
    const { run } = createRun();
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage: "prompt is too long: 300000 tokens",
    };
    const state = { messages: [] as Array<Record<string, unknown>> };
    run.agent = {
      state,
      prompt: vi.fn(async () => {
        state.messages = [{ role: "user", content: "task" }, failure];
        run.handleEvent({ type: "message_start", message: failure });
        run.handleEvent({ type: "message_end", message: failure });
      }),
      waitForIdle: vi.fn(async () => undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("failed");
    expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");
    expect(result.error?.message).toContain("larger context window");
    expect(result.error?.message).not.toContain("prompt is too long");
    expect(result.report).toContain("Narrow the task");
  });

  it.each([
    ["DashScope/Qwen", '400: {"code":"invalid_parameter_error","message":"Range of input length should be [1, 98304]"}'],
    ["Bedrock", "Validation error: Input is too long for requested model."],
  ])("remaps a %s overflow without retrying the same request", async (_provider, errorMessage) => {
    const { run } = createRun();
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage,
    };
    const state = { messages: [] as Array<Record<string, unknown>> };
    const prompt = vi.fn(async () => {
      state.messages = [{ role: "user", content: "task" }, failure];
      run.handleEvent({ type: "message_start", message: failure });
      run.handleEvent({ type: "message_end", message: failure });
      // An overflow re-sent unchanged fails identically; it must not claim
      // the transient budget the way a gateway 502 does.
      expect(run.pendingProviderRetry).toBeUndefined();
    });
    const continueRun = vi.fn(async () => undefined);
    run.agent = {
      state,
      prompt,
      continue: continueRun,
      waitForIdle: vi.fn(async () => undefined),
      abort: vi.fn(),
    };

    const result = await (run as unknown as SubagentRun).run();

    expect(result.status).toBe("failed");
    expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");
    expect(result.report).toContain("Narrow the task");
    expect(prompt).toHaveBeenCalledTimes(1);
    expect(continueRun).not.toHaveBeenCalled();
  });

  it("keeps the boundary guard's overflow code instead of classifying its thrown text", () => {
    const { run } = createRun();
    run.pendingContextOverflow = {
      code: "SUBAGENT_CONTEXT_OVERFLOW",
      message: "degraded context still does not fit",
    };

    run.handleEvent({
      type: "message_end",
      message: {
        ...assistantMessage({ content: [], stopReason: "error" }),
        errorMessage: "degraded context still does not fit",
      },
    });

    expect(run.streamError).toEqual({
      code: "SUBAGENT_CONTEXT_OVERFLOW",
      message: "degraded context still does not fit",
    });
    expect(run.pendingContextOverflow).toBeUndefined();
  });

  it("skips a fallback whose window cannot hold the carried context", () => {
    const small: RuntimeProviderConfig = {
      ...provider,
      id: "small",
      modelId: "small-model",
      modelConfig: {
        source: "generic",
        name: "small-model",
        baseUrl: provider.baseUrl ?? "",
        reasoning: false,
        input: ["text"],
        contextWindow: 4_096,
        maxTokens: 1_024,
      },
    };
    const { run } = createRun({
      fallbackModels: [{ key: "small/small-model", provider: small }],
    });
    const brief = { role: "user", content: "y".repeat(12_000), timestamp: 1 };
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage: "prompt is too long",
    };
    run.agent.state.messages = [brief, failure];
    run.streamError = { code: "CONTEXT_TOO_LARGE", message: "prompt is too long" };

    const switched = run.useNextModel();

    expect(switched).toBe(false);
    expect(run.agent.state.model.id).toBe("local-model");
    expect(run.modelFailures).toEqual([
      expect.objectContaining({
        model: "local/local-model",
        code: "CONTEXT_TOO_LARGE",
      }),
      expect.objectContaining({
        model: "small/small-model",
        code: "SUBAGENT_CONTEXT_OVERFLOW",
      }),
    ]);
  });

  it("carries the uncompacted context onto a fallback whose window fits", () => {
    const big: RuntimeProviderConfig = {
      ...provider,
      id: "big",
      modelId: "big-model",
    };
    const { run, events } = createRun({
      fallbackModels: [{ key: "big/big-model", provider: big }],
    });
    const brief = { role: "user", content: "y".repeat(12_000), timestamp: 1 };
    const failure = {
      ...assistantMessage({ content: [], stopReason: "error" }),
      errorMessage: "prompt is too long",
    };
    run.agent.state.messages = [brief, failure];
    run.streamError = { code: "CONTEXT_TOO_LARGE", message: "prompt is too long" };

    const switched = run.useNextModel();

    expect(switched).toBe(true);
    expect(run.agent.state.model.id).toBe("big-model");
    // Only the failed assistant row is dropped; nothing is compacted away.
    expect(run.agent.state.messages).toEqual([brief]);
    expect(run.streamError).toBeUndefined();
    expect(events.some((event) => event.event.type === "message_end")).toBe(true);
  });

  it("reports compactions and degradation on the run result", () => {
    const { run } = createRun();
    run.contextCompactions = 2;
    run.contextDegraded = true;

    const result = run.result("completed", "Done.");

    expect(result.contextCompactions).toBe(2);
    expect(result.contextDegraded).toBe(true);
    expect(result.report).toContain("older working history was discarded");

    const clean = createRun();
    const cleanResult = clean.run.result("completed", "Done.");
    expect(cleanResult.contextCompactions).toBeUndefined();
    expect(cleanResult.contextDegraded).toBeUndefined();
    expect(cleanResult.report).toBe("Done.");
  });
});

describe("SubagentRun retries before fallback", () => {
  it("removes every trailing failed assistant before retrying", async () => {
    const { run } = createRun();
    const user = { role: "user", content: "task", timestamp: 1 };
    const toolUse = {
      ...assistantMessage({ content: [{ type: "toolCall", id: "call-1", name: "Read", arguments: {} }], stopReason: "toolUse" }),
    };
    const toolResult = {
      role: "toolResult",
      toolCallId: "call-1",
      content: [{ type: "text", text: "result" }],
      isError: false,
      timestamp: 2,
    };
    const failed = {
      ...assistantMessage({ content: [{ type: "text", text: "partial" }], stopReason: "error" }),
      errorMessage: "stream terminated",
    };
    const continued = vi.fn(async () => {
      if (run.agent.state.messages.at(-1)?.role === "assistant") {
        throw new Error("Cannot continue from message role: assistant");
      }
    });
    run.agent = {
      state: { ...run.agent.state, messages: [user, toolUse, toolResult, failed, failed] },
      continue: continued,
      waitForIdle: async () => {},
    };
    run.pendingProviderRetry = {
      code: "PROVIDER_ERROR",
      message: "stream terminated",
      retriable: true,
    };
    run.providerTransientRetryAttempt = 1;

    vi.useFakeTimers();
    try {
      const retry = run.retryPendingProviderFailure();
      await vi.runAllTimersAsync();
      await retry;
    } finally {
      vi.useRealTimers();
    }

    expect(run.agent.state.messages).toEqual([user, toolUse, toolResult]);
    expect(continued).toHaveBeenCalledOnce();
  });

  it("retries from a compacted transcript when the failed assistant is gone (issue #1768)", async () => {
    const { run } = createRun();
    const user = { role: "user", content: "task", timestamp: 1 };
    const compactedTail = {
      role: "compactionSummary",
      content: "Earlier work was summarized.",
      timestamp: 2,
    };
    const continued = vi.fn(async () => undefined);
    run.agent = {
      state: { ...run.agent.state, messages: [user, compactedTail] as any },
      continue: continued,
      waitForIdle: async () => {},
    };
    run.pendingProviderRetry = {
      code: "STREAM_FAILED",
      message: "stream terminated",
      retriable: true,
    };
    run.providerTransientRetryAttempt = 1;

    vi.useFakeTimers();
    try {
      const retry = run.retryPendingProviderFailure();
      await vi.runAllTimersAsync();
      await retry;
    } finally {
      vi.useRealTimers();
    }

    expect(run.agent.state.messages).toEqual([user, compactedTail]);
    expect(continued).toHaveBeenCalledOnce();
  });

  it.each([429, 503])("exhausts the shared retry budget before switching after HTTP %s", async (status) => {
    const fallback = { ...provider, id: "backup", modelId: "backup-model" };
    const { run } = createRun({ fallbackModels: [{ key: "backup/backup-model", provider: fallback }] });
    const state = run.agent.state;
    const attempts: string[] = [];
    const attempt = async () => {
      const primary = state.model.id === provider.modelId;
      attempts.push(state.model.id);
      run.retryState.status = primary ? status : 200;
      const message = {
        ...assistantMessage({ content: [{ type: "text", text: primary ? "partial" : "Done" }], stopReason: primary ? "error" : "stop" }),
        ...(primary ? { errorMessage: `${status}: upstream unavailable` } : {}),
      };
      state.messages = [...state.messages, message];
      run.handleEvent({ type: "message_start", message });
      run.handleEvent({ type: "message_end", message });
    };
    run.agent = {
      state,
      prompt: async () => {
        const user: Message = { role: "user", content: "task", timestamp: 1 };
        state.messages = [user];
        await attempt();
      },
      continue: attempt,
      waitForIdle: async () => {},
      abort: () => {},
    };
    vi.useFakeTimers();
    try {
      const resultPromise = run.run();
      await vi.runAllTimersAsync();
      const result = await resultPromise;
      expect(result.status).toBe("completed");
      expect(attempts).toEqual([...Array(PROVIDER_TRANSIENT_MAX_RETRIES + 1).fill(provider.modelId), "backup-model"]);
      expect(result.modelFailures).toHaveLength(1);
      expect(result.modelId).toBe("backup-model");
    } finally {
      vi.useRealTimers();
    }
  });
});