Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b69714a750 |
@@ -121,7 +121,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
|
||||
|
||||
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request.
|
||||
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request. Every prompt ends with `RoadblockNote`: a run that is blocked (a tool failing again and again, a computer or page down, access it does not have) stops after two or three attempts and reports what failed and what the user must do, never works around it another way or describes the work as done. The app enforces the tool-loop half itself: `AppData.HarnessStuckToolRepeats` consecutive calls of one tool with the same answer end the run at a wrap up (`stuckToolNote`, `run-text-loop.ts`).
|
||||
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.0",
|
||||
"version": "0.28.1",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -672,6 +672,18 @@ export const AppData = {
|
||||
* row, each repeat resending the whole transcript.
|
||||
*/
|
||||
HarnessSameFailureRetries: 1,
|
||||
/**
|
||||
* How many calls of one tool in a row end a run: at this count the run
|
||||
* stops working and gets its wrap up, where it reports what it has and
|
||||
* what is blocking it (`stuckToolNote`). A reply with no step or token
|
||||
* limit otherwise loops until someone stops it: one spent 194 calls of
|
||||
* `search_computers` and 18M prompt tokens probing a browser that its
|
||||
* account can never reach (Nov 2026). Counted by tool name and its
|
||||
* answer, since the loop's calls each had different arguments, and a run
|
||||
* that clicks through a long list one item at a time gets a different
|
||||
* answer each time and is not stuck.
|
||||
*/
|
||||
HarnessStuckToolRepeats: 20,
|
||||
/**
|
||||
* How many times the review may send an answer back to be written again
|
||||
* before the run stops without an answer. A note fixes most answers; the
|
||||
|
||||
@@ -51,6 +51,19 @@ export const SupersededSnapshotNote = `[An older page snapshot or find, replaced
|
||||
*/
|
||||
export const browserSettleTimeoutNote = `This timed out because the element never stopped moving: the page animates, so the same call will time out in the same place however often it is made. Drive it from the page itself instead: browser_evaluate with getByRole('button', { name: 'Publish' }).click(), or with element.click() on the element.`;
|
||||
|
||||
/**
|
||||
* Appended to a browser tool whose connection to the computer's Playwright
|
||||
* MCP is gone (`browserRecoveryHint`). The agent supervises that server and
|
||||
* starts it again on its own, so the bridge being down is the computer's
|
||||
* problem, not the run's: a worker account cannot reach the agent, CDP or
|
||||
* the MCP port at all (`guardServicePorts`), and only the user can restart
|
||||
* the computer. One routine spent 18M prompt tokens probing 9222/8931,
|
||||
* starting its own Chrome and killing processes before it was told to stop.
|
||||
*/
|
||||
export const browserBridgeNote = `The browser belongs to the computer and is started and supervised there, so this run cannot start, restart or repair it. Your account is a worker account: the browser's ports are closed to it on purpose, so starting Chrome, killing processes, starting the MCP server or probing ports cannot work and is not the fix.
|
||||
|
||||
Only the user can restart the computer (its Restart button on the computer's page) or sign in to a site again on its screen. Stop here and report: what you were doing, what the browser last showed, and what the user has to do. Do not spend more calls on it.`;
|
||||
|
||||
/**
|
||||
* The folder-ref example a note shows, always over the running bot's own
|
||||
* folder: a literal owner id in the prompt teaches the bot to name another
|
||||
@@ -308,6 +321,19 @@ The user's request sets the scope. Do what they asked, in the scope they gave, a
|
||||
}
|
||||
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
|
||||
|
||||
/**
|
||||
* The last thing in every bot prompt (`composeBotPrompt`), not a note added
|
||||
* once a tool has already failed: what a blocked run does is the app's rule,
|
||||
* in replies, tasks, routines and hook calls alike. One routine spent 18M
|
||||
* prompt tokens probing a browser its account can never reach, and stopped
|
||||
* only when the user told it to (Nov 2026).
|
||||
*/
|
||||
export const RoadblockNote = `# When you are blocked
|
||||
|
||||
When something stops the work - a tool that keeps failing, a page or computer that is down, access you do not have, a step that will not work however you try it - stop and report. Say what you were doing, what failed, what you tried, and what the user has to do next.
|
||||
|
||||
Two or three attempts at the same error is the limit: another one buys the same answer and resends this whole conversation. Don't keep trying variations, don't switch to a way the user didn't ask for to get past it, and never describe the work as done while it is blocked. A clear block the user can act on is the right answer.`;
|
||||
|
||||
/**
|
||||
* Added to chat replies and to tasks the user started: before acting on
|
||||
* something unclear, a bot asks (`ask_user`) rather than guesses.
|
||||
@@ -499,6 +525,15 @@ export const failedToolCallNote = ({
|
||||
|
||||
Nothing has run since that could change that answer, so calling it once more only buys the same error (and resends this whole conversation). Fix the call itself: change the arguments, do the step it is missing first, or report it as blocked.`;
|
||||
|
||||
/**
|
||||
* What the wrap up says when it comes because one tool was called over and
|
||||
* over (`AppData.HarnessStuckToolRepeats`): the run is not out of steps or
|
||||
* tokens, it is out of ideas, and another call of the same tool buys the
|
||||
* same answer for the price of the whole conversation.
|
||||
*/
|
||||
export const stuckToolNote = ({ name, repeats }: { name: string; repeats: number }) =>
|
||||
`This run has called ${name} ${repeats} times in a row and got no further each time. Nothing about the situation has changed since the first call, so another one only buys the same answer (and resends this whole conversation). Stop working on it and say what is blocking it.`;
|
||||
|
||||
/**
|
||||
* Told once to a run that wrote a message for the user and then called a
|
||||
* tool: only the run's last message goes out, so that one never arrived.
|
||||
|
||||
@@ -4,7 +4,16 @@ import listMcpTools from "./list-mcp-tools";
|
||||
import mcpHarnessTool from "./mcp-harness-tool";
|
||||
|
||||
type Params = {
|
||||
client: Client;
|
||||
/**
|
||||
* The connected client, or how to connect on the first call and again
|
||||
* after a lost session.
|
||||
*/
|
||||
client: Client | (() => Promise<Client>);
|
||||
/**
|
||||
* Drops a lost connection so the next call connects again
|
||||
* (`mcpHarnessTool`).
|
||||
*/
|
||||
reconnect?: () => Promise<void>;
|
||||
/**
|
||||
* Tool names to leave out.
|
||||
*/
|
||||
@@ -25,11 +34,14 @@ type Params = {
|
||||
*/
|
||||
export default async function grabMcpTools({
|
||||
client,
|
||||
reconnect,
|
||||
exclude = [],
|
||||
image_focus,
|
||||
redact,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
return (await listMcpTools({ client }))
|
||||
const connected = typeof client == "function" ? await client() : client;
|
||||
|
||||
return (await listMcpTools({ client: connected }))
|
||||
.filter((tool) => !exclude.includes(tool.name))
|
||||
.map((tool) => mcpHarnessTool({ tool, client, image_focus, redact }));
|
||||
.map((tool) => mcpHarnessTool({ tool, client, reconnect, image_focus, redact }));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import isLostMcpSession from "./is-lost-mcp-session";
|
||||
|
||||
describe("isLostMcpSession", () => {
|
||||
test("matches the errors a restarted server gives", () => {
|
||||
expect(
|
||||
isLostMcpSession({
|
||||
text: "Error: Streamable HTTP error: Error POSTing to endpoint: Session not found",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(isLostMcpSession({ text: "Error: fetch failed" })).toBe(true);
|
||||
expect(isLostMcpSession({ text: "Error: Connection refused (ECONNREFUSED)" })).toBe(true);
|
||||
expect(isLostMcpSession({ text: "MCP error -32000: Connection closed" })).toBe(true);
|
||||
});
|
||||
|
||||
test("leaves a tool's own error alone", () => {
|
||||
expect(isLostMcpSession({ text: "Error: Element not found: ref=e12" })).toBe(false);
|
||||
expect(isLostMcpSession({ text: "Error: Wrong arguments for browser_click." })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Whether an MCP error means the session this run opened is gone. The
|
||||
* computer's agent restarts Playwright MCP on its own whenever it exits
|
||||
* (`computer/agent/start-services.ts`), and a restart invalidates every
|
||||
* session id the server handed out: the next call fails with `Session not
|
||||
* found` for the rest of the run, which is how a routine's browser died
|
||||
* mid-pass (Nov 2026). Calling again after a reconnect is safe: a session id
|
||||
* the server no longer knows cannot run the call a second time.
|
||||
*
|
||||
* Broad on purpose: a false match costs one reconnect that fails the same
|
||||
* way, a miss costs the run.
|
||||
*/
|
||||
const LostSession =
|
||||
/session not found|not connected|connection (?:closed|refused)|fetch failed|socket hang up|transport closed|ECONNRESET|ECONNREFUSED/i;
|
||||
|
||||
export default function isLostMcpSession({ text }: { text: string }) {
|
||||
return LostSession.test(text);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import mcpHarnessTool from "./mcp-harness-tool";
|
||||
|
||||
const tool = { name: "browser_snapshot", description: "Looks at the page.", input_schema: {} };
|
||||
const lost = "Streamable HTTP error: Error POSTing to endpoint: Session not found";
|
||||
|
||||
function fakeClient({ fail }: { fail: () => string | null }) {
|
||||
const client = {
|
||||
calls: 0,
|
||||
async callTool() {
|
||||
client.calls++;
|
||||
|
||||
const error = fail();
|
||||
if (error) throw new Error(error);
|
||||
|
||||
return { content: [{ type: "text", text: "The page." }] };
|
||||
},
|
||||
};
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
describe("mcpHarnessTool", () => {
|
||||
test("reconnects once and makes the call again when the session is gone", async () => {
|
||||
const broken = fakeClient({ fail: () => lost });
|
||||
const fresh = fakeClient({ fail: () => null });
|
||||
let current = broken as unknown as Client;
|
||||
let reconnects = 0;
|
||||
|
||||
const call = mcpHarnessTool({
|
||||
tool,
|
||||
client: async () => current,
|
||||
reconnect: async () => {
|
||||
reconnects++;
|
||||
current = fresh as unknown as Client;
|
||||
},
|
||||
});
|
||||
|
||||
expect(await call.run({ args: {}, signal: new AbortController().signal })).toBe("The page.");
|
||||
expect(reconnects).toBe(1);
|
||||
expect(broken.calls).toBe(1);
|
||||
expect(fresh.calls).toBe(1);
|
||||
});
|
||||
|
||||
test("a tool's own error is passed on without reconnecting", async () => {
|
||||
const broken = fakeClient({ fail: () => "Element not found: ref=e12" });
|
||||
let reconnects = 0;
|
||||
|
||||
const call = mcpHarnessTool({
|
||||
tool,
|
||||
client: broken as unknown as Client,
|
||||
reconnect: async () => {
|
||||
reconnects++;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(call.run({ args: {}, signal: new AbortController().signal })).rejects.toThrow("Element not found");
|
||||
expect(reconnects).toBe(0);
|
||||
expect(broken.calls).toBe(1);
|
||||
});
|
||||
|
||||
test("a bridge that is really down fails after one retry", async () => {
|
||||
const broken = fakeClient({ fail: () => lost });
|
||||
let reconnects = 0;
|
||||
|
||||
const call = mcpHarnessTool({
|
||||
tool,
|
||||
client: broken as unknown as Client,
|
||||
reconnect: async () => {
|
||||
reconnects++;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(call.run({ args: {}, signal: new AbortController().signal })).rejects.toThrow("Session not found");
|
||||
expect(reconnects).toBe(1);
|
||||
expect(broken.calls).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTool } from "../types";
|
||||
import isLostMcpSession from "./is-lost-mcp-session";
|
||||
import mcpResultToText from "./mcp-result-to-text";
|
||||
|
||||
type Params = {
|
||||
@@ -13,9 +14,17 @@ type Params = {
|
||||
*/
|
||||
tool: { name: string; description?: string; input_schema: Record<string, unknown> };
|
||||
/**
|
||||
* The connected client, or how to get it on the first call.
|
||||
* The connected client, or how to get it on the first call (and again
|
||||
* after `reconnect`).
|
||||
*/
|
||||
client: Client | (() => Promise<Client>);
|
||||
/**
|
||||
* Closes the lost connection and drops it, so the next call connects
|
||||
* again: a server that restarts mid-run leaves every call failing with
|
||||
* `Session not found` for the rest of the run, and a long run outlives
|
||||
* one restart (`isLostMcpSession`).
|
||||
*/
|
||||
reconnect?: () => Promise<void>;
|
||||
/**
|
||||
* What a reading of an image this tool returns should look for, for a
|
||||
* model that can't see it.
|
||||
@@ -30,44 +39,73 @@ type Params = {
|
||||
* results come back via `mcpResultToText`, the text redacted and images
|
||||
* (screenshots) handed back for the run to show the model, or have read
|
||||
* (and the reading redacted) for one that can't see.
|
||||
*
|
||||
* A call that fails because the session is gone is reconnected and made
|
||||
* once more: a session the server does not know has nothing left to run.
|
||||
*/
|
||||
export default function mcpHarnessTool({
|
||||
name,
|
||||
tool,
|
||||
client,
|
||||
reconnect,
|
||||
image_focus,
|
||||
redact = (text) => text,
|
||||
}: Params): HarnessTool {
|
||||
const call = async ({ args, signal }: { args: Record<string, unknown>; signal: AbortSignal }) => {
|
||||
const connected = typeof client == "function" ? await client() : client;
|
||||
|
||||
const { text, images } = mcpResultToText({
|
||||
result: await connected.callTool({ name: tool.name, arguments: args }, undefined, {
|
||||
signal,
|
||||
timeout: AppData.McpToolTimeoutMs,
|
||||
resetTimeoutOnProgress: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!images.length) return redact(text);
|
||||
|
||||
return {
|
||||
text: redact(text),
|
||||
images: images.map(({ data, mime_type }) => ({
|
||||
url: `data:${mime_type};base64,${data}`,
|
||||
focus: image_focus,
|
||||
redact,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
name: name || tool.name,
|
||||
description: tool.description || tool.name,
|
||||
parameters: tool.input_schema,
|
||||
run: async ({ args, signal }) => {
|
||||
try {
|
||||
const connected = typeof client == "function" ? await client() : client;
|
||||
|
||||
const { text, images } = mcpResultToText({
|
||||
result: await connected.callTool({ name: tool.name, arguments: args }, undefined, {
|
||||
signal,
|
||||
timeout: AppData.McpToolTimeoutMs,
|
||||
resetTimeoutOnProgress: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!images.length) return redact(text);
|
||||
|
||||
return {
|
||||
text: redact(text),
|
||||
images: images.map(({ data, mime_type }) => ({
|
||||
url: `data:${mime_type};base64,${data}`,
|
||||
focus: image_focus,
|
||||
redact,
|
||||
})),
|
||||
};
|
||||
return await call({ args, signal });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) error.message = redact(error.message);
|
||||
throw error;
|
||||
if (!reconnect || !isLostMcpSession({ text: messageOf(error) })) throw redacted({ error, redact });
|
||||
|
||||
await reconnect().catch(() => null);
|
||||
|
||||
try {
|
||||
return await call({ args, signal });
|
||||
} catch (retry_error: unknown) {
|
||||
throw redacted({ error: retry_error, redact });
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function messageOf(error: unknown) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* A tool error is handed to the model, so a secret the server echoed can't
|
||||
* ride along in it.
|
||||
*/
|
||||
function redacted({ error, redact }: { error: unknown; redact: (text: string) => string }) {
|
||||
if (error instanceof Error) error.message = redact(error.message);
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -55,6 +55,13 @@ const remember: HarnessTool<{ note: string }> = {
|
||||
},
|
||||
};
|
||||
|
||||
const glance: HarnessTool<{ at: string }> = {
|
||||
name: "glance",
|
||||
description: "Looks at something.",
|
||||
schema: z.object({ at: z.string() }),
|
||||
run: async () => "Looked.",
|
||||
};
|
||||
|
||||
const asked: string[] = [];
|
||||
|
||||
const askUser: HarnessTool<{ question: string }> = {
|
||||
@@ -283,16 +290,23 @@ describe("runTextLoop", () => {
|
||||
|
||||
test("a run with no step limit keeps going, and records the window it works to", async () => {
|
||||
memory.length = 0;
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
/**
|
||||
* Two tools in turn: the same one 30 times in a row is a stuck run
|
||||
* now (`HarnessStuckToolRepeats`), which is not what this tests.
|
||||
*/
|
||||
const loop_calls = [
|
||||
{ tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }] },
|
||||
{ tool_calls: [{ id: "c", name: "glance", arguments: `{"at":"x"}` }] },
|
||||
];
|
||||
const turns = 30;
|
||||
const { generate, seen } = scripted(Array.from({ length: turns }, () => loop_call));
|
||||
const { generate, seen } = scripted(
|
||||
Array.from({ length: turns }, (_turn, index) => loop_calls[index % loop_calls.length]!),
|
||||
);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
tools: [remember, glance],
|
||||
max_steps: UnlimitedLimit,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
@@ -483,6 +497,80 @@ describe("runTextLoop", () => {
|
||||
expect(prompt).not.toContain("start_task");
|
||||
});
|
||||
|
||||
test("stops a run stuck on one tool and makes it report", async () => {
|
||||
const repeats = AppData.HarnessStuckToolRepeats;
|
||||
const { generate, seen } = scripted(
|
||||
Array.from({ length: repeats }, (_, index) => ({
|
||||
text: null,
|
||||
tool_calls: [{ id: `c${index}`, name: "remember", arguments: `{"note":"${index}"}` }],
|
||||
})),
|
||||
);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const prompts = seen.map((params) => String(params.messages.at(-1)!.content));
|
||||
|
||||
expect(prompts.some((prompt) => prompt.includes(stuckToolNote({ name: "remember", repeats })))).toBe(true);
|
||||
expect(seen).toHaveLength(repeats + 1);
|
||||
});
|
||||
|
||||
test("a tool called over and over that answers differently each time is not stuck", async () => {
|
||||
let counted = 0;
|
||||
const counter: HarnessTool<Record<string, never>> = {
|
||||
name: "count",
|
||||
description: "Counts.",
|
||||
schema: z.object({}),
|
||||
run: async () => `Line ${++counted}.`,
|
||||
};
|
||||
const calls = AppData.HarnessStuckToolRepeats + 2;
|
||||
const { generate, seen } = scripted(
|
||||
Array.from({ length: calls }, (_, index) => ({
|
||||
text: null,
|
||||
tool_calls: [{ id: `c${index}`, name: "count", arguments: `` }],
|
||||
})),
|
||||
);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [counter],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const prompts = seen.map((params) => String(params.messages.at(-1)!.content));
|
||||
|
||||
expect(prompts.some((prompt) => prompt.includes("This run has called"))).toBe(false);
|
||||
});
|
||||
|
||||
test("a run one call short of the limit is not stopped", async () => {
|
||||
const calls = AppData.HarnessStuckToolRepeats - 1;
|
||||
const { generate, seen } = scripted(
|
||||
Array.from({ length: calls }, (_, index) => ({
|
||||
text: null,
|
||||
tool_calls: [{ id: `c${index}`, name: "remember", arguments: `{"note":"${index}"}` }],
|
||||
})),
|
||||
);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const prompts = seen.map((params) => String(params.messages.at(-1)!.content));
|
||||
|
||||
expect(prompts.some((prompt) => prompt.includes("This run has called"))).toBe(false);
|
||||
});
|
||||
|
||||
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
|
||||
const max_steps = AppData.HarnessStepsLowMinSteps;
|
||||
const loop_call = {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
replyDraftNote,
|
||||
replyNoTextNote,
|
||||
staticPromptOverBudgetNote,
|
||||
stuckToolNote,
|
||||
tokensLowNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
@@ -269,17 +270,28 @@ export const WrapUpSavingTurns = 2;
|
||||
export const wrapUpPrompt = ({
|
||||
uses,
|
||||
reason = "steps",
|
||||
tool,
|
||||
saving = [],
|
||||
hand_off = [],
|
||||
answer = [],
|
||||
}: {
|
||||
uses: HarnessToolUse[];
|
||||
reason?: "steps" | "tokens";
|
||||
reason?: "steps" | "tokens" | "stuck";
|
||||
/**
|
||||
* The tool the run was stuck on, with the wrap up it caused (`stuck`).
|
||||
*/
|
||||
tool?: { name: string; repeats: number };
|
||||
saving?: string[];
|
||||
hand_off?: string[];
|
||||
answer?: string[];
|
||||
}) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${wrapUpToolsPrompt({
|
||||
`${
|
||||
reason == "stuck" && tool
|
||||
? stuckToolNote(tool)
|
||||
: reason == "tokens"
|
||||
? "This run has used all the tokens it may spend."
|
||||
: "You've used every step this run allows."
|
||||
} ${wrapUpToolsPrompt({
|
||||
saving,
|
||||
hand_off,
|
||||
answer,
|
||||
@@ -568,6 +580,17 @@ export default async function runTextLoop({
|
||||
const step_ceiling = isUnlimitedLimit(max_steps) ? Infinity : max_steps;
|
||||
|
||||
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
|
||||
/**
|
||||
* The last tool the run called, how many times in a row it called it,
|
||||
* and the answer it got: the same call giving the same answer is a run
|
||||
* getting nowhere, and at `AppData.HarnessStuckToolRepeats` it stops and
|
||||
* reports (`same_tool.stuck`) instead of paying for that answer again
|
||||
* with the whole conversation.
|
||||
*/
|
||||
const same_tool: {
|
||||
last: { name: string; answer: string; count: number } | null;
|
||||
stuck: { name: string; repeats: number } | null;
|
||||
} = { last: null, stuck: null };
|
||||
let prefer_key = planned_key;
|
||||
/**
|
||||
* How many answers the review has sent back, and the last one it faulted,
|
||||
@@ -767,7 +790,12 @@ export default async function runTextLoop({
|
||||
max_prompt_tokens > 0 &&
|
||||
usage.prompt_tokens >= max_prompt_tokens,
|
||||
);
|
||||
const wrap_up = out_of_steps || out_of_tokens;
|
||||
const wrap_up: boolean = out_of_steps || out_of_tokens || same_tool.stuck !== null;
|
||||
/**
|
||||
* Why the run is wrapping up: its steps, its tokens, or one tool
|
||||
* called over and over.
|
||||
*/
|
||||
const wrap_reason = same_tool.stuck ? "stuck" : out_of_steps ? "steps" : "tokens";
|
||||
/**
|
||||
* The saving turn: only the tools a wrap up has left. Without one
|
||||
* of them, or once it had its round, the wrap up is the old one,
|
||||
@@ -797,7 +825,8 @@ export default async function runTextLoop({
|
||||
transcript,
|
||||
content: wrapUpPrompt({
|
||||
uses: tool_uses,
|
||||
reason: out_of_steps ? "steps" : "tokens",
|
||||
reason: wrap_reason,
|
||||
tool: same_tool.stuck ?? undefined,
|
||||
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
|
||||
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
|
||||
answer: answer_tools.map((tool) => tool.name),
|
||||
@@ -808,7 +837,13 @@ export default async function runTextLoop({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "wrap_up",
|
||||
text: `${out_of_steps ? "Out of steps" : "Out of tokens"}. ${wrap_tools.length ? `It has one turn left with ${wrap_tools.map((tool) => tool.name).join(", ")}.` : "It has no tool left and must answer now."}`,
|
||||
text: `${
|
||||
same_tool.stuck
|
||||
? `Stuck on ${same_tool.stuck.name} (${same_tool.stuck.repeats} calls in a row)`
|
||||
: out_of_steps
|
||||
? "Out of steps"
|
||||
: "Out of tokens"
|
||||
}. ${wrap_tools.length ? `It has one turn left with ${wrap_tools.map((tool) => tool.name).join(", ")}.` : "It has no tool left and must answer now."}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1229,6 +1264,20 @@ export default async function runTextLoop({
|
||||
|
||||
tool_uses.push({ name: call.name, ok });
|
||||
|
||||
/**
|
||||
* The same tool over and over, answering the same thing, gets
|
||||
* the run nowhere: it stops and reports at the wrap up
|
||||
* (`AppData.HarnessStuckToolRepeats`).
|
||||
*/
|
||||
const previous = same_tool.last;
|
||||
const repeats =
|
||||
previous && previous.name == call.name && previous.answer == content ? previous.count + 1 : 1;
|
||||
|
||||
same_tool.last = { name: call.name, answer: content, count: repeats };
|
||||
if (!same_tool.stuck && repeats >= AppData.HarnessStuckToolRepeats) {
|
||||
same_tool.stuck = { name: call.name, repeats };
|
||||
}
|
||||
|
||||
await traced({
|
||||
kind: "tool",
|
||||
index,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { browserSettleTimeoutNote } from "@/src/data/harness-prompts";
|
||||
import { browserBridgeNote, browserSettleTimeoutNote } from "@/src/data/harness-prompts";
|
||||
import browserRecoveryHint from "./browser-recovery-hint";
|
||||
|
||||
const settle_timeout = `Error: ### Error
|
||||
@@ -19,6 +19,12 @@ describe("browserRecoveryHint", () => {
|
||||
expect(browserRecoveryHint({ name: "laptop__browser_click", text: settle_timeout })).toBe(browserSettleTimeoutNote);
|
||||
});
|
||||
|
||||
test("says the bridge is the computer's after the session dies", () => {
|
||||
const lost = "Error: Streamable HTTP error: Error POSTing to endpoint: Session not found";
|
||||
|
||||
expect(browserRecoveryHint({ name: "browser_snapshot", text: lost })).toBe(browserBridgeNote);
|
||||
});
|
||||
|
||||
test("says nothing about a failure that already names its own fix", () => {
|
||||
const bad_target = `Error: ### Error
|
||||
Error: "button "More account and team options"" is not a valid target. Use a ref from the page snapshot (e.g. "e5"), a CSS selector, or a locator.`;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { browserSettleTimeoutNote } from "@/src/data/harness-prompts";
|
||||
import { browserBridgeNote, browserSettleTimeoutNote } from "@/src/data/harness-prompts";
|
||||
import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
import isLostMcpSession from "../../mcp/is-lost-mcp-session";
|
||||
|
||||
/**
|
||||
* Playwright's wording for an action that gave up on an element which never
|
||||
@@ -10,15 +11,24 @@ import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
const SettleTimeout = /waiting for element to be visible, enabled and stable/i;
|
||||
|
||||
/**
|
||||
* What to add after a browser action that timed out waiting for its element
|
||||
* to settle, or nothing when the call did not fail that way. The run has
|
||||
* just spent 5 seconds on it, and retrying the same call is what one Canva
|
||||
* run did five times in a row.
|
||||
* What to add to a browser tool's error, or nothing when the call failed
|
||||
* for a reason the error already explains (a bad target, a missing
|
||||
* element). Two failures say more than the error itself:
|
||||
*
|
||||
* - the element never settled, so retrying it is what one Canva run did
|
||||
* five times in a row;
|
||||
* - the connection to the computer's browser bridge is gone, which is the
|
||||
* computer's to fix, not the run's (`browserBridgeNote`).
|
||||
*
|
||||
* Applied where tool errors become the model's text (`run-tool-call`): a
|
||||
* result the server flags as an error is thrown, so a wrapper around a
|
||||
* successful result never sees it.
|
||||
*/
|
||||
export default function browserRecoveryHint({ name, text }: { name: string; text: string }) {
|
||||
if (!isBrowserTool({ name })) return "";
|
||||
if (!text.startsWith("Error:")) return "";
|
||||
if (!SettleTimeout.test(text)) return "";
|
||||
if (SettleTimeout.test(text)) return browserSettleTimeoutNote;
|
||||
if (isLostMcpSession({ text })) return browserBridgeNote;
|
||||
|
||||
return browserSettleTimeoutNote;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { ComputerMcpExcludedTools } from "@/src/dict/computer-dict";
|
||||
@@ -213,9 +214,28 @@ export default async function openComputerTools({
|
||||
*/
|
||||
const redact_page = (text: string) => redact(maskPasswordFieldValues({ text }));
|
||||
|
||||
const client = browser
|
||||
? await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal })
|
||||
: null;
|
||||
/**
|
||||
* Connected on the first browser call, and again after the computer's
|
||||
* agent restarts Playwright MCP under the run: a session it handed out
|
||||
* stops existing, and every call fails with `Session not found` until
|
||||
* the run connects again (`mcpHarnessTool`).
|
||||
*/
|
||||
const link: { client: Client | null } = { client: null };
|
||||
const connect = async () => {
|
||||
const client =
|
||||
link.client ??
|
||||
(link.client = await connectMcpServer({
|
||||
url: target.url,
|
||||
headers: { authorization: `Bearer ${target.token}` },
|
||||
signal,
|
||||
}));
|
||||
|
||||
return client;
|
||||
};
|
||||
const reconnect = async () => {
|
||||
await link.client?.close().catch(() => null);
|
||||
link.client = null;
|
||||
};
|
||||
const context: ComputerToolContext = {
|
||||
computer: target,
|
||||
computer_id: Number(computer_id),
|
||||
@@ -228,9 +248,10 @@ export default async function openComputerTools({
|
||||
};
|
||||
|
||||
try {
|
||||
const browser_tools = client
|
||||
const browser_tools = browser
|
||||
? await grabMcpTools({
|
||||
client,
|
||||
client: connect,
|
||||
reconnect,
|
||||
exclude: ComputerMcpExcludedTools,
|
||||
redact: redact_page,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
@@ -272,11 +293,11 @@ export default async function openComputerTools({
|
||||
envs: envs.map((env) => ({ key: env.key, description: env.description })),
|
||||
redact,
|
||||
close: async () => {
|
||||
await client?.close().catch(() => {});
|
||||
await link.client?.close().catch(() => {});
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await client?.close().catch(() => {});
|
||||
await link.client?.close().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import type { ComputerApi } from "@/src/functions/backend/computers/computer-fet
|
||||
import browserOutputText from "@/src/utils/browser-output-text";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import browserRecoveryHint from "./browser-recovery-hint";
|
||||
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
|
||||
|
||||
type Params = {
|
||||
@@ -52,10 +51,8 @@ export default function withBrowserOutputs({ tool, computer, dirs }: Params): Ha
|
||||
? await computerWorkspaceFullWarning({ computer, dirs, signal }).catch(() => null)
|
||||
: null;
|
||||
const parts = [lines.length ? `${text}\n### Downloads\n${lines.join("\n")}` : text];
|
||||
const hint = browserRecoveryHint({ name: tool.name, text });
|
||||
|
||||
if (full) parts.push(full);
|
||||
if (hint) parts.push(hint);
|
||||
|
||||
const next = parts.join("\n\n");
|
||||
|
||||
|
||||
@@ -22,6 +22,15 @@ const failing: HarnessTool = {
|
||||
},
|
||||
};
|
||||
|
||||
const browser_fails: HarnessTool = {
|
||||
name: "pc__browser_snapshot",
|
||||
description: "Fails to reach the browser.",
|
||||
schema: z.object({}),
|
||||
run: async () => {
|
||||
throw new Error("Streamable HTTP error: Error POSTing to endpoint: Session not found");
|
||||
},
|
||||
};
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
const shot: HarnessTool = {
|
||||
name: "shot",
|
||||
@@ -39,7 +48,7 @@ const shot: HarnessTool = {
|
||||
const run = (name: string, args: string) =>
|
||||
runToolCall({
|
||||
call: { id: "1", name, arguments: args },
|
||||
tools: [echo, failing, shot],
|
||||
tools: [echo, failing, shot, browser_fails],
|
||||
signal,
|
||||
});
|
||||
const call = async (name: string, args: string) => (await run(name, args)).text;
|
||||
@@ -49,6 +58,13 @@ describe("runToolCall", () => {
|
||||
expect(await call("echo", `{"text":"hi"}`)).toBe("hi");
|
||||
});
|
||||
|
||||
test("adds what a failed browser call's error doesn't say", async () => {
|
||||
const text = await call("pc__browser_snapshot", "");
|
||||
|
||||
expect(text.startsWith("Error: Streamable HTTP error")).toBe(true);
|
||||
expect(text).toContain("Only the user can restart the computer");
|
||||
});
|
||||
|
||||
test("reports problems to the model instead of throwing", async () => {
|
||||
expect(await call("nope", "{}")).toContain(`no tool called "nope"`);
|
||||
expect(await call("echo", "{bad")).toContain("weren't valid JSON");
|
||||
|
||||
@@ -4,6 +4,7 @@ import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
import TaskTimeoutError from "@/src/utils/task-timeout-error";
|
||||
import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "../harness-error";
|
||||
import browserRecoveryHint from "./computer/browser-recovery-hint";
|
||||
import unknownToolArgs from "./unknown-tool-args";
|
||||
import unknownToolMessage from "./unknown-tool-message";
|
||||
import toolTimeoutMs from "./tool-timeout-ms";
|
||||
@@ -130,13 +131,31 @@ async function runTool({ call, tools, signal }: Params): Promise<ToolOutput> {
|
||||
}
|
||||
|
||||
if (error instanceof TaskTimeoutError) {
|
||||
return { text: `Error: ${error.message}`, images: [], ok: false };
|
||||
return { text: withBrowserHint({ name: call.name, text: `Error: ${error.message}` }), images: [], ok: false };
|
||||
}
|
||||
|
||||
return { text: `Error: ${error instanceof Error ? error.message : String(error)}`, images: [], ok: false };
|
||||
return {
|
||||
text: withBrowserHint({
|
||||
name: call.name,
|
||||
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
||||
}),
|
||||
images: [],
|
||||
ok: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed browser call with what its error doesn't say (`browserRecoveryHint`):
|
||||
* an element that never settled, or a bridge that is down and belongs to the
|
||||
* computer. Every other tool, and every other failure, is left as it is.
|
||||
*/
|
||||
function withBrowserHint({ name, text }: { name: string; text: string }) {
|
||||
const hint = browserRecoveryHint({ name, text });
|
||||
|
||||
return hint ? `${text}\n\n${hint}` : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* A result past its tool's cap is cut there, keeping its start and its
|
||||
* end: a command's answer and the totals or error it ends with are the
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { RoadblockNote } from "@/src/data/harness-prompts";
|
||||
import composeBotPrompt from "./compose-bot-prompt";
|
||||
|
||||
describe("composeBotPrompt", () => {
|
||||
@@ -8,6 +9,7 @@ describe("composeBotPrompt", () => {
|
||||
"# You are Scout",
|
||||
"You are a worker bot on this crew. Your role: Finds things.",
|
||||
"Your bot id is 7. That id is you: when a tool takes a bot id for the bot it is about (your own tasks, your own picture), this is it, and when you name yourself in a message write the ref `[bot:7]`, never another bot's.",
|
||||
RoadblockNote,
|
||||
].join("\n\n"),
|
||||
);
|
||||
});
|
||||
@@ -18,6 +20,7 @@ describe("composeBotPrompt", () => {
|
||||
"# You are A bot",
|
||||
"You are the coordinator on this crew.",
|
||||
"Your bot id is 1. That id is you: when a tool takes a bot id for the bot it is about (your own tasks, your own picture), this is it, and when you name yourself in a message write the ref `[bot:1]`, never another bot's.",
|
||||
RoadblockNote,
|
||||
].join("\n\n"),
|
||||
);
|
||||
});
|
||||
@@ -35,6 +38,7 @@ describe("composeBotPrompt", () => {
|
||||
"You are a worker bot on this crew.",
|
||||
"Your bot id is 4. That id is you: when a tool takes a bot id for the bot it is about (your own tasks, your own picture), this is it, and when you name yourself in a message write the ref `[bot:4]`, never another bot's.",
|
||||
"Core.",
|
||||
RoadblockNote,
|
||||
].join("\n\n"),
|
||||
);
|
||||
});
|
||||
@@ -67,6 +71,7 @@ describe("composeBotPrompt", () => {
|
||||
"# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n- Cite sources.",
|
||||
"# Memory about the user\n\nWhat you've learned about the user. It shapes how you do the work, never what you do beyond it.\n\n- The user prefers short replies.",
|
||||
`# Memory in Launch\n\nYour own notes for this workspace: what you have learned here. They shape how you do the work here, never what you do beyond it. They are not the workspace's description or context, which the user sets above; never call them the workspace's record. The user reads them in the workspace's settings, under this bot's row.\n\n- Marketing signs off on copy.`,
|
||||
RoadblockNote,
|
||||
].join("\n\n"),
|
||||
);
|
||||
});
|
||||
@@ -89,6 +94,7 @@ describe("composeBotPrompt", () => {
|
||||
"# Install-wide instructions\n\nNever invent sources.",
|
||||
`# Workspace: Launch\n\nYou're working in the workspace "Launch". Follow its context and your instructions for it below, over your general habits where they differ.\n\nThe workspace's context, which the user sets:\n\nThe spring launch.`,
|
||||
"# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n- Cite sources.",
|
||||
RoadblockNote,
|
||||
].join("\n\n"),
|
||||
);
|
||||
});
|
||||
@@ -133,6 +139,17 @@ describe("composeBotPrompt", () => {
|
||||
expect(composeBotPrompt({ workspace: { name: "Launch" }, user_role: " " })).not.toContain("role in Launch");
|
||||
});
|
||||
|
||||
test("ends with the app's rule for a blocked run, for every bot", () => {
|
||||
const prompt = composeBotPrompt({
|
||||
bot: { id: 4, name: "Scout" },
|
||||
system_prompt: "Core.",
|
||||
memory: "- Cite sources.",
|
||||
});
|
||||
|
||||
expect(prompt.endsWith(RoadblockNote)).toBe(true);
|
||||
expect(composeBotPrompt({ system_prompt: "Core." })).not.toContain("# When you are blocked");
|
||||
});
|
||||
|
||||
test("names an untitled workspace even when it has no context", () => {
|
||||
expect(composeBotPrompt({ workspace: { name: null } })).toBe(
|
||||
`# Workspace: Untitled\n\nYou're working in the workspace "Untitled". Follow its context and your instructions for it below, over your general habits where they differ.`,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { RoadblockNote } from "@/src/data/harness-prompts";
|
||||
|
||||
type WorkspacePrompt = {
|
||||
name?: string | null;
|
||||
description?: string | null;
|
||||
@@ -140,6 +142,12 @@ export default function composeBotPrompt({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's rule for a blocked run, said last so no workspace text or
|
||||
* memory stands after it.
|
||||
*/
|
||||
if (identity) parts.push(RoadblockNote);
|
||||
|
||||
return parts.join("\n\n");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user