Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep acp/core.ts and agents-call.ts within the file-size ratchet
luishron123abc3a617665a
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex f3df6f3710..77c44fff9e 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -74,7 +74,7 @@ import { startupFailureRecoverable } from "./startup-recovery.ts";import { engineFailure, engineFailureKind } from "../engine-errors.ts";import { acpRuntimeFailure, acpStopFailure } from "./failure-words.ts";import { narrowsNativeTools, parseToolScope } from "../../../shared/tool-scope.ts";-import { acpMcpServers, type AcpMcpServer } from "../turn-mcp.ts"; import { acpOwnMcpTransport, acpSessionMcpServers, loopbackUnproxied } from "../own-mcp-http.ts"; import { leftOutToolsNote } from "../session-tool-budget.ts"; import { acpToolOutput, acpToolProgress } from "../tool-progress.ts";+import { acpMcpServers, type AcpMcpServer } from "../turn-mcp.ts"; import { acpOwnMcpTransport, acpSessionMcpServers, loopbackUnproxied } from "../own-mcp-http.ts"; import { acpToolOutput, acpToolProgress } from "../tool-progress.ts";import { learnedToolCountLimit, mcpToolBudget, retryUnderToolLimit } from "../../tool-count-limit.ts"; import { instanceEnvNames } from "../../bot-box/env.ts";import { learnedTextOnlyTools, learnTextOnlyTools, TEXT_ONLY_PROMPT_NOTE } from "../../mcp-text-only.ts"; import { isHermesReasoningReplay } from "./hermes-replay.ts";@@ -1121,11 +1121,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (liveSessionId !== null && session.sessionKey === liveSessionKey(sessionKey, heldSystem()) && (cursor === null || cursor === liveSessionId)) {break;}- const sessionServers = () => acpSessionMcpServers(mcpServers, ownMcp, init, support.takesUnadvertisedHttpMcp, support.sessionToolBudget,- (left) => { session.toolsLeftOut = () => leftOutToolsNote(left()); });const selectionParams = narrowsNativeTools(turn.toolScope)? support.toolScopeSessionParams!(turn, init, mcpServers.length > 0, { config: turnConfig, env, cwd }) : {};- let loaded = false;+ let loaded = false; const sessionServers = () => acpSessionMcpServers(mcpServers, ownMcp, init, support.takesUnadvertisedHttpMcp, support.sessionToolBudget, (note) => { session.toolsLeftOut = note; });if (cursor && !brokenSessions.has(cursor) && (!support.closeBeforeLiveLoad || liveSessionId !== cursor || await request("session/close", { sessionId: cursor }, 30_000).then(() => { session.sessionId = session.sessionKey = null; return true; }, () => false))) {try {await loadUntilReplayQuiet({diff --git a/server/drivers/agents-assignment-result.ts b/server/drivers/agents-assignment-result.tsnew file mode 100644index 0000000000..b3cbdabf44--- /dev/null+++ b/server/drivers/agents-assignment-result.ts@@ -0,0 +1,47 @@+import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";+import type { Json } from "./agents-client.ts";++const jsonRecord = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);++/** How much of a long result the assignment notice shows before it says where to read on. */+const RESULT_HEAD = 2_000;++/** A long result is read on with tool_result_read, given the assignment's own id: it is kept with the assignment, not in+ * the hour-long saved results, so the tool list stays as it is. */+const readOn = (id: string, offset: number) => `[The result goes on: call tool_result_read with id "${id}" and offset ${offset} to read the next part.]`;++/** One part of a long result, and where the next starts; past the end of what was kept, whether it was all of it. */+export function resultPartLines(part: Json, id: string): string[] {+ const text = typeof part.text === "string" ? part.text : "";+ const offset = Number(part.offset) || 0;+ const end = Number(part.end) || offset;+ const total = Number(part.total) || end;+ const lines = [`Result, characters ${offset}-${end} of ${total}: ${text}`];+ if (text && end < total) lines.push(readOn(id, end));+ else if (part.truncated === true) {+ lines.push(`[truncated: only the first ${end} of ${total} characters of this result were kept; the rest is lost. Tell the person the end of the report is missing; do not present what you read as the whole report.]`);+ } else lines.push("[End of the result: that was all of it.]");+ return lines;+}++/** The result lines of an assignment notice: all of a short result, or its head and where to read on. */+export function assignmentResultLines(a: Json, id: string): string[] {+ const result = typeof a.result === "string" ? a.result : "";+ const total = typeof a.resultChars === "number" ? a.resultChars : result.length;+ if (!result.trim()) return [];+ if (total <= RESULT_HEAD) return [`Result: ${result.trim()}`];+ return [`Result, characters 0-${RESULT_HEAD} of ${total}: ${result.slice(0, RESULT_HEAD)}`, readOn(id, RESULT_HEAD)];+}++/** tool_result_read given an assignment id (any id that is not a saved result's `r-` id): the next part of its result. */+export function isAssignmentResultRead(args: Json): args is Json & { id: string } {+ const offsetOk = args.offset === undefined || (Number.isSafeInteger(args.offset) && Number(args.offset) >= 0);+ return typeof args.id === "string" && !args.id.startsWith("r-") && /^[\w-]{4,64}$/.test(args.id) && offsetOk;+}++export async function readAssignmentResult(args: Json & { id: string }, context: ToolCallContext): Promise<ToolCallResult> {+ const { ok, status, body: r } = await context.client.apiResponse(`/api/internal/assignment-status?id=${encodeURIComponent(args.id)}&offset=${Number(args.offset ?? 0)}`);+ const part = ok && jsonRecord(r.assignment) && jsonRecord(r.assignment.resultPart) ? r.assignment.resultPart : undefined;+ if (!part) return { text: status === 404 ? `No assignment ${args.id} is known here: use the id the last notice gave.` : String(r.error ?? `HTTP ${status}`), isError: true };+ return { text: resultPartLines(part, args.id).join("\n") };+}diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex dece1a6f70..a1b76160b5 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -15,6 +15,7 @@ import { harnessClientFromEnv } from "./agents-client.ts";import type { HarnessClient, Json } from "./agents-client.ts";import { memorySavedText, memorySearchText, threadReadText, threadsListText } from "./memory-search-text.ts";import { apiAnswer, boundedAgentResult } from "./agents-result.ts";+import { assignmentResultLines, isAssignmentResultRead, readAssignmentResult, resultPartLines } from "./agents-assignment-result.ts";import { argumentNames, outOfBounds } from "./agents-schema.ts";import { dropBlankArguments } from "./agents-blank-arguments.ts";import { callResearchTool, RESEARCH_TOOL_NAMES } from "./agents-research-tools.ts";@@ -78,7 +79,6 @@ const STATUS_WORDS: Record<string, string> = {failed: "failed",cancelled: "cancelled",};-const RESULT_HEAD = 2_000;function assignmentLine(a: Json): string {const id = typeof a.id === "string" && a.id ? a.id : "?";@@ -101,13 +101,7 @@ function renderAssignmentStatus(r: Json, id: string): string {}const part = jsonRecord(raw.resultPart) ? raw.resultPart : undefined;if (part) return [lines[0], ...resultPartLines(part, id)].join("\n");- const result = typeof a.result === "string" ? a.result : "";- const total = typeof a.resultChars === "number" ? a.resultChars : result.length;- if (result.trim() && total <= RESULT_HEAD) lines.push(`Result: ${result.trim()}`);- else if (result.trim()) {- lines.push(`Result, characters 0-${RESULT_HEAD} of ${total}: ${result.slice(0, RESULT_HEAD)}`,- readOn(id, RESULT_HEAD));- }+ lines.push(...assignmentResultLines(a, id));const children = Array.isArray(r.children) ? r.children.filter(jsonRecord) : [];if (children.length) lines.push("Its own hand-offs:", ...children.map((child) => `- ${assignmentLine(child)}`));const settled = a.status === "completed" || a.status === "failed" || a.status === "cancelled" || a.status === "done";@@ -115,24 +109,6 @@ function renderAssignmentStatus(r: Json, id: string): string {return lines.join("\n");}-/** A long result is read on with tool_result_read, given the assignment's own id: it is kept with the assignment, not in- * the hour-long saved results, so the tool list stays as it is. */-const readOn = (id: string, offset: number) => `[The result goes on: call tool_result_read with id "${id}" and offset ${offset} to read the next part.]`;--/** One part of a long result, and where the next starts; past the end of what was kept, whether it was all of it. */-function resultPartLines(part: Json, id: string): string[] {- const text = typeof part.text === "string" ? part.text : "";- const offset = Number(part.offset) || 0;- const end = Number(part.end) || offset;- const total = Number(part.total) || end;- const lines = [`Result, characters ${offset}-${end} of ${total}: ${text}`];- if (text && end < total) lines.push(readOn(id, end));- else if (part.truncated === true) {- lines.push(`[truncated: only the first ${end} of ${total} characters of this result were kept; the rest is lost. Tell the person the end of the report is missing; do not present what you read as the whole report.]`);- } else lines.push("[End of the result: that was all of it.]");- return lines;-}-function handoffIds(r: Json): string[] {const receipts = Array.isArray(r.receipts) ? r.receipts.filter(jsonRecord) : [];return receipts.map((receipt) => receipt.requestId).filter((id): id is string => typeof id === "string" && id.trim().length > 0);@@ -299,13 +275,7 @@ export async function callTool(called: string, input: Json, context: ToolCallConreturn { text: JSON.stringify(result) };}if (name === "tool_result_read") {- const offsetOk = args.offset === undefined || (Number.isSafeInteger(args.offset) && Number(args.offset) >= 0);- if (typeof args.id === "string" && !args.id.startsWith("r-") && /^[\w-]{4,64}$/.test(args.id) && offsetOk) {- const { ok, status, body: r } = await apiResponse(`/api/internal/assignment-status?id=${encodeURIComponent(args.id)}&offset=${Number(args.offset ?? 0)}`);- const part = ok && jsonRecord(r.assignment) && jsonRecord(r.assignment.resultPart) ? r.assignment.resultPart : undefined;- if (!part) return { text: status === 404 ? `No assignment ${args.id} is known here: use the id the last notice gave.` : String(r.error ?? `HTTP ${status}`), isError: true };- return { text: resultPartLines(part, args.id).join("\n") };- }+ if (isAssignmentResultRead(args)) return readAssignmentResult(args, context);if (typeof args.id !== "string" || !/^r-[0-9a-f-]{36}$/.test(args.id) ||(args.offset !== undefined && (!Number.isSafeInteger(args.offset) || Number(args.offset) < 0))) {return { text: "Use the saved result id and a non-negative integer offset from its notice.", isError: true };diff --git a/server/drivers/own-mcp-http.ts b/server/drivers/own-mcp-http.tsindex 5b5fe00f26..22ed57dd1b 100644--- a/server/drivers/own-mcp-http.ts+++ b/server/drivers/own-mcp-http.ts@@ -7,7 +7,7 @@// port is the box's bridge to the harness gate (bot-box/harness-gate.ts), which passes /api/internal/ only, and the box// keeps loopback out of its egress proxy (NO_PROXY).import { botBox } from "../bot-box/box.ts";-import { withSessionToolBudget, type LeftOutTools } from "./session-tool-budget.ts";+import { leftOutToolsNote, withSessionToolBudget } from "./session-tool-budget.ts";import { acpOwnServersOverHttp, ownMcpOverHttp, type AcpMcpServer } from "./turn-mcp.ts";/** "1" turns the URL form on for every engine that can take it; "0" keeps every engine on stdio proxies, the ACP agents@@ -79,11 +79,12 @@ export function acpAgentTakesHttpMcp(init: unknown): boolean {* the session's agent takes them, by its `initialize` answer or, for an agent that takes them without saying so, by* `takesUnadvertised`. Deciding here, after `initialize`, lets an agent's first session use the URL form too. An agent* with a session-wide budget for tool definitions (`toolBudget`, by its `initialize` answer) has every server OpenMausBot- * serves or relays share it out, by URL or stdio alike, and `leftOut` is told what their lists leave out to fit it. */+ * serves or relays share it out, by URL or stdio alike, and `leftOut` is given the line that names to the bot what their+ * lists leave out to fit it (none when nothing is). */export function acpSessionMcpServers(servers: AcpMcpServer[], transport: AcpOwnMcpTransport, init: unknown,- takesUnadvertised?: (init: unknown) => boolean, toolBudget?: (init: unknown) => number | undefined, leftOut?: (left: () => LeftOutTools[]) => void): AcpMcpServer[] {+ takesUnadvertised?: (init: unknown) => boolean, toolBudget?: (init: unknown) => number | undefined, leftOut?: (note: () => string | undefined) => void): AcpMcpServer[] {const budget = toolBudget?.(init);- if (budget === undefined) leftOut?.(() => []);- const shared = budget === undefined ? servers : withSessionToolBudget(servers, budget, { leftOut });+ if (budget === undefined) leftOut?.(() => undefined);+ const shared = budget === undefined ? servers : withSessionToolBudget(servers, budget, { leftOut: leftOut && ((left) => leftOut(() => leftOutToolsNote(left()))) });return transport === "advertised" && (acpAgentTakesHttpMcp(init) || takesUnadvertised?.(init) === true) ? acpOwnServersOverHttp(shared) : shared;}