Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
OpenAI-compatible: a long agent turn over llama.cpp's window drops its oldest tool output, and retries stop at 3/3
Absterrg04187ecf34024
diff --git a/server/drivers/chat-size-limit.test.ts b/server/drivers/chat-size-limit.test.tsindex 2e2577c4a6..bb7abb77e9 100644--- a/server/drivers/chat-size-limit.test.ts+++ b/server/drivers/chat-size-limit.test.ts@@ -8,8 +8,9 @@ import type { SendTurnInput } from "../contracts.ts";import { recordEvents } from "../testing/events.ts";import { removeTempDir } from "../testing/cleanup.ts";import { requestTooLargeMessage } from "../../shared/request-too-large.ts";-import { IMAGE_OMITTED, refusesRequestSize, shareThatFits, smallerResend, TOOL_OUTPUT_SHORTENED } from "./chat-size-limit.ts";+import { IMAGE_OMITTED, refusesRequestSize, shareThatFits, smallerResend, TOOL_OUTPUT_OMITTED, TOOL_OUTPUT_SHORTENED } from "./chat-size-limit.ts";import type { OpenAIChatMessage } from "./openai-chat.ts";+import { RETRY_MAX_ATTEMPTS } from "./retry.ts";import { OpenAICompatDriver } from "./openai-compat.ts";const NGINX_413 = "<html>\r\n<head><title>413 Request Entity Too Large</title></head>\r\n<body>\r\n<center><h1>413 Request Entity Too Large</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n";@@ -152,6 +153,27 @@ describe("smallerResend", () => {expect(10 - earlier).toBeGreaterThan(10 - (first.messages.indexOf(request) - 2));});+ it("omits this turn's oldest tool output last, keeping every call's pairing and the newest round whole", () => {+ const rounds = Array.from({ length: 6 }, (_, index): OpenAIChatMessage[] => [+ { role: "assistant", content: null, tool_calls: [{ id: `read-${index}`, type: "function", function: { name: "read_page", arguments: `{"page":${index}}` } }] },+ { role: "tool", tool_call_id: `read-${index}`, content: JSON.stringify({ ok: true, result: `page ${index} ${"p".repeat(3_000)}` }) },+ ]).flat();+ const { request, messages, refused } = turn(history(2, 500), rounds);+ const plain = { ...request, content: "Read the six pages." };+ const sent = messages.map((message) => message === request ? plain : message);+ const resend = smallerResend(sent, plain, refused - 40_000, 0.6)!;+ expect(resend.after.bytes).toBeLessThanOrEqual((refused - 40_000) * 0.6);+ expect(resend.messages.indexOf(plain)).toBe(2);+ const outputs = resend.messages.filter((message) => message.role === "tool").map((message) => JSON.parse(String(message.content)) as { ok: boolean; result: string });+ const omitted = outputs.findIndex((output) => output.result !== TOOL_OUTPUT_OMITTED);+ expect(omitted).toBeGreaterThan(0);+ expect(outputs.slice(0, omitted).every((output) => output.ok && output.result === TOOL_OUTPUT_OMITTED)).toBe(true);+ expect(outputs.slice(omitted).map((output) => output.result.slice(0, 6))).toEqual(Array.from({ length: 6 - omitted }, (_, index) => `page ${omitted + index}`));+ expect(resend.messages.slice(3).map((message) => message.role)).toEqual(Array.from({ length: 6 }, () => ["assistant", "tool"]).flat());+ expect(resend.messages.slice(3).filter((message) => message.role === "tool").map((message) => message.tool_call_id)).toEqual(Array.from({ length: 6 }, (_, index) => `read-${index}`));+ expect(smallerResend(resend.messages, plain, resend.after.bytes, 0.01)!.messages.at(-1)).toBe(resend.messages.at(-1));+ });+it("offers nothing to resend when only an omission note stands before the request", () => {const { request, messages, refused } = turn(history(4, 4_000));const first = smallerResend(messages, request, refused, 0.01)!;@@ -315,6 +337,16 @@ describe("an OpenAI-compatible provider that refuses large requests", () => {expect(f.errors()).toEqual([]);});+ it("stops after as many requests as any retried turn when llama.cpp refuses every smaller copy", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const f = await provider(llamaCpp(() => 999, () => 1_000));+ const done = await f.run({ system: "Fixture system prompt.", transcript: transcript(20, 3_000) });+ expect(done).toMatchObject({ ok: false });+ expect(f.requests).toHaveLength(RETRY_MAX_ATTEMPTS);+ expect(f.retries().map((retry) => (retry as { attempt: number }).attempt)).toEqual([1, 2]);+ expect(f.errors()).toEqual([requestTooLargeMessage("Fixture Flash")]);+ });+it("fails with one plain message when not even the newest message fits llama.cpp's window", async () => {vi.spyOn(console, "warn").mockImplementation(() => {});const f = await provider(llamaCpp(() => 100));diff --git a/server/drivers/chat-size-limit.ts b/server/drivers/chat-size-limit.tsindex 1dbc2e3aa7..51efd89cfe 100644--- a/server/drivers/chat-size-limit.ts+++ b/server/drivers/chat-size-limit.ts@@ -2,6 +2,7 @@ import { prefixBytes } from "../context-rebuild.ts";import type { ChatContentPart } from "./chat-images.ts";import type { OpenAIChatMessage } from "./openai-chat.ts";import { object } from "./openai-chat-protocol.ts";+import { RETRY_MAX_ATTEMPTS } from "./retry.ts";/** nginx's "413 Request Entity Too Large" page, Express's "request entity too large", "Payload Too Large", and* OpenAI's "Request too large for <model>". */@@ -46,10 +47,11 @@ export class RequestTooLargeError extends Error {/** A provider that counts each refused request may be asked again with fresh counts, since bytes and its tokens differ* in proportion (an image, a dense prompt); a refusal that gives no count gets one smaller copy. */-export const resendsAllowed = (refusal: RequestTooLargeError): number => refusal.fits === undefined ? 1 : 3;+export const resendsAllowed = (refusal: RequestTooLargeError): number => refusal.fits === undefined ? 1 : RETRY_MAX_ATTEMPTS - 1;export const IMAGE_OMITTED = "[image omitted to fit the provider's size limit]";export const TOOL_OUTPUT_SHORTENED = "\n[tool output shortened to fit the provider's size limit]";+export const TOOL_OUTPUT_OMITTED = "[earlier tool output omitted to fit the provider's size limit; run the tool again if it is still needed]";const omittedHistory = (count: number) =>`[${count} earlier message${count === 1 ? "" : "s"} omitted to fit the provider's size limit; full history remains in the app.]`;const OMITTED_HISTORY = /^\[(\d+) earlier messages? omitted to fit the provider's size limit; full history remains in the app\.\]$/;@@ -83,16 +85,19 @@ function withoutImages(message: OpenAIChatMessage): OpenAIChatMessage {return { ...message, content: message.content.map((part) => isImage(part) ? { type: "text" as const, text: IMAGE_OMITTED } : part) };}-function shortenedToolOutput(message: OpenAIChatMessage): OpenAIChatMessage {+function withToolOutput(message: OpenAIChatMessage, change: (text: string) => string): OpenAIChatMessage {const content = typeof message.content === "string" ? message.content : "";- const shorten = (text: string) => prefixBytes(text, SHORT_TOOL_OUTPUT_BYTES) + TOOL_OUTPUT_SHORTENED;let envelope: Record<string, unknown> | undefined;try { envelope = object(JSON.parse(content)); } catch { envelope = undefined; }- return { ...message, content: typeof envelope?.result === "string" ? JSON.stringify({ ...envelope, result: shorten(envelope.result) }) : shorten(content) };+ return { ...message, content: typeof envelope?.result === "string" ? JSON.stringify({ ...envelope, result: change(envelope.result) }) : change(content) };}-/** Aims at `fits` of `refusedBytes`, half when the provider did not say; null when nothing but the system prompt and- * `request` could shrink. */+const shortenedToolOutput = (message: OpenAIChatMessage) =>+ withToolOutput(message, (text) => prefixBytes(text, SHORT_TOOL_OUTPUT_BYTES) + TOOL_OUTPUT_SHORTENED);+const omittedToolOutput = (message: OpenAIChatMessage) => withToolOutput(message, () => TOOL_OUTPUT_OMITTED);++/** Aims at `fits` of `refusedBytes`, half when the provider did not say: earlier history goes before this turn's own+ * older tool output, and the newest round is kept whole. Null when nothing else could shrink. */export function smallerResend(messages: readonly OpenAIChatMessage[],request: OpenAIChatMessage,@@ -114,11 +119,14 @@ export function smallerResend(out[index] = next;};const shrinkable = messages.flatMap((message, index) => index === requestAt || message.role === "system" ? [] : [index]);+ const latestCalls = messages.findLastIndex((message) => message.role === "assistant" && Boolean(message.tool_calls?.length));const steps = [...shrinkable.filter((index) => imagesIn(messages[index]!)).map((index) => () => replace(index, withoutImages(out[index]!))),...shrinkable.filter((index) => index > requestAt && messages[index]!.role === "tool" && sizes[index]! > LONG_TOOL_OUTPUT_BYTES).map((index) => () => replace(index, shortenedToolOutput(out[index]!))),...shrinkable.filter((index) => index < requestAt && omittedBefore(messages[index]!) === undefined).map((index) => () => replace(index, null)),+ ...shrinkable.filter((index) => index > requestAt && index < latestCalls && messages[index]!.role === "tool"+ && sizes[index]! > bytesOf(omittedToolOutput(messages[index]!))).map((index) => () => replace(index, omittedToolOutput(out[index]!))),];let taken = 0;for (; taken < steps.length && total > target; taken++) steps[taken]!();