Compare commits

...
3 Commits
Author SHA1 Message Date
tben 37bd3335ff Bump version to 0.19.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 12:12:22 +01:00
tben 0a6d7d7410 Let a worker hand on a task of its own, and stop rooms closing over live work
A worker told to hand its tasks to another bot had no tool for it: it asked
the crew instead, the coordinator answered over the Software Engineer's
still-running job (closing the room cancels it), and the answer said the
tasks were picked up. Nothing had moved.

hand_over_task passes an open task of the worker's own list to a bot it
could already ask, reporting back in its session. answer_requester and
refuse_request now refuse over a live job unless close_anyway says
otherwise. ask_user and suggest_next_steps stay out of hidden sessions,
where no card exists to answer and a bare ref reached the coordinator.
2026-11-13 12:12:18 +01:00
tben 7a0e16a6b5 Show what a chatroom's bots spent, message by message and in total 2026-11-13 11:55:58 +01:00
46 changed files with 1422 additions and 101 deletions
+5 -5
View File
@@ -83,7 +83,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bot types
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). A plain worker gets no work to hand out, but may pass on an open task of its own to a bot it could ask (`hand_over_task`, `hand-over-task-tool.ts`): its one permission, its own list only, and `BotTypeTargetMatrix` is left alone so it still directs no one, the targets coming from `chatroomAskableBots`. Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
### Bots, sessions, chat
@@ -99,7 +99,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`.
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
@@ -133,7 +133,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
### Chatrooms (`chatrooms`)
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). Closing is what cancels a room's jobs, so `answer_requester` and `refuse_request` refuse while a member job still runs (`grabChatroomOpenJobs`, `chatroomOpenJobsWarning`) unless given `close_anyway`: a coordinator that answered over a live run once killed the very work it was asked for, then reported it picked up. A coordinator's turn creates no task and moves none (`chatroomCoordinatorNote`): a task is handed over by the bot that has it or by the user. A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. A room shows what it cost the way a conversation's messages do: each message carries its `MessageUsageChip` and the Details modal (read through the room's own `api/admin/chatrooms/message-details`, which checks the room's user), and above the thread `ChatroomUsageSummary` totals the room (`usage` on its summary, from `grabChatroomUsage`: every model call counted by its run's `bot_sessions.chatroom_id`, a turn still running included, with the room's failed calls and the same split by bot). **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
### Workspaces
@@ -165,7 +165,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -221,7 +221,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, `hand_over_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.10",
"version": "0.19.0",
"module": "index.ts",
"type": "module",
"private": true,
+34 -16
View File
@@ -17,6 +17,7 @@ import {
CoordinatorSoloNote,
TasksNote,
TaskReminderNote,
HandOverTaskNote,
workspaceAdminNote,
WorkspaceLearningNote,
openRunsNote,
@@ -331,6 +332,12 @@ export default async function runBotReply({
* admin is told who leads it.
*/
const can_delegate = tools.some((tool) => tool.name == "delegate_task");
/**
* A worker passes on a task of its own (`hand_over_task`): the reply says
* where it went and that it needs the run id, so no one claims a hand-over
* that didn't happen.
*/
const can_hand_over = tools.some((tool) => tool.name == "hand_over_task");
const lead = led as WorkspaceAdminTools | null;
const crew_note = powers.is_coordinator
? can_delegate
@@ -357,9 +364,10 @@ export default async function runBotReply({
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
TasksNote,
TaskReminderNote,
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
RequestScopeNote({ can_ask: true }),
QuestionsNote,
RequestScopeNote({ can_ask: Boolean(attended) }),
attended ? QuestionsNote : "",
SecretsNote,
SettingsNote,
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
@@ -410,20 +418,30 @@ export default async function runBotReply({
onRequest: ({ ref }) => proposals.push(ref),
onShow: ({ ref }) => shown.push(ref),
}),
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => shown.push(ref),
}),
/**
* Only where the user follows the conversation: a chatroom's
* hidden session has no card they could answer, and a
* question there was once shown to the coordinator as a bare
* ref, its answer never reaching the bot.
*/
...(attended
? [
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => shown.push(ref),
}),
]
: []),
...(has_past_sessions
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
: []),
+17 -3
View File
@@ -418,6 +418,20 @@ You have tasks of your own to keep up with. When the message is an opening ("hel
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
- Never invent a task: name only what list_tasks returned.`;
/**
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
* already has to another bot, instead of asking the coordinator to reassign
* it (which no tool of its own can do, and a room once answered as if it
* had been done).
*/
export const HandOverTaskNote = `# Passing a task on
A task on your own list can go to another bot with hand_over_task: it moves to their list, they work that same task, and their result comes back to this conversation. Do it only when the user asked for that task to go to that bot; the list is theirs and the work costs them a run.
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
- Say where it went with the run id the tool returned. Never say a task was handed over, or that someone picked work up, without it.
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
/**
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
* the user approved its brief when they set it up, so it acts on its own.
@@ -536,9 +550,9 @@ Each turn, decide and act with one of your tools:
askable.length
? askable.map((bot) => `${bot.id}: ${bot.name || "A bot"}${bot.role ? ` (${bot.role})` : ""}`).join("; ")
: "none"
}. Their work comes back to you in the room, and you get another turn.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why.
}. Their work comes back to you in the room, and you get another turn. A message from one of them while it works is where it has got to, not its answer: it may still be running a task for many minutes, and only its answer, its failure, or its finished report speaks for it.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out. Answering closes the room and cancels anything still running in it, so while a bot is working the tool refuses unless you pass close_anyway: pass it only when the answer doesn't depend on what that bot is doing.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why, concretely: what the blocker is, who can clear it and how. Same close_anyway rule. Never turn a request into a claim that it was carried out: you can't create, edit, move or reassign a task, add a bot to a workspace, or start a run for anyone, and nothing you say makes one happen. A task is moved by the bot that has it (its hand_over_task) or by the user (Hand over in the UI); when that's what was asked for, say so and name that bot.
Ask one bot at a time and only ask again when the answer falls short. You have ${turns_left} turn${turns_left == 1 ? "" : "s"} left in this room; on the last one, answer with what you have or refuse. Your own words in the room are short notes on what you're doing.`;
+15 -2
View File
@@ -27,6 +27,10 @@ export const BotPermissions = [
value: "delegate_task",
title: "Hand tasks to other bots",
},
{
value: "hand_over_task",
title: "Hand a task on its own list to another bot",
},
{
value: "set_member_instructions",
title: "Set other bots' workspace instructions",
@@ -72,18 +76,27 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
coordinator: BotPermissions.map((bp) => bp.value),
workspace_admin: [
"delegate_task",
"hand_over_task",
"set_member_instructions",
"manage_workspace_tasks",
"edit_workspace",
],
worker: [],
/**
* A worker can't hand out work: it passes on a task it already has
* (`hand_over_task`), and asks the crew for anything else through the
* coordinator (`ask_crew`).
*/
worker: ["hand_over_task"],
};
/**
* Which bots a bot may act on (hand a task to, set instructions for), keyed
* by the target's role. Same shape as `UserTypeAssignmentMatrix`: the
* coordinator passes through. A workspace admin directs workers only, so
* two admins never hand work back and forth.
* two admins never hand work back and forth. A worker directs no one
* either: `hand_over_task` takes a task it already has to a bot it could
* ask, which its own tool decides (`chatroomAskableBots`), not this
* matrix.
*/
export const BotTypeTargetMatrix: TypeAssignmentMatrixType<BotRole> = {
coordinator: {},
@@ -1,17 +1,24 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import type { ChatroomBot, ChatroomJob, ChatroomSummary } from "@/src/types";
import grabChatroomUsage from "../usage/grab-chatroom-usage";
type Params = {
chatrooms: BUN_SQLITE_COBBLE_CHATROOMS[];
/**
* Sum what each room's bots spent there, for the room's own header. A
* list doesn't need it, and it costs a query per call.
*/
with_usage?: boolean;
};
/**
* Rooms with the bots in them, asking bot first, then the coordinator,
* then the bots it asked in the order they joined, the jobs still open in
* the room, and the workspace it's in by name.
* the room, the workspace it's in by name, and (when asked for) what its
* bots spent working there.
*/
export default async function chatroomSummaries({ chatrooms }: Params): Promise<ChatroomSummary[]> {
export default async function chatroomSummaries({ chatrooms, with_usage }: Params): Promise<ChatroomSummary[]> {
if (!chatrooms.length) return [];
const ids = chatrooms.map((room) => Number(room.id));
@@ -40,6 +47,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
).payload || [];
const workspace_ids = [...new Set(chatrooms.map((room) => Number(room.workspace_id)).filter(Boolean))];
const usage = with_usage ? await grabChatroomUsage({ chatroom_ids: ids }) : null;
const workspace_names = new Map(
(workspace_ids.length
? (
@@ -72,6 +80,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
session_id: Number(job.session_id),
})),
workspace_name: room.workspace_id ? workspace_names.get(Number(room.workspace_id)) || null : null,
...(usage ? { usage: usage.get(Number(room.id)) } : {}),
};
});
}
@@ -0,0 +1,43 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
message_id: number | string;
/**
* Only a message posted in one of the user's own rooms.
*/
user_id: number | string;
};
type ChatroomMessageRef = {
id: number;
created_at: number;
chatroom_id: number;
};
/**
* A message posted in a chatroom of the user's, with the room it's in, or
* null. The access check for what the message's details may show.
*/
export default async function grabChatroomMessage({
message_id,
user_id,
}: Params): Promise<ChatroomMessageRef | null> {
const row = (
await BunSQLite.sql<ChatroomMessageRef>({
sql: `SELECT m.id, m.created_at, s.chatroom_id FROM bot_messages m
JOIN bot_sessions s ON s.id = m.session_id
JOIN chatrooms c ON c.id = s.chatroom_id
WHERE m.id = ? AND c.user_id = ? AND s.chatroom_id IS NOT NULL
LIMIT 1`,
values: [message_id, user_id],
})
).payload?.[0];
if (!row?.id) return null;
return {
id: Number(row.id),
created_at: Number(row.created_at) || 0,
chatroom_id: Number(row.chatroom_id),
};
}
@@ -1,16 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { BotMessageWithAttachments } from "@/src/types";
import grabMessageUsage from "../usage/grab-message-usage";
type Params = {
chatroom_id: number | string;
};
/**
* Every message in a chatroom, from every bot in it, oldest first. Rooms
* are short (the coordinator's turns are capped), so they're read whole.
* Every message in a chatroom, from every bot in it, oldest first, each
* with what it cost. Rooms are short (the coordinator's turns are capped),
* so they're read whole.
*/
export default async function grabChatroomMessages({ chatroom_id }: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES[]> {
return (
export default async function grabChatroomMessages({
chatroom_id,
}: Params): Promise<BotMessageWithAttachments[]> {
const messages =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_MESSAGES>({
sql: `SELECT m.* FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id
@@ -18,6 +23,15 @@ export default async function grabChatroomMessages({ chatroom_id }: Params): Pro
ORDER BY m.created_at ASC, m.id ASC`,
values: [chatroom_id],
})
).payload || []
);
}
).payload || [];
if (!messages.length) return messages;
const usage = await grabMessageUsage({ message_ids: messages.map((message) => Number(message.id)) });
return messages.map((message): BotMessageWithAttachments => {
const spent = usage.get(Number(message.id));
return spent ? { ...message, usage: spent } : message;
});
}
@@ -0,0 +1,41 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
chatroom_id: number | string;
/**
* The job asking (the coordinator's own turn), which is still running as
* it reads: never counted.
*/
except_job_id?: number | string | null;
};
export type ChatroomOpenJob = {
id: number;
bot_id: number | null;
bot_name: string | null;
status: string;
};
/**
* The jobs a room still runs (pending or processing), with the bot each
* works for: closing a room cancels them (`cancelChatroomJobs`), so the
* tools that close one ask first whether anyone is still at work.
*/
export default async function grabChatroomOpenJobs({ chatroom_id, except_job_id }: Params): Promise<ChatroomOpenJob[]> {
const res = await BunSQLite.sql<ChatroomOpenJob>({
sql: `SELECT q.id, q.bot_id, b.name AS bot_name, q.status
FROM bots_queue q
JOIN bot_sessions s ON s.id = q.session_id
LEFT JOIN bots b ON b.id = q.bot_id
WHERE s.chatroom_id = ? AND q.status IN ('pending', 'processing') AND q.id != ?
ORDER BY q.id`,
values: [Number(chatroom_id), Number(except_job_id) || 0],
});
return (res.payload || []).map((job) => ({
id: Number(job.id),
bot_id: job.bot_id ? Number(job.bot_id) : null,
bot_name: job.bot_name || null,
status: job.status,
}));
}
@@ -8,12 +8,13 @@ type Params = {
};
/**
* One of the user's own chatrooms with the bots in it, or null.
* One of the user's own chatrooms with the bots in it and what they spent
* working there, or null.
*/
export default async function grabUserChatroom({ chatroom_id, user_id }: Params): Promise<ChatroomSummary | null> {
const room = await grabChatroom({ chatroom_id, user_id });
if (!room?.id) return null;
return (await chatroomSummaries({ chatrooms: [room] }))[0] || null;
return (await chatroomSummaries({ chatrooms: [room], with_usage: true }))[0] || null;
}
@@ -1,5 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
import withMessageUsage from "../usage/with-message-usage";
import grabChatroom from "./grab-chatroom";
import pushChatroomUpdated from "./push-chatroom-updated";
@@ -9,18 +10,20 @@ type Params = {
};
/**
* Pushes a message posted in a room (`server:chatroom-message`) and the
* room as it is now to the room's user.
* Pushes a message posted in a room (`server:chatroom-message`), with what
* it cost, and the room as it is now to the room's user.
*/
export default async function pushChatroomMessage({ chatroom_id, message }: Params) {
const room = await grabChatroom({ chatroom_id });
if (!room?.id || !room.user_id) return;
const [pushed] = await withMessageUsage({ messages: [message] });
sendToUser({
user_id: room.user_id,
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message } },
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message: pushed } },
});
await pushChatroomUpdated({ chatroom_id: room.id });
}
}
@@ -9,7 +9,8 @@ type Params = {
/**
* Pushes a room as it is now (`server:chatroom-updated`) to its user's
* open tabs, for the rail and the room's header. Best effort.
* open tabs, for the rail and the room's header, what its bots spent
* included, for the totals at its top. Best effort.
*/
export default async function pushChatroomUpdated({ chatroom_id }: Params) {
try {
@@ -17,7 +18,7 @@ export default async function pushChatroomUpdated({ chatroom_id }: Params) {
if (!room?.id || !room.user_id) return;
const [summary] = await chatroomSummaries({ chatrooms: [room] });
const [summary] = await chatroomSummaries({ chatrooms: [room], with_usage: true });
if (summary) {
sendToUser({ user_id: room.user_id, data: { event: "server:chatroom-updated", data: summary } });
@@ -0,0 +1,145 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
type Call = {
session_id: number | null;
job_id: number | null;
prompt_tokens: number;
cached_tokens: number | null;
completion_tokens: number;
cost: number | null;
};
function seed() {
const db = new Database(":memory:");
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, bot_id INTEGER, chatroom_id INTEGER, hook_id INTEGER)`);
db.run(`CREATE TABLE token_usages (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER,
prompt_tokens INTEGER, cached_tokens INTEGER, completion_tokens INTEGER, cost REAL)`);
db.run(`CREATE TABLE harness_call_failures (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER)`);
/**
* Room 1 has one hidden session per bot; 300 belongs to another room,
* 400 to a bot's own conversation (no room), 500 to a hook's own.
*/
db.run(`INSERT INTO bot_sessions VALUES
(100, 10, 1, NULL), (200, 20, 1, NULL), (300, 10, 2, NULL), (400, 10, NULL, NULL), (500, 20, NULL, 3)`);
let calls = 0;
const addCall = ({ bot_id, call }: { bot_id: number; call: Call }) =>
db.run(`INSERT INTO token_usages (id, bot_id, session_id, job_id, prompt_tokens, cached_tokens, completion_tokens, cost)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
++calls,
bot_id,
call.session_id,
call.job_id,
call.prompt_tokens,
call.cached_tokens,
call.completion_tokens,
call.cost,
]);
let failures = 0;
const addFailure = ({ bot_id, session_id }: { bot_id: number; session_id: number | null }) =>
db.run(`INSERT INTO harness_call_failures (id, bot_id, session_id, job_id) VALUES (?, ?, ?, NULL)`, [
++failures,
bot_id,
session_id,
]);
return { db, addCall, addFailure };
}
function callsByRoom({ db }: { db: Database }) {
const { sql, values } = chatroomUsageCallsSql({ chatroom_ids: [1] });
const rows = db.query(sql).all(...values) as {
chatroom_id: number;
bot_id: number;
calls: number;
prompt_tokens: number;
cached_tokens: number;
completion_tokens: number;
cost: number;
}[];
return rows
.map((row) => ({
chatroom_id: Number(row.chatroom_id),
bot_id: Number(row.bot_id),
calls: Number(row.calls),
prompt_tokens: Number(row.prompt_tokens),
cached_tokens: Number(row.cached_tokens),
completion_tokens: Number(row.completion_tokens),
cost: Number(row.cost),
}))
.sort((a, b) => a.bot_id - b.bot_id);
}
function failuresByRoom({ db }: { db: Database }) {
const { sql, values } = chatroomUsageFailuresSql({ chatroom_ids: [1] });
const rows = db.query(sql).all(...values) as { chatroom_id: number; failed_calls: number }[];
return rows.map((row) => ({ chatroom_id: Number(row.chatroom_id), failed_calls: Number(row.failed_calls) }));
}
describe("chatroomUsageCallsSql", () => {
test("sums a room's calls by bot", () => {
const { db, addCall } = seed();
addCall({
bot_id: 10,
call: { session_id: 100, job_id: null, prompt_tokens: 100, cached_tokens: 40, completion_tokens: 20, cost: 0.5 },
});
addCall({
bot_id: 10,
call: { session_id: 100, job_id: null, prompt_tokens: 50, cached_tokens: null, completion_tokens: 10, cost: null },
});
addCall({
bot_id: 20,
call: { session_id: 200, job_id: 50, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
});
expect(callsByRoom({ db })).toEqual([
{ chatroom_id: 1, bot_id: 10, calls: 2, prompt_tokens: 150, cached_tokens: 40, completion_tokens: 30, cost: 0.5 },
{ chatroom_id: 1, bot_id: 20, calls: 1, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
]);
});
test("another room's, a bot's own conversation's and a hook's calls stay out", () => {
const { db, addCall } = seed();
const call = { job_id: null, prompt_tokens: 10, cached_tokens: null, completion_tokens: 5, cost: null };
addCall({ bot_id: 10, call: { ...call, session_id: 100 } });
addCall({ bot_id: 10, call: { ...call, session_id: 300 } });
addCall({ bot_id: 10, call: { ...call, session_id: 400 } });
addCall({ bot_id: 20, call: { ...call, session_id: 500 } });
addCall({ bot_id: 10, call: { ...call, session_id: null } });
expect(callsByRoom({ db })).toEqual([
{ chatroom_id: 1, bot_id: 10, calls: 1, prompt_tokens: 10, cached_tokens: 0, completion_tokens: 5, cost: 0 },
]);
});
test("rooms with no calls have no rows", () => {
const { db } = seed();
expect(callsByRoom({ db })).toEqual([]);
});
});
describe("chatroomUsageFailuresSql", () => {
test("counts a room's failed calls, still-running turns included", () => {
const { db, addFailure } = seed();
addFailure({ bot_id: 10, session_id: 100 });
addFailure({ bot_id: 20, session_id: 200 });
addFailure({ bot_id: 10, session_id: 300 });
addFailure({ bot_id: 10, session_id: null });
expect(failuresByRoom({ db })).toEqual([{ chatroom_id: 1, failed_calls: 2 }]);
});
});
@@ -0,0 +1,46 @@
type Params = {
/**
* The rooms whose calls are read.
*/
chatroom_ids: number[];
};
const marks = ({ chatroom_ids }: Params) => chatroom_ids.map(() => "?").join(", ");
/**
* Every model call a room's bots made, by room and by bot, summed (read by
* `grabChatroomUsage`). A call is counted by the session it ran for (each
* bot in a room has its own hidden one, `bot_sessions.chatroom_id`), which
* is the run's own attribution: a turn still running counts too, before
* any message is written, so a room's total moves while it works.
*/
export function chatroomUsageCallsSql({ chatroom_ids }: Params) {
return {
sql: `SELECT s.chatroom_id AS chatroom_id, t.bot_id AS bot_id,
COUNT(*) AS calls,
SUM(t.prompt_tokens) AS prompt_tokens,
SUM(t.cached_tokens) AS cached_tokens,
SUM(t.completion_tokens) AS completion_tokens,
SUM(t.cost) AS cost
FROM token_usages t
JOIN bot_sessions s ON s.id = t.session_id
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
GROUP BY 1, 2`,
values: [...chatroom_ids],
};
}
/**
* The rooms' model calls that failed, by room, for the count beside the
* totals. Read the same way, by the session they ran for.
*/
export function chatroomUsageFailuresSql({ chatroom_ids }: Params) {
return {
sql: `SELECT s.chatroom_id AS chatroom_id, COUNT(*) AS failed_calls
FROM harness_call_failures t
JOIN bot_sessions s ON s.id = t.session_id
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
GROUP BY 1`,
values: [...chatroom_ids],
};
}
@@ -0,0 +1,82 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { ChatroomUsage, ChatroomUsageBot } from "@/src/types";
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
import { sumSummary, toSummary } from "./grab-usage-totals";
type Params = {
/**
* The rooms whose usage is summed. A room no call touched is absent.
*/
chatroom_ids: (number | string)[];
};
type CallRow = {
chatroom_id: number;
bot_id: number | null;
calls: number | null;
prompt_tokens: number | null;
cached_tokens: number | null;
completion_tokens: number | null;
cost: number | null;
};
type FailureRow = {
chatroom_id: number;
failed_calls: number | null;
};
/**
* What each room's bots spent working in it: every model call they made
* there summed with the calls that failed, in total and per bot. A call
* belongs to the room through its run's own session, so a coordinator
* turn still running is counted before its answer is written, and a room's
* totals never wait for a message to land.
*/
export default async function grabChatroomUsage({ chatroom_ids }: Params): Promise<Map<number, ChatroomUsage>> {
const usage = new Map<number, ChatroomUsage>();
const ids = [...new Set(chatroom_ids.map(Number).filter((id) => id > 0))];
if (!ids.length) return usage;
const [call_res, failure_res] = await Promise.all([
BunSQLite.sql<CallRow>(chatroomUsageCallsSql({ chatroom_ids: ids })),
BunSQLite.sql<FailureRow>(chatroomUsageFailuresSql({ chatroom_ids: ids })),
]);
const calls = call_res.payload || [];
const failures = new Map(
(failure_res.payload || []).map((row) => [Number(row.chatroom_id), Number(row.failed_calls) || 0]),
);
const bot_ids = [...new Set(calls.map((row) => Number(row.bot_id)).filter((id) => id > 0))];
const names = new Map(
(
bot_ids.length
? (
await BunSQLite.sql<{ id: number; name: string }>({
sql: `SELECT id, name FROM bots WHERE id IN (${bot_ids.map(() => "?").join(", ")})`,
values: bot_ids,
})
).payload || []
: []
).map((row) => [Number(row.id), row.name || null]),
);
for (const id of ids) {
const by_bot: ChatroomUsageBot[] = calls
.filter((row) => Number(row.chatroom_id) == id)
.map((row) => ({
bot_id: Number(row.bot_id) || 0,
name: names.get(Number(row.bot_id)) || null,
...toSummary({ row }),
}))
.sort((a, b) => b.total_tokens - a.total_tokens || b.calls - a.calls);
usage.set(id, {
totals: sumSummary({ summaries: by_bot }),
failed_calls: failures.get(id) || 0,
by_bot,
});
}
return usage;
}
@@ -37,6 +37,9 @@ mock.module("@/src/functions/backend/db/workspaces/grab-user-workspaces", () =>
mock.module("@/src/functions/backend/db/bots/grab-crew-workers", () => ({
default: async () => workers,
}));
mock.module("@/src/functions/backend/db/chatrooms/chatroom-askable-bots", () => ({
default: async () => workers,
}));
const grabBotChatTools = (await import("./grab-bot-chat-tools")).default;
@@ -66,6 +69,32 @@ async function names({ workspace_id }: { workspace_id: number | null }) {
return tools.map((tool) => tool.name);
}
/**
* The same list for a plain worker: no work to hand out, only its own task to
* pass on, to a bot it could ask (`chatroomAskableBots`).
*/
async function workerNames({ workspace_id, allowed = ["hand_over_task"] }: { workspace_id: number | null; allowed?: string[] }) {
const worker = {
bot_types: [],
is_coordinator: false,
admin_workspace_ids: [],
is_workspace_admin: false,
can: (permission: string) => allowed.includes(permission),
};
const tools = await grabBotChatTools({
bot: { id: 5, kind: "worker", name: "SEO Expert" },
powers: worker,
user_id: 1,
computers: [],
session_id: 43,
workspace_id,
onPropose: () => {},
});
return tools.map((tool) => tool.name);
}
describe("grabBotChatTools", () => {
test("the coordinator in a workspace reaches the install's skills, servers and tools", async () => {
workers = [{ id: 5, name: "A worker", kind: "worker" }];
@@ -93,4 +122,23 @@ describe("grabBotChatTools", () => {
expect(list).toContain("list_extensions");
expect(list).toContain("propose_skill");
});
test("a worker gets no work to hand out, only its own task to pass on", async () => {
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
const list = await workerNames({ workspace_id: 11 });
expect(list).toContain("hand_over_task");
expect(list).not.toContain("delegate_task");
expect(list).not.toContain("manage_workspace_tasks");
});
test("a worker whose types don't allow it gets neither", async () => {
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
const list = await workerNames({ workspace_id: 11, allowed: [] });
expect(list).not.toContain("hand_over_task");
expect(list).not.toContain("delegate_task");
});
});
+32 -7
View File
@@ -24,6 +24,8 @@ import updateWorkspaceTool from "./update-workspace-tool";
import listWorkspacePeopleTool from "./list-workspace-people-tool";
import setUserWorkspaceRoleTool from "./set-user-workspace-role-tool";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import chatroomAskableBots from "@/src/functions/backend/db/chatrooms/chatroom-askable-bots";
import handOverTaskTool from "./hand-over-task-tool";
import setWorkspaceInstructionsTool from "./set-workspace-instructions-tool";
import startTaskTool from "./start-task-tool";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -111,9 +113,10 @@ type Params = {
* workspace's crew (a bot's core prompt is asked for from wherever the
* user is), plus set_bot_type to make a worker a workspace's admin. A
* workspace admin, in the workspace it leads, gets
* `grabWorkspaceAdminTools`. Every gate reads the bot's types (`powers`),
* never `bots.kind`. Anything else on a computer goes through a task,
* never mid-reply.
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
* a computer goes through a task, never mid-reply.
*/
export default async function grabBotChatTools({
bot,
@@ -169,12 +172,34 @@ export default async function grabBotChatTools({
];
if (!powers.is_coordinator) {
if (!workspace_id || !powers.is_workspace_admin) return tools;
if (workspace_id && powers.is_workspace_admin) {
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
return tools;
}
/**
* Only what it already has goes: the bots it may hand to are the
* ones it could ask for this user, read again when it does.
*/
if (session_id && powers.can("hand_over_task")) {
const workers = await chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id });
tools.push(
handOverTaskTool({
user_id,
bot,
session_id,
powers,
workers,
grabTargets: () => chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id }),
onTask,
}),
);
}
return tools;
}
@@ -0,0 +1,161 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
/**
* What `grabRunTask` answers: the task it would act on.
*/
let task: BUN_SQLITE_COBBLE_TASKS = {
id: 43,
title: "Cut the LCP on the homepage",
bot_id: 2,
workspace_id: 2,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
/**
* What `handOverTask` answers, and with which arguments it was called: a
* worker's hand-over has to carry the bot that had the task and the session
* the result is reported back to.
*/
let handed: Record<string, unknown> = {};
let handedArgs: Record<string, unknown> | null = null;
mock.module("@/src/functions/backend/db/tasks/grab-run-task", () => ({
default: async () => task,
}));
mock.module("@/src/functions/backend/db/tasks/hand-over-task", () => ({
default: async (args: Record<string, unknown>) => {
handedArgs = args;
return handed;
},
}));
const handOverTaskTool = (await import("./hand-over-task-tool")).default;
afterAll(() => {
mock.restore();
});
const bot = { id: 2, name: "SEO Expert", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const engineer = { id: 6, name: "Software Engineer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const designer = { id: 3, name: "Graphic Designer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const powers = {
bot_types: [],
is_coordinator: false,
admin_workspace_ids: [],
is_workspace_admin: false,
can: (permission: string) => permission == "hand_over_task",
} as unknown as BotRunPowers;
beforeEach(() => {
task = { id: 43, title: "Cut the LCP on the homepage", bot_id: 2, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
handedArgs = null;
});
function build({ targets = [engineer, designer], onTask }: { targets?: BUN_SQLITE_COBBLE_BOTS[]; onTask?: (params: { task_id: number }) => void } = {}) {
return handOverTaskTool({
user_id: 1,
bot,
session_id: 43,
powers,
workers: targets,
grabTargets: async () => targets,
onTask,
});
}
describe("handOverTaskTool", () => {
test("takes a task of its own and one of the bots it can ask", () => {
const tool = build();
expect(tool.name).toBe("hand_over_task");
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6 }).success).toBe(true);
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6, start: false }).success).toBe(true);
expect(tool.schema?.safeParse({ bot_id: 6 }).success).toBe(false);
});
test("names the crew it can hand to", () => {
const tool = build();
expect(tool.description).toContain("6: Software Engineer; 3: Graphic Designer");
});
test("hands the task over with the bot and session to report back to", async () => {
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(handedArgs?.task_id).toBe(43);
expect(handedArgs?.to_bot_id).toBe(6);
expect(handedArgs?.user_id).toBe(1);
expect(handedArgs?.handed_by).toBe("SEO Expert");
expect(handedArgs?.requested_by_bot_id).toBe(2);
expect(handedArgs?.requested_by_session_id).toBe(43);
expect(handedArgs?.start).toBe(true);
expect(String(answer)).toContain("is with Software Engineer now (job #312)");
expect(String(answer)).toContain("it's off your list");
expect(String(answer)).toContain("their result is reported back here");
});
test("the same task, not a copy: it reports the new bot's joined note", async () => {
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "It joined the workspace." };
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(String(answer)).toContain("It joined the workspace.");
});
test("start: false only moves it, and says nothing is running", async () => {
handed = { task, job_id: null, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
const answer = await build().run({ args: { task_id: 43, bot_id: 6, start: false }, signal: new AbortController().signal });
expect(handedArgs?.start).toBe(false);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("reports the task it touched, so the message links it", async () => {
const touched: number[] = [];
await build({ onTask: ({ task_id }) => touched.push(task_id) }).run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(touched).toEqual([43]);
});
test("refuses a task that isn't its own", async () => {
task = { id: 44, title: "Someone else's", bot_id: 9, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
"isn't on your own list (it's another bot's), so it isn't yours to hand over",
);
expect(handedArgs).toBeNull();
});
test("refuses a workspace-wide task", async () => {
task = { id: 44, title: "Everyone's", bot_id: null, workspace_id: 2, status: "todo" } as unknown as BUN_SQLITE_COBBLE_TASKS;
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow("(it's workspace-wide)");
});
test("refuses a bot it can't ask, and lists the ones it can", async () => {
await expect(build().run({ args: { task_id: 43, bot_id: 99 }, signal: new AbortController().signal })).rejects.toThrow(
"No bot has id 99 among the ones you can hand to. Bot: 6: Software Engineer; 3: Graphic Designer.",
);
expect(handedArgs).toBeNull();
});
test("with no crew says so", async () => {
const tool = build({ targets: [] });
expect(tool.description).toContain("Crew you can hand to: none.");
await expect(tool.run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
"No bot has id 6 among the ones you can hand to. Bot: none.",
);
});
});
@@ -0,0 +1,128 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import handOverTask from "@/src/functions/backend/db/tasks/hand-over-task";
import type { HarnessTool } from "../../types";
type Params = {
user_id: number | string;
/**
* The bot passing its own task on: the worker that has it, or a
* workspace's admin.
*/
bot: BUN_SQLITE_COBBLE_BOTS;
/**
* The session it hands over from: the new bot's result is reported
* back there (`relayJobToRequester`).
*/
session_id: number | string;
/**
* The run's reach over the task tracker (`grabBotRunPowers`), beside the
* check that the task is this bot's own.
*/
powers: BotRunPowers;
/**
* The bots it may hand to, for the description (`chatroomAskableBots`).
*/
workers: BUN_SQLITE_COBBLE_BOTS[];
/**
* Reads the bots it may hand to when it does, so a bot added mid-run is
* there: the ones it could ask (`chatroomAskableBots`).
*/
grabTargets: () => Promise<BUN_SQLITE_COBBLE_BOTS[]>;
/**
* Called with the task it hands over, so the message the run posts links
* to it (`bot_messages.task_ids`).
*/
onTask?: (params: { task_id: number }) => void;
};
type Args = {
task_id: number;
bot_id: number;
/**
* False to only move it: the task goes to the other bot's list as to do
* and no job is queued, for when the user hasn't asked for the work to
* begin.
*/
start?: boolean;
};
/**
* Lets a bot give a task on its own list to another bot (`handOverTask`):
* the narrow hand-over of `delegate_task`, for the runs that have no right
* to hand out work. It only ever moves a task the run already has, only an
* open one, and only to a bot it could ask for the same user, so it can't
* create a task for someone else or widen a run's reach. The task keeps its
* place (a workspace's stays there), the other bot works that same task, and
* the result is reported back in this session.
*/
export default function handOverTaskTool({ user_id, bot, session_id, powers, workers, grabTargets, onTask }: Params): HarnessTool<Args> {
const bot_id = bot.id || 0;
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
return {
name: "hand_over_task",
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list and they work that same task there, and their result is reported back here. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_crew; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
schema: z.object({
task_id: z.number().int().describe("An open task on your own list (list_tasks)"),
bot_id: z.number().int(),
start: z
.boolean()
.optional()
.describe("false to only move the task (to do, nothing runs) until the user says to start"),
}),
run: async ({ args }) => {
const task = await grabRunTask({
task_id: args.task_id,
bot_id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
});
/**
* A workspace-wide task is nobody's: handing it to one bot would
* take it away from the rest of the crew.
*/
if (Number(task.bot_id || 0) != bot_id) {
throw new Error(
`Task #${task.id} isn't on your own list (it's ${
task.workspace_id && !task.bot_id ? "workspace-wide" : "another bot's"
}), so it isn't yours to hand over.`,
);
}
const fresh = await grabTargets();
if (!fresh.some((target) => target.id == args.bot_id)) {
throw new Error(
`No bot has id ${args.bot_id} among the ones you can hand to. Bot: ${
fresh.map((target) => `${target.id}: ${target.name}`).join("; ") || "none"
}.`,
);
}
const handed = await handOverTask({
user_id,
task_id: Number(task.id),
to_bot_id: args.bot_id,
instructions: undefined,
handed_by: bot.name || "The bot that had it",
requested_by_bot_id: bot_id,
requested_by_session_id: session_id,
start: args.start !== false,
});
onTask?.({ task_id: Number(task.id) });
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in its own chat";
if (!handed.job_id) {
return `Task #${task.id} "${task.title}" is on ${handed.bot_name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.`;
}
return `Task #${task.id} "${task.title}" is with ${handed.bot_name} now (job #${handed.job_id})${where}, marked doing, and it's off your list.${handed.joined} They work that same task; their result is reported back here.`;
},
};
}
@@ -0,0 +1,87 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
/**
* Jobs still running in the room. Closing cancels them, so the tool has to
* refuse over one: a coordinator once answered while the Software Engineer
* ran the work it had been asked for, the run died with "The chatroom
* closed", and the answer said the tasks were picked up.
*/
let open: { id: number; bot_id: number | null; bot_name: string | null; status: string }[] = [];
let closedArgs: Record<string, unknown> | null = null;
let closed = true;
mock.module("@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs", () => ({
default: async () => open,
}));
mock.module("@/src/functions/backend/db/chatrooms/share-room-files", () => ({
default: async ({ answer }: { answer: string }) => answer,
}));
mock.module("@/src/functions/backend/db/chatrooms/close-chatroom", () => ({
default: async (args: Record<string, unknown>) => {
closedArgs = args;
return closed;
},
}));
const answerRequesterTool = (await import("./answer-requester-tool")).default;
afterAll(() => {
mock.restore();
});
const room = { id: 3, status: "open", requester_bot_id: 2 } as BUN_SQLITE_COBBLE_CHATROOMS;
beforeEach(() => {
open = [];
closedArgs = null;
closed = true;
});
function build(onClosed?: () => void) {
return answerRequesterTool({ chatroom: room, job_id: 300, onClosed });
}
describe("answerRequesterTool", () => {
test("answers and closes the room when nothing else runs", async () => {
const acted: string[] = [];
const answer = await build(() => acted.push("closed")).run({ args: { answer: "The plan." }, signal: new AbortController().signal });
expect(String(answer)).toContain("The room is closed");
expect(closedArgs?.status).toBe("answered");
expect(closedArgs?.outcome).toBe("The plan.");
expect(closedArgs?.job_id).toBe(300);
expect(acted).toEqual(["closed"]);
});
test("refuses while a member job still runs, naming it", async () => {
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
await expect(build().run({ args: { answer: "Done." }, signal: new AbortController().signal })).rejects.toThrow(
"Still working here: Software Engineer (run #295, processing). Answering closes the room and cancels that run",
);
expect(closedArgs).toBeNull();
});
test("close_anyway answers over it", async () => {
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
await build().run({ args: { answer: "Not needed after all.", close_anyway: true }, signal: new AbortController().signal });
expect(closedArgs?.status).toBe("answered");
});
test("a room already closed is reported, not acted on", async () => {
closed = false;
const acted: string[] = [];
await expect(build(() => acted.push("closed")).run({ args: { answer: "Late." }, signal: new AbortController().signal })).rejects.toThrow(
"This room is already closed.",
);
expect(acted).toEqual([]);
});
});
@@ -1,7 +1,9 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
import shareRoomFiles from "@/src/functions/backend/db/chatrooms/share-room-files";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
import type { HarnessTool } from "../../types";
type Params = {
@@ -18,22 +20,38 @@ type Params = {
type Args = {
answer: string;
/**
* Closes over a job still running in the room, cancelling it.
*/
close_anyway?: boolean;
};
/**
* The coordinator sends the answer back to the bot that asked, closing the
* room as answered (`closeChatroom`). Files it names that the asker can't
* read are copied to it first and their refs pointed at the copies
* (`shareRoomFiles`).
* (`shareRoomFiles`). While a member's job still runs it refuses, unless
* `close_anyway` says the answer doesn't depend on it: closing cancels that
* job and the work with it.
*/
export default function answerRequesterTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
return {
name: "answer_requester",
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown.`,
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown. Closing cancels whatever still runs in the room, so while a bot is working this refuses: read where it stands first, or pass close_anyway when the answer doesn't depend on its work.`,
schema: z.object({
answer: z.string().trim().min(1).max(12000),
close_anyway: z
.boolean()
.optional()
.describe("Close over a run still working here, cancelling it: only when the answer doesn't depend on it"),
}),
run: async ({ args }) => {
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
if (open.length && !args.close_anyway) {
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Answering" }));
}
const outcome = await shareRoomFiles({ chatroom, answer: args.answer });
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "answered", outcome, job_id });
@@ -1,6 +1,8 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
import type { HarnessTool } from "../../types";
type Params = {
@@ -17,20 +19,35 @@ type Params = {
type Args = {
reason: string;
/**
* Closes over a job still running in the room, cancelling it.
*/
close_anyway?: boolean;
};
/**
* The coordinator turns the request down, telling the bot that asked why,
* and closes the room as refused (`closeChatroom`).
* and closes the room as refused (`closeChatroom`). While a member's job
* still runs it refuses, unless `close_anyway` (closing cancels it).
*/
export default function refuseRequestTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
return {
name: "refuse_request",
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it.`,
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it. Closing cancels whatever still runs in the room, so while a bot is working this refuses: pass close_anyway when the refusal doesn't depend on its work.`,
schema: z.object({
reason: z.string().trim().min(1).max(4000),
close_anyway: z
.boolean()
.optional()
.describe("Close over a run still working here, cancelling it: only when the refusal doesn't depend on it"),
}),
run: async ({ args }) => {
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
if (open.length && !args.close_anyway) {
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Turning it down" }));
}
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "refused", outcome: args.reason, job_id });
if (!closed) {
+1 -1
View File
@@ -29,7 +29,7 @@ export default async function relayChangedChatrooms({ since, users }: Params) {
const mine = rooms.filter((room) => room.user_id && users.has(String(room.user_id)));
for (const summary of await chatroomSummaries({ chatrooms: mine })) {
for (const summary of await chatroomSummaries({ chatrooms: mine, with_usage: true })) {
sendToUser({ user_id: summary.user_id!, data: { event: "server:chatroom-updated", data: summary } });
}
}
@@ -10,19 +10,24 @@ type Params = {
* modal lists.
*/
full?: boolean;
/**
* The room the message was posted in: a chatroom's message is read
* from its own route, an answer in a bot's conversation from the
* bot's.
*/
chatroom_id?: number;
};
/**
* How one of the bot's messages was generated. `full` reads every call
* and failure it took, which the modal's copy of the report needs.
* How one bot message was generated. `full` reads every call and failure
* it took, which the modal's copy of the report needs.
*/
export default async function fetchMessageDetails({ message_id, full }: Params) {
export default async function fetchMessageDetails({ message_id, full, chatroom_id }: Params) {
const query = new URLSearchParams({ message_id: String(message_id) });
if (full) query.set("full", "1");
return await fetchApi<{}, APIResponseObject<MessageDetails>>(
`/api/admin/bots/message-details?${query.toString()}`,
{ method: "GET" },
);
}
const url = chatroom_id ? `/api/admin/chatrooms/message-details` : `/api/admin/bots/message-details`;
return await fetchApi<{}, APIResponseObject<MessageDetails>>(`${url}?${query.toString()}`, { method: "GET" });
}
@@ -8,13 +8,19 @@ type Params = {
* Load only once the modal opens, so the thread's messages stay small.
*/
enabled?: boolean;
/**
* Set when the message was posted in a chatroom, so its details are read
* from the room's route.
*/
chatroom_id?: number;
};
/**
* How one bot message was generated (`api/admin/bots/message-details`),
* loaded when its details modal opens and kept while the thread is open.
* How one bot message was generated (`api/admin/bots/message-details`, or
* the chatroom's own route for a message posted in a room), loaded when its
* details modal opens and kept while the thread is open.
*/
export default function useMessageDetails({ message_id, enabled = true }: Params) {
export default function useMessageDetails({ message_id, enabled = true, chatroom_id }: Params) {
const [details, setDetails] = useState<MessageDetails>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -23,7 +29,7 @@ export default function useMessageDetails({ message_id, enabled = true }: Params
setLoading(true);
setError(undefined);
const res = await fetchMessageDetails({ message_id }).catch(() => null);
const res = await fetchMessageDetails({ message_id, chatroom_id }).catch(() => null);
setLoading(false);
@@ -33,7 +39,7 @@ export default function useMessageDetails({ message_id, enabled = true }: Params
}
setDetails(res.singleRes);
}, [message_id]);
}, [message_id, chatroom_id]);
useEffect(() => {
if (enabled) load().catch(() => {});
@@ -8,6 +8,11 @@ import fetchMessageDetails from "../(functions)/fetch-message-details";
type Props = {
message_id: number;
/**
* Set when the message was posted in a chatroom, so its details are read
* from the room's route.
*/
chatroom_id?: number;
};
/**
@@ -16,7 +21,7 @@ type Props = {
* every call and failure it took included, not only the ones the modal
* lists. The row shows a check for a moment, then goes back.
*/
export default function CopyMessageDetailsButton({ message_id }: Props) {
export default function CopyMessageDetailsButton({ message_id, chatroom_id }: Props) {
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -30,7 +35,7 @@ export default function CopyMessageDetailsButton({ message_id }: Props) {
const copy = async () => {
setLoading(true);
const markdown = fetchMessageDetails({ message_id, full: true }).then((res) => {
const markdown = fetchMessageDetails({ message_id, full: true, chatroom_id }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load this message's details.");
}
@@ -3,7 +3,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import type { MessageDetails } from "@/src/types";
import formatTokens from "@/src/utils/format-tokens";
import relativeTime from "@/src/utils/relative-time";
import costLabel from "../(utils)/cost-label";
import costLabel from "@/src/utils/cost-label";
import messageDetailsFacts from "../(utils)/message-details-facts";
import MessageDetailRow from "./message-detail-row";
import MessageDetailsCallRow from "./message-details-call-row";
@@ -4,7 +4,7 @@ import type { MessageDetailsCall } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatDuration from "@/src/utils/format-duration";
import formatTokens from "@/src/utils/format-tokens";
import costLabel from "../(utils)/cost-label";
import costLabel from "@/src/utils/cost-label";
import harnessLabel from "../(utils)/harness-label";
type Props = {
@@ -17,16 +17,22 @@ type Props = {
* passed along to the copied report.
*/
tool_log?: string | null;
/**
* Set when the message was posted in a chatroom, so its details are read
* from the room's route.
*/
chatroom_id?: number;
};
/**
* The info button under a bot message, and the modal it opens: which
* provider and model generated it, the run behind it, what its tools did,
* and every model call with its tokens and cost. Loaded when it opens.
* The info button under a bot message (in a conversation or a chatroom),
* and the modal it opens: which provider and model generated it, the run
* behind it, what its tools did, and every model call with its tokens and
* cost. Loaded when it opens.
*/
export default function MessageDetailsModal({ message_id, tool_log }: Props) {
export default function MessageDetailsModal({ message_id, tool_log, chatroom_id }: Props) {
const [open, set_open] = useState(false);
const { details, loading, error } = useMessageDetails({ message_id, enabled: open });
const { details, loading, error } = useMessageDetails({ message_id, enabled: open, chatroom_id });
return (
<Modal
@@ -43,7 +49,7 @@ export default function MessageDetailsModal({ message_id, tool_log }: Props) {
<Stack className="w-full gap-1! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
<CopyMessageDetailsButton message_id={message_id} />
<CopyMessageDetailsButton message_id={message_id} chatroom_id={chatroom_id} />
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
How this answer was generated: the provider and model behind it, the settings they were called with, and what it spent.
@@ -4,7 +4,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import type { MessageDetailsModel } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatTokens from "@/src/utils/format-tokens";
import costLabel from "../(utils)/cost-label";
import costLabel from "@/src/utils/cost-label";
import harnessLabel from "../(utils)/harness-label";
import providerLabel from "../(utils)/provider-label";
import MessageDetailsSetting from "./message-details-setting";
@@ -1,7 +1,7 @@
import type { MessageDetails, MessageDetailsCall, MessageDetailsFailure, MessageDetailsModel } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatDuration from "@/src/utils/format-duration";
import costLabel from "./cost-label";
import costLabel from "@/src/utils/cost-label";
import failureSourceLabel from "./failure-source-label";
import harnessLabel from "./harness-label";
import messageDetailsFacts from "./message-details-facts";
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import costLabel from "./cost-label";
import costLabel from "@/src/utils/cost-label";
import providerLabel from "./provider-label";
describe("providerLabel", () => {
@@ -1,11 +1,10 @@
import { useState } from "react";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import useServerEvent from "@/src/hooks/use-server-event";
import type { ChatroomMessageData, ChatroomSummary } from "@/src/types";
import type { BotMessageWithAttachments, ChatroomMessageData, ChatroomSummary } from "@/src/types";
type Params = {
chatroom: ChatroomSummary;
messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[];
messages: BotMessageWithAttachments[];
};
/**
@@ -3,12 +3,13 @@ import remarkGfm from "remark-gfm";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import ChatroomStone from "@/src/components/general/chatroom-stone";
import type { ChatroomBot } from "@/src/types";
import type { BotMessageWithAttachments, ChatroomBot } from "@/src/types";
import linkComputerRefs from "@/src/utils/link-computer-refs";
import relativeTime from "@/src/utils/relative-time";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import MessageDetailsModal from "@/src/pages/admin/bots/[bot_id]/(partials)/message-details-modal";
import MessageUsageChip from "@/src/pages/admin/bots/[bot_id]/(partials)/message-usage-chip";
/**
* Kept module-level: a new array on every render makes `react-markdown`
@@ -17,19 +18,25 @@ import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data
const RemarkPlugins = [remarkGfm];
type Props = {
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
message: BotMessageWithAttachments;
/**
* The bot that posted it, null once it was deleted.
*/
bot?: ChatroomBot | null;
/**
* The room it was posted in, for its details (they're read from the
* room's own route).
*/
chatroom_id: number;
};
/**
* One message in a chatroom, under the stone and name of the bot that
* posted it, rendered from markdown like a conversation's (raw HTML
* never). Rooms are records: nothing here replies or reacts.
* never), with what it spent and its details underneath. Rooms are
* records: nothing here replies or reacts.
*/
export default function ChatroomMessageRow({ message, bot }: Props) {
export default function ChatroomMessageRow({ message, bot, chatroom_id }: Props) {
return (
<Row className="w-full gap-3! flex-nowrap items-start">
<Span className="inline-flex shrink-0 -mt-0.5">
@@ -47,6 +54,14 @@ export default function ChatroomMessageRow({ message, bot }: Props) {
{linkComputerRefs({ text: message.text || "" })}
</Markdown>
</Stack>
<Row className="w-full gap-1! flex-nowrap items-center">
<MessageUsageChip usage={message.usage} />
<MessageDetailsModal
message_id={Number(message.id)}
tool_log={message.tool_log}
chatroom_id={chatroom_id}
/>
</Row>
</Stack>
</Row>
);
@@ -0,0 +1,37 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import type { ChatroomUsageBot } from "@/src/types";
import costLabel from "@/src/utils/cost-label";
import formatTokens from "@/src/utils/format-tokens";
type Props = {
bot: ChatroomUsageBot;
};
/**
* One bot's part of what a room spent, under the room's totals: its name,
* then the tokens, calls and price of every model call it made there. The
* hover title breaks it down.
*/
export default function ChatroomUsageBotRow({ bot }: Props) {
const title = [
`${formatTokens({ tokens: bot.prompt_tokens })} in, ${formatTokens({ tokens: bot.completion_tokens })} out`,
`${bot.calls} model ${bot.calls == 1 ? "call" : "calls"}`,
typeof bot.cost == "number" && bot.cost > 0 ? costLabel({ cost: bot.cost }) : "",
]
.filter(Boolean)
.join(" · ");
return (
<Row className="w-full gap-3! flex-nowrap items-baseline justify-between">
<Span className="min-w-0 truncate text-[12px] leading-4 font-bold text-ink">
{bot.name || "A removed bot"}
</Span>
<Span title={title} className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums">
{formatTokens({ tokens: bot.total_tokens })} tokens · {formatTokens({ tokens: bot.calls })}{" "}
{bot.calls == 1 ? "call" : "calls"}
{typeof bot.cost == "number" && bot.cost > 0 ? ` · ${costLabel({ cost: bot.cost })}` : ""}
</Span>
</Row>
);
}
@@ -0,0 +1,85 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type { ChatroomUsage } from "@/src/types";
import ChatroomUsageSummary from "./chatroom-usage-summary";
const usage: ChatroomUsage = {
totals: {
prompt_tokens: 12_400,
cached_tokens: 6200,
completion_tokens: 1600,
total_tokens: 14_000,
cost: 0.042,
calls: 7,
},
failed_calls: 2,
by_bot: [
{
bot_id: 10,
name: "Ember",
prompt_tokens: 10_400,
cached_tokens: 6000,
completion_tokens: 1100,
total_tokens: 11_500,
cost: 0.031,
calls: 4,
},
{
bot_id: 20,
name: null,
prompt_tokens: 2000,
completion_tokens: 500,
total_tokens: 2500,
cost: 0.011,
calls: 3,
},
],
};
describe("ChatroomUsageSummary", () => {
test("totals what the room spent, and what failed", () => {
const html = renderToString(<ChatroomUsageSummary usage={usage} />);
expect(html).toContain("What this room spent");
expect(html).toContain("14K");
expect(html).toContain("12K in (50% cached), 1.6K out");
expect(html).toContain("7");
expect(html).toContain("2 failed");
expect(html).toContain("$0.0420");
});
test("splits it by bot, naming a bot that's gone", () => {
const html = renderToString(<ChatroomUsageSummary usage={usage} />);
expect(html).toContain("By bot");
expect(html).toContain("Ember");
expect(html).toContain("12K<!-- --> tokens");
expect(html).toContain("4<!-- --> <!-- -->calls");
expect(html).toContain("A removed bot");
expect(html).toContain("2.5K<!-- --> tokens");
expect(html).toContain("3<!-- --> <!-- -->calls");
});
test("says nothing was spent in a room with no calls yet", () => {
const html = renderToString(
<ChatroomUsageSummary
usage={{
totals: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, calls: 0 },
failed_calls: 0,
by_bot: [],
}}
/>,
);
expect(html).toContain("Nothing spent yet");
expect(html).toContain("Not reported");
expect(html).not.toContain("By bot");
expect(html).not.toContain("failed");
});
test("reads a room with no usage at all as nothing yet", () => {
const html = renderToString(<ChatroomUsageSummary />);
expect(html).toContain("Nothing spent yet");
});
});
@@ -0,0 +1,75 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import UsageStat from "@/src/components/general/usage-stat";
import type { ChatroomUsage } from "@/src/types";
import costLabel from "@/src/utils/cost-label";
import formatTokens from "@/src/utils/format-tokens";
import ChatroomUsageBotRow from "./chatroom-usage-bot-row";
type Props = {
usage?: ChatroomUsage | null;
};
/**
* What everything in a room cost, under the bots in it: the tokens and
* model calls every bot's work there took (a turn still running included),
* the price when the providers reported it, the calls that failed, and the
* same split by bot.
*/
export default function ChatroomUsageSummary({ usage }: Props) {
const totals = usage?.totals;
const failed_calls = usage?.failed_calls || 0;
const by_bot = usage?.by_bot || [];
const calls = totals?.calls || 0;
return (
<Stack className="w-full gap-4! items-stretch py-6 border-0 border-t border-solid border-hairline">
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[11px] uppercase tracking-wide text-ink-secondary">What this room spent</Span>
<Span className="text-[12px] leading-4 text-ink-secondary">
Every model call its bots made here, a turn still running included.
</Span>
</Stack>
<Row className="w-full gap-6! items-start flex-wrap">
<UsageStat
label="Tokens"
value={formatTokens({ tokens: totals?.total_tokens })}
hint={
calls
? `${formatTokens({ tokens: totals?.prompt_tokens })} in${cachedShare({ cached: totals?.cached_tokens, prompt: totals?.prompt_tokens })}, ${formatTokens({ tokens: totals?.completion_tokens })} out`
: "Nothing spent yet"
}
/>
<UsageStat
label="Model calls"
value={formatTokens({ tokens: calls })}
hint={failed_calls ? `${failed_calls} failed` : calls ? "None failed" : undefined}
/>
<UsageStat
label="Cost"
value={costLabel({ cost: totals?.cost })}
hint={totals?.cost ? "As the providers reported it" : "Free models, or no price"}
/>
</Row>
{by_bot.length ? (
<Stack className="w-full gap-1.5! items-stretch pt-1">
<Span className="text-[11px] uppercase tracking-wide text-ink-secondary">By bot</Span>
{by_bot.map((bot) => (
<ChatroomUsageBotRow key={bot.bot_id} bot={bot} />
))}
</Stack>
) : null}
</Stack>
);
}
/**
* How much of what was sent the providers served from their cache, when
* they said: " (40% cached)".
*/
function cachedShare({ cached, prompt }: { cached?: number; prompt?: number }) {
if (!cached || !prompt) return "";
return ` (${Math.round((cached / prompt) * 100)}% cached)`;
}
@@ -6,8 +6,7 @@ import SettingsShell from "@/src/pages/admin/settings/(partials)/settings-shell"
import ChatroomRetryButton from "@/src/components/general/chatroom-retry-button";
import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context";
import { CrewWorkspacesContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-workspaces-context";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { ChatroomSummary } from "@/src/types";
import type { BotMessageWithAttachments, ChatroomSummary } from "@/src/types";
import chatroomStatusLine from "@/src/utils/chatroom-status-line";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import useLiveChatroom from "../(hooks)/use-live-chatroom";
@@ -15,17 +14,19 @@ import ChatroomBotsRow from "../(partials)/chatroom-bots-row";
import ChatroomMessageRow from "../(partials)/chatroom-message-row";
import ChatroomOutcome from "../(partials)/chatroom-outcome";
import ChatroomStopButton from "../(partials)/chatroom-stop-button";
import ChatroomUsageSummary from "../(partials)/chatroom-usage-summary";
import ChatroomStatus from "./chatroom-status";
type Props = {
chatroom: ChatroomSummary;
messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[];
messages: BotMessageWithAttachments[];
};
/**
* The open room, live: who is in it and their part, the thread and the
* outcome, where each bot stands while it's open, with Stop for anyone who
* can do more than read, and Try again once it failed or was stopped.
* The open room, live: who is in it and their part, what everything there
* spent, the thread and the outcome, where each bot stands while it's open,
* with Stop for anyone who can do more than read, and Try again once it
* failed or was stopped.
*/
export default function ChatroomBody({ chatroom, messages }: Props) {
const { pageProps } = useContext(AppContext);
@@ -64,12 +65,14 @@ export default function ChatroomBody({ chatroom, messages }: Props) {
/>
))}
</Row>
<ChatroomUsageSummary usage={room.usage} />
<Stack className="w-full gap-6! items-stretch py-2">
{thread.map((message) => (
<ChatroomMessageRow
key={message.id}
message={message}
bot={bots.get(Number(message.bot_id)) || null}
chatroom_id={Number(room.id)}
/>
))}
<ChatroomOutcome chatroom={room} />
@@ -1,8 +1,8 @@
import Row from "@moduletrace/twui/layout/Row";
import type { UsageOverview } from "@/src/types";
import UsageStat from "@/src/components/general/usage-stat";
import formatTokens from "@/src/utils/format-tokens";
import { UsageHarnessTitles } from "../(data)/usage-harness-titles";
import UsageStat from "./usage-stat";
type Props = {
usage: UsageOverview;
@@ -0,0 +1,48 @@
import { AppData } from "@/src/data/app-data";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabChatroomMessage from "@/src/functions/backend/db/chatrooms/grab-chatroom-message";
import grabMessageDetails from "@/src/functions/backend/db/usage/grab-message-details";
import { MessageDetailsRequestSchema } from "@/src/schemas/bot-schema";
import type { MessageDetails } from "@/src/types";
import parseWithSchema from "@/src/utils/parse-with-schema";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* `GET ?message_id=`: how a message posted in one of the user's chatrooms
* was generated (the job, every model call with its provider and model,
* and the tokens and cost). Loaded when its details modal opens, so the
* room's messages stay small. `&full=1` lists every call and failure, for
* the copy of the report.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> = async ({ req, query }) => {
try {
if (req.method != "GET") {
return { success: false, msg: `Method not allowed` };
}
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const { message_id, full } = parseWithSchema({ schema: MessageDetailsRequestSchema, data: query });
const message = await grabChatroomMessage({ message_id, user_id: Number(user.id) });
if (!message) {
return { success: false, msg: `Not found` };
}
return {
success: true,
singleRes: await grabMessageDetails({
message_id: message.id,
created_at: message.created_at || null,
...(full ? { max_calls: AppData.MessageDetailsCopyMaxCalls } : {}),
}),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+36 -3
View File
@@ -438,14 +438,47 @@ export type ChatroomSummary = BUN_SQLITE_COBBLE_CHATROOMS & {
* The workspace the request came from, by name.
*/
workspace_name?: string | null;
/**
* What the room's bots spent while working in it, summed. Only asked
* for the room itself (and its live pushes), never for a list.
*/
usage?: ChatroomUsage;
};
/**
* `server:chatroom-message` data: a message one of the room's bots posted.
* What one bot's work in a chatroom spent: every model call it made there,
* a call of a turn still running included.
*/
export type ChatroomUsageBot = TokenUsageSummary & {
bot_id: number;
/**
* Its name while it exists, like the messages it posted.
*/
name: string | null;
};
/**
* What everything in a chatroom cost: every model call its bots made there
* (a turn still running included), the calls that failed, and the same
* split by bot. This is what the totals at the top of a room show.
*/
export type ChatroomUsage = {
totals: TokenUsageSummary;
/**
* How many model calls failed there; they spent nothing, so they aren't
* in `totals`.
*/
failed_calls: number;
by_bot: ChatroomUsageBot[];
};
/**
* `server:chatroom-message` data: a message one of the room's bots posted,
* with what it cost.
*/
export type ChatroomMessageData = {
chatroom_id: number;
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
message: BotMessageWithAttachments;
};
/**
@@ -2233,7 +2266,7 @@ export type PagePropsType = {
* message in it.
*/
chatroom?: ChatroomSummary | null;
chatroom_messages?: BUN_SQLITE_COBBLE_BOT_MESSAGES[] | null;
chatroom_messages?: BotMessageWithAttachments[] | null;
/**
* The user's chatrooms (`/admin/chatrooms`).
*/
@@ -0,0 +1,46 @@
import { describe, expect, test } from "bun:test";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
/**
* A room can't be closed over a bot still working in it: closing cancels
* its job (`cancelChatroomJobs`). A coordinator once answered a room while
* the Software Engineer ran the very work it was asked for, the run died
* with "The chatroom closed", and the answer said the tasks were picked up.
* The warning is what the tool throws instead, so it has to name who is
* busy and how to go on.
*/
describe("chatroomOpenJobsWarning", () => {
test("says nothing when nothing runs", () => {
expect(chatroomOpenJobsWarning({ jobs: [], closing: "Answering" })).toBe("");
});
test("names the bot, its run and what it was about to do", () => {
const warning = chatroomOpenJobsWarning({
jobs: [{ id: 295, bot_name: "Software Engineer", status: "processing" }],
closing: "Answering",
});
expect(warning).toContain("Still working here: Software Engineer (run #295, processing).");
expect(warning).toContain("Answering closes the room and cancels that run, so the work is lost.");
expect(warning).toContain("close_anyway: true");
});
test("lists every job still open, in the order given", () => {
const warning = chatroomOpenJobsWarning({
jobs: [
{ id: 12, bot_name: "Writer", status: "pending" },
{ id: 13, bot_name: "Reviewer", status: "processing" },
],
closing: "Turning it down",
});
expect(warning).toContain("Writer (run #12, pending), Reviewer (run #13, processing)");
expect(warning).toContain("Turning it down closes the room");
});
test("copes with a job whose bot is gone", () => {
const warning = chatroomOpenJobsWarning({ jobs: [{ id: 7, bot_name: null }], closing: "Answering" });
expect(warning).toContain("Still working here: A bot (run #7).");
});
});
+33
View File
@@ -0,0 +1,33 @@
type Job = {
id: number | string;
bot_name?: string | null;
status?: string | null;
};
type Params = {
/**
* The room's open jobs (`grabChatroomOpenJobs`).
*/
jobs: Job[];
/**
* What the coordinator was about to do: "Answering", "Turning it down".
*/
closing: string;
};
/**
* Why a room can't be closed yet: closing cancels whatever still runs in it
* (`cancelChatroomJobs`), so a coordinator that answers over a member's
* live work throws that work away. Written as the tool's error, so the
* coordinator reads who is busy and asks again instead. Empty with no open
* job: then there is nothing to warn about.
*/
export default function chatroomOpenJobsWarning({ jobs, closing }: Params): string {
if (!jobs.length) return "";
const working = jobs
.map((job) => `${job.bot_name || "A bot"} (run #${job.id}${job.status ? `, ${job.status}` : ""})`)
.join(", ");
return `Still working here: ${working}. ${closing} closes the room and cancels that run, so the work is lost. Ask them where they stand first, or pass close_anyway: true when the outcome doesn't depend on what they find.`;
}
@@ -6,4 +6,4 @@ export default function costLabel({ cost }: { cost?: number | null }) {
if (typeof cost != "number" || !(cost > 0)) return "Not reported";
return `$${cost < 0.01 ? cost.toFixed(6) : cost.toFixed(4)}`;
}
}
+11
View File
@@ -49,6 +49,12 @@ describe("botCan", () => {
test("a worker can't delegate", () => {
expect(botCan({ kind: "worker", bot_types: [], permission: "delegate_task", workspace_id: 3 })).toBe(false);
});
test("a worker can hand on a task of its own, and a workspace admin can too", () => {
expect(botCan({ kind: "worker", bot_types: [], permission: "hand_over_task", workspace_id: 3 })).toBe(true);
expect(botCan({ kind: "worker", bot_types: [], permission: "hand_over_task" })).toBe(true);
expect(botCan({ bot_types: admin_of_3, permission: "hand_over_task", workspace_id: 3 })).toBe(true);
});
});
describe("botCanTarget", () => {
@@ -77,6 +83,11 @@ describe("botCanTarget", () => {
});
test("a worker directs no one", () => {
/**
* `hand_over_task` is separate: it moves a task the worker already
* has, to a bot it could ask (`chatroomAskableBots`). Nothing here
* lets it hand work out.
*/
expect(botCanTarget({ actor_bot_types: [], target_bot_types: [], workspace_id: 3 })).toBe(false);
});
});