Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Merge main into image generation; cap images at 50 a day, only for a person's turn

milind-sonib6b12510e956
diff --cc docs/image-generation.md
index dd910f4b50,0000000000..20213f1546
mode 100644,000000..100644
--- a/docs/image-generation.md
+++ b/docs/image-generation.md
@@@ -1,95 -1,0 +1,103 @@@
+# Image generation
+
+Bots can create images in a chat: ask "make an image of…" and the bot calls
+its `generate_image` tool, on any engine. Bot avatars use the same providers.
+The image is attached to the bot's reply when its turn ends, like a voice note.
+
+## Setup
+
+Open **Settings → Image generation** (an AI page shown in Advanced mode; a
+link from the avatar editor opens it in Simple mode too). Choose:
+
+- **Base provider**: used first for every image.
+- **Backup provider** (optional): used only when the base could not start.
+- **Model** for each: a list with the recommended models first. For
+ OpenRouter, the rest of the list is its live image catalog
+ (`/api/v1/models?output_modalities=image`, fetched without a key and kept
+ for an hour). When the catalog cannot be loaded, the page says so and shows
+ only the recommended ones. **Other** opens a field to type any model ID.
+ Custom has no list, so its model is always typed.
+- **Images per reply**: the most images a bot may create in one turn (1–10,
+ default 4). Images still being made count, so parallel calls cannot pass it.
+ Images from Codex's own image tool count toward the same limit.
++- **A day's images**: bots make at most 50 images a day on one installation,
++ counted on disk so a restart does not reset it, starting again at local
++ midnight. There is no setting for it. Avatars made in Settings are not
++ counted.
++- **Only for a person**: `generate_image` makes an image only in a turn a
++ person's own message started (or work handed on from one). A routine, a
++ webhook, an outside app or a guest's turn is refused with a line the bot
++ can pass on, so nothing spends the image key unattended.
+- **Keys**: each chosen provider gets a key field on this page. The Grok and
+ OpenRouter fields save the same key as **API keys**. A key pasted into a
+ model field is refused.
+- **Test** (once a key is saved): checks the key with the provider and makes
+ no image. For OpenRouter it also checks that the chosen model exists, and
+ says when the account has no credit, since image models are paid. For the
+ other providers the model is only checked when the first image is made.
+
+Bots are shown `generate_image` only while the base or the backup has what it
+needs, so a bot never spends a turn finding out it cannot make images.
+
+| Provider | Key | Default model | Endpoint |
+| --- | --- | --- | --- |
+| OpenAI | its own, in this section | `gpt-image-2` | `api.openai.com/v1/images/generations` |
+| Grok (xAI) | in this section; the same key as under **API keys** | `grok-imagine-image-2.0` | `api.x.ai/v1/images/generations` |
+| Gemini | its own (Google AI Studio), in this section | `gemini-2.5-flash-image` | `generativelanguage.googleapis.com/v1beta/openai/images/generations` |
+| OpenRouter | in this section; the same key as under **API keys** | `google/gemini-2.5-flash-image` | `openrouter.ai/api/v1/images` |
+| Custom | optional, in this section | none: enter one | `<base URL>/images/generations` |
+
+Each key goes only to its own provider; a missing key is never borrowed from
+another one. Signing in to a ChatGPT, Claude, Gemini, Grok or Copilot
+subscription does not give API access, so it does not configure any of these.
+Bots on Codex can also use Codex's own image tool, which bills the ChatGPT
+plan; it does not use these providers, but its images count toward
+**Images per reply**.
+
+## When the backup is used
+
+The backup is tried only when the base confirmed that nothing started, the
+same rule the text backups follow:
+
+- the base has no key (or no URL and model, for Custom);
+- the connection was refused or the host was not found;
+- the base answered HTTP 401, 402, 403 or 429.
+
+A timeout or an HTTP 5xx stays on the base, because the image may already have
+been made and billed. A refused request (HTTP 400, including a moderation
+block) also stays on the base: OpenMausBot does not retry a refused prompt
+with another provider.
+
+When the backup makes the image, the bot is told why the base did not, such as
+`OpenAI image generation failed (HTTP 401, model gpt-image-2)`. When both fail,
+the error names both reasons.
+
+When the person names a provider ("make it with Grok"), the bot passes it and
+only that provider is tried; it must be the base or the backup. When the base
+and the backup are the same provider, naming it keeps the normal base-then-backup
+order.
+
+A generation stops when the bot's tool call goes away (the turn is stopped or
+the engine gives up on the call), and nothing is attached.
+
+## Custom gateway compatibility
+
+For a local gateway such as OmniRoute, a base URL might be
+`http://127.0.0.1:20128/v1`. OpenMausBot appends `/images/generations`; pasting
+that complete endpoint is also accepted. `localhost` and `127.0.0.1` refer to
+the machine running the OpenMausBot server, including when you open the app
+remotely. Public endpoints require HTTPS. HTTP is supported for local/private
+endpoints. URLs must not contain embedded credentials, query parameters, or
+fragments.
+
+The gateway must accept a synchronous OpenAI-style Images API request with
+`model`, `prompt`, `size`, `n: 1`, and `response_format: "b64_json"`. Its JSON
+response must contain `data[0].b64_json` with raw base64-encoded PNG, JPEG, or
+WebP bytes. Chat API compatibility alone is insufficient; URL-only responses,
+redirects, and asynchronous job responses are not supported.
+
+## Limits
+
+Each decoded image is limited to 10 MiB, the response to 15 MiB, and
+generation to two minutes. Provider error bodies are never shown or stored:
+an error names only the provider, the HTTP status and the model ID.
diff --cc server/drivers/agents-bridge-wire.test.ts
index e2d48783aa,650f4513f1..fd4b1adbe7
--- a/server/drivers/agents-bridge-wire.test.ts
+++ b/server/drivers/agents-bridge-wire.test.ts
@@@ -83,35 -81,33 +83,35 @@@ const FULL = "skills+shared+voice+escal
* either: lock a saving in by lowering the number. A Chief's list is longer
* than another bot's only by the Chief-only names in find_tool's description. */
const BUDGET_BASELINE: Record<string, number> = {
- "default": 16688,
- "voice": 17469,
- "shared": 16728,
- "shared+voice": 17509,
- "skills": 16715,
- "skills+voice": 17496,
- "skills+shared": 16755,
- "skills+shared+voice": 17550,
- "non-chief": 16571,
- "voice+non-chief": 17352,
- "shared+non-chief": 16611,
- "shared+voice+non-chief": 17392,
- "skills+non-chief": 16598,
- "skills+voice+non-chief": 17379,
- "skills+shared+non-chief": 16638,
- "skills+shared+voice+non-chief": 17419,
- "skills+shared+voice+cloud-home": 17552,
- "skills+shared+voice+non-chief+cloud-home": 17417,
- "skills+shared+voice+escalations": 17568,
- "skills+shared+voice+escalations+x": 17629,
- "skills+shared+voice+escalations+x+team": 17645,
- "default+legacy-switches": 16688,
- "default+mausbot": 16740,
- "skills+shared+voice+mausbot": 17602,
- "default+no-computer-pick": 15455,
- "default+room": 15415,
- "non-chief+room": 15298,
- "skills+shared+voice+escalations+x+team+images": 17416,
- "default+images": 16409,
+ "default": 17486,
+ "voice": 17909,
+ "shared": 17526,
+ "shared+voice": 17949,
+ "skills": 17513,
+ "skills+voice": 17936,
+ "skills+shared": 17553,
+ "skills+shared+voice": 17990,
+ "non-chief": 17369,
+ "voice+non-chief": 18150,
+ "shared+non-chief": 17409,
+ "shared+voice+non-chief": 18190,
+ "skills+non-chief": 17396,
+ "skills+voice+non-chief": 18177,
+ "skills+shared+non-chief": 17436,
+ "skills+shared+voice+non-chief": 18217,
+ "skills+shared+voice+cloud-home": 17992,
+ "skills+shared+voice+non-chief+cloud-home": 18233,
+ "skills+shared+voice+escalations": 18008,
+ "skills+shared+voice+escalations+x": 18069,
+ "skills+shared+voice+escalations+x+team": 18085,
+ "default+legacy-switches": 17486,
+ "default+mausbot": 17538,
+ "skills+shared+voice+mausbot": 18042,
+ "default+no-computer-pick": 16274,
+ "default+room": 16213,
+ "non-chief+room": 16096,
++ "skills+shared+voice+escalations+x+team+images": 18429,
++ "default+images": 17502,
};
type RpcAnswer = { id: number; result?: { tools?: unknown[]; content?: Array<{ text: string }>; isError?: boolean }; error?: { code: number; message: string } };
diff --cc server/drivers/agents-catalog-goldens/bridged.profiles.json
index efc1d5c644,0051e636ae..5061d2904e
--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json
+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json
@@@ -453,31 -474,9 +474,32 @@@
"use_tool"
]
},
+ "skills+shared+voice+escalations+x+team+images": {
- "bytes": 17653,
- "sha256": "409c11091960e99e521994a03be2d92344be3d95101fb696bf84529feef8688d",
++ "bytes": 18429,
++ "sha256": "bbbe7bb7e483b7e6df32f08db33aa661946ae079db2e3fe369bf4062bf7be3c9",
+ "tools": [
+ "tool_result_read",
+ "list_room_targets",
+ "coordinate_bots",
+ "list_bots",
+ "list_rooms",
+ "select_computer",
+ "attach_file",
+ "publish_page",
+ "post_to_room",
+ "request_credential",
+ "request_sign_in",
+ "fill_login",
+ "send_voice_note",
++ "message_person",
+ "memory_update",
+ "find_tool",
+ "use_tool"
+ ]
+ },
"default+legacy-switches": {
- "bytes": 16709,
- "sha256": "ecaa84405a300c86deacca84c4dcf12e7956bb239ae76cc115179d85f560fc66",
+ "bytes": 17486,
+ "sha256": "d6c5f68fac5114c9a084906d9dbb41e4acf688dc399af136f646a8dbe09b3a48",
"tools": [
"tool_result_read",
"list_room_targets",
@@@ -598,26 -603,5 +626,27 @@@
"find_tool",
"use_tool"
]
+ },
+ "default+images": {
- "bytes": 16710,
- "sha256": "09e58fa4556ac7baefe75b2bb4260a96ec12424d097ce59ebcf2b25e757a00ef",
++ "bytes": 17502,
++ "sha256": "ce42f064070e44731e840ec00db6977fbe880c8318f2188364f2dd8202b46867",
+ "tools": [
+ "tool_result_read",
+ "list_room_targets",
+ "coordinate_bots",
+ "list_bots",
+ "list_rooms",
+ "select_computer",
+ "attach_file",
+ "publish_page",
+ "post_to_room",
+ "request_credential",
+ "request_sign_in",
+ "fill_login",
++ "message_person",
+ "memory_update",
+ "find_tool",
+ "use_tool"
+ ]
}
}
diff --cc server/drivers/agents-catalog-goldens/bridged.tools-list.json
index 2e950c1783,0a5fb8c179..bc8fead8a0
--- a/server/drivers/agents-catalog-goldens/bridged.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/bridged.tools-list.json
@@@ -376,7 -409,7 +409,7 @@@
},
{
"name": "find_tool",
- "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, raise_escalation, usage_limits, list_threads, close_thread, start_thread, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, generate_image, message_person, report_bug, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server.",
- "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, raise_escalation, usage_limits, list_threads, close_thread, start_thread, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, report_bug, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server.",
++ "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, raise_escalation, usage_limits, list_threads, close_thread, start_thread, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, generate_image, report_bug, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
diff --cc server/drivers/agents-catalog-goldens/full.tools-list.json
index 12b859e003,e86e2107f7..1a7e706675
--- a/server/drivers/agents-catalog-goldens/full.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json
@@@ -1091,46 -1096,9 +1096,46 @@@
]
}
},
+ {
+ "name": "generate_image",
+ "description": "Create one image from a text description with the person's image provider; it is attached to your reply when the turn ends, so do not describe or link it again. Write the prompt in English, concrete and visual. Name a provider only when the person asked for that one.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "description": "What the image shows: subject, setting, style, lighting."
+ },
+ "aspect": {
+ "type": "string",
+ "enum": [
+ "1:1",
+ "16:9",
+ "9:16"
+ ],
+ "description": "Shape; square when omitted."
+ },
+ "provider": {
+ "type": "string",
+ "enum": [
+ "openai",
+ "xai",
+ "gemini",
+ "openrouter",
+ "custom"
+ ],
+ "description": "Only when the person named one; it must be their base or backup."
+ }
+ },
+ "required": [
+ "prompt"
+ ]
+ }
+ },
{
"name": "message_person",
- "description": "Pass a message to a person on this team, when someone asks you to tell them something (\"tell Bob the launch moved\"). Only your message goes, never this conversation. Someone who can see this conversation is tagged here; anyone else gets it in a new private conversation with you, and their answer can come back here.",
+ "description": "Reach a person in their Inbox, with news they may miss here or when asked to tell someone something. Their answer comes back here. Only what you write goes.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
diff --cc server/drivers/agents-catalog-goldens/profiles.json
index 271c3760c7,7307cbdc3a..59b11f6200
--- a/server/drivers/agents-catalog-goldens/profiles.json
+++ b/server/drivers/agents-catalog-goldens/profiles.json
@@@ -1063,71 -1083,9 +1083,71 @@@
"mcp_server"
]
},
+ "skills+shared+voice+escalations+x+team+images": {
- "bytes": 70560,
- "sha256": "1d4d5ab77da5c3e1aee8c8a72783578362c1e419791829d92e9201e17ddf52b4",
++ "bytes": 70647,
++ "sha256": "6d6532b3fd436d84d03023bfcab158483ce420bd3ff2ee863b707ad8f1fad4d3",
+ "tools": [
+ "tool_result_read",
+ "list_shared_computers",
+ "shared_computer",
+ "list_room_targets",
+ "coordinate_bots",
+ "assignment_status",
+ "raise_escalation",
+ "list_bots",
+ "usage_limits",
+ "list_rooms",
+ "select_computer",
+ "list_threads",
+ "close_thread",
+ "start_thread",
+ "vm_exec",
+ "attach_file",
+ "show_widget",
+ "show_html",
+ "publish_page",
+ "unpublish_page",
+ "post_to_room",
+ "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",
+ "generate_image",
+ "message_person",
+ "report_bug",
+ "memory_update",
+ "retry_thread",
+ "memory_log",
+ "session_search",
+ "trigger_info",
+ "trigger",
+ "delete_trigger",
+ "wait_until",
+ "list_waits",
+ "cancel_wait",
+ "propose_profile",
+ "propose_model",
+ "propose_team_memory",
+ "skills_list",
+ "skill_manage",
+ "mcp_server"
+ ]
+ },
"default+legacy-switches": {
- "bytes": 58596,
- "sha256": "e79c76eda1bd38d90fcf31c0f383c150259500fdd5abfa76c0c7f6c08832a73b",
+ "bytes": 59340,
+ "sha256": "65d2d72264da0bb12933526d00f03a59d3ba967620701fc789fd9bebfe21f8ad",
"tools": [
"tool_result_read",
"list_room_targets",
@@@ -1413,56 -1377,5 +1439,57 @@@
"propose_team_memory",
"mcp_server"
]
+ },
+ "default+images": {
- "bytes": 59394,
- "sha256": "10706a0688c0687e923e2a6048b452b20ade65853004369f8cde9c74f35a1ec5",
++ "bytes": 60113,
++ "sha256": "600ec9e8c705f967f2bc4869d472fd0e52249ad6d7d13159c39571869b8ecf19",
+ "tools": [
+ "tool_result_read",
+ "list_room_targets",
+ "coordinate_bots",
+ "assignment_status",
+ "list_bots",
+ "usage_limits",
+ "list_rooms",
+ "select_computer",
+ "list_threads",
+ "close_thread",
+ "start_thread",
+ "vm_exec",
+ "attach_file",
+ "show_widget",
+ "show_html",
+ "publish_page",
+ "unpublish_page",
+ "post_to_room",
+ "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",
+ "generate_image",
++ "message_person",
+ "report_bug",
+ "memory_update",
+ "retry_thread",
+ "memory_log",
+ "session_search",
+ "trigger_info",
+ "trigger",
+ "delete_trigger",
+ "wait_until",
+ "list_waits",
+ "cancel_wait",
+ "propose_profile",
+ "propose_model",
+ "propose_team_memory",
+ "mcp_server"
+ ]
}
}
diff --cc server/drivers/agents-catalog-wire.test.ts
index 6313c39ef4,0e65246a0a..1cb77401a6
--- a/server/drivers/agents-catalog-wire.test.ts
+++ b/server/drivers/agents-catalog-wire.test.ts
@@@ -108,10 -106,8 +108,10 @@@ const BUDGET_BASELINE: Record<string, n
"skills+shared+voice+escalations+x": 68784,
"skills+shared+voice+escalations+x+team": 69416,
"default+no-computer-pick": 57038,
- "default+room": 49808,
- "non-chief+room": 40751,
- "skills+shared+voice+escalations+x+team+images": 70348,
- "default+images": 59182,
+ "default+room": 50849,
+ "non-chief+room": 41633,
++ "skills+shared+voice+escalations+x+team+images": 70647,
++ "default+images": 60113,
};
const RPC_PREFIX = '{"jsonrpc":"2.0","id":1,"result":';
diff --cc server/drivers/agents-catalog.ts
index 269755a7f5,c9f505737f..50dce0149a
--- a/server/drivers/agents-catalog.ts
+++ b/server/drivers/agents-catalog.ts
@@@ -8,9 -9,8 +9,9 @@@ import { HELPER_TOOL_DEFINITIONS } fro
import { USAGE_LIMITS_TOOL_DEFINITION } from "./agents-usage-tool.ts";
import { WAIT_TOOL_DEFINITIONS, WAIT_TOOL_NAMES } from "./agents-wait-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 { MAUSBOT_TOOL_DEFINITIONS } from "./agents-mausbot-tools.ts";
- import { PERSON_TOOL_DEFINITIONS, PERSON_TOOL_NAMES } from "./agents-person-tools.ts";
+ import { PERSON_TOOL_DEFINITIONS } from "./agents-person-tools.ts";
import { RESEARCH_TOOL_DEFINITIONS, RESEARCH_TOOL_NAMES, X_TOOL_NAMES } from "./agents-research-tools.ts";
import type { CatalogProfile } from "./agents-catalog-profile.ts";
import { advertisedSchema } from "./agents-schema.ts";
@@@ -913,10 -913,8 +914,9 @@@ function catalogTools(profile: CatalogP
(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.escalations === true || tool.name !== "raise_escalation") &&
- (profile.team === true || !PERSON_TOOL_NAMES.has(tool.name)) &&
(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.imageGeneration === true || !IMAGE_TOOL_NAMES.has(tool.name)));
const AUTHORING_TOOLS = profile.skillAuthoring
? BOT_SCOPED_TOOLS
: BOT_SCOPED_TOOLS.filter((tool) => !SKILL_TOOL_NAMES.has(tool.name));
diff --cc server/host/turn-attachments.test.ts
index 0000000000,d15f88cb69..759678f854
mode 000000,100644..100644
--- a/server/host/turn-attachments.test.ts
+++ b/server/host/turn-attachments.test.ts
@@@ -1,0 -1,21 +1,28 @@@
+ import { expect, it } from "vitest";
+ import { settleParkedFiles } from "./turn-attachments.ts";
+
+ const image = { kind: "image" as const, path: "/a/one.png", mime: "image/png" };
+ const note = { kind: "audio" as const, path: "/a/two.mp3", mime: "audio/mpeg", text: " the token is sk-live-abc " };
+ const redact = (text: string) => text.replace(/sk-live-\w+/, "[redacted]");
+
+ it("lands a failed turn's voice note with its images, its words kept as a redacted transcript", () => {
+ expect(settleParkedFiles([image, note], false, redact)).toEqual({
+ land: [image, { kind: "audio", path: "/a/two.mp3", mime: "audio/mpeg", text: "the token is [redacted]" }],
+ discard: [],
+ });
+ });
+
+ it("discards only the voice notes of a stopped turn", () => {
+ expect(settleParkedFiles([image, note], true, redact)).toEqual({ land: [image], discard: [note] });
+ });
+
+ it("leaves no transcript on a note recorded without words", () => {
+ expect(settleParkedFiles([{ ...note, text: " " }], false, redact).land).toEqual([{ kind: "audio", path: "/a/two.mp3", mime: "audio/mpeg" }]);
+ });
++
++it("discards a goal coordinator's images and keeps its voice notes", () => {
++ expect(settleParkedFiles([image, note], false, redact, true)).toEqual({
++ land: [{ kind: "audio", path: "/a/two.mp3", mime: "audio/mpeg", text: "the token is [redacted]" }],
++ discard: [image],
++ });
++});
diff --cc server/host/turn-attachments.ts
index 0000000000,2172aebb4b..2543b1f410
mode 000000,100644..100644
--- a/server/host/turn-attachments.ts
+++ b/server/host/turn-attachments.ts
@@@ -1,0 -1,21 +1,24 @@@
+ // The files a turn parked while it ran (generated images, recorded voice notes), and what becomes of them when it settles.
+ import type { Message } from "../store.ts";
+
+ export type ParkedTurnAttachment = NonNullable<Message["attachments"]>[number];
+
+ /** A turn the person stopped loses the voice notes it recorded; every other turn, a failed one included, keeps all its
- * files. A note's words stay on it as its transcript, redacted. */
++ * files. A goal coordinator's turn loses its images: its artifacts never reach the public room. A note's words stay on
++ * it as its transcript, redacted. */
+ export function settleParkedFiles(
+ parked: readonly ParkedTurnAttachment[],
+ stopped: boolean,
+ redact: (text: string) => string,
++ coordinator = false,
+ ): { land: ParkedTurnAttachment[]; discard: ParkedTurnAttachment[] } {
+ const land: ParkedTurnAttachment[] = [];
+ const discard: ParkedTurnAttachment[] = [];
+ for (const file of parked) {
- if (file.kind !== "audio") land.push(file);
++ if (file.kind === "image" && coordinator) discard.push(file);
++ else if (file.kind !== "audio") land.push(file);
+ else if (stopped) discard.push(file);
+ else land.push({ kind: "audio", path: file.path, mime: file.mime, ...(file.text?.trim() ? { text: redact(file.text.trim()) } : {}) });
+ }
+ return { land, discard };
+ }
diff --cc server/image-daily-cap.test.ts
index 0000000000,0000000000..6f99cbb3d2
new file mode 100644
--- /dev/null
+++ b/server/image-daily-cap.test.ts
@@@ -1,0 -1,0 +1,52 @@@
++import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
++import { tmpdir } from "node:os";
++import { join } from "node:path";
++import { expect, it } from "vitest";
++
++import { createImageDailyCap, IMAGE_DAILY_CAP, IMAGE_DAY_FILE } from "./image-daily-cap.ts";
++
++const scratch = () => mkdtempSync(join(tmpdir(), "omb-image-cap-"));
++const at = (day: number, hour = 12) => () => new Date(2026, 10, day, hour, 0, 0);
++
++it("allows 50 images a day by default", () => {
++ const cap = createImageDailyCap(scratch(), { now: at(5) });
++ expect(cap.cap).toBe(IMAGE_DAILY_CAP);
++ expect(IMAGE_DAILY_CAP).toBe(50);
++ for (let made = 0; made < 50; made += 1) {
++ expect(cap.reserve()).toBe(true);
++ cap.settle(true);
++ }
++ expect(cap.reserve()).toBe(false);
++});
++
++it("counts images being made, and frees the place of one the provider did not make", () => {
++ const cap = createImageDailyCap(scratch(), { cap: 2, now: at(5) });
++ expect([cap.reserve(), cap.reserve(), cap.reserve()]).toEqual([true, true, false]);
++ cap.settle(false);
++ expect(cap.reserve()).toBe(true);
++});
++
++it("keeps the day's count on disk, so a restart does not reset it", () => {
++ const dir = scratch();
++ const before = createImageDailyCap(dir, { cap: 2, now: at(5, 9) });
++ for (let made = 0; made < 2; made += 1) { before.reserve(); before.settle(true); }
++ expect(JSON.parse(readFileSync(join(dir, IMAGE_DAY_FILE), "utf8"))).toEqual({ day: "2026-11-05", count: 2 });
++ expect(createImageDailyCap(dir, { cap: 2, now: at(5, 23) }).reserve()).toBe(false);
++});
++
++it("starts again at local midnight", () => {
++ const dir = scratch();
++ let now = at(5, 23);
++ const cap = createImageDailyCap(dir, { cap: 1, now: () => now() });
++ cap.reserve();
++ cap.settle(true);
++ expect(cap.reserve()).toBe(false);
++ now = at(6, 0);
++ expect(cap.reserve()).toBe(true);
++});
++
++it("reads a damaged count file as no images yet", () => {
++ const dir = scratch();
++ writeFileSync(join(dir, IMAGE_DAY_FILE), "{not json");
++ expect(createImageDailyCap(dir, { cap: 1, now: at(5) }).reserve()).toBe(true);
++});
diff --cc server/image-daily-cap.ts
index 0000000000,0000000000..f58bf1e3ea
new file mode 100644
--- /dev/null
+++ b/server/image-daily-cap.ts
@@@ -1,0 -1,0 +1,55 @@@
++// The most images bots make on this installation in one day, so a bot left looping cannot run up the image key's bill.
++// Counted on disk, so a restart never resets it; the day is local (a Cloud runs in its owner's zone: server/time-zone.ts)
++// and starts again at midnight. Avatars a person makes in Settings are not counted: they are a person's own clicks.
++import { readFileSync } from "node:fs";
++import { join } from "node:path";
++
++import { writeFileAtomic } from "./atomic.ts";
++
++export const IMAGE_DAILY_CAP = 50;
++export const IMAGE_DAY_FILE = "image-generation-day.json";
++
++function localDay(at: Date): string {
++ return `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, "0")}-${String(at.getDate()).padStart(2, "0")}`;
++}
++
++export interface ImageDailyCap {
++ readonly cap: number;
++ /** Holds one of today's images while it is made; false once today's are all made or held. */
++ reserve(): boolean;
++ /** Ends a hold: an image the provider made counts, one it did not make frees its place. */
++ settle(made: boolean): void;
++}
++
++export function createImageDailyCap(dataDir: string, options: { cap?: number; now?: () => Date } = {}): ImageDailyCap {
++ const cap = options.cap ?? IMAGE_DAILY_CAP;
++ const now = options.now ?? (() => new Date());
++ const file = join(dataDir, IMAGE_DAY_FILE);
++ let held = 0;
++ const madeToday = (): number => {
++ try {
++ const saved = JSON.parse(readFileSync(file, "utf8")) as { day?: unknown; count?: unknown } | null;
++ const count = saved?.count;
++ return saved?.day === localDay(now()) && typeof count === "number" && Number.isInteger(count) && count > 0 ? count : 0;
++ } catch {
++ return 0;
++ }
++ };
++ return {
++ cap,
++ reserve() {
++ if (madeToday() + held >= cap) return false;
++ held += 1;
++ return true;
++ },
++ settle(made) {
++ held = Math.max(0, held - 1);
++ if (!made) return;
++ try {
++ writeFileAtomic(file, `${JSON.stringify({ day: localDay(now()), count: madeToday() + 1 })}\n`, { mode: 0o600 });
++ } catch (error) {
++ console.warn(`image generation: could not count today's image in ${file}: ${error instanceof Error ? error.message : String(error)}`);
++ }
++ },
++ };
++}
diff --cc server/image-generation.e2e.test.ts
index ca53464ab7,0000000000..0e259b1078
mode 100644,000000..100644
--- a/server/image-generation.e2e.test.ts
+++ b/server/image-generation.e2e.test.ts
@@@ -1,140 -1,0 +1,160 @@@
+import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { z } from "zod";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { request } from "../scripts/mcp-server.ts";
+import { startFakeImageApi, type FakeImageApi } from "./testing/fake-image-api.ts";
+
+const botSchema = z.object({ bot: z.object({ id: z.string(), activeTaskId: z.string() }) });
+const waitSchema = z.object({ status: z.string() });
+const evidenceSchema = z.object({
+ botId: z.string(),
+ evidence: z.array(z.object({
+ step: z.unknown().optional(),
+ result: z.object({ tools: z.array(z.object({ name: z.string() })).optional() }).optional(),
+ response: z.object({ result: z.object({ isError: z.boolean().optional(), content: z.array(z.object({ text: z.string() })) }) }).optional(),
+ })),
+});
+const messagesSchema = z.object({
+ messages: z.array(z.object({
+ role: z.string(),
+ text: z.string().optional(),
+ attachments: z.array(z.object({ kind: z.string(), path: z.string(), mime: z.string() })).optional(),
+ })),
+});
+
+interface ImageFixture {
+ images: FakeImageApi;
+ configure: (patch: unknown) => Promise<void>;
+ newBot: (name: string) => Promise<z.infer<typeof botSchema>["bot"]>;
+ ask: (bot: { id: string; activeTaskId: string }, text: string) => Promise<string>;
+ savePlan: (plan: Record<string, unknown>) => void;
+ turnOf: (botId: string) => z.infer<typeof evidenceSchema>;
+ messages: (threadId: string) => Promise<z.infer<typeof messagesSchema>["messages"]>;
+ savedImages: () => string[];
+ api: (path: string, body?: unknown, method?: string) => Promise<unknown>;
++ /** As the app in a browser sends it: a person's own line, not a local program's. */
++ typed: (path: string, body: unknown) => Promise<unknown>;
+}
+
+async function withImageFixture(test: (f: ImageFixture) => Promise<void>) {
+ // A fake image URL exported in the shell would configure Custom in every fixture.
+ const session = await launchVerificationServer({ ...process.env, OMB_FAKE_IMAGE_API_URL: undefined }, undefined, undefined, undefined, undefined, { scripted: true });
+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } });
+ const api = (path: string, body?: unknown, method = "POST") =>
+ request(path, body === undefined ? {} : { method, body: JSON.stringify(body) }, session.info.url);
+ let images: FakeImageApi | undefined;
+ const dataDir = session.info.dataDir;
+ const planPath = join(dataDir, "room-plan.json");
+ try {
+ images = await startFakeImageApi();
+ await test({
+ images,
+ api,
++ typed: (path, body) => request(path, { method: "POST", body: JSON.stringify(body), headers: { origin: new URL(session.info.url).origin } }, session.info.url),
+ configure: async (patch) => { await api("/api/config", patch, "PUT"); },
+ newBot: async (name) => botSchema.parse(await cli("new-bot", "--name", name)).bot,
+ ask: async (bot, text) => {
+ await cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", text);
+ return waitSchema.parse(await cli("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30")).status;
+ },
+ savePlan: (plan) => writeFileSync(planPath, JSON.stringify(plan)),
+ turnOf: (botId) => {
+ const lines = existsSync(planPath + ".evidence.jsonl") ? readFileSync(planPath + ".evidence.jsonl", "utf8").trim().split("\n").filter(Boolean) : [];
+ const turn = lines.map((line) => evidenceSchema.parse(JSON.parse(line))).find((entry) => entry.botId === botId);
+ if (!turn) throw new Error(`no scripted turn was recorded for ${botId}`);
+ return turn;
+ },
+ messages: async (threadId) => messagesSchema.parse(await api("/api/threads/" + threadId + "/messages")).messages,
+ savedImages: () => {
+ const dir = join(dataDir, "attachments");
+ return existsSync(dir) ? readdirSync(dir).filter((name) => name.endsWith(".png")) : [];
+ },
+ });
+ } finally {
+ await images?.stop();
+ await session.close();
+ }
+}
+
+const listedTools = (turn: z.infer<typeof evidenceSchema>) => turn.evidence[0]?.result?.tools?.map((tool) => tool.name) ?? [];
+
+it("falls back from a keyless base to the backup and attaches the image to the settling reply", async () => withImageFixture(async (f) => {
+ await f.configure({ imageGen: { primary: { provider: "openai" }, fallback: { provider: "custom", model: "fixture-image" }, customUrl: f.images.url } });
+ const bot = await f.newBot("Image bot");
+ f.savePlan({
+ [bot.id]: {
+ steps: [{ tool: "generate_image", arguments: { prompt: "a navy owl with a brass compass", aspect: "16:9" } }],
+ reply: "Here is your owl.",
+ },
+ });
+ expect(await f.ask(bot, "Make an image of a navy owl.")).toBe("settled");
+
+ const turn = f.turnOf(bot.id);
+ expect(listedTools(turn)).toContain("generate_image");
+ const step = turn.evidence.find((entry) => entry.step)?.response?.result;
+ expect(step?.isError).toBeFalsy();
+ expect(step?.content[0]?.text).toContain("backup image provider, because the base failed: Add an OpenAI image API key first");
+
+ expect(f.images.requests).toEqual([
+ { model: "fixture-image", prompt: "a navy owl with a brass compass", response_format: "b64_json", size: "1536x1024", n: 1 },
+ ]);
+
+ const withImage = (await f.messages(bot.activeTaskId)).filter((m) => (m.attachments ?? []).some((a) => a.kind === "image"));
+ expect(withImage).toHaveLength(1);
+ expect(withImage[0]!.role).toBe("bot");
+ expect(withImage[0]!.text).toBe("Here is your owl.");
+ const image = withImage[0]!.attachments!.find((a) => a.kind === "image")!;
+ expect(image.mime).toBe("image/png");
+ const files = f.savedImages();
+ expect(files).toHaveLength(1);
+ expect(image.path.endsWith(files[0]!)).toBe(true);
+}), 60_000);
+
+it("hides generate_image from a bot when no image provider is set up", async () => withImageFixture(async (f) => {
+ const bot = await f.newBot("No image bot");
+ f.savePlan({ [bot.id]: { steps: [], reply: "No images here." } });
+ expect(await f.ask(bot, "Make an image.")).toBe("settled");
+ expect(listedTools(f.turnOf(bot.id))).not.toContain("generate_image");
+ expect(f.images.requests).toEqual([]);
+}), 60_000);
+
- it("keeps an image a goal coordinator makes out of the room's public reply", async () => withImageFixture(async (f) => {
++const roomOf = async (f: ImageFixture, roomId: string) => z.object({ groups: z.array(z.object({ id: z.string(), messages: z.array(z.object({
++ kind: z.string(), goalRun: z.object({ status: z.string() }).optional(), attachments: z.array(z.object({ kind: z.string() })).optional(),
++})) })) }).parse(await f.api("/api/bots?messages=30", undefined, "GET")).groups.find((group) => group.id === roomId)!;
++
++async function newRoom(f: ImageFixture, name: string, lead: { id: string }, helper: { id: string }) {
++ return z.object({ group: z.object({ id: z.string() }) }).parse(await f.api("/api/groups", {
++ name, memberIds: [lead.id, helper.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: lead.id } },
++ })).group;
++}
++
++it("makes an image for a person's line in a room and attaches it to the member's reply", async () => withImageFixture(async (f) => {
++ await f.configure({ imageGen: { primary: { provider: "custom", model: "fixture-image" }, customUrl: f.images.url } });
++ const lead = await f.newBot("Room painter");
++ const helper = await f.newBot("Room helper");
++ f.savePlan({ [lead.id]: { steps: [{ tool: "generate_image", arguments: { prompt: "a lighthouse at dusk" } }], reply: "Here it is." } });
++ const room = await newRoom(f, "Image room", lead, helper);
++ await f.typed(`/api/groups/${room.id}/messages`, { text: "Make a lighthouse picture", sendId: "room_send_image_1234" });
++ await expect.poll(async () => (await roomOf(f, room.id)).messages.flatMap((message) => message.attachments ?? []).filter((attachment) => attachment.kind === "image").length, { timeout: 30_000 }).toBe(1);
++ expect(f.images.requests).toHaveLength(1);
++}), 90_000);
++
++it("makes no image for a goal's coordinator, whose files never reach the room's public reply", async () => withImageFixture(async (f) => {
+ await f.configure({ imageGen: { primary: { provider: "custom", model: "fixture-image" }, customUrl: f.images.url } });
+ const lead = await f.newBot("Goal lead");
+ const helper = await f.newBot("Goal helper");
+ f.savePlan({
+ [lead.id]: {
- steps: [{ tool: "generate_image", arguments: { prompt: "a private sketch" } }],
++ steps: [{ tool: "generate_image", arguments: { prompt: "a private sketch" }, expectError: true }],
+ reply: "Done.\n<openmaus-goal>{\"status\":\"completed\",\"detail\":\"Sketch made.\"}</openmaus-goal>",
+ },
+ });
- const room = z.object({ group: z.object({ id: z.string() }) }).parse(await f.api("/api/groups", {
- name: "Goal room", memberIds: [lead.id, helper.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: lead.id } },
- })).group;
++ const room = await newRoom(f, "Goal room", lead, helper);
+ await f.api(`/api/groups/${room.id}/messages`, { text: "Make a sketch", mode: "goal", sendId: "goal_send_image_1234" });
- const roomState = async () => z.object({ groups: z.array(z.object({ id: z.string(), messages: z.array(z.object({
- kind: z.string(), goalRun: z.object({ status: z.string() }).optional(), attachments: z.array(z.object({ kind: z.string() })).optional(),
- })) })) }).parse(await f.api("/api/bots?messages=30", undefined, "GET")).groups.find((group) => group.id === room.id)!;
- await expect.poll(async () => (await roomState()).messages.find((message) => message.kind === "goal.run")?.goalRun?.status, { timeout: 30_000 }).toBe("completed");
- expect(f.images.requests).toHaveLength(1);
- expect((await roomState()).messages.flatMap((message) => message.attachments ?? []).filter((attachment) => attachment.kind === "image")).toEqual([]);
++ await expect.poll(async () => (await roomOf(f, room.id)).messages.find((message) => message.kind === "goal.run")?.goalRun?.status, { timeout: 30_000 }).toBe("completed");
++ expect(f.turnOf(lead.id).evidence.find((entry) => entry.step)?.response?.result.content[0]?.text).toContain("Images are made only for a person's own message");
++ expect(f.images.requests).toEqual([]);
++ expect((await roomOf(f, room.id)).messages.flatMap((message) => message.attachments ?? []).filter((attachment) => attachment.kind === "image")).toEqual([]);
+}), 90_000);
diff --cc server/index.ts
index e43c440f49,bc8028103b..4bd07fa73a
--- a/server/index.ts
+++ b/server/index.ts
@@@ -2857,15 -2822,14 +2821,15 @@@ const { cloudLendingTurn, cloudLendingR
store, cloudHome: CLOUD_HOME !== null, team: CLOUD_TEAM?.name ?? null, directRequest: (threadId) => directRequestOwners.get(threadId), threadStarter: (threadId) => threadStarters.get(threadId),
ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),
routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,
- memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true });
- const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) });
+ memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, handedSince: (threadId, since) => handedInSince(coordinator.all(), threadId, since) });
+ const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn, notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;
const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,
- refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalNotice(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;
- const { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning } = createPersonStop({
+ refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalForBot(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;
+ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,
- stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),
- }); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });
- const imageTools = createImageToolRoutes({ config: () => cfg, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
+ stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage,
+ }); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });
++const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
@@@ -6452,6 -6416,16 +6416,16 @@@ bus.subscribe((event: RuntimeEvent) =>
pushMessage({ role: "bot", kind: "text", text: spoken.text, turnId });
lastReply.set(event.threadId, spoken.text);
};
+ const landParkedFiles = (stopped: boolean) => {
+ const key = turnAttachmentKey(event.threadId, event.turnId);
- const { land, discard } = settleParkedFiles(turnAttachmentsByTurn.get(key) ?? [], stopped, redactSecretsInText);
++ const { land, discard } = settleParkedFiles(turnAttachmentsByTurn.get(key) ?? [], stopped, redactSecretsInText, Boolean(goalCoordinatorTurn || ambiguousCoordinatorText));
+ turnAttachmentsByTurn.delete(key);
+ for (const file of discard) deleteAttachment(file.path);
+ if (!land.length) return;
+ const response = store.messagesFor(event.threadId).findLast((message) => message.role === "bot" && message.kind === "text" && message.turnId === completedTurnId);
+ if (response) store.patchMessage(event.threadId, response.id, { attachments: [...(response.attachments ?? []), ...land] });
+ else pushMessage({ role: "bot", kind: "text", text: "", attachments: land, turnId: completedTurnId });
+ };
if (coordinatorVisibleText) pushAssistantText(coordinatorVisibleText, completedTurnId);
if (bot) handoffs.onEvent(event); else roomSessions.onEvent(event);
@@@ -8565,7 -8490,8 +8490,7 @@@ async function beginTurn
integrations,
...(integrations.browser && browserIsThePlace(turnSurfacePlan(bot, undefined, threadId, true)) ? { preloadBrowserTools: true } : {}),
...settingsTurnFields(cfg, DATA_DIR, managedPolicy.restrictsMcp()),
-- cwd,
- ...(worksInWorkspace || guestConfined || cloudGuestOpened(threadId) ? {} : { toolResultFolder: messageFileRootsForThread(bot.id, threadId).find((root) => root !== ATTACHMENTS_DIR) }),
++ cwd, ...(worksInWorkspace || guestConfined || cloudGuestOpened(threadId) ? {} : { toolResultFolder: messageFileRootsForThread(bot.id, threadId).find((root) => root !== ATTACHMENTS_DIR) }),
botSettingsFile: botSettingsFile(bot),
}, (input) => quickFallback.sendTurn(instance, input, route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined))), () => companyShutdown || !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {
await (runningTurnEngines.get(threadId) ?? instance).adapter.interruptTurn(threadId).catch(() => {});
@@@ -12323,7 -12246,7 +12245,7 @@@ ROUTES.push(createBotMemoryRoutes(
broadcast({ kind: "config", ...configStatus() });
},
}));
- const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
-const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
++const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));
@@@ -13140,7 -13064,7 +13063,7 @@@ const handleRequest = async (req: Incom
throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });
}
};
- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS)) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
++ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
const delegatedThisTurn = (taskId: string) => {
(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);
};
diff --cc server/routes/image-tools.test.ts
index c05faf166d,0000000000..b8cbe2c996
mode 100644,000000..100644
--- a/server/routes/image-tools.test.ts
+++ b/server/routes/image-tools.test.ts
@@@ -1,223 -1,0 +1,259 @@@
++import { mkdtempSync } from "node:fs";
+import { IncomingMessage, ServerResponse } from "node:http";
+import { Socket } from "node:net";
++import { tmpdir } from "node:os";
++import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+
++import { createImageDailyCap } from "../image-daily-cap.ts";
+import type { GeneratedImage } from "../image-generation.ts";
+import { createImageToolRoutes, generateImageForTurn, IMAGE_MESSAGES } from "./image-tools.ts";
+
+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64");
+const CFG = {
+ imageGen: { key: "openai-secret", primary: { provider: "openai" as const }, fallback: { provider: "xai" as const } },
+ xai: { key: "xai-secret" },
+};
+
+function okFetch(): typeof fetch {
+ return vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ data: [{ b64_json: PNG.toString("base64") }] })));
+}
+
- function deps(overrides: { cfg?: Parameters<typeof generateImageForTurn>[1]["cfg"]; fetchImpl?: typeof fetch; parked?: number; live?: boolean; noTurn?: boolean } = {}) {
++const scratch = () => mkdtempSync(join(tmpdir(), "omb-image-tools-"));
++
++function deps(overrides: { cfg?: Parameters<typeof generateImageForTurn>[1]["cfg"]; fetchImpl?: typeof fetch; parked?: number; live?: boolean; noTurn?: boolean; personTurn?: boolean; dailyCap?: number; dataDir?: string } = {}) {
+ const attached: GeneratedImage[] = [];
+ const live = overrides.live ?? true;
+ return {
+ attached,
+ deps: {
+ cfg: overrides.cfg ?? CFG,
++ personTurn: overrides.personTurn ?? true,
++ daily: createImageDailyCap(overrides.dataDir ?? scratch(), { cap: overrides.dailyCap }),
+ fetchImpl: overrides.fetchImpl ?? okFetch(),
+ inFlight: new Map<string, number>(),
+ turn: overrides.noTurn ? null : {
+ key: "thread:turn",
+ parked: () => (overrides.parked ?? 0) + attached.length,
+ attach: (image: GeneratedImage) => { if (live) attached.push(image); return live; },
+ },
+ },
+ };
+}
+
+describe("generate_image for a turn", () => {
+ it("attaches the base provider's image to the turn and says which provider made it", async () => {
+ const { deps: d, attached } = deps();
+ const result = await generateImageForTurn({ prompt: "a navy owl" }, d);
+ expect(result).toEqual({ status: 201, body: { text: expect.stringContaining("OpenAI (gpt-image-2)") } });
+ expect(attached).toEqual([{ bytes: PNG, mime: "image/png" }]);
+ });
+
+ it("says so when the backup made the image, and why the base did not", async () => {
+ const { deps: d } = deps({ cfg: { ...CFG, imageGen: { ...CFG.imageGen, key: "" } } });
+ const result = await generateImageForTurn({ prompt: "owl" }, d);
+ expect(result.body).toEqual({ text: expect.stringMatching(/xAI .*backup image provider, because the base failed: Add an OpenAI image API key first/) });
+ });
+
+ it("still moves to the backup when the person names a provider the base and backup share", async () => {
+ const fetchImpl = vi.fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response("{}", { status: 429 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ data: [{ b64_json: PNG.toString("base64") }] })));
+ const cfg = { imageGen: { key: "openai-secret", primary: { provider: "openai" as const }, fallback: { provider: "openai" as const, model: "gpt-image-1" } } };
+ const { deps: d } = deps({ cfg, fetchImpl });
+ const result = await generateImageForTurn({ prompt: "owl", provider: "openai" }, d);
+ expect(result).toEqual({ status: 201, body: { text: expect.stringContaining("OpenAI (gpt-image-1), the person's backup image provider") } });
+ });
+
+ it("keeps a failure outside the provider, such as saving the file, away from the model", async () => {
+ const { deps: d } = deps();
+ d.turn!.attach = () => { throw new Error("ENOSPC: no space left on device, open 'C:/private/attachments/x.png'"); };
+ expect(await generateImageForTurn({ prompt: "owl" }, d)).toEqual({ status: 500, body: { error: IMAGE_MESSAGES.notSaved } });
+ });
+
+ it("uses the provider the person named when it is their backup", async () => {
+ const fetchImpl = okFetch();
+ const { deps: d } = deps({ fetchImpl });
+ await generateImageForTurn({ prompt: "owl", provider: "xai" }, d);
+ expect(String(vi.mocked(fetchImpl).mock.calls[0]![0])).toContain("api.x.ai");
+ });
+
+ it("refuses a provider that is neither the base nor the backup, naming the ones set", async () => {
+ const { deps: d, attached } = deps();
+ const result = await generateImageForTurn({ prompt: "owl", provider: "gemini" }, d);
+ expect(result.status).toBe(400);
+ expect(result.body).toEqual({ error: expect.stringMatching(/Gemini.*base is OpenAI.*backup is xAI/) });
+ expect(attached).toEqual([]);
+ });
+
+ it("points the person to Settings when nothing is set up", async () => {
+ const { deps: d } = deps({ cfg: { imageGen: {} } });
+ const result = await generateImageForTurn({ prompt: "owl" }, d);
+ expect(result).toEqual({ status: 409, body: { error: IMAGE_MESSAGES.notSetUp } });
+ });
+
+ it("stops at the turn's image limit without calling a provider", async () => {
+ const fetchImpl = okFetch();
+ const { deps: d } = deps({ fetchImpl, cfg: { ...CFG, imageGen: { ...CFG.imageGen, maxPerTurn: 2 } }, parked: 2 });
+ const result = await generateImageForTurn({ prompt: "owl" }, d);
+ expect(result.status).toBe(429);
+ expect(result.body).toEqual({ error: expect.stringContaining("2 images") });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it("counts an image still being made, so parallel calls cannot pass the limit", async () => {
+ let finish!: () => void;
+ const started = new Promise<void>((resolve) => { finish = resolve; });
+ const fetchImpl = vi.fn<typeof fetch>(async () => {
+ await started;
+ return new Response(JSON.stringify({ data: [{ b64_json: PNG.toString("base64") }] }));
+ });
+ const { deps: d, attached } = deps({ fetchImpl, cfg: { ...CFG, imageGen: { ...CFG.imageGen, maxPerTurn: 1 } } });
+ const first = generateImageForTurn({ prompt: "owl" }, d);
+ const second = generateImageForTurn({ prompt: "fox" }, d);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ finish();
+ expect((await Promise.all([first, second])).map((result) => result.status)).toEqual([201, 429]);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(attached).toHaveLength(1);
+ });
+
+ it("frees the slot of an image that failed, so the next call can still make one", async () => {
+ const fetchImpl = vi.fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response("", { status: 500 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ data: [{ b64_json: PNG.toString("base64") }] })));
+ const { deps: d, attached } = deps({ fetchImpl, cfg: { ...CFG, imageGen: { ...CFG.imageGen, maxPerTurn: 1 } } });
+ expect((await generateImageForTurn({ prompt: "owl" }, d)).status).toBe(502);
+ expect((await generateImageForTurn({ prompt: "owl" }, d)).status).toBe(201);
+ expect(attached).toHaveLength(1);
+ });
+
++ it("makes no image in a turn no person started, such as a routine's or a webhook's", async () => {
++ const fetchImpl = okFetch();
++ const { deps: d, attached } = deps({ fetchImpl, personTurn: false });
++ expect(await generateImageForTurn({ prompt: "owl" }, d)).toEqual({ status: 403, body: { error: IMAGE_MESSAGES.notPerson } });
++ expect(fetchImpl).not.toHaveBeenCalled();
++ expect(attached).toEqual([]);
++ });
++
++ it("stops at the day's image cap without calling a provider, across turns and restarts", async () => {
++ const dataDir = scratch();
++ const first = deps({ dataDir, dailyCap: 2 });
++ expect((await generateImageForTurn({ prompt: "owl" }, first.deps)).status).toBe(201);
++ const fetchImpl = okFetch();
++ const restarted = deps({ dataDir, dailyCap: 2, fetchImpl, cfg: { ...CFG, imageGen: { ...CFG.imageGen, maxPerTurn: 9 } } });
++ expect((await generateImageForTurn({ prompt: "fox" }, restarted.deps)).status).toBe(201);
++ expect(await generateImageForTurn({ prompt: "cat" }, restarted.deps)).toEqual({ status: 429, body: { error: IMAGE_MESSAGES.dailyCap(2) } });
++ expect(fetchImpl).toHaveBeenCalledTimes(1);
++ });
++
+ it("refuses when no turn is running, and drops an image whose turn ended meanwhile", async () => {
+ const idle = deps({ noTurn: true });
+ expect((await generateImageForTurn({ prompt: "owl" }, idle.deps)).status).toBe(409);
+
+ const ended = deps({ live: false });
+ expect((await generateImageForTurn({ prompt: "owl" }, ended.deps)).status).toBe(409);
+ expect(ended.attached).toEqual([]);
+ });
+
+ it.each([{}, { prompt: " " }, { prompt: "x".repeat(4001) }, { prompt: "owl", aspect: "4:3" }])("rejects a malformed call: %j", async (body) => {
+ const { deps: d } = deps();
+ expect((await generateImageForTurn(body, d)).status).toBe(400);
+ });
+
+ it("returns the provider's redacted error, not its body", async () => {
+ const fetchImpl = vi.fn<typeof fetch>(async () => new Response("Bearer openai-secret", { status: 500 }));
+ const { deps: d } = deps({ fetchImpl });
+ const result = await generateImageForTurn({ prompt: "owl" }, d);
+ expect(result).toEqual({ status: 502, body: { error: "OpenAI image generation failed (HTTP 500, model gpt-image-2)" } });
+ });
+});
+
+describe("the generate_image route", () => {
- function route(options: { fetchImpl: typeof fetch; requireActive?: () => void }) {
++ function route(options: { fetchImpl: typeof fetch; requireActive?: () => void; personTurn?: boolean }) {
+ const live = new Map([["thread", "turn-1"]]);
+ const parked = new Map<string, GeneratedImage[]>();
+ const routes = createImageToolRoutes({
+ config: () => ({ ...CFG, imageGen: { ...CFG.imageGen, maxPerTurn: 1 } }),
++ dataDir: scratch(),
+ fetchImpl: options.fetchImpl,
+ liveTurn: (threadId) => live.get(threadId),
+ key: (threadId, turnId) => `${threadId}:${turnId}`,
+ images: (key) => parked.get(key)?.length ?? 0,
+ park: (key, image) => { parked.set(key, [...parked.get(key) ?? [], image]); },
+ });
+ const res = new ServerResponse(new IncomingMessage(new Socket()));
+ const call = async () => {
+ let answer: { status: number; body: unknown } | undefined;
+ await routes.internal({
+ method: "POST", path: "/api/internal/images/generate", res,
+ json: (_res: ServerResponse, status: number, body: unknown) => { answer = { status, body }; },
+ readBody: async () => ({ prompt: "owl" }),
- threadId: "thread", requireActive: options.requireActive ?? (() => {}),
++ threadId: "thread", requireActive: options.requireActive ?? (() => {}), personTurn: options.personTurn ?? true,
+ });
+ return answer!;
+ };
+ return { call, live, parked, res };
+ }
+
+ it("drops an image whose turn was replaced while it was made, and frees its slot", async () => {
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ const fetchImpl = vi.fn<typeof fetch>(async () => {
+ await held;
+ return new Response(JSON.stringify({ data: [{ b64_json: PNG.toString("base64") }] }));
+ });
+ const r = route({ fetchImpl });
+ const pending = r.call();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ r.live.set("thread", "turn-2");
+ release();
+ expect(await pending).toEqual({ status: 409, body: { error: IMAGE_MESSAGES.noTurn } });
+ expect([...r.parked.values()].flat()).toEqual([]);
+ expect((await r.call()).status).toBe(201);
+ expect(r.parked.get("thread:turn-2")).toHaveLength(1);
+ });
+
+ it("answers 401 and parks nothing when the capability expired while the image was made", async () => {
+ let checks = 0;
+ const requireActive = () => {
+ if (++checks === 2) throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });
+ };
+ const r = route({ fetchImpl: okFetch(), requireActive });
+ expect(await r.call()).toEqual({ status: 401, body: { error: "the internal turn capability has expired" } });
+ expect([...r.parked.values()].flat()).toEqual([]);
+ expect((await r.call()).status).toBe(201);
+ });
+
++ it("answers a turn no person started with a refusal the bot can pass on, and parks nothing", async () => {
++ const fetchImpl = okFetch();
++ const r = route({ fetchImpl, personTurn: false });
++ expect(await r.call()).toEqual({ status: 403, body: { error: IMAGE_MESSAGES.notPerson } });
++ expect(fetchImpl).not.toHaveBeenCalled();
++ expect([...r.parked.values()].flat()).toEqual([]);
++ });
++
+ it("leaves other requests to the next route", async () => {
- const routes = createImageToolRoutes({ config: () => CFG, liveTurn: () => "turn", key: (a, b) => a + b, images: () => 0, park: () => {} });
++ const routes = createImageToolRoutes({ config: () => CFG, dataDir: scratch(), liveTurn: () => "turn", key: (a, b) => a + b, images: () => 0, park: () => {} });
+ const answered = vi.fn<(res: ServerResponse, status: number, body: unknown) => void>();
+ const res = new ServerResponse(new IncomingMessage(new Socket()));
- const out = await routes.internal({ method: "POST", path: "/api/internal/voice-note", res, json: answered, readBody: async () => ({}), threadId: "t", requireActive: () => {} });
++ const out = await routes.internal({ method: "POST", path: "/api/internal/voice-note", res, json: answered, readBody: async () => ({}), threadId: "t", requireActive: () => {}, personTurn: true });
+ expect(typeof out).toBe("symbol");
+ expect(answered).not.toHaveBeenCalled();
+ });
+
+ it("cancels the provider call when the bot's tool call goes away", async () => {
+ let signal: AbortSignal | undefined;
+ const fetchImpl = vi.fn<typeof fetch>((_input, init) => new Promise((_resolve, reject) => {
+ signal = init!.signal!;
+ signal.addEventListener("abort", () => reject(Object.assign(new Error("aborted"), { name: "AbortError" })));
+ }));
+ const r = route({ fetchImpl });
+ const pending = r.call();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ r.res.emit("close");
+ expect(await pending).toEqual({ status: 409, body: { error: "Image generation was cancelled" } });
+ expect(signal!.aborted).toBe(true);
+ expect([...r.parked.values()].flat()).toEqual([]);
+ });
+});
diff --cc server/routes/image-tools.ts
index a5e5d32f45,0000000000..3fb53c9361
mode 100644,000000..100644
--- a/server/routes/image-tools.ts
+++ b/server/routes/image-tools.ts
@@@ -1,132 -1,0 +1,146 @@@
+import type { ServerResponse } from "node:http";
+import { z } from "zod";
+
+import { IMAGE_MAX_PER_TURN_DEFAULT, IMAGE_PROVIDERS } from "../../shared/image-generation.ts";
+import { IMAGE_PROMPT_MAX_CHARS } from "../drivers/agents-image-tools.ts";
+import {
+ generateImage, imageGenerationReady, imageProviderName, imageSlots,
+ type GeneratedImage, type ImageCredentials,
+} from "../image-generation.ts";
++import { createImageDailyCap, type ImageDailyCap } from "../image-daily-cap.ts";
+import type { json } from "../harness/http.ts";
+import { PASS } from "./table.ts";
+
+export const IMAGE_MESSAGES = {
+ notSetUp: "Image generation isn't set up on this computer. Ask the person to choose an image provider in Settings → AI → Image generation (shown in advanced mode).",
+ noTurn: "This turn has not started yet or already ended, so the image could not be attached.",
+ notSaved: "The image could not be saved on this computer. Try again shortly.",
++ notPerson: "Images are made only for a person's own message in a chat. This turn was started another way (a routine, a webhook, an app, a guest or a room goal's coordinator), so no image was made. Tell the person they can ask for the image in a chat.",
++ dailyCap: (cap: number) => `Bots on this computer have made ${cap} images today, the most allowed in one day, so no image was made. Tell the person it starts again after midnight.`,
+} as const;
+
+const requestSchema = z.object({
+ prompt: z.string().trim().min(1).max(IMAGE_PROMPT_MAX_CHARS),
+ aspect: z.enum(["1:1", "16:9", "9:16"]).optional(),
+ provider: z.enum(IMAGE_PROVIDERS).optional(),
+});
+
+export interface ImageTurn {
+ key: string;
+ parked: () => number;
+ attach: (image: GeneratedImage) => boolean;
+}
+
+export interface ImageToolDeps {
+ cfg: ImageCredentials;
++ /** A person's own line started this turn's work, from the harness's records (server/peer-provenance.ts, and a room
++ * run's request line): never a routine, a webhook, an app, a guest or a goal's coordinator, whose images never land. */
++ personTurn: boolean;
++ daily: ImageDailyCap;
+ fetchImpl?: typeof fetch;
+ turn: ImageTurn | null;
+ /** Images still being made, per turn key: they count toward the limit before they are attached. */
+ inFlight: Map<string, number>;
+ signal?: AbortSignal;
+}
+
+type Outcome = { status: number; body: { text: string } | { error: string } };
+
+export async function generateImageForTurn(raw: unknown, deps: ImageToolDeps): Promise<Outcome> {
+ const parsed = requestSchema.safeParse(raw);
+ if (!parsed.success) {
+ return { status: 400, body: { error: `generate_image takes a prompt (1 to ${IMAGE_PROMPT_MAX_CHARS} characters), an optional aspect (1:1, 16:9 or 9:16) and an optional provider.` } };
+ }
+ const { prompt, aspect, provider } = parsed.data;
++ if (!deps.personTurn) return { status: 403, body: { error: IMAGE_MESSAGES.notPerson } };
+ const { turn } = deps;
+ if (!turn) return { status: 409, body: { error: IMAGE_MESSAGES.noTurn } };
+ const limit = deps.cfg.imageGen?.maxPerTurn ?? IMAGE_MAX_PER_TURN_DEFAULT;
+ if (turn.parked() + (deps.inFlight.get(turn.key) ?? 0) >= limit) {
+ return { status: 429, body: { error: `This turn already has ${limit} images, the most the person allows per reply. Send what you have.` } };
+ }
+
+ const { primary, fallback } = imageSlots(deps.cfg);
+ let slot: "primary" | "fallback" | undefined;
+ if (provider) {
+ const base = primary.provider === provider;
+ const backup = fallback?.provider === provider;
+ if (!base && !backup) {
+ const set = `the base is ${imageProviderName(primary.provider)}${fallback ? ` and the backup is ${imageProviderName(fallback.provider)}` : " and there is no backup"}`;
+ return { status: 400, body: { error: `${imageProviderName(provider)} is not one of the person's image providers: ${set}. Use one of those, or ask the person to change it in Settings.` } };
+ }
+ if (!(base && backup)) slot = base ? "primary" : "fallback";
+ } else if (!imageGenerationReady(deps.cfg)) {
+ return { status: 409, body: { error: IMAGE_MESSAGES.notSetUp } };
+ }
+
++ if (!deps.daily.reserve()) return { status: 429, body: { error: IMAGE_MESSAGES.dailyCap(deps.daily.cap) } };
++ let made = false;
+ deps.inFlight.set(turn.key, (deps.inFlight.get(turn.key) ?? 0) + 1);
+ try {
+ const image = await generateImage(deps.cfg, { prompt, aspect }, { slot, fetchImpl: deps.fetchImpl, signal: deps.signal });
++ made = true;
+ if (!turn.attach({ bytes: image.bytes, mime: image.mime })) return { status: 409, body: { error: IMAGE_MESSAGES.noTurn } };
+ const backup = image.usedFallback ? `, the person's backup image provider${image.baseError ? `, because the base failed: ${image.baseError}` : ""}` : "";
+ const by = `${imageProviderName(image.provider)} (${image.model})${backup}`;
+ return { status: 201, body: { text: `Image made by ${by}. It will be attached to this turn's reply when the turn ends.` } };
+ } catch (error) {
+ const status = (error as { status?: unknown } | null)?.status;
+ if (typeof status !== "number" || !(error instanceof Error)) return { status: 500, body: { error: IMAGE_MESSAGES.notSaved } };
+ return { status, body: { error: error.message } };
+ } finally {
++ deps.daily.settle(made);
+ const left = (deps.inFlight.get(turn.key) ?? 1) - 1;
+ if (left > 0) deps.inFlight.set(turn.key, left); else deps.inFlight.delete(turn.key);
+ }
+}
+
+export interface ImageRouteContext {
+ method: string;
+ path: string;
+ res: ServerResponse;
+ json: typeof json;
+ readBody: () => Promise<unknown>;
+ threadId: string;
+ requireActive: () => void;
++ personTurn: boolean;
+}
+
+export interface ImageTurnStore {
+ liveTurn: (threadId: string) => string | undefined;
+ key: (threadId: string, turnId: string) => string;
+ images: (key: string) => number;
+ park: (key: string, image: GeneratedImage) => void;
+}
+
+export function imageTurn(store: ImageTurnStore, threadId: string, requireActive: () => void): ImageTurn | null {
+ requireActive();
+ const turnId = store.liveTurn(threadId);
+ if (!turnId) return null;
+ const key = store.key(threadId, turnId);
+ return {
+ key,
+ parked: () => store.images(key),
+ attach: (image) => {
+ requireActive();
+ if (store.liveTurn(threadId) !== turnId) return false;
+ store.park(key, image);
+ return true;
+ },
+ };
+}
+
- export function createImageToolRoutes(deps: ImageTurnStore & { config: () => ImageCredentials; fetchImpl?: typeof fetch }) {
++export function createImageToolRoutes(deps: ImageTurnStore & { config: () => ImageCredentials; dataDir: string; fetchImpl?: typeof fetch }) {
+ const inFlight = new Map<string, number>();
++ const daily = createImageDailyCap(deps.dataDir);
+ return {
+ async internal(ctx: ImageRouteContext): Promise<typeof PASS | void> {
+ if (ctx.method !== "POST" || ctx.path !== "/api/internal/images/generate") return PASS;
+ const turn = imageTurn(deps, ctx.threadId, ctx.requireActive);
+ const call = new AbortController();
+ ctx.res.once("close", () => { if (!ctx.res.writableEnded) call.abort(); });
- const outcome = await generateImageForTurn(await ctx.readBody(), { cfg: deps.config(), fetchImpl: deps.fetchImpl, turn, inFlight, signal: call.signal });
++ const outcome = await generateImageForTurn(await ctx.readBody(), { cfg: deps.config(), personTurn: ctx.personTurn, daily, fetchImpl: deps.fetchImpl, turn, inFlight, signal: call.signal });
+ ctx.json(ctx.res, outcome.status, outcome.body);
+ },
+ };
+}