Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
#6461 rework: the safe coordination fixes only
milind-soni25254cde46de
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 0e01244fb9..fa5adcd12d 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -9,6 +9,7 @@ import { extname, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { createCoordinator, type CoordinateBotsCall, type Coordinator, type CoordinatorHost, type HandoffView, type HostTurnResult } from "../coordinator.ts";+import { callTool } from "../drivers/agents-call.ts";import type { RequestAuth } from "../request-auth.ts";import type { SessionRecord } from "../sessions.ts";import type { PassedFile } from "../host/handoff-files.ts";@@ -289,6 +290,78 @@ describe("the link between a computer and its Cloud", () => {expect(computer.results[0]).toMatchObject({ name: "Atlas (My Cloud)", status: "completed", result: "shared did: Which of us is which?" });});+ it("a bot of another place named after a bot's id here in another case never takes that bot's work", async () => {+ const { computer, cloud } = await two();+ cloud.bots.push({ id: "cloud-shadow", name: "SHARED" });+ cloud.link.botsChanged();+ await until(() => computer.link.agents().some((bot) => bot.name === "SHARED"), "the computer hears of the Cloud's SHARED");+ expect(computer.link.resolve("SHARED")).toBeUndefined();+ expect(computer.link.resolve("Shared")).toBeUndefined();+ let asked: CoordinateBotsCall | undefined;+ const { receipts, answer } = await computer.handOff("local-writer", call(["SHARED"], "Which of us is which?"), async (input) => {+ asked = input;+ return { status: 200, body: { receipts: [{ botId: "shared", outcome: "queued", detail: "here" }], message: "Sent to Scout." } };+ });+ expect(asked?.botIds).toEqual(["SHARED"]);+ expect(answer.status).toBe(200);+ expect(receipts).toEqual([{ botId: "shared", outcome: "queued", detail: "here" }]);+ expect(cloud.runs).toEqual([]);+ });++ it("a bot of another place named after the first eight characters of a bot's id here never takes that bot's work", async () => {+ const { computer, cloud } = await two();+ cloud.bots.push({ id: "cloud-prefix", name: "local-wr" });+ cloud.link.botsChanged();+ await until(() => computer.link.agents().some((bot) => bot.name === "local-wr"), "the computer hears of the Cloud's local-wr");+ expect(computer.link.resolve("local-wr")).toBeUndefined();+ expect(computer.link.resolve("LOCAL-WR")).toBeUndefined();+ let asked: CoordinateBotsCall | undefined;+ const { receipts, answer } = await computer.handOff("shared", call(["local-wr"], "Draft the summary"), async (input) => {+ asked = input;+ return { status: 200, body: { receipts: [{ botId: "local-writer", outcome: "queued", detail: "here" }], message: "Sent to Writer." } };+ });+ expect(asked?.botIds).toEqual(["local-wr"]);+ expect(answer.status).toBe(200);+ expect(receipts).toEqual([{ botId: "local-writer", outcome: "queued", detail: "here" }]);+ expect(cloud.runs).toEqual([]);+ });++ it("a bot of another place named after an id here stays reachable by its address, and a name no bot here has still crosses", async () => {+ const { computer, cloud } = await two();+ cloud.bots.push({ id: "cloud-shadow", name: "SHARED" }, { id: "cloud-prefix", name: "local-wr" });+ cloud.link.botsChanged();+ await until(() => computer.link.agents().some((bot) => bot.name === "local-wr"), "the computer hears of both");+ expect(computer.link.resolve(onCloud("cloud-shadow"))?.bot.name).toBe("SHARED");+ expect(computer.link.resolve(onCloud("cloud-prefix"))?.bot.name).toBe("local-wr");+ expect(computer.link.resolve("Analyst")?.bot.id).toBe("cloud-analyst");+ const { receipts: byAddress } = await computer.handOff("shared", call([onCloud("cloud-prefix")], "Draft the summary"));+ expect(byAddress[0]).toMatchObject({ botId: onCloud("cloud-prefix"), outcome: "queued" });+ await until(() => cloud.runs.some((run) => run.botId === "cloud-prefix"), "the Cloud's local-wr works");+ });++ it("a bot here whose id is shaped like another place's address keeps its work, and never becomes that address", async () => {+ const { computer, cloud } = await two();+ // The Cloud's own Atlas answers to exactly this address here; this place is then given a bot of its own carrying it.+ const shaped = onCloud("shared");+ computer.bots.push({ id: shaped, name: "Importer" });+ computer.link.botsChanged();+ // A bot here answers to its own id first, in any case: the address never names the Cloud's Atlas again.+ expect(computer.link.resolve(shaped)).toBeUndefined();+ expect(computer.link.resolve(shaped.toUpperCase())).toBeUndefined();+ // Every other address resolves as it did.+ expect(computer.link.resolve(onCloud("cloud-analyst"))?.bot.id).toBe("cloud-analyst");+ let asked: CoordinateBotsCall | undefined;+ const { receipts, answer } = await computer.handOff("shared", call([shaped], "Draft the summary"), async (input) => {+ asked = input;+ return { status: 200, body: { receipts: [{ botId: shaped, outcome: "queued", detail: "here" }], message: "Sent to Importer." } };+ });+ expect(asked?.botIds).toEqual([shaped]);+ expect(answer.status).toBe(200);+ expect(receipts).toEqual([{ botId: shaped, outcome: "queued", detail: "here" }]);+ // Nothing crossed: the brief and its files stayed with the bot here.+ expect(cloud.runs).toEqual([]);+ });+it("work goes from the computer to the Cloud and its result resumes the requester once, as the person's own work", async () => {const { computer, cloud } = await two();const { receipts, answer } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders", { doneWhen: "a number" }));@@ -309,6 +382,26 @@ describe("the link between a computer and its Cloud", () => {expect(cloud.runs.filter((run) => run.botId === "cloud-analyst").map((run) => run.threadId)).toEqual(["cloud-analyst-work-1", "cloud-analyst-work-1"]);});+ it("a call that got one instruction-only local refusal and one real refusal from the other place fails, and says why", async () => {+ const { computer } = await two();+ const nothingLeft = "nothing of Writer's waits on an answer as a1: it was answered or its work ended. Send it without answers if it still needs doing";+ const localBody = { receipts: [{ botId: "local-writer", botName: "Writer", outcome: "failed", detail: nothingLeft, instructionOnly: true }], error: nothingLeft, instructionOnly: true };+ // "Analyst" lives in the Cloud, where an answer to a question cannot go; "Writer" is here, where the answer named is out of date.+ const { answer } = await computer.handOff("local-writer", call(["Analyst", "Writer"], "Send the numbers.", { answers: "a1" }),+ async () => ({ status: 409, body: localBody }));+ expect(answer.status).toBe(409);+ expect(answer.body.instructionOnly, "one part's instruction to finish is not the whole call's verdict").toBeUndefined();+ expect(String(answer.body.error)).toContain("That does not reach My Cloud yet");+ expect(String(answer.body.error)).toContain(nothingLeft);++ const tool = await callTool("coordinate_bots", { bot_ids: ["Analyst", "Writer"], message: "Send the numbers.", answers: "a1" },+ { botId: "local-writer", threadId: "local-writer-chat", externalRuntime: false, sharedComputers: false,+ client: { apiResponse: async () => ({ ok: false, status: answer.status, body: answer.body }), api: async () => ({}) } });+ expect(tool.isError).toBe(true);+ expect(tool.text).toContain("That does not reach My Cloud yet");+ expect(tool.text).toContain(nothingLeft);+ });+it("work goes from the Cloud to the computer over the same link, and a one-way notice returns nothing", async () => {const { computer, cloud } = await two();await cloud.handOff("cloud-analyst", call(["Writer"], "Draft the summary"));diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex dbe32052c1..1cce865621 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -21,6 +21,7 @@ import { writeFileAtomic } from "../atomic.ts";import type { CoordinateBotsCall, Coordinator, CoordinatorHost, HandoffView, HostTurnResult } from "../coordinator.ts";import type { PassedFile } from "../host/handoff-files.ts";import type { PeerDeliveryReceipt } from "../peer-delivery.ts";+import { isIdStart } from "../peer-roster.ts";import type { Level } from "../runtime/types.ts";import { BRIEF_MAX, EXCHANGE_BYTES, FILES_MAX, LINK_EXPIRES_MS, PEERS_MAX, frameSchema, handoffOfRoot, isLinkedId, linkRoot, linkedBotSchema, linkedId, parseLinked, peerKey, placeSchema,type FileMeta, type FileWay, type Frame, type HandoffFrame, type LinkedBot, type Numbered, type Place, type ResultFrame } from "./protocol.ts";@@ -312,13 +313,16 @@ export function createBotLink(deps: BotLinkDeps) {return address && bot ? { peer: address.peer, bot } : undefined;};const fold = (value: string) => value.replace(/^@/u, "").replace(/[-_]+/gu, " ").replace(/\s+/gu, " ").trim().toLowerCase();- /** The bot of another place `raw` names: by its address here, or by a name no bot here has and only one bot elsewhere has. */+ /** The bot of another place `raw` names: by its address here, or by a name no bot here has and only one bot elsewhere has.+ * A bot's id here, in any case, or the start of one (8+ characters), stays with the local resolver, so a bot elsewhere+ * named after it never takes that bot's work or its files. */function resolve(raw: string): Remote | undefined {if (!state) return undefined;- const wanted = raw.trim();- if (isLinkedId(wanted)) return remoteOf(wanted);+ const wanted = raw.trim(), lower = wanted.toLowerCase();const local = deps.bots();- if (local.some((bot) => bot.id === wanted)) return undefined;+ if (local.some((bot) => bot.id.toLowerCase() === lower)) return undefined;+ if (isLinkedId(wanted)) return remoteOf(wanted);+ if (isIdStart(wanted) && local.some((bot) => bot.id.toLowerCase().startsWith(lower))) return undefined;const named = fold(wanted);if (!named || local.some((bot) => !bot.hidden && fold(bot.name) === named)) return undefined;const matches = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => fold(bot.name) === named).map((bot) => ({ peer, bot })));@@ -674,8 +678,13 @@ export function createBotLink(deps: BotLinkDeps) {const theirs = Array.isArray(rest.body.receipts) ? rest.body.receipts as PeerDeliveryReceipt[] : [];const ok = sent || rest.status === 200;const errors = [...refused, ...(typeof rest.body.error === "string" ? [rest.body.error] : [])];- return { status: ok ? 200 : rest.status, body: { ...rest.body, receipts: [...receipts, ...theirs],- ...(ok ? { message: [mine, rest.body.message].filter(Boolean).join(" "), ...(errors.length ? { notSent: errors.join("; ") } : {}) } : { error: errors.join("; ") }) } };+ // Instruction-only is the whole call's verdict: nothing was delivered anywhere and no refusal of another place is a+ // real failure. One genuine refusal, or a delivery, keeps this a failed call however the local part answered.+ const { instructionOnly: localInstructionOnly, ...restBody } = rest.body;+ const instructionOnly = !ok && refused.length === 0 && localInstructionOnly === true;+ return { status: ok ? 200 : rest.status, body: { ...restBody, receipts: [...receipts, ...theirs],+ ...(ok ? { message: [mine, rest.body.message].filter(Boolean).join(" "), ...(errors.length ? { notSent: errors.join("; ") } : {}) } : { error: errors.join("; ") }),+ ...(instructionOnly ? { instructionOnly: true } : {}) } };}/** Why this call cannot go to another place at all, or null. */function unsupportedHere(call: CoordinateBotsCall, context: CoordinateContext, place: string): string | null {diff --git a/server/cloud-send.test.ts b/server/cloud-send.test.tsindex 082ca1331b..38849443c3 100644--- a/server/cloud-send.test.ts+++ b/server/cloud-send.test.ts@@ -81,7 +81,7 @@ describe("saved Vault secrets in the comparison", () => {});describe("a bot sent from the person's other computer keeps its id", () => {- const store = { bot: (id: string) => (id === "taken-0001" ? ({} as BotRecord) : null), botByThread: (id: string) => (id === "thread-taken" ? ({} as BotRecord) : null), groupByThread: () => undefined };+ const store = { bot: (id: string) => (id === "taken-0001" ? ({} as BotRecord) : null), botByThread: (id: string) => (id === "thread-taken" ? ({} as BotRecord) : null), groupByThread: () => undefined, bots: [] as Array<{ id: string }> };it("takes the server's own id form, only while nothing here uses it", () => {expect(keptBotIds({}, store)).toEqual({});expect(keptBotIds({ id: "ember-0001", threadId: "thread-0001" }, store)).toEqual({ id: "ember-0001", threadId: "thread-0001" });@@ -92,4 +92,21 @@ describe("a bot sent from the person's other computer keeps its id", () => {for (const id of ["short", "../../etc/passwd", "x".repeat(129), 42]) expect(keptBotIds({ id }, store)).toHaveProperty("error");expect(keptBotIds({ threadId: "thread-0001" }, store)).toHaveProperty("error");});++ it("refuses an id shaped like another place's address, so a bot here is never also an address", () => {+ // bot-link/protocol.ts addresses a bot of another place as `link-<that place's key>-<its id there>`.+ for (const id of ["link-0123abcd-local-writer", "LINK-0123abcd-local-writer", "Link-0123abcd-writer"]) {+ expect(keptBotIds({ id }, store), id).toEqual({ error: "id must not begin with \"link-\": that is how a bot in another place is addressed here" });+ }+ // The reserved shape only: an id that merely contains or ends in it is taken as usual.+ for (const id of ["my-link-0001", "linker-00001", "bot-link-0001"]) expect(keptBotIds({ id }, store), id).toEqual({ id });+ });++ it("refuses an id that differs from one here only by case, so no case-variant twin can be brought in beside a bot", () => {+ const here = { bot: () => null, botByThread: () => null, groupByThread: () => undefined, bots: [{ id: "ember-0001-4eea-ac52" }] };+ expect(keptBotIds({ id: "EMBER-0001-4eea-ac52" }, here)).toEqual({ error: "a bot with this id already exists here" });+ expect(keptBotIds({ id: "Ember-0001-4eea-ac52" }, here)).toEqual({ error: "a bot with this id already exists here" });+ // An id that names no bot here, exactly or in another case, is taken as usual.+ expect(keptBotIds({ id: "ember-0002-4eea-ac52" }, here)).toEqual({ id: "ember-0002-4eea-ac52" });+ });});diff --git a/server/drivers/agents-bridge-chat.test.ts b/server/drivers/agents-bridge-chat.test.tsindex a28a560f43..e4b2694aeb 100644--- a/server/drivers/agents-bridge-chat.test.ts+++ b/server/drivers/agents-bridge-chat.test.ts@@ -103,3 +103,60 @@ it("a bridged turn on the chat-completions runtime carries on after use_tool namexpect(completed).toMatchObject({ ok: true });expect(errors).toEqual([]);}, 30_000);++it("does not fail a turn that ends after a hand-off refused only because nothing was left to do", async () => {+ // One whole turn: the bot hands a message to a teammate that no longer waits on an answer, is told so, and finishes.+ const detail = "nothing of Scout's waits on an answer as a1: it was answered or its work ended. Send it without answers if it still needs doing";+ const requests: ChatRequest[] = [];+ const provider = createServer(async (request, response) => {+ if (request.url === "/v1/models") {+ response.setHeader("content-type", "application/json");+ response.end('{"data":[]}');+ return;+ }+ let data = "";+ if (request.method !== "POST") { response.writeHead(404); response.end(); return; }+ for await (const part of request) data += part.toString();+ requests.push(JSON.parse(data) as ChatRequest);+ if (requests.length === 1) calls(response, "call_handoff", "agents_coordinate_bots", { bot_ids: ["bot-scout"], message: "Thanks, looks good", answers: "a1" });+ else sse(response, { content: "Nothing is left to do for @Scout; finishing here." }, "stop");+ });+ // The harness as the proxy reaches it: this hand-off is refused for what is left to do, not for anything that broke.+ const harness = createServer(async (request, response) => {+ let data = "";+ for await (const part of request) data += part.toString();+ response.setHeader("content-type", "application/json");+ if (request.url !== "/api/internal/coordinate-bots") { response.end("{}"); return; }+ response.statusCode = 409;+ response.end(JSON.stringify({ receipts: [{ botId: "bot-scout", outcome: "failed", detail, instructionOnly: true }], error: detail, instructionOnly: true }));+ });+ await new Promise<void>((resolve) => provider.listen(0, "127.0.0.1", resolve));+ await new Promise<void>((resolve) => harness.listen(0, "127.0.0.1", resolve));+ const providerAddress = provider.address(), harnessAddress = harness.address();+ if (!providerAddress || typeof providerAddress === "string" || !harnessAddress || typeof harnessAddress === "string") throw new Error("a fixture did not bind TCP");+ const instance = await OpenAICompatDriver.create({+ instanceId: randomUUID(), displayName: "Refusal fixture", enabled: true,+ config: { url: `http://127.0.0.1:${providerAddress.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY" },+ environment: { FIXTURE_CHAT_KEY: "fixture-key" },+ });+ const recorder = recordEvents(instance.adapter);+ cleanups.push(async () => {+ recorder.stop();+ await instance.dispose();+ for (const server of [provider, harness]) { server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve())); }+ });+ const agents: NonNullable<SendTurnInput["integrations"]>["agents"] = {+ command: process.execPath,+ args: [join(dirname(fileURLToPath(import.meta.url)), "agents-proxy.ts")],+ env: { OMB_HARNESS_URL: `http://127.0.0.1:${harnessAddress.port}`, OMB_BOT_ID: "bot-chat", OMB_THREAD_ID: "thread-chat", OMB_COMMS_TOKEN: "unused" },+ };+ await instance.adapter.sendTurn({ threadId: randomUUID(), text: "Answer Scout's question.", model: "fixture-model", integrations: { agents } });+ const completed = await recorder.until((event) => event.type === "turn.completed");++ // The refusal reached the model as an ordinary result it can read...+ expect(requests[1]!.messages.at(-1)).toMatchObject({ role: "tool", tool_call_id: "call_handoff" });+ expect(JSON.parse(requests[1]!.messages.at(-1)!.content as string)).toEqual({ ok: true, result: detail });+ // ...so the turn it ended on is a success, not "Stopped because the tool call ... failed".+ expect(completed).toMatchObject({ ok: true });+ expect(recorder.events.filter((event) => event.type === "runtime.error")).toEqual([]);+}, 30_000);diff --git a/server/drivers/agents-call.test.ts b/server/drivers/agents-call.test.tsindex d16c29e2da..3902b10d36 100644--- a/server/drivers/agents-call.test.ts+++ b/server/drivers/agents-call.test.ts@@ -554,11 +554,11 @@ describe("coordinate_bots", () => {const calls: Array<{ path: string; body: any }> = [];const result = await callTool("coordinate_bots", args, context({client: {- api: async (path, init) => {+ apiResponse: async (path, init) => {calls.push({ path, body: JSON.parse(String(init?.body)) });- return { id: "a1" };+ return { ok: true, status: 200, body: { receipts: [{ botId: "bot-scout", outcome: "queued", detail: "handed to the coordinator", requestId: "a1" }] } };},- apiResponse: async () => ({ ok: true, status: 200, body: {} }),+ api: async () => { throw new Error("coordinate_bots reads its answer through apiResponse"); },},}));return { result, calls };@@ -576,6 +576,47 @@ describe("coordinate_bots", () => {}});+ it("sends a 6,000-character brief whole, and refuses only past the engine's limit", async () => {+ const brief = "x".repeat(6_000);+ const { result, calls } = await coordinate({ ...BASE, message: brief });+ expect(result.isError).toBeFalsy();+ expect(calls[0]!.body.message).toBe(brief);+ const long = await coordinate({ ...BASE, message: "x".repeat(12_001) });+ expect(long.result.isError).toBe(true);+ expect(long.result.text).toContain("message takes at most 12000 characters");+ expect(long.calls).toEqual([]);+ });++ it("reads a refusal that only says nothing is left to do as a result, not as a failed call", async () => {+ const detail = "nothing of Scout's waits on an answer as a1: it was answered or its work ended. Send it without answers if it still needs doing";+ const body = { receipts: [{ botId: "bot-scout", outcome: "failed", detail, instructionOnly: true }], error: detail, instructionOnly: true };+ const result = await callTool("coordinate_bots", { ...BASE, answers: "a1" }, context({+ client: { apiResponse: async () => ({ ok: false, status: 409, body }), api: async () => ({}) },+ }));+ expect(result.isError).toBeFalsy();+ expect(result.text).toBe(detail);+ });++ it("does not fail the call when every refusal in the batch only says there is nothing left to do", async () => {+ const one = "nothing of Scout's waits on an answer as a1: it was answered or its work ended. Send it without answers if it still needs doing";+ const two = "nothing of Atlas's waits on an answer as a2: it was answered or its work ended. Send it without answers if it still needs doing";+ const receipts = [{ botId: "bot-scout", outcome: "failed", detail: one, instructionOnly: true }, { botId: "bot-atlas", outcome: "failed", detail: two, instructionOnly: true }];+ const result = await callTool("coordinate_bots", { ...BASE, bot_ids: ["bot-scout", "bot-atlas"], answers: "a1" }, context({+ client: { apiResponse: async () => ({ ok: false, status: 409, body: { receipts, error: `${one}; ${two}`, instructionOnly: true } }), api: async () => ({}) },+ }));+ expect(result.isError).toBeFalsy();+ expect(result.text).toBe(`${one}; ${two}`);+ });++ it("still fails the call on a refusal that says something went wrong", async () => {+ const detail = 'No bot with id "bot-ghost" — call list_bots and copy the exact id from the result';+ const result = await callTool("coordinate_bots", BASE, context({+ client: { apiResponse: async () => ({ ok: false, status: 403, body: { receipts: [], error: detail } }), api: async () => ({}) },+ }));+ expect(result.isError).toBe(true);+ expect(result.text).toBe(detail);+ });+it("drops an empty-string group_id instead of posting it", async () => {const { result, calls } = await coordinate({ ...BASE, group_id: "" });expect(result.isError).toBeFalsy();diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex eae3424f82..46df20c9d4 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -14,7 +14,7 @@ import { catalogProfileFromEnv, fullInputSchema, SHARED_COMPUTER_TOOL_NAMES } frimport { harnessClientFromEnv } from "./agents-client.ts";import type { HarnessClient, Json } from "./agents-client.ts";import { memorySearchText } from "./memory-search-text.ts";-import { boundedAgentResult } from "./agents-result.ts";+import { apiAnswer, boundedAgentResult } from "./agents-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";@@ -314,7 +314,7 @@ export async function callTool(called: string, input: Json, context: ToolCallConisError: true,};}- const r = await api("/api/internal/coordinate-bots", { method: "POST", body: JSON.stringify({+ const answer = await apiResponse("/api/internal/coordinate-bots", { method: "POST", body: JSON.stringify({groupId: typeof canonical.group_id === "string" && canonical.group_id.trim() ? canonical.group_id.trim() : undefined, botIds: ids, message: canonical.message,reason: typeof canonical.reason === "string" && canonical.reason.trim() ? canonical.reason.trim() : undefined,rework: canonical.rework,@@ -323,7 +323,7 @@ export async function callTool(called: string, input: Json, context: ToolCallCondone_when: typeof canonical.done_when === "string" && canonical.done_when.trim() ? canonical.done_when.trim() : undefined,answers: typeof canonical.answers === "string" && canonical.answers.trim() ? canonical.answers.trim() : undefined, files: Array.isArray(canonical.files) && canonical.files.some((path) => path.trim()) ? canonical.files.filter((path) => path.trim()) : undefined,}) });- return { text: JSON.stringify(r), ...(r.error ? { isError: true } : {}) };+ return apiAnswer(answer.ok, answer.status, answer.body);}if (name === "assignment_status") {const id = args.id === undefined || args.id === null || args.id === "" ? "" : String(args.id).trim();diff --git a/server/drivers/agents-catalog-goldens/bridged.tools-list.json b/server/drivers/agents-catalog-goldens/bridged.tools-list.jsonindex 342953194a..273bdfecb6 100644--- a/server/drivers/agents-catalog-goldens/bridged.tools-list.json+++ b/server/drivers/agents-catalog-goldens/bridged.tools-list.json@@ -51,7 +51,7 @@"type": "array","items": {"type": "string",- "description": "A teammate's id as list_bots prints it, or its unique name."+ "description": "A teammate's name, preferred, or its id from list_bots; an id's first 8 characters or more work too."}},"message": {diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex db07be8d01..9ddd971320 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -135,7 +135,7 @@"type": "array","items": {"type": "string",- "description": "A teammate's id as list_bots prints it, or its unique name."+ "description": "A teammate's name, preferred, or its id from list_bots; an id's first 8 characters or more work too."}},"message": {diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex 09da4d837b..01da2c966f 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -107,6 +107,9 @@ const TRIGGER_FIELDS_SCHEMA = {run_on_startup: { type: "boolean", description: "Repeating schedules: also run when OpenMausBot starts." },} as const;+/** What the engine keeps of a brief: it clips a longer one instead of refusing the call. */+const MESSAGE_MAX = 12_000;+const CHIEF_PROFILE_TARGET = " A Chief of Staff may pass for_bot_id (from list_bots) for a requested change to another bot in its section.";const APPLIES_AT_ONCE = " It applies at once, with an Undo where possible: read the result before saying it did.";const APPLIES_OUTCOME = APPLIES_AT_ONCE + " It never raises another bot's execution permissions.";@@ -171,8 +174,8 @@ const TOOL_DEFINITIONS = [description: "The one way to hand work on: ask existing OpenMausBot teammates a question or assign them concrete work. Give 1-4 bot_ids from list_bots; they see only what you send, so include constraints and done_when, and pass files they need in files. In a room it goes to this room; elsewhere to your standing work thread with each teammate. Results return here and resume you, so end your turn after sending; on return, verify the outcome and send fixes with rework true. Never target whoever assigned you this work or anyone above it: end your turn and your reply reaches them. Never thank a finished teammate or repeat a refused call unchanged.",inputSchema: { type: "object", additionalProperties: false, properties: {group_id: { type: "string", description: "Another room, from list_room_targets." },- bot_ids: { type: "array", items: { type: "string", description: "A teammate's id as list_bots prints it, or its unique name." }, minItems: 1, maxItems: 4, uniqueItems: true },- message: { type: "string", minLength: 1, maxLength: 4000, description: "The question or task; separate calls for different responsibilities." },+ bot_ids: { type: "array", items: { type: "string", description: "A teammate's name, preferred, or its id from list_bots; an id's first 8 characters or more work too." }, minItems: 1, maxItems: 4, uniqueItems: true },+ message: { type: "string", minLength: 1, maxLength: MESSAGE_MAX, description: "The question or task; separate calls for different responsibilities." },reason: { type: "string", maxLength: 200, description: "Optional one line for the person on why (shown as a chip)." },rework: { type: "boolean", description: "True only to resend finished or failed work: a fix, a re-check or a retry." },thread: { type: "string", description: "standing (default), new (its own history and run), or a threadId from your receipts or list_threads." },diff --git a/server/drivers/agents-result.ts b/server/drivers/agents-result.tsindex 38268d387a..5dde393afd 100644--- a/server/drivers/agents-result.ts+++ b/server/drivers/agents-result.ts@@ -1,5 +1,15 @@import { redactSecretsInText } from "../../shared/redact.ts";import { TOOL_RESULT_MAX_CHARS, TOOL_RESULT_PREVIEW_CHARS, toolResultPrefix } from "../tool-results.ts";+import type { ToolCallResult } from "./agents-call.ts";+import type { Json } from "./agents-client.ts";++/** The internal API's answer as the tool result the model reads. A refusal that only says there is nothing left for this+ * message to do — `instructionOnly`, as coordinate_bots answers a stale `answers` — is an instruction to finish, not a+ * failed call: the bot reads it and ends its turn. Anything that broke stays a failure. */+export function apiAnswer(accepted: boolean, status: number, body: Json): ToolCallResult {+ if (!accepted) return { text: String(body.error ?? `HTTP ${status}`), ...(body.instructionOnly === true ? {} : { isError: true }) };+ return { text: JSON.stringify(body), ...(body.error ? { isError: true } : {}) };+}/** The operation already happened. Saving overflow must never retry it or* turn a successful operation into a failed MCP call. Only cache I/O is timed. */diff --git a/server/drivers/agents-schema.test.ts b/server/drivers/agents-schema.test.tsindex 0a7e4fb9f4..5d8ce5a3f9 100644--- a/server/drivers/agents-schema.test.ts+++ b/server/drivers/agents-schema.test.ts@@ -100,7 +100,7 @@ describe("the advertised agents tool schemas", () => {expect(coordinate.bot_ids).not.toHaveProperty("minItems");expect(coordinate.bot_ids).not.toHaveProperty("uniqueItems");expect(coordinate.message).not.toHaveProperty("maxLength");- expect(fullInputSchema("coordinate_bots")).toMatchObject({ properties: { bot_ids: { minItems: 1, maxItems: 4, uniqueItems: true }, message: { maxLength: 4000 } } });+ expect(fullInputSchema("coordinate_bots")).toMatchObject({ properties: { bot_ids: { minItems: 1, maxItems: 4, uniqueItems: true }, message: { maxLength: 12_000 } } });const schema = { type: "object", additionalProperties: false, properties: {every_minutes: { type: "integer", minimum: 5, maximum: 1_440, description: "Whole minutes, from 5 to 1440." },limit: { type: "integer", minimum: 1, maximum: 25 },@@ -149,11 +149,20 @@ describe("every agents call is held to its full schema", () => {const schema = fullInputSchema("coordinate_bots");expect(outOfBounds("coordinate_bots", schema, { bot_ids: ["a"], message: "hi", title: null, reason: null })).toBeUndefined();const refused = outOfBounds("coordinate_bots", schema, {- bot_ids: ["a", "a", "b", "c", "d"], message: "m".repeat(4_001), title: "t".repeat(81), reason: "r".repeat(201), done_when: "d".repeat(1_001),+ bot_ids: ["a", "a", "b", "c", "d"], message: "m".repeat(12_001), title: "t".repeat(81), reason: "r".repeat(201), done_when: "d".repeat(1_001),})!;expect(refused).toContain("bot_ids takes at most 4 items (it has 5)");expect(refused).toContain("bot_ids must not repeat an item");- expect(refused).toContain("message takes at most 4000 characters (it has 4001)");+ expect(refused).toContain("message takes at most 12000 characters (it has 12001)");expect(refused).toContain("and 2 more");});++ it("takes a brief up to the engine's own limit, and refuses only past it", () => {+ const schema = fullInputSchema("coordinate_bots");+ // The 4,013-6,448-character briefs a bot really sends were refused by the old 4,000 cap.+ expect(outOfBounds("coordinate_bots", schema, { bot_ids: ["a"], message: "m".repeat(6_000) })).toBeUndefined();+ expect(outOfBounds("coordinate_bots", schema, { bot_ids: ["a"], message: "m".repeat(12_000) })).toBeUndefined();+ expect(outOfBounds("coordinate_bots", schema, { bot_ids: ["a"], message: "m".repeat(12_001) }))+ .toBe("coordinate_bots was not run: message takes at most 12000 characters (it has 12001). Fix these and call it again.");+ });});diff --git a/server/host/personal-reach.test.ts b/server/host/personal-reach.test.tsindex 28f68da4c8..f5862d7a17 100644--- a/server/host/personal-reach.test.ts+++ b/server/host/personal-reach.test.ts@@ -50,7 +50,9 @@ describe("a person's own MausBot reaching the team's bots", () => {const unknown = resolveTeammate(bots, mausbot, "Nobody", undefined, undefined, wider());expect(resolveTeammate(bots, mausbot, "Payroll", undefined, undefined, wider())).toEqual({ error: (unknown as { error: string }).error.replaceAll("Nobody", "Payroll") });expect(resolveTeammate(bots, mausbot, "payroll", undefined, undefined, wider())).not.toEqual({ id: "payroll", byName: false });- expect(resolveTeammate(bots, mausbot, "Sales", undefined, undefined, wider())).toEqual({ id: "sales", byName: true });+ // "Sales" is this bot's id in another case, which names it as its id would (byName false).+ expect(resolveTeammate(bots, mausbot, "Sales", undefined, undefined, wider())).toEqual({ id: "sales", byName: false });+ expect(resolveTeammate(bots, mausbot, "@sales", undefined, undefined, wider())).toEqual({ id: "sales", byName: true });});it("refuses a bot its person can only view, and says so", () => {diff --git a/server/host/question-routing.ts b/server/host/question-routing.tsindex 45da5c7d81..8a5b383205 100644--- a/server/host/question-routing.ts+++ b/server/host/question-routing.ts@@ -108,7 +108,7 @@ export function createQuestionRouting(deps: QuestionRoutingDeps) {const pick = input.answers !== undefined ? waiting.find((one) => one.node?.id === input.answers): waiting.find((one) => one.node !== undefined && input.senderNode?.carrying?.includes(one.node.id) === true && (!input.selected || one.threadId === input.threadId))?? waiting.find((one) => ownWork(one.node) && (one.card !== undefined || !one.node.cards?.length));- const refused = () => input.answers === undefined ? undefined : peerDeliveryReceipt({ botId: target.id, botName: target.name, outcome: "failed",+ const refused = () => input.answers === undefined ? undefined : peerDeliveryReceipt({ botId: target.id, botName: target.name, outcome: "failed", instructionOnly: true,detail: `nothing of ${target.name}'s waits on an answer as ${input.answers}: it was answered or its work ended. Send it without answers if it still needs doing` });// A question in words only the person can answer; a wait on a card (a sign-in) is still settled from elsewhere.if (pick && personOnly(pick.question) && !pick.node?.cards?.length) {diff --git a/server/index.ts b/server/index.tsindex 746ddc5a73..ff968b4ac6 100644--- a/server/index.ts+++ b/server/index.ts@@ -117,7 +117,7 @@ import { vpsLeftBehindNotice, vpsNotChosenReason } from "./cloud-backend.ts";import * as composio from "./composio.ts";import { appSandboxRule, connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";import { signInCardText } from "./connector-card-text.ts";-import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";+import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateMessageMax, coordinateTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";import { buildRecall, recallRooms, recallThreadIds, withRecalled } from "./recall.ts";import { hostTimeZone, takesTurnClock, turnClockLine, withTurnClock } from "./turn-clock.ts";import { createMemoryUpkeep, dreamConversations, upkeepEnabled } from "./memory-upkeep.ts";@@ -289,7 +289,7 @@ import type { ProviderInstance } from "./contracts.ts";import { readyToRun, selectDefaultModelSelection, withInstanceConfig, withNewBotEffort, type SelectableInstance } from "./default-model-selection.ts"; import { configIdentity, createTestedAi } from "./tested-ai.ts"; import { instanceLook } from "./provider-icon.ts";import { threadModelFallback, type ThreadEngine } from "./thread-model.ts";import { computerEngineMoveText, removedComputerInstanceIds, writeComputerEngineMoveLines } from "./computer-engine-removal.ts";-import { peerDeliveryReceipt, type PeerDeliveryReceipt } from "./peer-delivery.ts";+import { peerDeliveryReceipt, refusalsOnlyInstructions, type PeerDeliveryReceipt } from "./peer-delivery.ts";import { createRoomAccess, PRIVATE_CHAT_ROOM_WRITE } from "./host/room-access.ts";import { outsideRoomNote, sentRow, teammateResultRow, WAIT_CARD_CLOSED_REASON } from "./host/handoff-sent.ts"; import { createHandoffFiles, handoffFilesSchema, inboxRead, turnsRunInOwnFolder } from "./host/handoff-files.ts";import { createWebhookRoomPost } from "./host/webhook-room-deps.ts";@@ -13724,7 +13724,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {{ senderId: internalSender.id, returns, lanes, awaited: reply !== "none" }) : "";if (EXTERNAL) coordinator.endTurn(generation, { ok: sent, text: sent ? "" : refused.join("; ") });const message = coordinateResultMessage(reply, answeredOnly);- return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: lead ? `${lead} ${message}` : message } : { error: refused.join("; ") }),+ return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: lead ? `${lead} ${message}` : message } : { error: refused.join("; "), ...(refusalsOnlyInstructions(refused, receipts) ? { instructionOnly: true } : {}) }),...(EXTERNAL && sent ? { rootId: generation } : {}) } };}, coordinateBots = (call: CoordinateBotsCall) => botLink.link.coordinate(call, { sender: internalSender, address: { groupId: store.groupByThread(internalCapability.threadId)?.id, threadId: internalCapability.threadId, botId: internalSender.id }, generation: internalCapability.generation, parentId: internalCapability.roomHandoffId, external: EXTERNAL, handed: delegatedThisTurn, problem: linkSourceProblem(internalSender.id, internalCapability.threadId) }, coordinateHere);if (method === "GET" && path === "/api/internal/assignment-status") {@@ -13781,7 +13781,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const parsed = z.object({groupId: z.string().min(1).max(128).optional(),botIds: z.array(z.string().min(1).max(128)).min(1).max(4).refine(ids => new Set(ids).size === ids.length),- message: z.string().trim().min(1).max(4000),+ message: z.string().trim().min(1).max(coordinateMessageMax),reason: z.string().trim().max(200).optional(),rework: z.boolean().default(false),thread: z.string().trim().min(1).max(128).default("standing"), title: z.string().trim().max(80).refine(fitsOnOneLine).optional(),@@ -13790,7 +13790,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {inMyFolder: z.boolean().optional(),done_when: z.string().trim().max(1000).optional(), answers: z.string().trim().min(1).max(128).optional(), files: handoffFilesSchema,}).safeParse(await readInternalBody());- if (!parsed.success) return json(res, 400, { error: coordinateTooLong(parsed.error.issues) ?? "Provide 1-4 distinct botIds and a message of 1-4000 characters; thread is standing, new or the id of a thread you opened on that teammate, title one line of at most 80 characters, reply is resume or none, consult is a boolean, done_when at most 1000 characters, files at most 5 paths." });+ if (!parsed.success) return json(res, 400, { error: coordinateTooLong(parsed.error.issues) ?? `Provide 1-4 distinct botIds and a message of 1-${coordinateMessageMax} characters; thread is standing, new or the id of a thread you opened on that teammate, title one line of at most 80 characters, reply is resume or none, consult is a boolean, done_when at most 1000 characters, files at most 5 paths.` });const { groupId, botIds, message, reason, rework, thread, title, reply, consult, inMyFolder, done_when: doneWhen, answers, files: paths } = parsed.data;const result = await handoffFiles.coordinate({ paths, answers, senderId: internalSender.id, recipients: botIds.length, saveOne: async (path) => saveTurnFile(internalCapability, internalSender.id, await attachmentVmForTurn(internalCapability), path, undefined, true),send: (files) => coordinateBots({ groupId, botIds, message, reason: reason || undefined, rework, thread, title: title || undefined, reply, consult, inMyFolder, doneWhen: doneWhen || undefined, ...(answers ? { answers } : {}), ...(files ? { files } : {}) }) }); refusedHandoffs.settled(internalCapability.threadId, internalSender, botIds, result.status);diff --git a/server/peer-delivery.ts b/server/peer-delivery.tsindex beb5444c36..277bbdcd7f 100644--- a/server/peer-delivery.ts+++ b/server/peer-delivery.ts@@ -9,6 +9,9 @@ export interface PeerDeliveryReceipt {botName?: string;outcome: PeerDeliveryOutcome;detail: string;+ /** A refusal that only says there is nothing left for this message to do: the bot reads it and finishes, and no turn+ * fails on it. Anything that broke stays absent. */+ instructionOnly?: true;taskId?: string;requestId?: string;threadId?: string;@@ -25,6 +28,7 @@ export function peerDeliveryReceipt(receipt: PeerDeliveryReceipt): PeerDeliveryR...(receipt.botName ? { botName: receipt.botName } : {}),outcome: receipt.outcome,detail: clip(receipt.detail, DETAIL_MAX) || "no detail recorded",+ ...(receipt.instructionOnly ? { instructionOnly: true as const } : {}),...(receipt.taskId ? { taskId: receipt.taskId } : {}),...(receipt.requestId ? { requestId: receipt.requestId } : {}),...(receipt.threadId ? { threadId: receipt.threadId } : {}),@@ -36,6 +40,14 @@ export function peerDeliveryReceipt(receipt: PeerDeliveryReceipt): PeerDeliveryRconst named = (receipt: PeerDeliveryReceipt): string =>peerName(receipt.botName ?? "") || peerName(receipt.botId) || "teammate";+/** The coordinate call refused only to say there is nothing left for its message to do: it had a refusal, and every+ * refusal's own words came from a receipt that said so. One part's instruction to finish is not the whole call's+ * verdict, and a receipt that said anything else keeps the call a failure. */+export function refusalsOnlyInstructions(refused: readonly string[], receipts: readonly PeerDeliveryReceipt[]): boolean {+ const instructed = receipts.filter((receipt) => receipt.outcome === "failed" && receipt.instructionOnly === true).map((receipt) => receipt.detail);+ return refused.length > 0 && refused.every((said) => instructed.includes(said));+}+export function renderPeerDeliveryReceipts(receipts: readonly PeerDeliveryReceipt[]): string {if (!receipts.length) return "";const line = (receipt: PeerDeliveryReceipt) => `${named(receipt)}: ${receipt.outcome} — ${receipt.detail}`;diff --git a/server/peer-roster.test.ts b/server/peer-roster.test.tsindex bad806cfd7..78a94211c1 100644--- a/server/peer-roster.test.ts+++ b/server/peer-roster.test.ts@@ -11,6 +11,7 @@ import {LIVE_PEER_ROSTER_MAX,livePeerRoster,livePeerRosterBlock,+ namesTeammate,outsideDepartmentReason,peerAllowed,peerName,@@ -23,6 +24,7 @@ import {roomPeerRosterSystemPrompt,roomRosterLine,teammateAvailabilityPrompt,+ unreachableTeammate,type RosterMember,} from "./peer-roster.ts";import { chiefOfStaffSystemPrompt } from "./chief-of-staff.ts";@@ -247,6 +249,39 @@ describe("resolveTeammate", () => {});});+describe("a teammate named by the start of its id or its id in another case", () => {+ const long: RosterMember[] = [+ self,+ { id: "5f1c9a2e-7b3d-4e8f-9a0b-1c2d3e4f5a6b", name: "Quill", section: "Work" },+ { id: "5f1c9a2e-0000-4e8f-9a0b-1c2d3e4f5a6b", name: "Patch", section: "Work" },+ { id: "9d8e7f6a-1111-4e8f-9a0b-1c2d3e4f5a6b", name: "Scout", section: "Work" },+ ];++ it("takes an id's first 8 characters or more, and an id in any case, as that id", () => {+ expect(resolveTeammate(long, self, "9d8e7f6a")).toEqual({ id: long[3]!.id, byName: false });+ expect(resolveTeammate(long, self, "9D8E7F6A-1111")).toEqual({ id: long[3]!.id, byName: false });+ expect(resolveTeammate(long, self, "5F1C9A2E-7B3D-4E8F-9A0B-1C2D3E4F5A6B")).toEqual({ id: long[1]!.id, byName: false });+ expect(resolveTeammate(long, self, "5f1c9a2e-7b3d")).toEqual({ id: long[1]!.id, byName: false });+ });++ it("refuses a start shared by two ids, and a start under 8 characters, rather than guess", () => {+ expect(resolveTeammate(long, self, "5f1c9a2e")).toEqual({ error: 'More than one bot\'s id starts with "5f1c9a2e", so nothing was sent — call list_bots and copy the exact id from the result' });+ expect(resolveTeammate(long, self, "9d8e7f6")).toMatchObject({ error: expect.stringContaining('No bot with id or name "9d8e7f6"') });+ });++ it("still resolves a name, and never takes a bot its caller may not be told of", () => {+ expect(resolveTeammate(long, self, "Scout")).toEqual({ id: long[3]!.id, byName: true });+ const hides = { reaches: () => false, hides: (bot: RosterMember) => bot.id === long[3]!.id, refusal: () => null };+ expect(resolveTeammate(long, self, "9d8e7f6a", undefined, undefined, hides)).toMatchObject({ error: expect.stringContaining('No bot with id or name "9d8e7f6a"') });+ });++ it("names the same teammate in a routine's refused hand-off", () => {+ expect(namesTeammate(long[3]!, "9D8E7F6A")).toBe(true);+ expect(namesTeammate(long[3]!, "9d8e7f6")).toBe(false);+ expect(unreachableTeammate([...long, { ...long[3]!, id: "77aa88bb-cc", visibility: "admins" }], self, "77AA88BB")?.id).toBe("77aa88bb-cc");+ });+});+describe("peerRosterSystemPrompt", () => {it("names every reachable teammate, its department and how to reach them, granting no new authority", () => {const prompt = peerRosterSystemPrompt(reachablePeers(fleet, self), self);diff --git a/server/peer-roster.ts b/server/peer-roster.tsindex 46933c89de..4e804f7d9c 100644--- a/server/peer-roster.ts+++ b/server/peer-roster.ts@@ -157,10 +157,29 @@ const foldedName = (value: string) => value.replace(/^@/, "").replace(/\s+/g, "// Models slug names they saw ("Reviewer 2" → "reviewer-2").const looseName = (value: string) => foldedName(value.replace(/[-_]+/g, " "));-/** Whether `raw`, as a bot wrote it, means this teammate: its id, or its name however it was typed. */+/** The fewest characters of an id that name it: a model retyping a 36-character id drops one, and the first 8 have to agree. */+export const ID_PREFIX_MIN = 8;++/** Whether a spelling can be the start of an id at all. */+export const isIdStart = (value: string): boolean => value.length >= ID_PREFIX_MIN && !/\s/u.test(value);++/** Whether `raw` is this id in any case, or its first 8 characters or more. */+const startsId = (id: string, raw: string): boolean => isIdStart(raw) && id.toLowerCase().startsWith(raw.toLowerCase());++/** The one bot `raw` names by id when it is not the id exactly: the id in any case, else the start of one. Undefined when+ * no bot's id matches that way; "ambiguous" when more than one does, so a brief never lands on the wrong one. */+export function botById<T extends RosterMember>(bots: readonly T[], raw: string): T | "ambiguous" | undefined {+ const wanted = raw.trim(), lower = wanted.toLowerCase();+ const sameId = bots.filter(bot => bot.id.toLowerCase() === lower);+ const found = sameId.length ? sameId : bots.filter(bot => startsId(bot.id, wanted));+ return found.length > 1 ? "ambiguous" : found[0];+}++/** Whether `raw`, as a bot wrote it, means this teammate: its id (in any case, or its first 8 characters or more), or its+ * name however it was typed. */export function namesTeammate(target: Pick<RosterMember, "id" | "name">, raw: string): boolean {const wanted = raw.trim();- return target.id === wanted || foldedName(target.name) === foldedName(wanted) || looseName(target.name) === looseName(wanted);+ return target.id === wanted || startsId(target.id, wanted) || foldedName(target.name) === foldedName(wanted) || looseName(target.name) === looseName(wanted);}/** Their audiences alone would let `from` reach `target`, whatever its own list of peers says. */@@ -197,6 +216,10 @@ export function resolveTeammate<T extends RosterMember>(const name = fold(wanted);const shown = peerName(wanted) || wanted;if (!name) return { error: `No bot with id "${shown}" — call list_bots and copy the exact id from the result` };+ // The id in another case, or its first 8 characters or more, names that bot as its id would, before any name does.+ const byId = botById(bots.filter(bot => !wider?.hides(bot)), wanted);+ if (byId === "ambiguous") return { error: `More than one bot's id starts with "${shown}", so nothing was sent — call list_bots and copy the exact id from the result` };+ if (byId) return { id: byId.id, byName: false };const reachable = reachablePeers(bots, from, wider?.reaches);const matches = reachable.filter(bot => fold(bot.name) === name);if (matches.length === 1) return { id: matches[0]!.id, byName: true };diff --git a/server/room-coordination.e2e.test.ts b/server/room-coordination.e2e.test.tsindex 8abd8c7b76..282cd9d1b8 100644--- a/server/room-coordination.e2e.test.ts+++ b/server/room-coordination.e2e.test.ts@@ -199,11 +199,11 @@ it("hands work to a bot in another department, into a room whose readers are inexpect((await f.messages(f.source.activeTaskId)).some((m: any) => m.text === "Reviewed downstream outcome")).toBe(true);}), 45_000);-it.each([4000, 4001])("enforces the %i-character request boundary on the real server", length => withRooms(async f => {+it.each([6_000, 12_000, 12_001])("enforces the %i-character request boundary on the real server", length => withRooms(async f => {f.plan[f.sender.id].steps[0].arguments.message = "x".repeat(length);- f.plan[f.sender.id].steps[0].expectError = length > 4000;+ f.plan[f.sender.id].steps[0].expectError = length > 12_000;await f.start(); expect((await f.wait()).status).toBe("settled");- if (length > 4000) expect(f.handoffs()).toEqual([]);+ if (length > 12_000) expect(f.handoffs()).toEqual([]);else expect(f.nodes().find((n: any) => n.parentId).status).toBe("completed");}), 45_000);diff --git a/server/routes/bots-create.ts b/server/routes/bots-create.tsindex 8a2bde2f93..7429c8b61e 100644--- a/server/routes/bots-create.ts+++ b/server/routes/bots-create.ts@@ -1,5 +1,6 @@import type { BotCreateResponse, WireBot } from "../../shared/wire.ts";import { freshLook } from "../bot-look.ts";+import { LINK_PREFIX } from "../bot-link/protocol.ts";import { validateBotCwd } from "../bot-cwd.ts";import { parseBotProfilePatch } from "../bot-profile.ts";import { parseVisibility } from "../bot-visibility.ts";@@ -59,14 +60,24 @@ export interface BotCreateRouteDeps {const OWN_ID = /^[\w-]{8,128}$/;/** A bot sent from the person's other computer keeps its id and its conversation's, so later sends and Bring newer- * chats find it. Only ids in the server's own form, and only while nothing here uses them. */-export function keptBotIds(body: Record<string, unknown>, store: Pick<Store, "bot" | "botByThread" | "groupByThread">): { id?: string; threadId?: string } | { error: string } {+ * chats find it. Only ids in the server's own form, and only while nothing here uses them, compared as the roster compares+ * them: exact case, and case-insensitively too. A bot whose id differs from one here only by case could otherwise be+ * brought in beside it, and every id a teammate writes would then be ambiguous between the two. */+export function keptBotIds(body: Record<string, unknown>, store: Pick<Store, "bot" | "botByThread" | "groupByThread"> & { bots: ReadonlyArray<Pick<BotRecord, "id">> }): { id?: string; threadId?: string } | { error: string } {const { id, threadId } = body;if (id === undefined && threadId === undefined) return {};if (typeof id !== "string" || !OWN_ID.test(id) || (threadId !== undefined && (typeof threadId !== "string" || !OWN_ID.test(threadId)))) {return { error: "id and threadId must be ids of letters, digits, - and _ (8 to 128)" };}+ // This place admits no id shaped like another place's address (`link-<place key>-<id there>`): everything that settles+ // an address reads such an id as a bot elsewhere, so no bot here may carry one. In any case, as this route compares+ // ids case-insensitively too.+ if (id.toLowerCase().startsWith(LINK_PREFIX)) {+ return { error: `id must not begin with "${LINK_PREFIX}": that is how a bot in another place is addressed here` };+ }if (store.bot(id) || store.botByThread(id) || store.groupByThread(id)) return { error: "a bot with this id already exists here" };+ const folded = id.toLowerCase();+ if (store.bots.some(bot => bot.id.toLowerCase() === folded)) return { error: "a bot with this id already exists here" };if (threadId !== undefined && (threadId === id || store.bot(threadId) || store.botByThread(threadId) || store.groupByThread(threadId))) {return { error: "this conversation id is already used here" };}diff --git a/server/too-long.test.ts b/server/too-long.test.tsindex f13124ce9d..9ad50aba8e 100644--- a/server/too-long.test.ts+++ b/server/too-long.test.ts@@ -5,7 +5,7 @@ import { coordinateTooLong, tooLongRefusal } from "./too-long.ts";const shape = z.object({botIds: z.array(z.string()).min(1).max(4),- message: z.string().trim().min(1).max(4000),+ message: z.string().trim().min(1).max(12_000),reason: z.string().trim().max(200).optional(),title: z.string().trim().max(80).optional(),done_when: z.string().trim().max(1000).optional(),@@ -23,8 +23,8 @@ describe("calls refused for length", () => {});it("tells a coordinate_bots caller how to shorten each long field", () => {- expect(refusal({ botIds: ["a"], message: "x".repeat(4001) })).toContain("message is over its 4000-character limit");- expect(refusal({ botIds: ["a"], message: "x".repeat(4001) })).toContain("save the long detail to a file");+ expect(refusal({ botIds: ["a"], message: "x".repeat(12_001) })).toContain("message is over its 12000-character limit");+ expect(refusal({ botIds: ["a"], message: "x".repeat(12_001) })).toContain("save the long detail to a file");expect(refusal({ botIds: ["a"], message: "ok", done_when: "x".repeat(1001) })).toContain("done_when is over its 1000-character limit");expect(refusal({ botIds: ["a"], message: "ok", title: "x".repeat(81) })).toContain("title is over its 80-character limit");});@@ -32,6 +32,6 @@ describe("calls refused for length", () => {it("leaves any other refusal to the general words", () => {expect(refusal({ botIds: ["a", "b", "c", "d", "e"], message: "ok" }), "too many teammates is no length").toBeUndefined();expect(refusal({ botIds: [], message: "" })).toBeUndefined();- expect(refusal({ botIds: ["a", "b", "c", "d", "e"], message: "x".repeat(4001) }), "the general words cover both").toBeUndefined();+ expect(refusal({ botIds: ["a", "b", "c", "d", "e"], message: "x".repeat(12_001) }), "the general words cover both").toBeUndefined();});});diff --git a/server/too-long.ts b/server/too-long.tsindex 1d27e7cf0d..a252aeaeae 100644--- a/server/too-long.ts+++ b/server/too-long.ts@@ -1,6 +1,12 @@// What a bot hears when a call is refused for length: which field, the limit, that nothing happened, and how to send it// again. Without the last part a bot retries the same words or gives up.+import { BRIEF_MAX } from "./bot-link/protocol.ts";++/** The longest brief a coordinate_bots call carries: exactly what the engine keeps of one, so the route refuses nothing+ * the receiver would have kept, and the words below name the same number the catalog gives the tool. */+export const coordinateMessageMax = BRIEF_MAX;+type Issue = { code: string; path: readonly PropertyKey[]; maximum?: number | bigint };export const tooLongRefusal = (field: string, max: number | bigint, how: string): string =>