Compare commits

...
22 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 c924ff9776 Release v0.16.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 09:24:14 +01:00
tbenandClaude Opus 5.5 5d79c379dd Give task chips their colours in dark mode too
The chip is a twui ghost button, whose own dark fill and text won over
the chip's light-only classes, so in dark mode it lost its background
and took the wrong text colour. It now sets both for each theme, like
the link chips beside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 09:23:42 +01:00
tbenandClaude Opus 5.5 ebc9ade7e0 Link bot messages to the tracker tasks they're about
Which tasks a message concerns is now the app's record, not the bot's
word: a run's task tools report every task they read in full, add, move
along or hand over, plus a handed-over job's task, into
bot_messages.task_ids (also on its failure notice and the report relayed
to the requester). The thread shows them under the message as chips with
title and status, read per viewer and only for tasks they reach, on
loads and live pushes alike.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 09:23:39 +01:00
tbenandClaude Opus 5.5 ea4b5c1bf2 Have bots check the next step with ask_user instead of deciding
The proactive note asked for a next-step question in text, the questions
note only allowed asking when the bot couldn't tell what the user would
pick, and the coordinator prompt said to pick a sensible default. Next
steps and choices that are the user's now go on an ask_user card, in
replies, user-started task reports and the coordinator's prompts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 08:53:37 +01:00
tbenandClaude Opus 5.5 4063cd3b22 Show a file's full path beside its size in the preview
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:57:14 +01:00
tbenandClaude Opus 5.5 3bd749428e Release v0.16.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:38:37 +01:00
tbenandClaude Opus 5.5 cd6702de55 Lead back to the last conversation from settings and the rail pages
The last-visited cookie now records the workspace too (`<bot>:<workspace>`),
the landing page still reading only the bot. Settings and the rail pages get
that conversation, access-checked, as `last_conversation`, shown above their
rail list as a way back naming the bot and its workspace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:38:37 +01:00
tbenandClaude Opus 5.5 1a6ae71286 Keep replies on the picked model, with fallbacks of its own
A production chat dropped from the pinned DeepSeek to a free Nemotron
after one failed call mid-run, and every reply for the next half hour
ran on it: it called browser tools from chat replies, then said it had
no browser. Nothing recorded why.

- A failed model (or provider, for a key or credits) rests for the
  install's model rest, 2 minutes by default (Settings > General run
  limits, harness_model_rest_seconds), never longer, Retry-After
  included. A refused request (400, 422) benches nothing.
- The text model takes up to 3 fallback models, from any provider,
  tried in order after the pick and before the free automatic picks
  (fallback_model_ids in the setting's options; defaults, bots and
  workspaces).
- A run that fell back to an automatic pick goes back to the pick or
  its fallbacks once they've rested.
- Every model failure is logged with the provider's error and its rest.
- A message answered in place of the model ahead of it shows the
  fallback on its usage chip; the details list what failed and what
  was passed over while resting.
- A computer or browser tool called from a reply is told to start a
  task instead of getting a list of names.
- The work-under-way check catches "I'll open/drive/check ... now /
  directly / and see" with no run started.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:31:36 +01:00
tbenandClaude Opus 5.5 7cc881f1da Release v0.16.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:37:58 +01:00
tbenandClaude Opus 5.5 b717220bc3 Let task runs hear the user mid-run
A production run kept a verdict the user had overruled while it worked,
and the reply to the correction queued a second run that redid the first.

- Task runs the user follows take in what they write in the conversation
  since the run was queued: at the start, between steps, past a report
  not yet out, and by the wrap up (no steps left: the report says what it
  changes). A correction changes the work; anything else is left to the
  chat, and crew messages to the reply they wake. Routines, hook calls
  and rooms are unchanged.
- runTextLoop takes the caller's notes for what came in (incoming_notes)
  and, with a wrap_up note, reads it before the wrap up too.
- A reply is told which of the bot's runs are open in its session and
  hear the user, so a correction never starts another; start_task's
  open-run refusal says the same.
- The reply's message-to-turn reading is shared (messagesToTurns).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:32:17 +01:00
tbenandClaude Opus 5.5 6e153d311e Stop the crew asking for the same files three times
A production chat took three chatrooms to get two files from one bot,
hit the step limit twice with the report unwritten, and spent three runs
on hand-overs that only said they were waiting.

- A room's answer copies every file it names that the asking bot can't
  read (a member saves to its own folder) into the asker's folder under
  crew/room-<id>/, and points the refs at the copies.
- ask_crew refuses a second open request from the same place unless it's
  separate, and task runs, which see only their brief, are shown their
  bot's open and recent requests.
- update_task unlinks files with unlink_file_ids (a task holds 20), and
  list_tasks with task_id lists what's filed.
- A long run is told once, 5 steps before the wrap up, to save its report.
- delegate_task with start: false hands a task over without starting it.
- Prompt notes: task reports speak to the user as "you"; a bot goes with
  the user's reading once overruled; a crew answer isn't the go-ahead and
  silence isn't an answer.
- Quoting a message reads each ref chip as one inline label instead of a
  paragraph per chip; a copied chat says "Task #27", not "Task task #27".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:06:25 +01:00
tbenandClaude Opus 5.5 6532abc715 Release v0.16.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 05:55:47 +01:00
tbenandClaude Opus 5.5 be4eb13a7c Cut the tokens every run resends
Production spent 284M prompt tokens against 4M written: every turn resends
the system prompt, tool definitions and whole transcript, and on 1M-window
models a run was only trimmed near 730k tokens (one routine run spent 39M,
one task ran 401 steps).

- A working context (Settings > General, 80k tokens by default) caps what a
  turn sends whatever the model's window, counting tool definitions too.
  Old tool output, then long tool call arguments, are cut in one block
  down to 60% of it, so the cached start of the prompt holds between cuts.
- Routine runs and hook calls stop at 40 steps by default, and any run
  wraps up once it has sent 4M prompt tokens; both are settings.
- Only the newest page snapshot of each browser stays in a run, and
  browser results are capped at 12k characters.
- MCP server tools and a user's browser tools are listed by name and
  loaded with load_tools when their definitions are large, instead of
  riding along on every turn.
- token_usages records cached_tokens; the Usage page and message details
  show the cached share.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 05:55:47 +01:00
