Compare commits

...
6 Commits
Author SHA1 Message Date
tben 3209828723 Bump version to 0.19.1
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:56:37 +01:00
tben 0d38268fef Let a hand-over only move a task, and ask before work starts
Handing a task to another bot started it by default: it went to doing and
queued a run, so handing three tasks over "to wait for the go-ahead" ran
three jobs that each only reported they were waiting.

handOverTask now only moves the task, as to do, with no job; `start: true`
(the user asked for the work to begin now) is what sets it doing and queues
the run. hand_over_task and delegate_task pass that only when the user asked
and are told to ask first with one ask_user card for every task they named,
since a worker can't start a task once it has left its list. The UI's hand
over form gains a "Start it now" toggle, unchecked by default, and the
coordinator and workspace-admin prompts say the same.
2026-11-13 12:52:01 +01:00
tben 41be1b6fb1 Make a release mean the whole chain, watched to the end
CI / check (push) Canceled after 0s
2026-11-13 12:15:40 +01:00
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
56 changed files with 1612 additions and 133 deletions
+7 -6
View File
@@ -36,7 +36,7 @@ For the current UI read `src/layouts/bots/` (rail, workspace rail, user popover)
| DB schema sync / admin UI / backup | `bun run db:schema` / `db:admin` / `db:backup` |
| Seed super admin / sample crew | `bun run seed` (needs `SEED_SUPER_ADMIN_PASSWORD`) / `bun run seed:bots [email]` (idempotent) |
| Query DB (read-only, JSON envelope) | `bun llm-code-assistant/query-db.ts "<sql>"` |
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards |
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards (`gh run watch` in between until the image build ends) |
No linter or formatter. `bun run typecheck` and `bun run test` are the verification steps. Use `query-db.ts` to see what is actually in the database instead of reading ORM code.
@@ -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) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `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).
@@ -241,6 +241,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **App networks:** extra docker networks for the app's own container (never computers) are the app setting `app_extra_networks` (Settings > General, super admin, picked from the networks docker lists, `listJoinableNetworks`), joined by the app itself over the docker socket (`syncAppNetworks`) at boot, on save and every 5 minutes, so they outlast `install.sh` recreating the container; the installer's `--extra-network` still works beside it.
- Plain HTTP only; TLS is the proxy's job. Container: `--network cobble`, `.env` read-only at `/app/.env`, docker socket, `MAIN_SERVER=1`, `--init`, `--cpus 1 --memory 2048m` by default.
- Publishing: `scripts/publish-github.sh` / `publish-gitea.sh` sharing `scripts/lib/publish-*.sh` (tested by `scripts/publish-tools.test.ts`). A GitHub release triggers `.github/workflows/release.yml` (amd64 + arm64 to `ghcr.io/moduletrace/cobble`); `mirror-gitea.sh` copies to `git.tben.me/moduletrace/cobble` (CI can't reach the VPN). **Bump `package.json`'s `version` with a release.** CI (`ci.yml`) runs typecheck and tests. Dockerfile pins Bun 1.4.3.
- **A release is done when every artifact exists, not when the tag is pushed.** Publishing (`publish`/`release`/`ship`, any of them) means the whole chain, run by you and watched to the end: `publish:github`, `publish:gitea`, then `gh run watch` until the image build succeeds, then `mirror:gitea` (it has nothing to copy until that build finishes). Report each artifact with its link, and say plainly (with the reason) if one fails or is still building: never hand back a tag and leave the rest as a note for the user.
## Admin routes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.10",
"version": "0.19.1",
"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)]
: []),
+26 -2
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import Checkbox from "@moduletrace/twui/form/Checkbox";
import Form from "@moduletrace/twui/form/Form";
import Select from "@moduletrace/twui/form/Select";
import Textarea from "@moduletrace/twui/form/Textarea";
@@ -24,6 +25,12 @@ type Props<T> = {
* Offer a note added to the brief (a task's hand-over).
*/
with_note?: boolean;
/**
* Offer to start the work now (a task's hand-over). Off by default:
* handing a task over only moves it, it never starts the work unless
* the user asks for that here.
*/
with_start?: boolean;
onHandedOver: (params: { saved: T; msg: string }) => void;
onCancel: () => void;
};
@@ -39,12 +46,14 @@ export default function HandOverForm<T extends { [k: string]: any }>({
submit_path,
body,
with_note,
with_start,
onHandedOver,
onCancel,
}: Props<T>) {
const [targets, setTargets] = useState<HandOverTarget[]>();
const [bot_id, setBotId] = useState<number>();
const [note, setNote] = useState("");
const [start, setStart] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -73,14 +82,19 @@ export default function HandOverForm<T extends { [k: string]: any }>({
return;
}
if (!window.confirm(`Hand ${what} over to ${target.name}?`)) return;
if (!window.confirm(`Hand ${what} over to ${target.name}${with_start && start ? " and start it now" : ""}?`)) return;
setLoading(true);
setError(undefined);
const res = await postAdminApi<T>({
path: submit_path,
body: { ...body, bot_id: target.id, instructions: with_note && note.trim() ? note : undefined },
body: {
...body,
bot_id: target.id,
instructions: with_note && note.trim() ? note : undefined,
...(with_start ? { start } : {}),
},
});
setLoading(false);
@@ -121,6 +135,16 @@ export default function HandOverForm<T extends { [k: string]: any }>({
disabled={loading}
/>
) : null}
{with_start && targets?.length ? (
<Checkbox
title="Start it now"
label="Start it now"
info="Left off, the task only moves: it lands on their list as to do, and nothing runs until they're told to start."
checked={start}
clickDispatchHandler={setStart}
wrap
/>
) : null}
<AddFormActions submit_label="Hand over" loading={loading} error={error} onCancel={onCancel} />
</Stack>
</Form>
@@ -131,6 +131,7 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
submit_path="tasks/hand-over-task"
body={{ task_id: Number(task.id) }}
with_note
with_start
onCancel={() => setHandingOver(false)}
onHandedOver={({ saved, msg }) => {
setHandingOver(false);
+1 -1
View File
@@ -34,7 +34,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
- Delegating into a workspace the worker isn't in adds it to that workspace as a side effect. Say that in your reply when it happens; don't add members silently for a one-off.
- Give a full brief: objective, inputs, deliverable, acceptance criteria, constraints.
- Check \`list_tasks\` first. Never give two bots the same job, and don't restart work an open task already covers.
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there), goes to doing, and the worker moves that same task along. Never copy it into a new one.
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there) and the worker moves that same task along. Never copy it into a new one. A hand-over lands on their list as to do and starts nothing: pass \`start: true\` only when the user asked for the work to begin now, and when they asked for the move but not whether to start it, ask first (one \`ask_user\` card with every task they named) and hand over once they've answered.
- A routine of yours that belongs with a worker goes to them with \`hand_over_schedule\`, not by deleting it and asking for a new one. A routine in a workspace keeps running there.
- Track what comes back, judge it against the request, and integrate it. Don't pass a worker's unchecked claim on as fact.
- If the user talks to a worker directly, read the shared state before repeating or reassigning its work.
+2
View File
@@ -113,6 +113,7 @@ describe("RequestScopeNote", () => {
expect(note).toContain("a standing preference is not a standing instruction");
expect(note).toContain("the same ask_user card");
expect(note).toContain("delegating a task");
expect(note).toContain("ask before it leaves: one ask_user card with every task they named");
expect(note).toContain("don't offer it again in this conversation");
expect(note).not.toContain("the brief is what you may do");
expect(note).not.toContain("\u2014");
@@ -123,6 +124,7 @@ describe("RequestScopeNote", () => {
expect(note).toContain("the brief is what you may do");
expect(note).toContain("Say in your report what you would propose");
expect(note).toContain("move it as to do and say in your report that it waits for the user to start it");
expect(note).not.toContain("ask_user");
expect(note).not.toContain("\u2014");
});
+26 -5
View File
@@ -229,6 +229,11 @@ The user's request sets the scope. Do what they asked, in the scope they gave, a
: `the brief is what you may do. Say in your report what you would propose, and why.`
}
- When you can't tell whether something was asked for, it wasn't: ask. Once the user has chosen, do exactly that, nothing bundled with it.
- Handing a task over moves it; starting the work is a separate thing the user asks for. When they asked for the move but not for it to start, ${
can_ask
? `ask before it leaves: one ask_user card with every task they named.`
: `move it as to do and say in your report that it waits for the user to start it.`
}
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
/**
@@ -258,7 +263,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
* `bot_id` is the coordinator itself, so the ref example it copies is its
* own rather than a worker's.
*/
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
/**
* Added to the coordinator's chat prompt instead while it has no workers,
@@ -279,7 +284,7 @@ export const workspaceAdminNote = ({
members: { id?: number | "" }[];
}) => `# Leading ${workspace_name}
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
/**
* Added to a workspace member's prompt while the workspace has an admin,
@@ -418,6 +423,22 @@ 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, 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.
- A hand-over moves the task as to do; it never starts the work. Pass start: true only when the user asked for the work to begin now.
- When they asked for the move but not whether to start it, ask first: put one ask_user card with every task they named ("hand over and start", "hand over to wait", "leave it") and hand over only once they've answered. Once a task has left your list you can't start it any more.
- 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 the way the tool returned it: the run id when it started, or that it's on their list as to do. 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 +557,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 } });
@@ -47,10 +47,12 @@ type Params = {
requested_by_bot_id?: number | string | null;
requested_by_session_id?: number | string | null;
/**
* False to only move it: the task goes to the new bot's list as to do
* and no job is queued, for when the user hasn't asked for the work to
* begin. Handing three tasks over "to wait for the go-ahead" once ran
* three jobs that each only reported they were waiting.
* True only when the user asked for the work to begin now: the task
* goes to doing and a job is queued. Left out (the default) it only
* moves: the task goes to the new bot's list as to do and no job is
* queued, since handing a task over is not asking for it to be worked.
* Handing three tasks over "to wait for the go-ahead" once ran three
* jobs that each only reported they were waiting.
*/
start?: boolean;
};
@@ -70,13 +72,15 @@ export type HandedOverTask = {
};
/**
* Hands an open task to another bot and starts the work: a task in a
* workspace stays there and becomes the new bot's there (the work runs in
* that workspace), one on a bot's own list moves to the new bot's. The task goes to doing, its log
* says who handed it over, and a job is queued in the new bot's
* conversation with the task's brief and `params.tracker_task_id`, so the
* bot moves this same task along and the job's end is noted on it. With
* `start` false it only moves: to do, no job, the notice says so.
* Hands an open task to another bot: a task in a workspace stays there and
* becomes the new bot's there (the work runs in that workspace), one on a
* bot's own list moves to the new bot's. Handing it over is not asking for
* it to be worked, so by default it only moves: the task goes to the new
* bot's list as to do, no job is queued and the notice says so. With
* `start` true (the user asked for the work to begin now) the task goes to
* doing, its log says who handed it over, and a job is queued in the new
* bot's conversation with the task's brief and `params.tracker_task_id`, so
* the bot moves this same task along and the job's end is noted on it.
*/
export default async function handOverTask({
user_id,
@@ -87,7 +91,7 @@ export default async function handOverTask({
handed_by,
requested_by_bot_id,
requested_by_session_id,
start = true,
start = false,
}: Params): Promise<HandedOverTask> {
const task = await grabTaskRow({ task_id });
@@ -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;
}
@@ -0,0 +1,87 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
/**
* The task being handed over, and what `handOverTask` answered with it:
* what a hand-over passes on is the whole point of these tests, so the
* helper is mocked and its arguments recorded.
*/
let task = {
id: 27,
title: "Rewrite the pricing page",
bot_id: 4,
workspace_id: 3,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
let handedArgs: Record<string, unknown> | null = null;
let handed: Record<string, unknown> = {};
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 delegateTaskTool = (await import("./delegate-task-tool")).default;
afterAll(() => {
mock.restore();
});
const worker = { id: 5, name: "Researcher", role: "research", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const signal = new AbortController().signal;
function tool() {
return delegateTaskTool({
user_id: 1,
requester_id: 1,
session_id: 10,
requester_name: "Coordinator",
workers: [worker],
workspaces: [],
grabTargets: async () => [worker],
});
}
beforeEach(() => {
task = {
id: 27,
title: "Rewrite the pricing page",
bot_id: 4,
workspace_id: 3,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
handedArgs = null;
handed = { task, job_id: null, bot_name: "Researcher", workspace_id: 3, joined: "" };
});
describe("delegateTaskTool, handing over a task on a list", () => {
test("moves it as to do by default: no run is queued", async () => {
const answer = await tool().run({ args: { bot_id: 5, task_id: 27 }, signal });
expect(handedArgs?.start).toBe(false);
expect(handedArgs?.task_id).toBe(27);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("starts it only with start: true, when the user asked for that", async () => {
handed = { task, job_id: 318, bot_name: "Researcher", workspace_id: 3, joined: "" };
const answer = await tool().run({ args: { bot_id: 5, task_id: 27, start: true }, signal });
expect(handedArgs?.start).toBe(true);
expect(String(answer)).toContain("is with Researcher now (job #318)");
expect(String(answer)).toContain("marked doing");
});
test("says a hand-over starts nothing, and to ask before it moves", () => {
expect(tool().description).toContain("Handing a task over never starts it");
expect(tool().description).toContain("ask first with ask_user");
});
});
@@ -96,11 +96,11 @@ describe("delegateTaskTool", () => {
expect(tool.description).toContain("task_id");
});
test("can hand a task over without starting it", () => {
test("hands a task over as to do unless told to start it", () => {
const tool = coordinatorTool();
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: false }).success).toBe(true);
expect(tool.description).toContain("start: false");
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: true }).success).toBe(true);
expect(tool.description).toContain("start: true");
});
test("without a task_id, still needs a title and instructions", async () => {
+5 -4
View File
@@ -69,7 +69,8 @@ type Args = {
*/
task_id?: number;
/**
* With `task_id`: false to only move the task, nothing started.
* The user asked for that task's work to begin now (with `task_id`):
* left out it only moves, to do, and no run is spent.
*/
start?: boolean;
title?: string;
@@ -114,7 +115,7 @@ export default function delegateTaskTool({
return {
name: "delegate_task",
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there), goes to doing, and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. When the user hasn't asked for that task's work to begin yet (they want it moved, or to decide first), add start: false: it only moves to their list as to do, and no run is spent on reporting that they're waiting. Crew: ${crew}.${
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there) and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. Handing a task over never starts it: it lands there as to do, and only start: true (when the user asked for the work to begin now) marks it doing and queues the run. When the user asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it) and hand over only once they've answered. A new brief with no task_id always runs at once. Crew: ${crew}.${
workspace_id
? ` You are working in a workspace, so the task runs there: in this workspace's context.`
: ` Leave workspace_id out to run it in the crew member's own chat: only its own memory, files and directly assigned computers apply there, and the user finds the result by talking to it on its own. Add workspace_id to run it in one of the user's workspaces instead: the workspace's shared context, the member's instructions and memory there, its files and its computers (the workspace's own and the member's) all apply, and the result lands in its conversation in that workspace, beside the project it belongs to. Pick a workspace when the work belongs to that project; the member is added to it when it isn't in it yet. Workspaces: ${places || "none"}.`
@@ -125,7 +126,7 @@ export default function delegateTaskTool({
start: z
.boolean()
.optional()
.describe("With task_id: false to only move the task (to do, nothing runs) until the user says to start"),
.describe("With task_id: true to start the work at once, only when the user asked for it; left out it only moves (to do, nothing runs)"),
title: z.string().min(1).max(80).optional(),
instructions: z.string().min(1).max(8000).optional(),
workspace_id: z
@@ -198,7 +199,7 @@ export default function delegateTaskTool({
handed_by: requester_name,
requested_by_bot_id: requester_id,
requested_by_session_id: session_id,
start: args.start !== false,
start: args.start === true,
});
onTask?.({ task_id: Number(task.id) });
@@ -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,179 @@
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({ task_id: 43, bot_id: 6, start: true }).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("tells the bot to ask before the task leaves its list, and that a hand-over starts nothing", () => {
const tool = build();
expect(tool.description).toContain("Handing it over never starts it");
expect(tool.description).toContain("ask first with ask_user");
});
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, start: true }, 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("moves it as to do unless the user asked to start it", 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 }, signal: new AbortController().signal });
expect(handedArgs?.start).toBe(false);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("an explicit start: false asks for the same move", 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,130 @@
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;
/**
* True only when the user asked for the work to begin now. Left out the
* task only moves: it goes to the other bot's list as to do and no job
* is queued.
*/
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) and moves as to do: it never starts the
* work unless the user asked for that (`start`), and when they only asked
* for the move the bot asks first. 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 as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. 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("true to start the work at once, only when the user asked for it; left out it only moves (to do, nothing runs)"),
}),
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 === true,
});
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.${handed.joined ? ` ${handed.joined}` : ""}`;
}
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 }) };
}
};
+13 -7
View File
@@ -13,10 +13,11 @@ import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Hands an open task to another bot and starts the work (`handOverTask`):
* the bot works that same task, and its result lands in its conversation.
* Crew managers only, like every other change to a task by hand. Returns
* the task as it is now.
* Hands an open task to another bot (`handOverTask`): the bot has that same
* task on its list, and its result lands in its conversation. It only moves
* the task by default, as to do; it starts the work only when the user
* ticked that in the form (`start`). Crew managers only, like every other
* change to a task by hand. Returns the task as it is now.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
try {
@@ -38,7 +39,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
throw new AppError(`Only an admin can hand a task over.`);
}
const { task_id, bot_id, instructions } = parseWithSchema({ schema: HandOverTaskRequestSchema, data: body });
const { task_id, bot_id, instructions, start } = parseWithSchema({ schema: HandOverTaskRequestSchema, data: body });
await assertUserReachesTask({ user_id: user.id, task_id });
@@ -48,14 +49,19 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
to_bot_id: bot_id,
instructions,
handed_by: user.first_name || user.username || "The user",
start: start === true,
});
wakeBotsQueue();
if (handed.job_id) {
wakeBotsQueue();
}
return {
success: true,
singleRes: await grabTask({ user_id: user.id, task_id }),
msg: `${handed.bot_name} has it now and is starting on it.`,
msg: handed.job_id
? `${handed.bot_name} has it now and is starting on it.`
: `${handed.bot_name} has it now, as to do on their list.`,
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
+5
View File
@@ -81,6 +81,11 @@ export const HandOverTaskRequestSchema = z.object({
task_id: z.number().int().positive(),
bot_id: z.number().int().positive("Pick a bot"),
instructions: z.string().max(AppData.TaskDescriptionMaxLength).optional(),
/**
* True to start the work now (the user ticked "Start it now"): left out
* the task only moves, as to do.
*/
start: z.boolean().optional(),
});
export const TaskIdRequestSchema = z.object({
+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);
});
});