Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Board: the server hands ready items to free bots; three bot tools (#7411)
Milind Soni07e6de9c6ee8
diff --git a/docs/team-board.md b/docs/team-board.mdindex 2ddcabbfd9..b19138f15c 100644--- a/docs/team-board.md+++ b/docs/team-board.md@@ -7,8 +7,10 @@ thread stands. Nothing new is shown to anyone: a person sees an item exactly wheIt is off unless an Owner or Admin turns on **Board** in Settings → Features (`features.teamBoard` in `config.json`).The switch exists only on a Team Cloud; anywhere else, and while it is off, the routes below answer 404.-This release has the items, their states, the routes and the live frame. Bots taking items, the bot tools, the Board-page and repeating items come later.+The server hands each ready item to a free bot of its room and starts that bot's turn in the item's thread; the bot+settles it with its board tools. There is no Board page: items are read and changed through the routes below and the+bots' tools, and a room thread whose item waits on a person shows as waiting on you, as an open card does. Repeating+items come later.## The item@@ -23,7 +25,9 @@ page and repeating items come later.| `forBotId` | Only this member bot of the room may take it; otherwise any of them. || `holder` | The bot working on it, and since when (while `working` or `needs_person`). || `attempts` | Times a bot took it since it was made or reopened. |-| `question` | What its bot asked a person (while `needs_person`). |+| `question` | What its bot asked a person (while `needs_person`), and whom. |+| `later` | When its bot set it aside to look again, and its note (while `working`). |+| `laterCount` | Times its bot set it aside since it was made or reopened; at most 20. || `result` | What came of it, at most 2,000 characters. || `createdBy` | The person or bot who made it. |@@ -35,7 +39,7 @@ A room holds at most 200 items that are not settled.- A new item is `waiting` while any need is not `done`, else `ready`. A waiting item becomes ready by itself when itslast need is done; a failed or cancelled need readies nothing.-- `ready` → `working`: the server gives it to a bot (later releases).+- `ready` → `working`: the server gives it to a bot (see Dispatch).- `working` → `done`, `failed`, `needs_person` (the bot asked someone) or back to `ready` (released, or the turn endedwithout settling it). `needs_person` → `working` when the person replies, `ready` when a person releases it, or`cancelled`.@@ -45,6 +49,53 @@ A room holds at most 200 items that are not settled.Every other move is refused with 409 `board_bad_move`. The rules are `server/board/state.ts`.+## Dispatch++`server/board/dispatcher.ts`, wired in `server/board/wiring.ts`. It runs on a Team Cloud with the board on, whenever the+board changes, a bot's state changes, the runtime reports a turn's node changed, and on the shared due-timer.++- **Per bot.** A bot runs one room turn at a time and only when idle everywhere. For each `ready` item, oldest first,+ the dispatcher picks its `forBotId`, else the first member bot of the room that is free: not hidden, held, paused,+ awaiting an approval level, busy anywhere, its engine's account not being changed, and holding no other item it is+ working on (an item waiting on a person, or set aside, does not count). No free bot: the item stays ready.+- **Caps first.** Before a start it checks the monthly spend limit and the usage caps as unattended work (nobody+ waiting). A refusal pauses every dispatch until the cap resets; no attempt is counted.+- **Model.** A bot whose engine is missing is passed over for 10 minutes.+- **The turn.** `take` (attempts + 1), then `startGroupTurn` in the item's thread with `@Bot` and the bot as the one+ mention, as unattended work (`trigger: { kind: "bot" }`, never the person's own request), from a sender named Board+ with no person behind it. The line carries the item's title, its thread's first line, what each need came to, and how+ to finish. A start the server refuses hands the item back (or fails it at the third attempt) and waits a minute.+- **The lease is the turn.** An item still `working`, not set aside, whose thread is idle 20 seconds or more after its+ bot took it, lost its turn: back to `ready`, or `failed` with "Stopped after 3 tries" at the third.+- **Restarts.** Nothing is started, and no lease is checked, in the first two minutes after the server starts: the+ runtime re-runs a room turn a restart cut. An item set aside keeps its time across a restart, and a sleeping Cloud+ wakes for it.+- **Maintenance and moves.** It stops with the other timers during maintenance and while the Cloud is moving.+- **Waiting on a person.** `ask` keeps the item's holder and frees the bot. The person's chat line in that thread is+ addressed to the holder (`@Bot ` is put in front unless it already names it), whoever the room's default responder+ is, and the item goes back to `working`. An answer from the person's inbox lands in the thread as the bot's relay line+ and starts no turn by itself: the item then goes back to `working` and the holder is started as soon as it is free,+ with that answer as its line.+- **Set aside.** `later` keeps the item `working` and its holder, frees the bot, and starts the same bot again at the+ time with its own note. It counts no attempt. The 21st `later` on one item fails it.++## Bot tools++Listed only on a Team Cloud with the board on (`OMB_TEAM_BOARD`), in chats and in rooms, deferred for Claude; each is+in the core tool group. The internal routes are `server/routes/board-tools.ts`; a confined turn (work from outside)+cannot reach them.++- `board_add` `{ room?, items: [{ key, title, brief?, needs?, labels?, for? }] }`: 1 to 15 items, each on a new thread of+ the room (default: the room of the turn), the bot's `brief` (or the title) as its first line, written as the bot's.+ `needs` are keys of the same call or item ids of the room; `for` is a bot's name in the room. Everything is checked+ before the first thread opens, so a bad entry leaves nothing behind. Only rooms the bot is a member of.+- `board_list` `{ room?, state? }`: the items of the bot's rooms, one line each, at most 60.+- `board_update` `{ item?, move?, text?, person?, minutes?, labels? }`: the item of this thread unless `item` is given.+ `done` and `failed` take `text` as the result; `ask` posts `text` as the bot's line in the thread and puts it in the+ inbox of `person` (a teammate's name or email), else of the person who made the item; `later` takes `minutes` (1 to+ 1,440) and `text` as the note; `release` hands it back to ready. `labels` replaces them. Only the bot holding an item+ may settle, ask about or set it aside.+## RoutesFor every member and admin who is signed in (`server/routes/board.ts`). Writing needs what writing in the room needs:diff --git a/docs/verification/README.md b/docs/verification/README.mdindex 1acf0ed34c..f3a7fe1043 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -108,6 +108,7 @@ Use only mapped, tested commands:- [Shared-workspace trust: loopback, card answerers, decision log](shared-workspace-trust.md)- [Shared-workspace governance: bot visibility and admin activity](shared-workspace-governance.md)- [Who can see, chat with and change each team bot](team-bot-access.md)+- [The Team Board with a real model](team-board.md)- [Usage ledger](usage-ledger.md)- [Bounded built-in tool results](tool-results.md)- [Memory: recall, upkeep and the tidy-up](memory-layer.md)diff --git a/docs/verification/team-board.md b/docs/verification/team-board.mdnew file mode 100644index 0000000000..0471d319c7--- /dev/null+++ b/docs/verification/team-board.md@@ -0,0 +1,73 @@+# The Team Board with a real model++The contract is [team-board.md](../team-board.md). The tests drive it with the synthetic Claude CLI:++```sh+pnpm exec vitest run server/board server/cloud-team-board.e2e.test.ts server/cloud-team-board-dispatch.e2e.test.ts \+ server/drivers/agents-catalog-wire.test.ts server/drivers/agents-tool-groups.test.ts+```++- `server/board/dispatcher.test.ts`: one bot gets one item at a time and two bots two at once; `forBotId`; a spend cap+ pauses everything and counts no attempt; a bot with no model is passed over for ten minutes; a turn that ends without+ settling hands the item back and the third fails it; nothing starts in the first two minutes or twice; a dependent+ starts once its need is done; a refused start; a person's reply; an inbox answer; `later`.+- `server/cloud-team-board-dispatch.e2e.test.ts`: a Team Cloud whose board waits run 20 times faster+ (`OMB_BOARD_TIME_SCALE=0.05`); the tools are listed only with the switch on; a person's item reaches Writer as+ unattended work (its usage row's trigger is `bot`) and its done result reaches the review that needed it; an ask+ lands in the maker's inbox, the room thread shows waiting on you, and her reply goes to Writer although Reviewer is+ the room's default; `board_add` from Lead; `later`.++What only a real model shows is whether a bot reads its line and uses the tools well. That pass is by hand.++## A throwaway Team Cloud++```sh+# One provider key is enough; only these names cross into the server (scripts/launch-team-board.ts).+export OMB_OPENROUTER_API_KEY=… # or OMB_ANTHROPIC_API_KEY (Claude bots on the API; the claude CLI on PATH), or OMB_OPENAI_API_KEY+# Optional, to wait less: OMB_BOARD_TIME_SCALE=0.1 makes the quiet minutes 12 s, the lease 2 s and a `later` minute 6 s.+node --experimental-strip-types scripts/launch-team-board.ts+```++It makes a temp folder for the server's HOME and data folder (never `~/.openmausbot`), starts a Team Cloud with the board+on, pairs an Owner ([email protected]) and a Member ([email protected]) with the Admin's signed claims, and prints the URL,+both tokens and a header line `H`. Ctrl-C stops it and removes the folder. `--offline` starts it with no network at+all, to check that it starts and pairs.++In a second terminal, with the printed `BASE`, `OWNER`, `MEMBER` and `H`:++```sh+curl -s $H -H "authorization: Bearer $OWNER" $BASE/api/instances | jq '.instances[] | {instanceId, authenticated: .snapshot.authenticated}'+# Three bots on the provider's instance and model, everyone may chat:+for name in Lead Writer Reviewer; do+ curl -s $H -H "authorization: Bearer $OWNER" -X POST $BASE/api/bots \+ -d "{\"name\":\"$name\",\"visibility\":\"everyone\",\"modelSelection\":{\"instanceId\":\"INSTANCE\",\"model\":\"MODEL\"}}" | jq -r '.bot.id'+done+# A room with all three; Lead answers what nobody addresses:+curl -s $H -H "authorization: Bearer $OWNER" -X POST $BASE/api/groups \+ -d '{"name":"Launch","memberIds":["LEAD","WRITER","REVIEWER"],"setup":{"bulletin":"","defaultResponder":{"kind":"member","botId":"LEAD"}}}' | jq '.group | {id, threadId}'+```++## The pass++1. **Lead splits a goal.** As Mira, write in the room's thread: `@Lead Plan our launch post: Writer drafts it, Reviewer+ reviews the draft. Put it on the board with board_add.` Expect two new room threads with items; the review `needs`+ the draft and is `for` Reviewer (`GET /api/board`).+2. **A worker takes it.** About two minutes after the server started (sooner with the scale), the draft goes to Writer:+ its thread gets a line from Board starting `@Writer`, and Writer works there.+3. **Kill it mid-run.** While Writer works, write `@Writer stop` in the draft thread as Mira. Writer's turn stops and+ Writer is held in the room. Within about 20 s the item is `ready` again with `attempts: 1`, and the next free member+ bot (Lead or Reviewer) is started on it (`attempts: 2`); held Writer is not (lift the hold as `server/room-holds.ts` says).+4. **The bot asks.** Tell Writer in the draft thread to ask Mira which date to name before finishing. Expect the item+ `needs_person` with `question.person` Mira's key, Mira's `GET /api/inbox` listing the question, and the room thread's+ `activity` `waiting-on-you`.+5. **The person replies.** As Mira, write in the draft thread: `Friday the 5th.` The line is saved as+ `@Writer Friday the 5th.`; Writer, not Lead, answers, and the item is `working` again. Answer from Mira's inbox+ instead (in the app, or by answering her inbox line) on a second ask: Writer is started with that answer once it is free.+6. **The dependent readies.** When Writer calls `board_update done`, the review becomes `ready` and goes to Reviewer,+ whose line from Board lists what the draft came to.+7. **Later.** Ask a bot to `board_update later` with `minutes: 1` and a note; the item stays `working`, the bot takes+ other items meanwhile, and after a minute the same bot gets a Board line with its note.++Things to look for: each Board line is in the thread's language; the usage page counts these turns as the bot's own+(unattended), never as Mira's request; nothing asks anyone to approve anything; a spend limit set below what is spent+(Settings → Spending) leaves every ready item ready and starts nothing until it is raised.diff --git a/packages/phone-protocol/src/board.ts b/packages/phone-protocol/src/board.tsindex bdd03c987f..9ba0940961 100644--- a/packages/phone-protocol/src/board.ts+++ b/packages/phone-protocol/src/board.ts@@ -21,6 +21,13 @@ export interface BoardItemQuestion {person?: string;}+/** Its bot set the item aside to look again at `at` (board_update later): the item stays `working` and keeps its holder,+ * and the server starts that bot again then with `note`. */+export interface BoardItemLater {+ at: number;+ note: string;+}+export interface BoardItemCreator {kind: "person" | "bot";/** A person key or a bot id. */@@ -44,6 +51,10 @@ export interface BoardItem {/** Times a bot took it since it was made or last reopened. */attempts: number;question?: BoardItemQuestion;+ /** Set while its bot waits to look again. */+ later?: BoardItemLater;+ /** Times its bot set it aside to look again since it was made or last reopened. */+ laterCount?: number;/** What came of it, set when it is settled. */result?: string;createdBy: BoardItemCreator;@@ -65,6 +76,11 @@ export const BOARD_LIMITS = {openPerRoom: 200,/** Items one bot call may add. */itemsPerCall: 15,+ /** board_update later: minutes ahead, and times per item. */+ laterMinutesMax: 1_440,+ latersMax: 20,+ /** Dispatches before a turn that ends without settling the item fails it. */+ triesMax: 3,} as const;/** A label key: lowercase letters, digits, `_` and `-`. */diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 82d85409c3..1ff62cea12 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -91,6 +91,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-away.e2e.test.ts","server/cloud-team-bitwarden.e2e.test.ts","server/cloud-team-board.e2e.test.ts",+ "server/cloud-team-board-dispatch.e2e.test.ts","server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-check-backs.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 8cb96a702c..64bbdc0267 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -231,6 +231,7 @@ describe("CI outputs", () => {"server/cloud-team-away.e2e.test.ts","server/cloud-team-bitwarden.e2e.test.ts","server/cloud-team-board.e2e.test.ts",+ "server/cloud-team-board-dispatch.e2e.test.ts","server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-check-backs.e2e.test.ts",diff --git a/scripts/launch-team-board.ts b/scripts/launch-team-board.tsnew file mode 100644index 0000000000..33b96426f0--- /dev/null+++ b/scripts/launch-team-board.ts@@ -0,0 +1,85 @@+// A throwaway Team Cloud on this computer for a real-model pass over the Team Board (docs/verification/team-board.md).+// Everything lives in a new temp folder (its HOME and its data folder), the board is switched on, an Owner and a Member+// are paired the way the Admin pairs them, and the tokens and a few curl lines are printed. It runs until Ctrl-C and+// then removes the folder. Only the provider keys named below cross from this shell into the server.+// node --experimental-strip-types scripts/launch-team-board.ts [--offline]+// --offline: the server reaches nothing but this computer (a check that it starts and pairs, with no model to answer).+import { spawn } from "node:child_process";+import { randomBytes, randomUUID } from "node:crypto";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { createServer } from "node:net";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { cloudPairingSignature } from "../server/cloud-home.ts";++const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");+const HOST = "omb-team-board.local.test";+const EDGE = { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}` };+const TEAM = { id: "team-board-local", name: "Board test" };+/** The only variables that cross from this shell: provider keys, and the board's test clock if you want it faster. */+const PASS_THROUGH = ["OMB_ANTHROPIC_API_KEY", "OMB_OPENAI_API_KEY", "OMB_OPENROUTER_API_KEY", "OPENAI_COMPAT_API_KEY", "OPENAI_COMPAT_URL",+ "OPENAI_COMPAT_MODEL", "OPENAI_COMPAT_PROVIDER", "OMB_BOARD_TIME_SCALE"];++const freePort = () => new Promise<number>((resolve, reject) => {+ const server = createServer();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => { const { port } = server.address() as { port: number }; server.close(() => resolve(port)); });+});++const root = mkdtempSync(join(tmpdir(), "omb-team-board-"));+const dataDir = join(root, ".openmausbot");+mkdirSync(dataDir, { recursive: true });+writeFileSync(join(dataDir, "config.json"), JSON.stringify({ features: { teamBoard: true } }));+const port = await freePort();+const secret = randomBytes(32).toString("base64url");+const base = `http://127.0.0.1:${port}`;+const passed = Object.fromEntries(PASS_THROUGH.flatMap((name) => process.env[name] ? [[name, process.env[name]!]] : []));+const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline", { status: 503 });')}`;+const child = spawn(process.execPath, [...(process.argv.includes("--offline") ? ["--import", offline] : []), join(ROOT, "server", "index.ts")], {+ cwd: ROOT,+ env: {+ PATH: process.env.PATH, HOME: root, USERPROFILE: root, OMB_DATA_DIR: dataDir, OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1),+ OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: TEAM.id, OMB_CLOUD_TEAM_NAME: TEAM.name, OMB_CLOUD_MACHINE_ID: randomUUID(),+ OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${HOST}`, ...passed,+ },+ stdio: ["ignore", "inherit", "inherit"],+});+const stop = () => { child.kill("SIGTERM"); };+process.on("SIGINT", stop);+process.on("SIGTERM", stop);+child.on("exit", (code) => { rmSync(root, { recursive: true, force: true }); console.log(`\nTeam Cloud stopped (${code ?? "signal"}); removed ${root}`); process.exit(0); });++for (const deadline = Date.now() + 60_000; ;) {+ try { if ((await fetch(`${base}/api/health`)).ok) break; } catch {}+ if (Date.now() > deadline) { console.error("The Team Cloud did not start."); stop(); break; }+ await new Promise((resolve) => setTimeout(resolve, 200));+}++/** A session for one teammate, paired with the Admin's signed claims. */+async function pair(email: string, role: "owner" | "member"): Promise<string> {+ const body = JSON.stringify({ label: "Board test", ttlSeconds: 300, team: TEAM, member: { email, role } });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const minted = await fetch(`${base}/api/cloud/pairing`, { method: "POST", headers: { ...EDGE, "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}` }, body });+ if (!minted.ok) throw new Error(`pairing ${email}: ${minted.status} ${await minted.text()}`);+ const { code } = await minted.json() as { code: string };+ const paired = await fetch(`${base}/api/auth/pair`, { method: "POST", headers: { ...EDGE, "content-type": "application/json" }, body: JSON.stringify({ code }) });+ if (!paired.ok) throw new Error(`pair ${email}: ${paired.status} ${await paired.text()}`);+ return ((await paired.json()) as { token: string }).token;+}++const owner = await pair("[email protected]", "owner");+const member = await pair("[email protected]", "member");+const headers = `-H 'host: ${HOST}' -H 'x-forwarded-proto: https' -H 'x-forwarded-for: 203.0.113.9' -H 'origin: https://${HOST}' -H 'content-type: application/json'`;+console.log(`+Team Cloud with the board on: ${base} (data: ${dataDir})+Provider keys passed: ${Object.keys(passed).join(", ") || "none"}+OWNER=${owner}+MEMBER=${member}+H="${headers.replaceAll('"', '\\"')}"++ curl -s $H -H "authorization: Bearer $OWNER" ${base}/api/instances # engines and their models+ curl -s $H -H "authorization: Bearer $OWNER" ${base}/api/board # the board+Ctrl-C stops it and removes the folder.`);diff --git a/server/agent-tool-policy.test.ts b/server/agent-tool-policy.test.tsindex be4fef3e8c..e76ec42bc7 100644--- a/server/agent-tool-policy.test.ts+++ b/server/agent-tool-policy.test.ts@@ -19,6 +19,7 @@ describe("built-in agent tool read policy", () => {"list_unread_notifications","usage_limits","what_changed",+ "board_list",]);for (const name of READ_ONLY_AGENT_TOOL_NAMES) {expect(isReadOnlyAgentTool(name)).toBe(true);diff --git a/server/agent-tool-policy.ts b/server/agent-tool-policy.tsindex 78a5d3a3e0..924a74eabd 100644--- a/server/agent-tool-policy.ts+++ b/server/agent-tool-policy.ts@@ -16,6 +16,7 @@ export const READ_ONLY_AGENT_TOOL_NAMES: ReadonlySet<string> = new Set(["list_unread_notifications","usage_limits","what_changed",+ "board_list",]);export const READ_ONLY_ANNOTATIONS = Object.freeze({diff --git a/server/agents-turn.ts b/server/agents-turn.tsindex 57b8b2cfa2..f21862ae82 100644--- a/server/agents-turn.ts+++ b/server/agents-turn.ts@@ -18,7 +18,7 @@ export interface AgentsConversation {botDriven?: boolean;/** `x`: a research credential is held (a treg key or a plan's); `research`: research works for it too; `appHosting`:* the plan's included app hosting reaches this server. */- host: { skillAuthoring: boolean; skillBurger?: boolean; sharedComputers: boolean; cloudHome: boolean; team: boolean; voiceNotes: boolean; x: boolean; research: boolean; imageGeneration: boolean; meetings?: boolean; appHosting?: boolean; localVm: boolean };+ host: { skillAuthoring: boolean; skillBurger?: boolean; sharedComputers: boolean; cloudHome: boolean; team: boolean; voiceNotes: boolean; x: boolean; research: boolean; imageGeneration: boolean; meetings?: boolean; appHosting?: boolean; localVm: boolean; board?: boolean };}/** What one turn may do. Its bearer carries this to the harness, which checks it on every call. */@@ -45,7 +45,7 @@ export function agentsServerEnv(conversation: AgentsConversation, turn: AgentsTuOMB_SKILL_BURGER: flag(host.skillBurger !== false),OMB_MEMORY_ENABLED: flag(bot.memoryEnabled !== false),OMB_SHARED_COMPUTERS_ENABLED: flag(host.sharedComputers),- OMB_CLOUD_HOME: flag(host.cloudHome), OMB_TEAM_PEOPLE: flag(host.team), OMB_ROOM: flag(conversation.room),+ OMB_CLOUD_HOME: flag(host.cloudHome), OMB_TEAM_PEOPLE: flag(host.team), OMB_TEAM_BOARD: flag(host.board === true), OMB_ROOM: flag(conversation.room),OMB_VOICE_NOTES: flag(host.voiceNotes),OMB_X_RESEARCH: flag(host.x && bot.xResearch !== false),OMB_RESEARCH: flag(host.x && host.research && bot.xResearch !== false),diff --git a/server/board/dispatcher.test.ts b/server/board/dispatcher.test.tsnew file mode 100644index 0000000000..186723d9e8--- /dev/null+++ b/server/board/dispatcher.test.ts@@ -0,0 +1,308 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { BoardItem } from "../../shared/board.ts";+import { BOARD_LEASE_MS, BOARD_MODEL_SKIP_MS, BOARD_QUIET_MS, createBoardDispatcher, type BoardBrief } from "./dispatcher.ts";+import { createBoard } from "./host.ts";++const T0 = 1_700_000_000_000;+const MIRA = { kind: "person" as const, id: "p_mira", name: "Mira" };+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++/** A board in a temp folder, two rooms, and fake bots whose turns run until `end` is called. */+function harness(options: { bots?: string[]; on?: boolean } = {}) {+ const dir = mkdtempSync(join(tmpdir(), "omb-board-dispatch-"));+ dirs.push(dir);+ const h = {+ clock: T0,+ on: options.on ?? true,+ rooms: new Map<string, { bots: string[]; threads: Set<string> }>([["g1", { bots: options.bots ?? ["scout"], threads: new Set() }]]),+ /** Threads with a turn running now, by bot. */+ running: new Map<string, string>(),+ started: [] as Array<{ threadId: string; botId: string; text: string }>,+ cap: null as { resetsAt: number } | null,+ noModel: new Set<string>(),+ refuse: false,+ opened: 0,+ };+ const board = createBoard({+ dataDir: dir, now: () => h.clock, log: () => {},+ alive: (groupId, threadId) => h.rooms.get(groupId)?.threads.has(threadId) ?? false,+ roomBots: (groupId) => h.rooms.get(groupId)?.bots ?? null,+ });+ const dispatcher = createBoardDispatcher({+ board, on: () => h.on, now: () => h.clock, log: () => {},+ roomBots: (groupId) => h.rooms.get(groupId)?.bots ?? null,+ botFree: (botId) => ![...h.running.values()].includes(botId),+ threadWorking: (_groupId, threadId) => h.running.has(threadId),+ capped: () => h.cap,+ modelReady: (botId) => !h.noModel.has(botId),+ brief: (brief: BoardBrief) => brief.kind === "take" ? `@${brief.botId} take ${brief.item.title}` : `@${brief.botId} wake ${brief.item.title}: ${brief.note}`,+ start: (item, botId, text) => {+ if (h.refuse) throw Object.assign(new Error("finish room setup first"), { status: 409 });+ h.running.set(item.threadId, botId);+ h.started.push({ threadId: item.threadId, botId, text });+ },+ stoppedResult: () => "Stopped after 3 tries",+ });+ const add = (title: string, over: { needs?: string[]; forBotId?: string } = {}): BoardItem => {+ h.clock += 1;+ return board.create({ groupId: "g1", title, createdBy: MIRA, ...over }, () => {+ const threadId = `t${++h.opened}`;+ h.rooms.get("g1")!.threads.add(threadId);+ return threadId;+ });+ };+ /** The bot's turn in `threadId` is over. */+ const end = (threadId: string) => { h.running.delete(threadId); };+ const after = (ms: number) => { h.clock += ms; };+ const pastQuiet = () => { h.clock = T0 + BOARD_QUIET_MS + 1; };+ const state = (threadId: string) => board.get(threadId)!;+ return { h, board, dispatcher, add, end, after, pastQuiet, state };+}++describe("board dispatcher", () => {+ it("starts nothing in the first two minutes after the server starts, then the oldest ready item", async () => {+ const { h, dispatcher, add, after, state } = harness();+ const first = add("Draft the post");+ await dispatcher.tick();+ after(BOARD_QUIET_MS - 10);+ await dispatcher.tick();+ expect(h.started).toEqual([]);+ expect(state(first.threadId).state).toBe("ready");+ after(20);+ await dispatcher.tick();+ expect(h.started).toEqual([{ threadId: first.threadId, botId: "scout", text: "@scout take Draft the post" }]);+ expect(state(first.threadId)).toMatchObject({ state: "working", holder: { botId: "scout" }, attempts: 1 });+ });++ it("gives one bot one item at a time, and two bots two at once", async () => {+ const one = harness();+ const a = one.add("A");+ const b = one.add("B");+ one.pastQuiet();+ await one.dispatcher.tick();+ await one.dispatcher.tick();+ expect(one.h.started.map((start) => start.threadId)).toEqual([a.threadId]);+ expect(one.state(b.threadId).state).toBe("ready");+ one.board.move(a.threadId, { move: "done", result: "ok" }, { kind: "bot", botId: "scout" });+ one.end(a.threadId);+ await one.dispatcher.tick();+ expect(one.h.started.map((start) => start.threadId)).toEqual([a.threadId, b.threadId]);++ const two = harness({ bots: ["scout", "payroll"] });+ const c = two.add("C");+ const d = two.add("D");+ two.pastQuiet();+ await two.dispatcher.tick();+ expect(two.h.started.map((start) => [start.threadId, start.botId])).toEqual([[c.threadId, "scout"], [d.threadId, "payroll"]]);+ });++ it("gives an item for one bot only to that bot, even when another is free", async () => {+ const { h, dispatcher, add, pastQuiet, end, state, board } = harness({ bots: ["scout", "payroll"] });+ const busy = add("Busy work", { forBotId: "payroll" });+ const mine = add("Payroll only", { forBotId: "payroll" });+ pastQuiet();+ await dispatcher.tick();+ expect(h.started.map((start) => [start.threadId, start.botId])).toEqual([[busy.threadId, "payroll"]]);+ expect(state(mine.threadId).state).toBe("ready");+ board.move(busy.threadId, { move: "done" }, { kind: "bot", botId: "payroll" });+ end(busy.threadId);+ await dispatcher.tick();+ expect(h.started.at(-1)).toMatchObject({ threadId: mine.threadId, botId: "payroll" });+ });++ it("pauses everything at a spend cap until it lifts, counting no attempt", async () => {+ const { h, dispatcher, add, pastQuiet, after, state } = harness();+ const item = add("Report");+ pastQuiet();+ h.cap = { resetsAt: h.clock + 3_600_000 };+ await dispatcher.tick();+ expect(h.started).toEqual([]);+ expect(state(item.threadId)).toMatchObject({ state: "ready", attempts: 0 });+ expect(dispatcher.nextDueAt()).toBe(h.cap.resetsAt);+ h.cap = null;+ after(60_000);+ await dispatcher.tick();+ expect(h.started, "still paused until the cap's reset time").toEqual([]);+ after(3_600_000);+ await dispatcher.tick();+ expect(state(item.threadId)).toMatchObject({ state: "working", attempts: 1 });+ });++ it("passes over a bot with no model for ten minutes", async () => {+ const { h, dispatcher, add, pastQuiet, after, state } = harness({ bots: ["scout", "payroll"] });+ const item = add("Report");+ pastQuiet();+ h.noModel.add("scout");+ await dispatcher.tick();+ expect(h.started).toEqual([{ threadId: item.threadId, botId: "payroll", text: "@payroll take Report" }]);+ const other = add("Other", { forBotId: "scout" });+ h.noModel.delete("scout");+ await dispatcher.tick();+ expect(state(other.threadId).state, "scout is still passed over").toBe("ready");+ after(BOARD_MODEL_SKIP_MS);+ await dispatcher.tick();+ expect(state(other.threadId)).toMatchObject({ state: "working", holder: { botId: "scout" } });+ });++ it("hands an item back when its turn ends without settling it, and fails it the third time", async () => {+ const { h, dispatcher, add, pastQuiet, after, end, state } = harness();+ const item = add("Flaky");+ pastQuiet();+ for (let attempt = 1; attempt <= 3; attempt++) {+ await dispatcher.tick();+ expect(state(item.threadId)).toMatchObject({ state: "working", attempts: attempt });+ end(item.threadId);+ after(BOARD_LEASE_MS - 1);+ await dispatcher.tick();+ expect(state(item.threadId).state, "still within the lease").toBe("working");+ after(2);+ await dispatcher.tick();+ if (attempt < 3) expect(state(item.threadId)).toMatchObject({ state: attempt < 3 ? "working" : "failed", attempts: attempt + 1 });+ }+ expect(state(item.threadId)).toMatchObject({ state: "failed", result: "Stopped after 3 tries", attempts: 3 });+ expect(h.started).toHaveLength(3);+ });++ it("never starts an item twice while its turn runs, and does not reconcile during the quiet minutes", async () => {+ const { h, dispatcher, board, add, after, state } = harness();+ const item = add("Long");+ board.move(item.threadId, { move: "take", botId: "scout" }, { kind: "dispatcher" });+ after(BOARD_LEASE_MS * 3);+ await dispatcher.tick();+ expect(state(item.threadId).state, "the runtime's own rerun owns the first minutes").toBe("working");+ h.running.set(item.threadId, "scout");+ after(BOARD_QUIET_MS);+ await dispatcher.tick();+ await dispatcher.tick();+ expect(h.started).toEqual([]);+ expect(state(item.threadId)).toMatchObject({ state: "working", attempts: 1 });+ });++ it("looks at nothing while the switch is off", async () => {+ const { h, dispatcher, add, pastQuiet } = harness({ on: false });+ add("Hidden");+ pastQuiet();+ await dispatcher.tick();+ expect(h.started).toEqual([]);+ expect(dispatcher.nextDueAt()).toBeNull();+ });++ it("stays stopped while maintenance or a move holds it, and runs again on start", async () => {+ const { h, dispatcher, add, pastQuiet } = harness();+ add("Held");+ pastQuiet();+ dispatcher.start();+ dispatcher.stop();+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(h.started).toHaveLength(1);+ const later = add("After the stop");+ dispatcher.poke();+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(h.started.map((start) => start.threadId)).not.toContain(later.threadId);+ });++ it("dispatches a dependent item once what it needs is done", async () => {+ const { h, dispatcher, board, add, pastQuiet, end, state } = harness();+ const first = add("Write");+ const second = add("Review", { needs: [first.threadId] });+ expect(second.state).toBe("waiting");+ pastQuiet();+ await dispatcher.tick();+ board.move(first.threadId, { move: "done", result: "draft.md" }, { kind: "bot", botId: "scout" });+ end(first.threadId);+ expect(state(second.threadId).state).toBe("ready");+ await dispatcher.tick();+ expect(h.started.map((start) => start.threadId)).toEqual([first.threadId, second.threadId]);+ });++ it("hands back an item whose start the server refused, and waits before trying it again", async () => {+ const { h, dispatcher, add, pastQuiet, after, state } = harness();+ const item = add("Refused");+ pastQuiet();+ h.refuse = true;+ await dispatcher.tick();+ expect(state(item.threadId)).toMatchObject({ state: "ready", attempts: 1 });+ h.refuse = false;+ await dispatcher.tick();+ expect(h.started).toEqual([]);+ after(60_000);+ await dispatcher.tick();+ expect(state(item.threadId)).toMatchObject({ state: "working", attempts: 2 });+ });++ it("frees the bot while its item waits on a person, and takes the item back to work when the person answers", async () => {+ const { h, dispatcher, board, add, pastQuiet, end } = harness();+ const asked = add("Needs a client");+ const other = add("Other");+ pastQuiet();+ await dispatcher.tick();+ board.move(asked.threadId, { move: "ask", question: "Which client?" }, { kind: "bot", botId: "scout" });+ end(asked.threadId);+ await dispatcher.tick();+ expect(h.started.map((start) => start.threadId)).toEqual([asked.threadId, other.threadId]);+ expect(dispatcher.personReplied(asked.threadId)).toMatchObject({ state: "working", holder: { botId: "scout" }, attempts: 1 });+ expect(dispatcher.personReplied(asked.threadId), "only once").toBeNull();+ });++ it("brings an inbox answer back to the bot that asked once it is free, counting no attempt", async () => {+ const { h, dispatcher, board, add, pastQuiet, end, state } = harness();+ const asked = add("Needs a client");+ const other = add("Other");+ pastQuiet();+ await dispatcher.tick();+ board.move(asked.threadId, { move: "ask", question: "Which client?" }, { kind: "bot", botId: "scout" });+ end(asked.threadId);+ await dispatcher.tick();+ dispatcher.answered(asked.threadId, "Mira replied: Globex");+ await dispatcher.tick();+ expect(h.started).toHaveLength(2);+ board.move(other.threadId, { move: "done" }, { kind: "bot", botId: "scout" });+ end(other.threadId);+ await dispatcher.tick();+ expect(h.started.at(-1)).toEqual({ threadId: asked.threadId, botId: "scout", text: "@scout wake Needs a client: Mira replied: Globex" });+ expect(state(asked.threadId)).toMatchObject({ state: "working", attempts: 1 });+ expect(state(asked.threadId).later).toBeUndefined();+ });++ it("wakes an item set aside at its time, to the same bot, which may work on others meanwhile", async () => {+ const { h, dispatcher, board, add, pastQuiet, after, end, state } = harness();+ const ci = add("Ship");+ const other = add("Other");+ pastQuiet();+ await dispatcher.tick();+ board.move(ci.threadId, { move: "later", at: h.clock + 5 * 60_000, note: "Check CI" }, { kind: "bot", botId: "scout" });+ end(ci.threadId);+ after(BOARD_LEASE_MS * 2);+ await dispatcher.tick();+ expect(state(ci.threadId)).toMatchObject({ state: "working", later: { note: "Check CI" } });+ expect(h.started.map((start) => start.threadId)).toEqual([ci.threadId, other.threadId]);+ expect(dispatcher.nextDueAt()).toBe(state(ci.threadId).later!.at);+ after(5 * 60_000);+ await dispatcher.tick();+ expect(h.started, "scout is still on the other item").toHaveLength(2);+ board.move(other.threadId, { move: "done" }, { kind: "bot", botId: "scout" });+ end(other.threadId);+ await dispatcher.tick();+ expect(h.started.at(-1)).toEqual({ threadId: ci.threadId, botId: "scout", text: "@scout wake Ship: Check CI" });+ expect(state(ci.threadId)).toMatchObject({ state: "working", attempts: 1, laterCount: 1 });+ });++ it("hands back an item set aside whose bot left the room", async () => {+ const { h, dispatcher, board, add, pastQuiet, after, end, state } = harness({ bots: ["scout", "payroll"] });+ const ci = add("Ship", { forBotId: "scout" });+ pastQuiet();+ await dispatcher.tick();+ board.move(ci.threadId, { move: "later", at: h.clock + 60_000, note: "Check CI" }, { kind: "bot", botId: "scout" });+ end(ci.threadId);+ h.rooms.get("g1")!.bots = ["payroll"];+ after(60_000);+ await dispatcher.tick();+ expect(state(ci.threadId)).toMatchObject({ state: "ready", attempts: 1 });+ expect(state(ci.threadId).later).toBeUndefined();+ });+});diff --git a/server/board/dispatcher.ts b/server/board/dispatcher.tsnew file mode 100644index 0000000000..6d44d40940--- /dev/null+++ b/server/board/dispatcher.ts@@ -0,0 +1,225 @@+// The Team Board's dispatcher: the server, not the bots, hands each ready item to a free member bot of its room and starts+// that bot's turn in the item's thread. A bot runs one room turn at a time and only when idle everywhere, so work is+// scheduled per bot: a bot that is busy, or already holds an item it is working on, gets nothing new. The bot settles the+// item with board_update; a turn that ends without settling it hands the item back (the "lease" is the turn itself), and+// the third such end fails it. Nothing starts in the first minutes after the server starts: the runtime re-runs a room+// turn a restart cut, and owns those minutes.+import { BOARD_LIMITS, type BoardItem } from "../../shared/board.ts";+import { startDueTimer, type DueTimer } from "../due-timer.ts";+import type { Board } from "./host.ts";++/** No dispatch, and no lease check, this long after the server starts. */+export const BOARD_QUIET_MS = 2 * 60_000;+/** A working item whose thread is idle this long after its bot took it lost its turn. */+export const BOARD_LEASE_MS = 20_000;+/** A bot whose model is missing is passed over this long. */+export const BOARD_MODEL_SKIP_MS = 10 * 60_000;+/** An item whose start the server refused waits this long before it is tried again. */+export const BOARD_START_RETRY_MS = 60_000;+/** How often the dispatcher looks again while something waits on a bot or a turn. */+export const BOARD_RETRY_MS = 15_000;++/** What the bot is told: the item handed to it, or the item it set aside (or a person answered) coming back. */+export type BoardBrief = { kind: "take"; item: BoardItem; botId: string } | { kind: "wake"; item: BoardItem; botId: string; note: string };++export interface BoardDispatchDeps {+ board: Pick<Board, "list" | "get" | "move" | "onChange">;+ /** A Team Cloud with `features.teamBoard` on. */+ on(): boolean;+ now?: () => number;+ /** The room's member bots, in the room's order; null for no such room. */+ roomBots(groupId: string): readonly string[] | null;+ /** The bot may start a room turn in this thread now: it exists, is not hidden, held, paused or busy anywhere. */+ botFree(botId: string, groupId: string, threadId: string): boolean;+ threadWorking(groupId: string, threadId: string): boolean;+ /** A spend or usage cap that refuses unattended work for this bot now, and when it lifts. */+ capped(botId: string): { resetsAt: number } | null;+ modelReady(botId: string): boolean;+ brief(brief: BoardBrief): string;+ /** Starts the bot's turn in the item's thread as unattended work; throws when the server refuses to start it. */+ start(item: BoardItem, botId: string, text: string): void;+ /** The result of an item whose turn ended without settling it `BOARD_LIMITS.triesMax` times. */+ stoppedResult(item: BoardItem): string;+ /** Multiplies every wait above; only tests set it. */+ timeScale?: number;+ log?(text: string): void;+}++export function createBoardDispatcher(deps: BoardDispatchDeps) {+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((text: string) => console.error(text));+ const scale = deps.timeScale && deps.timeScale > 0 ? deps.timeScale : 1;+ const quietUntil = now() + BOARD_QUIET_MS * scale;+ const leaseMs = BOARD_LEASE_MS * scale;+ /** Bots passed over until then (a missing model). */+ const skipBot = new Map<string, number>();+ /** Items whose start was refused, until then. */+ const holdItem = new Map<string, number>();+ /** Every dispatch waits until then: a spend or usage cap refused unattended work. */+ let cappedUntil = 0;+ let timer: DueTimer | null = null;+ let running = false;+ // A change only asks for a look: the run itself makes changes, so it never runs inside a listener.+ deps.board.onChange(() => timer?.poke());++ const due = (at: number | undefined, t: number) => at !== undefined && at > t;+ /** The item's bot is on it now: working, not set aside. */+ const active = (item: BoardItem) => item.state === "working" && item.later === undefined;+ const holdsActive = (items: readonly BoardItem[], botId: string) => items.some((item) => active(item) && item.holder?.botId === botId);++ function move(item: BoardItem, change: Parameters<Board["move"]>[1]): BoardItem | null {+ try {+ return deps.board.move(item.threadId, change, { kind: "dispatcher" });+ } catch (error) {+ log(`board: could not ${change.move} item ${item.threadId}: ${String(error)}`);+ return null;+ }+ }++ /** A turn on the item ended, or never started, without settling it: back to ready, or failed after the last try. */+ function lost(item: BoardItem): void {+ if (item.attempts >= BOARD_LIMITS.triesMax) move(item, { move: "failed", result: deps.stoppedResult(item) });+ else move(item, { move: "release" });+ }++ /** Whether all dispatch must wait on a cap for this bot; the pause is the whole board's, and no attempt is counted. */+ function stoppedByCap(botId: string, t: number): boolean {+ const cap = deps.capped(botId);+ if (!cap) return false;+ cappedUntil = Math.max(cap.resetsAt, t + BOARD_RETRY_MS);+ log(`board: a spend or usage cap holds every item until ${new Date(cappedUntil).toISOString()}`);+ return true;+ }++ function startTurn(item: BoardItem, botId: string, text: string, t: number): void {+ try {+ deps.start(item, botId, text);+ } catch (error) {+ log(`board: the turn for item ${item.threadId} did not start: ${String(error)}`);+ holdItem.set(item.threadId, t + BOARD_START_RETRY_MS * scale);+ const current = deps.board.get(item.threadId);+ if (current && current.state === "working") lost(current);+ }+ }++ /** Working items whose turn is over: the thread is idle well after the bot took the item. */+ function reconcile(t: number): void {+ for (const item of deps.board.list({ state: "working" })) {+ if (!active(item) || !item.holder || t - item.holder.since < leaseMs) continue;+ if (deps.threadWorking(item.groupId, item.threadId)) continue;+ lost(item);+ }+ }++ /** Items set aside whose time came, each back to its own bot once that bot is free. False when a cap stopped all work. */+ function wake(t: number): boolean {+ for (const item of deps.board.list({ state: "working" })) {+ if (!item.later || !item.holder || item.later.at > t || due(holdItem.get(item.threadId), t)) continue;+ const botId = item.holder.botId;+ // Its bot left the room: anyone of the room may take it again.+ if (!(deps.roomBots(item.groupId) ?? []).includes(botId)) { move(item, { move: "release" }); continue; }+ if (!deps.botFree(botId, item.groupId, item.threadId) || holdsActive(deps.board.list({ state: "working" }), botId)) continue;+ if (deps.threadWorking(item.groupId, item.threadId)) continue;+ if (stoppedByCap(botId, t)) return false;+ if (!deps.modelReady(botId)) continue;+ const note = item.later.note;+ const woken = move(item, { move: "wake" });+ if (woken) startTurn(woken, botId, deps.brief({ kind: "wake", item: woken, botId, note }), t);+ }+ return true;+ }++ /** Each ready item, oldest first, to its own bot or the first free member bot holding no other item. */+ function dispatch(t: number): void {+ for (const item of deps.board.list({ state: "ready" })) {+ if (due(holdItem.get(item.threadId), t) || deps.threadWorking(item.groupId, item.threadId)) continue;+ const members = deps.roomBots(item.groupId) ?? [];+ const candidates = item.forBotId ? members.filter((id) => id === item.forBotId) : members;+ for (const botId of candidates) {+ if (due(skipBot.get(botId), t)) continue;+ if (!deps.botFree(botId, item.groupId, item.threadId) || holdsActive(deps.board.list({ state: "working" }), botId)) continue;+ if (stoppedByCap(botId, t)) return;+ if (!deps.modelReady(botId)) {+ skipBot.set(botId, t + BOARD_MODEL_SKIP_MS * scale);+ log(`board: no model for bot ${botId}; passed over for ${Math.round(BOARD_MODEL_SKIP_MS * scale / 60_000)} min`);+ continue;+ }+ const taken = move(item, { move: "take", botId });+ if (taken) startTurn(taken, botId, deps.brief({ kind: "take", item: taken, botId }), t);+ break;+ }+ }+ }++ async function tick(): Promise<void> {+ if (running || !deps.on()) return;+ running = true;+ try {+ const t = now();+ if (t < quietUntil) return;+ reconcile(t);+ if (t < cappedUntil) return;+ if (!wake(t)) return;+ dispatch(t);+ } finally {+ running = false;+ }+ }++ /** When the dispatcher must look next: now while anything is ready or a turn may have ended, else the soonest wake. */+ function next(): number | null {+ if (!deps.on()) return null;+ const t = now();+ const open = deps.board.list().filter((item) => item.state === "ready" || item.state === "working");+ if (!open.length) return null;+ if (t < quietUntil) return quietUntil;+ let soonest = Infinity;+ for (const item of open) {+ const at = item.state === "ready" ? Math.max(cappedUntil, holdItem.get(item.threadId) ?? 0)+ : item.later ? Math.max(item.later.at, cappedUntil) : (item.holder?.since ?? t) + leaseMs;+ soonest = Math.min(soonest, at);+ }+ return Number.isFinite(soonest) ? soonest : null;+ }++ return {+ start(): void {+ if (timer) return;+ timer = startDueTimer({ run: () => tick(), next, now, retryMs: BOARD_RETRY_MS * scale, onError: (error) => log(`board: dispatch failed: ${String(error)}`) });+ },+ stop(): void {+ timer?.stop();+ timer = null;+ },+ /** Something changed that may free a bot or end a turn: look again soon. */+ poke(): void {+ timer?.poke();+ },+ tick,+ get isTicking(): boolean { return running; },+ /** When a sleeping Cloud must wake: the soonest item set aside, or the end of a cap's pause while work is ready. */+ nextDueAt(): number | null {+ if (!deps.on()) return null;+ const items = deps.board.list();+ const due = items.flatMap((item) => item.state === "working" && item.later ? [Math.max(item.later.at, cappedUntil)]+ : item.state === "ready" && cappedUntil > now() ? [cappedUntil] : []);+ return due.length ? Math.min(...due) : null;+ },+ /** A person wrote in the item's thread, and that line goes to its bot: the item is worked on again. */+ personReplied(threadId: string): BoardItem | null {+ const item = deps.board.get(threadId);+ return item?.state === "needs_person" && item.holder ? move(item, { move: "resume" }) : null;+ },+ /** A person's answer reached the thread from their inbox, which starts no turn: the item goes back to its bot with+ * that answer as soon as the bot is free. */+ answered(threadId: string, note: string): BoardItem | null {+ const item = deps.board.get(threadId);+ if (item?.state !== "needs_person" || !item.holder) return null;+ const resumed = move(item, { move: "resume", later: { at: now(), note } });+ timer?.poke();+ return resumed;+ },+ };+}++export type BoardDispatcher = ReturnType<typeof createBoardDispatcher>;diff --git a/server/board/state.test.ts b/server/board/state.test.tsindex 0d13076679..bae2175147 100644--- a/server/board/state.test.ts+++ b/server/board/state.test.ts@@ -27,7 +27,7 @@ const inState = (state: BoardItemState): BoardItem => item({const MOVES: Record<BoardMove["move"], BoardMove> = {take: { move: "take", botId: "scout" }, done: { move: "done", result: "Shipped" }, failed: { move: "failed", result: "No access" },ask: { move: "ask", question: "Which client?" }, resume: { move: "resume" }, release: { move: "release" },- cancel: { move: "cancel" }, reopen: { move: "reopen" },+ cancel: { move: "cancel" }, reopen: { move: "reopen" }, later: { move: "later", at: T + 60_000, note: "See CI" }, wake: { move: "wake" },};/** Every move each actor may make, by state: anything not listed is refused. */@@ -36,7 +36,7 @@ const ALLOWED: Record<string, Array<[BoardItemState, BoardMove["move"], BoardAct["ready", "take", DISPATCHER], ["working", "done", DISPATCHER], ["working", "failed", DISPATCHER], ["working", "release", DISPATCHER],["needs_person", "resume", DISPATCHER], ["needs_person", "release", DISPATCHER],],- holder: [["working", "done", HOLDER], ["working", "failed", HOLDER], ["working", "ask", HOLDER], ["working", "release", HOLDER]],+ holder: [["working", "done", HOLDER], ["working", "failed", HOLDER], ["working", "ask", HOLDER], ["working", "release", HOLDER], ["working", "later", HOLDER]],person: [["waiting", "done", PERSON], ["ready", "done", PERSON], ["working", "done", PERSON], ["needs_person", "done", PERSON],["needs_person", "release", PERSON],@@ -193,3 +193,38 @@ describe("fields", () => {expect(() => boardResult(5)).toThrow(BoardError);});});++describe("later", () => {+ const working = inState("working");+ it("keeps the item working with its holder, notes when and why, and counts it", () => {+ const set = applyMove(working, { move: "later", at: T + 300_000, note: " See CI " }, HOLDER, [], T + 1);+ expect(set).toMatchObject({ state: "working", holder: { botId: "scout", since: T }, later: { at: T + 300_000, note: "See CI" }, laterCount: 1, attempts: 0 });+ });+ it("needs a note and a time ahead", () => {+ expect(() => applyMove(working, { move: "later", at: T + 60_000, note: " " }, HOLDER, [], T + 1)).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ expect(() => applyMove(working, { move: "later", at: T, note: "See CI" }, HOLDER, [], T + 1)).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ });+ it(`is refused after ${BOARD_LIMITS.latersMax} times`, () => {+ const many = item({ state: "working", holder: { botId: "scout", since: T }, laterCount: BOARD_LIMITS.latersMax });+ expect(() => applyMove(many, { move: "later", at: T + 60_000, note: "Again" }, HOLDER, [], T + 1)).toThrow(expect.objectContaining({ code: "board_bad_move" }));+ });+ it("wakes only by the dispatcher, back to the same holder, counting no attempt", () => {+ const set = applyMove(working, { move: "later", at: T + 60_000, note: "See CI" }, HOLDER, [], T + 1);+ expect(() => applyMove(set, { move: "wake" }, HOLDER, [], T + 2)).toThrow(expect.objectContaining({ code: "board_bad_move" }));+ const woken = applyMove(set, { move: "wake" }, DISPATCHER, [], T + 60_000);+ expect(woken).toMatchObject({ state: "working", holder: { botId: "scout", since: T + 60_000 }, attempts: 0, laterCount: 1 });+ expect(woken.later).toBeUndefined();+ });+ it("is cleared by every move that settles, releases or asks, and its count by a reopen", () => {+ const set = applyMove(working, { move: "later", at: T + 60_000, note: "See CI" }, HOLDER, [], T + 1);+ for (const move of [MOVES.done, MOVES.failed, MOVES.release, MOVES.ask]) expect(applyMove(set, move, HOLDER, [], T + 2).later).toBeUndefined();+ const done = applyMove(set, MOVES.done, HOLDER, [], T + 2);+ expect(applyMove(done, MOVES.reopen, PERSON, [], T + 3).laterCount).toBeUndefined();+ });+ it("resumes a waiting item with a later the dispatcher starts", () => {+ const asked = inState("needs_person");+ const resumed = applyMove(asked, { move: "resume", later: { at: T + 5, note: "Mira answered" } }, DISPATCHER, [], T + 5);+ expect(resumed).toMatchObject({ state: "working", holder: { botId: "scout", since: T + 5 }, later: { at: T + 5, note: "Mira answered" } });+ expect(resumed.question).toBeUndefined();+ });+});diff --git a/server/board/state.ts b/server/board/state.tsindex 0811df20fc..738116c4eb 100644--- a/server/board/state.ts+++ b/server/board/state.ts@@ -27,7 +27,11 @@ export type BoardMove =| { move: "done"; result?: string }| { move: "failed"; result?: string }| { move: "ask"; question: string; person?: string }- | { move: "resume" }+ /** The holder sets the item aside until `at`; the dispatcher's `wake` starts it again then, with `note`. */+ | { move: "later"; at: number; note: string }+ | { move: "wake" }+ /** With `later`, the holder is started again when it is free rather than by the person's own line. */+ | { move: "resume"; later?: { at: number; note: string } }| { move: "release" }| { move: "cancel"; result?: string }| { move: "reopen" };@@ -117,6 +121,8 @@ function allowed(item: BoardItem, move: BoardMove["move"], actor: BoardActor): bcase "done": return state === "working" ? person || dispatcher || holds(item, actor) : person && isOpen(state);case "failed": return state === "working" && (dispatcher || holds(item, actor));case "ask": return state === "working" && holds(item, actor);+ case "later": return state === "working" && holds(item, actor);+ case "wake": return state === "working" && dispatcher && item.later !== undefined;case "resume": return state === "needs_person" && dispatcher;case "release": return state === "working" ? dispatcher || holds(item, actor) : state === "needs_person" && (person || dispatcher);case "cancel": return isOpen(state) && (person || madeIt(item, actor));@@ -125,7 +131,7 @@ function allowed(item: BoardItem, move: BoardMove["move"], actor: BoardActor): b}const settle = (item: BoardItem, state: BoardItemState, result: string | undefined, now: number): BoardItem => {- const { holder: _holder, question: _question, ...rest } = item;+ const { holder: _holder, question: _question, later: _later, ...rest } = item;return { ...rest, state, ...(result !== undefined ? { result } : {}), updatedAt: now };};@@ -134,7 +140,7 @@ export function applyMove(item: BoardItem, move: BoardMove, actor: BoardActor, iif (!allowed(item, move.move, actor)) throw badMove(`This item is ${item.state.replace("_", " ")}: it cannot be moved to ${move.move} now.`);switch (move.move) {case "take": {- const { question: _question, result: _result, ...rest } = item;+ const { question: _question, result: _result, later: _later, ...rest } = item;return { ...rest, state: "working", holder: { botId: move.botId, since: now }, attempts: item.attempts + 1, updatedAt: now };}case "done":@@ -145,18 +151,32 @@ export function applyMove(item: BoardItem, move: BoardMove, actor: BoardActor, iconst text = typeof move.question === "string" ? move.question.trim() : "";if (!text) throw badInput("Say what you want to ask.");if (text.length > BOARD_LIMITS.questionMax) throw badInput(`A question is at most ${BOARD_LIMITS.questionMax} characters.`);- return { ...item, state: "needs_person", question: { text, askedAt: now, ...(move.person ? { person: move.person } : {}) }, updatedAt: now };+ const { later: _later, ...rest } = item;+ return { ...rest, state: "needs_person", question: { text, askedAt: now, ...(move.person ? { person: move.person } : {}) }, updatedAt: now };+ }+ case "later": {+ const note = typeof move.note === "string" ? move.note.trim() : "";+ if (!note) throw badInput("Say what to look at again.");+ if (note.length > BOARD_LIMITS.questionMax) throw badInput(`A note is at most ${BOARD_LIMITS.questionMax} characters.`);+ if (!Number.isFinite(move.at) || move.at <= now) throw badInput("Pick a time ahead.");+ const count = item.laterCount ?? 0;+ if (count >= BOARD_LIMITS.latersMax) throw badMove(`This item was already set aside ${BOARD_LIMITS.latersMax} times, the most it may be.`);+ return { ...item, later: { at: move.at, note }, laterCount: count + 1, updatedAt: now };+ }+ case "wake": {+ const { later: _later, ...rest } = item;+ return { ...rest, holder: { botId: item.holder!.botId, since: now }, updatedAt: now };}case "resume": {- const { question: _question, ...rest } = item;- return { ...rest, state: "working", holder: { botId: item.holder!.botId, since: now }, updatedAt: now };+ const { question: _question, later: _later, ...rest } = item;+ return { ...rest, state: "working", holder: { botId: item.holder!.botId, since: now }, ...(move.later ? { later: { ...move.later } } : {}), updatedAt: now };}case "release": {- const { holder: _holder, question: _question, ...rest } = item;+ const { holder: _holder, question: _question, later: _later, ...rest } = item;return { ...rest, state: "ready", updatedAt: now };}case "reopen": {- const { holder: _holder, question: _question, result: _result, ...rest } = item;+ const { holder: _holder, question: _question, result: _result, later: _later, laterCount: _laterCount, ...rest } = item;return { ...rest, state: startState(item, items), attempts: 0, updatedAt: now };}}diff --git a/server/board/store.ts b/server/board/store.tsindex 6e6d29088a..a0cd679cbb 100644--- a/server/board/store.ts+++ b/server/board/store.ts@@ -20,6 +20,8 @@ const itemSchema = z.looseObject({holder: z.object({ botId: id, since: z.number() }).optional(),attempts: z.number().int().min(0),question: z.object({ text: z.string(), askedAt: z.number(), person: z.string().optional() }).optional(),+ later: z.object({ at: z.number(), note: z.string() }).optional(),+ laterCount: z.number().int().min(0).optional(),result: z.string().optional(),createdBy: z.object({ kind: z.enum(["person", "bot"]), id: z.string(), name: z.string() }),createdAt: z.number(), updatedAt: z.number(),diff --git a/server/board/wiring.ts b/server/board/wiring.tsindex 48b9d721a3..a7fc63d200 100644--- a/server/board/wiring.ts+++ b/server/board/wiring.ts@@ -1,19 +1,28 @@-// The Team Board as the server runs it: the items, their routes, and a `board.item` frame for every change.+// The Team Board as the server runs it: the items, their routes, a `board.item` frame for every change, the dispatcher+// that hands ready items to free bots, the bots' three tools, and a person's answer taking an item back to work.import type { ResolvedSender } from "../../shared/wire.ts";-import type { BoardItemFrame } from "../../shared/board.ts";+import { BOARD_LIMITS, type BoardItem, type BoardItemFrame } from "../../shared/board.ts";+import { resolveMentions } from "../../shared/room-mentions.ts";+import { queuedChannelSends } from "../channel-queue.ts";import type { VisibleSet } from "../bot-visibility.ts";import type { RequestAuth } from "../request-auth.ts";import { createBoardRoutes, type BoardPerson } from "../routes/board.ts";+import { createBoardToolRoutes } from "../routes/board-tools.ts";+import { conversationLanguage, serverLine } from "../server-lines.ts";import type { Store } from "../store.ts";+import { createBoardDispatcher, type BoardBrief } from "./dispatcher.ts";import { createBoard } from "./host.ts";+/** Brief text of the item's first line the bot is handed; the whole thread is in its context anyway. */+const BRIEF_TEXT_MAX = 2_000;+export interface TeamBoardDeps {dataDir: string;/** A Team Cloud. */team: boolean;/** `features.teamBoard`, read on every request. */enabled(): boolean;- store: Pick<Store, "group" | "groupTaskByThread" | "createGroupTask" | "appendMessage" | "bot">;+ store: Pick<Store, "group" | "groups" | "groupByThread" | "groupTaskByThread" | "createGroupTask" | "patchGroupTask" | "appendMessage" | "messagesFor" | "bot" | "onChange">;visible(auth: RequestAuth): VisibleSet;person(auth: RequestAuth): BoardPerson | null;sender(auth: RequestAuth): ResolvedSender | undefined;@@ -21,22 +30,98 @@ export interface TeamBoardDeps {opened(auth: RequestAuth, threadId: string): void;roomRefusal(groupId: string): string | null;broadcast(payload: Record<string, unknown>): void;+ /** The bot may start a room turn in this thread now: not hidden, held, paused or busy anywhere. */+ botFree(botId: string, groupId: string, threadId: string): boolean;+ threadWorking(groupId: string, threadId: string): boolean;+ /** A spend or usage cap that refuses unattended work for this bot now, and when it lifts. */+ capped(botId: string): { resetsAt: number } | null;+ modelReady(botId: string): boolean;+ /** startGroupTurn with this text, a non-person trigger and the bot as the one mentioned. */+ startTurn(groupId: string, threadId: string, botId: string, text: string, sender: ResolvedSender): void;+ /** Reaches the person's inbox with a bot's question (team-messages.ts `ask`). */+ askPerson(botId: string, threadId: string, to: { name?: string; key?: string }, question: string, title: string): { status: number; text: string; person?: string };+ /** A card in this thread waits on a person (person-waits.ts), which owns the thread's waiting state while it does. */+ cardWaiting(threadId: string): boolean;+ /** Multiplies the dispatcher's waits and a later's minute; only tests set it (OMB_BOARD_TIME_SCALE, up to 1,000). */+ timeScale?: number;}export function createTeamBoard(deps: TeamBoardDeps) {const { store } = deps;+ const on = () => deps.team && deps.enabled();+ const scale = deps.timeScale && deps.timeScale > 0 && deps.timeScale <= 1_000 ? deps.timeScale : 1;+ const memberBots = (groupId: string) => {+ const room = store.group(groupId);+ return room && !room.dm ? room.memberIds : null;+ };const board = createBoard({dataDir: deps.dataDir,alive: (groupId, threadId) => Boolean(store.groupTaskByThread(groupId, threadId)),- roomBots: (groupId) => {- const room = store.group(groupId);- return room && !room.dm ? room.memberIds : null;- },+ roomBots: memberBots,});board.onChange((change) => deps.broadcast({ kind: "board.item", ...change } satisfies BoardItemFrame));+ const line = (threadId: string, key: Parameters<typeof serverLine>[1], params?: Record<string, string | number>) => serverLine(conversationLanguage(threadId), key, params);+ const botName = (botId: string) => store.bot(botId)?.name ?? botId;++ /** The bot's first line for an item: its title, its thread's first line, what its needs came to, and how to finish. */+ function brief(given: BoardBrief): string {+ const { item, botId } = given;+ if (given.kind === "wake") return line(item.threadId, "server.board.wake", { bot: botName(botId), title: item.title, note: given.note });+ const first = store.messagesFor(item.threadId).find((message) => message.kind === "text" && message.text?.trim())?.text?.trim() ?? item.title;+ const text = first.length > BRIEF_TEXT_MAX ? `${first.slice(0, BRIEF_TEXT_MAX - 1)}…` : first;+ const needs = item.needs.map((id) => board.get(id)).filter((need): need is BoardItem => Boolean(need))+ .map((need) => `- ${need.title}: ${need.result ?? need.state}`);+ const body = line(item.threadId, "server.board.brief", { bot: botName(botId), title: item.title, text });+ return needs.length ? `${body}\n\n${line(item.threadId, "server.board.briefNeeds", { results: needs.join("\n") })}` : body;+ }++ const dispatcher = createBoardDispatcher({+ board, on, timeScale: scale,+ roomBots: memberBots,+ botFree: deps.botFree,+ // A person's line queued behind a running turn starts the next one there: the thread is still at work.+ threadWorking: (groupId, threadId) => deps.threadWorking(groupId, threadId) || queuedChannelSends(threadId) > 0,+ capped: deps.capped,+ modelReady: deps.modelReady,+ brief,+ start: (item, botId, text) => deps.startTurn(item.groupId, item.threadId, botId, text, { name: line(item.threadId, "server.board.sender") }),+ stoppedResult: (item) => line(item.threadId, "server.board.stopped", { count: BOARD_LIMITS.triesMax }),+ });++ /** A needs_person item shows on its room thread as waiting on a person, as an open card does. */+ function showWaiting(item: BoardItem | null, groupId: string, threadId: string): void {+ const task = store.groupTaskByThread(groupId, threadId);+ if (!task) return;+ const waiting = item?.state === "needs_person";+ if (waiting && task.activity !== "waiting-on-you") store.patchGroupTask(groupId, threadId, { activity: "waiting-on-you" });+ else if (!waiting && task.activity === "waiting-on-you" && !deps.cardWaiting(threadId)) store.patchGroupTask(groupId, threadId, { activity: null });+ }+ board.onChange((change) => showWaiting(change.item, change.groupId, change.threadId));++ store.onChange((change) => {+ if (!on()) return;+ // A bot freed somewhere may take a ready item.+ if (change.type === "bot") { dispatcher.poke(); return; }+ // A person's answer from their inbox lands in the room thread as the asking bot's relay line and starts no turn.+ if (change.type !== "message") return;+ const message = change.message;+ if (message.role !== "bot" || message.kind !== "text" || !message.relay || (message.relay.kind !== "reply" && message.relay.kind !== "assistant")) return;+ const item = board.get(change.threadId);+ if (item?.state === "needs_person" && item.holder?.botId === message.from?.botId) dispatcher.answered(change.threadId, message.text ?? "");+ });++ /** `text` addressed to the bot holding the thread's item, unless it already names that bot. */+ function addressedTo(groupId: string, threadId: string, text: string, states: readonly BoardItem["state"][]): { text: string; botId: string } | null {+ if (!on()) return null;+ const item = board.get(threadId);+ const bot = item?.holder ? store.bot(item.holder.botId) : null;+ if (!item || item.groupId !== groupId || !states.includes(item.state) || !bot || bot.hidden || !memberBots(groupId)?.includes(bot.id)) return null;+ const named = resolveMentions(text, [bot]).bots.length > 0;+ return { text: named ? text : `@${bot.name} ${text}`, botId: bot.id };+ }+const routes = createBoardRoutes({- board,- on: () => deps.team && deps.enabled(),+ board, on,person: deps.person,visible: deps.visible,room: (groupId) => {@@ -54,7 +139,55 @@ export function createTeamBoard(deps: TeamBoardDeps) {return task.threadId;},});- return { board, routes };++ return {+ board, routes, dispatcher,+ /** The bots' tools, for one internal request: its capability's bot and thread. */+ toolRoutes: (turn: { requireActive(): void; botId(): string; threadId(): string; readBody(): Promise<unknown> }) => createBoardToolRoutes({+ ...turn, board, on, minuteMs: 60_000 * scale,+ botName: (botId) => store.bot(botId)?.name,+ rooms: (botId) => store.groups.filter((room) => !room.dm && room.memberIds.includes(botId)).map((room) => ({ id: room.id, name: room.name, memberIds: room.memberIds })),+ roomOf: (threadId) => {+ const room = store.groupByThread(threadId);+ return room && !room.dm && store.groupTaskByThread(room.id, threadId) ? { id: room.id, name: room.name, memberIds: room.memberIds } : null;+ },+ openThread: (groupId, title, text, botId) => {+ const task = store.createGroupTask(groupId, title, false);+ if (!task) throw new Error(`could not open a thread in room ${groupId}`);+ const bot = store.bot(botId);+ store.appendMessage(task.threadId, { role: "bot", kind: "text", text, ...(bot ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {}) });+ return task.threadId;+ },+ ask: (botId, threadId, question, to) => {+ const bot = store.bot(botId);+ const item = board.get(threadId);+ if (bot) store.appendMessage(threadId, { role: "bot", kind: "text", text: question, from: { botId: bot.id, name: bot.name, color: bot.color } });+ if (!to.name && !to.key) return { ok: false, text: "Nobody made this item to ask, so the question waits in this thread for anyone who sees it." };+ const asked = deps.askPerson(botId, threadId, to, question, line(threadId, "server.board.askTitle", { bot: bot?.name ?? botId, title: item?.title ?? "" }));+ return { ok: asked.status === 200, text: asked.text, ...(asked.person ? { person: asked.person } : {}) };+ },+ tooManyLaters: (threadId) => line(threadId, "server.board.tooManyLaters", { count: BOARD_LIMITS.latersMax }),+ }),+ /** A person's chat line in a room thread whose item waits on a person: addressed to the bot that asked, with the move+ * that takes the item back to work once the line is sent. Null for every other line. */+ reply(groupId: string, threadId: string, text: string): { text: string; botId: string; resume(): void } | null {+ const addressed = addressedTo(groupId, threadId, text, ["needs_person"]);+ return addressed ? { ...addressed, resume: () => { dispatcher.personReplied(threadId); } } : null;+ },+ /** What a resent line may have been saved as: addressed to the item's bot. */+ addressed(groupId: string, threadId: string, text: string): string | null {+ return addressedTo(groupId, threadId, text, ["needs_person", "working"])?.text ?? null;+ },+ start(): void {+ dispatcher.start();+ // A restart cleared every room thread's waiting state (person-waits.ts boot): items that still wait show it again.+ for (const item of board.list({ state: "needs_person" })) showWaiting(item, item.groupId, item.threadId);+ },+ stop(): void { dispatcher.stop(); },+ get isTicking(): boolean { return dispatcher.isTicking; },+ nextDueAt: () => dispatcher.nextDueAt(),+ poke: () => dispatcher.poke(),+ };}export type TeamBoard = ReturnType<typeof createTeamBoard>;diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex c7d914be48..15678d3341 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -55,7 +55,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_THREAD_CACHE_MB", "OMB_THREAD_LOG_CAP", "OMB_THREAD_LOG_CUT", "OMB_THREAD_LOG_SWEEP", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE","OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURNS_MAX_RUNNING", "OMB_TURN_STALL_MS", "OMB_UNATTENDED_TURN_MAX_DENIALS", "OMB_UNATTENDED_TURN_MAX_MS", "OMB_UNATTENDED_TURN_MAX_REQUESTS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL","OMB_USAGE_CAP_DAILY_TOKENS", "OMB_USAGE_CAP_DAILY_USD", "OMB_USAGE_CAP_MONTHLY_TOKENS", "OMB_USAGE_CAP_MONTHLY_USD",- "OMB_USAGE_CAP_STOPS", "OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET",+ "OMB_USAGE_CAP_STOPS", "OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_BOARD_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET","OMB_WORKERS_AI_TOKEN", "OMB_XAI_TTS_API","OMB_BURST_PART_MAX_RESTARTS", "OMB_CHIEF_INCIDENT_TURNS_PER_HOUR", "OMB_ROUTINE_FAILURES_BEFORE_SPACING", "OMB_ROUTINE_FAILURE_SPACING_MAX_MS","OMB_ROUTINE_FAILURE_SPACING_MS", "OMB_ROUTINE_GOAL_RUN_LIMIT_HOURS", "OMB_ROUTINE_RESTART_STAGGER_MS", "OMB_ROUTINE_RUN_LIMIT_HOURS",diff --git a/server/bot-box/env.ts b/server/bot-box/env.tsindex 57cd15bf6c..f6b14f44d3 100644--- a/server/bot-box/env.ts+++ b/server/bot-box/env.ts@@ -25,7 +25,7 @@ export const BOX_SSH_CONNECTION = "127.0.0.1 0 127.0.0.1 0";export const BOX_ENV_OMB_NAMES: ReadonlySet<string> = new Set(["OMB_HARNESS_URL", "OMB_BOT_ID", "OMB_THREAD_ID", "OMB_COMMS_TOKEN", "OMB_EXTERNAL_RUNTIME","OMB_CHIEF_OF_STAFF", "OMB_MAUSBOT", "OMB_SKILL_AUTHORING_ENABLED", "OMB_SKILL_BURGER", "OMB_MEMORY_ENABLED", "OMB_SHARED_COMPUTERS_ENABLED",- "OMB_VOICE_NOTES", "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_COMPUTER_SELECTION", "OMB_ROOM",+ "OMB_VOICE_NOTES", "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_TEAM_BOARD", "OMB_COMPUTER_SELECTION", "OMB_ROOM","OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", "OMB_LOCAL_VM", "OMB_AGENTS_TOOL_BRIDGE", "OMB_AGENTS_DEFER_TOOLS", "OMB_TOOL_LIMIT", "OMB_TOOL_SCHEMA_PROFILE","OMB_MCP_CONFIG", "OMB_MCP_RESTART", "OMB_MCP_RESULT_BUDGET","OMB_HOOK_URL", "OMB_HOOK_TOKEN_FILE", "OMB_HOOK_TIMEOUT_MS", "OMB_PERMISSION_TOOL_SCOPE",diff --git a/server/cloud-team-board-dispatch.e2e.test.ts b/server/cloud-team-board-dispatch.e2e.test.tsnew file mode 100644index 0000000000..b64a590c43--- /dev/null+++ b/server/cloud-team-board-dispatch.e2e.test.ts@@ -0,0 +1,237 @@+// The Team Board handing work to bots on a real Team Cloud: Olive (the Owner) and Mira (a Member), and the Launch room+// with Writer, Reviewer and Lead, whose default responder is Reviewer. The synthetic Claude CLI plays each bot's part by+// calling the board tools through the real agents MCP server, keyed by a word of the turn's newest line. The board's+// waits run at a twentieth of their length (OMB_BOARD_TIME_SCALE): two quiet minutes are six seconds, a minute of+// `later` three. It proves what is started, for whom and with what, not a model's judgement.+import { randomBytes } from "node:crypto";+import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import type { BoardItem } from "../shared/board.ts";+import { personKey } from "./person-key.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OLIVE = { email: "[email protected]", role: "owner" as const };+const MIRA = { email: "[email protected]", role: "member" as const };+const ENGINE = `const dir = process.env.FAKE_CLAUDE_FIXTURE_DIR;+process.env.FAKE_CLAUDE_DUMP = dir + "/dump.json";+process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = dir + "/tool-calls.json";+process.env.FAKE_CLAUDE_MARKERS_LATEST = "1";+process.env.FAKE_CLAUDE_RELEASE = dir + "/release";`;++type Bot = { id: string; name: string; threadId: string };+type Room = { id: string; threadId: string };+type Line = { id: string; role: string; kind: string; text?: string; sender?: { name: string; id?: string }; from?: { botId: string } };++let fx: CloudSendFixture, team: CloudTeamFixture;+let olive = "", mira = "";+let writer: Bot, reviewer: Bot, lead: Bot, launch: Room;++const file = (name: string) => join(team.home, name);+/** Each bot's part, by a word of its turn's newest line; the first word found wins. */+const parts = (calls: Record<string, unknown[]>) => writeFileSync(file("tool-calls.json"), JSON.stringify(calls));+const update = (input: Record<string, unknown>) => ({ name: "board_update", server: "agents", input });+const messages = async (token: string, threadId: string) => (await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as Line[];+const board = async (token: string) => (await team.as(token, "GET", "/api/board")).body.items as BoardItem[];+const item = async (threadId: string) => (await board(olive)).find((one) => one.threadId === threadId)!;+const add = async (token: string, body: Record<string, unknown>) => {+ const made = await team.as(token, "POST", "/api/board/items", body);+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ return made.body.item as BoardItem;+};+/** The usage rows the Team Cloud booked for one thread. */+const usageRows = (threadId: string) => {+ const dir = join(team.home, ".openmausbot", "usage");+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter((name) => /^\d{4}-\d{2}\.jsonl$/.test(name)).flatMap((name) => readFileSync(join(dir, name), "utf8").split("\n").filter(Boolean).map((row) => JSON.parse(row) as { threadId: string; botId: string; trigger: { kind: string } }))+ .filter((row) => row.threadId === threadId);+};++async function until(done: () => Promise<boolean> | boolean, what: string, timeoutMs = 60_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error(`timed out waiting: ${what}\n${fx.logs().slice(-6_000)}`);+ await new Promise((resolve) => setTimeout(resolve, 150));+ }+}+const settled = (threadId: string, state: BoardItem["state"]) => until(async () => (await item(threadId)).state === state, `${threadId} ${state}`);++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-board-dispatch-${randomBytes(8).toString("hex")}`,+ team: { id: "team-acme-board-dispatch", name: "Acme", engine: ENGINE, env: { OMB_BOARD_TIME_SCALE: "0.05" } } });+ team = fx.team!;+ olive = (await team.pair(OLIVE)).token!;+ mira = (await team.pair(MIRA)).token!;+ parts({});+ const bot = async (name: string) => {+ const made = await team.as(olive, "POST", "/api/bots", { name, visibility: "everyone" });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ return made.body.bot as Bot;+ };+ writer = await bot("Writer");+ reviewer = await bot("Reviewer");+ lead = await bot("Lead");+ const made = await team.as(olive, "POST", "/api/groups", { name: "Launch", memberIds: [writer.id, reviewer.id, lead.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: reviewer.id } } });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ launch = made.body.group as Room;+}, hostTimeout(180_000));++afterAll(async () => {+ await fx?.close();+});++it("lists no board tools while the switch is off, and refuses their calls", async () => {+ rmSync(file("dump.json"), { force: true });+ const sent = await team.as(olive, "POST", `/api/bots/${writer.id}/messages`, { text: "Hello", threadId: writer.threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await until(() => existsSync(file("dump.json")), "a turn");+ const env = () => JSON.parse(readFileSync(file("dump.json"), "utf8")).mcpConfig?.mcpServers?.agents?.env as Record<string, string>;+ expect(env().OMB_TEAM_BOARD).toBe("0");+ const bearer = await team.capability(writer.id, launch.threadId);+ const refused = await fetch(`${team.base}/api/internal/board/list`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: "{}" });+ expect(refused.status).toBe(404);+ const on = await team.as(olive, "PATCH", "/api/config", { features: { teamBoard: true } });+ expect(on.status, JSON.stringify(on.body)).toBe(200);+ await until(async () => ((await team.as(olive, "GET", "/api/bots")).body.bots as Array<{ busy?: boolean }>).every((one) => !one.busy), "idle");+ rmSync(file("dump.json"), { force: true });+ await team.as(olive, "POST", `/api/bots/${writer.id}/messages`, { text: "Hello again", threadId: writer.threadId });+ await until(() => existsSync(file("dump.json")), "a second turn");+ expect(env().OMB_TEAM_BOARD).toBe("1");+ // Writer's own chat turn must be over before the next case: a busy Writer would hand its first item to another bot.+ await until(async () => ((await team.as(olive, "GET", "/api/bots")).body.bots as Array<{ busy?: boolean }>).every((one) => !one.busy), "idle again");+}, hostTimeout(90_000));++it("hands a person's item to a free bot as unattended work, and a done item readies and dispatches what needs it", async () => {+ parts({+ "Beta review": [update({ move: "done", text: "Reads well." })],+ "Alpha draft": [update({ move: "done", text: "Draft at drafts/alpha.md" })],+ });+ const alpha = await add(mira, { groupId: launch.id, title: "Alpha draft", text: "Write the launch post for Friday." });+ const beta = await add(mira, { groupId: launch.id, title: "Beta review", needs: [alpha.threadId], forBotId: reviewer.id });+ expect(beta.state).toBe("waiting");+ await settled(alpha.threadId, "done");+ expect(await item(alpha.threadId)).toMatchObject({ result: "Draft at drafts/alpha.md", attempts: 1 });+ const lines = await messages(mira, alpha.threadId);+ const brief = lines.find((line) => line.role === "user" && line.sender?.name === "Board")!;+ expect(brief.text).toMatch(/^@Writer /);+ expect(brief.text).toContain("Alpha draft");+ expect(brief.text).toContain("Write the launch post for Friday.");+ expect(brief.sender?.id, "the board is no person").toBeUndefined();+ await until(async () => (await messages(mira, alpha.threadId)).some((line) => line.role === "bot" && line.kind === "text" && line.from?.botId === writer.id), "Writer's reply");+ await settled(beta.threadId, "done");+ const review = (await messages(mira, beta.threadId)).find((line) => line.sender?.name === "Board")!;+ expect(review.text).toMatch(/^@Reviewer /);+ expect(review.text).toContain("Draft at drafts/alpha.md");+ expect(await item(beta.threadId)).toMatchObject({ result: "Reads well." });+ await until(() => usageRows(alpha.threadId).length > 0, "a usage row");+ expect(usageRows(alpha.threadId).map((row) => [row.botId, row.trigger.kind])).toEqual([[writer.id, "bot"]]);+}, hostTimeout(120_000));++it("an ask waits on the person who made the item, reaches their inbox, and their reply in the thread starts the same bot", async () => {+ parts({+ "Friday the 5th": [update({ move: "done", text: "Launch set for Friday the 5th." })],+ "Gamma launch date": [update({ move: "ask", text: "Which date should the launch be?" })],+ });+ const gamma = await add(mira, { groupId: launch.id, title: "Gamma launch date", forBotId: writer.id });+ await settled(gamma.threadId, "needs_person");+ const asked = await item(gamma.threadId);+ expect(asked).toMatchObject({ holder: { botId: writer.id }, question: { text: "Which date should the launch be?", person: personKey({ id: "", email: MIRA.email }) } });+ expect((await messages(mira, gamma.threadId)).some((line) => line.role === "bot" && line.text === "Which date should the launch be?" && line.from?.botId === writer.id)).toBe(true);+ await until(async () => ((await team.as(mira, "GET", "/api/inbox")).body.rows as Array<{ text: string; origin?: { threadId: string } }>)+ .some((row) => row.text === "Which date should the launch be?" && row.origin?.threadId === gamma.threadId), "Mira's inbox line");+ const rooms = (await team.as(mira, "GET", "/api/bots?messages=0")).body.groups as Array<Room & { tasks?: Array<{ threadId: string; activity?: string }> }>;+ expect(rooms.find((room) => room.id === launch.id)!.tasks!.find((task) => task.threadId === gamma.threadId)!.activity).toBe("waiting-on-you");+ const replied = await team.as(mira, "POST", `/api/groups/${launch.id}/messages`, { text: "Friday the 5th", threadId: gamma.threadId });+ expect(replied.status, JSON.stringify(replied.body)).toBe(202);+ // Writer's asking turn may still be ending (the item waits on Mira from the moment it asked), so her line is either+ // started at once or queued behind that turn; either way it is saved addressed to Writer.+ if (replied.body.queued) expect(replied.body.queueId).toBeTruthy();+ else expect(replied.body.message?.text).toBe("@Writer Friday the 5th");+ await until(async () => (await messages(mira, gamma.threadId)).some((line) => line.role === "user" && line.text === "@Writer Friday the 5th"), "Mira's line, addressed to Writer");+ expect((await messages(mira, gamma.threadId)).filter((line) => line.role === "user" && line.text?.includes("Friday the 5th"))).toHaveLength(1);+ await settled(gamma.threadId, "done");+ expect(await item(gamma.threadId)).toMatchObject({ result: "Launch set for Friday the 5th.", attempts: 1 });+ const answers = (await messages(mira, gamma.threadId)).filter((line) => line.role === "bot" && line.kind === "text");+ expect(answers.every((line) => line.from?.botId === writer.id), "Reviewer, the room's default, never answered").toBe(true);+}, hostTimeout(120_000));++it("a reply queued behind the turn that asked still goes to the same bot, and the item is not handed on meanwhile", async () => {+ rmSync(file("release"), { force: true });+ parts({+ "Thursday works": [update({ move: "done", text: "Booked Thursday." })],+ // Writer asks, then stays in its turn until the release file exists: Mira's reply has to wait in the queue.+ "Theta booking": [update({ move: "ask", text: "Which day should I book?" }), { name: "Bash", input: { command: "echo still finishing" }, hold: true }],+ });+ const theta = await add(mira, { groupId: launch.id, title: "Theta booking", forBotId: writer.id });+ await settled(theta.threadId, "needs_person");+ const replied = await team.as(mira, "POST", `/api/groups/${launch.id}/messages`, { text: "Thursday works", threadId: theta.threadId });+ expect(replied.status, JSON.stringify(replied.body)).toBe(202);+ expect(replied.body.queued, "Writer's turn is still running").toBe(true);+ expect(await item(theta.threadId)).toMatchObject({ state: "working", holder: { botId: writer.id }, attempts: 1 });+ writeFileSync(file("release"), "");+ await settled(theta.threadId, "done");+ expect(await item(theta.threadId)).toMatchObject({ result: "Booked Thursday.", attempts: 1 });+ const lines = await messages(mira, theta.threadId);+ expect(lines.filter((line) => line.role === "user" && line.text?.includes("Thursday works")).map((line) => line.text)).toEqual(["@Writer Thursday works"]);+ expect(lines.filter((line) => line.sender?.name === "Board"), "never handed out again").toHaveLength(1);+ rmSync(file("release"), { force: true });+}, hostTimeout(120_000));++it("an answer from the person's inbox, which starts no turn by itself, brings the item back to the bot that asked", async () => {+ parts({+ "The Hall": [update({ move: "done", text: "Booked The Hall." })],+ "Zeta venue": [update({ move: "ask", text: "Which venue should I book?" })],+ });+ const zeta = await add(mira, { groupId: launch.id, title: "Zeta venue", forBotId: writer.id });+ await settled(zeta.threadId, "needs_person");+ type Inbox = { botId: string; threadId: string; rows: Array<{ id: string; text: string; origin?: { threadId: string } }> };+ let inbox: Inbox | null = null;+ await until(async () => {+ inbox = (await team.as(mira, "GET", "/api/inbox")).body as Inbox;+ return inbox.rows.some((row) => row.origin?.threadId === zeta.threadId);+ }, "Mira's inbox line");+ const line = inbox!.rows.find((row) => row.origin?.threadId === zeta.threadId)!;+ const answered = await team.as(mira, "POST", `/api/bots/${inbox!.botId}/messages`, { text: "The Hall, please.", threadId: inbox!.threadId, replyToId: line.id });+ expect(answered.status, JSON.stringify(answered.body)).toBe(202);+ await settled(zeta.threadId, "done");+ expect(await item(zeta.threadId)).toMatchObject({ result: "Booked The Hall.", attempts: 1 });+ const boardLines = (await messages(mira, zeta.threadId)).filter((row) => row.sender?.name === "Board");+ expect(boardLines).toHaveLength(2);+ expect(boardLines[1]!.text).toMatch(/^@Writer .*The Hall, please\./s);+}, hostTimeout(120_000));++it("board_add from a lead makes a thread and an item each, with needs, and a bad batch makes nothing", async () => {+ parts({ "Delta two": [update({ move: "done", text: "Two done." })], "Delta one": [update({ move: "done", text: "One done." })] });+ const bearer = await team.capability(lead.id, launch.threadId);+ const call = (path: string, body: unknown) => fetch(`${team.base}/api/internal/board/${path}`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: JSON.stringify(body) });+ const before = (await board(olive)).length;+ const bad = await call("add", { items: [{ key: "a", title: "Delta zero" }, { key: "b", title: "Delta nobody", for: "Nobody" }] });+ expect(bad.status).toBe(400);+ expect((await board(olive)).length).toBe(before);+ const made = await call("add", { items: [{ key: "two", title: "Delta two", needs: ["one"], for: "Reviewer", labels: { area: "launch" } }, { key: "one", title: "Delta one", brief: "Book the room for Friday." }] });+ expect(made.status, await made.clone().text()).toBe(201);+ const items = (await board(olive)).filter((one) => one.title.startsWith("Delta"));+ const one = items.find((entry) => entry.title === "Delta one")!, two = items.find((entry) => entry.title === "Delta two")!;+ expect(two).toMatchObject({ needs: [one.threadId], forBotId: reviewer.id, labels: { area: "launch" }, createdBy: { kind: "bot", id: lead.id } });+ const first = (await messages(olive, one.threadId))[0]!;+ expect(first).toMatchObject({ role: "bot", text: "Book the room for Friday.", from: { botId: lead.id } });+ await settled(two.threadId, "done");+ const listed = await (await call("list", {})).json() as { text: string };+ expect(listed.text).toContain(`${two.threadId} [done] Delta two`);+}, hostTimeout(120_000));++it("later sets the item aside and brings it back to the same bot at its time, counting no attempt", async () => {+ parts({+ "See whether CI passed": [update({ move: "done", text: "CI green." })],+ "Epsilon ship": [update({ move: "later", minutes: 1, text: "See whether CI passed" })],+ });+ const epsilon = await add(mira, { groupId: launch.id, title: "Epsilon ship", forBotId: writer.id });+ await until(async () => (await item(epsilon.threadId)).later !== undefined, "set aside");+ expect(await item(epsilon.threadId)).toMatchObject({ state: "working", holder: { botId: writer.id }, laterCount: 1, later: { note: "See whether CI passed" } });+ await settled(epsilon.threadId, "done");+ expect(await item(epsilon.threadId)).toMatchObject({ result: "CI green.", attempts: 1, laterCount: 1 });+ const woken = (await messages(mira, epsilon.threadId)).filter((line) => line.sender?.name === "Board");+ expect(woken).toHaveLength(2);+ expect(woken[1]!.text).toMatch(/^@Writer .*See whether CI passed/s);+}, hostTimeout(120_000));diff --git a/server/cloud-team-board.e2e.test.ts b/server/cloud-team-board.e2e.test.tsindex 96eb2084bc..35e55deb45 100644--- a/server/cloud-team-board.e2e.test.ts+++ b/server/cloud-team-board.e2e.test.ts@@ -60,7 +60,8 @@ async function listen(token: string) {}beforeAll(async () => {- fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-board-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-board", name: "Acme" } });+ // The dispatcher's quiet minutes after a start last hours here: this file is about items, and nothing takes them.+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-board-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-board", name: "Acme", env: { OMB_BOARD_TIME_SCALE: "1000" } } });team = fx.team!;olive = (await team.pair(OLIVE)).token!;mira = (await team.pair(MIRA)).token!;diff --git a/server/drivers/agents-board-tools.ts b/server/drivers/agents-board-tools.tsnew file mode 100644index 0000000000..a4a3e007a3--- /dev/null+++ b/server/drivers/agents-board-tools.ts@@ -0,0 +1,75 @@+// The Team Board's three agents tools (docs/team-board.md), mounted only on a Team Cloud with the board on. Each is a+// thin call to its internal route (server/routes/board-tools.ts), which checks the bot, its rooms and every move.+import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";+import type { Json } from "./agents-client.ts";++export const BOARD_TOOL_NAMES: ReadonlySet<string> = new Set(["board_add", "board_list", "board_update"]);++const PATHS: Record<string, string> = { board_add: "add", board_list: "list", board_update: "update" };++export async function callBoardTool(name: string, args: Json, context: ToolCallContext): Promise<ToolCallResult> {+ const { ok, body } = await context.client.apiResponse(`/api/internal/board/${PATHS[name]}`, { method: "POST", body: JSON.stringify(args) });+ return ok ? { text: String(body.text ?? "") } : { text: String(body.error ?? "The board did not answer. Try again shortly."), isError: true };+}++const LABELS = { type: "object", additionalProperties: { type: "string", maxLength: 80 }, description: "Tags." };++export const BOARD_TOOL_DEFINITIONS = [+ {+ name: "board_add",+ description: "Add work items to a room's board, each on a new thread; the server gives ready ones to free bots of the room.",+ inputSchema: {+ type: "object",+ additionalProperties: false,+ properties: {+ room: { type: "string", description: "Room id or name; default: this room." },+ items: {+ type: "array",+ maxItems: 15,+ items: {+ type: "object",+ additionalProperties: false,+ properties: {+ key: { type: "string", description: "Its name for needs in this call." },+ title: { type: "string", maxLength: 120 },+ brief: { type: "string", description: "What to do and what done means." },+ needs: { type: "array", items: { type: "string" }, description: "Keys from this call or item ids to finish first." },+ labels: LABELS,+ for: { type: "string", description: "Only this bot of the room may take it." },+ },+ required: ["key", "title"],+ },+ },+ },+ required: ["items"],+ },+ },+ {+ name: "board_list",+ description: "The board items of your rooms, with state, holder and needs.",+ inputSchema: {+ type: "object",+ additionalProperties: false,+ properties: {+ room: { type: "string" },+ state: { type: "string", enum: ["waiting", "ready", "working", "needs_person", "done", "failed", "cancelled"] },+ },+ },+ },+ {+ name: "board_update",+ description: "Settle the board item you hold (default: this thread's): done or failed with text as the result, ask a person (text = question), later (look again in minutes; text = note) or release it.",+ inputSchema: {+ type: "object",+ additionalProperties: false,+ properties: {+ item: { type: "string", description: "Item id from board_list." },+ move: { type: "string", enum: ["done", "failed", "ask", "later", "release"] },+ text: { type: "string", maxLength: 2000 },+ person: { type: "string", description: "ask: who; default: who made the item." },+ minutes: { type: "integer", minimum: 1, maximum: 1440 },+ labels: LABELS,+ },+ },+ },+];diff --git a/server/drivers/agents-bridge-wire.test.ts b/server/drivers/agents-bridge-wire.test.tsindex 68880cc828..0e59a36808 100644--- a/server/drivers/agents-bridge-wire.test.ts+++ b/server/drivers/agents-bridge-wire.test.ts@@ -72,6 +72,8 @@ function profiles(): Record<string, Record<string, string>> {all["default+images"] = { ...all.default!, OMB_IMAGE_GENERATION: "1" };all["skills+shared+voice+x+team+images+hosting"] = { ...all["skills+shared+voice+x+team+images"]!, OMB_APP_HOSTING: "1" };all["default+hosting"] = { ...all.default!, OMB_APP_HOSTING: "1" };+ all["skills+shared+voice+x+team+board"] = { ...all["skills+shared+voice+x+team"]!, OMB_TEAM_BOARD: "1" };+ all["default+room+board"] = { ...all["default+room"]!, OMB_TEAM_PEOPLE: "1", OMB_TEAM_BOARD: "1" };all["default+tools-off"] = { ...all.default!, OMB_TOOLS_OFF: "pages,meetings" };return all;}@@ -118,6 +120,8 @@ const BUDGET_BASELINE: Record<string, number> = {"skills+shared+voice+x+team+images+hosting": 20215,"default+hosting": 19278,"default+tools-off": 16419,+ "skills+shared+voice+x+team+board": 19047,+ "default+room+board": 16855,};type RpcAnswer = { id: number; result?: { tools?: unknown[]; content?: Array<{ text: string }>; isError?: boolean }; error?: { code: number; message: string } };diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex 32a604bf67..05768a79c0 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -22,7 +22,7 @@ import { callHelperTool, HELPER_TOOL_NAMES } from "./agents-helper-tools.ts";import { callWhatChangedTool, WHAT_CHANGED_TOOL } from "./agents-what-changed-tool.ts";import { callUsageLimitsTool, USAGE_LIMITS_TOOL } from "./agents-usage-tool.ts";import { callThreadPostTool, THREAD_POST_TOOL } from "./agents-thread-post-tool.ts"; import { callListThreadsTool, closedThreadText, LIST_THREADS_TOOL } from "./agents-list-threads-tool.ts"; import { callRenameThreadTool, RENAME_THREAD_TOOL } from "./agents-thread-title-tool.ts"; import { callWorkflowTool, WORKFLOW_TOOL_NAMES } from "./agents-workflow-tool.ts";-import { callWaitTool, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts"; import { callCheckBackTool, CHECK_BACK_TOOL_NAMES } from "./agents-check-back-tool.ts";+import { callWaitTool, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts"; import { callCheckBackTool, CHECK_BACK_TOOL_NAMES } from "./agents-check-back-tool.ts"; import { BOARD_TOOL_NAMES, callBoardTool } from "./agents-board-tools.ts";import { callBurstTool } from "./agents-burst-tool.ts";import { callComputerAskTool, COMPUTER_ASK_TOOL_NAMES } from "./agents-computer-ask-tool.ts";import { callImageTool, IMAGE_TOOL_NAMES } from "./agents-image-tools.ts";@@ -257,7 +257,7 @@ export async function callTool(called: string, input: Json, context: ToolCallConif (PERSON_TOOL_NAMES.has(name)) return callPersonTool(name, args, context);if (DEVS_TOOL_NAMES.has(name)) return callDevsTool(name, args, context);if (TRIGGER_TOOL_NAMES.has(name)) return callTriggerTool(name, args, context);- if (WAIT_TOOL_NAMES.has(name)) return callWaitTool(name, args, context); if (CHECK_BACK_TOOL_NAMES.has(name)) return callCheckBackTool(args, context);+ if (WAIT_TOOL_NAMES.has(name)) return callWaitTool(name, args, context); if (CHECK_BACK_TOOL_NAMES.has(name)) return callCheckBackTool(args, context); if (BOARD_TOOL_NAMES.has(name)) return callBoardTool(name, args, context);if (name === USAGE_LIMITS_TOOL) return callUsageLimitsTool(context, args);if (COMPUTER_ASK_TOOL_NAMES.has(name)) return callComputerAskTool(args, context);// Second lock: with sharing off the catalog already omits these tools.diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.jsonindex 8b5c573b78..8293ed6215 100644--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json@@ -733,6 +733,54 @@"use_tool"]},+ "skills+shared+voice+x+team+board": {+ "bytes": 19047,+ "sha256": "b952fee38047b56ab210b8accb5197a3e3f47a67afd3b0bcc78f1eb8b5d46292",+ "tools": [+ "tool_result_read",+ "list_room_targets",+ "coordinate_bots",+ "list_bots",+ "list_rooms",+ "select_computer",+ "attach_file",+ "publish_page",+ "post_to_room",+ "post_to_thread",+ "request_credential",+ "request_sign_in",+ "fill_login",+ "send_voice_note",+ "message_person",+ "share",+ "memory_update",+ "find_tool",+ "use_tool"+ ]+ },+ "default+room+board": {+ "bytes": 16855,+ "sha256": "1da389a5178734674ca47b44d4c97f9c4e4660fea18840345b9831777865c103",+ "tools": [+ "tool_result_read",+ "list_room_targets",+ "coordinate_bots",+ "list_bots",+ "list_rooms",+ "attach_file",+ "publish_page",+ "post_to_room",+ "post_to_thread",+ "request_credential",+ "request_sign_in",+ "fill_login",+ "message_person",+ "share",+ "memory_update",+ "find_tool",+ "use_tool"+ ]+ },"default+tools-off": {"bytes": 16444,"sha256": "1b468d3464d21ab53160b2c7c06f3d9a2f9c2202c7715f3bec41a11ac8e2a15b",diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex 8e1d8c7f46..b76593c605 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1849,6 +1849,136 @@"app_settings"]},+ "skills+shared+voice+x+team+board": {+ "bytes": 73047,+ "sha256": "2f3f652b40d486453150cf1ddc7107401ec34c8f363502c2f15d842d9a4e4126",+ "tools": [+ "tool_result_read",+ "list_shared_computers",+ "shared_computer",+ "list_room_targets",+ "coordinate_bots",+ "assignment_status",+ "list_bots",+ "usage_limits",+ "list_rooms",+ "select_computer",+ "list_threads",+ "close_thread",+ "rename_thread",+ "run_workflow",+ "workflow_edit",+ "start_thread",+ "burst",+ "list_models",+ "vm_exec",+ "attach_file",+ "show_widget",+ "show_html",+ "publish_page",+ "unpublish_page",+ "post_to_room",+ "post_to_thread",+ "create_bot",+ "list_team_setup",+ "list_team_library",+ "propose_team_setup",+ "propose_bot_deletion",+ "manage_room",+ "request_credential",+ "request_sign_in",+ "fill_login",+ "send_voice_note",+ "x_search",+ "research_search",+ "research_endpoint",+ "research_call",+ "decide",+ "extract",+ "what_changed",+ "message_person",+ "report_bug",+ "share",+ "memory_update",+ "retry_thread",+ "memory_log",+ "session_search",+ "trigger_info",+ "trigger",+ "delete_trigger",+ "wait_until",+ "list_waits",+ "cancel_wait",+ "check_back",+ "board_add",+ "board_list",+ "board_update",+ "propose_profile",+ "propose_model",+ "propose_team_memory",+ "skills_list",+ "skill_manage",+ "mcp_server",+ "app_settings"+ ]+ },+ "default+room+board": {+ "bytes": 59189,+ "sha256": "03a6429caec5fc69dfaa5eed72c02e6621bbb0bf960c097536dbd9347cbf907a",+ "tools": [+ "tool_result_read",+ "list_room_targets",+ "coordinate_bots",+ "assignment_status",+ "list_bots",+ "usage_limits",+ "list_rooms",+ "list_threads",+ "close_thread",+ "run_workflow",+ "workflow_edit",+ "start_thread",+ "list_models",+ "vm_exec",+ "attach_file",+ "show_widget",+ "show_html",+ "publish_page",+ "unpublish_page",+ "post_to_room",+ "post_to_thread",+ "create_bot",+ "list_team_setup",+ "list_team_library",+ "propose_team_setup",+ "propose_bot_deletion",+ "manage_room",+ "request_credential",+ "request_sign_in",+ "fill_login",+ "decide",+ "extract",+ "what_changed",+ "message_person",+ "report_bug",+ "share",+ "memory_update",+ "retry_thread",+ "memory_log",+ "session_search",+ "trigger_info",+ "trigger",+ "delete_trigger",+ "board_add",+ "board_list",+ "board_update",+ "propose_profile",+ "propose_model",+ "propose_team_memory",+ "mcp_server",+ "app_settings"+ ]+ },"default+tools-off": {"bytes": 57469,"sha256": "1ff600e1d65c11cae40425671f6e35324a78c7eb7b8f74663ed8633c1ef03f6e",diff --git a/server/drivers/agents-catalog-profile.ts b/server/drivers/agents-catalog-profile.tsindex b1df4a3bf0..9519158a03 100644--- a/server/drivers/agents-catalog-profile.ts+++ b/server/drivers/agents-catalog-profile.ts@@ -24,6 +24,8 @@ export interface CatalogProfile {botId: string;/** A Team Cloud: message_person is mounted. */team?: boolean;+ /** A Team Cloud with its board on: board_add, board_list and board_update are mounted. Absent means off. */+ board?: boolean;/** The person's MausBot with a Chief's powers: its notification tools are mounted. */mausbot?: boolean;/** A direct chat whose bot may pick where it works (Works on is not Off and no team computer is its own): select_computer@@ -57,6 +59,7 @@ export function catalogProfileFromEnv(env: NodeJS.ProcessEnv): CatalogProfile {chief: env.OMB_CHIEF_OF_STAFF === "1",botId: env.OMB_BOT_ID ?? "",team: env.OMB_TEAM_PEOPLE === "1",+ board: env.OMB_TEAM_BOARD === "1",mausbot: env.OMB_MAUSBOT === "1",computerSelection: env.OMB_COMPUTER_SELECTION === "1",localVm: env.OMB_LOCAL_VM !== "0",diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.tsindex 50db91e134..3ea56aabfa 100644--- a/server/drivers/agents-catalog-wire.test.ts+++ b/server/drivers/agents-catalog-wire.test.ts@@ -66,6 +66,9 @@ function profiles(): Record<string, Profile> {// The plan's included app hosting reaches only a Cloud home the Admin wired for it; the fullest profile carries it.all["skills+shared+voice+x+team+images+hosting"] = { env: { ...all["skills+shared+voice+x+team+images"]!.env, OMB_APP_HOSTING: "1" } };all["default+hosting"] = { env: { ...all.default!.env, OMB_APP_HOSTING: "1" } };+ // A Team Cloud with its board on mounts the three board tools, in a chat and in a room; never on the fullest profile.+ all["skills+shared+voice+x+team+board"] = { env: { ...all["skills+shared+voice+x+team"]!.env, OMB_TEAM_BOARD: "1" } };+ all["default+room+board"] = { env: { ...all["default+room"]!.env, OMB_TEAM_PEOPLE: "1", OMB_TEAM_BOARD: "1" } };// A bot whose person turned groups off; the fullest profile has every group on.all["default+tools-off"] = { env: { ...all.default!.env, OMB_TOOLS_OFF: "pages,meetings" } };return all;@@ -77,6 +80,7 @@ const CHIEF_TARGET_TOOLS = ["propose_profile", "propose_model"];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 TEAMWORK_TOOLS = ["list_room_targets", "coordinate_bots", "assignment_status", "list_bots", "list_rooms", "list_threads", "close_thread", "start_thread", "post_to_room"];const MAUSBOT_TOOLS = ["list_unread_notifications", "mark_notifications_read"];+const BOARD_TOOLS = ["board_add", "board_list", "board_update"];/** MausBot's tools may make its list at most this much longer than the same Chief's without them. */const MAUSBOT_ADDS = 0.02;const RESEARCH_TOOLS = ["x_search", "research_search", "research_endpoint", "research_call"];@@ -118,6 +122,8 @@ const BUDGET_BASELINE: Record<string, number> = {"skills+shared+voice+x+team+images+hosting": 74525,"default+hosting": 63372,"default+tools-off": 57192,+ "skills+shared+voice+x+team+board": 73047,+ "default+room+board": 59189,};const RPC_PREFIX = '{"jsonrpc":"2.0","id":1,"result":';@@ -221,6 +227,7 @@ describe("agents proxy tools/list golden", () => {if (profile.env.OMB_CLOUD_HOME === "1" && (tool.name === "select_computer" || OWN_CLOUD_TOOLS.includes(tool.name))) continue;if (profile.env.OMB_CHIEF_OF_STAFF === "0" && CHIEF_TARGET_TOOLS.includes(tool.name)) continue;if (profile.env.OMB_MAUSBOT === "1" && MAUSBOT_TOOLS.includes(tool.name)) continue;+ if (profile.env.OMB_TEAM_BOARD === "1" && BOARD_TOOLS.includes(tool.name)) continue;expect(JSON.stringify(tool), `${name}: ${tool.name}`).toBe(full.get(tool.name));}}@@ -277,6 +284,15 @@ describe("agents proxy tools/list golden", () => {}});+ it("mounts the three board tools only on a Team Cloud with the board on, in a chat and in a room, and adds nothing else", () => {+ const names = (wire: string) => toolsOf(wire).map((tool) => tool.name);+ expect(names(wires["skills+shared+voice+x+team+board"]!).filter((tool) => !BOARD_TOOLS.includes(tool))).toEqual(names(wires["skills+shared+voice+x+team"]!));+ expect(names(wires["default+room+board"]!).filter((tool) => !BOARD_TOOLS.includes(tool))).toEqual(names(wires["default+room"]!));+ for (const [name, profile] of Object.entries(PROFILES)) {+ for (const tool of BOARD_TOOLS) expect(names(wires[name]!).includes(tool), `${name}: ${tool}`).toBe(profile.env.OMB_TEAM_BOARD === "1");+ }+ });+it("mounts generate_image and edit_image only when an image provider is set up, and adds nothing else", () => {const names = (wire: string) => toolsOf(wire).map((tool) => tool.name);expect(names(wires["default+images"]!).filter((tool) => tool !== "generate_image" && tool !== "edit_image")).toEqual(names(wires.default!));diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex 22ee6c2741..618aa42e2d 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -13,7 +13,7 @@ import { APP_SETTINGS_TOOL_DEFINITION } from "./agents-app-settings-tool.ts";import { THREAD_POST_TOOL_DEFINITION } from "./agents-thread-post-tool.ts";import { RENAME_THREAD_TOOL_DEFINITION } from "./agents-thread-title-tool.ts";import { WORKFLOW_TOOL_DEFINITIONS, WORKFLOW_TOOL_NAMES } from "./agents-workflow-tool.ts";-import { WAIT_TOOL_DEFINITIONS, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts"; import { CHECK_BACK_TOOL_DEFINITIONS, CHECK_BACK_TOOL_NAMES } from "./agents-check-back-tool.ts";+import { WAIT_TOOL_DEFINITIONS, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts"; import { CHECK_BACK_TOOL_DEFINITIONS, CHECK_BACK_TOOL_NAMES } from "./agents-check-back-tool.ts"; import { BOARD_TOOL_DEFINITIONS, BOARD_TOOL_NAMES } from "./agents-board-tools.ts";import { COMPUTER_ASK_TOOL_DEFINITIONS, COMPUTER_ASK_TOOL_NAMES } from "./agents-computer-ask-tool.ts";import { IMAGE_TOOL_DEFINITIONS, IMAGE_TOOL_NAMES } from "./agents-image-tools.ts";import { HOSTING_TOOL_DEFINITIONS, HOSTING_TOOL_NAMES } from "./agents-hosting-tools.ts";@@ -651,7 +651,7 @@ const TOOL_DEFINITIONS = [},},...WAIT_TOOL_DEFINITIONS,- ...CHECK_BACK_TOOL_DEFINITIONS,+ ...CHECK_BACK_TOOL_DEFINITIONS, ...BOARD_TOOL_DEFINITIONS,...COMPUTER_ASK_TOOL_DEFINITIONS,{name: "propose_profile",@@ -859,7 +859,7 @@ function catalogTools(profile: CatalogProfile) {(profile.botId === WATCHER_OPTIONS_CARD_BOT_ID || !WATCHER_TOOL_NAMES.has(tool.name)) &&(profile.memoryEnabled !== false || (tool.name !== "memory_update" && tool.name !== "memory_log")) &&(profile.computerSelection === true || tool.name !== "select_computer") &&- (profile.room !== true || !ROOM_REFUSED_TOOL_NAMES.has(tool.name)) &&+ (profile.room !== true || !ROOM_REFUSED_TOOL_NAMES.has(tool.name)) && (profile.board === true || !BOARD_TOOL_NAMES.has(tool.name)) &&(profile.imageGeneration === true || !IMAGE_TOOL_NAMES.has(tool.name)) && (profile.appHosting === true || !HOSTING_TOOL_NAMES.has(tool.name)) &&(profile.meetings === true || (!MEETING_TOOL_NAMES.has(tool.name) && tool.name !== "reset_cloud_computer")) &&(profile.skillBurger !== false || !WORKFLOW_TOOL_NAMES.has(tool.name)));diff --git a/server/drivers/agents-claude-defer.test.ts b/server/drivers/agents-claude-defer.test.tsindex 7ed196ad99..8d68a92bd9 100644--- a/server/drivers/agents-claude-defer.test.ts+++ b/server/drivers/agents-claude-defer.test.ts@@ -19,6 +19,8 @@ const PROFILES: Record<string, Record<string, string>> = {OMB_TEAM_PEOPLE: "1", OMB_IMAGE_GENERATION: "1", OMB_APP_HOSTING: "1",},};+// A Team Cloud with its board on: the three board tools come deferred, their names only.+PROFILES.board = { ...PROFILES.fullest!, OMB_TEAM_BOARD: "1" };const DEFER = { [DEFER_TOOLS_ENV]: "1" };/** Bytes Claude Code sends up front for the agents server when the budget was last set; each may move at most 2%. */@@ -26,6 +28,7 @@ const UP_FRONT_BASELINE: Record<string, { whole: number; deferred: number }> = {default: { whole: 3896, deferred: 1331 },specialist: { whole: 1495, deferred: 1159 },fullest: { whole: 3896, deferred: 1692 },+ board: { whole: 3896, deferred: 1765 },};const listed = (env: Record<string, string>) => agentsToolList(env).listed as Array<{ name: string; description: string; inputSchema: unknown; _meta?: Record<string, unknown> }>;diff --git a/server/drivers/agents-mcp-env.ts b/server/drivers/agents-mcp-env.tsindex f449b1037a..4068bf179f 100644--- a/server/drivers/agents-mcp-env.ts+++ b/server/drivers/agents-mcp-env.ts@@ -5,6 +5,6 @@ import { DEFER_TOOLS_ENV } from "./agents-claude-defer.ts";/** The settings the harness gives the agents MCP server, and the only ones a request may carry over HTTP. */export const AGENTS_MCP_ENV = ["OMB_BOT_ID", "OMB_THREAD_ID", "OMB_EXTERNAL_RUNTIME", "OMB_CHIEF_OF_STAFF","OMB_SKILL_AUTHORING_ENABLED", "OMB_SKILL_BURGER", "OMB_MEMORY_ENABLED", "OMB_SHARED_COMPUTERS_ENABLED", "OMB_CLOUD_HOME", "OMB_VOICE_NOTES",- "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_MAUSBOT", "OMB_COMPUTER_SELECTION", "OMB_ROOM", "OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", "OMB_LOCAL_VM", TOOL_BRIDGE_ENV, TOOL_LIMIT_ENV,+ "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_TEAM_BOARD", "OMB_MAUSBOT", "OMB_COMPUTER_SELECTION", "OMB_ROOM", "OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", "OMB_LOCAL_VM", TOOL_BRIDGE_ENV, TOOL_LIMIT_ENV,// Claude's deferred catalog: the URL form carries it as the stdio proxy's environment does.DEFER_TOOLS_ENV] as const;diff --git a/server/drivers/agents-schema.test.ts b/server/drivers/agents-schema.test.tsindex 5d8ce5a3f9..198e768fa3 100644--- a/server/drivers/agents-schema.test.ts+++ b/server/drivers/agents-schema.test.ts@@ -12,7 +12,7 @@ const record = (value: unknown): value is Json => value !== null && typeof value/** Every switch on: each tool the catalog can list, in the form tools/list sends it. */const LISTED = availableTools(catalogProfileFromEnv({OMB_BOT_ID: WATCHER_OPTIONS_CARD_BOT_ID, OMB_CHIEF_OF_STAFF: "1", OMB_SKILL_AUTHORING_ENABLED: "1", OMB_SHARED_COMPUTERS_ENABLED: "1",- OMB_VOICE_NOTES: "1", OMB_X_RESEARCH: "1", OMB_RESEARCH: "1", OMB_TEAM_PEOPLE: "1", OMB_MAUSBOT: "1",+ OMB_VOICE_NOTES: "1", OMB_X_RESEARCH: "1", OMB_RESEARCH: "1", OMB_TEAM_PEOPLE: "1", OMB_TEAM_BOARD: "1", OMB_MAUSBOT: "1",}));/** Each keyword the advertised node lacks, with where it sat in the full one. */diff --git a/server/drivers/agents-tool-groups.test.ts b/server/drivers/agents-tool-groups.test.tsindex 81fec759f8..e9478c1fd1 100644--- a/server/drivers/agents-tool-groups.test.ts+++ b/server/drivers/agents-tool-groups.test.ts@@ -13,7 +13,7 @@ import { CORE_TOOLS, OWN_SWITCH_TOOLS, serverTurnedOff, TOOL_GROUP_MEMBERS, toolconst FULLEST = {OMB_BOT_ID: "bot-full", OMB_SKILL_AUTHORING_ENABLED: "1", OMB_SHARED_COMPUTERS_ENABLED: "1", OMB_VOICE_NOTES: "1", OMB_CHIEF_OF_STAFF: "1",OMB_COMPUTER_SELECTION: "1", OMB_X_RESEARCH: "1", OMB_RESEARCH: "1", OMB_TEAM_PEOPLE: "1", OMB_IMAGE_GENERATION: "1", OMB_APP_HOSTING: "1",- OMB_MEETINGS: "1", OMB_MAUSBOT: "1",+ OMB_MEETINGS: "1", OMB_MAUSBOT: "1", OMB_TEAM_BOARD: "1",};const listed = (env: Record<string, string>) => availableTools(catalogProfileFromEnv(env));const names = (env: Record<string, string>) => listed(env).map((tool) => tool.name);diff --git a/server/drivers/agents-tool-groups.ts b/server/drivers/agents-tool-groups.tsindex 00dd56f3cc..4fc2bd790e 100644--- a/server/drivers/agents-tool-groups.ts+++ b/server/drivers/agents-tool-groups.ts@@ -32,7 +32,7 @@ export const CORE_TOOLS: ReadonlySet<string> = new Set(["post_to_room", "post_to_thread", "create_bot", "list_team_setup", "list_team_library", "propose_team_setup","propose_bot_deletion", "manage_room", "request_credential", "request_sign_in", "fill_login", "send_voice_note", "decide","extract", "what_changed", "message_person", "report_bug", "retry_thread", "session_search", "trigger_info", "trigger", "delete_trigger",- "wait_until", "list_waits", "cancel_wait", "check_back", "propose_profile", "propose_model", "propose_team_memory", "skills_list",+ "wait_until", "list_waits", "cancel_wait", "check_back", "board_add", "board_list", "board_update", "propose_profile", "propose_model", "propose_team_memory", "skills_list","skill_manage", "run_workflow", "workflow_edit", "mcp_server", "app_settings", "list_unread_notifications", "mark_notifications_read",]);diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex 16b4b43190..e9c07a25aa 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -206,6 +206,22 @@ export function createTeamMessages(deps: TeamMessagesDeps) {return { status: 200, text: `Passed on to ${to.name}'s inbox; they were notified. Only your message went, nothing else from here. Their answer comes back here, and you carry on from it.` };}+ /** A board item's bot asks a teammate (by name or address, else by person key) in a room thread: the question reaches+ * their inbox, from the bot, and their answer comes back to that thread. No hourly cap: a bot asks once per item turn. */+ function ask(botId: string, threadId: string, to: { name?: string; key?: string }, question: string, title: string): Passed & { person?: string } {+ const at = where(botId, threadId);+ if (!team || !at?.group) return { status: 403, text: "Only a bot in this room can ask from it." };+ if (deps.confined?.(threadId)) return { status: 403, text: OUTSIDE_REFUSAL };+ const found = to.name ? resolve(to.name) : { person: byKey(to.key) };+ if ("error" in found) return { status: found.status, text: found.error };+ const person = found.person;+ if (!person) return { status: 404, text: "Nobody here was named, and nobody made this item: name the person to ask." };+ if (!deps.sees(person).thread(threadId)) return { status: 403, text: `${person.name} can't see this room, so they can't answer here. Ask someone who can.` };+ const delivered = inbox.deliver(person.key, { kind: "message", from: { name: at.bot.name, botId: at.bot.id }, to: "bot", origin: originOf(at, threadId), text: question, title, notify: "mention" });+ if (!delivered) return { status: 409, text: `${person.name} has no inbox here yet, so the question waits in this thread for anyone who sees it.` };+ return { status: 200, text: `Asked ${person.name} in their inbox.`, person: person.key };+ }+const handledTurns = new Set<string>();const mentionable = () => mentionablePeople(current().map((one) => ({ key: one.key, name: one.name })));const botNames = () => store.bots.filter((bot) => !bot.hidden).map((bot) => bot.name);@@ -328,6 +344,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {return ctx.json(ctx.res, passed.status, passed.status === 200 ? { text: passed.text } : { error: passed.text });},pass,+ ask,inbox,/** Each teammate here and the tags that reach them ("@Ada", "@Ada Lovelace"); empty off a team. A bot sharing a tag* is never reached by it: a tie is the person's (shared/person-mention.ts). */diff --git a/server/index.ts b/server/index.tsindex 66e9a38021..5f6b6ab84b 100644--- a/server/index.ts+++ b/server/index.ts@@ -1798,7 +1798,7 @@ function agentsIntegration() {const bot = store.bot(botId), speaking = botForThread(botId, threadId) ?? bot;// Only advertises the tools; the routes behind them refuse regardless.- const host = { skillAuthoring: skillAuthoringEnabled(cfg), skillBurger: skillBurgerEnabled(cfg), sharedComputers: botLending(), cloudHome: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM),+ const host = { skillAuthoring: skillAuthoringEnabled(cfg), skillBurger: skillBurgerEnabled(cfg), sharedComputers: botLending(), cloudHome: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM), board: Boolean(CLOUD_TEAM) && cfg.features?.teamBoard === true,voiceNotes: tts.voiceReady(cfg, speaking?.voice) && speaking?.voiceNotes !== false, x: Boolean(researchCredential(cfg.treg?.key)), research: researchAvailability.available(), imageGeneration: imageGenerationReady(cfg), meetings: boat.boatConfigured(cfg), appHosting: hostingCredential() !== null, localVm: localVmAvailability.available() };return { ...agentsProxyLaunch(), env: agentsServerEnv({ threadId, bot: bot ?? { id: botId }, room: Boolean(store.groupByThread(threadId)), teamComputer: Boolean(bot && inheritedTeamComputer(bot)), botDriven: automated || botDrivenConversation(store.taskByThread(botId, threadId)), host },{ generation, depth, skillAuthoring, roomHandoffId, ...(hostFiles && !CLOUD_HOME && !HOSTED_WORKSPACE ? { deliversSavedFiles: true } : {}) },@@ -3829,7 +3829,7 @@ function followupAtBoot(threadId: string): "dispatched" | "pending" | undefined}return bootFollowups.get(threadId);}-const followupEndedRoots = new Map<string, string | undefined>();+const followupEndedRoots = new Map<string, string | undefined>(); let pokeBoard = (): void => {}; // the board's dispatcher, once it is made belowconst askCards = createAskCards({ store, node: (id) => coordinator.node(id), delegatorOf, notify, answerCard: respondToCard, answerNode: (id, text) => coordinator.answerNode(id, text),answeredIn: (threadId, requestId) => automationReports.answeredIn(teamMessages.inbox.answeredIn(threadId, requestId), requestId), live: (threadId, requestId) => askMessageByRequest.has(`${threadId}:${requestId}`),@@ -3870,8 +3870,8 @@ const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGateconst bot = store.botByThread(threadId);if (bot) botFrames.send(bot, threadId);}- // Node changes are the release signal for messages parked behind a settled coordination: no later turn.completed arrives.- if (directThreadIds.size > 0) drainQueuedSends();+ // Node changes are the release signal for messages parked behind a settled coordination, and a turn the board waits on may have ended.+ if (directThreadIds.size > 0) drainQueuedSends(); pokeBoard();},report: (child, parent) => {askCards.closed(child); if (child.outcome === "expired" && child.cards?.length) stopCards(child.threadId, new Set(child.cards));@@ -11378,7 +11378,7 @@ function claimPhoneSecretBotDeletion(botId: string): (() => void) | null {}const secretCards = createSecretCards({ store, cfg, botLogins, vaultStore: logins, vaultReader: vaultReaders.turn, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, email: { connect: (request, reading) => emailService.connect(request, reading), refusal: () => emailService.status().reason, connected: (address) => { const one = emailService.store.get(address); return Boolean(one && !one.problem); }, sendingProblem: (address) => emailService.sendingProblem(address), account: (address) => emailService.status().accounts.find((one) => one.address.toLowerCase() === address.toLowerCase()), checkOutgoing: (address, fields) => emailService.checkOutgoing(address, fields), profileAddress: () => cfg.profile?.email?.trim() || undefined }, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });-const teamBoard = createTeamBoard({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), enabled: () => cfg.features?.teamBoard === true, store, visible: (auth) => visibleTo(viewerFor(auth)), person: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), name: messageSender(auth)?.name ?? "" } : null, sender: messageSender, opened: (auth, threadId) => { if (auth.kind === "session") threadStarters.set(threadId, actorKey(auth)); }, roomRefusal: (groupId) => phoneSecretSubmissions.hasGroup(groupId) ? "This room is securely saving a credential. Try again when it finishes." : null, broadcast }); ROUTES.push(teamBoard.routes); ROUTES.push(createCheckBackRoutes({ checkBacks, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, messageId) => cardAnswerRefusal(auth, threadId, messageId, "deny") })); ROUTES.push(createBurstRoutes({ owner: (id) => burst.owner(id), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, id) => cardAnswerRefusal(auth, threadId, id, "allow"), view: (id) => burst.view(id), run: (id) => burst.run(id), cancel: (id) => burst.cancel(id), retry: (id) => burst.retryFailed(id), edit: (id, plan) => burst.edit(id, plan) })); ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));+const teamBoard = createTeamBoard({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), enabled: () => cfg.features?.teamBoard === true, store, visible: (auth) => visibleTo(viewerFor(auth)), person: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), name: messageSender(auth)?.name ?? "" } : null, sender: messageSender, opened: (auth, threadId) => { if (auth.kind === "session") threadStarters.set(threadId, actorKey(auth)); }, roomRefusal: (groupId) => phoneSecretSubmissions.hasGroup(groupId) ? "This room is securely saving a credential. Try again when it finishes." : null, broadcast, botFree: (botId, groupId, threadId) => { const bot = store.bot(botId), group = store.group(groupId); return Boolean(bot && group && !bot.hidden && !bot.busy && !bot.approvalGrant && !botHolds.held(botId) && !starterCaps.pausedText(botId, undefined, threadId) && !roomHeld(group, botId) && !providerInstancesChanging.has(bot.modelSelection.instanceId) && !roomMemberLock.heldElsewhere(botId, threadId) && !activeGroupTurnForBot(botId)); }, threadWorking: groupThreadIsWorking, capped: (botId) => { try { assertWithinBudget(cfg, DATA_DIR); usageCapGate.assertTurn(botId, false); return null; } catch (error) { const refused = error as { code?: unknown; resetsAt?: unknown }; return refused?.code === USAGE_CAP_CODE ? { resetsAt: typeof refused.resetsAt === "number" ? refused.resetsAt : Date.now() + 3_600_000 } : null; } }, modelReady: (botId) => { const instance = registry.get(store.bot(botId)?.modelSelection.instanceId ?? ""); return Boolean(instance && !policyModelRefusal(instance) && registry.lastSnapshot(instance.instanceId)?.authenticated !== false); }, startTurn: (groupId, threadId, botId, text, sender) => { startGroupTurn(groupId, text, undefined, undefined, "chat", undefined, { threadId, mentions: [botId], trigger: { kind: "bot", botId }, sender }); }, askPerson: teamMessages.ask, cardWaiting: (threadId) => Boolean(personWaits.open(threadId)), timeScale: Number(process.env.OMB_BOARD_TIME_SCALE) || undefined }); ROUTES.push(teamBoard.routes); pokeBoard = teamBoard.poke; ROUTES.push(createCheckBackRoutes({ checkBacks, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, messageId) => cardAnswerRefusal(auth, threadId, messageId, "deny") })); ROUTES.push(createBurstRoutes({ owner: (id) => burst.owner(id), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, id) => cardAnswerRefusal(auth, threadId, id, "allow"), view: (id) => burst.view(id), run: (id) => burst.run(id), cancel: (id) => burst.cancel(id), retry: (id) => burst.retryFailed(id), edit: (id, plan) => burst.edit(id, plan) })); ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));// By design OpenMausBot never receives a website password: the person signs in where the bot works, and the bot uses that session.@@ -11900,15 +11900,15 @@ const workspaceBackupAccess = {return work();}, {idle: () => !providerFleetReloading && !providerAuthSessions.active && !browserEngineInstall &&- !routines?.isTicking && !calendarCalls?.isTicking && !botWaits.isTicking && !checkBacks.isTicking &&+ !routines?.isTicking && !calendarCalls?.isTicking && !botWaits.isTicking && !checkBacks.isTicking && !teamBoard.isTicking &&!localVmImageBusy && !localVmProvisionBusy && !localVmModeChangeBusy &&!localVmLifecycleBusy.size && !boatLifecycleBusyBots.size && !computerPreviews.size && !orphanBoatLifecycleBusyIds.size &&!computerProviderConfigTransitions.size &&teamComputers.list().every(computer => !teamComputerInUse(computer)) &&store.bots.every((bot) => !botHasActiveTurn(bot.id) && !routines?.activeRunForBot(bot.id) && !sharedVm.snapshot(bot.id).held) &&store.groups.every((group) => !groupIsWorking(group)),- pause: () => { routines?.stop(); calendarCalls?.stop(); botWaits.stop(); checkBacks.stop(); watchdog.stop(); memoryUpkeep.pause(); },- resume: () => { if (!moveFreeze.frozen()) { routines?.start(); calendarCalls?.start(); botWaits.start(); checkBacks.start(); } watchdog.start(); memoryUpkeep.resume(); },+ pause: () => { routines?.stop(); calendarCalls?.stop(); botWaits.stop(); checkBacks.stop(); teamBoard.stop(); watchdog.stop(); memoryUpkeep.pause(); },+ resume: () => { if (!moveFreeze.frozen()) { routines?.start(); calendarCalls?.start(); botWaits.start(); checkBacks.start(); teamBoard.start(); } watchdog.start(); memoryUpkeep.resume(); },flush: async () => {await Promise.all([chatApps.settleLive(), flushAllProfileHistory(), flushAllMemoryJournals(), flushUsageLedger(DATA_DIR), flushDecisionLog(DATA_DIR), flushAdminActivity(DATA_DIR), releaseDataForBackup(dataEngine, (id) => store.bot(id)?.name)]);// Writers gated and work idle: release the WAL connection for a consistent snapshot; Store reopens it lazily.@@ -12062,7 +12062,7 @@ ROUTES.push(createGroupRoutes({groupFor: personRooms.groupForAuth,}));ROUTES.push(createChannelRoutes({- store, threadRead: teamMessages.seen, runOwners, runActor,+ store, threadRead: teamMessages.seen, runOwners, runActor, boardReply: teamBoard.reply, boardAddressed: teamBoard.addressed,personMarkRoom: personRooms.personMarkRoom,groupFor: personRooms.groupForAuth, threadShown: (auth: RequestAuth, threadId: string) => visibleTo(viewerFor(auth)).thread(threadId),cfg,@@ -13279,7 +13279,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {});return json(res, 201, proposed);}- if (await dispatchRoutes([createCheckBackToolRoutes({ checkBacks, requireActive: requireActiveInternalCapability, readBody: readInternalBody, botId: () => internalSender.id, threadId: () => internalCapability.threadId, zone: () => proactive.brief.timeZone() ?? routineTimeZone(), origin: () => { const origin = turnOrigin(internalCapability); return origin.kind === "user" ? withPerson(origin, origin.person ?? threadPersonKey(internalCapability.threadId)) : origin; }, refusal: () => { const source = connectorThread(internalSender.id, internalCapability.threadId); return checkBackRefusal({ owned: source !== null, room: Boolean(source?.group), depth: internalCapability.depth, handedOff: Boolean(internalCapability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(internalCapability.threadId)), outsideDriven: outsideDrivenThread(internalCapability.threadId) || outsideWorkStaysHere(internalCapability.threadId), personStarted: turnOrigin(internalCapability).kind === "user", guest: cloudGuestDriven(internalCapability.threadId) }); } }), createBurstProposalRoutes({ requireActive: requireActiveInternalCapability, readBody: readInternalBody, refusal: () => burstProposalRefusal({ owner: connectorThread(internalSender.id, internalCapability.threadId), outside: outsideWorkStaysHere(internalCapability.threadId), self: selfThreadRefusal({ handoff: Boolean(internalCapability.roomHandoffId), requestLine: store.activePath(internalCapability.threadId).findLast((line) => line.role === "user" && line.kind === "text") }) }), model: () => burst.model(internalSender, internalCapability.threadId), propose: (plan) => burst.propose({ ...plan, botId: internalSender.id, threadId: internalCapability.threadId }) }), createInternalChiefTeamRoutes({ bot: () => store.bot(internalCapability.botId), requireActive: requireActiveInternalCapability,+ if (await dispatchRoutes([createCheckBackToolRoutes({ checkBacks, requireActive: requireActiveInternalCapability, readBody: readInternalBody, botId: () => internalSender.id, threadId: () => internalCapability.threadId, zone: () => proactive.brief.timeZone() ?? routineTimeZone(), origin: () => { const origin = turnOrigin(internalCapability); return origin.kind === "user" ? withPerson(origin, origin.person ?? threadPersonKey(internalCapability.threadId)) : origin; }, refusal: () => { const source = connectorThread(internalSender.id, internalCapability.threadId); return checkBackRefusal({ owned: source !== null, room: Boolean(source?.group), depth: internalCapability.depth, handedOff: Boolean(internalCapability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(internalCapability.threadId)), outsideDriven: outsideDrivenThread(internalCapability.threadId) || outsideWorkStaysHere(internalCapability.threadId), personStarted: turnOrigin(internalCapability).kind === "user", guest: cloudGuestDriven(internalCapability.threadId) }); } }), teamBoard.toolRoutes({ requireActive: requireActiveInternalCapability, readBody: readInternalBody, botId: () => internalSender.id, threadId: () => internalCapability.threadId }), createBurstProposalRoutes({ requireActive: requireActiveInternalCapability, readBody: readInternalBody, refusal: () => burstProposalRefusal({ owner: connectorThread(internalSender.id, internalCapability.threadId), outside: outsideWorkStaysHere(internalCapability.threadId), self: selfThreadRefusal({ handoff: Boolean(internalCapability.roomHandoffId), requestLine: store.activePath(internalCapability.threadId).findLast((line) => line.role === "user" && line.kind === "text") }) }), model: () => burst.model(internalSender, internalCapability.threadId), propose: (plan) => burst.propose({ ...plan, botId: internalSender.id, threadId: internalCapability.threadId }) }), createInternalChiefTeamRoutes({ bot: () => store.bot(internalCapability.botId), requireActive: requireActiveInternalCapability,teams: teamSetupTeams, bots: () => store.bots, instances: () => registry.describe() }), createInternalModelRoutes({ requireActive: requireActiveInternalCapability, menu: (search) => ownThreads.menu(internalCapability.botId, internalCapability.threadId, search) })], { req, res, url, path, method, auth, json, readBody })) return;if (method === "POST" && path === "/api/internal/team-setup-requests") {const parsed = z.object({ fromBotId: z.string().optional(), fromThreadId: z.string().optional(), plan: z.unknown() }).strict().safeParse(await readInternalBody());@@ -15117,7 +15117,7 @@ restoreChannelMessages();if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA_DIR, broadcast: (payload) => broadcast(payload), log: (line) => console.warn(line), bootedFromSleep: startedFromSleep, onBootWakeRequest: (at) => cloudHealth?.speed.wakeRequest(at), onWoke: createWokeNotifier({ adminOrigin: CLOUD_HOME.adminOrigin, machineId: CLOUD_HOME.machineId, secret: CLOUD_HOME.bootstrapSecret, log: (line) => console.warn(line) }), probes: {turn: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking), run: () => Boolean(routines?.hasActiveRuns()), handoff: () => coordinator.pace() === "busy",- liveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt(), checkBacks.nextDueAt(), botMoves?.nextLapseAt() ?? null].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },+ liveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt(), checkBacks.nextDueAt(), botMoves?.nextLapseAt() ?? null, teamBoard.nextDueAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));botLink.start(); let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });@@ -15136,7 +15136,7 @@ server.listen(PORT, listenHost(server), async () => {if (companyShutdown) return;}// Only once every registry is initialized and the endpoint listens: earlier dispatch can hit uninitialized bindings.- moveFreeze.hold(() => { routines!.start(); botWaits.start(); checkBacks.start(); proactive.start(); }, () => { routines!.stop(); botWaits.stop(); checkBacks.stop(); proactive.stop(); });+ moveFreeze.hold(() => { routines!.start(); botWaits.start(); checkBacks.start(); teamBoard.start(); proactive.start(); }, () => { routines!.stop(); botWaits.stop(); checkBacks.stop(); teamBoard.stop(); proactive.stop(); });limitClock.start(); burst.recover(); handoffStatus.changed();moveFreeze.hold(() => memoryUpkeep.start(), () => memoryUpkeep.stop());});@@ -15202,7 +15202,7 @@ const gracefulShutdown = createGracefulShutdown({vps.closeAllVpsDesktopTunnels();watchdog.stop();routines?.close(); void appTriggers.stop();- calendarCalls?.stop(); botWaits.stop(); checkBacks.stop();+ calendarCalls?.stop(); botWaits.stop(); checkBacks.stop(); teamBoard.stop();memoryUpkeep.stop();cacheKeepWarm.dispose(); warmSummaries.dispose();skillReview.stop();diff --git a/server/routes/board-tools.ts b/server/routes/board-tools.tsnew file mode 100644index 0000000000..46224a9f2c--- /dev/null+++ b/server/routes/board-tools.ts@@ -0,0 +1,261 @@+// The Team Board's bot tools (board_add, board_list, board_update), inside index.ts's /api/internal/ block, after the+// capability bearer is checked: the bot and its thread are the capability's, never a body field. On a Team Cloud with+// the board on only; anywhere else they answer 404 like an unknown path.+// POST /api/internal/board/add new room threads, each an item, needs given by keys of the same call+// POST /api/internal/board/list the items of the rooms the bot is in+// POST /api/internal/board/update the bot settles, asks about, sets aside, hands back or labels an item+// Security: a bot sees and adds items only in rooms it is a member of; which moves it may make is the state machine's+// (server/board/state.ts): only the bot holding an item may settle, ask about or set it aside.+import { z } from "zod";++import { BOARD_LIMITS, type BoardItem, type BoardItemState } from "../../shared/board.ts";+import type { Board } from "../board/host.ts";+import { boardLabels, boardTitle, BoardError, isOpen } from "../board/state.ts";+import { PASS, type RouteHandler } from "./table.ts";++export const BOARD_TOOL_PATH = "/api/internal/board";++export interface BoardRoom {+ id: string;+ name: string;+ memberIds: readonly string[];+}++export interface BoardToolDeps {+ board: Pick<Board, "list" | "get" | "create" | "patch" | "move">;+ /** A Team Cloud with `features.teamBoard` on. */+ on(): boolean;+ requireActive(): void;+ botId(): string;+ threadId(): string;+ readBody(): Promise<unknown>;+ botName(botId: string): string | undefined;+ /** The rooms (not bot-to-bot chats) this bot is a member of. */+ rooms(botId: string): readonly BoardRoom[];+ /** The room whose thread this is, or null. */+ roomOf(threadId: string): BoardRoom | null;+ /** Opens a room thread without making it the room's current one, with `text` as the bot's first line there. */+ openThread(groupId: string, title: string, text: string, botId: string): string;+ /** Posts the question as the bot's line in the thread and reaches the person's inbox; `person` is the asked person's key. */+ ask(botId: string, threadId: string, question: string, to: { name?: string; key?: string }): { ok: boolean; text: string; person?: string };+ /** The result an item gets when its bot sets it aside once too often. */+ tooManyLaters(threadId: string): string;+ /** A minute; tests shorten it. */+ minuteMs?: number;+ now?: () => number;+}++const STATES: readonly BoardItemState[] = ["waiting", "ready", "working", "needs_person", "done", "failed", "cancelled"];+const ADD_EXAMPLE = 'Example: {"items":[{"key":"draft","title":"Draft the post","brief":"Write 200 words for Friday."},{"key":"review","title":"Review the post","needs":["draft"]}]}';+const UPDATE_EXAMPLE = 'Example: {"move":"done","text":"Posted at https://…"} or {"move":"later","minutes":5,"text":"See whether CI passed"}.';+const LIST_MAX = 60;++const asList = (value: unknown) => typeof value === "string" ? [value] : value;+const addSchema = z.object({+ room: z.string().max(200).optional(),+ items: z.array(z.object({+ key: z.coerce.string().trim().min(1).max(40),+ title: z.string(),+ brief: z.string().max(BOARD_LIMITS.textMax).optional(),+ needs: z.preprocess(asList, z.array(z.string().max(200)).max(BOARD_LIMITS.needsMax)).optional(),+ labels: z.record(z.string(), z.unknown()).optional(),+ for: z.string().max(200).optional(),+ }).strict()).min(1).max(BOARD_LIMITS.itemsPerCall),+}).strict();+const listSchema = z.object({ room: z.string().max(200).optional(), state: z.string().max(40).optional() }).strict();+const updateSchema = z.object({+ item: z.string().max(200).optional(),+ move: z.string().max(20).optional(),+ text: z.string().max(BOARD_LIMITS.resultMax).optional(),+ person: z.string().max(254).optional(),+ minutes: z.coerce.number().optional(),+ labels: z.record(z.string(), z.unknown()).optional(),+}).strict();++const oneLine = (text: string, max: number) => {+ const line = text.replace(/\s+/g, " ").trim();+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;+};++export function createBoardToolRoutes(deps: BoardToolDeps): RouteHandler {+ const now = deps.now ?? Date.now;+ const minuteMs = deps.minuteMs ?? 60_000;++ /** A room of this bot by id or name; the room of its thread when none is named. */+ function roomFor(botId: string, threadId: string, raw: string | undefined): BoardRoom | string {+ const mine = deps.rooms(botId);+ if (!raw?.trim()) return deps.roomOf(threadId) ?? `This is not a room thread: name the room. Your rooms: ${mine.map((room) => room.name).join(", ") || "none"}.`;+ const wanted = raw.trim().replace(/^#/, "").toLowerCase();+ const hits = mine.filter((room) => room.id === raw.trim() || room.name.toLowerCase() === wanted);+ if (hits.length === 1) return hits[0]!;+ return hits.length ? `More than one of your rooms is called "${raw}": use its id (${hits.map((room) => room.id).join(", ")}).`+ : `You are not in a room called "${raw}". Your rooms: ${mine.map((room) => `${room.name} (${room.id})`).join(", ") || "none"}.`;+ }++ function line(item: BoardItem): string {+ const parts = [`${item.threadId} [${item.state}] ${oneLine(item.title, 120)}`];+ if (item.holder) parts.push(`by ${deps.botName(item.holder.botId) ?? item.holder.botId}`);+ if (item.forBotId) parts.push(`for ${deps.botName(item.forBotId) ?? item.forBotId}`);+ if (item.needs.length) parts.push(`needs ${item.needs.join(",")}`);+ const labels = Object.entries(item.labels).map(([key, value]) => `${key}=${value}`).join(",");+ if (labels) parts.push(`labels ${labels}`);+ if (item.question) parts.push(`asked: ${oneLine(item.question.text, 160)}`);+ if (item.result) parts.push(`result: ${oneLine(item.result, 200)}`);+ return `- ${parts.join(" · ")}`;+ }++ function add(botId: string, threadId: string, body: z.infer<typeof addSchema>): { status: number; text: string } {+ const room = roomFor(botId, threadId, body.room);+ if (typeof room === "string") return { status: 404, text: room };+ if (!room.memberIds.includes(botId)) return { status: 403, text: "You can add items only in a room you are in." };+ const existing = deps.board.list({ groupId: room.id });+ if (existing.filter((item) => isOpen(item.state)).length + body.items.length > BOARD_LIMITS.openPerRoom) {+ return { status: 409, text: `${room.name} would have more than ${BOARD_LIMITS.openPerRoom} open items. Finish or cancel some first.` };+ }+ // Everything is checked before the first thread opens: a bad entry leaves no thread behind.+ const keys = new Set<string>();+ const planned: Array<{ key: string; title: string; brief: string; needKeys: string[]; needIds: string[]; labels: Record<string, string>; forBotId?: string }> = [];+ try {+ for (const entry of body.items) {+ if (keys.has(entry.key)) return { status: 400, text: `The key "${entry.key}" is used twice. Give each item its own key. ${ADD_EXAMPLE}` };+ keys.add(entry.key);+ const title = boardTitle(entry.title);+ const labels = boardLabels(entry.labels);+ let forBotId: string | undefined;+ if (entry.for?.trim()) {+ const wanted = entry.for.trim().replace(/^@/, "").toLowerCase();+ const named = room.memberIds.filter((id) => id === entry.for || deps.botName(id)?.toLowerCase() === wanted);+ if (named.length !== 1) return { status: 400, text: named.length ? `More than one bot in ${room.name} is called "${entry.for}".` : `No bot called "${entry.for}" is in ${room.name}. Its bots: ${room.memberIds.map((id) => deps.botName(id) ?? id).join(", ")}.` };+ forBotId = named[0];+ }+ planned.push({ key: entry.key, title, brief: entry.brief?.trim() || title, needKeys: [], needIds: [], labels, ...(forBotId ? { forBotId } : {}) });+ }+ for (const [index, entry] of body.items.entries()) {+ for (const need of entry.needs ?? []) {+ if (keys.has(need)) planned[index]!.needKeys.push(need);+ else if (existing.some((item) => item.threadId === need)) planned[index]!.needIds.push(need);+ else return { status: 400, text: `"${need}" in the needs of "${entry.key}" is neither a key of this call nor an item of ${room.name}. ${ADD_EXAMPLE}` };+ }+ }+ } catch (error) {+ if (error instanceof BoardError) return { status: error.status, text: `${error.message} ${ADD_EXAMPLE}` };+ throw error;+ }+ // The keys' needs as a graph of their own: no loop, and each item is made after what it needs.+ const order: typeof planned = [];+ const placed = new Set<string>();+ while (order.length < planned.length) {+ const ready = planned.filter((entry) => !placed.has(entry.key) && entry.needKeys.every((key) => placed.has(key)));+ if (!ready.length) return { status: 409, text: "Those needs would make items wait for each other forever. Remove the loop." };+ for (const entry of ready) { order.push(entry); placed.add(entry.key); }+ }+ const made = new Map<string, BoardItem>();+ const creator = { kind: "bot" as const, id: botId, name: deps.botName(botId) ?? "Bot" };+ for (const entry of order) {+ const needs = [...entry.needIds, ...entry.needKeys.map((key) => made.get(key)!.threadId)];+ try {+ const item = deps.board.create({ groupId: room.id, title: entry.title, needs, labels: entry.labels, ...(entry.forBotId ? { forBotId: entry.forBotId } : {}), createdBy: creator },+ (title) => deps.openThread(room.id, title, entry.brief, botId));+ made.set(entry.key, item);+ } catch (error) {+ const done = [...made.entries()].map(([key, item]) => `${key} → ${item.threadId}`).join(", ");+ const why = error instanceof BoardError ? error.message : "The item could not be saved.";+ return { status: error instanceof BoardError ? error.status : 500, text: `${why}${done ? ` Already added: ${done}.` : ""}` };+ }+ }+ const lines = body.items.map((entry) => { const item = made.get(entry.key)!; return `- ${entry.key} → ${item.threadId} [${item.state}] ${item.title}`; });+ return { status: 201, text: `Added to ${room.name}; the server gives each ready item to a free bot of the room:\n${lines.join("\n")}` };+ }++ function list(botId: string, threadId: string, body: z.infer<typeof listSchema>): { status: number; text: string } {+ if (body.state !== undefined && !STATES.includes(body.state as BoardItemState)) return { status: 400, text: `state is one of ${STATES.join(", ")}.` };+ let rooms = deps.rooms(botId);+ if (body.room?.trim()) {+ const room = roomFor(botId, threadId, body.room);+ if (typeof room === "string") return { status: 404, text: room };+ rooms = [room];+ }+ const names = new Map(rooms.map((room) => [room.id, room.name]));+ const items = deps.board.list(body.state ? { state: body.state as BoardItemState } : {}).filter((item) => names.has(item.groupId));+ if (!items.length) return { status: 200, text: "No items." };+ const shown = items.slice(-LIST_MAX);+ const byRoom = new Map<string, string[]>();+ for (const item of shown) byRoom.set(item.groupId, [...(byRoom.get(item.groupId) ?? []), line(item)]);+ const text = [...byRoom].map(([groupId, lines]) => `${names.get(groupId)} (${groupId}):\n${lines.join("\n")}`).join("\n");+ return { status: 200, text: items.length > shown.length ? `The newest ${shown.length} of ${items.length}:\n${text}` : text };+ }++ function update(botId: string, threadId: string, body: z.infer<typeof updateSchema>): { status: number; text: string } {+ const itemId = body.item?.trim() || threadId;+ const item = deps.board.get(itemId);+ if (!item || !deps.rooms(botId).some((room) => room.id === item.groupId)) {+ return { status: 404, text: body.item ? "No item of your rooms has that id; board_list shows them." : "This thread is not a board item: pass item (its thread id from board_list)." };+ }+ const move = body.move?.trim().toLowerCase();+ const text = body.text?.trim() ?? "";+ if (move === undefined && body.labels === undefined) return { status: 400, text: `Say a move (done, failed, ask, later or release) or labels. ${UPDATE_EXAMPLE}` };+ const actor = { kind: "bot" as const, botId };+ if (move === "ask") {+ if (!text) return { status: 400, text: 'ask needs text: the question. Example: {"move":"ask","text":"Which client is this for?","person":"Mira"}' };+ if (item.state !== "working" || item.holder?.botId !== botId) return { status: 409, text: `This item is ${item.state.replace("_", " ")} and not yours to ask about now.` };+ const to = body.person?.trim() ? { name: body.person.trim() } : item.createdBy.kind === "person" ? { key: item.createdBy.id } : {};+ const reached = deps.ask(botId, item.threadId, text, to);+ deps.board.patch(item.threadId, { move: { move: "ask", question: text, ...(reached.person ? { person: reached.person } : {}) }, ...(body.labels !== undefined ? { labels: body.labels } : {}) }, actor);+ return { status: 200, text: `${reached.text} The item waits on a person; end your turn now. When they answer in this thread you are started again here.` };+ }+ if (move === "later") {+ const minutes = Math.round(body.minutes ?? NaN);+ if (!Number.isFinite(minutes) || minutes < 1 || minutes > BOARD_LIMITS.laterMinutesMax) return { status: 400, text: `later needs minutes from 1 to ${BOARD_LIMITS.laterMinutesMax}. ${UPDATE_EXAMPLE}` };+ if (!text) return { status: 400, text: `later needs text: what to look at then. ${UPDATE_EXAMPLE}` };+ if ((item.laterCount ?? 0) >= BOARD_LIMITS.latersMax && item.holder?.botId === botId && item.state === "working") {+ deps.board.move(item.threadId, { move: "failed", result: deps.tooManyLaters(item.threadId) }, actor);+ return { status: 409, text: `This item was set aside ${BOARD_LIMITS.latersMax} times, the most it may be, so it is now failed. Say so in one line and stop.` };+ }+ const at = now() + minutes * minuteMs;+ deps.board.patch(item.threadId, { move: { move: "later", at, note: text }, ...(body.labels !== undefined ? { labels: body.labels } : {}) }, actor);+ return { status: 200, text: `Set aside until ${new Date(at).toISOString()}. End your turn now; do not wait or poll. You are started again here then with your note.` };+ }+ const moves: Record<string, () => Parameters<Board["patch"]>[1]["move"]> = {+ done: () => ({ move: "done", ...(text ? { result: text } : {}) }),+ failed: () => ({ move: "failed", ...(text ? { result: text } : {}) }),+ release: () => ({ move: "release" }),+ };+ if (move !== undefined && !Object.hasOwn(moves, move)) return { status: 400, text: `move is one of done, failed, ask, later or release. ${UPDATE_EXAMPLE}` };+ const changed = deps.board.patch(item.threadId, { ...(move ? { move: moves[move]!() } : {}), ...(body.labels !== undefined ? { labels: body.labels } : {}) }, actor);+ const after: Record<string, string> = {+ done: "Marked done; items waiting on it are ready now. End your turn with a short summary.",+ failed: "Marked failed. End your turn with one line on why.",+ release: "Handed back; another free bot of the room may take it. End your turn.",+ };+ return { status: 200, text: move ? after[move]! : `Labels set: ${Object.entries(changed.labels).map(([key, value]) => `${key}=${value}`).join(", ") || "none"}.` };+ }++ return async ({ res, path, method, json }) => {+ if (path !== BOARD_TOOL_PATH && !path.startsWith(`${BOARD_TOOL_PATH}/`)) return PASS;+ if (!deps.on()) return json(res, 404, { error: "The board is off here. Ask an Owner or Admin to turn on Board in Settings → Features." });+ if (method !== "POST") return json(res, 405, { error: "method not allowed" });+ deps.requireActive();+ const botId = deps.botId(), threadId = deps.threadId();+ const raw = await deps.readBody();+ try {+ let answer: { status: number; text: string };+ if (path === `${BOARD_TOOL_PATH}/add`) {+ const parsed = addSchema.safeParse(raw);+ if (!parsed.success) return json(res, 400, { error: `board_add takes items: 1 to ${BOARD_LIMITS.itemsPerCall} of {key, title, brief?, needs?, labels?, for?}, and room?. ${ADD_EXAMPLE}` });+ answer = add(botId, threadId, parsed.data);+ } else if (path === `${BOARD_TOOL_PATH}/list`) {+ const parsed = listSchema.safeParse(raw ?? {});+ if (!parsed.success) return json(res, 400, { error: `board_list takes room? and state? (${STATES.join(", ")}).` });+ answer = list(botId, threadId, parsed.data);+ } else if (path === `${BOARD_TOOL_PATH}/update`) {+ const parsed = updateSchema.safeParse(raw);+ if (!parsed.success) return json(res, 400, { error: `board_update takes item?, move, text, person?, minutes?, labels?. ${UPDATE_EXAMPLE}` });+ answer = update(botId, threadId, parsed.data);+ } else return json(res, 404, { error: "not found" });+ return json(res, answer.status, answer.status < 300 ? { text: answer.text } : { error: answer.text });+ } catch (error) {+ if (error instanceof BoardError) return json(res, error.status, { error: error.message });+ throw error;+ }+ };+}diff --git a/server/routes/channels.ts b/server/routes/channels.tsindex 9de7f5bb5e..99ad98cf86 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -103,6 +103,11 @@ export interface ChannelRouteDeps {options: { via?: "api"; sender?: ResolvedSender; trigger?: UsageTrigger; threadId?: string; mentions?: string[]; pointed?: RoomPick },): Message;applyRoomHoldsFromMessage(groupId: string, text: string, mentions?: readonly string[]): void;+ /** A person's chat line in a thread whose board item waits on a person: the line addressed to the bot that asked, and+ * the move that takes the item back to work once it is sent. Null for every other thread (board/wiring.ts). */+ boardReply?(groupId: string, threadId: string, text: string): { text: string; botId: string; resume(): void } | null;+ /** What a resent line may have been saved as by `boardReply`. */+ boardAddressed?(groupId: string, threadId: string, text: string): string | null;cancelGroupTurnOperations(groupId: string, threadId: string): void;/** Whether this bot's live turn in the thread is a job another bot handed it. */speakerOnHandedWork(threadId: string, botId: string): boolean;@@ -427,7 +432,9 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (cancelledChatFollowup("channel", group.id, threadId, sendId)) {throw Object.assign(new Error("this queued sendId was cancelled; send a new message to try again"), { status: 409 });}- const accepted = acceptedSendMatch(store.messagesFor(threadId), sendId, text, replyTo?.id, channelMode);+ let accepted = acceptedSendMatch(store.messagesFor(threadId), sendId, text, replyTo?.id, channelMode);+ const addressed = accepted.kind === "conflict" ? deps.boardAddressed?.(group.id, threadId, text) : null;+ if (addressed) accepted = acceptedSendMatch(store.messagesFor(threadId), sendId, addressed, replyTo?.id, channelMode);if (accepted.kind === "conflict") {throw Object.assign(new Error("sendId already belongs to another message"), { status: 409 });}@@ -437,7 +444,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {const queued = queuedChannelMessage(group.id, threadId, sendId);if (queued) {if (- queued.text !== text ||+ (queued.text !== text && queued.text !== deps.boardAddressed?.(group.id, threadId, text)) ||queued.replyToId !== replyTo?.id ||queued.mode !== channelMode) {@@ -469,22 +476,26 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {: sameNameRefusal(text, members, mentions, conversationLanguage(threadId));if (sameName) throw Object.assign(new Error(sameName), { status: 409 });if (channelMode === "chat" && !owners.stopRefusal(auth, threadId)) applyRoomHoldsFromMessage(current.id, text, mentions);+ const board = channelMode === "chat" && !via && (trigger.kind === "user" || trigger.kind === "owner") ? deps.boardReply?.(current.id, threadId, text) ?? null : null;+ const lineText = board?.text ?? text, lineMentions = board ? [...new Set([...(mentions ?? []), board.botId])] : mentions;const threadWorking = groupThreadIsWorking(current.id, threadId);const decision = admit("room", {}, { roomWorking: threadWorking, threadWorking });if (decision.action === "queue") {- const queued = queueChannelMessage(current.id, threadId, text, {+ const queued = queueChannelMessage(current.id, threadId, lineText, {replyToId: replyTo?.id,sendId,mode: channelMode,via,sender: messageSender(auth),trigger,- mentions,+ mentions: lineMentions,...(pick ? { pointed: pick } : {}),});+ board?.resume();return { ok: true as const, queued: true as const, queueId: queued.id, threadId };}- const message = startGroupTurn(current.id, text, replyTo, sendId, channelMode, undefined, { via, sender: messageSender(auth), trigger, threadId, mentions, ...(pick ? { pointed: pick } : {}) });+ const message = startGroupTurn(current.id, lineText, replyTo, sendId, channelMode, undefined, { via, sender: messageSender(auth), trigger, threadId, mentions: lineMentions, ...(pick ? { pointed: pick } : {}) });+ board?.resume();return { ok: true as const, threadId, message };},);diff --git a/src/locales/de.json b/src/locales/de.jsonindex 349e816096..f1e269695b 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -282,6 +282,13 @@"server.checkBack.started": "Hat {when} wieder nachgeschaut","server.checkBack.cancelled": "Nachschauen abgebrochen","server.checkBack.failed": "Konnte {when} nicht wieder nachschauen",+ "server.board.sender": "Board",+ "server.board.brief": "@{bot} Dieser Board-Eintrag gehört dir: „{title}“.\n\n{text}\n\nEr ist erledigt, wenn die Arbeit oben fertig ist und du sagen kannst, was daraus wurde. Schließe mit board_update ab: done oder failed (text: was daraus wurde), ask (text: deine Frage an eine Person), later (Minuten und eine Notiz, um dann wieder nachzusehen) oder release (um ihn zurückzugeben).",+ "server.board.briefNeeds": "Worauf er gewartet hat:\n{results}",+ "server.board.wake": "@{bot} Zurück zum Board-Eintrag „{title}“: {note}\n\nSchließe mit board_update ab: done, failed, ask, later oder release.",+ "server.board.stopped": "Nach {count} Versuchen gestoppt: Jeder Durchgang endete, ohne den Eintrag abzuschließen.",+ "server.board.tooManyLaters": "{count}-mal zurückgestellt, ohne fertig zu werden, daher gestoppt.",+ "server.board.askTitle": "{bot} fragt dich zu „{title}“","server.teammates.sentInRoom": "An {bot} gesendet · {room}","server.teammates.sentDirectly": "Direkt an {bot} gesendet: er ist nicht in {room}.","server.teammates.sentDirectlyHere": "Direkt an {bot} gesendet: er ist nicht in diesem Raum.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 83749429f1..c86657d93e 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -435,6 +435,13 @@"server.checkBack.started": "Checked back {when}","server.checkBack.cancelled": "Check-back cancelled","server.checkBack.failed": "Couldn't check back {when}",+ "server.board.sender": "Board",+ "server.board.brief": "@{bot} This board item is yours: \"{title}\".\n\n{text}\n\nIt is done when the work above is finished and you can say what came of it. Finish with board_update: done or failed (text: what came of it), ask (text: your question for a person), later (minutes and a note, to look again then) or release (to hand it back).",+ "server.board.briefNeeds": "What it waited on:\n{results}",+ "server.board.wake": "@{bot} Back to the board item \"{title}\": {note}\n\nFinish with board_update: done, failed, ask, later or release.",+ "server.board.stopped": "Stopped after {count} tries: each turn ended without finishing the item.",+ "server.board.tooManyLaters": "Set aside {count} times without finishing, so it stopped.",+ "server.board.askTitle": "{bot} asks you about \"{title}\"","server.teammates.sentInRoom": "Sent to {bot} · {room}","server.teammates.sentDirectly": "Sent to {bot} directly: it isn't in {room}.","server.teammates.sentDirectlyHere": "Sent to {bot} directly: it isn't in this room.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 9211f00498..0840202a50 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -409,6 +409,13 @@"server.checkBack.started": "Verificou de novo: {when}","server.checkBack.cancelled": "Verificação cancelada","server.checkBack.failed": "Não foi possível verificar de novo: {when}",+ "server.board.sender": "Quadro",+ "server.board.brief": "@{bot} Este item do quadro é seu: \"{title}\".\n\n{text}\n\nEle está concluído quando o trabalho acima estiver pronto e você puder dizer o que resultou dele. Termine com board_update: done ou failed (text: o que resultou), ask (text: sua pergunta para uma pessoa), later (minutos e uma nota, para olhar de novo depois) ou release (para devolvê-lo).",+ "server.board.briefNeeds": "O que ele esperava:\n{results}",+ "server.board.wake": "@{bot} De volta ao item do quadro \"{title}\": {note}\n\nTermine com board_update: done, failed, ask, later ou release.",+ "server.board.stopped": "Parado após {count} tentativas: cada vez terminou sem concluir o item.",+ "server.board.tooManyLaters": "Adiado {count} vezes sem terminar, então parou.",+ "server.board.askTitle": "{bot} pergunta a você sobre \"{title}\"","server.teammates.sentInRoom": "Enviado para {bot} · {room}","server.teammates.sentDirectly": "Enviado diretamente para {bot}: ele não está em {room}.","server.teammates.sentDirectlyHere": "Enviado diretamente para {bot}: ele não está neste grupo.",