A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Declare the session tools in /btw side questions and block their use (#2233)
Sebastian Müller48d7fca76b1f
diff --git a/packages/coding-agent/.changes/btw-side-question-tools.md b/packages/coding-agent/.changes/btw-side-question-tools.mdnew file mode 100644index 0000000000..d5c3763844--- /dev/null+++ b/packages/coding-agent/.changes/btw-side-question-tools.md@@ -0,0 +1 @@+- Changed `/btw` side questions to declare the session's tools without allowing their use: the request now matches the main conversation's cached prefix byte for byte (tools included), any tool call gets an error result instead of executing, and the side thread's first turn explains that it is a `/btw` side conversation with tools deactivated.diff --git a/packages/coding-agent/src/core/side-question.ts b/packages/coding-agent/src/core/side-question.tsindex 1ab9ea1b6d..53cac1ac9f 100644--- a/packages/coding-agent/src/core/side-question.ts+++ b/packages/coding-agent/src/core/side-question.ts@@ -29,7 +29,12 @@ export interface SideQuestionRun {}const SIDE_QUESTION_INSTRUCTION =- "Answer this side question using only the conversation context above. Do not use tools. The user may send follow-up side questions; none of this side conversation is added to the main session.";+ "The user asked this via `/btw` — a temporary side thread cloned from the main conversation to answer a question without interrupting the main work. Tools (including `ipython`) are deactivated in this side thread and return an error if called; answer using only the conversation context above. The user may send follow-up side questions. Nothing here is added to the main session, so don't start or plan main-session work from this thread.";++const SIDE_QUESTION_TOOL_BLOCKED = "Tools are deactivated in this side thread. Answer from the conversation context.";++/** Backstop for a model that keeps calling deactivated tools instead of answering. */+const SIDE_QUESTION_MAX_TURNS = 3;function sideQuestionPrompt(question: string, isFirstTurn: boolean): string {const body = isFirstTurn ? `${SIDE_QUESTION_INSTRUCTION}\n\n${question}` : question;@@ -86,6 +91,7 @@ export function startSideQuestion(} satisfies AssistantMessage,]);+ let turnCount = 0;const sideAgent = new Agent({initialState: {model,@@ -93,7 +99,9 @@ export function startSideQuestion(messages: [...structuredClone(parent.state.messages), ...previousTurnMessages],thinkingLevel: getAuxiliaryThinkingLevel(model, parent.state.thinkingLevel),serviceTier: parent.state.serviceTier,- tools: [],+ // Providers serialize tool declarations ahead of the cached prefix, so an+ // empty list would miss the main cache; execution is blocked in beforeToolCall.+ tools: parent.state.tools,},convertToLlm: parent.convertToLlm,transformContext: parent.transformContext,@@ -102,13 +110,24 @@ export function startSideQuestion(getApiKey: parent.getApiKey,onPayload: parent.onPayload,onResponse: parent.onResponse,- shouldStopAfterTurn: () => true,+ beforeToolCall: async () => ({ block: true, reason: SIDE_QUESTION_TOOL_BLOCKED }),+ shouldStopAfterTurn: ({ message }) => {+ turnCount += 1;+ return turnCount >= SIDE_QUESTION_MAX_TURNS || !message.content.some((block) => block.type === "toolCall");+ },sessionId: parent.sessionId,thinkingBudgets: parent.thinkingBudgets,transport: "sse",toolExecution: parent.toolExecution,});+ const clonedMessageCount = sideAgent.state.messages.length;+ // A turn-capped run can end on tool results, so its outcome lives in the+ // assistant turns it appended rather than in its last message.+ const assistantTurns = () =>+ sideAgent.state.messages+ .slice(clonedMessageCount)+ .filter((message): message is AssistantMessage => message.role === "assistant");let answer = "";let abortRequested = false;let started = false;@@ -116,12 +135,14 @@ export function startSideQuestion(const emit = (status: SideQuestionStatus, errorMessage?: string) =>onEvent({ id, question, answer, status, ...(errorMessage ? { errorMessage } : {}) });+ // Streaming events carry one partial turn at a time, so they only fill in text+ // as it arrives; the answer of the whole run is derived from its finished turns.const unsubscribe = sideAgent.subscribe(async (event) => {if (event.type !== "message_update" && event.type !== "message_end") {return;}const nextAnswer = readAssistantText(event.message);- if (nextAnswer === answer) {+ if (!nextAnswer || nextAnswer === answer) {return;}answer = nextAnswer;@@ -139,7 +160,7 @@ export function startSideQuestion(started = true;// Standalone side agents bypass the session auto-retry loop; retry here instead.let promptedOnce = false;- await completeWithProviderRetry(+ const finalTurn = await completeWithProviderRetry(async () => {if (promptedOnce) {// Session-loop recovery: drop the failed assistant turn and re-run.@@ -149,11 +170,11 @@ export function startSideQuestion(promptedOnce = true;await sideAgent.prompt(prompt);}- const last = sideAgent.state.messages.at(-1);- if (last?.role !== "assistant") {+ const last = assistantTurns().at(-1);+ if (!last) {throw new Error(sideAgent.state.errorMessage || "Side question produced no assistant message");}- return last as AssistantMessage;+ return last;},{ policy: retry, signal: retryAbortController.signal },);@@ -165,6 +186,11 @@ export function startSideQuestion(await emit("error", sideAgent.state.errorMessage);return;}+ // A run that ends on a tool turn was answered in an earlier turn; a textless+ // final turn without tool calls is a genuinely empty answer.+ answer = finalTurn.content.some((block) => block.type === "toolCall")+ ? (assistantTurns().map(readAssistantText).filter(Boolean).at(-1) ?? "")+ : readAssistantText(finalTurn);await emit("complete");}).catch(async (error) => {diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.tsindex b1a56f5a10..c0f4d47625 100644--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts@@ -1,6 +1,8 @@-import { fauxAssistantMessage } from "@earendil-works/pi-ai";+import type { AgentTool } from "@earendil-works/pi-agent-core";+import { fauxAssistantMessage, fauxThinking, fauxToolCall } from "@earendil-works/pi-ai";import { Container } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";+import { Type } from "typebox";import { beforeAll, describe, expect, it, vi } from "vitest";import { type SideQuestionEvent, startSideQuestion } from "../../../src/core/side-question.js";import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";@@ -23,7 +25,7 @@ describe("ENG-4509 side questions", () => {initTheme("dark");});- it("uses the current context without tools or session persistence", async () => {+ it("uses the current context without session persistence", async () => {const harness = await createHarness({ systemPrompt: "Remember relevant project context." });try {harness.setResponses([fauxAssistantMessage("The codename is kestrel.")]);@@ -39,7 +41,6 @@ describe("ENG-4509 side questions", () => {harness.setResponses([(context, options) => {expect(context.systemPrompt).toBe(systemPromptBefore);- expect(context.tools).toEqual([]);expect(context.messages.map(getMessageText)).toEqual([expect.stringContaining("The persistent memories produced across this session so far:"),"The project codename is kestrel.",@@ -89,10 +90,9 @@ describe("ENG-4509 side questions", () => {"first side answer",expect.stringContaining("Second side question?"),]);- expect(context.tools).toEqual([]);// The instruction is repeated only on the first side turn.- expect(texts[3]).toContain("Answer this side question");- expect(texts[5]).not.toContain("Answer this side question");+ expect(texts[3]).toContain("asked this via `/btw`");+ expect(texts[5]).not.toContain("asked this via `/btw`");return fauxAssistantMessage("second side answer");},]);@@ -115,6 +115,147 @@ describe("ENG-4509 side questions", () => {}});+ let probeExecutions = 0;+ const probe: AgentTool = {+ name: "probe",+ label: "Probe",+ description: "Records executions",+ parameters: Type.Object({}),+ execute: async () => {+ probeExecutions += 1;+ return { content: [{ type: "text", text: "executed" }], details: {} };+ },+ };++ it("sends the session's tool declarations but blocks their execution", async () => {+ const harness = await createHarness({ tools: [probe] });+ try {+ let mainTools: unknown;+ harness.setResponses([+ (context) => {+ mainTools = context.tools;+ return fauxAssistantMessage("main answer");+ },+ ]);+ await harness.session.prompt("Main context message.");++ let secondTurnTexts: string[] = [];+ harness.setResponses([+ (context) => {+ expect(context.tools).toEqual(mainTools);+ return fauxAssistantMessage(fauxToolCall("probe", {}), { stopReason: "toolUse" });+ },+ (context) => {+ secondTurnTexts = context.messages.map(getMessageText);+ return fauxAssistantMessage("answered from context");+ },+ ]);++ const events: SideQuestionEvent[] = [];+ const run = startSideQuestion(harness.session.agent, "tools-1", "Which tool would you use?", (event) => {+ events.push(event);+ });+ await run.done;++ expect(probeExecutions).toBe(0);+ expect(secondTurnTexts.some((text) => text.includes("Tools are deactivated in this side thread"))).toBe(true);+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "answered from context" });+ } finally {+ harness.cleanup();+ }+ });++ it("answers empty when the terminal turn is textless without tool calls", async () => {+ const harness = await createHarness({ tools: [probe] });+ try {+ harness.setResponses([fauxAssistantMessage("main answer")]);+ await harness.session.prompt("Main context message.");+ harness.setResponses([+ fauxAssistantMessage([{ type: "text", text: "Checking." }, fauxToolCall("probe", {})], {+ stopReason: "toolUse",+ }),+ fauxAssistantMessage("", { stopReason: "stop" }),+ ]);+ const events: SideQuestionEvent[] = [];+ const run = startSideQuestion(harness.session.agent, "tools-3", "Empty finish?", (event) => {+ events.push(event);+ });+ await run.done;+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "" });+ } finally {+ harness.cleanup();+ }+ });++ it("stops after three turns when the model keeps calling tools", async () => {+ const harness = await createHarness({ tools: [probe] });+ try {+ harness.setResponses([fauxAssistantMessage("main answer")]);+ await harness.session.prompt("Main context message.");++ const callsBefore = harness.faux.state.callCount;+ harness.setResponses([+ fauxAssistantMessage([{ type: "text", text: "Checking." }, fauxToolCall("probe", {})], {+ stopReason: "toolUse",+ }),+ // This turn streams thinking before its tool call, so its mid-turn updates+ // are textless while the first turn's answer is the run's only text.+ fauxAssistantMessage([fauxThinking("still stuck"), fauxToolCall("probe", {})], {+ stopReason: "toolUse",+ }),+ fauxAssistantMessage(fauxToolCall("probe", {}), { stopReason: "toolUse" }),+ ]);++ const events: SideQuestionEvent[] = [];+ const run = startSideQuestion(harness.session.agent, "tools-2", "Keep trying?", (event) => {+ events.push(event);+ });+ await run.done;++ expect(harness.faux.state.callCount - callsBefore).toBe(3);+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "Checking." });+ // Streamed text must never be wiped mid-run by textless updates.+ const running = events.filter((event) => event.status === "running");+ const firstText = running.findIndex((event) => event.answer !== "");+ expect(firstText).toBeGreaterThanOrEqual(0);+ expect(running.slice(firstText).every((event) => event.answer !== "")).toBe(true);+ } finally {+ harness.cleanup();+ }+ });++ it("derives the answer from finished turns when a retried run ends on tool calls", async () => {+ const harness = await createHarness({ tools: [probe] });+ try {+ harness.setResponses([fauxAssistantMessage("main answer")]);+ await harness.session.prompt("Main context message.");+ harness.setResponses([+ fauxAssistantMessage([{ type: "text", text: "Checking." }, fauxToolCall("probe", {})], {+ stopReason: "toolUse",+ }),+ fauxAssistantMessage("Almost 42", { stopReason: "error", errorMessage: "500 Internal Server Error" }),+ fauxAssistantMessage(fauxToolCall("probe", {}), { stopReason: "toolUse" }),+ fauxAssistantMessage(fauxToolCall("probe", {}), { stopReason: "toolUse" }),+ ]);+ const events: SideQuestionEvent[] = [];+ const run = startSideQuestion(+ harness.session.agent,+ "retry-2",+ "Survives a failed turn?",+ (event) => {+ events.push(event);+ },+ [],+ { enabled: true, maxRetries: 3, baseDelayMs: 1, maxRetryDelayMs: 60_000 },+ );+ await run.done;+ // The failed turn's streamed partial is not the outcome; finished turns are.+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "Checking." });+ } finally {+ harness.cleanup();+ }+ });+it("retries a transient provider error once and completes", async () => {const harness = await createHarness();try {@@ -159,7 +300,6 @@ describe("ENG-4509 side questions", () => {return fauxAssistantMessage("main complete");},(context) => {- expect(context.tools).toEqual([]);expect(context.messages.map(getMessageText)).toEqual([expect.stringContaining("The persistent memories produced across this session so far:"),"Run the main task.",