Compare commits

...
10 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 419a50b95b Release v0.17.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-08 10:02:37 +01:00
tbenandClaude Opus 5.5 c4c86fc66b Set up a new install from a backup, and restart after a database restore
First-run setup can now restore another install's database file or
whole-data archive instead of creating a super admin. The upload is told
apart by its bytes, refused once any account exists or for a database
with no accounts, restored like Settings > Backups, and the app restarts
onto it.

Settings > Backups' database restore swapped in a new file from a
separate process while the server kept its handle on the old one, so
everything written until the next restart was lost. Database restores now
run in the background and restart the app, like data archive restores.
Log entries for a restore are queued in the data folder and written at
boot, into the restored database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 10:02:37 +01:00
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
152 changed files with 3033 additions and 454 deletions
+7 -6
View File
@@ -54,7 +54,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Auth
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings; or Restore from a backup: another install's database file or data archive, told apart by their bytes, through public `api/auth/bootstrap-restore`, refused once any user exists or for a database with no users, restored like Settings > Backups and then the app restarts, the page polling `bootstrap-status` and going to the login); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
- **Session:** AES-256-GCM cookie (key from `ENCRYPTION_KEY`/`ENCRYPTION_SALT`) plus CSRF cookie, `Secure` only over HTTPS (`isSecureRequest`, honours `X-Forwarded-Proto`). `userAuth` (`src/functions/backend/auth/user-auth.ts`) checks expiry (60 days), CSRF (constant-time) and re-reads `user_types` every request.
- **Login:** email/username + password (`api/auth/password-login.ts`, rate limited). No emailed codes or resets. Google login only for existing accounts, when `GOOGLE_CLIENT_ID` is set. Sessions issued by `login-user.ts`.
- **Passwords:** bcrypt in `user_passwords` (never in `users`; blocked from CRUD via `src/dict/private-tables.ts`).
@@ -90,13 +90,14 @@ 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 `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.
- **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 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.
- **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).
- **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).
@@ -211,10 +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`; 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).
- **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).
@@ -241,7 +242,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Rail pages** (`src/dict/rail-pages-dict.ts`): Routines, Files, Usage (crew managers), Activity (`/admin/logs`, super admin), Help (`(data)/help-topics.ts`). Visibility via `canSeeRailItem` for both the popover and the aside.
- **Settings** (`src/dict/settings-pages-dict.ts`; add a sub page = folder + dict entry): `general` (theme per device, plus super-admin app settings: prompt append, run limits, skill limits; crew-manager storage quota; running version), `setup` (super admin; shares the Models page's server props and `useModelsOverview`), `profile`, `notifications`, `change-password`, `secrets`, `browsers`, `models`, `environment`, `backups` and `database` (super admin), `bots`, `workspaces`, `computers`, `mcps`, `tools`, `skills`, `knowledgebases` (crew managers), `users` (`canListUsers`).
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process.
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process. **A database snapshot restore restarts too** (also a background run, `db_restore`): `bun-sqlite import` swaps in a new file from another process, and this process's handle would stay on the old one, so nothing may be written to the database between a restore and the restart (log entries go through `queueBootLog`, written by `flushBootLogs` at boot).
- **Database browser:** strictly read-only; values cut in SQL; state in the address via `databaseHref`.
- Add flow (`(partials)/add-flow.tsx`) from the rail's Add icon: bot, workspace, computer (super admin). Page heroes use `AdminHero`.
+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=="],
+5
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`,
+4
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
*/
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.16.1",
"version": "0.17.0",
"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",
+1
View File
@@ -237,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 });
+6
View File
@@ -217,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
@@ -260,6 +264,7 @@ export default async function runBotReply({
led = admin;
},
onChatroom: ({ ref }) => shown.push(ref),
onTask: ({ task_id }) => task_ids.push(task_id),
});
/**
@@ -451,6 +456,7 @@ export default async function runBotReply({
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
};
} finally {
await extensions.close();
+14 -1
View File
@@ -111,6 +111,10 @@ 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({
@@ -194,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 = [
@@ -208,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
@@ -473,6 +485,7 @@ export default async function runBotTask({
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
};
} finally {
await extensions?.close();
+5
View File
@@ -57,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;
}
@@ -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>
);
}
+16 -1
View File
@@ -9,6 +9,10 @@ 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.
@@ -24,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, gallery, 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 (
@@ -50,6 +64,7 @@ export default function FilePreviewLink({ name, url, media_type, size, gallery,
url={url}
media_type={media_type}
size={size}
full_path={full_path}
gallery={gallery}
onClose={() => setOpen(false)}
/>
@@ -11,9 +11,9 @@ 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 = {
@@ -21,6 +21,10 @@ type Props = {
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
@@ -34,7 +38,7 @@ 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
@@ -44,7 +48,7 @@ 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 } = shown;
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;
@@ -77,11 +81,7 @@ export default function FilePreviewModal({ gallery, onClose, ...opened }: Props)
>
{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
@@ -2,6 +2,7 @@ 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";
@@ -86,3 +87,12 @@ test("a gallery's stepper says where the image stands and stops at the ends", ()
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("");
});
@@ -61,6 +61,7 @@ export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder
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"
>
+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}`}
@@ -42,8 +42,9 @@ type Props = {
};
/**
* Picks one file and sends it for a restore: shared by the database upload
* and the data archive upload, which differ only in what they accept.
* Picks one file and sends it for a restore: shared by the database upload,
* the data archive upload and the restore at first-run setup, which differ
* only in what they accept.
*/
export default function UploadRestoreFields({
label,
+25 -3
View File
@@ -387,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
@@ -405,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,
@@ -944,6 +960,12 @@ export const AppData = {
*/
DataBackupNamePrefix: "cobble-data-",
DataBackupsKept: 5,
/**
* Log entries a restore leaves in `DATA_DIR` for the next boot to
* write (`queueBootLog`): written before the restart they would land
* in the replaced database, which the process still has open.
*/
PendingBootLogsFile: ".pending-boot-logs.json",
/**
* How often the backups page asks how a whole-data archive or restore
* is going, and how long it waits for the app to come back after a
+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.**
`;
+10 -4
View File
@@ -72,7 +72,7 @@ You are chatting with the user. Answer their latest messages directly and briefl
## 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,
@@ -200,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
@@ -215,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,
@@ -250,7 +256,7 @@ 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. 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, 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
+6
View File
@@ -125,6 +125,12 @@ export const RunMaxPromptTokensSettingKey = "run_max_prompt_tokens";
*/
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.
@@ -0,0 +1,66 @@
import { afterAll, describe, expect, test } from "bun:test";
import { Database } from "bun:sqlite";
import fs from "fs";
import os from "os";
import path from "path";
import assertDbHasUsers from "./assert-db-has-users";
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-bootstrap-db-"));
type Params = {
name: string;
sql: string;
};
function makeDb({ name, sql }: Params) {
const db_path = path.join(dir, name);
const db = new Database(db_path, { create: true });
db.run(sql);
db.close();
return db_path;
}
afterAll(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
describe("assertDbHasUsers", () => {
test("passes a database with an account", () => {
const db_path = makeDb({
name: "with-user.db",
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT); INSERT INTO users (email) VALUES ('[email protected]');`,
});
expect(() => assertDbHasUsers({ db_path })).not.toThrow();
});
test("refuses a database with no accounts", () => {
const db_path = makeDb({
name: "empty-users.db",
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);`,
});
expect(() => assertDbHasUsers({ db_path })).toThrow(/no accounts/);
});
test("refuses a database without a users table", () => {
const db_path = makeDb({
name: "other.db",
sql: `CREATE TABLE notes (id INTEGER PRIMARY KEY);`,
});
expect(() => assertDbHasUsers({ db_path })).toThrow(/no users table/);
});
test("leaves the file unchanged", () => {
const db_path = makeDb({
name: "unchanged.db",
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY); INSERT INTO users DEFAULT VALUES;`,
});
const before = fs.readFileSync(db_path);
assertDbHasUsers({ db_path });
expect(fs.readFileSync(db_path).equals(before)).toBe(true);
});
});
@@ -0,0 +1,38 @@
import { Database } from "bun:sqlite";
import AppError from "@/src/utils/app-error";
import { SiteData } from "@/src/data/site-data";
type Params = {
db_path: string;
};
/**
* Refuses a database file that holds no accounts: restoring it would
* only send the install back to first-run setup. Opened read-only, so
* the file is never changed by the look.
*/
export default function assertDbHasUsers({ db_path }: Params) {
let db: Database | undefined;
try {
db = new Database(db_path, { readonly: true });
const row = db
.query<{ id: number }, []>(`SELECT id FROM users LIMIT 1`)
.get();
if (!row?.id) {
throw new AppError(
`That database has no accounts, so there is nothing to sign in with`,
);
}
} catch (error: unknown) {
if (error instanceof AppError) throw error;
throw new AppError(
`That file isn't a ${SiteData["SiteName"]} database (it has no users table)`,
);
} finally {
db?.close();
}
}
@@ -0,0 +1,36 @@
import fs from "fs";
import path from "path";
import { AppData } from "@/src/data/app-data";
import grabDirNames from "@/src/utils/grab-dir-names";
import logEvent, { type LogEventParams } from "@/src/functions/backend/logger";
/**
* Writes the log entries a restore queued before the restart
* (`queueBootLog`) into the database the app came back up on, once. The
* file is moved aside first, so a second process starting at the same
* time never writes them twice.
*/
export default async function flushBootLogs() {
const { DATA_DIR } = grabDirNames();
const file_path = path.join(DATA_DIR, AppData.PendingBootLogsFile);
const claimed_path = `${file_path}.${process.pid}`;
try {
fs.renameSync(file_path, claimed_path);
} catch {
return;
}
try {
const parsed = JSON.parse(fs.readFileSync(claimed_path, "utf-8"));
const entries: LogEventParams[] = Array.isArray(parsed) ? parsed : [];
for (const entry of entries) {
await logEvent(entry);
}
} catch {
// A broken file is dropped: these are only log entries.
} finally {
fs.rmSync(claimed_path, { force: true });
}
}
@@ -0,0 +1,51 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import { AppData } from "@/src/data/app-data";
import queueBootLog from "./queue-boot-log";
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-boot-log-"));
const previous = process.env.DATA_DIR;
const file_path = path.join(dir, AppData.PendingBootLogsFile);
beforeAll(() => {
process.env.DATA_DIR = dir;
});
afterAll(() => {
if (previous === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = previous;
fs.rmSync(dir, { recursive: true, force: true });
});
describe("queueBootLog", () => {
test("keeps entries in order across calls", () => {
queueBootLog({
entry: { title: "One", category: "system", plain_text: "first" },
});
queueBootLog({
entry: { title: "Two", category: "system", plain_text: "second" },
});
const entries = JSON.parse(fs.readFileSync(file_path, "utf-8"));
expect(entries.map((entry: { title: string }) => entry.title)).toEqual([
"One",
"Two",
]);
});
test("starts over from a broken file", () => {
fs.writeFileSync(file_path, "{not json");
queueBootLog({
entry: { title: "Three", category: "system", plain_text: "third" },
});
const entries = JSON.parse(fs.readFileSync(file_path, "utf-8"));
expect(entries).toHaveLength(1);
expect(entries[0].title).toBe("Three");
});
});
@@ -0,0 +1,33 @@
import fs from "fs";
import path from "path";
import { AppData } from "@/src/data/app-data";
import grabDirNames from "@/src/utils/grab-dir-names";
import type { LogEventParams } from "@/src/functions/backend/logger";
type Params = {
entry: LogEventParams;
};
/**
* Keeps a log entry for the next boot to write (`flushBootLogs`). For
* what happens right before the app restarts onto a replaced database:
* the process still has the old file open, so a `logEvent` now would
* land in a file nothing reads again. Call it after the data is in place
* (a whole-data restore empties `DATA_DIR` first).
*/
export default function queueBootLog({ entry }: Params) {
const { DATA_DIR } = grabDirNames();
const file_path = path.join(DATA_DIR, AppData.PendingBootLogsFile);
let entries: LogEventParams[] = [];
try {
const parsed = JSON.parse(fs.readFileSync(file_path, "utf-8"));
if (Array.isArray(parsed)) entries = parsed;
} catch {
// Nothing queued yet, or a broken file: start over.
}
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFileSync(file_path, JSON.stringify([...entries, entry]));
}
@@ -0,0 +1,42 @@
import restoreDbBackup from "./restore-db-backup";
import restoreDataBackup from "./restore-data-backup";
import restartApp from "./restart-app";
import queueBootLog from "./queue-boot-log";
import type { BootstrapUpload } from "./save-bootstrap-upload";
import type { LogEventParams } from "@/src/functions/backend/logger";
type Params = {
upload: BootstrapUpload;
/**
* What the restored install's log should say about it, written once
* the app is back up.
*/
log_entry: LogEventParams;
};
/**
* Puts a saved bootstrap upload in place, then restarts the app: a
* database file replaces the database (`bun-sqlite import`, as Settings >
* Backups does), a data archive replaces the whole data volume. Either
* way the open SQLite handle still points at the old file, so the process
* comes back up on the new one (and the entrypoint brings an older
* database's schema up to date).
*
* Runs only inside `startDataBackupRun`, which holds the backup run lock.
* Resolves to the name restored.
*/
export default async function restoreBootstrapUpload({
upload,
log_entry,
}: Params) {
if (upload.kind == "database") {
await restoreDbBackup({ backup_name: upload.backup_name });
} else {
await restoreDataBackup({ backup_name: upload.backup_name });
}
queueBootLog({ entry: log_entry });
restartApp();
return upload.backup_name;
}
@@ -1,5 +1,5 @@
import resolveDbBackupPath from "./resolve-db-backup-path";
import runBunSQLiteCommand from "./run-bun-sqlite-command";
import spawnBunSQLiteCommand from "./spawn-bun-sqlite-command";
type Params = {
backup_name?: string;
@@ -8,10 +8,19 @@ type Params = {
/**
* Restores a database snapshot from the backups directory. `bun-sqlite
* restore` is an interactive picker, so this uses its non-interactive
* equivalent, `bun-sqlite import <file>`.
* equivalent, `bun-sqlite import <file>`, which snapshots the current
* database first.
*
* The import runs in its own process and swaps in a new file, so this
* process's open SQLite handle still points at the old one: the caller
* restarts the app afterwards (`restartApp`), and nothing may be written
* in between (a log entry goes through `queueBootLog`).
*
* Runs only inside `startDataBackupRun`, which holds the backup run lock
* for it.
*/
export default async function restoreDbBackup({ backup_name }: Params) {
const backup_path = resolveDbBackupPath({ backup_name });
return await runBunSQLiteCommand({ args: ["import", backup_path] });
return await spawnBunSQLiteCommand({ args: ["import", backup_path] });
}
@@ -1,4 +1,5 @@
import withBackupRunLock from "./with-backup-run-lock";
import spawnBunSQLiteCommand from "./spawn-bun-sqlite-command";
type Params = {
args: string[];
@@ -11,33 +12,6 @@ type Params = {
*/
export default async function runBunSQLiteCommand({ args }: Params) {
return await withBackupRunLock({
task: async () => {
const proc = Bun.spawn(
[process.execPath, "x", "bun-sqlite", ...args],
{
cwd: process.cwd(),
env: process.env,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
},
);
const [stdout, stderr, exit_code] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
if (exit_code !== 0) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
`bun-sqlite ${args[0]} failed (exit ${exit_code})`,
);
}
return { stdout };
},
task: () => spawnBunSQLiteCommand({ args }),
});
}
@@ -0,0 +1,70 @@
import path from "path";
import AppError from "@/src/utils/app-error";
import grabDbBackupDir from "./grab-db-backup-dir";
import saveUploadedDbBackup from "./save-uploaded-db-backup";
import saveUploadedDataBackup from "./save-uploaded-data-backup";
import assertDbHasUsers from "./assert-db-has-users";
import deleteDbBackup from "./delete-db-backup";
type Params = {
file: File;
};
export type BootstrapUploadKind = "database" | "archive";
export type BootstrapUpload = {
kind: BootstrapUploadKind;
/**
* The name it was saved under: a database snapshot, or a data
* archive.
*/
backup_name: string;
};
const SQLITE_HEADER = "SQLite format 3\0";
/**
* Saves the file a new install is bootstrapped from, telling the two
* kinds apart by their first bytes rather than the file name: a SQLite
* database (a snapshot downloaded from Settings > Backups) goes to the
* database snapshots, a gzip (a whole-data archive) to the archives. A
* database with no accounts is refused and removed again. Anything else
* is refused before it's written.
*/
export default async function saveBootstrapUpload({
file,
}: Params): Promise<BootstrapUpload> {
if (!file.size) {
throw new AppError(`The uploaded file is empty`);
}
const head = await file.slice(0, SQLITE_HEADER.length).text();
if (head === SQLITE_HEADER) {
const backup_name = await saveUploadedDbBackup({ file });
try {
assertDbHasUsers({
db_path: path.join(grabDbBackupDir(), backup_name),
});
} catch (error) {
deleteDbBackup({ backup_name });
throw error;
}
return { kind: "database", backup_name };
}
const bytes = new Uint8Array(await file.slice(0, 2).arrayBuffer());
if (bytes[0] == 0x1f && bytes[1] == 0x8b) {
return {
kind: "archive",
backup_name: await saveUploadedDataBackup({ file }),
};
}
throw new AppError(
`Only a SQLite database file or a whole-data .tar.gz archive can be restored`,
);
}
@@ -0,0 +1,35 @@
type Params = {
args: string[];
};
/**
* Runs a `bun-sqlite` CLI command (same as `bunx bun-sqlite ...`) without
* taking the backup run lock: only for a caller that already holds it
* (a task inside `startDataBackupRun`). Everyone else goes through
* `runBunSQLiteCommand`.
*/
export default async function spawnBunSQLiteCommand({ args }: Params) {
const proc = Bun.spawn([process.execPath, "x", "bun-sqlite", ...args], {
cwd: process.cwd(),
env: process.env,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exit_code] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
if (exit_code !== 0) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
`bun-sqlite ${args[0]} failed (exit ${exit_code})`,
);
}
return { stdout };
}
@@ -3,6 +3,7 @@ import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
import {
HarnessContextBudgetSettingKey,
HarnessMaxToolStepsSettingKey,
HarnessModelRestSettingKey,
RunMaxPromptTokensSettingKey,
UnattendedMaxToolStepsSettingKey,
} from "@/src/dict/harness-dict";
@@ -79,17 +80,32 @@ export async function grabContextBudgetTokens() {
});
}
/**
* 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, unattended_steps, run_tokens, context_tokens] = await Promise.all([
grabHarnessMaxToolSteps(),
grabReplyMaxToolSteps(),
grabUnattendedMaxToolSteps(),
grabRunMaxPromptTokens(),
grabContextBudgetTokens(),
]);
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,
@@ -97,6 +113,7 @@ export default async function grabRunLimitsOverview() {
unattended_steps,
run_tokens,
context_tokens,
model_rest_seconds,
task_default: AppData.HarnessMaxToolSteps,
reply_default: AppData.BotReplyMaxToolSteps,
unattended_default: AppData.UnattendedMaxToolSteps,
@@ -107,6 +124,9 @@ export default async function grabRunLimitsOverview() {
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;
@@ -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) {
@@ -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 });
@@ -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 });
@@ -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,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,
});
}
@@ -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 }),
}));
}
@@ -178,6 +178,7 @@ export default async function handOverTask({
session_id: Number(session.id),
workspace_id: run_workspace_id,
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)],
}),
});
@@ -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 }
: {}),
});
}
@@ -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 }),
+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;
}
+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 }),
@@ -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 = {
@@ -98,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})` : ""}`)
@@ -195,6 +201,8 @@ export default function delegateTaskTool({
start: args.start !== false,
});
onTask?.({ task_id: Number(task.id) });
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in their own chat";
if (!handed.job_id) {
+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,
})),
];
}
@@ -21,6 +21,11 @@ type Params = {
*/
session_id?: number | string;
scopes?: StorageScope[];
/**
* 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;
};
export type WorkspaceAdminTools = {
@@ -46,6 +51,7 @@ export default async function grabWorkspaceAdminTools({
powers,
session_id,
scopes = [],
onTask,
}: Params): Promise<WorkspaceAdminTools> {
const workspace = await grabUserWorkspace({ workspace_id, user_id });
@@ -69,6 +75,7 @@ export default async function grabWorkspaceAdminTools({
workers: members,
grabTargets,
admin_workspace_ids: powers.admin_workspace_ids,
onTask,
}),
handOverScheduleTool({
user_id,
@@ -40,8 +40,10 @@ export default function askUserTool({ user_id, bot_id, session_id, workspace_id,
return {
name: "ask_user",
description: `Ask the user multiple-choice questions to be sure what they want before you act, shown as a card in the chat they answer by picking options. Use it when the request is ambiguous or open to more than one reading, when a choice is theirs to make (which target, which items, how far to go), or before something that is hard to undo, costly or visible to others, and you can't tell what they'd pick. Don't ask what they already told you, what you can find out yourself, or what any sensible choice would settle. Put every question in one call (at most one per reply). Their answers arrive as their next message${
in_task ? `. In a task, ask, then stop and report that you're waiting for their answers.` : `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
in_task
? `. In a task, ask, then stop working on what you asked about and finish your report; the card goes out with it.`
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
}`,
schema: z.object({
title: z.string().trim().max(120).optional().describe("A short heading for the card, e.g. \"Before I deploy\""),
@@ -73,7 +75,7 @@ export default function askUserTool({ user_id, bot_id, session_id, workspace_id,
return `Asked the user ${count} question${count == 1 ? "" : "s"}: the card is on your message. ${
in_task
? `Stop here and report that you're waiting for their answers.`
? `Stop working on what you asked about and finish with your report (if you asked to settle something before going on, say you're waiting for their answers).`
: `End your reply now with a short line saying what you need settled; their answers arrive as their next message.`
} Don't repeat the questions or options in your text.`;
},
@@ -32,6 +32,11 @@ type Params = {
* it may add to.
*/
members?: BUN_SQLITE_COBBLE_BOTS[];
/**
* Called with each task the run worked on through this tool, so the
* message it posts links to it (\`bot_messages.task_ids\`).
*/
onTask?: (params: { task_id: number }) => void;
};
type Args = {
@@ -133,6 +138,7 @@ export default function createTaskTool({
workspaces = [],
admin_workspace_ids = [],
members = [],
onTask,
}: Params): HarnessTool<Args> {
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
const places = workspaces.map((workspace) => `${workspace.id}: ${workspace.name}`).join("; ");
@@ -194,6 +200,8 @@ export default function createTaskTool({
});
if (twin) {
onTask?.({ task_id: Number(twin.id) });
return `Task #${twin.id} "${twin.title}" is already open with that title. Update it with update_task instead of adding a second one for the same work.`;
}
@@ -208,6 +216,8 @@ export default function createTaskTool({
created_by_bot_id: bot_id,
});
onTask?.({ task_id: Number(task.id) });
const where = place.workspace_id
? `in workspace ${place.workspace_id}, ${!place.bot_id ? "workspace-wide (every bot there works on it)" : place.bot_id == Number(bot_id) ? "yours" : `bot ${place.bot_id}'s`}`
: place.bot_id == Number(bot_id)
@@ -27,6 +27,11 @@ type Params = {
* routine, a hook call or a chatroom run.
*/
can_delete?: boolean;
/**
* Called with each task the run reads in full, adds or moves along, so
* the message it posts links to them (\`bot_messages.task_ids\`).
*/
onTask?: (params: { task_id: number }) => void;
};
/**
@@ -45,6 +50,7 @@ export default async function grabBotTaskTools({
admin_workspace_ids = [],
workspace_id,
can_delete,
onTask,
}: Params): Promise<HarnessTool[]> {
let workers: BUN_SQLITE_COBBLE_BOTS[] = [];
let members: BUN_SQLITE_COBBLE_BOTS[] = [];
@@ -72,7 +78,7 @@ export default async function grabBotTaskTools({
});
return [
listTasksTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id }),
listTasksTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id, onTask }),
createTaskTool({
user_id,
bot_id,
@@ -82,8 +88,9 @@ export default async function grabBotTaskTools({
workspaces,
admin_workspace_ids,
members,
onTask,
}),
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes }),
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes, onTask }),
...(can_delete ? [deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids })] : []),
];
}
@@ -22,6 +22,11 @@ type Params = {
* The workspace the run is in, if any.
*/
workspace_id?: number | string | null;
/**
* Called with each task the run worked on through this tool, so the
* message it posts links to it (\`bot_messages.task_ids\`).
*/
onTask?: (params: { task_id: number }) => void;
};
type Args = {
@@ -38,7 +43,7 @@ type Args = {
* Used both to plan work and to remind the user of what's pending. With
* `task_id`, one task with its brief and whole log (who did what, when).
*/
export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_workspace_ids, workspace_id }: Params): HarnessTool<Args> {
export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_workspace_ids, workspace_id, onTask }: Params): HarnessTool<Args> {
return {
name: "list_tasks",
description: `List tasks: yours (your own list and the ones you have in workspaces), the ones in ${workspace_id ? "this workspace" : "a workspace"}, or ${is_coordinator ? "every task in the install" : "every task you can reach (yours, the workspace-wide ones in your workspaces, and as a workspace's admin every task there)"}. Each line is its id, status, title, whose it is, its files and its latest note with who wrote it. Open ones come first (blocked, then doing, then to do). Use it to plan work, and to check what's still pending when the user says hello or asks what's next. A workspace-wide task is worked on by every bot in its workspace: before you work on one, read it with task_id to see its brief and its whole log (which bot did what, and when), so you pick up where the others left off instead of redoing their part.`,
@@ -62,6 +67,8 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
if (args.task_id) {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
onTask?.({ task_id: Number(task.id) });
return describeTaskLog({
task,
notes: await grabTaskNotes({ task_id: task.id! }),
@@ -26,6 +26,11 @@ type Params = {
* The run's folders, for linking a deliverable by its `[file:ID]` ref.
*/
scopes?: StorageScope[];
/**
* Called with each task the run worked on through this tool, so the
* message it posts links to it (\`bot_messages.task_ids\`).
*/
onTask?: (params: { task_id: number }) => void;
};
type Args = {
@@ -52,7 +57,7 @@ type Args = {
* which bot did what and when. The coordinator and a workspace's admin bot
* can also turn a bot's task there into a workspace-wide one.
*/
export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [], scopes = [] }: Params): HarnessTool<Args> {
export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [], scopes = [], onTask }: Params): HarnessTool<Args> {
/**
* Only the coordinator and workspace admins get the switch at all.
*/
@@ -110,6 +115,8 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
run: async ({ args }) => {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
const said: string[] = [];
onTask?.({ task_id: Number(task.id) });
const workspace_wide = !task.bot_id && Boolean(task.workspace_id);
/**
* On a workspace-wide task: what this call did, for the log.
+2 -1
View File
@@ -5,6 +5,7 @@ import TaskTimeoutError from "@/src/utils/task-timeout-error";
import withTimeout from "@/src/utils/with-timeout";
import HarnessError from "../harness-error";
import unknownToolArgs from "./unknown-tool-args";
import unknownToolMessage from "./unknown-tool-message";
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
type Params = {
@@ -47,7 +48,7 @@ async function runTool({ call, tools, signal }: Params) {
const tool = tools.find((t) => t.name == call.name);
if (!tool) {
return `Error: There is no tool called "${call.name}". Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
return unknownToolMessage({ name: call.name, tools });
}
let raw: unknown;
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test";
import unknownToolMessage from "./unknown-tool-message";
describe("unknownToolMessage", () => {
test("lists the tools for an unknown tool", () => {
expect(unknownToolMessage({ name: "nope", tools: [{ name: "a" }, { name: "b" }] })).toBe(
`Error: There is no tool called "nope". Available: a, b.`,
);
});
test("points a reply's browser call to start_task", () => {
const text = unknownToolMessage({ name: "browser_navigate", tools: [{ name: "start_task" }] });
expect(text).toContain("only exist in a task on a computer");
expect(text).toContain("call start_task");
});
test("says where computer tools live without offering start_task when there is none", () => {
const text = unknownToolMessage({ name: "computer_bash", tools: [{ name: "list_files" }] });
expect(text).toContain("only exist in a task on a computer");
expect(text).not.toContain("start_task");
});
});
+35
View File
@@ -0,0 +1,35 @@
import type { HarnessTool } from "@/src/harness/types";
type Params = {
name: string;
tools: Pick<HarnessTool, "name">[];
};
/**
* Computer tools: the app's own shell and file tools and Playwright MCP's
* browser tools, which only a task run on a computer has.
*/
const ComputerToolPattern = /^(?:computer_|browser_)/;
/**
* What a call to a tool the run doesn't have gets back. A computer or
* browser tool called from a run without one (a chat reply, seeing them in
* its history's app records) is told to start a task: a weak model called
* `browser_navigate` from a reply three times, then told the user it had
* no browser.
*/
export default function unknownToolMessage({ name, tools }: Params) {
const available = `Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
if (!ComputerToolPattern.test(name)) {
return `Error: There is no tool called "${name}". ${available}`;
}
const can_start = tools.some((t) => t.name == "start_task");
return `Error: There is no tool called "${name}" here: computer and browser tools only exist in a task on a computer.${
can_start
? " To use the computer or its browser (an open tab, a site the user is logged in to), call start_task with a clear brief, then tell the user what you're doing. You can use the computer that way; never say you can't."
: ""
} ${available}`;
}
+4 -2
View File
@@ -175,9 +175,11 @@ export type HarnessCandidate = {
provider: HarnessProviderConfig;
model: HarnessModelInfo;
/**
* `pinned`: the super admin's pick. `auto`: an automatic free pick.
* `pinned`: the setting's pick. `fallback`: one of the setting's
* fallback models, tried in order after it. `auto`: an automatic free
* pick.
*/
source: "pinned" | "auto";
source: "pinned" | "fallback" | "auto";
};
export type HarnessUsage = {
+7 -2
View File
@@ -10,11 +10,15 @@ type Params = {
* whose they were. The model's source and the fallback are filled in
* here.
*/
settings?: Omit<HarnessCallSettings, "model_source" | "fell_back_from">;
settings?: Omit<HarnessCallSettings, "model_source" | "fell_back_from" | "resting">;
/**
* The candidates that failed before this one (`withCandidates`).
*/
failed?: string[];
/**
* The candidates ahead of it passed over while resting.
*/
resting?: string[];
};
/**
@@ -23,7 +27,7 @@ type Params = {
* still get a row (no tokens), so a call is never invisible. Its settings
* say how it was made, for a message's details.
*/
export default function buildUsageCall({ harness, candidate, usage, settings, failed }: Params): HarnessUsageCall {
export default function buildUsageCall({ harness, candidate, usage, settings, failed, resting }: Params): HarnessUsageCall {
return {
harness,
provider_id: candidate.provider.id,
@@ -38,6 +42,7 @@ export default function buildUsageCall({ harness, candidate, usage, settings, fa
model_source: candidate.source,
...settings,
...(failed?.length ? { fell_back_from: failed } : {}),
...(resting?.length ? { resting } : {}),
},
};
}
+15 -2
View File
@@ -32,9 +32,10 @@ export type HarnessUsageScope = {
*/
export type HarnessCallSettings = {
/**
* `pinned`: the model picked in the setting. `auto`: an automatic pick.
* `pinned`: the model picked in the setting. `fallback`: one of its
* fallback models. `auto`: an automatic pick.
*/
model_source: "pinned" | "auto";
model_source: "pinned" | "fallback" | "auto";
/**
* Whose setting the call used: the workspace's, the bot's own or the
* install's default. Left out when the call overrode it.
@@ -55,6 +56,11 @@ export type HarnessCallSettings = {
* answered, in the order they were tried.
*/
fell_back_from?: string[];
/**
* The candidates ahead of this one passed over because they were
* resting after an earlier failure, in order.
*/
resting?: string[];
};
export type HarnessUsageCall = {
@@ -94,4 +100,11 @@ export type TokenUsageSummary = {
* How many model calls it took.
*/
calls: number;
/**
* Messages only: a model that answered text calls in place of the one
* ahead of it (it failed or was resting), and how many calls it
* answered so. Left out when every text call ran on the first choice.
*/
fallback_model?: string;
fallback_calls?: number;
};
@@ -0,0 +1,60 @@
import Link from "@moduletrace/twui/layout/Link";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { ArrowLeft } from "lucide-react";
import { twMerge } from "tailwind-merge";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { LastConversation } from "@/src/types";
import botStoneProps from "@/src/utils/bot-stone-props";
type Props = {
conversation: LastConversation;
};
/**
* Above the rail's list on settings and the rail pages: back to the
* conversation this browser was last in, the bot's own chat or a
* workspace's (named under the bot). The logo still goes to `/admin/bots`.
* Avatar only when the rail collapses. The stone stays idle: this row
* isn't live, so it never shows a status it can't keep current.
*/
export default function RailLastConversation({ conversation }: Props) {
const { bot, workspace, href } = conversation;
const title = workspace
? `Back to ${bot.name} in ${workspace.name}`
: `Back to ${bot.name}`;
return (
<Stack className="shrink-0 gap-0! items-stretch px-2 @rail:px-3 pb-3">
<Link
href={href}
title={title}
aria-label={title}
className={twMerge(
"flex shrink-0 h-14 items-center gap-3 rounded-default px-1 @rail:px-3 leading-normal text-ink",
"border-0 @rail:border @rail:border-solid @rail:border-hairline",
"hover:opacity-100 hover:bg-sunken transition-colors duration-[var(--m-fast)]",
"focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper",
)}
>
<Span className="hidden @rail:flex shrink-0 items-center justify-center text-ink-secondary">
<ArrowLeft size={16} aria-hidden />
</Span>
<Span className="shrink-0 flex items-center justify-center mx-auto @rail:mx-0">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
/>
</Span>
<Stack className="hidden @rail:flex grow min-w-0 gap-0!">
<Span className="w-full text-sm font-bold leading-5 text-ink truncate">
{bot.name}
</Span>
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
{workspace ? `In ${workspace.name}` : "Back to the conversation"}
</Span>
</Stack>
</Link>
</Stack>
);
}
+8 -3
View File
@@ -8,6 +8,7 @@ import useLiveWorkspaces from "../(hooks)/use-live-workspaces";
import { RailPages } from "@/src/dict/rail-pages-dict";
import { RailDrawerContext } from "../(data)/rail-drawer-context";
import RailHeader from "../(partials)/rail-header";
import RailLastConversation from "../(partials)/rail-last-conversation";
import RailPagesList from "../(partials)/rail-pages-list";
import RailCrewList from "../(partials)/rail-crew-list";
import RailSettingsAside from "../(partials)/rail-settings-aside";
@@ -17,9 +18,10 @@ import RailWorkspaceList from "../(partials)/rail-workspace-list";
/**
* Left rail: wordmark and Add, then the crew (pinned coordinator first,
* the latest bots, the workspaces). Inside a workspace it lists that
* workspace's crew instead; on `/admin/settings/*` a back link and the
* settings sub pages, and on routines, activity and help a back link and
* those pages (`RailPages`). Below `md` it is a slide-over drawer from the
* workspace's crew instead; on `/admin/settings/*` the settings sub pages,
* and on routines, files, usage, activity and help those pages
* (`RailPages`), both under a way back to the last conversation
* (`last_conversation`, the bot's own chat or a workspace's). Below `md` it is a slide-over drawer from the
* pane header's menu button; from `md` it is a 64px icon rail, and from
* `lg` the full 260px rail. Its own width, not the viewport's, decides
* whether it shows names (a container query), so the drawer opens full.
@@ -77,6 +79,9 @@ export default function BotsRail() {
}
>
<RailHeader show_add={!is_settings_page && !is_rail_page} />
{(is_settings_page || is_rail_page) && pageProps?.last_conversation ? (
<RailLastConversation conversation={pageProps.last_conversation} />
) : null}
<Stack className="grow min-h-0 overflow-y-auto gap-0! items-stretch px-2 @rail:px-3 pt-1 pb-3">
{is_settings_page ? (
<RailSettingsAside pathname={pathname} />
+15 -1
View File
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import grabMessagesReplies from "@/src/functions/backend/db/bots/grab-messages-replies";
import withMessageUsage from "@/src/functions/backend/db/usage/with-message-usage";
import withMessageTasks from "@/src/functions/backend/db/bots/with-message-tasks";
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
type Params = {
@@ -29,10 +30,23 @@ export default async function relayNewBotMessages({ after_id, users }: Params) {
* With what each one spent, like a loaded message, so the thread shows
* its tokens without a reload.
*/
const rows = await withMessageUsage({
const spent = await withMessageUsage({
messages: read.filter((row) => users.has(String(row.user_id))),
});
/**
* And the tracker tasks each one is about, as its own user sees them.
*/
const rows = (
await Promise.all(
[...new Set(spent.map((row) => row.user_id))].map((user_id) =>
withMessageTasks({ messages: spent.filter((row) => row.user_id == user_id), user_id }),
),
)
)
.flat()
.sort((a, b) => Number(a.id) - Number(b.id));
const replies = await grabMessagesReplies({
message_ids: rows
.filter((row) => row.reply_to_message_id)
+11
View File
@@ -8,6 +8,8 @@ import isUnknownSettingsPath from "../utils/is-unknown-settings-path";
import { SettingsDefaultPath } from "../dict/settings-pages-dict";
import grabInstallName from "../functions/backend/db/app-settings/grab-install-name";
import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-icon";
import grabLastConversation from "../functions/backend/db/bot-sessions/grab-last-conversation";
import isPagesRailPath from "../utils/is-pages-rail-path";
/**
* Routing for a local install. There are no public pages:
@@ -17,6 +19,9 @@ import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-i
* - an unknown `/admin/settings/*` page: `/admin/settings/general`
* - `/admin/*` logged out: `/auth/login`
* - `/auth/*` logged in (except logout): `/admin/bots`
*
* Settings and the rail pages also get the conversation this browser was
* last in (`last_conversation`), for their rail's way back.
*/
const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
const { user, user_types } = await userAuth({ req });
@@ -84,6 +89,12 @@ const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
user_types,
install_name: await grabInstallName().catch(() => ""),
install_icon: await grabInstallIcon().catch(() => null),
last_conversation:
user?.id && isPagesRailPath({ pathname: url.pathname })
? await grabLastConversation({ user_id: user.id, req }).catch(
() => null,
)
: null,
},
};
};
@@ -14,6 +14,7 @@ import MessageActions from "./message-actions";
import MessageReactions from "./message-reactions";
import MessageReplyQuote from "./message-reply-quote";
import MessageNoToolsChip from "./message-no-tools-chip";
import MessageTaskChips from "./message-task-chips";
import MessageUsageChip from "./message-usage-chip";
import NeedsYouChip from "./needs-you-chip";
import SpeakMessageButton from "./speak-message-button";
@@ -38,8 +39,8 @@ type Props = {
* One bot message, rendered from markdown (GFM; raw HTML is never
* rendered). The summary opening a session the bot moved into is
* headed by a link to the session it carries on from. Computers it names (`computerRef`) show as buttons that
* switch the bot to them. A quoted reply sits above it, its reactions
* below, and a row under it replies, reacts, reads it aloud and shows
* switch the bot to them. A quoted reply sits above it, the tracker tasks
* it's about and its reactions below, and a row under it replies, reacts, reads it aloud and shows
* why it needs you. Its text can be selected and quoted.
*
* Memoized: a message only renders (and parses its markdown) again when
@@ -75,6 +76,7 @@ function BotMessageLine({ message, bot_name, at }: Props) {
{linkComputerRefs({ text: message.text || "" })}
</Markdown>
</Stack>
<MessageTaskChips tasks={message.tasks} />
{message.id ? (
<MessageReactions
message_id={message.id}
@@ -34,16 +34,29 @@ const OtherValue = "other";
* radios (one pick) or checkboxes (several), with "Other" and a field to
* type into when the bot allows it. Once answered, what the user picked.
*/
export default function BotQuestionField({ question_id, index, item, draft, answer, open, onChange }: Props) {
export default function BotQuestionField({
question_id,
index,
item,
draft,
answer,
open,
onChange,
}: Props) {
const single = item.kind == "single";
const picked = answer
? [...answer.choices.map((choice) => item.options[choice]), answer.other ? `Other: ${answer.other}` : ""].filter(Boolean)
? [
...answer.choices.map((choice) => item.options[choice]),
answer.other ? `Other: ${answer.other}` : "",
].filter(Boolean)
: [];
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>{`${index + 1}. ${single ? "Pick one" : "Pick any"}`}</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 font-bold text-ink break-words">{item.question}</Span>
<Span className="whitespace-pre-wrap text-[13px] leading-5 font-bold text-ink break-words">
{item.question}
</Span>
{open ? (
<Stack className="mt-2 w-full gap-2! items-stretch">
@@ -51,18 +64,37 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
<Radios
name={`question-${question_id}-${index}`}
values={[
...item.options.map((option, choice) => ({ value: String(choice), title: option })),
...(item.allow_other ? [{ value: OtherValue, title: "Other" }] : []),
...item.options.map((option, choice) => ({
value: String(choice),
title: option,
})),
...(item.allow_other
? [{ value: OtherValue, title: "Other" }]
: []),
]}
wrapperProps={{ className: "w-full flex-col items-start gap-2!" }}
labelProps={{ className: "text-[13px] leading-5 text-ink break-words cursor-pointer" }}
wrapperProps={{
className: "w-full flex-col items-start gap-2!",
}}
labelProps={{
className:
"text-[13px] leading-5 text-ink break-words cursor-pointer",
}}
changeHandler={(value) =>
onChange(
value == OtherValue
? { ...draft, choices: [], other_on: true }
: { ...draft, choices: [Number(value)], other_on: false },
? {
...draft,
choices: [],
other_on: true,
}
: {
...draft,
choices: [Number(value)],
other_on: false,
},
)
}
wrap
/>
) : (
<Stack className="w-full gap-2! items-stretch">
@@ -75,8 +107,15 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
onChange({
...draft,
choices: checked
? [...new Set([...draft.choices, choice])]
: draft.choices.filter((c) => c != choice),
? [
...new Set([
...draft.choices,
choice,
]),
]
: draft.choices.filter(
(c) => c != choice,
),
})
}
/>
@@ -85,7 +124,12 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
<BotQuestionOption
label="Other"
checked={draft.other_on}
onChange={(checked) => onChange({ ...draft, other_on: checked })}
onChange={(checked) =>
onChange({
...draft,
other_on: checked,
})
}
/>
) : null}
</Stack>
@@ -98,7 +142,9 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
placeholder="Your own answer"
maxLength={AppData.BotQuestionOtherMaxChars}
value={draft.other}
onChange={(e) => onChange({ ...draft, other: e.target.value })}
onChange={(e) =>
onChange({ ...draft, other: e.target.value })
}
/>
) : null}
</Stack>
@@ -92,6 +92,7 @@ export default function FileRefChip({ file_id }: Props) {
url={file.url}
media_type={file.media_type}
size={file.size}
full_path={file.full_path}
className="inline-flex h-6 max-w-full gap-1.5 items-center px-1.5 align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink hover:opacity-80"
>
<AttachmentIcon media_type={file.media_type as MediaType} />
@@ -38,6 +38,7 @@ export default function FileRow({ file, can_manage, busy, gallery, onDelete }: P
url={file.url}
media_type={file.media_type}
size={file.size}
full_path={file.full_path}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
@@ -14,11 +14,22 @@ export default function MessageAttachment({
media_type,
url,
thumbnail_url,
size,
full_path,
gallery,
}: BotMessageAttachment & { gallery?: FilePreviewItem[] }) {
if (media_type == "image") {
return (
<FilePreviewLink name={name} url={url} media_type={media_type} gallery={gallery} title={name} className="block">
<FilePreviewLink
name={name}
url={url}
media_type={media_type}
size={size}
full_path={full_path}
gallery={gallery}
title={name}
className="block"
>
<Img
src={thumbnail_url || url}
alt={name}
@@ -33,6 +44,8 @@ export default function MessageAttachment({
name={name}
url={url}
media_type={media_type}
size={size}
full_path={full_path}
title={name}
className="flex max-w-64 items-center gap-2 rounded-default-lg border border-solid border-hairline bg-surface px-3 py-2 text-[13px] leading-[18px] text-ink no-underline hover:border-hairline-strong"
>
@@ -0,0 +1,12 @@
import type { MessageTask } from "@/src/types";
import TaskRefChip from "./task-ref-chip";
type Props = MessageTask;
/**
* One tracker task linked under a bot message: its chip with title and
* status, opening the task.
*/
export default function MessageTaskChip({ id, title, status }: Props) {
return <TaskRefChip task_id={id} title={title} status={status} />;
}
@@ -0,0 +1,31 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import type { MessageTask } from "@/src/types";
import MessageTaskChip from "./message-task-chip";
type Props = {
tasks?: MessageTask[];
};
/**
* The tracker tasks a bot message is about, under it: every task the run
* behind it read in full, added, moved along or handed over (and the one a
* handed-over run was for), recorded by the app rather than written by the
* bot, so a message always says which tasks it concerns. Each opens the
* task.
*/
export default function MessageTaskChips({ tasks }: Props) {
if (!tasks?.length) return null;
return (
<Row className="gap-1.5! items-center flex-wrap max-w-full">
<Span className="text-[11px] leading-4 text-ink-secondary whitespace-nowrap">
{tasks.length == 1 ? "Task" : "Tasks"}
</Span>
{/* Keyed by what it shows, so a reload with a new title or status redraws it. */}
{tasks.map((task) => (
<MessageTaskChip key={`${task.id}:${task.status}:${task.title}`} {...task} />
))}
</Row>
);
}
@@ -9,17 +9,21 @@ type Props = {
/**
* What one answer cost, in the row under it beside its timestamp: the
* tokens every model call behind it spent (a chat turn, reading an image,
* making one), and the price when the provider reported it. The hover
* title breaks it down.
* making one), the price when the provider reported it, and the fallback
* model when one answered in place of the pick. The hover title breaks it
* down.
*/
export default function MessageUsageChip({ usage }: Props) {
if (!usage || usage.total_tokens <= 0) return null;
const { prompt_tokens, completion_tokens, total_tokens, cost, calls } = usage;
const { prompt_tokens, completion_tokens, total_tokens, cost, calls, fallback_model, fallback_calls } = usage;
const title = [
`${formatTokens({ tokens: prompt_tokens })} in, ${formatTokens({ tokens: completion_tokens })} out`,
`${calls} model ${calls == 1 ? "call" : "calls"}`,
typeof cost == "number" && cost > 0 ? `$${cost.toFixed(4)}` : "",
fallback_model
? `${fallback_calls ?? 1} answered by the fallback ${fallback_model}: the model ahead of it failed or was resting`
: "",
]
.filter(Boolean)
.join(" · ");
@@ -30,6 +34,7 @@ export default function MessageUsageChip({ usage }: Props) {
className="text-[11px] leading-4 text-ink-secondary tabular-nums whitespace-nowrap cursor-help"
>
{formatTokens({ tokens: total_tokens })} tokens
{fallback_model ? ` · fallback: ${fallback_model.slice(fallback_model.indexOf("/") + 1)}` : ""}
</Span>
);
}
@@ -1,26 +1,40 @@
import { useContext, useState } from "react";
import { twMerge } from "tailwind-merge";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { ListChecks } from "lucide-react";
import TaskDetailModal from "@/src/components/general/task-detail-modal";
import { TaskStatuses } from "@/src/dict/task-dict";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
type Props = {
task_id: number;
/**
* Its title, when the page already has it (a message's linked tasks):
* shown at once instead of "Task <id>".
*/
title?: string;
/**
* Its status, when known: shown after the title, and kept current as
* the task is changed in its modal.
*/
status?: string;
};
/**
* A task on the tracker named in a message (`taskRef`): a chip that opens
* the task in its own modal, read when it opens. One the user doesn't
* reach says so there.
* A task on the tracker named in a message (`taskRef`) or linked under it
* (`MessageTaskChips`): a chip that opens the task in its own modal, read
* when it opens. One the user doesn't reach says so there.
*/
export default function TaskRefChip({ task_id }: Props) {
export default function TaskRefChip({ task_id, title: initial_title, status: initial_status }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
const [title, setTitle] = useState<string>();
const [title, setTitle] = useState<string | undefined>(initial_title || undefined);
const [status, setStatus] = useState<string | undefined>(initial_status || undefined);
const [deleted, setDeleted] = useState(false);
const label = title ? `#${task_id} ${title}` : `Task ${task_id}`;
const status_title = status ? TaskStatuses.find((it) => it.value == status)?.title : undefined;
return (
<>
@@ -30,17 +44,37 @@ export default function TaskRefChip({ task_id }: Props) {
title={deleted ? "This task was deleted" : "Open the task"}
disabled={deleted}
onClick={() => setOpen(true)}
className="inline-flex h-6 max-w-full gap-1.5! flex-nowrap items-center px-1.5! py-0! align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink whitespace-nowrap hover:opacity-80 [&_.twui-button-content-wrapper]:min-w-0"
className={twMerge(
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap items-center px-1.5! py-0! align-middle rounded-default-xs border-0",
"text-[13px] font-bold leading-4 whitespace-nowrap hover:opacity-80 [&_.twui-button-content-wrapper]:min-w-0",
/**
* The ghost button sets its own dark fill and text
* (\`dark:bg-transparent\`, \`dark:text-primary-dark-text\`),
* so the chip's colours are given for both themes, like
* the link chips beside it.
*/
"bg-sunken dark:bg-sunken hover:bg-sunken dark:hover:bg-sunken",
"text-ink dark:text-ink",
)}
>
<ListChecks size={13} aria-hidden className="shrink-0" />
<Span className="min-w-0 truncate">{deleted ? `Task ${task_id} (deleted)` : label}</Span>
{status_title && !deleted ? (
<Span className="shrink-0 font-normal text-ink-secondary">{status_title}</Span>
) : null}
</Button>
<TaskDetailModal
task={open ? { id: task_id } : null}
can_manage={canManageCrew({ user_types: pageProps?.user_types })}
onClose={() => setOpen(false)}
onLoaded={({ task }) => setTitle(task.title || undefined)}
onChanged={({ task }) => setTitle(task.title || undefined)}
onLoaded={({ task }) => {
setTitle(task.title || undefined);
if (initial_status) setStatus(task.status || undefined);
}}
onChanged={({ task }) => {
setTitle(task.title || undefined);
if (initial_status) setStatus(task.status || undefined);
}}
onDeleted={() => {
setDeleted(true);
setOpen(false);
@@ -1,5 +1,5 @@
import React from "react";
import type { DataBackupRun } from "@/src/types";
import type { DataBackupRun, DataBackupRunKind } from "@/src/types";
export type DataBackupRunState = {
/**
@@ -10,6 +10,11 @@ export type DataBackupRunState = {
* Why the last run failed.
*/
error?: string;
/**
* What the run that failed was doing, so its section shows why
* (none for a run that couldn't start).
*/
error_kind?: DataBackupRunKind;
/**
* Follows a run a request just started until it ends.
*/
@@ -21,9 +26,9 @@ export type DataBackupRunState = {
};
/**
* The whole-data run the backups page is waiting on, shared by the list's
* actions, every archive row and the upload modal, so none of them starts
* another while one is going.
* The background run the backups page is waiting on (an archive, or a
* restore of either kind), shared by both lists' actions, every row and
* the upload modals, so none of them starts another while one is going.
*/
export const DataBackupRunContext = React.createContext<DataBackupRunState>({
track: () => {},
@@ -1,13 +1,17 @@
import adminFetchHandler from "@/src/functions/frontend/admin-fetch-handler";
import type { DbBackup } from "@/src/types";
import type { DataBackupRun, DbBackup } from "@/src/types";
import dayjs from "dayjs";
type Params = {
backup: DbBackup;
};
/**
* Starts restoring a snapshot. The server restores it in the background
* and restarts, so this hands back the run for the page to follow.
*/
export default async function restoreBackup({ backup }: Params) {
const confirm_msg = `Restore the database from the backup of ${dayjs(backup.created_at).format("MMM D, YYYY HH:mm:ss")}?\n\nAll current data will be replaced with the data in this backup. This cannot be undone. Consider creating a fresh backup first.`;
const confirm_msg = `Restore the database from the backup of ${dayjs(backup.created_at).format("MMM D, YYYY HH:mm:ss")}?\n\nAll current data will be replaced with the data in this backup, and the app restarts. A snapshot of the current database is taken first.`;
if (!window.confirm(confirm_msg)) {
return { success: false, cancelled: true };
@@ -24,5 +28,6 @@ export default async function restoreBackup({ backup }: Params) {
return {
success: Boolean(res.success),
msg: res.success ? undefined : res.msg || `Couldn't restore backup`,
run: res.success ? (res.singleRes as DataBackupRun | undefined) : undefined,
};
}
@@ -1,3 +1,5 @@
import type { DataBackupRun } from "@/src/types";
type Params = {
file: File;
};
@@ -5,10 +7,11 @@ type Params = {
/**
* Sends the file as multipart form data (not base64 JSON) so large dumps
* aren't inflated. The server saves it into the snapshots list, then
* restores it.
* restores it in the background and restarts, so this hands back the run
* for the page to follow.
*/
export default async function uploadRestoreBackup({ file }: Params) {
const confirm_msg = `Restore the database from "${file.name}"?\n\nAll current data will be replaced with the data in this file. This cannot be undone. Consider creating a fresh backup first.`;
const confirm_msg = `Restore the database from "${file.name}"?\n\nAll current data will be replaced with the data in this file, and the app restarts. A snapshot of the current database is taken first.`;
if (!window.confirm(confirm_msg)) {
return { success: false, cancelled: true };
@@ -28,6 +31,7 @@ export default async function uploadRestoreBackup({ file }: Params) {
return {
success: Boolean(json.success),
msg: json.success ? undefined : json.msg || `Couldn't restore backup`,
run: json.success ? (json.singleRes as DataBackupRun | undefined) : undefined,
};
} catch (error: any) {
return {
@@ -2,12 +2,12 @@ import { useContext, useEffect, useState } from "react";
import { AppContext } from "@/src/pages/__root";
import { AppData } from "@/src/data/app-data";
import adminFetchHandler from "@/src/functions/frontend/admin-fetch-handler";
import type { DataBackupRun, DataBackupStatus } from "@/src/types";
import type { DataBackupRun, DataBackupRunKind, DataBackupStatus } from "@/src/types";
import type { DataBackupRunState } from "../(data)/data-backup-run-context";
/**
* Follows a whole-data archive or restore, which runs in the background
* on the server, by polling `data-status` every `AppData.DataBackupPollMs`.
* Follows a whole-data archive or restore, or a database snapshot
* restore, which run in the background on the server, by polling `data-status` every `AppData.DataBackupPollMs`.
* An archive reloads the page once it is written. A restore restarts the
* app, so failed polls are expected and the page reloads once the status
* comes from a new boot (or after `AppData.DataRestoreWaitMs` anyway).
@@ -20,6 +20,7 @@ export default function useDataBackupRun(): DataBackupRunState {
initial?.status == "running" ? initial : undefined,
);
const [error, setError] = useState<string>();
const [error_kind, setErrorKind] = useState<DataBackupRunKind>();
useEffect(() => {
if (run?.status != "running") return;
@@ -32,6 +33,7 @@ export default function useDataBackupRun(): DataBackupRunState {
const fail = (msg: string) => {
setError(msg);
setErrorKind(active.kind);
setRun(undefined);
};
@@ -49,14 +51,19 @@ export default function useDataBackupRun(): DataBackupRunState {
current && current.boot_id != active.boot_id,
);
if (active.kind == "restore") {
if (active.kind != "archive") {
if (restarted || Date.now() > deadline) {
window.location.reload();
return;
}
if (current?.status == "failed") {
fail(current.error || `Couldn't restore archive`);
fail(
current.error ||
(active.kind == "db_restore"
? `Couldn't restore the database`
: `Couldn't restore archive`),
);
return;
}
} else if (current) {
@@ -90,10 +97,15 @@ export default function useDataBackupRun(): DataBackupRunState {
return {
run,
error,
error_kind,
track: (next) => {
setError(undefined);
setErrorKind(undefined);
setRun(next);
},
report: setError,
report: (next) => {
setError(next);
setErrorKind(undefined);
},
};
}
@@ -5,7 +5,8 @@ import Row from "@moduletrace/twui/layout/Row";
import useStatus from "@moduletrace/twui/hooks/useStatus";
import createBackup from "../(functions)/create-backup";
import UploadRestoreModal from "../(partials)/upload-restore-modal";
import { useState } from "react";
import { useContext, useState } from "react";
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
/**
* The database snapshot list's two ways in: make a fresh snapshot, or
@@ -14,6 +15,7 @@ import { useState } from "react";
export default function BackupListActions() {
const { loading, setLoading, status, setStatus } = useStatus();
const [uploading, setUploading] = useState(false);
const { run } = useContext(DataBackupRunContext);
const create_backup = async () => {
setStatus(undefined);
@@ -41,6 +43,7 @@ export default function BackupListActions() {
variant="outlined"
color="gray"
beforeIcon={<Upload />}
disabled={Boolean(run)}
onClick={() => {
setUploading(true);
}}
@@ -51,6 +54,7 @@ export default function BackupListActions() {
title="Create Backup"
beforeIcon={<DatabaseBackup />}
loading={loading}
disabled={Boolean(run)}
onClick={() => {
create_backup();
}}
@@ -0,0 +1,17 @@
import type { PropsWithChildren } from "react";
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
import useDataBackupRun from "../(hooks)/use-data-backup-run";
/**
* Follows the background run going on the server (`useDataBackupRun`)
* for the whole page, so both lists see it and neither starts another.
*/
export default function BackupRunProvider({ children }: PropsWithChildren) {
const data_backup_run = useDataBackupRun();
return (
<DataBackupRunContext.Provider value={data_backup_run}>
{children}
</DataBackupRunContext.Provider>
);
}
@@ -1,24 +1,36 @@
import { useContext } from "react";
import Tag from "@moduletrace/twui/elements/Tag";
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
import type { DataBackupRunKind } from "@/src/types";
type Props = {
/**
* True under the database snapshots, which show only a snapshot
* restore; the data archives show the rest.
*/
database?: boolean;
};
/**
* One line under the data archives' actions: the archive or restore
* running now, else why the last one failed. Nothing when neither, so the
* actions row keeps its layout either way.
* One line under a list's actions: the run of its own kind going now,
* else why the last one failed. Nothing when neither, so the actions row
* keeps its layout either way.
*/
export default function DataBackupRunNotice() {
const { run, error } = useContext(DataBackupRunContext);
export default function DataBackupRunNotice({ database }: Props) {
const { run, error, error_kind } = useContext(DataBackupRunContext);
if (run?.kind == "archive") {
return <Tag color="gray">Archiving, this can take a while...</Tag>;
}
const isMine = (kind?: DataBackupRunKind) =>
database ? kind == "db_restore" : kind != "db_restore";
if (run && isMine(run.kind)) {
if (run.kind == "archive") {
return <Tag color="gray">Archiving, this can take a while...</Tag>;
}
if (run?.kind == "restore") {
return <Tag color="warning">Restoring, the app restarts soon...</Tag>;
}
if (error) {
if (error && isMine(error_kind)) {
return <Tag color="error">{error}</Tag>;
}
@@ -2,11 +2,13 @@ import Button from "@moduletrace/twui/layout/Button";
import Tag from "@moduletrace/twui/elements/Tag";
import Row from "@moduletrace/twui/layout/Row";
import useStatus from "@moduletrace/twui/hooks/useStatus";
import type { DbBackup } from "@/src/types";
import type { DataBackupRun, DbBackup } from "@/src/types";
import restoreBackup from "../(functions)/restore-backup";
import deleteDbBackup from "../(functions)/delete-db-backup";
import RowIconButton from "@/src/components/general/row-icon-button";
import { ArchiveRestore, Download, Trash2 } from "lucide-react";
import { useContext } from "react";
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
type Props = {
backup: DbBackup;
@@ -14,17 +16,28 @@ type Props = {
/**
* One database snapshot's icon actions: restore, download or delete, with
* their own one-line status.
* their own one-line status. A restore runs in the background and restarts
* the app, so its run goes to the page to follow.
*/
export default function DbBackupRowActions({ backup }: Props) {
const { loading, setLoading, status, setStatus } = useStatus();
const { run: running, track } = useContext(DataBackupRunContext);
const busy = loading || Boolean(running);
const run = async (task: () => Promise<{ success: boolean; msg?: string }>) => {
const run = async (
task: () => Promise<{ success: boolean; msg?: string; run?: DataBackupRun }>,
) => {
setStatus(undefined);
setLoading(true);
const res = await task();
if (res.success && res.run) {
setLoading(false);
track(res.run);
return;
}
if (res.success) {
window.location.reload();
return;
@@ -43,7 +56,7 @@ export default function DbBackupRowActions({ backup }: Props) {
<RowIconButton
icon={ArchiveRestore}
title="Restore this snapshot"
disabled={loading}
disabled={busy}
onClick={() => {
run(() => restoreBackup({ backup }));
}}
@@ -64,7 +77,7 @@ export default function DbBackupRowActions({ backup }: Props) {
<RowIconButton
icon={Trash2}
title="Delete this snapshot"
disabled={loading}
disabled={busy}
onClick={() => {
run(() => deleteDbBackup({ backup }));
}}
@@ -1,5 +1,5 @@
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import UploadRestoreFields from "./upload-restore-fields";
import UploadRestoreFields from "@/src/components/general/upload-restore-fields";
import uploadRestoreBackup from "../(functions)/upload-restore-backup";
import uploadRestoreDataBackup from "../(functions)/upload-restore-data-backup";
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
@@ -10,22 +10,23 @@ type Props = {
open: boolean;
onClose: () => void;
/**
* True for an upload listing a data archive, which restarts the app.
* True for a data archive upload, false for a database file.
*/
is_data?: boolean;
};
/**
* Uploading a file and restoring it, in a modal over the list it came
* from. A database file is restored in place; a data archive replaces the
* whole data volume in the background, so the modal closes and the
* section follows the run until the app is back from its restart.
* from. Either restore runs in the background (a database file replaces
* the database, a data archive the whole data volume), so the modal
* closes and the page follows the run until the app is back from its
* restart.
*/
export default function UploadRestoreModal({ open, onClose, is_data }: Props) {
const { track } = useContext(DataBackupRunContext);
const done = ({ run }: { run?: DataBackupRun }) => {
if (!is_data || !run) {
if (!run) {
window.location.reload();
return;
}
@@ -42,7 +43,7 @@ export default function UploadRestoreModal({ open, onClose, is_data }: Props) {
description={
is_data
? "Upload a whole-data tar.gz archive. It replaces every folder and the database snapshots, a safety archive is made first, and the app restarts."
: "Upload a SQLite database file. It is saved to the snapshots list, then restored."
: "Upload a SQLite database file. It is saved to the snapshots list, then restored, and the app restarts."
}
>
{open ? (

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