tbenandClaude Opus 5.5 86d171729f Keep chatroom work moving when the asked bot's computer is busy
A chatroom job no longer waits behind the job holding its computer (often
the asking bot's own run, which could take an hour): it runs beside it with
the shell and files but no browser. Room jobs no longer count when a bot's
face is put back after another job ends, so a bot doesn't show work in its
own chat that only happens in a room. ask_crew tells bots not to start a
task that needs the answer in the same reply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 05:35:32 +01:00
tbenandClaude Opus 5.5 38648fc083 Release v0.15.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
tbenandClaude Opus 5.5 6414d4e675 Let bots learn from the user's reactions
A reply's history now shows the user's own reactions on each bot message
in its app record, and the chat reply note tells the bot to save the
lasting preferences they show in its memory of that user. Adds a Dislike
reaction so a bot can tell what to avoid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
tbenandClaude Opus 5.5 ae64ef195d Release v0.15.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 06a4b7bb36 Step through a folder's images in the preview
An image opened from a list (a folder, the Files page, the chat's files
modal, a message's images) gets that list's images as a gallery:
Previous and Next in the header and the arrow keys step through them in
the same modal, each opening at its own fit, neighbours preloaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 2c8023ee4b Release v0.15.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:02:22 +01:00
tbenandClaude Opus 5.5 c0e79ee39c Open folder chips in a modal and give image previews zoom and fits
A folder chip opens the folder's listing over the chat, files opening
their own preview on top; a modified click or Open in Files still goes
to the files browser. Image previews get a viewer: 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 and drag to pan. Escape closes only the top modal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:02:22 +01:00
tbenandClaude Opus 5.5 bc9739509c Release v0.15.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
tbenandClaude Opus 5.5 4d6c330954 Have worker bots work in their own home on computers
A worker now works in /home/cb-<bot>/workspace/users/<user> (cwd, HOME
and ~), with its bot-wide folder at /home/cb-<bot>/workspace and, in a
workspace, the shared folder at /home/cb-<bot>/workspace/workspaces/<id>.
Only /home/cb-<bot>/workspace is kept: the agent makes it a link to the
bot's folder on the mounted workspace (bots/<bot>), and workspaces/<id>
in it a link to the workspace's shared folder, checking both on every
request and putting back one that's gone. Nothing on disk moves, so
existing work opens at the new paths.

Paths are checked on their real place (computerWorkspacePath), so the
real spelling still works, and shown to a worker its own way
(computerRunPath). Computer folder refs take either spelling. The
coordinator keeps working in the computer's workspace.

Computer image 1.3.0; the layout bump recreates every computer once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
225 changed files with 6039 additions and 765 deletions
+14 -11
View File
@@ -90,16 +90,18 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot (cookie `cobble_last_visited_bot_id`, never a workspace conversation) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images/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. 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.
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **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.
- **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).
- **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`.
- **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.
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. Tasks don't get files yet.
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
@@ -115,11 +117,11 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Queue (`bots_queue`)
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last.
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
### Live updates
@@ -127,7 +129,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 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; 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`). 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`).
### Workspaces
@@ -141,7 +143,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: `--disable-gpu`, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at `LightweightFrameRate` fps), extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Chrome reads only one `--disable-features=`/`--enable-features=`, so `browserArgs` merges the agent's with the extra flags' (`mergeFeatureFlags`). Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
- **Folders:** a run works only in `bots/<bot>/users/<user>` (cwd, `HOME`), `bots/<bot>` and `workspaces/<workspace>` (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`), and Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
@@ -158,7 +160,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, 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`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **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`; 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 and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -210,9 +212,10 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`), trims old tool output to fit context. 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; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **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`), 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`; a long run is told once, `AppData.HarnessStepsLowWarning` steps before the wrap up, to save its report, since the wrap up has no tools) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
- **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; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). 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`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `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, `start_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). 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).
+2 -2
View File
@@ -9,7 +9,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.9",
"@moduletrace/twui": "^0.1.10",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -279,7 +279,7 @@
"@moduletrace/bunext": ["@moduletrace/[email protected]", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.5/bunext-1.3.5.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-Es59Dvq3/eF726+SOHPiKtlJ87UFmyJZI4gpeciW/fA/3ZwOWws2Mm3oD6eZnOj9BP/zlBKOWA9DPTl35IP3lg=="],
"@moduletrace/twui": ["@moduletrace/[email protected].9", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.9/twui-0.1.9.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-HN/emdqSCxQclzFEojDsaujjgO+dkQy4wC7Rk6gCQH/fK2Hv0CQ5DLOdOB8oDE7nu+m7/0qKo878UeufBbEotg=="],
"@moduletrace/twui": ["@moduletrace/[email protected].10", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.10/twui-0.1.10.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-eShpG6jK7qr2+oG7Pq4PvHnvAOUPkbxMCf9BVfiuJqUdtuaQSo2jqcggGAonGDu4p8Nn/KWTd2KrypE/+W4wTg=="],
"@next/mdx": ["@next/[email protected]", "", { "dependencies": { "source-map": "^0.7.0" }, "peerDependencies": { "@mdx-js/loader": ">=0.15.0", "@mdx-js/react": ">=0.15.0" }, "optionalPeers": ["@mdx-js/loader", "@mdx-js/react"] }, "sha512-Vpfuf928ACvx4AOdDXWx/cj13Ak6xlvMn3QCkjvfQMmLnQWCesQTeY01CPDbIyZvjY+NOwP7bvbvJ2ghkj/3GA=="],
+8 -2
View File
@@ -55,7 +55,13 @@ commands. Every worker bot works as its own account, `cb-<bot id>` (uid and
gid `100000 + id`, no sudo), made by the agent the first time the app acts
for it (`run_as`). Its folder `bots/<id>` is its own (`2770`), and a
workspace's folder `workspaces/<id>` (root's) belongs to the group `cw-<id>`
its bots join. `gem`, and so Chrome, can't open either: the app passes a
its bots join. A worker works through its home: `/home/cb-<id>/workspace`
is a link to `bots/<id>` (the only part of its home that's kept, since the
home itself lives in the container), its users' folders are `users/<user>`
in it, and in a workspace `workspaces/<workspace id>` in it is a link to
that workspace's folder. The agent checks both links on every request for
the worker and puts back one that's gone (whatever sits in its place is
moved aside). `gem`, and so Chrome, can't open either: the app passes a
worker's uploads, downloads and files saved by name through a folder of the
call's own, copied by the worker's account (`sudo -u`), and a worker can't
open `file:` URLs. Its env files live in its own home.
@@ -116,7 +122,7 @@ tag; the release workflow builds a tag once (a dispatch with
bun run build:computer # builds AppData.ComputerImage for this machine
docker run -d --name cobble-computer-dev --shm-size 2g \
--security-opt seccomp=unconfined --cap-add NET_ADMIN -p 8170:8080 \
ghcr.io/moduletrace/cobble-computer:1.2.0
ghcr.io/moduletrace/cobble-computer:1.3.0
```
A computer run by hand like that has no token, so anyone who reaches its port
+78 -9
View File
@@ -1,8 +1,9 @@
import { execFile } from "node:child_process";
import { chmod, chown, mkdir, stat } from "node:fs/promises";
import { chmod, chown, lstat, mkdir, readlink, rename, stat, symlink, unlink } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { AgentConfig } from "./config";
import commandArgv from "./command-argv";
import log from "./log";
import type { RunUser } from "./run-user-for";
@@ -20,19 +21,28 @@ let queue: Promise<unknown> = Promise.resolve();
* Makes a worker's account and, in a workspace, its group (idempotent,
* one at a time), and hands it its folders: its home (private), the bot's
* folder (its own) and the workspace's (its group's). Neither gem nor any
* other worker can read them; the coordinator, as gem, uses sudo.
* other worker can read them; the coordinator, as gem, uses sudo. Then,
* on every call, makes sure of the links the worker works through
* (`keepLinks`): only the bot's folder is kept, so a write through a link
* that's gone would land somewhere a recreate wipes.
*/
export default function ensureRunUser({ run_user }: { run_user: RunUser }) {
export default async function ensureRunUser({ run_user }: { run_user: RunUser }) {
const key = `${run_user.uid}:${run_user.workspace?.gid || 0}`;
if (ready.has(key)) return Promise.resolve();
if (!ready.has(key)) {
await serially(async () => {
if (ready.has(key)) return;
const next = queue.then(async () => {
if (ready.has(key)) return;
await setUp({ run_user });
ready.add(key);
});
}
await setUp({ run_user });
ready.add(key);
});
if (!(await linksInPlace({ run_user }))) await serially(() => keepLinks({ run_user }));
}
function serially(work: () => Promise<void>) {
const next = queue.then(work);
queue = next.catch(() => {});
@@ -71,6 +81,65 @@ async function setUp({ run_user }: { run_user: RunUser }) {
* bots share it through the group.
*/
if (workspace) await shareFolder({ dir: workspace.dir, uid: 0, gid: workspace.gid });
await keepLinks({ run_user });
}
/**
* Whether the worker's links lead where they should: `workspace` in its
* home to the bot's folder, and in a workspace, `workspaces/<id>` in the
* bot's folder to the workspace's shared one. Only reads.
*/
async function linksInPlace({ run_user }: { run_user: RunUser }) {
if (!(await isLinkTo({ link: run_user.kept_dir, target: run_user.bot_dir }))) return false;
return !run_user.workspace || isLinkTo({ link: run_user.workspace.link, target: run_user.workspace.dir });
}
async function isLinkTo({ link, target }: { link: string; target: string }) {
const info = await lstat(link).catch(() => null);
return !!info?.isSymbolicLink() && (await readlink(link).catch(() => "")) == target;
}
/**
* Puts the worker's links back where they're missing or lead elsewhere.
* Whatever else sits in a link's place is moved aside, never deleted.
* The home's link is made as root (the home is a real folder in root's
* /home, so nothing in its path is the worker's to swap); the shared
* folder's, inside the bot's folder (the worker's own), by the worker's
* account, so a link it left there can't send root anywhere.
*/
async function keepLinks({ run_user }: { run_user: RunUser }) {
const { kept_dir, bot_dir, workspace } = run_user;
if (!(await isLinkTo({ link: kept_dir, target: bot_dir }))) {
const info = await lstat(kept_dir).catch(() => null);
if (info?.isSymbolicLink()) await unlink(kept_dir);
else if (info) await rename(kept_dir, `${kept_dir}.before-${Date.now()}`);
await symlink(bot_dir, kept_dir);
}
if (workspace && !(await isLinkTo({ link: workspace.link, target: workspace.dir }))) {
const link = quoted({ text: workspace.link });
const target = quoted({ text: workspace.dir });
const argv = commandArgv({
command: [
`umask 007`,
`mkdir -p "$(dirname ${link})"`,
`if [ -L ${link} ]; then ln -sfn ${target} ${link}; elif [ -e ${link} ]; then mv ${link} ${link}.before-$(date +%s) && ln -s ${target} ${link}; else ln -s ${target} ${link}; fi`,
].join(" && "),
as: { uid: run_user.uid, gid: run_user.gid },
});
await run(argv.file, argv.args, { cwd: "/", timeout: 30_000 });
}
}
function quoted({ text }: { text: string }) {
return `'${text.replaceAll("'", `'\\''`)}'`;
}
/**
+2
View File
@@ -8,6 +8,7 @@ describe("runUserFor", () => {
uid: 100_007,
gid: 100_007,
home: "/home/cb-7",
kept_dir: "/home/cb-7/workspace",
bot_dir: "/home/gem/workspace/bots/7",
workspace: null,
});
@@ -18,6 +19,7 @@ describe("runUserFor", () => {
name: "cw-12",
gid: 10_000_012,
dir: "/home/gem/workspace/workspaces/12",
link: "/home/gem/workspace/bots/3/workspaces/12",
});
});
+16 -5
View File
@@ -9,21 +9,28 @@ export type RunUser = {
* Its home, in the container (the env files live there).
*/
home: string;
/**
* `workspace` in its home: a link to `bot_dir`, the only part of its
* home that's kept. The app names every worker path through it.
*/
kept_dir: string;
/**
* The bot's folder in the workspace, owned by the account.
*/
bot_dir: string;
/**
* The workspace the run is in: its shared folder belongs to this group,
* which the account joins.
* which the account joins, and `link` (`workspaces/<id>` in the bot's
* folder) leads to it.
*/
workspace: { name: string; gid: number; dir: string } | null;
workspace: { name: string; gid: number; dir: string; link: string } | null;
};
/**
* The account a worker bot's commands run as on this computer
* (`cb-<bot id>`, no sudo) and, in a workspace, the group its bots share
* (`cw-<id>`). Throws for an id that isn't a whole number in range.
* (`cw-<id>`). Keep alike the app's `computerWorkerAccount` and
* `computerRunDirs`. Throws for an id that isn't a whole number in range.
*/
export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown; workspace_id?: unknown }): RunUser {
const bot = runId({ value: bot_id });
@@ -38,18 +45,22 @@ export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown;
const id = AgentConfig.WorkerIdBase + bot;
const name = `cb-${bot}`;
const home = `/home/${name}`;
const bot_dir = path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot));
return {
name,
uid: id,
gid: id,
home: `/home/${name}`,
bot_dir: path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot)),
home,
kept_dir: path.posix.join(home, "workspace"),
bot_dir,
workspace: workspace
? {
name: `cw-${workspace}`,
gid: AgentConfig.WorkspaceGroupBase + workspace,
dir: path.posix.join(AgentConfig.WorkspaceDir, "workspaces", String(workspace)),
link: path.posix.join(bot_dir, "workspaces", String(workspace)),
}
: null,
};
+11
View File
@@ -592,6 +592,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `JSON \`[{ name, ok }]\`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)`,
dataType: "TEXT",
},
{
fieldName: "task_ids",
fieldDescription: `JSON \`[id, ...]\`: the tracker tasks (\`tasks\`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none`,
dataType: "TEXT",
},
{
fieldName: "from_chatroom_id",
fieldDescription: `Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key`,
@@ -4289,6 +4294,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
dataType: "INTEGER",
defaultValue: 0,
},
{
fieldName: "cached_tokens",
fieldDescription: `Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it`,
dataType: "INTEGER",
defaultValue: 0,
},
{
fieldName: "completion_tokens",
fieldDescription: `Tokens written back: the answer, its tool calls and its reasoning`,
+8
View File
@@ -412,6 +412,10 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
* JSON `[{ name, ok }]`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)
*/
tool_log?: string;
/**
* JSON `[id, ...]`: the tracker tasks (`tasks`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none
*/
task_ids?: string;
/**
* Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key
*/
@@ -2638,6 +2642,10 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
* Tokens sent: the prompt, the system instructions and the tool results
*/
prompt_tokens?: number | "";
/**
* Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it
*/
cached_tokens?: number | "";
/**
* Tokens written back: the answer, its tool calls and its reasoning
*/
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.14.2",
"version": "0.16.3",
"module": "index.ts",
"type": "module",
"private": true,
@@ -45,7 +45,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.9",
"@moduletrace/twui": "^0.1.10",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -212,3 +212,64 @@ describe("botMessagesToHarness with mentions", () => {
]);
});
});
describe("botMessagesToHarness with reactions", () => {
test("adds the user's reactions to the record of the message's tools", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "summarise it"),
{
...message("bot", "Here it is."),
tool_log: JSON.stringify([{ name: "read_file", ok: true }]),
reactions: [
{ emoji: "👍" as const, count: 1, mine: true },
{ emoji: "👎" as const, count: 1, mine: true },
],
},
],
}),
).toEqual([
{ role: "user", content: "summarise it" },
{
role: "assistant",
content:
"Here it is.\n\n[App record: this message's run called read_file. The user reacted to it with 👍 (like), 👎 (dislike).]",
},
]);
});
test("records reactions on a message whose run wasn't recorded", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "hi"),
{
...message("bot", "hello"),
reactions: [{ emoji: "❤️" as const, count: 1, mine: true }],
},
],
}),
).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello\n\n[App record: The user reacted to it with ❤️ (love).]" },
]);
});
test("leaves out reactions that aren't the user's", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "hi"),
{
...message("bot", "hello"),
reactions: [{ emoji: "🎉" as const, count: 1, mine: false }],
},
],
}),
).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello" },
]);
});
});
+51 -8
View File
@@ -1,7 +1,8 @@
import isCrewMessage from "@/src/utils/is-crew-message";
import { BotMessageReactions } from "@/src/dict/bot-dict";
import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/harness/types";
import type { BotMessageWithAttachments } from "@/src/types";
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
import describeAttachment from "./describe-attachment";
@@ -10,7 +11,15 @@ import crewMessageBlock from "@/src/utils/crew-message-block";
type Params = {
messages: Pick<
BotMessageWithAttachments,
"id" | "author" | "text" | "attachments" | "reply_to" | "tool_log" | "from_chatroom_id" | "from_install_request_id"
| "id"
| "author"
| "text"
| "attachments"
| "reply_to"
| "tool_log"
| "reactions"
| "from_chatroom_id"
| "from_install_request_id"
>[];
/**
* Loaded files by message id (`loadAttachmentParts`). Files of other
@@ -34,7 +43,8 @@ type Turn = { role: "user" | "assistant"; parts: HarnessContentPart[] };
* starts with the user. A turn that is only text stays a string. A bot
* message whose run was recorded (`tool_log`) is followed by the app's
* record of the tools it called, so the bot can tell what its past
* messages actually did from what they say. A chatroom's outcome brought
* messages actually did from what they say, and of how the user reacted
* to it, their feedback on it. A chatroom's outcome brought
* back to the bot, or the coordinator's answer to its install request
* (`isCrewMessage`), is a user turn fenced as what the
* coordinator passed on (`crewMessageBlock`), never the user's words.
@@ -95,7 +105,9 @@ function messageParts({
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
if (role == "assistant") {
const record = text ? appRecord({ tool_log: message.tool_log }) : "";
const record = text
? appRecord({ tool_log: message.tool_log, reactions: message.reactions })
: "";
return record ? [...content, { type: "text", text: record }] : content;
}
@@ -116,10 +128,25 @@ function messageParts({
}
/**
* The app's line after a bot message naming the tools its run called, or
* nothing when the run wasn't recorded.
* The app's line after a bot message naming the tools its run called and
* the user's own reactions to it, or nothing when there's neither.
*/
function appRecord({ tool_log }: { tool_log?: string | null }) {
function appRecord({
tool_log,
reactions,
}: {
tool_log?: string | null;
reactions?: BotMessageReaction[];
}) {
const facts = [toolsRecord({ tool_log }), reactionsRecord({ reactions })].filter(Boolean);
return facts.length ? `${AppRecordPrefix} ${facts.join(" ")}]` : "";
}
/**
* The tools a recorded run called, or nothing when it wasn't recorded.
*/
function toolsRecord({ tool_log }: { tool_log?: string | null }) {
if (!tool_log) return "";
let uses: HarnessToolUse[];
@@ -134,7 +161,23 @@ function appRecord({ tool_log }: { tool_log?: string | null }) {
const called = uses.length ? describeToolUses({ uses }) : "no tools";
return `${AppRecordPrefix} this message's run called ${called}.]`;
return `this message's run called ${called}.`;
}
/**
* The reactions the user gave a message, named, or nothing. A bot's own
* reactions aren't the user's feedback.
*/
function reactionsRecord({ reactions }: { reactions?: BotMessageReaction[] }) {
const named = (reactions || [])
.filter((reaction) => reaction.mine)
.map((reaction) => {
const title = BotMessageReactions.find((known) => known.value == reaction.emoji)?.title;
return title ? `${reaction.emoji} (${title.toLowerCase()})` : reaction.emoji;
});
return named.length ? `The user reacted to it with ${named.join(", ")}.` : "";
}
/**
+31
View File
@@ -0,0 +1,31 @@
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
import type { HarnessMessage } from "@/src/harness/types";
import type { BotMessageWithAttachments } from "@/src/types";
import botMessagesToHarness from "./bot-messages-to-harness";
import loadAttachmentParts from "./load-attachment-parts";
type Params = {
messages: BotMessageWithAttachments[];
/**
* Whose conversation it is: the refs in the user's messages are named
* as that user sees them.
*/
user_id: number | string;
};
/**
* A conversation's messages as a run reads them: with the files of each
* (`loadAttachmentParts`) and the names of the bots, workspaces and other
* refs the user's messages point at. Replies and task runs read the same
* way.
*/
export default async function messagesToTurns({ messages, user_id }: Params): Promise<HarnessMessage[]> {
return botMessagesToHarness({
messages,
parts: await loadAttachmentParts({ messages }),
refs: await grabMessageRefNames({
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
user_id,
}),
});
}
+12 -4
View File
@@ -168,7 +168,7 @@ export default async function processBotJob({
* The face changes once the job really starts, after any wait for
* its computer.
*/
const run = async () => {
const run = async ({ computer_shared }: { computer_shared?: boolean } = {}) => {
await setFace({
face: "working",
status_line:
@@ -194,6 +194,7 @@ export default async function processBotJob({
job,
params,
checkpoint: parseJobJson({ text: job.checkpoint }),
computer_shared,
signal: run_signal,
update,
report,
@@ -203,19 +204,25 @@ export default async function processBotJob({
/**
* A task whose computer is busy says so while it waits, so the
* user doesn't see silence.
* user doesn't see silence. A chatroom job doesn't wait: the bot
* that asked is often the one holding the computer, with a run of
* up to an hour, and the room would sit silent until it ends. It
* works beside it with the shell and files only (`computer_shared`),
* which is all most answers need.
*/
const runOnComputer = async (computer_id: number) => {
if (computer_lock.busy({ key: computer_id })) {
if (params.chatroom_id) return await run({ computer_shared: true });
await setFace({ face: "asleep", status_line: BotComputerBusyStatusLine });
}
return await computer_lock.run({ key: computer_id, task: run });
return await computer_lock.run({ key: computer_id, task: () => run() });
};
const outcome =
job.kind == "reply"
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: run })
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: () => run() })
: job.computer_id
? await runOnComputer(job.computer_id)
: await run();
@@ -230,6 +237,7 @@ export default async function processBotJob({
silent: outcome.silent,
attachments: outcome.attachments,
tool_log: outcome.tool_log,
task_ids: outcome.task_ids,
});
await pushBotNotice({ bot_id, ...completion });
+6 -2
View File
@@ -5,6 +5,7 @@ import notifyBotMessage from "@/src/push/notify-bot-message";
import notifyBotFace from "@/src/push/notify-bot-face";
import pushBotUpdated from "./push-bot-updated";
import pushToSessionUser from "./push-to-session-user";
import withSessionMessageTasks from "./with-session-message-tasks";
import grabSessionChatroomId from "@/src/functions/backend/db/chatrooms/grab-session-chatroom-id";
import pushChatroomMessage from "@/src/functions/backend/db/chatrooms/push-chatroom-message";
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
@@ -66,7 +67,10 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
} else if (message && !hook_id) {
await pushToSessionUser({
session_id: message.session_id,
data: { event: "server:bot-message", data: message },
/**
* With its task chips, like a loaded message.
*/
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message }) },
});
/**
@@ -78,7 +82,7 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
if (relay) {
await pushToSessionUser({
session_id: relay.message.session_id,
data: { event: "server:bot-message", data: relay.message },
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message: relay.message }) },
});
if (!quiet_push) void notifyBotMessage({ message: relay.message });
+25 -18
View File
@@ -17,11 +17,12 @@ import {
TaskReminderNote,
workspaceAdminNote,
WorkspaceLearningNote,
openRunsNote,
} from "@/src/data/harness-prompts";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import workspaceAdminsNote from "./workspace-admins-note";
import type { WorkspaceAdminTools } from "@/src/harness/tools/bot/grab-workspace-admin-tools";
import { grabReplyMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
@@ -36,7 +37,8 @@ import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-s
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
import grabKnowledgebaseContext from "@/src/harness/tools/knowledgebases/grab-knowledgebase-context";
import botMessagesToHarness from "./bot-messages-to-harness";
import messagesToTurns from "./messages-to-turns";
import grabOpenSessionRuns from "@/src/functions/backend/db/bots-queue/grab-open-session-runs";
import composeBrowsersNote from "./compose-browsers-note";
import composeComputersNote from "./compose-computers-note";
import composeEnvsNote from "./compose-envs-note";
@@ -48,8 +50,6 @@ import readPastSessionTool from "@/src/harness/tools/bot/sessions/read-past-sess
import { grabBotSessionMaxMessages } from "@/src/functions/backend/db/app-settings/grab-bot-session-max-messages";
import BunSQLite from "@moduletrace/bun-sqlite";
import jobSessionId from "@/src/functions/backend/db/bots-queue/job-session-id";
import loadAttachmentParts from "./load-attachment-parts";
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
import withTakeOverRefs from "./with-take-over-refs";
import stripAppRecords from "@/src/utils/strip-app-records";
import hasUnansweredMessage from "./has-unanswered-message";
@@ -84,8 +84,9 @@ type Params = BotJobContext & {
* Messages the user sends while it works join the run (`incoming`): one
* that changes the work changes the answer before it goes out, and one
* that's separate can be acknowledged at once (`send_message`) and done
* after the current work. The job records the newest
* one it read (`markReplyAnswered`). Finishes silently when an earlier
* after the current work. Runs open in the session take in what the user
* writes too (`openRunsNote`), so a correction to one starts no other.
* The job records the newest one it read (`markReplyAnswered`). Finishes silently when an earlier
* reply already read everything (`hasUnansweredMessage`). An answer naming
* files or tasks that don't exist, or saying work is under way when none
* is, is written again once (`reviewBotReply`).
@@ -108,6 +109,7 @@ export default async function runBotReply({
const history = await grabBotMessages({
session_id,
limit: AppData.BotReplyHistoryMessages,
user_id,
});
const answered_id = await grabAnsweredMessageId({ session_id });
@@ -123,16 +125,6 @@ export default async function runBotReply({
let seen_id = Math.max(0, ...history.map((message) => Number(message.id)));
let answering_id = newestUserMessageId({ messages: history });
const toTurns = async ({ messages }: { messages: BotMessageWithAttachments[] }) =>
botMessagesToHarness({
messages,
parts: await loadAttachmentParts({ messages }),
refs: await grabMessageRefNames({
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
user_id,
}),
});
/**
* What the user wrote since the run last looked.
*/
@@ -149,7 +141,7 @@ export default async function runBotReply({
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
return await toTurns({ messages: fresh });
return await messagesToTurns({ messages: fresh, user_id });
};
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
@@ -225,6 +217,10 @@ export default async function runBotReply({
* Files the bot wrote and asked to send with its reply.
*/
const attachments: number[] = [];
/**
* The tracker tasks the reply worked on, linked under it.
*/
const task_ids: number[] = [];
/**
* The files this run reaches: its file tools and the pictures it may
@@ -268,6 +264,7 @@ export default async function runBotReply({
led = admin;
},
onChatroom: ({ ref }) => shown.push(ref),
onTask: ({ task_id }) => task_ids.push(task_id),
});
/**
@@ -339,6 +336,12 @@ export default async function runBotReply({
? workspaceAdminNote({ workspace_name: lead.workspace.name || "this workspace", members: lead.members })
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id });
/**
* The bot's runs open here hear what the user writes: a correction to
* one reaches it, so the reply doesn't start another.
*/
const open_runs = attended ? await grabOpenSessionRuns({ bot_id: bot.id, session_id }) : [];
try {
const result = await runTextLoop({
system: [
@@ -368,6 +371,7 @@ export default async function runBotReply({
run_kind: browser_run_kind,
}),
crew_note,
openRunsNote({ runs: open_runs }),
powers.is_coordinator ? "" : AskCrewNote,
skills.note,
knowledge.note,
@@ -377,7 +381,7 @@ export default async function runBotReply({
]
.filter(Boolean)
.join("\n\n"),
messages: await toTurns({ messages: history }),
messages: await messagesToTurns({ messages: history, user_id }),
tools: [
...tools,
sendMessageTool({ bot_id: bot.id, session_id: Number(session_id), workspace_id }),
@@ -425,6 +429,8 @@ export default async function runBotReply({
...knowledge.tools,
],
max_steps: await grabReplyMaxToolSteps(),
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
bot_id: bot.id,
workspace_id,
signal,
@@ -450,6 +456,7 @@ export default async function runBotReply({
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
};
} finally {
await extensions.close();
+88 -17
View File
@@ -1,3 +1,4 @@
import grabCrewRequests from "@/src/functions/backend/db/chatrooms/grab-crew-requests";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings/grab-skill-limits";
import grabWorkspaceAdminTools from "@/src/harness/tools/bot/grab-workspace-admin-tools";
@@ -16,9 +17,18 @@ import {
TasksNote,
TaskRunNote,
AskCrewNote,
crewRequestsNote,
WorkspaceLearningNote,
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
} from "@/src/data/harness-prompts";
import { grabHarnessMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import {
grabContextBudgetTokens,
grabHarnessMaxToolSteps,
grabRunMaxPromptTokens,
grabUnattendedMaxToolSteps,
} from "@/src/functions/backend/db/app-settings/grab-run-limits";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
@@ -52,6 +62,9 @@ import stripAppRecords from "@/src/utils/strip-app-records";
import ScheduledRunFailedError from "./scheduled-run-failed-error";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
import taskIncoming from "./task-incoming";
import pushUserTurn from "@/src/harness/text/push-user-turn";
import type { HarnessMessage } from "@/src/harness/types";
type Params = BotJobContext & {
bot: Pick<BUN_SQLITE_COBBLE_BOTS, "kind"> & { id: number };
@@ -72,6 +85,10 @@ type Params = BotJobContext & {
* A scheduled run acts on its own (`ScheduledRunNote`), as does a hook
* call (`HookRunNote`, its payload only data); one that reports it failed
* (`report_run_failed`) throws, so the queue retries it.
* A task the user follows takes in what they write in its conversation
* from when it was queued (`taskIncoming`): already there at the start,
* between steps, past a report not yet out, and by the wrap up. A
* correction changes the work; anything else is left to the chat.
* Every model turn is reported as a step (`report`).
*/
export default async function runBotTask({
@@ -79,6 +96,7 @@ export default async function runBotTask({
user_id,
job,
params,
computer_shared,
signal,
report,
}: Params): Promise<BotJobOutcome> {
@@ -93,10 +111,15 @@ export default async function runBotTask({
* changed, whose chips the report always carries.
*/
const shown: string[] = [];
/**
* The tracker tasks the run worked on, linked under its report.
*/
const task_ids: number[] = [];
const computer = job.computer_id
? await openComputerTools({
computer_id: job.computer_id,
browser: !computer_shared,
bot_id: bot.id,
user_id,
workspace_id,
@@ -175,7 +198,14 @@ export default async function runBotTask({
*/
const admin_tools =
!powers.is_coordinator && workspace_id && powers.is_workspace_admin
? (await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, scopes })).tools
? (await grabWorkspaceAdminTools({
bot,
user_id,
workspace_id,
powers,
scopes,
onTask: ({ task_id }) => task_ids.push(task_id),
})).tools
: [];
const tools = [
@@ -189,6 +219,7 @@ export default async function runBotTask({
admin_workspace_ids: powers.admin_workspace_ids,
scopes,
hooked,
onTask: ({ task_id }) => task_ids.push(task_id),
})),
...admin_tools,
...(powers.is_coordinator
@@ -324,19 +355,50 @@ export default async function runBotTask({
/**
* The install's limit, or less when the brief's writer set a
* budget (`start_task` `max_steps`).
* budget (`start_task` `max_steps`). A routine run or a hook call,
* which nobody watches, gets the smaller unattended limit (never
* more than a task's).
*/
const install_steps = await grabHarnessMaxToolSteps();
const task_steps = await grabHarnessMaxToolSteps();
const install_steps =
scheduled || hooked ? Math.min(task_steps, await grabUnattendedMaxToolSteps()) : task_steps;
const budget = Math.floor(Number(params.max_steps) || 0);
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
/**
* What the user wrote since the run was queued, for a run they
* follow: what's there now goes after the brief.
*/
const incoming =
can_ask && session_id
? await taskIncoming({ session_id, queued_at: Number(job.created_at) || Date.now(), user_id })
: null;
const arrived = (await incoming?.take()) || [];
const brief: HarnessMessage = {
role: "user",
content: composeJobBrief({
title: job.title,
instructions: job.instructions,
params,
}),
};
const opening: HarnessMessage[] = [brief];
if (arrived.length) {
pushUserTurn({ transcript: opening, content: TaskIncomingNote });
for (const turn of arrived) {
if (turn.role == "user") pushUserTurn({ transcript: opening, content: turn.content });
}
}
const result = await runTextLoop({
system: [
prompt,
carry_over,
TaskRunNote,
budget > 0
? `This run has at most ${max_steps} steps (model turns), set when it was queued. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
budget > 0 || scheduled || hooked
? `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
: "",
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
@@ -358,7 +420,12 @@ export default async function runBotTask({
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
computer
powers.is_coordinator || hooked || params.chatroom_id
? ""
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
computer && computer_shared
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
: computer
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
: workspace_id
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
@@ -382,23 +449,26 @@ export default async function runBotTask({
]
.filter(Boolean)
.join("\n\n"),
messages: [
{
role: "user",
content: composeJobBrief({
title: job.title,
instructions: job.instructions,
params,
}),
},
],
messages: opening,
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
bot_id: bot.id,
workspace_id,
signal,
onStep: (step) =>
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
...(incoming
? {
incoming: incoming.take,
incoming_notes: {
working: TaskIncomingNote,
redraft: TaskRedraftNote,
wrap_up: TaskWrapUpIncomingNote,
},
}
: {}),
});
if (failure) {
@@ -415,6 +485,7 @@ export default async function runBotTask({
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
};
} finally {
await extensions?.close();
@@ -0,0 +1,40 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
/**
* A task run reads what the user wrote in its session after it was
* queued. Run against real SQLite.
*/
const db = new Database(":memory:");
db.run(`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT, created_at INTEGER)`);
db.run(`INSERT INTO bot_messages VALUES
(1, 1, 'user', 100),
(2, 1, 'bot', 200),
(3, 2, 'user', 250),
(4, 1, 'user', 300),
(5, 1, 'bot', 400)`);
function baseline({ session_id, queued_at }: { session_id: number; queued_at: number }) {
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
return (db.query(sql).get(...values) as { id: number }).id;
}
describe("taskIncomingBaselineSql", () => {
test("is the session's newest message when the run was queued", () => {
expect(baseline({ session_id: 1, queued_at: 250 })).toBe(2);
expect(baseline({ session_id: 1, queued_at: 300 })).toBe(4);
});
test("ignores other sessions", () => {
expect(baseline({ session_id: 2, queued_at: 260 })).toBe(3);
expect(baseline({ session_id: 1, queued_at: 260 })).toBe(2);
});
test("is 0 when the session had nothing yet", () => {
expect(baseline({ session_id: 1, queued_at: 50 })).toBe(0);
expect(baseline({ session_id: 9, queued_at: 500 })).toBe(0);
});
});
@@ -0,0 +1,22 @@
import type { SqlCondition } from "@/src/utils/crew-access/types";
type Params = {
session_id: number | string;
/**
* When the run was queued (`bots_queue.created_at`, ms).
*/
queued_at: number;
};
/**
* The SQL for the newest message a session had when a run was queued:
* what the user writes after it is new to the run, however long it waited
* for its computer or how often it was tried. Selects one `id` column, 0
* for an empty session.
*/
export default function taskIncomingBaselineSql({ session_id, queued_at }: Params): SqlCondition {
return {
sql: `SELECT COALESCE(MAX(id), 0) AS id FROM bot_messages WHERE session_id = ? AND created_at <= ?`,
values: [Number(session_id), Number(queued_at)],
};
}
+51
View File
@@ -0,0 +1,51 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import type { HarnessMessage } from "@/src/harness/types";
import isCrewMessage from "@/src/utils/is-crew-message";
import messagesToTurns from "./messages-to-turns";
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
type Params = {
session_id: number | string;
/**
* When the run was queued (`bots_queue.created_at`, ms).
*/
queued_at: number;
/**
* Whose conversation it is.
*/
user_id: number | string;
};
/**
* What the user writes in a task run's conversation, for the run to take
* in (`runTextLoop`'s `incoming`): each `take` returns the messages since
* the last, starting from when the run was queued. A crew message (a
* room's outcome, an install answer) is left to the reply it wakes.
*/
export default async function taskIncoming({ session_id, queued_at, user_id }: Params) {
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
const res = await BunSQLite.sql<{ id: number }>({ sql, values });
let seen_id = Number(res.payload?.[0]?.id) || 0;
const take = async (): Promise<HarnessMessage[]> => {
const fresh = await grabBotMessages({
session_id,
after_id: seen_id,
author: "user",
limit: AppData.BotReplyHistoryMessages,
});
if (!fresh.length) return [];
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
const from_user = fresh.filter((message) => !isCrewMessage({ message }));
return from_user.length ? await messagesToTurns({ messages: from_user, user_id }) : [];
};
return { take };
}
+11
View File
@@ -9,6 +9,12 @@ export type BotJobContext = {
* Saved by an earlier attempt, if the job was picked up again.
*/
checkpoint: Record<string, unknown> | null;
/**
* The job runs on its computer beside another job that holds it (a
* chatroom job, which never waits for a busy computer): it gets the
* computer's shell and files, never its browser.
*/
computer_shared?: boolean;
/**
* Aborted when the job is cancelled or lost to another handler. Stop
* work and return; the result is discarded.
@@ -51,6 +57,11 @@ export type BotJobOutcome = {
* the result message as `tool_log`.
*/
tool_log?: HarnessToolUse[];
/**
* The tracker tasks the run worked on (`onTask` from its task tools),
* kept on the result message as `task_ids`.
*/
task_ids?: number[];
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
@@ -0,0 +1,27 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import withMessageTasks from "@/src/functions/backend/db/bots/with-message-tasks";
type Params = {
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
};
/**
* A message about to be pushed, with the tracker tasks it's about as its
* session's user sees them (`withMessageTasks`). Without any, or when the
* session is gone, it's returned as it is.
*/
export default async function withSessionMessageTasks({ message }: Params) {
if (!message.task_ids || !message.session_id) return message;
const session = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT user_id FROM bot_sessions WHERE id = ? LIMIT 1`,
values: [message.session_id],
})
).payload?.[0];
if (!session?.user_id) return message;
return (await withMessageTasks({ messages: [message], user_id: session.user_id }))[0] ?? message;
}
+4 -7
View File
@@ -1,7 +1,7 @@
import Img from "@moduletrace/twui/layout/Img";
import Stack from "@moduletrace/twui/layout/Stack";
import type { FilePreviewKind } from "@/src/utils/file-preview-kind";
import FilePreviewNotice from "./file-preview-notice";
import ImageViewer from "./image-viewer";
import FilePreviewText from "./file-preview-text";
type Props = {
@@ -13,7 +13,8 @@ type Props = {
/**
* The preview itself, by kind. Media the browser draws itself (images,
* PDFs, audio, video) load from the file's URL; text kinds are read into
* PDFs, audio, video) load from the file's URL, an image in a viewer with
* zoom and fits (`ImageViewer`); text kinds are read into
* the page (`FilePreviewText`). Nothing here runs the file: an SVG shows
* through `<img>`, which runs no script, and an HTML page in a frame
* sandboxed twice (the attribute here and the `sandbox` CSP the media
@@ -22,11 +23,7 @@ type Props = {
*/
export default function FilePreviewBody({ kind, name, url, size }: Props) {
if (kind == "image") {
return (
<Stack className="grow min-h-0 w-full items-center justify-center p-4 overflow-auto bg-sunken">
<Img src={url} alt={name} className="max-w-full max-h-full object-contain" />
</Stack>
);
return <ImageViewer url={url} name={name} />;
}
if (kind == "pdf") {
@@ -0,0 +1,27 @@
import Span from "@moduletrace/twui/layout/Span";
import formatBytes from "@/src/utils/format-bytes";
type Props = {
size?: number;
/**
* Where the file sits (`bots/3/reports/q3.md`).
*/
full_path?: string;
};
/**
* The line under a previewed file's name: its size and its full path,
* whichever of them is known. The path wraps rather than cuts off, so all
* of it can be read (and selected to copy).
*/
export default function FilePreviewDetails({ size, full_path }: Props) {
const text = [size ? formatBytes({ bytes: size }) : "", full_path || ""].filter(Boolean).join(" · ");
if (!text) return null;
return (
<Span title={full_path || undefined} className="w-full text-[13px] leading-[18px] text-ink-secondary break-all">
{text}
</Span>
);
}
+23 -1
View File
@@ -1,5 +1,6 @@
import { useState, type ReactNode } from "react";
import Link from "@moduletrace/twui/layout/Link";
import type { FilePreviewItem } from "@/src/types";
import isPlainClick from "@/src/utils/is-plain-click";
import FilePreviewModal from "./file-preview-modal";
@@ -8,6 +9,15 @@ type Props = {
url: string;
media_type?: string | null;
size?: number;
/**
* Where the file sits (`bots/3/reports/q3.md`), for the preview.
*/
full_path?: string;
/**
* The images it sits among (`imagePreviewGallery`), for Previous and
* Next in the preview.
*/
gallery?: FilePreviewItem[];
title?: string;
className?: string;
children: ReactNode;
@@ -18,7 +28,17 @@ type Props = {
* plain click. It stays a real link to the bytes, so a middle click or
* Ctrl/Cmd click still opens the file in a new tab.
*/
export default function FilePreviewLink({ name, url, media_type, size, title, className, children }: Props) {
export default function FilePreviewLink({
name,
url,
media_type,
size,
full_path,
gallery,
title,
className,
children,
}: Props) {
const [open, setOpen] = useState(false);
return (
@@ -44,6 +64,8 @@ export default function FilePreviewLink({ name, url, media_type, size, title, cl
url={url}
media_type={media_type}
size={size}
full_path={full_path}
gallery={gallery}
onClose={() => setOpen(false)}
/>
) : null}
+49 -14
View File
@@ -1,3 +1,4 @@
import { useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Link from "@moduletrace/twui/layout/Link";
@@ -5,15 +6,31 @@ import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Download, SquareArrowOutUpRight } from "lucide-react";
import useGalleryKeys from "@/src/hooks/use-gallery-keys";
import usePreloadImages from "@/src/hooks/use-preload-images";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import type { FilePreviewItem } from "@/src/types";
import filePreviewKind from "@/src/utils/file-preview-kind";
import formatBytes from "@/src/utils/format-bytes";
import galleryIndex from "@/src/utils/gallery-index";
import FilePreviewBody from "./file-preview-body";
import FilePreviewDetails from "./file-preview-details";
import FilePreviewStepper from "./file-preview-stepper";
type Props = {
name: string;
url: string;
media_type?: string | null;
size?: number;
/**
* Where the file sits (`bots/3/reports/q3.md`), shown beside its size.
*/
full_path?: string;
/**
* The images it was opened among (a folder's, a message's). When the
* file is one of them, Previous and Next (and the arrow keys) step
* through them without closing the preview.
*/
gallery?: FilePreviewItem[];
onClose: () => void;
};
@@ -21,19 +38,32 @@ const ActionClassName =
"shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline";
/**
* A file over the page: markdown rendered, a CSV as a table, an image,
* A file over the page, its full path beside its size: markdown rendered, a CSV as a table, an image,
* PDF, audio or video in place, other text as code, with ways to download
* it or open it in a new tab. A file it can't show offers those only.
* Opened from a gallery, it steps through its images; each one opens fresh
* (fitted, scrolled to the top), and its neighbours load ahead.
*/
export default function FilePreviewModal({
name,
url,
media_type,
size,
onClose,
}: Props) {
export default function FilePreviewModal({ gallery, onClose, ...opened }: Props) {
const [index, set_index] = useState(() => galleryIndex({ gallery, url: opened.url }));
const stepping = Boolean(gallery && index >= 0 && gallery.length > 1);
const shown: FilePreviewItem = (stepping && gallery?.[index]) || opened;
const { name, url, media_type, size, full_path } = shown;
const kind = filePreviewKind({ name, media_type });
const base_name = name.split("/").pop() || name;
const count = gallery?.length || 0;
const step = ({ by }: { by: number }) =>
set_index((current) => Math.min(count - 1, Math.max(0, current + by)));
useTopModalEscape({ onClose });
useGalleryKeys({
enabled: stepping,
onPrevious: () => step({ by: -1 }),
onNext: () => step({ by: 1 }),
});
usePreloadImages({
urls: stepping ? [gallery?.[index + 1]?.url || "", gallery?.[index - 1]?.url || ""] : [],
});
return (
<Modal
@@ -51,12 +81,16 @@ export default function FilePreviewModal({
>
{base_name}
</H2>
{size ? (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{formatBytes({ bytes: size })}
</Span>
) : null}
<FilePreviewDetails size={size} full_path={full_path} />
</Stack>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
@@ -78,6 +112,7 @@ export default function FilePreviewModal({
</Link>
</Row>
<FilePreviewBody
key={url}
kind={kind}
name={base_name}
url={url}
@@ -0,0 +1,41 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { ChevronLeft, ChevronRight } from "lucide-react";
import RowIconButton from "./row-icon-button";
type Props = {
/**
* The shown file's place in the gallery, from 0.
*/
index: number;
count: number;
onPrevious: () => void;
onNext: () => void;
};
/**
* Previous and Next through a preview's gallery (the images of a folder or
* a message), with where the shown one stands: "3 of 12". The arrow keys
* do the same.
*/
export default function FilePreviewStepper({ index, count, onPrevious, onNext }: Props) {
return (
<Row className="shrink-0 gap-0! flex-nowrap items-center">
<RowIconButton
icon={ChevronLeft}
title="Previous image (Left arrow)"
disabled={index <= 0}
onClick={onPrevious}
/>
<Span className="min-w-16 text-center text-[13px] leading-[18px] tabular-nums text-ink-secondary">
{`${index + 1} of ${count}`}
</Span>
<RowIconButton
icon={ChevronRight}
title="Next image (Right arrow)"
disabled={index >= count - 1}
onClick={onNext}
/>
</Row>
);
}
@@ -2,9 +2,12 @@ import { expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import { AppData } from "@/src/data/app-data";
import FilePreviewBody from "./file-preview-body";
import FilePreviewDetails from "./file-preview-details";
import FilePreviewLink from "./file-preview-link";
import FilePreviewMarkdown from "./file-preview-markdown";
import FilePreviewTable from "./file-preview-table";
import FilePreviewStepper from "./file-preview-stepper";
import FolderPreviewLink from "./folder-preview-link";
test("a markdown file renders as a document, raw HTML left out", () => {
const html = renderToString(
@@ -51,3 +54,45 @@ test("a file link stays a real link to the bytes until clicked", () => {
expect(html).toContain('href="/media/9"');
expect(html).toContain("Preview report.md");
});
test("an image opens in the viewer, with its zoom and fit controls", () => {
const html = renderToString(<FilePreviewBody kind="image" name="page.png" url="/media/5" />);
expect(html).toContain('src="/media/5"');
expect(html).toContain("Zoom in (+)");
expect(html).toContain("Zoom out (-)");
expect(html).toContain("Fit width");
expect(html).toContain("Actual size");
});
test("a folder link stays a real link to the files browser until clicked", () => {
const html = renderToString(
<FolderPreviewLink spec={{ volume: "bots", owner_id: 3 }} path="reports" href="/admin/files?volume=bots&owner=3&path=reports" title="Open reports">
reports
</FolderPreviewLink>,
);
expect(html).toContain('href="/admin/files?volume=bots&amp;owner=3&amp;path=reports"');
expect(html).toContain("Open reports");
});
test("a gallery's stepper says where the image stands and stops at the ends", () => {
const first = renderToString(<FilePreviewStepper index={0} count={3} onPrevious={() => {}} onNext={() => {}} />);
const last = renderToString(<FilePreviewStepper index={2} count={3} onPrevious={() => {}} onNext={() => {}} />);
expect(first).toContain("1 of 3");
expect(first).toContain("Previous image");
expect(first).toContain("Next image");
expect(last).toContain("3 of 3");
expect((first.match(/disabled=""/g) || []).length).toBe(1);
expect((last.match(/disabled=""/g) || []).length).toBe(1);
});
test("the preview names the file's full path beside its size", () => {
const html = renderToString(<FilePreviewDetails size={2048} full_path="bots/3/reports/q3.md" />);
expect(html).toContain("2.0 KB");
expect(html).toContain("bots/3/reports/q3.md");
expect(renderToString(<FilePreviewDetails full_path="media/1/a.pdf" />)).toContain("media/1/a.pdf");
expect(renderToString(<FilePreviewDetails />)).toBe("");
});
@@ -0,0 +1,45 @@
import { useState, type ReactNode } from "react";
import Link from "@moduletrace/twui/layout/Link";
import isPlainClick from "@/src/utils/is-plain-click";
import type { StorageSpec } from "@/src/utils/storage-volumes";
import FolderPreviewModal from "./folder-preview-modal";
type Props = {
spec: StorageSpec;
path: string;
/**
* The folder in the files browser, where a modified click goes.
*/
href: string;
title?: string;
className?: string;
children: ReactNode;
};
/**
* A link to a folder that opens it over the page (`FolderPreviewModal`) on
* a plain click. It stays a real link to the files browser, so a middle
* click or Ctrl/Cmd click still opens the folder there in a new tab.
*/
export default function FolderPreviewLink({ spec, path, href, title, className, children }: Props) {
const [open, setOpen] = useState(false);
return (
<>
<Link
href={href}
title={title}
onClick={(event) => {
if (!isPlainClick({ event })) return;
event.preventDefault();
setOpen(true);
}}
className={className}
>
{children}
</Link>
{open ? <FolderPreviewModal spec={spec} path={path} onClose={() => setOpen(false)} /> : null}
</>
);
}
@@ -0,0 +1,107 @@
import { useMemo, useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Link from "@moduletrace/twui/layout/Link";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { SquareArrowOutUpRight } from "lucide-react";
import useDebouncedValue from "@/src/hooks/use-debounced-value";
import useStorageFolder from "@/src/hooks/use-storage-folder";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
import FilesBreadcrumbRow from "./files-breadcrumb-row";
import FilesSearchInput from "./files-search-input";
import StorageEntryRow from "./storage-entry-row";
type Props = {
spec: StorageSpec;
/**
* The folder it opens on, inside the volume (empty at the top).
*/
path: string;
onClose: () => void;
};
/**
* A folder over the page, as the files browser shows it: its entries,
* the trail back up and a search by name. A folder inside opens in place,
* a file opens in its own preview over this one (an image stepping
* through the folder's other images), and "Open in Files" goes
* to the same folder in the files browser. The listing loads through the
* files browser's API, so the same access rules hold.
*/
export default function FolderPreviewModal({ spec, path: start_path, onClose }: Props) {
const [path, set_path] = useState(start_path);
const [search, set_search] = useState("");
const query = useDebouncedValue({ value: search.trim() });
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
);
useTopModalEscape({ onClose });
const openFolder = (next_path: string) => {
set_path(next_path);
set_search("");
};
return (
<Modal
open
setOpen={(next_open) => {
if (!next_open) onClose();
}}
className="max-w-3xl! w-[95vw] h-[85vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Stack className="min-w-0 grow gap-0! items-start">
<H2
title={path || name}
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
>
{name}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{folderSummary({ folder })}
</Span>
</Stack>
<Link
href={storageSpecHref({ spec, path })}
title="Open this folder in Files"
className="shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline"
>
<SquareArrowOutUpRight size={16} aria-hidden />
<Span className="hidden sm:inline">Open in Files</Span>
</Link>
</Row>
<Stack className="w-full gap-0! items-stretch px-5">
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
<FilesSearchInput value={search} onChange={set_search} />
</Stack>
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
{folder?.entries.length ? (
folder.entries.map((entry) => (
<StorageEntryRow
key={entry.path}
entry={entry}
selected={entry.kind == "folder" && entry.path == path}
gallery={gallery}
onOpenFolder={openFolder}
/>
))
) : (
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
{emptyFolderText({ folder, search, loading, error })}
</Span>
)}
</Stack>
</Modal>
);
}
@@ -0,0 +1,44 @@
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import type { LucideIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
export type ImageViewerTool = {
id: string;
icon: LucideIcon;
/**
* What it does, with its key, for the tooltip and screen readers.
*/
title: string;
/**
* Shown beside the icon on wider screens; icon only without one.
*/
label?: string;
pressed?: boolean;
disabled?: boolean;
onClick: () => void;
};
/**
* One control on the image preview's toolbar: a zoom, or a preset that
* shows as pressed while it is the one in use.
*/
export default function ImageViewerToolButton({ icon: Icon, title, label, pressed, disabled, onClick }: ImageViewerTool) {
return (
<Button
type="button"
variant="ghost"
color="gray"
size="small"
title={title}
aria-label={title}
aria-pressed={pressed}
disabled={disabled}
onClick={onClick}
className={twMerge("gap-1.5! text-ink-secondary hover:text-ink", pressed && "bg-ink/5 text-ink")}
>
<Icon size={16} aria-hidden />
{label ? <Span className="hidden sm:inline text-[13px] leading-[18px]">{label}</Span> : null}
</Button>
);
}
@@ -0,0 +1,89 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { MoveHorizontal, Scan, Shrink, ZoomIn, ZoomOut } from "lucide-react";
import {
ImageViewerMaxScale,
ImageViewerMinScale,
type ImageViewerMode,
} from "@/src/dict/image-viewer-dict";
import ImageViewerToolButton, { type ImageViewerTool } from "./image-viewer-tool-button";
type Props = {
mode: ImageViewerMode;
scale: number;
natural: { width: number; height: number } | null;
onZoom: (direction: "in" | "out") => void;
onChoose: (mode: Exclude<ImageViewerMode, "custom">) => void;
};
/**
* The image preview's controls: zoom out and in around the zoom level,
* the presets (whole, the frame's width, actual size), and the picture's
* own size in pixels.
*/
export default function ImageViewerToolbar({ mode, scale, natural, onZoom, onChoose }: Props) {
const loaded = Boolean(natural);
const zoom_out: ImageViewerTool = {
id: "out",
icon: ZoomOut,
title: "Zoom out (-)",
disabled: !loaded || scale <= ImageViewerMinScale,
onClick: () => onZoom("out"),
};
const zoom_in: ImageViewerTool = {
id: "in",
icon: ZoomIn,
title: "Zoom in (+)",
disabled: !loaded || scale >= ImageViewerMaxScale,
onClick: () => onZoom("in"),
};
const preset_tools: ImageViewerTool[] = [
{
id: "fit",
icon: Shrink,
title: "Show the whole image (0)",
label: "Fit",
pressed: mode == "fit",
disabled: !loaded,
onClick: () => onChoose("fit"),
},
{
id: "width",
icon: MoveHorizontal,
title: "Fit the width and scroll down (W)",
label: "Fit width",
pressed: mode == "width",
disabled: !loaded,
onClick: () => onChoose("width"),
},
{
id: "actual",
icon: Scan,
title: "Actual size, one image pixel per screen pixel (1)",
label: "Actual size",
pressed: mode == "actual",
disabled: !loaded,
onClick: () => onChoose("actual"),
},
];
return (
<Row className="w-full gap-1! flex-wrap items-center px-3 py-1.5 border-0 border-b border-solid border-hairline bg-paper">
<ImageViewerToolButton {...zoom_out} />
<Span className="min-w-12 text-center text-[13px] leading-[18px] font-bold tabular-nums text-ink">
{loaded ? `${Math.round(scale * 100)}%` : "..."}
</Span>
<ImageViewerToolButton {...zoom_in} />
<Span className="inline-block mx-1 h-5 w-px bg-hairline" aria-hidden />
{preset_tools.map((tool) => (
<ImageViewerToolButton key={tool.id} {...tool} />
))}
{natural ? (
<Span className="ml-auto pl-2 text-[12px] leading-4 tabular-nums text-ink-secondary">
{`${natural.width} x ${natural.height} px`}
<Span className="hidden md:inline">{" · Ctrl + scroll to zoom, drag to move"}</Span>
</Span>
) : null}
</Row>
);
}
+67
View File
@@ -0,0 +1,67 @@
import Img from "@moduletrace/twui/layout/Img";
import Stack from "@moduletrace/twui/layout/Stack";
import type { RefObject } from "react";
import { twMerge } from "tailwind-merge";
import useImageViewer from "@/src/hooks/use-image-viewer";
import useImageViewerGestures from "@/src/hooks/use-image-viewer-gestures";
import FilePreviewNotice from "./file-preview-notice";
import ImageViewerToolbar from "./image-viewer-toolbar";
type Props = {
url: string;
name: string;
};
/**
* An image in the file preview, to inspect rather than glance at: zoom
* (buttons, keys, Ctrl/Cmd + wheel or a pinch at the pointer), fit whole,
* fit the width (a full-page screenshot opens that way and scrolls down),
* actual size, double click to zoom into a spot, drag to move around.
* The picture is sized with its `width` attribute, so no style is set,
* and centred with auto margins, which (unlike flex centring) never push
* the top of a picture taller than the frame out of reach.
*/
export default function ImageViewer({ url, name }: Props) {
const viewer = useImageViewer();
const { dragging, pointerHandlers } = useImageViewerGestures(viewer);
const width = viewer.natural ? Math.max(1, Math.floor(viewer.natural.width * viewer.scale)) : undefined;
return (
<Stack className="grow min-h-0 w-full gap-0! items-stretch">
<ImageViewerToolbar
mode={viewer.mode}
scale={viewer.scale}
natural={viewer.natural}
onZoom={(direction) => viewer.zoom({ direction })}
onChoose={(mode) => viewer.choose({ mode })}
/>
<Stack
componentRef={viewer.container_ref as RefObject<HTMLDivElement>}
{...pointerHandlers}
onDoubleClick={(event) => viewer.toggle({ point: { x: event.clientX, y: event.clientY } })}
className={twMerge(
"relative grow min-h-0 w-full gap-0! items-stretch overflow-auto overscroll-contain bg-sunken select-none",
viewer.scale < 1 && "cursor-zoom-in",
dragging && "cursor-grabbing",
)}
>
<Stack className="shrink-0 w-max min-w-full min-h-full gap-0! items-start p-4">
<Img
ref={viewer.image_ref}
src={url}
alt={name}
loading="eager"
draggable={false}
width={width}
onLoad={viewer.onImageLoad}
imgErrComp={<FilePreviewNotice message="This image couldn't be loaded. Download it to open it." />}
className={twMerge(
"block shrink-0 m-auto h-auto object-contain",
width ? "max-w-none max-h-none" : "max-w-full max-h-full",
)}
/>
</Stack>
</Stack>
</Stack>
);
}
@@ -4,7 +4,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import { FolderOpen } from "lucide-react";
import type { MediaType, StorageEntry } from "@/src/types";
import type { FilePreviewItem, MediaType, StorageEntry } from "@/src/types";
import formatBytes from "@/src/utils/format-bytes";
import relativeTime from "@/src/utils/relative-time";
import AttachmentIcon from "@/src/pages/admin/bots/[bot_id]/(partials)/attachment-icon";
@@ -13,6 +13,10 @@ import FilePreviewLink from "@/src/components/general/file-preview-link";
type Props = {
entry: StorageEntry;
selected?: boolean;
/**
* The folder's images, so an image's preview steps through the rest.
*/
gallery?: FilePreviewItem[];
onOpenFolder: (path: string) => void;
};
@@ -21,7 +25,7 @@ type Props = {
* file preview (its own media record when it is one of the bot's files, else
* the browser's streaming route).
*/
export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props) {
export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder }: Props) {
const is_folder = entry.kind == "folder";
return (
@@ -57,6 +61,8 @@ export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props
url={entry.url || ""}
media_type={entry.media_type}
size={entry.size}
full_path={entry.full_path}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
{entry.name}
+2
View File
@@ -43,6 +43,8 @@ export default function TaskFileRow({ file, onDetach, busy }: Props) {
name={file.name || `File ${file.media_id}`}
url={`/media/${file.media_id}`}
media_type={file.media_type}
size={file.size}
full_path={file.full_path}
className="grow min-w-0 text-[13px] leading-[18px] text-ink truncate hover:underline"
>
{file.name || `File ${file.media_id}`}
+98 -6
View File
@@ -110,7 +110,7 @@ export const AppData = {
* `computer/` (the release workflow builds that tag), and bump
* `ComputerWorkspaceLayout` too when existing computers must move to it.
*/
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.2.0",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.3.0",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
@@ -174,9 +174,12 @@ export const AppData = {
* (`migrateComputerLayout`), keeping its workspace and browser profile.
* `cobble-computer` moved every computer off the AIO sandbox;
* `cobble-computer-accounts` gave worker bots their own accounts (the
* container gets `NET_ADMIN` to keep them off its services).
* container gets `NET_ADMIN` to keep them off its services);
* `cobble-computer-homes` has workers work in their own home
* (`/home/cb-<bot>/workspace`, a link the agent keeps to their folder),
* which an older agent would make a folder that isn't kept.
*/
ComputerWorkspaceLayout: "cobble-computer-accounts",
ComputerWorkspaceLayout: "cobble-computer-homes",
ComputerUserUid: 1000,
ComputerUserGid: 1000,
/**
@@ -299,6 +302,17 @@ export const AppData = {
ChatroomMaxCoordinatorTurns: 6,
ChatroomMaxDepth: 2,
ChatroomMaxOpenPerBot: 3,
/**
* How far back a run is shown the requests its bot made to the crew
* from the same place (`grabCrewRequests`), and how many at most.
*/
CrewRequestsRecentMs: 6 * 60 * 60 * 1000,
CrewRequestsListed: 8,
/**
* Files a room's answer may have copied over to the bot that asked
* (`shareRoomFiles`); refs past it are left as written.
*/
ChatroomSharedFilesMax: 30,
ChatroomCoordinatorMaxToolSteps: 6,
ChatroomRailLimit: 8,
/**
@@ -373,10 +387,10 @@ export const AppData = {
HarnessAutoMinScore: 12,
HarnessAutoMinSizeB: 20,
/**
* Models tried per harness call before giving up (pinned plus
* automatic fallbacks).
* Models tried per harness call before giving up (the pick, its
* fallback models, then automatic picks).
*/
HarnessMaxCandidates: 5,
HarnessMaxCandidates: 6,
HarnessRequestTimeoutMs: 3 * 60 * 1000,
/**
* One tool call gives up after this long, whatever the tool is (bot
@@ -391,6 +405,22 @@ export const AppData = {
*/
HarnessCooldownMs: 60 * 1000,
HarnessMaxCooldownMs: 24 * 60 * 60 * 1000,
/**
* How long a model (or a provider, for a bad key or no credits) that
* failed is passed over before it is tried again, provider's
* `Retry-After` included. The install may save its own
* (`harness_model_rest_seconds`, Settings > General), read through
* `grabModelRestMs`. One failure once benched the pinned model for an
* hour and every reply ran on a weak free model meanwhile.
*/
HarnessModelRestMs: 2 * 60 * 1000,
HarnessModelRestMinSeconds: 10,
HarnessModelRestMaxSeconds: 60 * 60,
/**
* Models the text harness tries, in order, after its pick and before
* the automatic free picks (`fallback_model_ids` in its options).
*/
HarnessTextFallbackModelsMax: 3,
/**
* Model turns in one text run before it must stop and report. The
* install may save its own limit (the `harness_max_tool_steps` setting,
@@ -398,10 +428,63 @@ export const AppData = {
* through `grabHarnessMaxToolSteps`.
*/
HarnessMaxToolSteps: 200,
/**
* Model turns a routine run or a hook call may take: nobody watches
* them, and one routine run once spent 39M tokens checking a site. The
* install may save its own (`unattended_max_tool_steps`), read through
* `grabUnattendedMaxToolSteps`; a brief's own `max_steps` can only
* lower it.
*/
UnattendedMaxToolSteps: 40,
/**
* Prompt tokens one run may spend in all (every turn resends the
* prompt): past it the next turn is the wrap up. A safety net under the
* step limit, for runs whose turns are large. The install may save its
* own (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
*/
RunMaxPromptTokens: 4_000_000,
/**
* The working context: how many tokens (estimated) of system prompt,
* tool definitions and transcript a run sends per turn before old tool
* output is trimmed, whatever the model's window. Every turn resends
* all of it, so a run that only trims at a 1M window pays for its whole
* history on every step. The install may save its own
* (`harness_context_budget_tokens`), read through
* `grabContextBudgetTokens`.
*/
HarnessContextBudgetTokens: 80_000,
/**
* The least a saved working context may be: below it a run would trim
* the output it is reading right now.
*/
HarnessContextBudgetMinTokens: 20_000,
HarnessContextBudgetMaxTokens: 1_000_000,
/**
* Run token budgets the settings page accepts.
*/
RunMaxPromptTokensMin: 100_000,
RunMaxPromptTokensMax: 100_000_000,
/**
* Longest tool result handed back to the model.
*/
HarnessToolResultMaxChars: 20000,
/**
* Longest result of a browser tool (`browser_*`, the computer's or a
* user's own browser): page snapshots and `browser_evaluate` output
* were the heaviest results a run kept resending.
*/
HarnessBrowserResultMaxChars: 12000,
/**
* Extension tools (MCP servers, a user's browsers) are listed by name
* and loaded with `load_tools` only when their definitions together
* pass this many characters; below it they're simply all given.
*/
HarnessDeferToolsMinChars: 6000,
/**
* How much of a deferred tool's description its line in the list
* shows.
*/
HarnessDeferredToolLineChars: 140,
/**
* Images one tool call may hand back (the rest are dropped), and how
* many of the newest tool images stay in a run's transcript: every
@@ -410,6 +493,15 @@ export const AppData = {
*/
HarnessToolMaxImages: 4,
HarnessToolImagesKept: 3,
/**
* Steps left when a run is told, once, that it's nearly out, so it
* saves its report before the wrap up ends it (two runs in a row once
* ran out with the report unwritten). Only in runs of at least
* `HarnessStepsLowMinSteps` steps, where the warning still leaves room
* to act on it.
*/
HarnessStepsLowWarning: 5,
HarnessStepsLowMinSteps: 15,
/**
* Upload cap for audio sent to transcription.
*/
+3 -3
View File
@@ -20,7 +20,7 @@ A chat reply is short: about eight tool steps. Anything long, multi-step or on a
- Hand work that fits a worker to them with \`delegate_task\`. It runs in the background and is reported back here when they finish or fail.
- Say that work is under way, not done, and say who is on it.
If the request is clear, start. Ask one short question only when missing information would change the outcome; otherwise pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
If the request is clear, start. When missing information would change the outcome, or a choice is the user's to make, ask with \`ask_user\` (a card of multiple-choice questions they answer in a click) instead of picking for them. For details that don't change the outcome, pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
Permission to draft is not permission to send, permission to analyze is not permission to modify, and permission to configure a bot is not permission to grant unrelated access.
@@ -85,7 +85,7 @@ Done means the operation ran, the tool confirmed it, the artifact exists, the cr
## 7. Approval, safety, privacy
Ask before anything destructive, hard to undo, externally visible or beyond the task's data scope: sending email or messages, publishing, payments, deleting consequential data, changing a live site, sharing private data outside. Say what you'll do and what it costs, in one line.
Ask before anything destructive, hard to undo, externally visible or beyond the task's data scope: sending email or messages, publishing, payments, deleting consequential data, changing a live site, sharing private data outside. Use \`ask_user\` for it, saying what you'll do and what it costs in one line.
A clear request can authorize a well-defined action, so don't ask twice unless the scope or the risk changes. Negative instructions are binding: never bundle a declined action into an approved one, and never re-offer what the user just turned down.
@@ -105,7 +105,7 @@ Interrupt only for a decision that changes the outcome, information that can't b
Write in short, plain sentences: no filler, no hype, no emoji. Lead with the outcome, the blocker or the decision needed. Be candid about limits, use relative times, and don't dress up uncertainty as confidence. For ongoing work report needs-you, then in progress, then done, then blocked or failed, and omit empty groups.
Lead: after each report, suggest one concrete next step or ask the one question that settles the direction. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
Lead: after each report, offer the next step with \`ask_user\`: the concrete next steps, or the one question that settles the direction, as options with your suggestion first. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
**Be proactive in execution, rigorous in verification, economical with the user's attention, and completely honest about what happened.**
`;
+63 -3
View File
@@ -4,6 +4,11 @@ import {
chatReplyNote,
ComputerFilesNote,
coordinatorReplyNote,
crewRequestsNote,
openRunsNote,
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
TasksNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -53,9 +58,10 @@ describe("harness prompts", () => {
dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }),
});
expect(note).toContain("[folder:computer:8:bots/3/users/7/seo/coderank/raw]");
expect(note).toContain("/home/gem/workspace/bots/3/users/7");
expect(note).toContain("/home/gem/workspace/workspaces/2");
expect(note).toContain("[folder:computer:8:home/cb-3/workspace/users/7/seo/coderank/raw]");
expect(note).toContain("starts in /home/cb-3/workspace/users/7 (also ~ and $HOME)");
expect(note).toContain("/home/cb-3/workspace/workspaces/2: shared");
expect(note).toContain("only /home/cb-3/workspace and the browser's logins survive it (the rest of your account's home, /home/cb-3, doesn't)");
expect(note).toContain("request_install");
expect(note).not.toContain("sudo apt-get");
});
@@ -67,6 +73,8 @@ describe("harness prompts", () => {
});
expect(note).toContain("sudo apt-get");
expect(note).toContain("/home/gem/workspace/bots/1/users/7");
expect(note).toContain("only /home/gem/workspace and the browser's logins survive it. ");
expect(note).not.toContain("request_install");
});
@@ -75,3 +83,55 @@ describe("harness prompts", () => {
expect(TasksNote).not.toContain("[bot:");
});
});
describe("openRunsNote", () => {
test("names each open run and whether it's queued or under way", () => {
const note = openRunsNote({
runs: [
{ id: 12, title: "Art directions", status: "processing" },
{ id: 13, title: null, status: "pending" },
],
});
expect(note).toContain(`Run #12 "Art directions": under way`);
expect(note).toContain(`Run #13 "Task": queued`);
expect(note).toContain("don't start another run");
expect(note).not.toContain("\u2014");
});
test("is empty with no open runs", () => {
expect(openRunsNote({ runs: [] })).toBe("");
});
});
describe("task incoming notes", () => {
test("leave separate requests to the chat and never offer send_message", () => {
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
expect(note).not.toContain("send_message");
expect(note).not.toContain("\u2014");
}
expect(TaskIncomingNote).toContain("leave it to the chat");
expect(TaskRedraftNote).toContain("leave it to the chat");
});
});
describe("crewRequestsNote", () => {
test("lists open and answered requests, and where an answer's files are", () => {
const note = crewRequestsNote({
requests: [
{ id: 5, title: "Cite sheet", status: "open" },
{ id: 4, title: "Research files", status: "answered" },
],
});
expect(note).toContain(`[room:5] "Cite sheet": still open`);
expect(note).toContain(`[room:4] "Research files": answered`);
expect(note).toContain("crew/room-4/");
expect(note).toContain("Don't ask for these again");
});
test("is empty with no requests", () => {
expect(crewRequestsNote({ requests: [] })).toBe("");
});
});
+104 -9
View File
@@ -1,7 +1,8 @@
import { AppData } from "@/src/data/app-data";
import botRef from "@/src/utils/bot-ref";
import folderRef from "@/src/utils/folder-ref";
import { computerWorkspaceRelative, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkerAccount from "@/src/utils/computer-worker-account";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
/**
* Prompts the helper harnesses send. The text model gets their output in
@@ -32,6 +33,12 @@ export const ToolImagesNote = `The images the tool calls above returned (screens
*/
export const DroppedToolImageNote = `[An earlier image from a tool, no longer shown to save space. Take it again if you still need it.]`;
/**
* Stands in for a page snapshot a newer snapshot of the same browser
* replaced (`supersedeToolOutputs`): the page it showed is gone.
*/
export const SupersededSnapshotNote = `[An older page snapshot, replaced by the newer one further down. Take another if you need the page again.]`;
/**
* The folder-ref example a note shows, always over the running bot's own
* folder: a literal owner id in the prompt teaches the bot to name another
@@ -54,15 +61,18 @@ You are chatting with the user. Answer their latest messages directly and briefl
- When a message mixes both, answer the quick parts in this reply and start a task for the rest.
- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.
- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
- Never claim you did something you didn't do.
- When the user overrules how you read a rule or a brief, go with their reading: say once what you'd watch for if it matters, then work their way. Don't restate the objection in later replies.
- An answer from the crew, a finished run or any other app message is information, not the user's go-ahead. If you told the user you'd wait for their choice, say in a line or two what arrived and keep waiting. If it adds nothing new for them, keep your answer to a line. And never read the user's silence as an answer: they may simply not have seen your question yet.
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with start_task (with separate when another run of yours is open on that computer) and say it's queued.
- The user can mention a bot as [bot:ID] and a workspace as [workspace:ID]; a [Mentions: ...] line after their message says who and what those are. Write the same refs when you name them back.
- Documents, images and reports you make are files: save them with write_file, make_pdf or generate_image, and send one to the user with it ("attach"). When you name a file, write its [file:ID] ref, e.g. [file:12], so the user can open it. When you name a folder, write a folder ref instead, e.g. ${ownFolderRef({ bot_id })}: that opens the folder in Files and downloads nothing.
## Keep the work moving
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step: one concrete suggestion or a short question about what to do next, e.g. "Want me to draft the reply as well?" or "Should I check the other two accounts the same way?". Base it on what the user is trying to get done, not on generic options. Offer one step, not a menu. Skip it when you've already asked the user something in this reply, when you've just started a task (its result will suggest what's next), or when the user is clearly wrapping up.`;
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.`;
/**
* Added to every run, chat replies and tasks alike: where its files live,
@@ -109,14 +119,16 @@ export const ComputerFilesNote = ({
can_import?: boolean;
}) => `# Files on the computer
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~), and a path outside your folders is refused.
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~ and $HOME), and a path outside your folders is refused.
- ${dirs.cwd}: this user's work. Everything for them goes here.
- ${dirs.bot_dir}: only what is the same for every user you work for (other users' folders in it are not yours).${
dirs.shared_dir ? `\n- ${dirs.shared_dir}: shared with every bot in this workspace.` : ""
}
- The browser downloads to its own folder: move what you download into your folder straight away.
- A computer can be restarted or rebuilt at any time, and only ${AppData.ComputerWorkspaceDir} and the browser's logins survive it. ${
- A computer can be restarted or rebuilt at any time, and only ${dirs.run_as ? dirs.bot_dir : AppData.ComputerWorkspaceDir} and the browser's logins survive it${
dirs.run_as ? ` (the rest of your account's home, ${computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).home}, doesn't)` : ""
}. ${
dirs.run_as
? `You work as your own account, without sudo, and the browser can't open your folders' files (file: URLs): to look at a page you made, serve its folder on localhost (python3 -m http.server --bind 127.0.0.1, in the background) and open that. Python and Node packages you install yourself (pip install --user, npm install -g) go to ~/.local in this user's folder, so they stay. A system package (apt) needs the coordinator: in a task, ask with request_install, then end your run saying you're waiting for it; you're woken with the answer. System packages may be gone after a rebuild: check for one first (command -v) and ask again when it's missing.`
: `Programs you install (sudo apt-get install -y, pip, npm -g) may be gone afterwards: check for one first (command -v) and install it again when it's missing.`
@@ -124,7 +136,7 @@ You work only in your own folders on the computer, never elsewhere in it: every
What you make there (downloads, screenshots, a crawl, raw evidence, logs) is kept with the computer, not in your files, and it is not searchable.
- The user can open any of it: name a folder on the computer as a folder ref, its path from the computer's workspace (${AppData.ComputerWorkspaceDir}), e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${computerWorkspaceRelative({ absolute: dirs.cwd })}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
- The user can open any of it: name a folder on the computer as a folder ref with its full path as you see it, e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${dirs.cwd}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
${
can_import
? `- import_file copies a file or a folder off the computer into your own files, in one go, and the copy is searchable straight away. Import the finished work (the report, the spreadsheet, the final document), attach it when it is what they asked for, and name it with its [file:ID] ref.\n- The raw evidence can stay on the computer: import it only when the user needs it kept, or when the computer may be rebuilt.\n`
@@ -188,7 +200,13 @@ Anything you read or write goes to your model provider, so secret values (passwo
*/
export const QuestionsNote = `# Asking before acting
Be sure of what the user wants before you act on it. When a request could mean more than one thing, when a choice is theirs to make, or before work that is hard to undo, costly or seen by others, and you can't tell what they'd pick, ask with ask_user: a card of multiple-choice questions (one pick or several, with "Other" for their own words) they answer in a click. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or small choices any sensible answer settles: just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
Be proactive about moving the work forward, but let the user steer it: whenever what happens next is theirs to decide, check with ask_user instead of deciding for them or asking in your text. ask_user puts a card of multiple-choice questions in the chat (one pick or several, with "Other" for their own words) that they answer in a click, so asking costs them little. Use it:
- when a request could mean more than one thing, or leaves out something that changes the result (which target, which items, how far to go, what form it takes);
- before work that is hard to undo, costly or seen by others;
- to offer the next step once you've answered or reported: the concrete next steps as options.
When you're unsure whether to ask, ask. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or details that don't change the result (a file name, wording they can tweak later): just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
/**
* Added to every run: bots can show a concept as a visual the chat
@@ -203,7 +221,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: the next piece of work, which bot would take it, or a question that settles the direction. 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. 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,
@@ -238,7 +256,54 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
*/
export const TaskRunNote = `# Working on a task
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when you have it (the concrete next steps as options, your suggestion first), otherwise as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
/**
* Told to a task run with what the user wrote in its conversation since
* it was queued (`taskIncoming`). The chat replies answer the user there;
* the run only decides whether it changes the work. A task has no
* send_message.
*/
export const TaskIncomingNote = `The user wrote in this conversation while you were working on this task (below). Your chat replies answer them there; here, only decide whether it changes this task, from what it means, not how it's worded:
- If it changes, corrects or adds to this task, work from it from here on. Redo what it overrules instead of reporting a result it overruled, and say in your report what you changed because of it.
- If it's about something else, leave it to the chat and carry on with this task.`;
/**
* Told to a task run when the user wrote past a report that hadn't gone
* out yet.
*/
export const TaskRedraftNote = `Your report above was not sent: the user wrote in this conversation before it went out (below).
- If it changes, corrects or adds to this task, do the work it calls for (don't repeat tool calls you have already made), then write the report again.
- If it's about something else, leave it to the chat and send the report as it was.`;
/**
* Told to a task run with what the user wrote by its wrap up, when it has
* no steps left to act on it.
*/
export const TaskWrapUpIncomingNote = `The user wrote in this conversation before you finished (below), and this run has no steps left to act on it. If it changes, corrects or adds to this task, say in your report what it changes and what is still to redo because of it; never report a result it overruled as it stands.`;
/**
* Added to a chat reply while the bot has runs open in this conversation
* that take in what the user writes here: a correction to one reaches it,
* so the reply never starts another run for it. Empty with none.
*/
export const openRunsNote = ({
runs,
}: {
runs: { id: number; title?: string | null; status: string }[];
}) => {
if (!runs.length) return "";
const lines = runs.map(
(run) => `- Run #${run.id} "${run.title || "Task"}": ${run.status == "pending" ? "queued" : "under way"}`,
);
return `# Your runs open in this conversation
${lines.join("\n")}
Until it reports, a run is shown what the user writes here, between its steps. When the user corrects, changes or adds to the work of one of these runs, it takes that in: tell them so in a line, and don't start another run for it or redo that work in this reply (start_task with separate is only for different work). If they want a run to start over from scratch, they can Stop it and ask again.`;
};
/**
* Added to every run: the shared to-do list, and how a bot keeps it
@@ -386,11 +451,41 @@ Each turn, decide and act with one of your tools:
? 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.
- 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.
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.`;
/**
* Lists a task run's open and recent requests to the crew (`grabCrewRequests`):
* the run sees only its brief, so it otherwise asks again for what's on
* its way or already came back. Empty with none.
*/
export const crewRequestsNote = ({
requests,
}: {
requests: { id?: number | ""; title?: string | null; status?: string | null }[];
}) => {
if (!requests.length) return "";
const lines = requests.map(
(room) =>
`- [room:${room.id}] "${room.title || "Request"}": ${
room.status == "open"
? "still open; the answer comes to the conversation, not to this run"
: room.status == "answered"
? `answered; files it sent are in your files under crew/room-${room.id}/, or in the workspace's`
: room.status
}`,
);
return `# Your recent requests to the crew
${lines.join("\n")}
Don't ask for these again. For what an answered one sent, look in your files and the workspace's (list_files) before asking.`;
};
/**
* Added to a worker's prompt while it can ask the crew through the
* coordinator (`ask_crew`).
+4
View File
@@ -173,6 +173,10 @@ export const BotMessageReactions = [
title: "Like",
value: "👍",
},
{
title: "Dislike",
value: "👎",
},
{
title: "Love",
value: "❤️",
+1
View File
@@ -121,6 +121,7 @@ export const JobStepToolLabels: Record<string, string> = {
update_memory: "Updating memory",
update_instructions: "Updating instructions",
load_skill: "Reading a skill",
load_tools: "Loading tools",
send_message: "Sending a message",
create_graphic: "Drawing a graphic",
update_graphic: "Redrawing a graphic",
+24
View File
@@ -107,6 +107,30 @@ export function harnessFallbackTitle({ harness }: { harness: HarnessKind }) {
*/
export const HarnessMaxToolStepsSettingKey = "harness_max_tool_steps";
/**
* The `app_settings` key holding the install's limit on model turns in a
* routine run or a hook call. Unset means `AppData.UnattendedMaxToolSteps`.
*/
export const UnattendedMaxToolStepsSettingKey = "unattended_max_tool_steps";
/**
* The `app_settings` key holding the prompt tokens one run may spend.
* Unset means `AppData.RunMaxPromptTokens`.
*/
export const RunMaxPromptTokensSettingKey = "run_max_prompt_tokens";
/**
* The `app_settings` key holding the working context a run keeps, in
* tokens. Unset means `AppData.HarnessContextBudgetTokens`.
*/
export const HarnessContextBudgetSettingKey = "harness_context_budget_tokens";
/**
* The `app_settings` key holding how long a failed model rests, in
* seconds. Unset means `AppData.HarnessModelRestMs`.
*/
export const HarnessModelRestSettingKey = "harness_model_rest_seconds";
/**
* Vendors preferred for automatic picks, best first. Free models from any
* other vendor come after these, and only if they look competent.
+28
View File
@@ -0,0 +1,28 @@
/**
* How the image preview sizes a picture: `fit` shows it whole, `width`
* fills the frame's width and scrolls down (a full-page screenshot),
* `actual` is one image pixel per screen pixel, `custom` is wherever the
* user zoomed to. The fits never blow a small picture up past its own size.
*/
export const ImageViewerModes = ["fit", "width", "actual", "custom"] as const;
export type ImageViewerMode = (typeof ImageViewerModes)[number];
/**
* The stops the zoom buttons (and `+`/`-`) step through, from
* `ImageViewerMinScale` to `ImageViewerMaxScale`.
*/
export const ImageViewerZoomSteps = [
0.05, 0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 0.9, 1, 1.25, 1.5, 2, 3, 4, 6, 8, 12, 16,
] as const;
export const ImageViewerMinScale = 0.05;
export const ImageViewerMaxScale = 16;
/**
* A picture this much taller (relative to its width) than the frame opens
* at the frame's width rather than whole: shrunk to fit, a page screenshot
* is a thin unreadable strip.
*/
export const ImageViewerTallRatio = 2;
@@ -1,9 +1,18 @@
import { AppData } from "@/src/data/app-data";
import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
import { HarnessMaxToolStepsSettingKey } from "@/src/dict/harness-dict";
import {
HarnessContextBudgetSettingKey,
HarnessMaxToolStepsSettingKey,
HarnessModelRestSettingKey,
RunMaxPromptTokensSettingKey,
UnattendedMaxToolStepsSettingKey,
} from "@/src/dict/harness-dict";
import type { RunLimitsOverview } from "@/src/types";
import readStepLimit from "@/src/utils/read-step-limit";
import grabAppSetting from "./grab-app-setting";
export type { RunLimitsOverview };
/**
* Model turns a task run may take: the install's own limit
* (`harness_max_tool_steps`, Settings > General), else
@@ -32,44 +41,93 @@ export async function grabReplyMaxToolSteps() {
}
/**
* Both limits with their defaults, for the settings page.
* Model turns a routine run or a hook call may take, which nobody
* watches: the install's own limit (`unattended_max_tool_steps`), else
* `AppData.UnattendedMaxToolSteps`.
*/
export async function grabUnattendedMaxToolSteps() {
return readStepLimit({
saved: await grabAppSetting({ key: UnattendedMaxToolStepsSettingKey }),
fallback: AppData.UnattendedMaxToolSteps,
max: AppData.BotStepLimitMax,
});
}
/**
* Prompt tokens one run may spend before it must wrap up: the install's
* own budget (`run_max_prompt_tokens`), else `AppData.RunMaxPromptTokens`.
*/
export async function grabRunMaxPromptTokens() {
return readStepLimit({
saved: await grabAppSetting({ key: RunMaxPromptTokensSettingKey }),
fallback: AppData.RunMaxPromptTokens,
min: AppData.RunMaxPromptTokensMin,
max: AppData.RunMaxPromptTokensMax,
});
}
/**
* The working context a run keeps per turn, in estimated tokens: the
* install's own (`harness_context_budget_tokens`), else
* `AppData.HarnessContextBudgetTokens`.
*/
export async function grabContextBudgetTokens() {
return readStepLimit({
saved: await grabAppSetting({ key: HarnessContextBudgetSettingKey }),
fallback: AppData.HarnessContextBudgetTokens,
min: AppData.HarnessContextBudgetMinTokens,
max: AppData.HarnessContextBudgetMaxTokens,
});
}
/**
* How long a model that failed is passed over, in seconds: the install's
* own (`harness_model_rest_seconds`), else `AppData.HarnessModelRestMs`.
*/
export async function grabModelRestSeconds() {
return readStepLimit({
saved: await grabAppSetting({ key: HarnessModelRestSettingKey }),
fallback: AppData.HarnessModelRestMs / 1000,
min: AppData.HarnessModelRestMinSeconds,
max: AppData.HarnessModelRestMaxSeconds,
});
}
/**
* Every run limit with its default, for the settings page.
*/
export default async function grabRunLimitsOverview() {
const [task_steps, reply_steps] = await Promise.all([
grabHarnessMaxToolSteps(),
grabReplyMaxToolSteps(),
]);
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds] =
await Promise.all([
grabHarnessMaxToolSteps(),
grabReplyMaxToolSteps(),
grabUnattendedMaxToolSteps(),
grabRunMaxPromptTokens(),
grabContextBudgetTokens(),
grabModelRestSeconds(),
]);
const overview: RunLimitsOverview = {
task_steps,
reply_steps,
unattended_steps,
run_tokens,
context_tokens,
model_rest_seconds,
task_default: AppData.HarnessMaxToolSteps,
reply_default: AppData.BotReplyMaxToolSteps,
unattended_default: AppData.UnattendedMaxToolSteps,
run_tokens_default: AppData.RunMaxPromptTokens,
context_tokens_default: AppData.HarnessContextBudgetTokens,
max: AppData.BotStepLimitMax,
run_tokens_min: AppData.RunMaxPromptTokensMin,
run_tokens_max: AppData.RunMaxPromptTokensMax,
context_tokens_min: AppData.HarnessContextBudgetMinTokens,
context_tokens_max: AppData.HarnessContextBudgetMaxTokens,
model_rest_default: AppData.HarnessModelRestMs / 1000,
model_rest_min: AppData.HarnessModelRestMinSeconds,
model_rest_max: AppData.HarnessModelRestMaxSeconds,
};
return overview;
}
export type RunLimitsOverview = {
/**
* The limit a task run uses right now.
*/
task_steps: number;
/**
* The limit a chat reply uses right now.
*/
reply_steps: number;
/**
* What a task run uses when the install saved no limit.
*/
task_default: number;
/**
* What a chat reply uses when the install saved no limit.
*/
reply_default: number;
/**
* The most the settings page accepts.
*/
max: number;
};
@@ -4,6 +4,7 @@ import grabMediaURL from "../../media/grab-media-url";
import grabBotFileQuotaBytes, { grabBotFileQuotaMb } from "./grab-bot-file-quota-bytes";
import grabStorageUsage from "./grab-storage-usage";
import listBotFiles from "./list-bot-files";
import botFileFullPath from "@/src/utils/bot-file-full-path";
type Params = {
bot_id: number;
@@ -55,6 +56,7 @@ export default async function grabConversationFiles({
owner_id: Number(file.owner_id) || 0,
created_at: Number(file.created_at) || 0,
url: media_url || "",
full_path: botFileFullPath({ scope: file.scope, owner_id: file.owner_id, path: file.path }),
};
}),
folders: [],
@@ -0,0 +1,54 @@
import type { LastConversation } from "@/src/types";
import conversationHref from "@/src/utils/conversation-href";
import readLastVisitedBot from "@/src/utils/read-last-visited-bot";
import grabUserConversation, { type UserConversation } from "./grab-user-conversation";
type Params = {
user_id: number | string;
req: Request;
};
/**
* The conversation the last-visited cookie names, for the rail's way back
* on settings and the rail pages, only while the user still reaches it
* (`grabUserConversation`, the conversation pages' own check). A workspace
* conversation the user lost falls back to the bot's own chat; with
* neither, null and the rail shows no way back.
*/
export default async function grabLastConversation({
user_id,
req,
}: Params): Promise<LastConversation | null> {
const visited = readLastVisitedBot({ req });
if (!visited) return null;
const reach = ({ workspace_id }: { workspace_id: number | null }) =>
grabUserConversation({ user_id, bot_id: visited.bot_id, workspace_id }).catch(
() => null,
);
const conversation: UserConversation | null =
(visited.workspace_id ? await reach({ workspace_id: visited.workspace_id }) : null) ||
(await reach({ workspace_id: null }));
if (!conversation) return null;
const { bot, workspace } = conversation;
return {
href: conversationHref({ bot_id: bot.id, workspace_id: workspace?.id }),
bot: {
id: bot.id,
name: bot.name || `Bot ${bot.id}`,
kind: bot.kind || null,
color: bot.color || null,
stone: bot.stone || null,
hue: bot.hue || null,
image_media_id: bot.image_media_id || null,
},
workspace: workspace?.id
? { id: workspace.id, name: workspace.name || `Workspace ${workspace.id}` }
: null,
};
}
@@ -17,6 +17,7 @@ import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
import onChatroomJobEnded from "../chatrooms/on-chatroom-job-ended";
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
import settleInstallRequest from "../install-requests/settle-install-request";
import jobTrackerTaskId from "./job-tracker-task-id";
type Params = {
job_id: number | string;
@@ -42,6 +43,10 @@ type Params = {
* Every tool call the run made, kept on the message.
*/
tool_log?: HarnessToolUse[];
/**
* The tracker tasks the run worked on, linked under the message.
*/
task_ids?: number[];
};
/**
@@ -63,6 +68,7 @@ export default async function completeBotJob({
silent,
attachments,
tool_log,
task_ids = [],
}: Params) {
const job = await grabLockedBotJob({ job_id, worker });
@@ -86,6 +92,11 @@ export default async function completeBotJob({
values: [result, now, job.id],
});
/**
* A handed-over task's run is about that task, whatever its tools did.
*/
const message_task_ids = [jobTrackerTaskId({ job }), ...task_ids];
if (job.task_id) {
await BunSQLite.sql({
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
@@ -103,6 +114,7 @@ export default async function completeBotJob({
needs_you,
media_ids: attachments,
tool_log,
task_ids: message_task_ids,
});
if (job.id && inserted?.id) {
@@ -152,7 +164,7 @@ export default async function completeBotJob({
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id }))
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id, conversations_only: true }))
? await restoreRunningFace({ bot_id: job.bot_id, user_id })
: await setBotFace({
bot_id: job.bot_id,
@@ -164,7 +176,7 @@ export default async function completeBotJob({
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
const relay = silent ? null : await relayJobToRequester({ job, text: result });
const relay = silent ? null : await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await onChatroomJobEnded({ job, text: silent ? "" : result });
@@ -6,15 +6,21 @@ type Params = {
* Only jobs in this user's conversations.
*/
user_id: number | string;
/**
* Leave out jobs in chatrooms, which never show on the bot's face.
*/
conversations_only?: boolean;
};
/**
* How many of a bot's jobs for one user are still pending or processing.
*/
export default async function countOpenBotJobs({ bot_id, user_id }: Params) {
export default async function countOpenBotJobs({ bot_id, user_id, conversations_only }: Params) {
const res = await BunSQLite.sql<{ open: number }>({
sql: `SELECT COUNT(*) AS open FROM bots_queue WHERE bot_id = ? AND status IN ('pending', 'processing')
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL)`,
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL${
conversations_only ? " AND chatroom_id IS NULL" : ""
})`,
values: [bot_id, user_id],
});
@@ -0,0 +1,25 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import openSessionRunsSql from "./open-session-runs-sql";
type Params = {
bot_id: number | string;
session_id: number | string;
};
export type OpenSessionRun = {
id: number;
title: string | null;
status: "pending" | "processing";
};
/**
* The bot's runs in this session that are still to report and take in
* what the user writes here (`openSessionRunsSql`), for the reply to know
* a correction reaches them.
*/
export default async function grabOpenSessionRuns({ bot_id, session_id }: Params): Promise<OpenSessionRun[]> {
const { sql, values } = openSessionRunsSql({ bot_id, session_id });
const res = await BunSQLite.sql<OpenSessionRun>({ sql, values });
return res.payload || [];
}
@@ -15,7 +15,8 @@ type Params = {
* The face a bot should show one user while other jobs for them are
* still running: thinking while a reply runs (it's short, and its chat
* needs the row), else working on a task (in its workspace, if it runs in
* one). Null when none is running.
* one). Null when none is running. Work in a chatroom or a hook's thread
* never counts: it shows there, never on the face.
*/
export default async function grabRunningBotJobFace({
bot_id,
@@ -26,7 +27,7 @@ export default async function grabRunningBotJobFace({
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
LEFT JOIN workspaces w ON w.id = q.workspace_id
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL)
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL AND chatroom_id IS NULL)
ORDER BY q.id`,
values: [bot_id, user_id],
})
@@ -0,0 +1,16 @@
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import parseJobJson from "@/src/bots-queue/parse-job-json";
type Params = {
job: Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "params">;
};
/**
* The tracker task a job was started for (`params.tracker_task_id`, set
* by `handOverTask`), or null.
*/
export default function jobTrackerTaskId({ job }: Params): number | null {
const id = Number(parseJobJson({ text: job.params })?.tracker_task_id || 0);
return Number.isInteger(id) && id > 0 ? id : null;
}
@@ -1,5 +1,4 @@
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import { AppData } from "@/src/data/app-data";
import { logError } from "@/src/functions/backend/logger";
import grabBotById from "../bots/grab-bot-by-id";
@@ -7,6 +6,7 @@ import addTaskNote from "../tasks/add-task-note";
import grabTaskRow, { isOpenTask } from "../tasks/grab-task-scope";
import updateTask from "../tasks/update-task";
import grabJobUserId from "./grab-job-user-id";
import jobTrackerTaskId from "./job-tracker-task-id";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -25,7 +25,7 @@ type Params = {
* the job's wrap-up.
*/
export default async function noteTrackerTask({ job, failure }: Params) {
const tracker_task_id = Number(parseJobJson({ text: job.params })?.tracker_task_id || 0);
const tracker_task_id = jobTrackerTaskId({ job });
if (!tracker_task_id || !job.bot_id) return;
@@ -12,6 +12,7 @@ import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
import onChatroomJobEnded from "../chatrooms/on-chatroom-job-ended";
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
import settleInstallRequest from "../install-requests/settle-install-request";
import jobTrackerTaskId from "./job-tracker-task-id";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -40,6 +41,11 @@ export default async function notifyBotJobFailed({
values: [Date.now(), job.id],
});
/**
* A handed-over task's failed run links to that task.
*/
const task_ids = [jobTrackerTaskId({ job })];
const message = await insertBotMessage({
bot_id: job.bot_id,
session_id: await jobSessionId({ job }),
@@ -55,6 +61,7 @@ export default async function notifyBotJobFailed({
.filter(Boolean)
.join(" "),
needs_you: true,
task_ids,
});
const user_id = await grabJobUserId({ job });
@@ -84,6 +91,7 @@ export default async function notifyBotJobFailed({
job,
text: failure_message || job.last_error || "",
failed: true,
task_ids,
});
await onChatroomJobEnded({ job, text: failure_message || job.last_error || "", failed: true });
@@ -0,0 +1,35 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import openSessionRunsSql from "./open-session-runs-sql";
/**
* The runs a reply is told hear the user: the bot's open task runs in the
* session, never a routine's or a hook call's. Run against real SQLite.
*/
const db = new Database(":memory:");
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, kind TEXT, status TEXT, title TEXT, params TEXT)`);
db.run(`INSERT INTO bots_queue VALUES
(1, 10, 1, 'task', 'processing', 'Art directions', NULL),
(2, 10, 1, 'task', 'pending', 'Logo', '{"max_steps":20}'),
(3, 10, 1, 'reply', 'processing', NULL, NULL),
(4, 10, 1, 'task', 'completed', 'Old run', NULL),
(5, 10, 1, 'task', 'processing', 'Routine', '{"schedule_id":3}'),
(6, 10, 1, 'task', 'pending', 'Hook call', '{"hook_id":4}'),
(7, 11, 1, 'task', 'processing', 'Another bot', NULL),
(8, 10, 2, 'task', 'processing', 'Another session', NULL)`);
function runs() {
const { sql, values } = openSessionRunsSql({ bot_id: 10, session_id: 1 });
return db.query(sql).all(...values) as { id: number; title: string; status: string }[];
}
describe("openSessionRunsSql", () => {
test("lists the bot's open task runs in the session, oldest first", () => {
expect(runs()).toEqual([
{ id: 1, title: "Art directions", status: "processing" },
{ id: 2, title: "Logo", status: "pending" },
]);
});
});
@@ -0,0 +1,24 @@
import type { SqlCondition } from "@/src/utils/crew-access/types";
type Params = {
bot_id: number | string;
session_id: number | string;
};
/**
* The SQL for the bot's runs in a session that are queued or working and
* take in what the user writes there: routine runs and hook calls act on
* their own, so they're left out. Oldest first; selects `id`, `title` and
* `status`.
*/
export default function openSessionRunsSql({ bot_id, session_id }: Params): SqlCondition {
return {
sql: `SELECT id, title, status FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
AND json_extract(COALESCE(params, '{}'), '$.schedule_id') IS NULL
AND json_extract(COALESCE(params, '{}'), '$.hook_id') IS NULL
ORDER BY id ASC`,
values: [Number(bot_id), Number(session_id)],
};
}
@@ -14,6 +14,10 @@ type Params = {
*/
text: string;
failed?: boolean;
/**
* The tracker tasks the job worked on, linked under the report.
*/
task_ids?: (number | null)[];
};
/**
@@ -24,7 +28,7 @@ type Params = {
* failed. Returns the message for the live push, or null when nobody
* handed the job over.
*/
export default async function relayJobToRequester({ job, text, failed }: Params) {
export default async function relayJobToRequester({ job, text, failed, task_ids }: Params) {
if (!job.requested_by_bot_id || !job.bot_id || job.requested_by_bot_id == job.bot_id) {
return null;
}
@@ -70,6 +74,7 @@ export default async function relayJobToRequester({ job, text, failed }: Params)
? `${name} couldn't finish **${title}**. ${text}`.trim()
: `${name} finished **${title}**. Their report:\n\n${text}`,
needs_you: failed,
task_ids,
});
return { bot_id: requester.id, message };
@@ -1,10 +1,11 @@
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { BotMessageWithAttachments } from "@/src/types";
import type { BotMessageWithAttachments, MessageTask } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
import grabMessageUsage from "../usage/grab-message-usage";
import grabMessagesMedia from "./grab-messages-media";
import grabMessagesReactions from "./grab-messages-reactions";
import grabMessagesReplies from "./grab-messages-replies";
import grabMessagesTasks from "./grab-messages-tasks";
import mediaToAttachment, { grabAttachmentFileIds } from "./media-to-attachment";
type Params = {
@@ -33,7 +34,8 @@ type Params = {
/**
* The latest messages of a session (or the latest before `before_id`),
* oldest first, with their attachments,
* what each replies to, and (when `user_id` is given) its reactions.
* what each replies to, and (when `user_id` is given) its reactions and
* the tracker tasks it's about that the user reaches.
*/
export default async function grabBotMessages({
session_id,
@@ -77,13 +79,16 @@ export default async function grabBotMessages({
const messages = res.payload || [];
const message_ids = messages.map((message) => Number(message.id));
const [media, replies, reactions, usage] = await Promise.all([
const [media, replies, reactions, usage, tasks] = await Promise.all([
grabMessagesMedia({ message_ids }),
grabMessagesReplies({ message_ids }),
user_id
? grabMessagesReactions({ message_ids, user_id })
: Promise.resolve(new Map()),
grabMessageUsage({ message_ids }),
user_id
? grabMessagesTasks({ messages, user_id })
: Promise.resolve(new Map<number, MessageTask[]>()),
]);
/**
@@ -100,6 +105,7 @@ export default async function grabBotMessages({
const reply_to = replies.get(id);
const spent = usage.get(id);
const linked = tasks.get(id);
return {
...message,
@@ -116,6 +122,7 @@ export default async function grabBotMessages({
...(reply_to ? { reply_to } : {}),
...(user_id ? { reactions: reactions.get(id) || [] } : {}),
...(spent ? { usage: spent } : {}),
...(linked ? { tasks: linked } : {}),
};
});
}
@@ -0,0 +1,53 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { MessageTask } from "@/src/types";
import messageTaskIds from "@/src/utils/message-task-ids";
import taskScopesSql from "@/src/utils/task-access/task-scopes-sql";
import grabCrewRole from "../access/grab-crew-role";
type Params = {
messages: Pick<BUN_SQLITE_COBBLE_BOT_MESSAGES, "id" | "task_ids">[];
/**
* Whose conversation it is: only the tasks they reach are named.
*/
user_id: number | string;
};
/**
* The tracker tasks each message is about (`task_ids`), by message id,
* each with its title and status for its chip. A task the user doesn't
* reach, or that was deleted, is left out, so a chip never names a task
* the user couldn't open. Messages naming none are not in the map.
*/
export default async function grabMessagesTasks({ messages, user_id }: Params) {
const by_message = new Map<number, MessageTask[]>();
const wanted = new Map<number, number[]>();
for (const message of messages) {
const ids = messageTaskIds({ task_ids: message.task_ids });
if (message.id && ids.length) wanted.set(Number(message.id), ids);
}
const all_ids = [...new Set([...wanted.values()].flat())];
if (!all_ids.length) return by_message;
const access = taskScopesSql({ role: await grabCrewRole({ user_id }), user_id });
const res = await BunSQLite.sql<MessageTask>({
sql: `SELECT t.id, t.title, t.status FROM tasks t
WHERE t.id IN (${all_ids.map(() => "?").join(", ")}) AND ${access.sql}`,
values: [...all_ids, ...access.values],
});
const tasks = new Map((res.payload || []).map((task) => [Number(task.id), task]));
for (const [message_id, ids] of wanted) {
const found = ids.map((id) => tasks.get(id)).filter((task): task is MessageTask => Boolean(task));
if (found.length) by_message.set(message_id, found);
}
return by_message;
}
@@ -4,6 +4,7 @@ import type {
} from "@/db/types/db";
import BunSQLite from "@moduletrace/bun-sqlite";
import type { HarnessToolUse } from "@/src/harness/types";
import messageTaskIds from "@/src/utils/message-task-ids";
type Params = {
bot_id: number;
@@ -28,6 +29,11 @@ type Params = {
* message in later turns (`botMessagesToHarness`).
*/
tool_log?: HarnessToolUse[];
/**
* The tracker tasks the message is about (the run worked on them),
* shown as chips under it.
*/
task_ids?: (number | string | null | undefined)[];
/**
* Opens a session the conversation moved into
* (`carryOverBotSession`): the session it carries on from.
@@ -48,12 +54,15 @@ export default async function insertBotMessage({
interim,
media_ids = [],
tool_log,
task_ids,
carried_from_session_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
const now = Date.now();
const needs_you_flag = needs_you ? 1 : 0;
const interim_flag = interim ? 1 : 0;
const tool_log_json = tool_log ? JSON.stringify(tool_log) : undefined;
const tidy_task_ids = messageTaskIds({ task_ids });
const task_ids_json = tidy_task_ids.length ? JSON.stringify(tidy_task_ids) : undefined;
const res = await BunSQLite.insert<
BUN_SQLITE_COBBLE_BOT_MESSAGES,
@@ -70,6 +79,7 @@ export default async function insertBotMessage({
needs_you: needs_you_flag,
interim: interim_flag,
tool_log: tool_log_json,
task_ids: task_ids_json,
carried_from_session_id,
},
],
@@ -112,6 +122,7 @@ export default async function insertBotMessage({
needs_you: needs_you_flag,
interim: interim_flag,
tool_log: tool_log_json,
task_ids: task_ids_json,
carried_from_session_id,
created_at: now,
updated_at: now,
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_FILES, BUN_SQLITE_COBBLE_MEDIA } from "@/db/types/db";
import grabMediaURL from "@/src/functions/backend/media/grab-media-url";
import mediaFilePlace from "@/src/functions/backend/media/media-file-place";
import type { BotMessageAttachment, MediaType } from "@/src/types";
type Params = {
@@ -14,7 +15,8 @@ type Params = {
/**
* A `media` row as a chat attachment: its original name (`title`), type
* and the private URLs it's served at. A file saved in a bot's folder
* and the private URLs it's served at, with where it sits on the data
* volume and its size for the preview. A file saved in a bot's folder
* carries its `file_id`, so the chip can open the file's page.
*/
export default function mediaToAttachment({ media, file_id }: Params): BotMessageAttachment {
@@ -27,6 +29,7 @@ export default function mediaToAttachment({ media, file_id }: Params): BotMessag
url: media_url || "",
thumbnail_url: media_thumbnail_url,
file_id: file_id || undefined,
...mediaFilePlace({ write_path: media.media_write_path }),
};
}
@@ -0,0 +1,32 @@
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { MessageTask } from "@/src/types";
import grabMessagesTasks from "./grab-messages-tasks";
type Params<T extends BUN_SQLITE_COBBLE_BOT_MESSAGES> = {
messages: T[];
/**
* Whose conversation they're in.
*/
user_id: number | string;
};
/**
* The messages with the tracker tasks they're about (`tasks`), for a live
* push: a pushed bot message must carry its task chips like a loaded one
* (`grabBotMessages`), or they show only after a reload. Messages naming
* no task are left as they are.
*/
export default async function withMessageTasks<T extends BUN_SQLITE_COBBLE_BOT_MESSAGES>({
messages,
user_id,
}: Params<T>): Promise<(T & { tasks?: MessageTask[] })[]> {
if (!messages.some((message) => message.task_ids)) return messages;
const tasks = await grabMessagesTasks({ messages, user_id });
return messages.map((message) => {
const found = tasks.get(Number(message.id));
return found ? { ...message, tasks: found } : message;
});
}
@@ -0,0 +1,48 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
type Params = {
user_id: number | string;
/**
* The bot that asked.
*/
bot_id: number | string;
/**
* The place it asked from: rooms are kept per place, like
* conversations.
*/
workspace_id?: number | string | null;
/**
* Rooms closed before this aren't listed (open ones always are).
* Defaults to `AppData.CrewRequestsRecentMs` ago.
*/
since?: number;
};
export type CrewRequest = Pick<BUN_SQLITE_COBBLE_CHATROOMS, "id" | "title" | "status" | "closed_at">;
/**
* A bot's requests to the crew from one place, for one user: every open
* room and the ones closed lately, newest first. A task run gets only its
* brief, so without these it didn't know a request was already open or
* answered, and asked the crew for the same files three times.
*/
export default async function grabCrewRequests({ user_id, bot_id, workspace_id, since }: Params): Promise<CrewRequest[]> {
const res = await BunSQLite.sql<CrewRequest>({
sql: `SELECT id, title, status, closed_at FROM chatrooms
WHERE user_id = ? AND requester_bot_id = ? AND workspace_id IS ?
AND (status = 'open' OR closed_at >= ?)
ORDER BY id DESC
LIMIT ?`,
values: [
Number(user_id),
Number(bot_id),
workspace_id ? Number(workspace_id) : null,
since ?? Date.now() - AppData.CrewRequestsRecentMs,
AppData.CrewRequestsListed,
],
});
return res.payload || [];
}
@@ -0,0 +1,122 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS, BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { logError } from "@/src/functions/backend/logger";
import fileRefIds from "@/src/utils/file-ref-ids";
import rewriteFileRefs from "@/src/utils/rewrite-file-refs";
import type { StorageScope } from "@/src/utils/storage-access";
import copyBotFile from "../bot-files/copy-bot-file";
import grabBotFile from "../bot-files/grab-bot-file";
import grabRunScopes from "../bot-files/grab-run-scopes";
import grabBotById from "../bots/grab-bot-by-id";
type Params = {
chatroom: Pick<BUN_SQLITE_COBBLE_CHATROOMS, "id" | "user_id" | "workspace_id" | "requester_bot_id">;
/**
* The coordinator's answer, as it would be sent.
*/
answer: string;
};
/**
* Makes the files a room's answer names readable by the bot that asked.
* A bot asked in a room saves to its own folder, which the asker can't
* read, so an answer citing `[file:330]` sent the asker back to the crew
* for the same files twice more. Each cited file the asker doesn't reach
* but a bot in the room does is copied into the asker's own folder under
* `crew/room-<id>/` (the bytes, so the member's folder stays its own), and
* the ref is pointed at the copy. Files the asker already reaches, and
* files no bot in the room reaches, are left as they are. A copy that
* fails keeps the original ref, and the answer still goes out.
*/
export default async function shareRoomFiles({ chatroom, answer }: Params) {
const ids = fileRefIds({ text: answer }).slice(0, AppData.ChatroomSharedFilesMax);
const requester = chatroom.requester_bot_id ? await grabBotById({ bot_id: chatroom.requester_bot_id }) : null;
if (!ids.length || !requester?.id || !chatroom.user_id) return answer;
const place = { user_id: chatroom.user_id, workspace_id: chatroom.workspace_id || null };
const requester_scopes = await grabRunScopes({ bot: requester, ...place });
const own: StorageScope = { scope: "bot", owner_id: Number(requester.id) };
const member_scopes = await grabMemberScopes({ chatroom, requester_id: Number(requester.id), place });
const copies = new Map<number, number>();
for (const file_id of ids) {
if (await grabBotFile({ scopes: requester_scopes, file_id })) continue;
const source = await findReachingScopes({ member_scopes, file_id });
if (!source) continue;
try {
const copy = await copyBotFile({
scopes: [...source.scopes, own],
file_id,
bot_id: requester.id,
scope: own,
path: `crew/room-${chatroom.id}/${source.name}`,
user_id: chatroom.user_id,
});
if (copy?.id) copies.set(file_id, Number(copy.id));
} catch (error: unknown) {
await logError({
title: `Couldn't copy a crew answer's file for the bot that asked`,
error,
user_id: Number(chatroom.user_id),
metadata: { chatroom_id: chatroom.id, file_id, bot_id: requester.id },
});
}
}
return rewriteFileRefs({ text: answer, ids: copies });
}
/**
* The folders each bot asked in the room reaches there, for its user and
* place (never the coordinator's or the asker's own).
*/
async function grabMemberScopes({
chatroom,
requester_id,
place,
}: {
chatroom: Params["chatroom"];
requester_id: number;
place: { user_id: number | string; workspace_id: number | string | null };
}) {
const sessions = (
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_BOT_SESSIONS, "bot_id">>({
sql: `SELECT DISTINCT bot_id FROM bot_sessions WHERE chatroom_id = ? AND bot_id != ?`,
values: [Number(chatroom.id), requester_id],
})
).payload || [];
const scopes: StorageScope[][] = [];
for (const session of sessions) {
const bot = await grabBotById({ bot_id: session.bot_id! });
if (!bot?.id || bot.kind == "coordinator") continue;
scopes.push(await grabRunScopes({ bot, ...place }));
}
return scopes;
}
/**
* The first member's folders that reach a file, with the file's name for
* its copy.
*/
async function findReachingScopes({ member_scopes, file_id }: { member_scopes: StorageScope[][]; file_id: number }) {
for (const scopes of member_scopes) {
const file = await grabBotFile({ scopes, file_id });
if (file?.id) {
return { scopes, name: (file.path || file.name || `file-${file_id}`).split("/").pop() || `file-${file_id}` };
}
}
return null;
}
@@ -0,0 +1,59 @@
import { AppData } from "@/src/data/app-data";
import type { HarnessKind } from "@/src/dict/harness-dict";
import { withHarnessParameters } from "@/src/dict/harness-parameter-dict";
import AppError from "@/src/utils/app-error";
import assertHarnessModel from "./assert-harness-model";
type Params = {
harness: HarnessKind;
/**
* The options the setting row holds now (`{}` for a new row).
*/
existing: Record<string, unknown>;
/**
* The picked model, never also a fallback.
*/
model_id: number | null;
voice?: string;
sees_images?: boolean;
fallback_model_ids?: number[];
params?: Record<string, number | string>;
};
/**
* A harness setting's options as the settings forms save them: what the
* row held beyond the form's own fields, then the voice (speech), whether
* the text model reads images itself, the text harness's fallback models
* (each checked like a pick, on any provider) and the generation settings.
*/
export default async function buildHarnessSettingOptions({
harness,
existing,
model_id,
voice,
sees_images,
fallback_model_ids = [],
params = {},
}: Params) {
const { voice: _voice, sees_images: _sees, fallback_model_ids: _fallbacks, ...options } = existing;
const fallbacks =
harness == "text" ? [...new Set(fallback_model_ids)].filter((id) => id != model_id) : [];
if (fallbacks.length > AppData.HarnessTextFallbackModelsMax) {
throw new AppError(`Pick at most ${AppData.HarnessTextFallbackModelsMax} fallback models.`);
}
for (const id of fallbacks) {
await assertHarnessModel({ harness, model_id: id });
}
return withHarnessParameters({
options: {
...options,
...(voice ? { voice } : {}),
...(harness == "text" && sees_images ? { sees_images: true } : {}),
...(fallbacks.length ? { fallback_model_ids: fallbacks } : {}),
},
params,
});
}
@@ -113,7 +113,7 @@ export default async function attachTaskFile({
const count = (await grabTaskMedia({ task_id: task.id! })).length;
if (count >= AppData.TaskMediaMaxPerTask) {
throw new AppError(`Task #${task.id} already carries ${AppData.TaskMediaMaxPerTask} files. Unlink one first.`);
throw new AppError(`Task #${task.id} already carries ${AppData.TaskMediaMaxPerTask} files. Unlink one first (update_task with unlink_file_ids, or on the task in the app).`);
}
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_TASK_MEDIA, (typeof BunSQLiteTables)[number]>({
@@ -1,5 +1,6 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { TaskFile } from "@/src/types";
import mediaFilePlace from "@/src/functions/backend/media/media-file-place";
type Params = {
task_id: number | string;
@@ -7,13 +8,13 @@ type Params = {
/**
* A task's files with what a row shows: the `media` row's type, mime and
* size, and whether that row is still there (a failed cleanup or a
* size, where the file sits on the data volume, and whether that row is still there (a failed cleanup or a
* deleted file leaves the link behind, listed as missing rather than
* hiding it).
*/
export default async function grabTaskMedia({ task_id }: Params): Promise<TaskFile[]> {
const res = await BunSQLite.sql<TaskFile>({
sql: `SELECT tm.*, m.media_type, m.mime_type, m.title AS media_title
const res = await BunSQLite.sql<TaskFile & { media_write_path?: string | null }>({
sql: `SELECT tm.*, m.media_type, m.mime_type, m.title AS media_title, m.media_write_path
FROM task_media tm
LEFT JOIN media m ON m.id = tm.media_id
WHERE tm.task_id = ?
@@ -21,9 +22,10 @@ export default async function grabTaskMedia({ task_id }: Params): Promise<TaskFi
values: [Number(task_id)],
});
return (res.payload || []).map((file) => ({
return (res.payload || []).map(({ media_write_path, ...file }) => ({
...file,
name: file.name || file.media_title || `File ${file.media_id}`,
missing: !file.media_type,
...mediaFilePlace({ write_path: media_write_path }),
}));
}
@@ -46,11 +46,21 @@ 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.
*/
start?: boolean;
};
export type HandedOverTask = {
task: BUN_SQLITE_COBBLE_TASKS;
job_id: number | string;
/**
* The job doing the work; null when it wasn't started.
*/
job_id: number | string | null;
bot_name: string;
workspace_id: number | null;
/**
@@ -65,7 +75,8 @@ export type HandedOverTask = {
* 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.
* 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.
*/
export default async function handOverTask({
user_id,
@@ -76,6 +87,7 @@ export default async function handOverTask({
handed_by,
requested_by_bot_id,
requested_by_session_id,
start = true,
}: Params): Promise<HandedOverTask> {
const task = await grabTaskRow({ task_id });
@@ -107,7 +119,7 @@ export default async function handOverTask({
const conversation = await grabUserConversation({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const title = (task.title || "Task").slice(0, 80);
const open = await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title });
const open = start ? await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title }) : null;
if (open) {
throw new AppError(
@@ -130,28 +142,31 @@ export default async function handOverTask({
.filter(Boolean)
.join("\n\n");
const job_id = await enqueueBotJob({
user_id,
bot_id: bot.id,
session_id: Number(session.id),
title,
instructions: brief,
params: { tracker_task_id: Number(task.id) },
computer_id: computers[0]?.id || undefined,
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
});
const job_id = start
? await enqueueBotJob({
user_id,
bot_id: bot.id,
session_id: Number(session.id),
title,
instructions: brief,
params: { tracker_task_id: Number(task.id) },
computer_id: computers[0]?.id || undefined,
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
})
: null;
const status = start ? "doing" : "todo";
await updateTask({
user_id,
task_id: task.id!,
status: "doing",
status,
updated_by_bot_id: requested_by_bot_id || null,
});
await addTaskNote({
task_id: task.id!,
text: `${handed_by} handed this over to ${bot.name}.`,
text: `${handed_by} handed this over to ${bot.name}${start ? "" : ", to start when the user says so"}.`,
author: requested_by_bot_id ? "bot" : "user",
bot_id: requested_by_bot_id || null,
});
@@ -162,12 +177,13 @@ export default async function handOverTask({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**`,
text: `${handed_by} handed me task #${task.id}: **${title}**${start ? "" : ". It's on my list; I'll start when you say."}`,
task_ids: [Number(task.id)],
}),
});
return {
task: { ...moved, status: "doing" },
task: { ...moved, status },
job_id,
bot_name: conversation.bot.name || bot.name || "The bot",
workspace_id: run_workspace_id,
@@ -23,6 +23,7 @@ type CallRow = {
model_slug: string | null;
model_name: string | null;
prompt_tokens: number | null;
cached_tokens: number | null;
completion_tokens: number | null;
cost: number | null;
settings: string | null;
@@ -53,7 +54,7 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
await BunSQLite.sql<CallRow>({
sql: `SELECT t.id, t.created_at, t.harness, t.provider_id, t.provider_name,
p.kind AS provider_kind, t.model_slug, m.name AS model_name,
t.prompt_tokens, t.completion_tokens, t.cost, t.settings, t.job_id
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.cost, t.settings, t.job_id
FROM token_usages t
LEFT JOIN harness_providers p ON p.id = t.provider_id
LEFT JOIN harness_models m ON m.id = t.model_id
@@ -73,6 +74,7 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
model_slug: row.model_slug || null,
model_name: row.model_name || null,
prompt_tokens: Number(row.prompt_tokens) || 0,
cached_tokens: Number(row.cached_tokens) || 0,
completion_tokens: Number(row.completion_tokens) || 0,
cost: Number.isFinite(Number(row.cost)) && row.cost !== null ? Number(row.cost) : null,
settings: parseCallSettings({ json: row.settings }),
@@ -9,10 +9,19 @@ type Params = {
message_ids: number[];
};
/**
* A text call that a model answered in place of one ahead of it: one
* failed during the call, or was passed over while resting.
*/
const FellBackSql = `(harness = 'text' AND (
COALESCE(json_array_length(json_extract(settings, '$.fell_back_from')), 0) > 0
OR COALESCE(json_array_length(json_extract(settings, '$.resting')), 0) > 0))`;
/**
* What each of these messages cost, summed over every model call it took
* (chat turns, media readings, image generations). This is what a
* message's token line shows.
* (chat turns, media readings, image generations), and the fallback model
* that answered for it, if one did. This is what a message's token line
* shows.
*/
export default async function grabMessageUsage({ message_ids }: Params) {
const totals = new Map<number, TokenUsageSummary>();
@@ -26,12 +35,16 @@ export default async function grabMessageUsage({ message_ids }: Params) {
completion_tokens: number | null;
cost: number | null;
calls: number;
fallback_model: string | null;
fallback_calls: number | null;
}>({
sql: `SELECT message_id,
SUM(prompt_tokens) AS prompt_tokens,
SUM(completion_tokens) AS completion_tokens,
SUM(cost) AS cost,
COUNT(*) AS calls
COUNT(*) AS calls,
MAX(CASE WHEN ${FellBackSql} THEN model_slug END) AS fallback_model,
SUM(CASE WHEN ${FellBackSql} THEN 1 ELSE 0 END) AS fallback_calls
FROM token_usages
WHERE message_id IN (${ids.map(() => "?").join(", ")})
GROUP BY message_id`,
@@ -49,6 +62,9 @@ export default async function grabMessageUsage({ message_ids }: Params) {
total_tokens: prompt_tokens + completion_tokens,
...(Number.isFinite(cost) && cost > 0 ? { cost } : {}),
calls: Number(row.calls) || 0,
...(row.fallback_model
? { fallback_model: row.fallback_model, fallback_calls: Number(row.fallback_calls) || 1 }
: {}),
});
}
@@ -42,6 +42,7 @@ export default async function grabUsageModels({ start, end, limit }: Params): Pr
harness: string | null;
calls: number | null;
prompt_tokens: number | null;
cached_tokens: number | null;
completion_tokens: number | null;
cost: number | null;
}>({
@@ -52,6 +53,7 @@ export default async function grabUsageModels({ start, end, limit }: Params): Pr
u.harness,
COUNT(*) AS calls,
SUM(u.prompt_tokens) AS prompt_tokens,
SUM(u.cached_tokens) AS cached_tokens,
SUM(u.completion_tokens) AS completion_tokens,
SUM(u.cost) AS cost
FROM token_usages u
@@ -12,6 +12,10 @@ type Params = {
type UsageRow = {
calls: number | null;
prompt_tokens: number | null;
/**
* Left out by the queries that don't sum it.
*/
cached_tokens?: number | null;
completion_tokens: number | null;
cost: number | null;
};
@@ -34,6 +38,7 @@ export default async function grabUsageTotals({ start, end }: Params): Promise<U
sql: `SELECT harness,
COUNT(*) AS calls,
SUM(prompt_tokens) AS prompt_tokens,
SUM(cached_tokens) AS cached_tokens,
SUM(completion_tokens) AS completion_tokens,
SUM(cost) AS cost
FROM token_usages
@@ -59,12 +64,14 @@ export default async function grabUsageTotals({ start, end }: Params): Promise<U
*/
export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): TokenUsageSummary {
let prompt_tokens = 0;
let cached_tokens = 0;
let completion_tokens = 0;
let cost = 0;
let calls = 0;
for (const summary of summaries) {
prompt_tokens += summary.prompt_tokens;
cached_tokens += summary.cached_tokens || 0;
completion_tokens += summary.completion_tokens;
cost += summary.cost || 0;
calls += summary.calls;
@@ -72,6 +79,7 @@ export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): T
return {
prompt_tokens,
...(cached_tokens > 0 ? { cached_tokens } : {}),
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
...(cost > 0 ? { cost } : {}),
@@ -84,11 +92,13 @@ export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): T
*/
export function toSummary({ row }: { row: UsageRow }): TokenUsageSummary {
const prompt_tokens = Number(row.prompt_tokens) || 0;
const cached_tokens = Number(row.cached_tokens) || 0;
const completion_tokens = Number(row.completion_tokens) || 0;
const cost = Number(row.cost);
return {
prompt_tokens,
...(cached_tokens > 0 ? { cached_tokens } : {}),
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
...(Number.isFinite(cost) && cost > 0 ? { cost } : {}),
@@ -0,0 +1,30 @@
import { statSync } from "node:fs";
import mediaFilePath from "@/src/utils/media-file-path";
type Params = {
/**
* A `media` row's `media_write_path`, relative to the data directory.
*/
write_path?: string | null;
};
/**
* Where a media row's file sits on the data volume and how big it is, for
* the file preview. Nothing for a row whose path is unsafe or whose file
* is gone.
*/
export default function mediaFilePlace({ write_path }: Params): { full_path?: string; size?: number } {
const absolute = mediaFilePath({ write_path });
if (!absolute || !write_path) return {};
try {
const stats = statSync(absolute);
if (!stats.isFile()) return {};
return { full_path: write_path.replace(/^\/+/, ""), size: stats.size };
} catch {
return {};
}
}
@@ -8,6 +8,8 @@ import computerFolderLabel from "@/src/utils/computer-folder-label";
import computerPathAllowed from "@/src/utils/computer-path-allowed";
import { isInsideRoot } from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
import type { StorageEntry } from "@/src/types";
import dataVolumePath from "@/src/utils/data-volume-path";
import {
storageSpecHref,
type StorageSpec,
@@ -34,32 +36,7 @@ type Params = {
offset?: number;
};
export type StorageEntry = {
name: string;
/**
* Where it is, inside the volume's root, e.g. `seo/coderank/raw`.
*/
path: string;
kind: "file" | "folder";
size: number;
modified_at: number;
media_type?: string;
/**
* The `bot_files` row, when one of the bot's own files is that path, so
* it keeps opening through its own media record.
*/
file_id?: number;
/**
* Where to open it: a `bot_files` row's media URL, else the volume
* browser's own streaming route.
*/
url?: string;
/**
* What an id folder in a computer's workspace is: the bot's, user's or
* workspace's name.
*/
label?: string;
};
export type { StorageEntry };
/**
* One directory on the data volume, for the files browser: its entries
@@ -150,6 +127,7 @@ export default async function listStorageEntries({
media_type: file?.media_type || undefined,
file_id: file?.id ? Number(file.id) : undefined,
url: media_url || fileUrl({ spec: resolved.spec, path: entry_path }),
full_path: dataVolumePath({ absolute: entry_absolute }),
});
}
@@ -6,20 +6,26 @@ type Params = {
req: Request;
res: Response;
bot_id: number | string;
/**
* The workspace the conversation is in; none for the bot's own chat.
*/
workspace_id?: number | string | null;
};
/**
* The page's response with the last-visited cookie set, so `/admin/bots`
* opens this bot's own chat again next time. Called from the conversation
* opens this bot's own chat again next time and the rail on settings and
* the rail pages leads back to this conversation. Called from the conversation
* pages' `res_transform`, which is why it takes and returns the response.
*/
export default function withLastVisitedBotCookies({ req, res, bot_id }: Params): Response {
export default function withLastVisitedBotCookies({ req, res, bot_id, workspace_id }: Params): Response {
const new_res = res.clone();
setCookies(
new_res,
lastVisitedBotCookies({
bot_id,
workspace_id,
secure: isSecureRequest({ req }),
}),
);
+2 -1
View File
@@ -55,13 +55,14 @@ export default async function speakText({
* completion count to read: the call is recorded as it is, with
* the text's length standing in for what was spoken.
*/
on_success: async ({ candidate, failed }) =>
on_success: async ({ candidate, failed, resting }) =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "speech",
candidate,
usage: { prompt_tokens: text.length, completion_tokens: 0 },
failed,
resting,
settings: {
settings_source: setting.source,
voice: voiceFor(candidate),
+2 -1
View File
@@ -51,12 +51,13 @@ export default async function transcribeAudio({
const { result } = await withCandidates<{ text: string; usage?: HarnessUsage }>({
harness: "transcription",
candidates,
on_success: async ({ candidate, result: transcript, failed }): Promise<void> =>
on_success: async ({ candidate, result: transcript, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "transcription",
candidate,
failed,
resting,
usage: transcript.usage,
}),
}),
+2 -1
View File
@@ -63,12 +63,13 @@ export default async function embedText({
const { result, candidate: answered } = await withCandidates<HarnessEmbedResult>({
harness: "embedding",
candidates,
on_success: async ({ candidate, result: embedded, failed }): Promise<void> =>
on_success: async ({ candidate, result: embedded, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "embedding",
candidate,
failed,
resting,
usage: embedded.usage,
}),
}),
+2 -1
View File
@@ -67,12 +67,13 @@ export default async function generateImage({
const { result } = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
harness: edit?.picked ? "image_edit" : "image",
candidates: ordered.map(({ candidate }) => candidate),
on_success: async ({ candidate, result: made, failed }): Promise<void> =>
on_success: async ({ candidate, result: made, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: harness_of.get(candidate.key) || "image",
candidate,
failed,
resting,
usage: made.usage,
}),
}),
+2 -1
View File
@@ -53,13 +53,14 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
}>({
harness: "vision",
candidates,
on_success: async ({ candidate, result: answer, failed }): Promise<void> =>
on_success: async ({ candidate, result: answer, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "vision",
candidate,
usage: answer.usage,
failed,
resting,
settings: {
settings_source: saved_params.source,
params: flattenSentParams({ params: answer.sent_params }),
@@ -51,6 +51,15 @@ describe("readChatResponse", () => {
});
});
test("reads the cached prompt tokens, in either spelling", () => {
const answer = (usage: Record<string, unknown>) =>
read({ choices: [{ message: { content: "Hi." } }], usage: { prompt_tokens: 100, completion_tokens: 2, ...usage } }).usage;
expect(answer({ prompt_tokens_details: { cached_tokens: 80 } })?.cached_tokens).toBe(80);
expect(answer({ prompt_cache_hit_tokens: 60 })?.cached_tokens).toBe(60);
expect(answer({})?.cached_tokens).toBe(undefined);
});
test("joins content parts and treats empty text as none", () => {
expect(
read({
@@ -77,6 +77,13 @@ export default function readChatResponse({
usage: json.usage
? {
prompt_tokens: json.usage.prompt_tokens,
/**
* OpenAI's and OpenRouter's spelling; some providers
* (DeepSeek's own API) say `prompt_cache_hit_tokens`.
*/
cached_tokens:
Number(json.usage.prompt_tokens_details?.cached_tokens ?? json.usage.prompt_cache_hit_tokens) ||
undefined,
completion_tokens: json.usage.completion_tokens,
cost: json.usage.cost,
}
+15
View File
@@ -0,0 +1,15 @@
import { AppData } from "@/src/data/app-data";
import { grabModelRestSeconds } from "@/src/functions/backend/db/app-settings/grab-run-limits";
/**
* How long a failed model rests, in ms (`grabModelRestSeconds`). Falls
* back to `AppData.HarnessModelRestMs` when the setting can't be read, so
* a harness call never fails over it.
*/
export default async function grabModelRestMs() {
try {
return (await grabModelRestSeconds()) * 1000;
} catch {
return AppData.HarnessModelRestMs;
}
}
@@ -0,0 +1,49 @@
import logEvent from "@/src/functions/backend/logger";
import type HarnessError from "../harness-error";
import type { HarnessCandidate } from "../types";
type Params = {
harness: string;
candidate: HarnessCandidate;
error: HarnessError;
/**
* Unix ms it may be tried again, if it rests.
*/
rests_until?: number;
};
/**
* Writes a model's failure to the activity log: which model, what the
* provider said and how long it rests, so a switch to a fallback can be
* explained afterwards. Once per failure, and a resting model isn't tried,
* so an outage logs at most once per rest per model. Never throws.
*/
export default async function logCandidateFailure({ harness, candidate, error, rests_until }: Params) {
const provider = candidate.provider.name || candidate.provider.kind;
const rest = rests_until
? ` It rests for ${Math.max(1, Math.round((rests_until - Date.now()) / 1000))} seconds.`
: " It isn't benched; the next model takes this call.";
try {
await logEvent({
title: "Model failed",
category: "system",
plain_text: `${candidate.model.slug} on ${provider} failed a ${harness} call (${candidate.source} pick): ${error.message}.${rest}`,
details: [
{ label: "Model", value: candidate.model.slug },
{ label: "Provider", value: provider },
{ label: "Pick", value: candidate.source },
{ label: "Status", value: error.status ?? "none" },
],
metadata: {
harness,
candidate_key: candidate.key,
source: candidate.source,
status: error.status,
retryable: error.retryable,
provider_wide: error.provider_wide,
rests_until,
},
});
} catch {}
}
@@ -10,6 +10,7 @@ import harnessModelRowToCatalog from "@/src/functions/backend/db/harness/harness
import resolveProviderConfig from "@/src/functions/backend/db/harness/resolve-provider-config";
import modelServesHarness from "../catalog/model-serves-harness";
import rankAutoModels from "../catalog/rank-auto-models";
import harnessFallbackModelIds from "@/src/utils/harness-fallback-model-ids";
import HarnessError from "../harness-error";
import type {
HarnessCandidate,
@@ -35,12 +36,14 @@ type CatalogEntry = HarnessCatalogModel & {
};
/**
* The models a harness call tries, in order: the pick (the bot's own, else
* the super admin's), then
* (if it has fallback on, or there is no pick) the automatic free picks.
* Only enabled providers with a usable key count, and only the setting's
* provider when it has one. Empty when nothing is
* set up; throws `unavailable` when the harness is turned off.
* The models a harness call tries, in order: the pick (the workspace's,
* the bot's own, else the super admin's), then the setting's fallback
* models in their order (`fallback_model_ids`, each on its own provider),
* then (if it has fallback on, or there is no pick) the automatic free
* picks. Only enabled providers with a usable key count, and only the
* setting's provider for the pick and automatic picks when it has one.
* Empty when nothing is set up; throws `unavailable` when the harness is
* turned off.
*/
export default async function resolveHarnessCandidates({
harness,
@@ -65,25 +68,32 @@ export default async function resolveHarnessCandidates({
if (!providers.size) return [];
const fallback_ids = harnessFallbackModelIds({ options: setting.options }).filter(
(id) => id != setting.model_id,
);
const picked_ids = [setting.model_id ?? 0, ...fallback_ids];
const rows =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_HARNESS_MODELS>({
sql: `SELECT * FROM harness_models
WHERE available = 1 AND (free = 1 OR id = ?)`,
values: [setting.model_id ?? 0],
WHERE available = 1 AND (free = 1 OR id IN (${picked_ids.map(() => "?").join(", ")}))`,
values: picked_ids,
})
).payload || [];
const entries: CatalogEntry[] = rows.flatMap((row) => {
const toEntry = ({ row, any_provider }: { row: BUN_SQLITE_COBBLE_HARNESS_MODELS; any_provider: boolean }) => {
const provider =
row.provider_id && (!setting.provider_id || row.provider_id == setting.provider_id)
row.provider_id && (any_provider || !setting.provider_id || row.provider_id == setting.provider_id)
? providers.get(row.provider_id)
: undefined;
return provider && row.id
? [{ ...harnessModelRowToCatalog({ row }), row_id: row.id, provider }]
: [];
});
};
const entries: CatalogEntry[] = rows.flatMap((row) => toEntry({ row, any_provider: false }));
const pinned = entries.find(
(entry) =>
@@ -91,8 +101,21 @@ export default async function resolveHarnessCandidates({
modelServesHarness({ model: entry, harness }),
);
/**
* Each fallback model names its own provider, so the setting's
* provider limit doesn't apply to them.
*/
const fallbacks: CatalogEntry[] = fallback_ids.flatMap((id) => {
const row = rows.find((r) => r.id == id);
return row
? toEntry({ row, any_provider: true }).filter((entry) => modelServesHarness({ model: entry, harness }))
: [];
});
const ordered = [
...(pinned ? [{ entry: pinned, source: "pinned" as const }] : []),
...fallbacks.map((entry) => ({ entry, source: "fallback" as const })),
...(!pinned || setting.fallback
? rankAutoModels({ models: entries, harness }).map((entry) => ({
entry,
+113 -2
View File
@@ -4,7 +4,11 @@ import type { HarnessCandidate } from "../types";
import createCooldowns from "./create-cooldowns";
import withCandidates from "./with-candidates";
function candidate(slug: string, provider_id = 1): HarnessCandidate {
function candidate(
slug: string,
provider_id = 1,
source: HarnessCandidate["source"] = "auto",
): HarnessCandidate {
return {
key: `${provider_id}:${slug}`,
provider: {
@@ -18,7 +22,7 @@ function candidate(slug: string, provider_id = 1): HarnessCandidate {
output_modalities: ["text"],
supports_tools: true,
},
source: "auto",
source,
};
}
@@ -173,4 +177,111 @@ describe("withCandidates", () => {
expect(await run(bug)).toBe(bug);
});
test("a failed model rests no longer than the model rest, whatever it was", async () => {
const now = 1_000_000;
const rest_ms = 120_000;
for (const error of [
new HarnessError({ message: "gone", status: 404 }),
new HarnessError({ message: "refused", status: 403 }),
rateLimited("1:a", now + 60 * 60 * 1000),
new HarnessError({ message: "down", status: 503, retryable: true }),
]) {
const cooldowns = createCooldowns();
const a = candidate("a", 1, "pinned");
await withCandidates({
harness: "text",
candidates: [a, candidate("b")],
cooldowns,
rest_ms,
now: () => now,
run: async (c) => {
if (c == a) throw error;
},
});
expect(cooldowns.get({ key: a.key, now })).toBe(now + rest_ms);
}
});
test("a provider that says to come back sooner rests only that long", async () => {
const now = 1_000_000;
const cooldowns = createCooldowns();
const a = candidate("a");
await withCandidates({
harness: "text",
candidates: [a, candidate("b")],
cooldowns,
rest_ms: 120_000,
now: () => now,
run: async (c) => {
if (c == a) throw rateLimited(a.key, now + 5_000);
},
});
expect(cooldowns.get({ key: a.key, now })).toBe(now + 5_000);
});
test("a refused request benches nothing", async () => {
const cooldowns = createCooldowns();
const a = candidate("a");
await withCandidates({
harness: "text",
candidates: [a, candidate("b")],
cooldowns,
rest_ms: 120_000,
run: async (c) => {
if (c == a) throw new HarnessError({ message: "bad request", status: 400 });
},
});
expect(cooldowns.get({ key: a.key })).toBeUndefined();
});
test("tells the answer which models failed and which were resting", async () => {
const cooldowns = createCooldowns();
const pinned = candidate("pinned", 1, "pinned");
const first = candidate("first", 2, "fallback");
const second = candidate("second", 3, "fallback");
let seen: { failed: string[]; resting: string[] } | undefined;
cooldowns.set({ key: pinned.key, at: Date.now() + 60_000 });
await withCandidates({
harness: "text",
candidates: [pinned, first, second],
cooldowns,
rest_ms: 120_000,
run: async (c) => {
if (c == first) throw rateLimited(first.key);
},
on_success: ({ failed, resting }) => {
seen = { failed: [...failed], resting: [...resting] };
},
});
expect(seen).toEqual({ failed: [first.key], resting: [pinned.key] });
});
test("a run on an automatic pick goes back to the pick and its fallbacks once they rested", async () => {
const tried: string[] = [];
await withCandidates({
harness: "text",
candidates: [candidate("pinned", 1, "pinned"), candidate("fallback", 2, "fallback"), candidate("free-a"), candidate("free-b")],
prefer_key: "1:free-b",
cooldowns: createCooldowns(),
rest_ms: 120_000,
run: async (c) => {
tried.push(c.model.slug);
if (c.source != "auto") throw rateLimited(c.key);
},
});
expect(tried).toEqual(["pinned", "fallback", "free-b"]);
});
});
+85 -35
View File
@@ -3,15 +3,19 @@ import { Harnesses, type HarnessKind } from "@/src/dict/harness-dict";
import HarnessError from "../harness-error";
import type { HarnessCandidate } from "../types";
import type { HarnessCooldowns } from "./create-cooldowns";
import grabModelRestMs from "./grab-model-rest-ms";
import DefaultCooldowns from "./harness-cooldowns";
import logCandidateFailure from "./log-candidate-failure";
type Params<T> = {
harness: HarnessKind;
candidates: HarnessCandidate[];
run: (candidate: HarnessCandidate) => Promise<T>;
/**
* Tried first when it's a candidate: the model a multi-step run already
* uses, so it doesn't switch models mid-task without a reason.
* The model a multi-step run already uses, so it doesn't switch models
* mid-task without a reason. It goes before the other automatic picks,
* never before the pick or its fallback models: a run that fell back
* goes back to them once they've rested.
*/
prefer_key?: string;
/**
@@ -26,26 +30,32 @@ type Params<T> = {
* The candidates that failed before this one answered, by key.
*/
failed: string[];
/**
* The candidates ahead of this one that were passed over because
* they were resting after an earlier failure, by key.
*/
resting: string[];
}) => Promise<void> | void;
cooldowns?: HarnessCooldowns;
/**
* How long a failed candidate rests. Read from the install's setting
* (`grabModelRestMs`) when not given.
*/
rest_ms?: number;
/**
* Writes each failure to the activity log (`logCandidateFailure`). On
* by default for the process-wide cooldowns, i.e. real calls.
*/
log_failures?: boolean;
now?: () => number;
};
/**
* Bad keys and missing credits keep a provider out this long.
*/
const ProviderCooldownMs = 10 * 60 * 1000;
/**
* A model the provider no longer has (404) or won't serve to us (403)
* stays out this long.
*/
const GoneCooldownMs = 60 * 60 * 1000;
/**
* Runs a harness call on the first candidate that works, in order (the
* preferred one first), up to `AppData.HarnessMaxCandidates` tries.
* Runs a harness call on the first candidate that works, in order
* (`orderCandidates`), up to `AppData.HarnessMaxCandidates` tries.
* Candidates (and providers) on cooldown are skipped; a failure puts its
* candidate, or its whole provider for a key problem, on cooldown.
* candidate, or its whole provider for a key problem, on cooldown for the
* install's model rest (`coolDown`) and is logged.
*
* Throws a `HarnessError`: `unavailable` when there is nothing to try,
* otherwise the last failure, `retryable` if any failure was.
@@ -57,6 +67,8 @@ export default async function withCandidates<T>({
prefer_key,
on_success,
cooldowns = DefaultCooldowns,
rest_ms,
log_failures = cooldowns === DefaultCooldowns,
now = Date.now,
}: Params<T>): Promise<{ result: T; candidate: HarnessCandidate }> {
const title = Harnesses.find((h) => h.value == harness)?.title || harness;
@@ -68,10 +80,7 @@ export default async function withCandidates<T>({
});
}
const ordered = [
...candidates.filter((c) => c.key == prefer_key),
...candidates.filter((c) => c.key != prefer_key),
];
const ordered = orderCandidates({ candidates, prefer_key });
const isReady = (candidate: HarnessCandidate) =>
!cooldowns.get({ key: candidate.key, now: now() }) &&
@@ -97,6 +106,9 @@ export default async function withCandidates<T>({
}
const errors: HarnessError[] = [];
const failed: string[] = [];
const resting: string[] = [];
const rest = rest_ms ?? (await grabModelRestMs());
for (const candidate of ordered) {
if (errors.length >= AppData.HarnessMaxCandidates) break;
@@ -104,16 +116,15 @@ export default async function withCandidates<T>({
/**
* Checked each time: a failure can bench the rest of its provider.
*/
if (!isReady(candidate)) continue;
if (!isReady(candidate)) {
resting.push(candidate.key);
continue;
}
try {
const result = await run(candidate);
await on_success?.({
candidate,
result,
failed: errors.flatMap((e) => (e.candidate_key ? [e.candidate_key] : [])),
});
await on_success?.({ candidate, result, failed, resting });
return { result, candidate };
} catch (error: unknown) {
@@ -121,7 +132,13 @@ export default async function withCandidates<T>({
if (error.code == "aborted") throw error;
errors.push(error);
coolDown({ candidate, error, cooldowns, now: now() });
failed.push(candidate.key);
const rests_until = coolDown({ candidate, error, cooldowns, now: now(), rest_ms: rest });
if (log_failures) {
await logCandidateFailure({ harness, candidate, error, rests_until });
}
}
}
@@ -155,33 +172,66 @@ function providerKey(candidate: HarnessCandidate) {
return `provider:${candidate.provider.id ?? candidate.provider.base_url}`;
}
/**
* The order candidates are tried in: as resolved (the pick, its fallback
* models, then the automatic picks), with the model a run already uses
* moved ahead of the other automatic picks.
*/
function orderCandidates({
candidates,
prefer_key,
}: {
candidates: HarnessCandidate[];
prefer_key?: string;
}) {
const preferred = candidates.find((c) => c.key == prefer_key);
if (!preferred || preferred.source != "auto") return candidates;
return [
...candidates.filter((c) => c.source != "auto"),
preferred,
...candidates.filter((c) => c.source == "auto" && c != preferred),
];
}
/**
* Benches a failed candidate (or its whole provider, for a bad key or no
* credits) for `rest_ms`, or until the provider says to come back when
* that's sooner. A request the model refused (400, 422) benches nothing:
* it's about that request. Returns when it may be tried again, if benched.
*/
function coolDown({
candidate,
error,
cooldowns,
now,
rest_ms,
}: {
candidate: HarnessCandidate;
error: HarnessError;
cooldowns: HarnessCooldowns;
now: number;
rest_ms: number;
}) {
const until = now + rest_ms;
if (error.provider_wide) {
cooldowns.set({ key: providerKey(candidate), at: now + ProviderCooldownMs });
return;
cooldowns.set({ key: providerKey(candidate), at: until });
return until;
}
if (error.retryable) {
const at = error.retry_at || now + AppData.HarnessCooldownMs;
const at = Math.min(Math.max(error.retry_at || until, now), until);
cooldowns.set({
key: candidate.key,
at: Math.min(at, now + AppData.HarnessMaxCooldownMs),
});
return;
cooldowns.set({ key: candidate.key, at });
return at;
}
if (error.status == 403 || error.status == 404) {
cooldowns.set({ key: candidate.key, at: now + GoneCooldownMs });
cooldowns.set({ key: candidate.key, at: until });
return until;
}
return undefined;
}
+21
View File
@@ -0,0 +1,21 @@
import { AppData } from "@/src/data/app-data";
import type { HarnessTool } from "../types";
import { LoadToolsToolName } from "../tools/load-tools-tool";
/**
* The system prompt's list of the tools a run may load (`load_tools`):
* each by name with the start of its description, so the model knows
* what is there without every definition riding along on each turn.
*/
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
const lines = tools.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`);
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with the names you need (one call can load several), then call them. Don't load what you won't use.\n${lines.join("\n")}`;
}
function shortDescription({ text }: { text: string }) {
const line = text.trim().split("\n")[0]!.trim();
const max = AppData.HarnessDeferredToolLineChars;
return line.length > max ? `${line.slice(0, max - 3).trimEnd()}...` : line;
}
@@ -25,10 +25,10 @@ describe("fitTranscriptToContext", () => {
test("trims the oldest tool output first, keeping the newest", () => {
const transcript = run();
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 20000 });
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 26000 });
expect(result.trimmed).toBe(1);
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters");
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters of earlier computer_bash output");
expect(transcript[4]!.content).toBe(big);
expect(transcript[6]!.content).toBe("recent");
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
@@ -44,4 +44,69 @@ describe("fitTranscriptToContext", () => {
expect(result.trimmed).toBe(0);
expect(transcript[1]!.content).toBe(big);
});
test("keeps to the working context even when the window is far larger", () => {
const transcript = run();
const result = fitTranscriptToContext({
system: "s",
transcript,
context_length: 1_000_000,
budget_tokens: 15000,
});
expect(result.budget).toBe(15000);
expect(result.trimmed).toBe(1);
expect(String(transcript[2]!.content)).toStartWith("[Trimmed:");
expect(transcript[4]!.content).toBe(big);
});
test("cuts in one block, down to well under the budget, then leaves it alone", () => {
const transcript = run();
const first = fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 18000 });
expect(first.trimmed).toBe(1);
transcript.push(
{ role: "assistant", content: null, tool_calls: [{ id: "4", name: "computer_bash", arguments: "{}" }] },
{ role: "tool", tool_call_id: "4", content: "x".repeat(9000) },
);
const second = fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 18000 });
expect(second.trimmed).toBe(0);
});
test("counts the tool definitions against the budget", () => {
const transcript = run();
const without = fitTranscriptToContext({ system: "s", transcript: run(), context_length: 1_000_000, budget_tokens: 25000 });
const with_tools = fitTranscriptToContext({
system: "s",
transcript,
context_length: 1_000_000,
budget_tokens: 25000,
tools_chars: 30000,
});
expect(without.trimmed).toBe(0);
expect(with_tools.trimmed).toBeGreaterThan(0);
});
test("cuts long tool call arguments once the results are gone", () => {
const long = JSON.stringify({ path: "a.html", content: "y".repeat(30000) });
const transcript: HarnessMessage[] = [
{ role: "user", content: "Write the page." },
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_write_file", arguments: long }] },
{ role: "tool", tool_call_id: "1", content: "Written." },
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
{ role: "tool", tool_call_id: "2", content: "ok" },
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
{ role: "tool", tool_call_id: "3", content: "ok" },
];
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 5000 });
const call = (transcript[1] as { tool_calls: { arguments: string }[] }).tool_calls[0]!;
expect(JSON.parse(call.arguments).trimmed).toContain(`${long.length} characters`);
});
});
+118 -16
View File
@@ -11,6 +11,17 @@ type Params = {
* The model's context window, in tokens.
*/
context_length: number;
/**
* The working context (`grabContextBudgetTokens`): the most the prompt
* may be per turn, whatever the window. Left out, only the window
* limits it.
*/
budget_tokens?: number;
/**
* Characters of the tool definitions sent with every turn: they count
* against the budget like the prompt.
*/
tools_chars?: number;
/**
* The newest messages, never trimmed: the model needs them to go on.
*/
@@ -21,6 +32,12 @@ type Params = {
* Share of the window the prompt may fill; the rest is for the answer.
*/
const PromptShare = 0.7;
/**
* Once over budget, trimming goes on down to this share of it. Cutting in
* one block, rather than one message each turn, keeps the start of the
* prompt the same for many turns, which is what providers cache.
*/
const TrimToShare = 0.6;
/**
* Rough characters per token, on the low side so the estimate errs high.
*/
@@ -29,44 +46,129 @@ const CharsPerToken = 3;
* What an image or audio part is counted as, in tokens.
*/
const MediaTokens = 1500;
/**
* Tool call arguments longer than this (a file written whole) are cut on
* the second pass, after the tool results.
*/
const ArgumentsKeepChars = 1500;
/**
* Keeps a long tool run inside the model's context window: while the
* estimated prompt is over budget, the oldest tool results (then the
* oldest assistant texts) are replaced with a note of what was cut.
* Returns how many messages were trimmed.
* Keeps a long tool run inside its working context: once the estimated
* prompt (system, tool definitions, transcript) passes the budget (the
* working context, or 70% of the window when that is smaller), the
* oldest tool results, then long tool call arguments, then the oldest
* assistant texts are replaced with a note of what was cut, down to 60%
* of the budget. Returns how many messages were trimmed.
*/
export default function fitTranscriptToContext({
system,
transcript,
context_length,
budget_tokens,
tools_chars = 0,
keep_last = 4,
}: Params) {
const budget = Math.floor(context_length * PromptShare);
let total = estimateTokens({ text: system }) + transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
const window_budget = Math.floor(context_length * PromptShare);
const budget = budget_tokens && budget_tokens > 0 ? Math.min(window_budget, budget_tokens) : window_budget;
let total =
estimateTokens({ text: system }) +
Math.ceil(tools_chars / CharsPerToken) +
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
let trimmed = 0;
if (total <= budget) return { trimmed, estimated_tokens: total, budget };
const target = Math.floor(budget * TrimToShare);
const trimmable = transcript.length - keep_last;
const names = toolNames({ transcript });
for (const role of ["tool", "assistant"] as const) {
for (let index = 0; index < trimmable && total > budget; index++) {
const message = transcript[index]!;
const replace = ({ index, message }: { index: number; message: HarnessMessage }) => {
const before = messageTokens({ message: transcript[index]! });
if (message.role != role || typeof message.content != "string") continue;
if (message.content.startsWith("[Trimmed:")) continue;
transcript[index] = message;
total += messageTokens({ message }) - before;
trimmed++;
};
const before = messageTokens({ message });
const note = `[Trimmed: ${message.content.length} characters of earlier ${role == "tool" ? "tool output" : "notes"} to fit the context.]`;
for (let index = 0; index < trimmable && total > target; index++) {
const message = transcript[index]!;
transcript[index] = { ...message, content: note } as HarnessMessage;
total += messageTokens({ message: transcript[index]! }) - before;
trimmed++;
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
const name = names.get(message.tool_call_id);
replace({
index,
message: {
...message,
content: `[Trimmed: ${message.content.length} characters of earlier ${name ? `${name} output` : "tool output"} to fit the working context. Call it again if you still need it.]`,
},
});
}
for (let index = 0; index < trimmable && total > target; index++) {
const message = transcript[index]!;
if (message.role != "assistant" || !message.tool_calls?.some((call) => call.arguments.length > ArgumentsKeepChars)) {
continue;
}
replace({
index,
message: {
...message,
tool_calls: message.tool_calls.map((call) =>
call.arguments.length > ArgumentsKeepChars
? {
...call,
arguments: JSON.stringify({
trimmed: `${call.arguments.length} characters of arguments cut to fit the working context`,
}),
}
: call,
),
},
});
}
for (let index = 0; index < trimmable && total > target; index++) {
const message = transcript[index]!;
if (message.role != "assistant" || typeof message.content != "string" || isTrimmed({ text: message.content })) {
continue;
}
replace({
index,
message: {
...message,
content: `[Trimmed: ${message.content.length} characters of earlier notes to fit the working context.]`,
},
});
}
return { trimmed, estimated_tokens: total, budget };
}
/**
* The tool each call id went to, for the note that replaces its result.
*/
function toolNames({ transcript }: { transcript: HarnessMessage[] }) {
const names = new Map<string, string>();
for (const message of transcript) {
if (message.role != "assistant") continue;
for (const call of message.tool_calls || []) names.set(call.id, call.name);
}
return names;
}
function isTrimmed({ text }: { text: string }) {
return text.startsWith("[Trimmed:");
}
function messageTokens({ message }: { message: HarnessMessage }) {
let tokens = 4;
+2 -1
View File
@@ -96,13 +96,14 @@ export default async function generateText({
harness: "text",
candidates: resolved,
prefer_key,
on_success: async ({ candidate: answered, result: answer, failed }): Promise<void> =>
on_success: async ({ candidate: answered, result: answer, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "text",
candidate: answered,
usage: answer.usage,
failed,
resting,
settings: {
...(saved_params ? { settings_source: saved_params.source } : {}),
params: flattenSentParams({ params: answer.sent_params }),
+200 -2
View File
@@ -1,11 +1,11 @@
import { describe, expect, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { DroppedToolImageNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
import runTextLoop, { IncomingMessagesNote, RedraftNote } from "./run-text-loop";
import runTextLoop, { IncomingMessagesNote, RedraftNote, stepsLowNote } from "./run-text-loop";
const candidate: HarnessCandidate = {
key: "1:m",
@@ -201,6 +201,50 @@ describe("runTextLoop", () => {
});
});
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
const max_steps = AppData.HarnessStepsLowMinSteps;
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted(Array.from({ length: max_steps + 1 }, () => loop_call));
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
max_steps,
generate,
resolveCandidates,
});
const warned_at = max_steps - AppData.HarnessStepsLowWarning;
const note = stepsLowNote({ left: AppData.HarnessStepsLowWarning });
const warnings = seen.map((call) => call.messages.filter((m) => m.role == "user" && String(m.content).includes(note)).length);
expect(warnings[warned_at - 1]).toBe(0);
expect(warnings[warned_at]).toBe(1);
expect(seen[warned_at]!.messages.at(-1)).toEqual({ role: "user", content: note });
expect(warnings.at(-1)).toBe(1);
});
test("doesn't warn a short run", async () => {
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted([loop_call, loop_call, { text: "Done." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
max_steps: 2,
generate,
resolveCandidates,
});
expect(JSON.stringify(seen)).not.toContain("left in this run");
});
test("records failed tool calls, and tells the wrap up so", async () => {
const { generate, seen } = scripted([
{ tool_calls: [{ id: "c", name: "missing_tool", arguments: "{}" }] },
@@ -374,6 +418,59 @@ describe("runTextLoop", () => {
expect(seen[1]!.messages.at(-1)!.content).toContain("You've used every step");
});
test("tells the run its own notes with what came in", async () => {
const { generate, seen } = scripted([
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"x"}` }] },
{ text: "Report." },
{ text: "Report, corrected." },
]);
const arrivals = [
[{ role: "user" as const, content: "Use photos too." }],
[{ role: "user" as const, content: "And keep it short." }],
];
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Brief." }],
tools: [remember],
generate,
resolveCandidates,
incoming: async () => arrivals.shift() || [],
incoming_notes: { working: "Working note.", redraft: "Redraft note." },
});
expect(result.text).toBe("Report, corrected.");
expect(seen[1]!.messages.at(-1)).toEqual({ role: "user", content: "Working note.\n\nUse photos too." });
expect(seen[2]!.messages.at(-1)).toEqual({ role: "user", content: "Redraft note.\n\nAnd keep it short." });
});
test("with a wrap up note, takes in what came in by the wrap up before it", async () => {
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted([loop_call, { text: "Out of steps." }]);
let looks = 0;
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
max_steps: 1,
generate,
resolveCandidates,
incoming: async () => {
looks++;
return looks == 2 ? [{ role: "user", content: "Late correction." }] : [];
},
incoming_notes: { wrap_up: "Too late to act." },
});
expect(looks).toBe(2);
const last = seen[1]!.messages.at(-1)!.content as string;
expect(last).toContain("Too late to act.\n\nLate correction.");
expect(last.indexOf("Late correction.")).toBeLessThan(last.indexOf("You've used every step"));
});
test("writes an answer the review faults again, once, with its note and the tool calls", async () => {
const { generate, seen } = scripted([
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
@@ -443,4 +540,105 @@ describe("runTextLoop", () => {
expect(result.text).toBe("Out of steps.");
expect(reviews).toBe(0);
});
test("wraps up once the run has spent its token budget", async () => {
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
usage: { prompt_tokens: 600, completion_tokens: 1 },
};
const { generate, seen } = scripted([loop_call, loop_call, { text: "Stopping here.", ...loop_call }]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
max_prompt_tokens: 1000,
generate,
resolveCandidates,
});
expect(seen).toHaveLength(3);
expect(seen[2]!.tools).toBe(undefined);
expect(seen[2]!.messages.at(-1)!.content).toContain("This run has used all the tokens it may spend.");
expect(result.text).toBe("Stopping here.");
});
test("keeps only the newest page snapshot in the transcript", async () => {
let page = 0;
const snapshot: HarnessTool = {
name: "browser_snapshot",
description: "Reads the page.",
schema: z.object({}),
run: async () => `page ${++page}`,
};
const snap = (id: string) => ({ tool_calls: [{ id, name: "browser_snapshot", arguments: "{}" }] });
const { generate, seen } = scripted([snap("a"), snap("b")]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Look." }],
tools: [snapshot],
generate,
resolveCandidates,
});
const tool_turns = seen[2]!.messages.filter((message) => message.role == "tool");
expect(tool_turns.map((message) => message.content)).toEqual([SupersededSnapshotNote, "page 2"]);
});
test("lists deferred tools by name and gives their definitions once loaded", async () => {
const big = "Does a thing. ".repeat(Math.ceil(AppData.HarnessDeferToolsMinChars / 14));
const used: string[] = [];
const extension = (name: string): HarnessTool => ({
name,
description: big,
parameters: { type: "object", properties: {} },
deferred: true,
run: async () => {
used.push(name);
return "done";
},
});
const { generate, seen } = scripted([
{ tool_calls: [{ id: "1", name: "load_tools", arguments: `{"names":["srv__a"]}` }] },
{ tool_calls: [{ id: "2", name: "srv__a", arguments: "{}" }] },
{ tool_calls: [{ id: "3", name: "srv__b", arguments: "{}" }] },
{ text: "Done." },
]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, extension("srv__a"), extension("srv__b")],
generate,
resolveCandidates,
});
const names = (index: number) => seen[index]!.tools!.map((tool) => tool.name);
expect(names(0)).toEqual(["remember", "load_tools"]);
expect(String(seen[0]!.messages[0]!.content)).toContain("Tools you can load");
expect(String(seen[0]!.messages[0]!.content)).toContain("- srv__a: Does a thing.");
expect(names(1)).toEqual(["remember", "load_tools", "srv__a"]);
expect(seen[1]!.messages.at(-1)!.content).toContain("Loaded: srv__a.");
expect(names(3)).toEqual(["remember", "load_tools", "srv__a", "srv__b"]);
expect(used).toEqual(["srv__a", "srv__b"]);
});
test("gives small deferred tools straight away", async () => {
const small: HarnessTool = { ...remember, name: "srv__small", deferred: true };
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, small],
generate,
resolveCandidates,
});
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "srv__small"]);
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
});
});
+121 -14
View File
@@ -1,6 +1,7 @@
import { AppData } from "@/src/data/app-data";
import HarnessError from "../harness-error";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import loadToolsTool from "../tools/load-tools-tool";
import runToolCall from "../tools/run-tool-call";
import toolDefinition from "../tools/tool-definition";
import type {
@@ -12,11 +13,13 @@ import type {
HarnessToolUse,
HarnessUsage,
} from "../types";
import deferredToolsNote from "./deferred-tools-note";
import describeToolUses from "./describe-tool-uses";
import dropOldToolImages from "./drop-old-tool-images";
import fitTranscriptToContext from "./fit-transcript-to-context";
import generateText from "./generate-text";
import pushUserTurn from "./push-user-turn";
import supersedeToolOutputs from "./supersede-tool-outputs";
import toolImagesTurn from "./tool-images-turn";
export type TextLoopStep = {
@@ -35,8 +38,25 @@ type Params = {
* The conversation so far, ending with what to do now.
*/
messages: HarnessMessage[];
/**
* The run's tools. Deferred ones (`HarnessTool.deferred`) are listed
* by name and loaded with `load_tools`, when together they're large
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
*/
tools?: HarnessTool[];
max_steps?: number;
/**
* Prompt tokens the run may spend in all (`grabRunMaxPromptTokens`):
* once its turns have sent this many, the next one is the wrap up.
* Left out, only `max_steps` ends it.
*/
max_prompt_tokens?: number;
/**
* The working context (`grabContextBudgetTokens`): the most each turn
* sends before old tool output is trimmed, whatever the model's
* window. Left out, the window decides.
*/
context_budget?: number;
signal?: AbortSignal;
/**
* Called after each model turn, before its tools run. Use it for
@@ -51,6 +71,14 @@ type Params = {
* is written again with them in mind.
*/
incoming?: () => Promise<HarnessMessage[]>;
/**
* What the run is told with what came in: `working` after a round of
* tools, `redraft` past an answer that hadn't gone out (defaults
* `IncomingMessagesNote`, `RedraftNote`). With `wrap_up`, what came in
* by the wrap up is added before it too, for a run nothing picks up
* after (a task); without it a later reply does.
*/
incoming_notes?: { working?: string; redraft?: string; wrap_up?: string };
/**
* Checks an answer before it's returned, with the tool calls the run
* made. A note sends the answer back to be written again with it, once
@@ -91,13 +119,22 @@ export type TextLoopResult = {
/**
* Told on the last step, with the app's record of the tools the run
* called (`describeToolUses`): out of steps, a model tends to report the
* work it planned as done.
* work it planned as done. `tokens` when the run's token budget ended it
* rather than its steps.
*/
export const wrapUpPrompt = ({ uses }: { uses: HarnessToolUse[] }) =>
`You've used every step this run allows. Don't call any more tools. Report what you did, what is left, and anything you need from the user.
export const wrapUpPrompt = ({ uses, reason = "steps" }: { uses: HarnessToolUse[]; reason?: "steps" | "tokens" }) =>
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} Don't call any more tools. Report what you did, what is left, and anything you need from the user.
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
/**
* Told once, `AppData.HarnessStepsLowWarning` steps before the wrap up,
* while the run can still save what it has: the wrap up has no tools, so a
* report not written by then is lost.
*/
export const stepsLowNote = ({ left }: { left: number }) =>
`You have ${left} step${left == 1 ? "" : "s"} left in this run. Save what the user will want now (the report or deliverable, with write_file or import_file) before anything else, then finish. What isn't saved when the steps run out is lost.`;
/**
* Told with what the user wrote while the run worked. Whether a message
* belongs to the work is the model's call, from what it says: a correction
@@ -121,17 +158,27 @@ Don't repeat tool calls you have already made.`;
* The text harness at work: the model answers or calls tools, tool results
* go back to it, and so on until it answers without calling a tool. Tools
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
* `max_steps` turns the model is asked to wrap up without tools. An answer
* `review` finds fault with is written again once.
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
* model is asked to wrap up without tools. An answer `review` finds fault
* with is written again once.
*
* Every turn resends everything, so the run keeps it small: only the
* newest page snapshot of each browser stays (`supersedeToolOutputs`),
* old tool output is trimmed to the working context
* (`fitTranscriptToContext`), and deferred tools are listed by name until
* loaded.
*/
export default async function runTextLoop({
system,
messages,
tools = [],
max_steps = AppData.HarnessMaxToolSteps,
max_prompt_tokens,
context_budget,
signal = new AbortController().signal,
onStep,
incoming,
incoming_notes,
review,
bot_id,
workspace_id,
@@ -139,10 +186,39 @@ export default async function runTextLoop({
resolveCandidates = () => resolveHarnessCandidates({ harness: "text", bot_id, workspace_id }),
}: Params): Promise<TextLoopResult> {
const candidates = await resolveCandidates();
const definitions = tools.map((tool) => toolDefinition({ tool }));
/**
* Deferred tools wait to be loaded only when their definitions
* together are worth keeping out of every turn.
*/
const deferrable = tools.filter((tool) => tool.deferred);
const defer =
deferrable.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0) >=
AppData.HarnessDeferToolsMinChars;
/**
* Loaded deferred tools, in the order they were loaded: their
* definitions go after the others, so the start of the list (and of
* the prompt, which providers cache) stays the same.
*/
const loaded: string[] = [];
const run_tools: HarnessTool[] = defer
? [
...tools,
loadToolsTool({
deferred: deferrable,
isLoaded: (name) => loaded.includes(name),
onLoad: (names) => loaded.push(...names),
}),
]
: tools;
const all_definitions = new Map(run_tools.map((tool) => [tool.name, toolDefinition({ tool })]));
const definitionsNow = () => [
...run_tools.filter((tool) => !defer || !tool.deferred).map((tool) => all_definitions.get(tool.name)!),
...loaded.map((name) => all_definitions.get(name)!),
];
const run_system = defer ? `${system}\n\n${deferredToolsNote({ tools: deferrable })}` : system;
const media_cache = new Map<string, string>();
const transcript: HarnessMessage[] = [...messages];
const usage: Required<HarnessUsage> = {
const usage: Required<Omit<HarnessUsage, "cached_tokens">> = {
prompt_tokens: 0,
completion_tokens: 0,
cost: 0,
@@ -150,18 +226,27 @@ export default async function runTextLoop({
const tool_uses: HarnessToolUse[] = [];
let prefer_key: string | undefined;
let reviewed = false;
let warned_steps = max_steps < AppData.HarnessStepsLowMinSteps;
for (let index = 0; index <= max_steps; index++) {
if (signal.aborted) {
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
}
const wrap_up = index == max_steps;
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens);
const wrap_up = index == max_steps || out_of_tokens;
if (wrap_up) {
pushUserTurn({ transcript, content: wrapUpPrompt({ uses: tool_uses }) });
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up });
pushUserTurn({
transcript,
content: wrapUpPrompt({ uses: tool_uses, reason: index == max_steps ? "steps" : "tokens" }),
});
}
const definitions = definitionsNow();
/**
* Sized for the model the run is on (or will start on). A fallback
* with a smaller window gets a 400 and the next model is tried.
@@ -169,13 +254,15 @@ export default async function runTextLoop({
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
fitTranscriptToContext({
system,
system: run_system,
transcript,
context_length: model?.context_length || AppData.HarnessAutoMinContext,
budget_tokens: context_budget,
tools_chars: wrap_up ? 0 : JSON.stringify(definitions).length,
});
const answer = await generate({
messages: [{ role: "system", content: system }, ...transcript],
messages: [{ role: "system", content: run_system }, ...transcript],
tools: wrap_up || !definitions.length ? undefined : definitions,
candidates,
prefer_key,
@@ -209,7 +296,7 @@ export default async function runTextLoop({
* An answer the user wrote past is drafted again. Not on the wrap
* up: the run is out of steps, and a later reply picks them up.
*/
if (!tool_calls.length && !wrap_up && (await takeIncoming({ note: RedraftNote }))) {
if (!tool_calls.length && !wrap_up && (await takeIncoming({ note: incoming_notes?.redraft || RedraftNote }))) {
continue;
}
@@ -240,7 +327,15 @@ export default async function runTextLoop({
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
for (const call of tool_calls) {
const { text: content, images } = await runToolCall({ call, tools, signal });
const { text: content, images } = await runToolCall({ call, tools: run_tools, signal });
/**
* A deferred tool called without loading it ran all the same;
* it stays loaded from here on.
*/
if (defer && deferrable.some((tool) => tool.name == call.name) && !loaded.includes(call.name)) {
loaded.push(call.name);
}
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
transcript.push({ role: "tool", tool_call_id: call.id, content });
@@ -254,6 +349,8 @@ export default async function runTextLoop({
* setting allows it (`textSeesImages`); otherwise `generateText`
* has them read first.
*/
supersedeToolOutputs({ transcript });
if (shown.length) {
pushUserTurn({ transcript, content: toolImagesTurn({ shown }) });
dropOldToolImages({
@@ -263,7 +360,17 @@ export default async function runTextLoop({
});
}
await takeIncoming({ note: IncomingMessagesNote });
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote });
/**
* Steps left before the wrap up, once the next turn is taken.
*/
const left = max_steps - (index + 1);
if (!warned_steps && left <= AppData.HarnessStepsLowWarning) {
warned_steps = true;
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
}
}
throw new Error(`Unreachable: the text loop ended without an answer.`);
@@ -0,0 +1,47 @@
import { describe, expect, test } from "bun:test";
import { SupersededSnapshotNote } from "@/src/data/harness-prompts";
import type { HarnessMessage } from "../types";
import supersedeToolOutputs from "./supersede-tool-outputs";
const call = (id: string, name: string): HarnessMessage => ({
role: "assistant",
content: null,
tool_calls: [{ id, name, arguments: "{}" }],
});
const result = (id: string, content: string): HarnessMessage => ({ role: "tool", tool_call_id: id, content });
describe("supersedeToolOutputs", () => {
test("keeps only the newest snapshot of each browser", () => {
const transcript: HarnessMessage[] = [
{ role: "user", content: "Check the site." },
call("1", "browser_snapshot"),
result("1", "page one"),
call("2", "browser_click"),
result("2", "clicked"),
call("3", "pc__browser_snapshot"),
result("3", "my page"),
call("4", "browser_snapshot"),
result("4", "page two"),
];
expect(supersedeToolOutputs({ transcript })).toBe(1);
expect(transcript[2]!.content).toBe(SupersededSnapshotNote);
expect(transcript[4]!.content).toBe("clicked");
expect(transcript[6]!.content).toBe("my page");
expect(transcript[8]!.content).toBe("page two");
expect(supersedeToolOutputs({ transcript })).toBe(0);
});
test("a failed snapshot replaces nothing", () => {
const transcript: HarnessMessage[] = [
call("1", "browser_snapshot"),
result("1", "page one"),
call("2", "browser_snapshot"),
result("2", "Error: the browser is closed."),
];
expect(supersedeToolOutputs({ transcript })).toBe(0);
expect(transcript[1]!.content).toBe("page one");
});
});
@@ -0,0 +1,61 @@
import { SupersededSnapshotNote } from "@/src/data/harness-prompts";
import isBrowserTool from "@/src/utils/browser-tool-name";
import type { HarnessMessage } from "../types";
type Params = {
/**
* Changed in place, so the run keeps the savings.
*/
transcript: HarnessMessage[];
};
/**
* Keeps only the newest page snapshot of each browser in a run's
* transcript: a snapshot shows the page as it was, and the next one
* replaces it, so resending the old ones on every turn only costs tokens.
* Older ones become a note. A failed snapshot replaces nothing. Returns
* how many were replaced.
*/
export default function supersedeToolOutputs({ transcript }: Params) {
const names = new Map<string, string>();
for (const message of transcript) {
if (message.role != "assistant") continue;
for (const call of message.tool_calls || []) names.set(call.id, call.name);
}
const newest = new Map<string, number>();
transcript.forEach((message, index) => {
if (message.role != "tool" || !isSnapshot({ message, names })) return;
newest.set(names.get(message.tool_call_id)!, index);
});
let replaced = 0;
transcript.forEach((message, index) => {
if (message.role != "tool" || !isSnapshot({ message, names })) return;
if (newest.get(names.get(message.tool_call_id)!) == index) return;
transcript[index] = { ...message, content: SupersededSnapshotNote };
replaced++;
});
return replaced;
}
/**
* A successful snapshot that is still shown in full.
*/
function isSnapshot({ message, names }: { message: HarnessMessage & { role: "tool" }; names: Map<string, string> }) {
const name = names.get(message.tool_call_id);
return (
Boolean(name) &&
isBrowserTool({ name: name!, action: "browser_snapshot" }) &&
!message.content.startsWith("Error:") &&
message.content != SupersededSnapshotNote
);
}
+24 -3
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import grabBotById from "@/src/functions/backend/db/bots/grab-bot-by-id";
import chatroomAskableBots from "@/src/functions/backend/db/chatrooms/chatroom-askable-bots";
import createChatroom from "@/src/functions/backend/db/chatrooms/create-chatroom";
import grabCrewRequests from "@/src/functions/backend/db/chatrooms/grab-crew-requests";
import chatroomRef from "@/src/utils/chatroom-ref";
import type { HarnessTool } from "../../types";
@@ -29,6 +30,7 @@ type Args = {
title: string;
request: string;
bot_id?: number;
separate?: boolean;
};
/**
@@ -37,18 +39,25 @@ type Args = {
* coordinator works out who should answer, asks them, and sends the answer
* back to this conversation, which wakes the bot to act on it. Who can be
* asked is decided by the app, never the model: in a workspace its
* members, otherwise every worker the user reaches.
* members, otherwise every worker the user reaches. While one of its
* requests from the same place is open, another is refused unless it says
* it's `separate`: a task run that couldn't see the open one asked bot 20
* for the same two files a third time.
*/
export default function askCrewTool({ user_id, bot_id, session_id, workspace_id, onChatroom }: Params): HarnessTool<Args> {
return {
name: "ask_crew",
description: `Ask another bot for something you need (what it knows, a file it has, work in its line) through the coordinator. The coordinator reads your request, asks the bot best placed to answer and sends the answer back here as a message, which wakes you to act on it: don't wait or check on it. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
description: `Ask another bot for something you need (what it knows, a file it has, work in its line) through the coordinator. The coordinator reads your request, asks the bot best placed to answer and sends the answer back here as a message, which wakes you to act on it: don't wait or check on it. If a task you'd start needs the answer, don't start it in the same reply: it would run without it, so start it once the answer wakes you. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
workspace_id ? "You're in a workspace, so only its members can be asked." : "Any bot the user works with can be asked."
} The request and everything said about it is kept in a chatroom the user can read.`,
} The request and everything said about it is kept in a chatroom the user can read. While a request of yours from here is open, a new one is refused unless it asks for something else (separate: true).`,
schema: z.object({
title: z.string().trim().min(1).max(80).describe("A short label for the request"),
request: z.string().trim().min(1).max(8000).describe("The brief, in markdown"),
bot_id: z.number().int().optional().describe("The bot you think can help, if you know"),
separate: z
.boolean()
.optional()
.describe("true when this asks for something different from a request of yours that's still open"),
}),
run: async ({ args }) => {
const bot = await grabBotById({ bot_id });
@@ -71,6 +80,18 @@ export default function askCrewTool({ user_id, bot_id, session_id, workspace_id,
);
}
if (!args.separate) {
const open = (await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id })).filter(
(room) => room.status == "open",
);
if (open.length) {
return `Not asked: you already have ${open
.map((room) => `${chatroomRef({ id: room.id! })} "${room.title}"`)
.join(", ")} open. Its answer comes back here as a message and wakes you, so don't ask again for the same thing. If this asks for something different, call ask_crew again with separate: true.`;
}
}
const named = args.bot_id ? askable.find((other) => other.id == args.bot_id) : null;
if (args.bot_id && !named) {
@@ -96,6 +96,13 @@ describe("delegateTaskTool", () => {
expect(tool.description).toContain("task_id");
});
test("can hand a task over without starting 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");
});
test("without a task_id, still needs a title and instructions", async () => {
const tool = delegateTaskTool({
user_id: 1,
+25 -4
View File
@@ -53,6 +53,11 @@ type Params = {
*/
is_coordinator?: boolean;
admin_workspace_ids?: number[];
/**
* Called with a 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 = {
@@ -63,6 +68,10 @@ type Args = {
* and the worker works that same task.
*/
task_id?: number;
/**
* With `task_id`: false to only move the task, nothing started.
*/
start?: boolean;
title?: string;
instructions?: string;
/**
@@ -94,6 +103,7 @@ export default function delegateTaskTool({
grabTargets = ({ workspace_id }) => grabCrewWorkers({ workspace_id }),
is_coordinator = false,
admin_workspace_ids = [],
onTask,
}: Params): HarnessTool<Args> {
const crew = workers
.map((bot) => `${bot.id}: ${bot.name}${bot.role ? ` (${bot.role})` : ""}`)
@@ -104,7 +114,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. 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), 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}.${
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"}.`
@@ -112,6 +122,10 @@ export default function delegateTaskTool({
schema: z.object({
bot_id: z.number().int(),
task_id: z.number().int().optional().describe("An open task (list_tasks) to hand over as it is"),
start: z
.boolean()
.optional()
.describe("With task_id: false to only move the task (to do, nothing runs) until the user says to start"),
title: z.string().min(1).max(80).optional(),
instructions: z.string().min(1).max(8000).optional(),
workspace_id: z
@@ -184,11 +198,18 @@ export default function delegateTaskTool({
handed_by: requester_name,
requested_by_bot_id: requester_id,
requested_by_session_id: session_id,
start: args.start !== false,
});
return `Task #${task.id} "${task.title}" is with ${worker.name} now (job #${handed.job_id})${
handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in their own chat"
}, marked doing.${handed.joined} They work that same task; the result is reported back here.`;
onTask?.({ task_id: Number(task.id) });
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in their own chat";
if (!handed.job_id) {
return `Task #${task.id} "${task.title}" is on ${worker.name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.${handed.joined}`;
}
return `Task #${task.id} "${task.title}" is with ${worker.name} now (job #${handed.job_id})${where}, marked doing.${handed.joined} They work that same task; the result is reported back here.`;
}
if (!args.title?.trim() || !args.instructions?.trim()) {
+10 -1
View File
@@ -81,6 +81,11 @@ type Params = {
* Called with the ref of each chatroom the bot opened (`ask_crew`).
*/
onChatroom?: (params: { ref: string }) => void;
/**
* Called with each tracker task the run worked on, so the message it
* posts links to it (`bot_messages.task_ids`).
*/
onTask?: (params: { task_id: number }) => void;
};
/**
@@ -120,6 +125,7 @@ export default async function grabBotChatTools({
onPropose,
onWorkspaceAdmin,
onChatroom,
onTask,
}: Params): Promise<HarnessTool[]> {
const bot_id = bot.id || 0;
const tools = [
@@ -135,6 +141,7 @@ export default async function grabBotChatTools({
can_delete_tasks: Boolean(attended),
onPropose,
onChatroom,
onTask,
})),
startTaskTool({
user_id,
@@ -160,7 +167,7 @@ export default async function grabBotChatTools({
if (!powers.is_coordinator) {
if (!workspace_id || !powers.is_workspace_admin) return tools;
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes });
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
@@ -195,6 +202,7 @@ export default async function grabBotChatTools({
requester_name: bot.name || "The coordinator",
workers,
is_coordinator: true,
onTask,
}));
tools.push(handOverScheduleTool({
user_id,
@@ -236,6 +244,7 @@ export default async function grabBotChatTools({
workers,
workspaces,
is_coordinator: true,
onTask,
}),
handOverScheduleTool({
user_id,
+7
View File
@@ -62,6 +62,11 @@ type Params = {
* (`ask_crew`), so the reply carries its chip.
*/
onChatroom?: (params: { ref: string }) => void;
/**
* Called with each tracker task the run worked on, so the message it
* posts links to it (`bot_messages.task_ids`).
*/
onTask?: (params: { task_id: number }) => void;
};
/**
@@ -84,6 +89,7 @@ export default async function grabBotTools({
can_delete_tasks,
onPropose,
onChatroom,
onTask,
}: Params): Promise<HarnessTool[]> {
return [
setPictureTool({ user_id, bot_id, scopes, is_coordinator }),
@@ -112,6 +118,7 @@ export default async function grabBotTools({
admin_workspace_ids,
workspace_id,
can_delete: Boolean(can_delete_tasks) && !hooked,
onTask,
})),
];
}

Some files were not shown because too many files have changed in this diff Show More