Compare commits

...
22 Commits
Author SHA1 Message Date
tben 45556b3b7f Bump version to 0.19.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 13:31:34 +01:00
tben 956a6b9772 Restore a running reply's step after a reload
The thinking row's step only ever came from `server:bot-job-update`, so a
refreshed conversation sat on its label until the run's next step, and a
socket that dropped silently left it there.

The reply's step is read from the server now: with the history
(`grabSessionReplyStep` through `openSessionReplyStepSql`, the open reply
job's newest tool step) and by the catch-up (`session-messages`), which
replays it as the push it would have been. `use-reply-progress` takes it
as a seed and only ever moves forward in `bots_queue_updates` ids
(`isNewerStep`), so a read that lands just before a newer push cannot take
the row back a line, and a step from another session never shows.
2026-11-13 13:28:28 +01:00
tben 3209828723 Bump version to 0.19.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 12:56:37 +01:00
tben 0d38268fef Let a hand-over only move a task, and ask before work starts
Handing a task to another bot started it by default: it went to doing and
queued a run, so handing three tasks over "to wait for the go-ahead" ran
three jobs that each only reported they were waiting.

handOverTask now only moves the task, as to do, with no job; `start: true`
(the user asked for the work to begin now) is what sets it doing and queues
the run. hand_over_task and delegate_task pass that only when the user asked
and are told to ask first with one ask_user card for every task they named,
since a worker can't start a task once it has left its list. The UI's hand
over form gains a "Start it now" toggle, unchecked by default, and the
coordinator and workspace-admin prompts say the same.
2026-11-13 12:52:01 +01:00
tben 41be1b6fb1 Make a release mean the whole chain, watched to the end
CI / check (push) Canceled after 0s
2026-11-13 12:15:40 +01:00
tben 37bd3335ff Bump version to 0.19.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 12:12:22 +01:00
tben 0a6d7d7410 Let a worker hand on a task of its own, and stop rooms closing over live work
A worker told to hand its tasks to another bot had no tool for it: it asked
the crew instead, the coordinator answered over the Software Engineer's
still-running job (closing the room cancels it), and the answer said the
tasks were picked up. Nothing had moved.

hand_over_task passes an open task of the worker's own list to a bot it
could already ask, reporting back in its session. answer_requester and
refuse_request now refuse over a live job unless close_anyway says
otherwise. ask_user and suggest_next_steps stay out of hidden sessions,
where no card exists to answer and a bare ref reached the coordinator.
2026-11-13 12:12:18 +01:00
tben 7a0e16a6b5 Show what a chatroom's bots spent, message by message and in total 2026-11-13 11:55:58 +01:00
tben 0885e12a8b Bump version to 0.18.10
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 11:42:18 +01:00
tben 7da9003e7b Walk the user's earlier messages in the composer
Up recalls the message the user sent before (the newest from an empty
input, older ones from there), Down comes forward again and back to what
was being typed, a keystroke takes the input back, and an open mention
menu or a selection keeps the arrows. Only the user's own messages, never
a crew message.

A clear button (X, disabled while the input is empty) empties the text
without sending it, keeping the quote and the picked files.

The composer now reads ordered lists from digit markers only: Tiptap also
takes `a.` and `i.`, so a recalled "Ok. Do another pass on the browser."
came back as item 401 with "Ok." eaten as the marker, while the thread
(remark) always showed it as plain text.
2026-11-13 11:41:16 +01:00
tben b609d72888 Let a bot offer its next steps, one click from the input 2026-11-13 11:22:12 +01:00
tben 8e1084263c Bump version to 0.18.9
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 09:56:07 +01:00
tben e4e19ade1b Let a run have no limit, and make no limit the default
Every run limit was a number, so an install that wanted a bot to work
until the job was done had to guess at one, and the guess was wrong in
both directions: 300 steps cut long work short, and raising it to 10,000
made every short reply look like it had room to ramble.

- Each limit of Settings > General > Run limits can now be unlimited, and
  the three step limits are unlimited by default: a task, a chat reply and
  a routine or hook call run until their work is done, bounded by the
  job's own deadline and the run's prompt-token budget, which always
  holds. A failed model can rest for good too, until the setting changes
  or the app restarts.
- `RunLimit` (`src/utils/run-limit.ts`) is a number or `"unlimited"`, read
  by `read-run-limit` and saved as `-1` from the form (still `0` for the
  code's default), so no caller has to tell 0 from "no limit" any more.
- `run-text-loop` drops its step ceiling to Infinity, skips the low-steps
  warning and the notes that count steps left, and spends the model's own
  window when the working context is unlimited; a task run is told it has
  no step limit rather than "at most N steps", always plans first, and
  never ends exhausted.
- A rest with no end stays benched until the setting changes or the app
  restarts: saving the run limits clears the cooldowns, and the failure
  log and the "every model is resting" error say so instead of promising
  a retry in a minute.
- `token_usages` and `harness_call_failures` record `"unlimited"` as what
  the run was allowed, and the usage chip, the message details and the
  bot's own report say it rather than showing a number nobody set.
- The form labels each field (twui only draws its label with `showLabel`),
  reads a limit that's off as `Unlimited`, and fills in the default, or
  the number that was there, when its switch goes off.
- `BotStepLimitMax` is 10,000, so a limit the user picks can be as wide as
  the work needs.
2026-11-13 09:56:07 +01:00
tben 5b09e7a8db Let a bot name the setting that stopped it, and show what a run cost
A bot that hit a limit could only say "in Settings > General", and a
user asking why one answer cost so much got a guess: nothing told the bot
which page held the value, and the limits a run worked under were never
written down.

- `[setting:<section>:<field>]` renders as a pill naming the group and the
  field, opening `/admin/settings/general/<section>#<field>`
  (`src/dict/general-settings-dict.ts`, `SettingRefChip`), and every group
  of that page now has a page of its own with the same section in it:
  whoever may change it gets the form, everyone else reads the live values
  and who can raise them, since that is what a member sent there needs.
- `read_settings` gives every run the values, who may change them and the
  ref to write; `SettingsNote` tells it to name the setting, its value and
  its ref rather than pointing at a page in prose. `reviewBotReply` sends
  back a ref the app can't resolve, like a made-up file.
- `read_message_usage` reads a message's or a job's calls: the model, the
  prompt and cached tokens, what ran, and the cost drivers (steps resend
  the whole transcript, a long session re-reads it every reply), with the
  refs for the limits and for starting a session sooner.
- Every model call records the limits it ran under
  (`HarnessCallSettings.limits`, from `run-text-loop`), so a diagnosis
  compares then against today instead of assuming, and the message's
  details show them.
2026-11-13 08:47:56 +01:00
tben 1a2e7a25bb Let a provider declare its context window, and give runs room to work
A custom provider lists model ids and nothing else, so every
`harness_models.context_length` stayed null and `run-text-loop` assumed
32,000 for a model with a 1M window: 70% of that became the working
context, so the transcript was trimmed to 13,440 tokens and the run was
told to read the same files again, turn after turn, until its steps ran
out. The sync overwrites that column on every run, so editing the row by
hand never held.

- `harness_providers.context_length` is a field on the provider form
  (Settings > Models), and the sync writes it into every model that
  reports no window of its own (`modelContextLength`). Models that do
  report one keep theirs, so OpenRouter needs nothing.
- `HarnessUnknownContextWindow` (131,072) is what a run assumes when
  nothing declares a window, and `HarnessAutoMinContext` is back to
  32,000, its own job being the floor for automatic picks: at 131,072 it
  would have filtered out every 128k model.
- The defaults now suit work that takes hours: `HarnessContextBudgetTokens`
  200,000, `HarnessMaxToolSteps` 300, a task attempt at 2 hours, and tool
  results, file reads and task briefs large enough that a whole document
  arrives in one call (`HarnessToolResultMaxChars` 60,000 above
  `BotFileReadMaxChars` 55,000), so a run stops paying a call to see the
  rest of what it just read.
2026-11-13 07:30:32 +01:00
tben c892cda0eb Plan a task run before it starts, and read a file once
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A task run used to work out what the task was while spending its steps:
the same file read again to see it once more, the same folder listed
twice, a plan formed turn by turn at the price of a model call each.

- `planBotTask` spends one turn before the first step on the very system
  prompt the run then sends, so the provider's cache serves it and it
  costs little more than the plan. The bounded JSON plan
  (`BotTaskPlanSchema`) opens the run as `taskPlanNote` and shows as its
  first step line. `shouldPlanBotTask` keeps it off short runs and
  chatroom turns, and a plan that can't be written starts the run the way
  it always did.
- `runTextLoop` answers a read it already made from that answer
  (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`)
  instead of running it again; any non-read tool clears what was
  remembered, so a file read, edited and read again is read again.
2026-11-13 05:14:07 +01:00
tben b8fd60608d Stop letting a run that did nothing end as a finished task
Five honest "I did nothing" reports in a row left nothing to notice them
by, so the app now has an opinion of its own:

- A reply's wrap up offers start_task beside write_file and import_file,
  so work it can't finish in 20 steps is handed on with a brief instead of
  being promised for later.
- A run that used every step it had blocks the task it was handed
  (trackerTaskEnding), rather than leaving it open under a "run finished"
  note.
- A full workspace names the folder holding the space and whether the run
  can clear it (computerWorkspaceSpace), the agent reports the folder
  sizes with its usage, a failed measurement no longer reads as 0, and a
  daily cron logs a computer past 80% of its quota.
- A message's details count its run's calls by tool (MessageToolsRollup),
  so 242 calls read as one line rather than 242 rows.
2026-11-13 04:59:18 +01:00
tben 1bf50b717b Bump version to 0.18.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 04:42:16 +01:00
tben c6697c91cd Hold the full pull before letting go reloads it
Opening the room is easy to do by accident on a thread whose scroll is
already exhausted, so reaching the limit no longer reloads on its own: the
finger has to stay on the full room for half a second, which lights the icon
so the release is the user's decision, and a release before that closes the
room and reads nothing. A finger that rests fires no further touch moves, so
a timer notices the hold, not the moves, and dragging back down starts it
over.

The gesture's geometry and its hold now live in AppData with the other
conversation timings, and the refocus debounce both use-refocus and
use-connection-epoch were carrying separately is one AppData.RefocusGapMs.
2026-11-13 04:38:19 +01:00
tben 8d7309084f Refresh the conversation when the page comes back, and let a phone pull it
A thread that missed its pushes while the phone slept kept its thinking row
and a stale face until the page was reloaded. Every return to the page
(window focus, a hidden tab visible, back online) now reads the crew again
(api/admin/bots/live-crew -> cobble:live-crew-refreshed, taken by both
rails) and the session's latest messages, its bot's face and its task,
whether or not a reply is due, which is what the catch-up refused to do
before. The history is not reloaded: that would drop the older messages
loaded above it.

On a phone, pulling the thread up past its bottom lifts the newest message
off the edge, opening just enough room for a refresh icon (a ghost button,
no label) and letting go once that room is full reloads the conversation and
the rail, with the spinner up for at least a second. The room is written
straight onto the content as the finger moves, never through a render, the
pull owns the gesture until release, and a finger that rested first is a
selection, not a pull.
2026-11-13 04:27:08 +01:00
tben 6f26222e2c Bump version to 0.18.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 20:59:39 +01:00
tben 343fdb2d25 Make every bot ask before it widens a request
A production coordinator was asked only to create two bots. It placed
both in a workspace and handed each a task, then explained the extra
steps as the user's saved preference that new bots get put to work.

- RequestScopeNote, injected into every reply and task, says the request
  sets the scope, that memory, habits, routines and initiative never
  widen it, and that crew changes (create, place, remove, assign a
  computer, change a role) and handing work out (delegating, handing over
  a task or routine) happen only after the user asked for them: one
  ask_user card in a reply or task, and a proposal in the report where
  nobody watches (routine, hook call, chatroom).
- A decline is dropped, not done smaller and not re-offered.
- The memory sections of composeBotPrompt say memory shapes how the bot
  does the work, never what it does beyond the request.
- The default coordinator prompt says a request to create a bot is a
  request for that bot alone; existing installs keep their stored prompt
  and get the rule from the note.
2026-11-12 20:59:35 +01:00
237 changed files with 8907 additions and 623 deletions
+23 -18
View File
@@ -36,7 +36,7 @@ For the current UI read `src/layouts/bots/` (rail, workspace rail, user popover)
| DB schema sync / admin UI / backup | `bun run db:schema` / `db:admin` / `db:backup` |
| Seed super admin / sample crew | `bun run seed` (needs `SEED_SUPER_ADMIN_PASSWORD`) / `bun run seed:bots [email]` (idempotent) |
| Query DB (read-only, JSON envelope) | `bun llm-code-assistant/query-db.ts "<sql>"` |
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards |
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards (`gh run watch` in between until the image build ends) |
No linter or formatter. `bun run typecheck` and `bun run test` are the verification steps. Use `query-db.ts` to see what is actually in the database instead of reading ORM code.
@@ -68,7 +68,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Cron
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `prune-logs`.
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
### Admin CRUD API
@@ -83,7 +83,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bot types
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). A plain worker gets no work to hand out, but may pass on an open task of its own to a bot it could ask (`hand_over_task`, `hand-over-task-tool.ts`): its one permission, its own list only, and `BotTypeTargetMatrix` is left alone so it still directs no one, the targets coming from `chatroomAskableBots`. Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
### Bots, sessions, chat
@@ -92,14 +92,15 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **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'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.
- **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). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **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. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
- **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.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@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), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`.
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
@@ -112,14 +113,17 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Prompt and memory
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`.
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, chatroom). Memory, habits and the bot's own initiative never widen a request.
### Queue (`bots_queue`)
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`) and chatroom turns. A plan that can't be written or read starts the run unplanned, never blocks it.
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
@@ -129,7 +133,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
### Chatrooms (`chatrooms`)
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). Closing is what cancels a room's jobs, so `answer_requester` and `refuse_request` refuse while a member job still runs (`grabChatroomOpenJobs`, `chatroomOpenJobsWarning`) unless given `close_anyway`: a coordinator that answered over a live run once killed the very work it was asked for, then reported it picked up. A coordinator's turn creates no task and moves none (`chatroomCoordinatorNote`): a task is handed over by the bot that has it or by the user. A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. A room shows what it cost the way a conversation's messages do: each message carries its `MessageUsageChip` and the Details modal (read through the room's own `api/admin/chatrooms/message-details`, which checks the room's user), and above the thread `ChatroomUsageSummary` totals the room (`usage` on its summary, from `grabChatroomUsage`: every model call counted by its run's `bot_sessions.chatroom_id`, a turn still running included, with the room's failed calls and the same split by bot). **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
### Workspaces
@@ -141,7 +145,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
- Only `/home/gem/workspace` is mounted, from `DATA_DIR/computers/<id>` (with `bots/`, `workspaces/`, marker `AppData.ComputerWorkspaceMarker`), plus the browser profile; the rest of home lives in the container.
- **Browser profile:** `DATA_DIR/computer-browsers/<id>` mounted at `~/.cobble-browser`, which the agent starts Chrome with (`--user-data-dir`, `--password-store=basic` so the cookies' key is the same in every container), so logins, extensions and site permissions survive restarts and recreates. Seed prefs (`computer-browser-preferences.ts`) are written only when missing; stale `Singleton*` links are removed before each provision and before each Chrome start. The agent stops Chrome with TERM on `docker stop`, so the profile is saved. **Its regenerable cache is cleared at every start** (`pruneProfileCache`: HTTP and code caches, shader/GPU caches, extension assets, the component updater's CRX cache, only while no browser runs) and the HTTP cache is capped at `DiskCacheMaxBytes` (`--disk-cache-size`), so the mounted profile holds logins rather than gigabytes. **An idle browser is parked:** the virtual screen has no GPU or window manager, so the tab in front is always on show and drawn in software at full rate (one animated site took a core or two); after `COBBLE_BROWSER_PARK_AFTER_SECONDS` (default 180) without a `/mcp` call or screen view the agent puts a blank tab in front of each site on show (`createBrowserParking`, over its own CDP client), and the next `/mcp` call or view brings them back first. Pages are composited in software (`--disable-gpu-compositing`, WebGL unchanged) and the policy sets `TabDiscardingExceptions: ["*"]` so a parked tab never reloads. Bumping `AppData.ComputerWorkspaceLayout` recreates every computer once (`migrateComputerLayout`, skipped while a job runs on it). Default extensions (`ComputerBrowserExtensions`: Cookie-Editor, `normal_installed`: can be turned off, not removed) come from a managed policy written as root into the running container (`syncComputerBrowserPolicy`, on provision and every `sync-computers` run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (`pickReachableAddress`).
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: `--disable-gpu`, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at `LightweightFrameRate` fps), extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Chrome reads only one `--disable-features=`/`--enable-features=`, so `browserArgs` merges the agent's with the extra flags' (`mergeFeatureFlags`). Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
- **The workspace has a limit** (`computer_workspace_quota_mb`, Settings > General, default `AppData.ComputerWorkspaceQuotaMb`, 0 = none): it is the one folder on a computer mounted from the data volume, so it is what can fill the host. The agent only measures it (`GET /api/usage` -> `grabComputerUsage`, `du` cached 10s); the app refuses a write that would pass it (`computerWorkspaceRoomError` in `computer_write_file`/`computer_edit_file`), reports it after `computer_bash` and after a browser call that wrote a file (`computerWorkspaceFullWarning`, screenshots and downloads included) and bash still works, since it is how a bot cleans up. A run's caches go to the account's own home inside the container, never its folder (`computerCacheEnv`).
- **The workspace has a limit** (`computer_workspace_quota_mb`, Settings > General, default `AppData.ComputerWorkspaceQuotaMb`, 0 = none): it is the one folder on a computer mounted from the data volume, so it is what can fill the host. The agent measures it (`GET /api/usage` -> `grabComputerUsage`, `du` cached 10s, per-folder figures with it: `bots/<id>` and `workspaces/<id>`, highest first); the app refuses a write that would pass it (`computerWorkspaceRoomError` in `computer_write_file`/`computer_edit_file`), reports it after `computer_bash` and after a browser call that wrote a file (`computerWorkspaceFullWarning`, screenshots and downloads included) and bash still works, since it is how a bot cleans up. A refusal names the folder holding the space and whether the run can clear it (`computerWorkspaceSpace`: its own folder or its workspace's, else another bot's, which it can only report); nothing prunes that folder, so the daily `warn-computer-workspaces` cron logs an install past the quota rather than letting it fill quietly. A run's caches go to the account's own home inside the container, never its folder (`computerCacheEnv`).
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
@@ -161,7 +165,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -213,21 +217,21 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
- **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`. 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 run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`) for a saving turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines.
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, `hand_over_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
### Token usage
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`).
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`, including `limits`: the steps, run tokens and context the run was held to, so a bot can explain a cost against them with `read_message_usage`).
- Attribution through an `AsyncLocalStorage` scope (`src/harness/usage/harness-usage-scope.ts`) entered once in `run-bot-job.ts`; merged, not replaced; `null` clears a field. `withUsageScope` / `runWithFallbackScope` for calls outside a run. No owner, no row.
- Every failed model call also writes a `harness_call_failures` row (`recordHarnessFailure`, beside the log in `withCandidates`: model, pick, HTTP status, the provider's reason, rest), same attribution, no foreign keys, pruned with the logs' retention by `prune-logs`.
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons).
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons, and the run's calls counted by tool from `bot_messages.tool_log` in `MessageToolsRollup`: 242 model calls read differently once it says `computer_bash` 210, `start_task` 0).
- `/admin/usage` (crew managers). **Days are local, not UTC:** group with `date(created_at / 1000, 'unixepoch', 'localtime')`; never name a local day with `toISOString().slice(0, 10)` (`bucket-usage-days.test.ts` pins this). Bars use static `h-*` classes from `(data)/usage-bar-heights.ts`.
### Installer and release
@@ -237,6 +241,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **App networks:** extra docker networks for the app's own container (never computers) are the app setting `app_extra_networks` (Settings > General, super admin, picked from the networks docker lists, `listJoinableNetworks`), joined by the app itself over the docker socket (`syncAppNetworks`) at boot, on save and every 5 minutes, so they outlast `install.sh` recreating the container; the installer's `--extra-network` still works beside it.
- Plain HTTP only; TLS is the proxy's job. Container: `--network cobble`, `.env` read-only at `/app/.env`, docker socket, `MAIN_SERVER=1`, `--init`, `--cpus 1 --memory 2048m` by default.
- Publishing: `scripts/publish-github.sh` / `publish-gitea.sh` sharing `scripts/lib/publish-*.sh` (tested by `scripts/publish-tools.test.ts`). A GitHub release triggers `.github/workflows/release.yml` (amd64 + arm64 to `ghcr.io/moduletrace/cobble`); `mirror-gitea.sh` copies to `git.tben.me/moduletrace/cobble` (CI can't reach the VPN). **Bump `package.json`'s `version` with a release.** CI (`ci.yml`) runs typecheck and tests. Dockerfile pins Bun 1.4.3.
- **A release is done when every artifact exists, not when the tag is pushed.** Publishing (`publish`/`release`/`ship`, any of them) means the whole chain, run by you and watched to the end: `publish:github`, `publish:gitea`, then `gh run watch` until the image build succeeds, then `mirror:gitea` (it has nothing to copy until that build finishes). Report each artifact with its link, and say plainly (with the reason) if one fails or is still building: never hand back a tag and leave the rest as a note for the user.
## Admin routes
@@ -244,7 +249,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`).
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Each group of General also has a page of its own (`/admin/settings/general/<section>`, keyed in `src/dict/general-settings-dict.ts`, linked from the group's title): anyone who may read it sees its values (`SettingsReadOnlyValues`), only its owning role gets the form. A bot points at one with `read_settings` and a `[setting:section:field]` ref, so every limit refusal or cost answer names the page and value to change. 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`. What an archive leaves out is decided in one place, `listArchiveExclusions` (`--no-wildcards --exclude-from`): `DATA_DIR/computers` (a computer's workspace is the computer's own state, so `AppData.DataBackupsKept` copies of it never fill the volume and a restore neither empties nor copies that folder), each Chrome profile's caches (the profile is kept for its logins, a few MB against hundreds of MB of HTTP and code caches), `db/.backups` (that is the database snapshots' own list) and `.bun-sqlite`. A restore keeps the running install's `db/.backups` (copied aside and put back), since no archive carries them. 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`.
+1
View File
@@ -60,6 +60,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3",
},
"peerDependencies": {
+10 -4
View File
@@ -4,11 +4,17 @@ import sendJson from "./send-json";
import { workspaceUsage } from "./workspace-usage";
/**
* `GET /api/usage`: how much the computer's workspace holds
* (`workspaceUsage`). Only the size: what may be written there is the
* `GET /api/usage`: what the computer's workspace holds, and its biggest
* folders (`workspaceUsage`). Only sizes: what may be written there is the
* app's call (`grabComputerWorkspaceQuotaBytes`), so changing the limit
* needs no new container.
* needs no new container. The folders are how a full one is told apart from
* a bot's own overrun, which the app says in its refusal.
*/
export default async function handleUsage({ res }: { req: IncomingMessage; res: ServerResponse }) {
sendJson({ res, body: { used_bytes: await workspaceUsage(), workspace_dir: AgentConfig.WorkspaceDir } });
const { bytes, folders } = await workspaceUsage();
sendJson({
res,
body: { used_bytes: bytes, workspace_dir: AgentConfig.WorkspaceDir, folders },
});
}
+112 -19
View File
@@ -2,11 +2,34 @@ import { execFile } from "node:child_process";
import { AgentConfig } from "./config";
/**
* When the workspace was last measured, and what it held: the whole
* folder, every bot's and user's included, since that is what grows on the
* data volume.
* One folder inside the workspace, with what it holds: `bots/9` is a bot's
* folder, `workspaces/3` a workspace's shared one.
*/
let measured = { bytes: 0, at: 0 };
export type WorkspaceFolderUsage = {
/**
* Relative to the workspace root, e.g. `bots/9`.
*/
path: string;
bytes: number;
};
/**
* What the workspace holds, and the biggest folders in it. The whole
* folder, every bot's and user's included, is what grows on the data
* volume; the folders are what says whose it is.
*/
export type WorkspaceUsage = {
bytes: number;
folders: WorkspaceFolderUsage[];
};
/**
* When the workspace was last measured, and what it held. A measurement
* that fails keeps the last one: reporting 0 would let writes through a
* quota the app can't see (and `du` on a workspace full of small files can
* outlast its timeout).
*/
let measured: { usage: WorkspaceUsage; at: number } | null = null;
/**
* Measuring walks the whole workspace, so a run writing several files in a
@@ -16,29 +39,99 @@ let measured = { bytes: 0, at: 0 };
const CacheMs = 10_000;
/**
* How many bytes the workspace holds, measured with `du` (which reads the
* folders in C) and reused for `CacheMs`.
* How many of the biggest folders are named: enough that the one filling
* the volume is there, few enough to say in a sentence.
*/
export async function workspaceUsage() {
if (measured.at && Date.now() - measured.at < CacheMs) return measured.bytes;
const FoldersShown = 5;
measured = { bytes: await measureWorkspace(), at: Date.now() };
/**
* The workspace's folders whose size is reported: a bot's, a workspace's,
* and anything else sitting at the top.
*/
const GroupedFolders = ["bots", "workspaces"];
return measured.bytes;
/**
* What the workspace holds, measured with `du` (which reads the folders in
* C) and reused for `CacheMs`.
*/
export async function workspaceUsage(): Promise<WorkspaceUsage> {
if (measured && Date.now() - measured.at < CacheMs) return measured.usage;
const usage = await measureWorkspace();
if (!usage) return measured?.usage || { bytes: 0, folders: [] };
measured = { usage, at: Date.now() };
return usage;
}
/**
* The workspace's size through `du` (bytes), 0 when it can't be read: a
* missing folder holds nothing.
* The workspace's size and its biggest folders through `du`, or null when
* it can't be read.
*/
function measureWorkspace() {
return new Promise<number>((resolve) => {
execFile("du", ["-s", "-B1", "--", AgentConfig.WorkspaceDir], { timeout: 30_000 }, (error, stdout) => {
if (error) return resolve(0);
return new Promise<WorkspaceUsage | null>((resolve) => {
execFile(
"du",
["-B1", "--max-depth=2", "--", AgentConfig.WorkspaceDir],
{ timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
(error, stdout) => {
if (error) return resolve(null);
const bytes = Number(String(stdout).trim().split(/\s+/)[0]);
resolve(Number.isFinite(bytes) && bytes > 0 ? bytes : 0);
});
resolve(parseDu(String(stdout)));
},
);
});
}
/**
* `du`'s lines (`<bytes>\t<path>`) as the whole workspace and the folders
* that make it up: each bot's and each workspace's own, and whatever else
* sits at the top. A passthrough folder (`bots`, `workspaces`) is only
* counted through its children.
*/
function parseDu(stdout: string): WorkspaceUsage {
const root = AgentConfig.WorkspaceDir.replace(/\/+$/, "");
const deep: WorkspaceFolderUsage[] = [];
const shallow = new Map<string, number>();
let bytes = 0;
for (const line of stdout.split("\n")) {
const [size, path] = line.split("\t");
const value = Number(size);
if (!path || !Number.isFinite(value) || value <= 0) continue;
if (path == root) {
bytes = value;
continue;
}
const relative = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : "";
const [top, second] = relative.split("/");
if (!top || !GroupedFolders.includes(top)) {
shallow.set(relative, value);
continue;
}
if (second) deep.push({ path: relative, bytes: value });
else shallow.set(relative, value);
}
const folders = [...deep, ...[...shallow].map(([path, value]) => ({ path, bytes: value }))];
/**
* A passthrough folder with children is only counted through them: its
* own total would show every bot's folder twice.
*/
const grouped = new Set(deep.map((folder) => folder.path.split("/")[0]));
return {
bytes: bytes || folders.reduce((total, folder) => total + folder.bytes, 0),
folders: folders
.filter((folder) => !(shallow.has(folder.path) && grouped.has(folder.path)))
.sort((left, right) => right.bytes - left.bytes)
.slice(0, FoldersShown),
};
}
+47
View File
@@ -1797,6 +1797,48 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "bot_suggestions",
tableDescription: `Next steps a bot suggests under its answer (\`suggest_next_steps\`): buttons that put the step in the user's input. Unlike \`bot_questions\`, nothing waits on them`,
fields: [
{
fieldName: "title",
fieldDescription: `A short heading for the row of buttons; empty for "Next steps"`,
dataType: "TEXT",
},
{
fieldName: "steps",
fieldDescription: `JSON array of the suggested steps, each put in the user's input when clicked`,
dataType: "TEXT",
},
{
fieldName: "user_id",
fieldDescription: `The user they were suggested to, who alone reads them. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "bot_id",
fieldDescription: `The bot that suggested them. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "session_id",
fieldDescription: `The conversation they were suggested in. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "workspace_id",
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
dataType: "INTEGER",
},
],
indexes: [
{
indexName: "idx_bot_suggestions_session_id",
indexTableFields: ["session_id"],
},
],
},
{
tableName: "bot_graphics",
tableDescription: `A visual a bot made for a user (a chart, diagram, timeline or report) as one self-contained HTML document. Served by the app at \`/graphics/<id>\` in a sandbox with no network and an origin of its own, so it never runs with the viewer's session. Per user like the conversation it was made in; an edit replaces the HTML and bumps \`version\``,
@@ -2646,6 +2688,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
options: [0, 1],
defaultValue: 1,
},
{
fieldName: "context_length",
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
dataType: "INTEGER",
},
{
fieldName: "last_synced_at",
fieldDescription: `Unix timestamp of the last model list sync`,
+45 -1
View File
@@ -24,6 +24,7 @@ export const BunSQLiteTables = [
"secret_requests",
"install_requests",
"bot_questions",
"bot_suggestions",
"bot_graphics",
"workspaces",
"workspace_bots",
@@ -1164,6 +1165,45 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
/**
* A short heading for the row of buttons; empty for "Next steps"
*/
title?: string;
/**
* JSON array of the suggested steps, each put in the user's input when clicked
*/
steps?: string;
/**
* The user they were suggested to, who alone reads them. Not a foreign key
*/
user_id?: number | "";
/**
* The bot that suggested them. Not a foreign key
*/
bot_id?: number | "";
/**
* The conversation they were suggested in. Not a foreign key
*/
session_id?: number | "";
/**
* The session's workspace; null for the bot's own chat. Not a foreign key
*/
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_GRAPHICS = {
/**
* The unique identifier of the record.
@@ -1625,6 +1665,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
*/
api_key?: string;
enabled?: 0 | 1 | "";
/**
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
*/
context_length?: number | "";
/**
* Unix timestamp of the last model list sync
*/
@@ -2822,4 +2866,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
value?: string;
}
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.5",
"version": "0.19.2",
"module": "index.ts",
"type": "module",
"private": true,
@@ -35,6 +35,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3"
},
"peerDependencies": {
+17
View File
@@ -0,0 +1,17 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
/**
* The plan a task run writes for itself before its first step
* (`planBotTask`). Validated because it comes back from a model: anything
* that doesn't fit starts the run unplanned instead of steered by
* nonsense.
*/
export const BotTaskPlanSchema = z.object({
goal: z.string().trim().min(1).max(AppData.BotTaskPlanTextMaxChars),
gather: z.array(z.string().trim().min(1)).max(AppData.BotTaskPlanMaxGather).default([]),
steps: z.array(z.string().trim().min(1)).min(1).max(AppData.BotTaskPlanMaxSteps),
done: z.string().trim().max(AppData.BotTaskPlanTextMaxChars).default(""),
});
export type BotTaskPlan = z.infer<typeof BotTaskPlanSchema>;
+2 -30
View File
@@ -1,10 +1,6 @@
import {
JobStepBrowserToolInfix,
JobStepToolLabels,
JobStepToolPrefixLabels,
type BotJobUpdateKind,
} from "@/src/dict/bot-queue-dict";
import type { BotJobUpdateKind } from "@/src/dict/bot-queue-dict";
import type { TextLoopStep } from "@/src/harness/text/run-text-loop";
import toolLabel from "@/src/utils/tool-label";
/**
* Longest step line kept: the chat shows one line per step.
@@ -54,27 +50,3 @@ function firstLine({ text }: { text: string | null }) {
return line.length > MaxStepChars ? `${line.slice(0, MaxStepChars - 1)}…` : line;
}
function toolLabel({ name }: { name: string }) {
if (name.includes(JobStepBrowserToolInfix)) return JobStepToolPrefixLabels.browser_ as string;
const prefix = Object.keys(JobStepToolPrefixLabels).find((p) => name.startsWith(p));
return JobStepToolLabels[name] || (prefix && JobStepToolPrefixLabels[prefix]) || `Using ${readableToolName({ name })}`;
}
/**
* A tool name in words: `get_weather` reads "get weather", and an MCP
* server's `<slug>__<tool>` reads "Exa search (web search exa)".
*/
function readableToolName({ name }: { name: string }) {
const words = (part: string) => part.replace(/_+/g, " ").trim();
const [server, ...rest] = name.split("__");
const tool = words(rest.join(" "));
if (!tool) return words(name);
const server_words = words(server || "");
return `${server_words.charAt(0).toUpperCase()}${server_words.slice(1)} (${tool})`;
}
@@ -0,0 +1,56 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import parseBotTaskPlan from "./parse-bot-task-plan";
const plan = {
goal: "Ship the release notes",
gather: ["docs/changelog.md"],
steps: ["Read the changelog", "Write the notes", "Publish them"],
done: "The notes are on the site",
};
describe("parseBotTaskPlan", () => {
test("reads a plan", () => {
expect(parseBotTaskPlan({ text: JSON.stringify(plan) })).toEqual(plan);
});
test("tolerates a code fence and a sentence around the object", () => {
const fenced = `Here is the plan:\n\`\`\`json\n${JSON.stringify(plan)}\n\`\`\`\nReady.`;
expect(parseBotTaskPlan({ text: fenced })).toEqual(plan);
});
test("fills what a plan may leave out", () => {
expect(parseBotTaskPlan({ text: `{"goal":"G","steps":["one"]}` })).toEqual({
goal: "G",
gather: [],
steps: ["one"],
done: "",
});
});
test("is null when it isn't a plan", () => {
expect(parseBotTaskPlan({})).toBeNull();
expect(parseBotTaskPlan({ text: null })).toBeNull();
expect(parseBotTaskPlan({ text: "" })).toBeNull();
expect(parseBotTaskPlan({ text: "I will just do it." })).toBeNull();
expect(parseBotTaskPlan({ text: "{nope" })).toBeNull();
expect(parseBotTaskPlan({ text: `{"goal":"G"}` })).toBeNull();
expect(parseBotTaskPlan({ text: `{"goal":"","steps":["one"]}` })).toBeNull();
expect(parseBotTaskPlan({ text: `{"goal":"G","steps":[]}` })).toBeNull();
});
test("caps how much a plan may ask for", () => {
const too_many = {
goal: "G",
steps: Array.from({ length: AppData.BotTaskPlanMaxSteps + 1 }, (_, index) => `step ${index}`),
};
expect(parseBotTaskPlan({ text: JSON.stringify(too_many) })).toBeNull();
expect(
parseBotTaskPlan({
text: JSON.stringify({ ...too_many, steps: too_many.steps.slice(1), goal: "x".repeat(AppData.BotTaskPlanTextMaxChars + 1) }),
}),
).toBeNull();
});
});
+28
View File
@@ -0,0 +1,28 @@
import { BotTaskPlanSchema, type BotTaskPlan } from "./bot-task-plan-schema";
/**
* Reads the plan a planning turn answered with. Models wrap JSON in a code
* fence or a sentence whatever the prompt says, so the object is cut out
* of the answer first. Null when it isn't a plan: the run then starts the
* way it always did, since a plan is an economy and never a gate.
*/
export default function parseBotTaskPlan({ text }: { text?: string | null }): BotTaskPlan | null {
if (!text) return null;
const start = text.indexOf("{");
const end = text.lastIndexOf("}");
if (start < 0 || end <= start) return null;
let value: unknown;
try {
value = JSON.parse(text.slice(start, end + 1));
} catch {
return null;
}
const parsed = BotTaskPlanSchema.safeParse(value);
return parsed.success ? parsed.data : null;
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, test } from "bun:test";
import { TaskPlanPrompt } from "@/src/data/harness-prompts";
import type { HarnessCandidate, HarnessMessage } from "@/src/harness/types";
import type { GenerateTextParams } from "@/src/harness/text/generate-text";
import planBotTask from "./plan-bot-task";
const candidate = {
key: "1:m",
provider: { id: 1, kind: "openrouter", base_url: "https://x.test" },
model: { slug: "m", input_modalities: ["text"], output_modalities: ["text"], supports_tools: true },
source: "auto",
} as HarnessCandidate;
const plan = {
goal: "Ship the release notes",
gather: ["docs/changelog.md"],
steps: ["Read the changelog", "Write the notes"],
done: "The notes are on the site",
};
function fakeGenerate({ text }: { text: string }) {
const seen: GenerateTextParams[] = [];
const generate = (async (params: GenerateTextParams) => {
seen.push(structuredClone({ ...params, signal: undefined }));
return { text, tool_calls: [], candidate };
}) as unknown as typeof import("@/src/harness/text/generate-text").default;
return { generate, seen };
}
const messages: HarnessMessage[] = [{ role: "user", content: "Write the release notes." }];
describe("planBotTask", () => {
test("asks for the plan in one turn on the prompt the run sends anyway", async () => {
const { generate, seen } = fakeGenerate({ text: JSON.stringify(plan) });
const planned = await planBotTask({
system: "You are a bot.",
messages,
signal: new AbortController().signal,
bot_id: 3,
workspace_id: 7,
generate,
});
expect(planned).toEqual({ plan, candidate });
expect(seen.length).toBe(1);
expect(seen[0]!.messages[0]).toEqual({ role: "system", content: "You are a bot." });
expect(String(seen[0]!.messages[1]!.role)).toBe("user");
expect(String(seen[0]!.messages[1]!.content)).toContain("Write the release notes.");
expect(String(seen[0]!.messages[1]!.content)).toContain(TaskPlanPrompt);
expect(seen[0]!.bot_id).toBe(3);
expect(seen[0]!.workspace_id).toBe(7);
expect(seen[0]!.tools).toBeUndefined();
});
test("leaves the run's own opening as it was", async () => {
const { generate } = fakeGenerate({ text: JSON.stringify(plan) });
await planBotTask({ system: "You are a bot.", messages, signal: new AbortController().signal, generate });
expect(messages).toEqual([{ role: "user", content: "Write the release notes." }]);
});
test("is null when the answer isn't a plan, so the run starts unplanned", async () => {
const { generate } = fakeGenerate({ text: "I'll figure it out as I go." });
const planned = await planBotTask({
system: "You are a bot.",
messages,
signal: new AbortController().signal,
generate,
});
expect(planned).toBeNull();
});
});
+56
View File
@@ -0,0 +1,56 @@
import { TaskPlanPrompt } from "@/src/data/harness-prompts";
import generateText from "@/src/harness/text/generate-text";
import pushUserTurn from "@/src/harness/text/push-user-turn";
import type { HarnessCandidate, HarnessMessage } from "@/src/harness/types";
import type { BotTaskPlan } from "./bot-task-plan-schema";
import parseBotTaskPlan from "./parse-bot-task-plan";
type Params = {
/**
* The system prompt the run's own turns send, unchanged: this turn
* shares its cached prefix, so the plan costs little more than the
* plan itself.
*/
system: string;
/**
* What the run opens with (its brief, and what the user wrote since).
* Planned from a copy: the run's own opening is left as it is.
*/
messages: HarnessMessage[];
signal: AbortSignal;
bot_id?: number | string;
workspace_id?: number | string | null;
generate?: typeof generateText;
};
/**
* Asks the run's model for the plan before the run takes a step
* (`TaskPlanPrompt`). One turn, no tools: a plan that takes steps to write
* is the wandering it exists to avoid.
*
* Null when the answer isn't a plan, so the run starts unplanned rather
* than steered by one it can't read.
*/
export default async function planBotTask({
system,
messages,
signal,
bot_id,
workspace_id,
generate = generateText,
}: Params): Promise<{ plan: BotTaskPlan; candidate: HarnessCandidate } | null> {
const planning = structuredClone(messages);
pushUserTurn({ transcript: planning, content: TaskPlanPrompt });
const answer = await generate({
messages: [{ role: "system", content: system }, ...planning],
signal,
bot_id,
workspace_id,
});
const plan = parseBotTaskPlan({ text: answer.text });
return plan ? { plan, candidate: answer.candidate } : null;
}
+1
View File
@@ -238,6 +238,7 @@ export default async function processBotJob({
attachments: outcome.attachments,
tool_log: outcome.tool_log,
task_ids: outcome.task_ids,
exhausted: outcome.exhausted,
});
await pushBotNotice({ bot_id, ...completion });
+4 -1
View File
@@ -7,6 +7,7 @@ import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessToolUse } from "@/src/harness/types";
import replyClaimProblems from "@/src/utils/reply-claim-problems";
import replyRefIds from "@/src/utils/reply-ref-ids";
import unresolvedSettingRefs from "@/src/utils/unresolved-setting-refs";
import type { StorageScope } from "@/src/utils/storage-access";
type Params = {
@@ -24,7 +25,8 @@ type Params = {
/**
* Checks a chat reply's answer against what the app knows before it goes
* out (`replyClaimProblems`): every file and task it names must exist for
* the user (as their chips would open them), and work it says is under
* the user (as their chips would open them), every setting ref the app can
* resolve, and work it says is under
* way must have been started by this reply or still be open from this
* conversation. Returns the note that sends the answer back to be written
* again, or null when it holds up. Bots wrote "I'm scanning now" with the
@@ -52,6 +54,7 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
tool_uses,
missing_file_ids,
missing_task_ids,
unresolved_setting_refs: unresolvedSettingRefs({ text }),
has_open_work: await hasOpenWork({ bot_id, session_id }),
});
+41 -10
View File
@@ -3,9 +3,11 @@ import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings
import { AppData } from "@/src/data/app-data";
import {
ActionCheckNote,
RequestScopeNote,
QuestionsNote,
AskCrewNote,
SecretsNote,
SettingsNote,
GraphicsNote,
botFilesNote,
chatReplyNote,
@@ -15,6 +17,7 @@ import {
CoordinatorSoloNote,
TasksNote,
TaskReminderNote,
HandOverTaskNote,
workspaceAdminNote,
WorkspaceLearningNote,
openRunsNote,
@@ -59,6 +62,7 @@ import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import type { BotMessageWithAttachments } from "@/src/types";
import type { HarnessMessage } from "@/src/harness/types";
import type { BotJobContext, BotJobOutcome } from "./types";
@@ -209,8 +213,9 @@ export default async function runBotReply({
*/
const proposals: string[] = [];
/**
* The secrets the bot showed (`show_secret`) and the graphics it made
* or changed, whose chips the reply always carries.
* The secrets the bot showed (`show_secret`), the graphics it made
* or changed, and the next steps it suggested: their chips the reply
* always carries, without needing the user.
*/
const shown: string[] = [];
/**
@@ -327,6 +332,12 @@ export default async function runBotReply({
* admin is told who leads it.
*/
const can_delegate = tools.some((tool) => tool.name == "delegate_task");
/**
* A worker passes on a task of its own (`hand_over_task`): the reply says
* where it went and that it needs the run id, so no one claims a hand-over
* that didn't happen.
*/
const can_hand_over = tools.some((tool) => tool.name == "hand_over_task");
const lead = led as WorkspaceAdminTools | null;
const crew_note = powers.is_coordinator
? can_delegate
@@ -353,9 +364,12 @@ export default async function runBotReply({
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
TasksNote,
TaskReminderNote,
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
QuestionsNote,
RequestScopeNote({ can_ask: Boolean(attended) }),
attended ? QuestionsNote : "",
SecretsNote,
SettingsNote,
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
@@ -404,13 +418,30 @@ export default async function runBotReply({
onRequest: ({ ref }) => proposals.push(ref),
onShow: ({ ref }) => shown.push(ref),
}),
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
/**
* Only where the user follows the conversation: a chatroom's
* hidden session has no card they could answer, and a
* question there was once shown to the coordinator as a bare
* ref, its answer never reaching the bot.
*/
...(attended
? [
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => shown.push(ref),
}),
]
: []),
...(has_past_sessions
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
: []),
+122 -57
View File
@@ -6,8 +6,10 @@ import workspaceAdminsNote from "./workspace-admins-note";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import {
ActionCheckNote,
RequestScopeNote,
QuestionsNote,
SecretsNote,
SettingsNote,
GraphicsNote,
botFilesNote,
ComputerFilesNote,
@@ -22,6 +24,7 @@ import {
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
taskPlanNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -33,6 +36,7 @@ import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-comp
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import runTextLoop from "@/src/harness/text/run-text-loop";
import { isUnlimitedLimit, smallerRunLimit } from "@/src/utils/run-limit";
import openComputerTools from "@/src/harness/tools/computer/open-computer-tools";
import openBotBrowsers, { type OpenBotBrowsers } from "@/src/harness/tools/browsers/open-bot-browsers";
import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/extensions/open-bot-extensions";
@@ -41,6 +45,7 @@ import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-k
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool";
import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
@@ -65,6 +70,8 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
import taskIncoming from "./task-incoming";
import planBotTask from "./plan-bot-task";
import shouldPlanBotTask from "./should-plan-bot-task";
import pushUserTurn from "@/src/harness/text/push-user-turn";
import type { HarnessMessage } from "@/src/harness/types";
@@ -157,6 +164,11 @@ export default async function runBotTask({
signal,
}).catch(() => "");
const take_overs: string[] = [];
/**
* The next steps the bot suggested: added to the message without
* needing the user.
*/
const suggestions: string[] = [];
/**
* Files the bot wrote and asked to send with its report.
*/
@@ -279,6 +291,13 @@ export default async function runBotTask({
in_task: true,
onAsk: ({ ref }) => take_overs.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => suggestions.push(ref),
}),
]
: []),
...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []),
@@ -369,9 +388,19 @@ export default async function runBotTask({
*/
const task_steps = await grabHarnessMaxToolSteps();
const install_steps =
scheduled || hooked ? Math.min(task_steps, await grabUnattendedMaxToolSteps()) : task_steps;
scheduled || hooked
? smallerRunLimit({ a: task_steps, b: await grabUnattendedMaxToolSteps() })
: task_steps;
const budget = Math.floor(Number(params.max_steps) || 0);
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
const max_steps = budget > 0 ? smallerRunLimit({ a: budget, b: install_steps }) : install_steps;
/**
* What the run is told it has. Unlimited is said as such rather
* than as a number: the job's deadline still ends it, and a run
* told "at most 0 steps" would stop before it began.
*/
const steps_note = isUnlimitedLimit(max_steps)
? `This run has no step limit: work until the job is done. Its job still stops it after a while, so save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
: `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`;
/**
* What the user wrote since the run was queued, for a run they
@@ -400,61 +429,92 @@ export default async function runBotTask({
}
}
const system = [
prompt,
carry_over,
TaskRunNote,
steps_note,
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
TasksNote,
ActionCheckNote,
RequestScopeNote({ can_ask }),
can_ask ? QuestionsNote : "",
SecretsNote,
SettingsNote,
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
powers.is_coordinator
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
: admin_tools.some((tool) => tool.name == "update_workspace")
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
: "",
powers.is_coordinator || powers.is_workspace_admin
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
powers.is_coordinator || hooked || params.chatroom_id
? ""
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
computer && computer_shared
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
: computer
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
: workspace_id
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
: `You have no computer for this task.`,
computers.length > 1
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
: "",
computer?.envs.length
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
.join("\n")}`
: "",
composeBrowsersNote({
browsers: browsers.browsers,
has_computer_browser: Boolean(computer),
run_kind: browser_run_kind,
}),
skills.note,
knowledge.note,
extensions.note,
]
.filter(Boolean)
.join("\n\n");
/*
* The plan this run works from, written in one turn before it takes
* a step (`planBotTask`). It shares this run's prompt, so it costs
* little more than the plan, and it saves the steps a long run
* spends finding out what it is doing. A run whose plan can't be
* written starts the way it always did.
*/
const planned = shouldPlanBotTask({ max_steps, in_chatroom: Boolean(params.chatroom_id) })
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
(error) => {
if (signal.aborted) throw error;
return null;
},
)
: null;
if (planned) {
pushUserTurn({ transcript: opening, content: taskPlanNote({ plan: planned.plan }) });
await report({
index: -1,
text: `Plan: ${planned.plan.goal}`,
tool_calls: [],
candidate: planned.candidate,
});
}
const result = await runTextLoop({
system: [
prompt,
carry_over,
TaskRunNote,
`This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`,
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
TasksNote,
ActionCheckNote,
can_ask ? QuestionsNote : "",
SecretsNote,
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
powers.is_coordinator
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
: admin_tools.some((tool) => tool.name == "update_workspace")
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
: "",
powers.is_coordinator || powers.is_workspace_admin
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
powers.is_coordinator || hooked || params.chatroom_id
? ""
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
computer && computer_shared
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
: computer
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
: workspace_id
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
: `You have no computer for this task.`,
computers.length > 1
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
: "",
computer?.envs.length
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
.join("\n")}`
: "",
composeBrowsersNote({
browsers: browsers.browsers,
has_computer_browser: Boolean(computer),
run_kind: browser_run_kind,
}),
skills.note,
knowledge.note,
extensions.note,
]
.filter(Boolean)
.join("\n\n"),
system,
messages: opening,
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
max_steps,
@@ -487,11 +547,16 @@ export default async function runBotTask({
...withTakeOverRefs({
text: computer ? computer.redact(text) : text,
refs: take_overs,
shown,
shown: [...shown, ...suggestions],
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
/**
* The wrap up was announced (`steps` counts its turns), so the
* run never got to the end of the work it was given.
*/
exhausted: !isUnlimitedLimit(max_steps) && result.steps > max_steps,
};
} finally {
await extensions?.close();
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import shouldPlanBotTask from "./should-plan-bot-task";
describe("shouldPlanBotTask", () => {
test("plans a run long enough to repay the plan", () => {
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps })).toBe(true);
expect(shouldPlanBotTask({ max_steps: 200 })).toBe(true);
});
test("always plans a run with no step limit: it has the steps to repay it", () => {
expect(shouldPlanBotTask({ max_steps: UnlimitedLimit })).toBe(true);
});
test("leaves a short run alone: its first turn is its plan", () => {
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps - 1 })).toBe(false);
expect(shouldPlanBotTask({ max_steps: 1 })).toBe(false);
});
test("never plans a chatroom turn, not even an unlimited one", () => {
expect(shouldPlanBotTask({ max_steps: 200, in_chatroom: true })).toBe(false);
expect(shouldPlanBotTask({ max_steps: UnlimitedLimit, in_chatroom: true })).toBe(false);
});
});
+27
View File
@@ -0,0 +1,27 @@
import { AppData } from "@/src/data/app-data";
import { isUnlimitedLimit, type RunLimit } from "@/src/utils/run-limit";
/**
* Whether a task run plans before its first step (`planBotTask`).
*
* Planning is an economy, not a rule. It costs one turn, mostly served
* from the cache the run's own turns share, and it saves the steps a run
* spends working out what it is doing. A run too short to repay that gets
* nothing from it: its first turn is its plan. An unlimited run always
* plans, since it has the steps to repay it.
*
* A chatroom turn is never planned: it is short, it has almost no tools,
* and nobody follows it.
*/
export default function shouldPlanBotTask({
max_steps,
in_chatroom,
}: {
max_steps: RunLimit;
in_chatroom?: boolean;
}) {
if (in_chatroom) return false;
if (isUnlimitedLimit(max_steps)) return true;
return max_steps >= AppData.BotTaskPlanMinSteps;
}
+7
View File
@@ -62,6 +62,13 @@ export type BotJobOutcome = {
* kept on the result message as `task_ids`.
*/
task_ids?: number[];
/**
* The run used every step it was allowed and stopped before it finished
* (its wrap up was announced). A handed-over task stays open only when
* the run did no work, so the task is blocked rather than left `doing`
* (`noteTrackerTask`).
*/
exhausted?: boolean;
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import takeOverRef from "@/src/utils/take-over-ref";
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
import withTakeOverRefs from "./with-take-over-refs";
const ref = takeOverRef({ id: 1, mode: "browser" });
@@ -21,4 +22,13 @@ describe("withTakeOverRefs", () => {
test("leaves a message without a take-over alone", () => {
expect(withTakeOverRefs({ text: "Done.", refs: [] })).toEqual({ result: "Done.", needs_you: false });
});
test("adds suggested next steps without needing the user", () => {
const suggestions = botSuggestionRef({ id: 4 });
expect(withTakeOverRefs({ text: "Done.", refs: [], shown: [suggestions] })).toEqual({
result: `Done.\n\n${suggestions}`,
needs_you: false,
});
});
});
+5 -3
View File
@@ -6,8 +6,9 @@ type Params = {
*/
refs: string[];
/**
* The secrets it showed (`secretRef`): added the same way, but they
* don't need the user.
* The secrets it showed (`secretRef`) and the next steps it suggested
* (`botSuggestionRef`): added the same way, but they don't need the
* user, so neither makes the message.
*/
shown?: string[];
};
@@ -16,7 +17,8 @@ type Params = {
* A job's message with every take-over the bot asked for in it and every
* proposal it made: refs the bot didn't write itself are added at the
* end, so the user always gets the button. A message asking for either
* needs the user.
* needs the user; secrets it showed and next steps it suggested are added
* without asking anything of them.
*/
export default function withTakeOverRefs({ text, refs, shown = [] }: Params) {
const missing = [...new Set([...refs, ...shown])].filter((ref) => !text.includes(ref));
+26 -2
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import Checkbox from "@moduletrace/twui/form/Checkbox";
import Form from "@moduletrace/twui/form/Form";
import Select from "@moduletrace/twui/form/Select";
import Textarea from "@moduletrace/twui/form/Textarea";
@@ -24,6 +25,12 @@ type Props<T> = {
* Offer a note added to the brief (a task's hand-over).
*/
with_note?: boolean;
/**
* Offer to start the work now (a task's hand-over). Off by default:
* handing a task over only moves it, it never starts the work unless
* the user asks for that here.
*/
with_start?: boolean;
onHandedOver: (params: { saved: T; msg: string }) => void;
onCancel: () => void;
};
@@ -39,12 +46,14 @@ export default function HandOverForm<T extends { [k: string]: any }>({
submit_path,
body,
with_note,
with_start,
onHandedOver,
onCancel,
}: Props<T>) {
const [targets, setTargets] = useState<HandOverTarget[]>();
const [bot_id, setBotId] = useState<number>();
const [note, setNote] = useState("");
const [start, setStart] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -73,14 +82,19 @@ export default function HandOverForm<T extends { [k: string]: any }>({
return;
}
if (!window.confirm(`Hand ${what} over to ${target.name}?`)) return;
if (!window.confirm(`Hand ${what} over to ${target.name}${with_start && start ? " and start it now" : ""}?`)) return;
setLoading(true);
setError(undefined);
const res = await postAdminApi<T>({
path: submit_path,
body: { ...body, bot_id: target.id, instructions: with_note && note.trim() ? note : undefined },
body: {
...body,
bot_id: target.id,
instructions: with_note && note.trim() ? note : undefined,
...(with_start ? { start } : {}),
},
});
setLoading(false);
@@ -121,6 +135,16 @@ export default function HandOverForm<T extends { [k: string]: any }>({
disabled={loading}
/>
) : null}
{with_start && targets?.length ? (
<Checkbox
title="Start it now"
label="Start it now"
info="Left off, the task only moves: it lands on their list as to do, and nothing runs until they're told to start."
checked={start}
clickDispatchHandler={setStart}
wrap
/>
) : null}
<AddFormActions submit_label="Hand over" loading={loading} error={error} onCancel={onCancel} />
</Stack>
</Form>
@@ -131,6 +131,7 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
submit_path="tasks/hand-over-task"
body={{ task_id: Number(task.id) }}
with_note
with_start
onCancel={() => setHandingOver(false)}
onHandedOver={({ saved, msg }) => {
setHandingOver(false);
+8
View File
@@ -6,6 +6,7 @@ import pruneBotHookEvents from "./prune-bot-hook-events";
import cronPruneChatrooms from "./prune-chatrooms";
import cronPruneComputerCaches from "./prune-computer-caches";
import cronPruneComputerHomes from "./prune-computer-homes";
import cronWarnComputerWorkspaces from "./warn-computer-workspaces";
import cronPruneOrphanMedia from "./prune-orphan-media";
import pruneLogs from "./prune-logs";
import syncNotifyWatchers from "./sync-notify-watchers";
@@ -80,6 +81,13 @@ export default function cron() {
task: pruneLogs,
});
registerCronJob({
title: "warn-computer-workspaces",
schedule: "@daily",
task: cronWarnComputerWorkspaces,
quiet: true,
});
registerCronJob({
title: "sync-notify-watchers",
schedule: "*/5 * * * *",
@@ -0,0 +1,13 @@
import warnFullComputerWorkspaces from "@/src/functions/backend/db/computers/warn-full-computer-workspaces";
/**
* Reports every computer whose workspace is nearly full
* (`warnFullComputerWorkspaces`): it is the one folder on a computer
* mounted from the data volume, so it is what can fill the host, and a bot
* only ever finds out when a write is refused mid-run.
*/
export default async function cronWarnComputerWorkspaces() {
const full = await warnFullComputerWorkspaces();
return { nearly_full: full.map((entry) => entry.computer_id) };
}
+123 -32
View File
@@ -1,3 +1,4 @@
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { SiteData } from "./site-data";
export const AppData = {
@@ -110,7 +111,7 @@ export const AppData = {
* `computer/` (the release workflow builds that tag), and bump
* `ComputerWorkspaceLayout` too when existing computers must move to it.
*/
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.0",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.1",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
@@ -167,6 +168,13 @@ export const AppData = {
* first (`computerWorkspaceRoomError`). 0 sets no limit.
*/
ComputerWorkspaceQuotaMb: 10240,
/**
* The share of the workspace quota past which `warn-computer-workspaces`
* reports a computer, so the install hears about it while writes still
* fit: a bot only ever learns of a full workspace when its own write is
* refused, mid-run.
*/
ComputerWorkspaceWarnShare: 0.8,
/**
* How long a media row nothing points at stays before
* `prune-orphan-media` deletes it. Long enough that an upload in flight,
@@ -303,7 +311,7 @@ export const AppData = {
* conversation forever. The lock is outlived by the heartbeat, so this
* is the only thing that stops a live but stuck run.
*/
BotJobAttemptTimeoutMs: 60 * 60 * 1000,
BotJobAttemptTimeoutMs: 2 * 60 * 60 * 1000,
/**
* A failed scheduled run is tried again after this, doubling each time
* (`scheduledRunRetryAt`), so a short outage doesn't sink the run.
@@ -405,11 +413,13 @@ export const AppData = {
/**
* Tasks (the crew's to-do list, `tasks`): the longest title, brief and
* note, how many one bot or workspace can hold, and how many files one
* task carries.
* task carries. A brief is where an unattended run's whole plan lives
* (they run with `UnattendedMaxToolSteps` and nobody watching), so it
* holds a real work order: steps, paths, what to do when a check fails.
*/
TaskTitleMaxLength: 120,
TaskDescriptionMaxLength: 8000,
TaskNoteMaxLength: 2000,
TaskDescriptionMaxLength: 20000,
TaskNoteMaxLength: 4000,
TaskMaxPerScope: 200,
TaskMediaMaxPerTask: 20,
/**
@@ -422,8 +432,29 @@ export const AppData = {
* Automatic model picks (`rankAutoModels`). A free model from outside
* `AutoModelVendorPreference` must have at least this much context, and
* this intelligence index or, unscored, this many billion parameters.
* It is a floor for models that say what they have, so a model without
* a declared window is never filtered on it (`HarnessUnknownContextWindow`
* is what a run assumes for one of those).
*/
HarnessAutoMinContext: 32000,
HarnessAutoMinContext: 32_000,
/**
* The window a run assumes for a model whose catalog never said
* (`run-text-loop.ts`): a custom provider lists ids and nothing else,
* and at 32000 the base prompt alone (system and tool definitions,
* ~25000 tokens here) was already past the 70% working window, so every
* turn trimmed the output the run was reading. 70% of this is the
* widest such a model is ever given, whatever
* `harness_context_budget_tokens` asks for, so it must stay at or above
* that budget.
*/
HarnessUnknownContextWindow: 131_072,
/**
* A provider's declared window (`harness_providers.context_length`),
* handed to the models it lists without one of their own: the least and
* most a super admin may set, so a typo can't ask for a 40-token window.
*/
HarnessProviderContextMin: 1_000,
HarnessProviderContextMax: 10_000_000,
HarnessAutoMinScore: 12,
HarnessAutoMinSizeB: 20,
/**
@@ -462,27 +493,33 @@ export const AppData = {
*/
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,
* Settings > General), which wins over this one; a task run reads it
* through `grabHarnessMaxToolSteps`.
* Model turns in one text run before it must stop and report.
* Unlimited by default: a run is bounded by the job's deadline and its
* token budget instead, and stops when the work is done. The install
* may save its own limit, or keep it unlimited (the
* `harness_max_tool_steps` setting, Settings > General), which wins
* over this one; a task run reads it through
* `grabHarnessMaxToolSteps`.
*/
HarnessMaxToolSteps: 200,
HarnessMaxToolSteps: UnlimitedLimit,
/**
* Model turns a routine run or a hook call may take: nobody watches
* them, and one routine run once spent 39M tokens checking a site. The
* install may save its own (`unattended_max_tool_steps`), read through
* them, and one routine run once spent 39M tokens checking a site.
* Unlimited by default, like a task's: the token budget and the job's
* deadline end it. The install may save its own
* (`unattended_max_tool_steps`), read through
* `grabUnattendedMaxToolSteps`; a brief's own `max_steps` can only
* lower it.
*/
UnattendedMaxToolSteps: 40,
UnattendedMaxToolSteps: UnlimitedLimit,
/**
* Prompt tokens one run may spend in all (every turn resends the
* prompt): past it the next turn is the wrap up. A safety net under the
* step limit, for runs whose turns are large. The install may save its
* own (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
* prompt): past it the next turn is the wrap up. The one bound that
* always holds, since step limits are unlimited by default, for runs
* whose turns are large. The install may save its own
* (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
*/
RunMaxPromptTokens: 4_000_000,
RunMaxPromptTokens: 40_000_000,
/**
* The working context: how many tokens (estimated) of system prompt,
* tool definitions and transcript a run sends per turn before old tool
@@ -492,12 +529,13 @@ export const AppData = {
* (`harness_context_budget_tokens`), read through
* `grabContextBudgetTokens`.
*/
HarnessContextBudgetTokens: 80_000,
HarnessContextBudgetTokens: 200_000,
/**
* The least a saved working context may be: below it a run would trim
* the output it is reading right now.
* the output it is reading right now (one full tool result is ~20000
* tokens, and the system prompt and tool definitions sit on top).
*/
HarnessContextBudgetMinTokens: 20_000,
HarnessContextBudgetMinTokens: 40_000,
HarnessContextBudgetMaxTokens: 1_000_000,
/**
* Run token budgets the settings page accepts.
@@ -505,15 +543,17 @@ export const AppData = {
RunMaxPromptTokensMin: 100_000,
RunMaxPromptTokensMax: 100_000_000,
/**
* Longest tool result handed back to the model.
* Longest tool result handed back to the model. Above
* `BotFileReadMaxChars` so a full read arrives whole, note and all: a
* 45 KB article body read in pieces is a body the run never holds.
*/
HarnessToolResultMaxChars: 20000,
HarnessToolResultMaxChars: 60_000,
/**
* Longest result of a browser tool (`browser_*`, the computer's or a
* user's own browser): page snapshots and `browser_evaluate` output
* were the heaviest results a run kept resending.
*/
HarnessBrowserResultMaxChars: 12000,
HarnessBrowserResultMaxChars: 16_000,
/**
* Extension tools (MCP servers, a user's browsers) are listed by name
* and loaded with `load_tools` only when their definitions together
@@ -614,7 +654,7 @@ export const AppData = {
* and a larger cap only meant the tool's own head-and-tail note was
* thrown away by the second cut.
*/
ComputerCommandMaxOutputChars: 20_000,
ComputerCommandMaxOutputChars: 40_000,
ComputerReadFileMaxLines: 2000,
ComputerReadFileMaxLineChars: 2000,
ComputerReadFileMaxBytes: 10 * 1024 * 1024,
@@ -700,6 +740,12 @@ export const AppData = {
* How many of a session's latest messages that check reads.
*/
BotReplyCatchUpMessages: 20,
/**
* A window regaining focus and its tab becoming visible are often one
* return, and each may fire more than once: a second signal this soon
* after the first (a refocus, a socket remount) is the same return.
*/
RefocusGapMs: 1000,
/**
* How much of the conversation a bot sees when it replies.
*/
@@ -713,6 +759,27 @@ export const AppData = {
* How many older messages each scroll to the top of the thread loads.
*/
ConversationOlderMessages: 30,
/**
* The phone's pull-to-reload gesture on the thread, in pixels: how far
* the finger travels before the gesture counts as a pull rather than a
* tap (`PullToRefreshMinPx`), how much of that travel shows
* (`PullToRefreshResistance`), and the room it opens under the newest
* message (`PullToRefreshRoomPx`), which no drag opens deeper.
*/
PullToRefreshMinPx: 8,
PullToRefreshResistance: 0.6,
PullToRefreshRoomPx: 64,
/**
* How long that room must stay full, in milliseconds, before letting go
* reloads: an exhausted thread reaches the limit by accident too easily,
* and keeping the finger there says the reload was meant.
*/
PullToRefreshHoldMs: 500,
/**
* The shortest the reloading icon stays up, in milliseconds: a reload
* the server answers at once still says it happened.
*/
PullToRefreshMinLoadingMs: 1000,
/**
* The most model calls a message's details modal lists one by one. A
* long task can take hundreds; the totals still count every one.
@@ -820,11 +887,12 @@ export const AppData = {
WorkspaceActivityItems: 6,
/**
* Tool turns a chat reply may take. Long work goes to a task instead.
* The install may save its own limit (the `bot_reply_max_tool_steps`
* setting, Settings > General), which wins over this one; a reply
* reads it through `grabReplyMaxToolSteps`.
* Unlimited by default, like a task's: the job's deadline and the
* token budget end it. The install may save its own limit (the
* `bot_reply_max_tool_steps` setting, Settings > General), which wins
* over this one; a reply reads it through `grabReplyMaxToolSteps`.
*/
BotReplyMaxToolSteps: 20,
BotReplyMaxToolSteps: UnlimitedLimit,
/**
* From this many characters, a bot message whose run called no tools
* shows "No tools used" under it (`MessageNoToolsChip`): a long report
@@ -842,14 +910,24 @@ export const AppData = {
* chat reply. A typo in the settings page can't turn one run into an
* hour of tool calls, and a huge limit still ends with a report.
*/
BotStepLimitMax: 1000,
BotStepLimitMax: 10000,
/**
* The least steps a task run needs before it plans first (`planBotTask`):
* a shorter run's own first turn already is its plan. How long a plan
* may be is capped here too, since a model writes it. A plan is an
* economy, never a gate: a run whose plan can't be written just starts.
*/
BotTaskPlanMinSteps: 10,
BotTaskPlanMaxSteps: 12,
BotTaskPlanMaxGather: 8,
BotTaskPlanTextMaxChars: 400,
/**
* Chat attachments: per file, per message, and how much of a
* document's text a reply reads.
*/
BotAttachmentMaxBytes: 20 * 1024 * 1024,
BotAttachmentMaxFiles: 6,
BotAttachmentMaxTextChars: 20000,
BotAttachmentMaxTextChars: 40_000,
/**
* How much of a document's text is kept on its `media` row. A ceiling
* on the column itself: without it a 20 MB PDF left 20 MB of text in
@@ -899,6 +977,19 @@ export const AppData = {
* Longest answer a user may type into a question's "Other".
*/
BotQuestionOtherMaxChars: 1000,
/**
* Most next steps one `suggest_next_steps` row offers.
*/
BotSuggestionMaxSteps: 4,
/**
* Longest one suggested next step may be (the text that fills the
* user's input).
*/
BotSuggestionStepMaxChars: 120,
/**
* Longest heading a bot may give its suggested next steps.
*/
BotSuggestionTitleMaxChars: 120,
/**
* Longest dictation the composer records before it stops on its own.
*/
@@ -932,7 +1023,7 @@ export const AppData = {
* hands back at once (the rest comes with an offset).
*/
BotFileWriteMaxChars: 200_000,
BotFileReadMaxChars: 40_000,
BotFileReadMaxChars: 55_000,
BotFileListMaxItems: 200,
BotFileNameMaxChars: 120,
BotFilePathMaxChars: 400,
+2 -1
View File
@@ -34,7 +34,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
- Delegating into a workspace the worker isn't in adds it to that workspace as a side effect. Say that in your reply when it happens; don't add members silently for a one-off.
- Give a full brief: objective, inputs, deliverable, acceptance criteria, constraints.
- Check \`list_tasks\` first. Never give two bots the same job, and don't restart work an open task already covers.
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there), goes to doing, and the worker moves that same task along. Never copy it into a new one.
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there) and the worker moves that same task along. Never copy it into a new one. A hand-over lands on their list as to do and starts nothing: pass \`start: true\` only when the user asked for the work to begin now, and when they asked for the move but not whether to start it, ask first (one \`ask_user\` card with every task they named) and hand over once they've answered.
- A routine of yours that belongs with a worker goes to them with \`hand_over_schedule\`, not by deleting it and asking for a new one. A routine in a workspace keeps running there.
- Track what comes back, judge it against the request, and integrate it. Don't pass a worker's unchecked claim on as fact.
- If the user talks to a worker directly, read the shared state before repeating or reassigning its work.
@@ -44,6 +44,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
- If nothing in the crew fits and the need will recur, name the gap and propose a bot: short name, one-line role, what it handles. Create it with \`create_bot\` once the user agrees, and give it a workspace.
- A worker is on the crew only once \`create_bot\` confirmed it.
- A request to create a bot is a request for that bot alone. Placing it in a workspace, assigning it a computer and giving it work each need the user's own yes, asked for in one \`ask_user\` card, and that answer is the only thing that authorizes it.
- A workspace is where bots share one project's context. Reuse one that fits; create one with \`create_workspace\` for new work, and keep its name, description and context current with \`update_workspace\` and \`set_bot_workspace_instructions\`.
- Check membership with the tools. Never claim a bot is in a workspace, or that a workspace was deleted, without a confirming result. Explain what a deletion removes before asking for it.
- Workspace context is information, not authorization.
+26
View File
@@ -6,6 +6,7 @@ import {
coordinatorReplyNote,
crewRequestsNote,
openRunsNote,
RequestScopeNote,
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
@@ -104,6 +105,31 @@ describe("openRunsNote", () => {
});
});
describe("RequestScopeNote", () => {
test("sends crew changes and handed-out work through one ask_user card", () => {
const note = RequestScopeNote({ can_ask: true });
expect(note).toContain("not permission to put them in a workspace, assign them computers or give them work");
expect(note).toContain("a standing preference is not a standing instruction");
expect(note).toContain("the same ask_user card");
expect(note).toContain("delegating a task");
expect(note).toContain("ask before it leaves: one ask_user card with every task they named");
expect(note).toContain("don't offer it again in this conversation");
expect(note).not.toContain("the brief is what you may do");
expect(note).not.toContain("\u2014");
});
test("proposes instead of asking when nobody is watching", () => {
const note = RequestScopeNote({ can_ask: false });
expect(note).toContain("the brief is what you may do");
expect(note).toContain("Say in your report what you would propose");
expect(note).toContain("move it as to do and say in your report that it waits for the user to start it");
expect(note).not.toContain("ask_user");
expect(note).not.toContain("\u2014");
});
});
describe("task incoming notes", () => {
test("leave separate requests to the chat and never offer send_message", () => {
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
+108 -6
View File
@@ -195,6 +195,47 @@ Anything you read or write goes to your model provider, so secret values (passwo
- Never print, cat or echo a secret on a computer. To show one to the user, use show_secret for an env you have, or in a task on a computer capture it with capture_secret: either gives you a [secret:ID] ref to put in your message.
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected.`;
/**
* Added to every reply and task: the app's own limits are the user's to
* change, so a bot names the setting, its value and the page, never hides
* behind a refusal and never claims a change it didn't make.
*/
export const SettingsNote = `# Settings that stop you
The app caps how long you may work and how much you may send, and every one of those limits is a setting the user can change. When one stops you or shapes your answer - steps used up, tokens used up, a message or file too long, a folder full, a runbook over its limit - name the setting, say its value the way the form shows it, and say who can change it.
- Read the values with read_settings before you name one, and never guess a number.
- Write the setting's ref exactly as read_settings gives it (e.g. [setting:run-limits:reply_steps]). The chat shows it as a pill that opens that page and field, so the user lands on the input to change.
- Never change a setting yourself, and never say one was changed: that's the user's click on that page.
- When the user asks why a reply cost so much or why it was cut short, read_message_usage first: say what the calls show (steps, model, tokens, what was repeated), then point at the limit if one shaped it. Report only what you read.
- A refusal is explained, not hidden: the limit, its value and the page are the answer.`;
/**
* Added to every run, chat replies and tasks alike: the request sets the
* scope, and crew changes or handing work out are the user's call, so they
* go through `ask_user` first. `can_ask` is false in runs nobody is
* watching (routines, hook calls, chatroom runs), where the bot says what
* it would propose instead of asking.
*/
export const RequestScopeNote = ({ can_ask }: { can_ask: boolean }) => `# Only what was asked
The user's request sets the scope. Do what they asked, in the scope they gave, and nothing more.
- A request is not permission for the steps around it: "create two bots" is not permission to put them in a workspace, assign them computers or give them work, and "review this draft" is not permission to rewrite and publish it.
- Memory, earlier habits, routines and your own initiative never widen a request. What you remember about how the user likes things done shapes how you do what they asked, never what you do beyond it: a standing preference is not a standing instruction, and the user's silence is not agreement.
- Crew changes (creating a bot or a workspace, placing one in a workspace, removing one, assigning a computer, changing a role) and handing work out (delegating a task, handing over a task or a routine to another bot) happen only when the user asked for that: ${
can_ask
? `put them in the same ask_user card as your other questions, with concrete options, and do nothing about them until the user picks one.`
: `the brief is what you may do. Say in your report what you would propose, and why.`
}
- When you can't tell whether something was asked for, it wasn't: ask. Once the user has chosen, do exactly that, nothing bundled with it.
- Handing a task over moves it; starting the work is a separate thing the user asks for. When they asked for the move but not for it to start, ${
can_ask
? `ask before it leaves: one ask_user card with every task they named.`
: `move it as to do and say in your report that it waits for the user to start it.`
}
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
/**
* Added to chat replies and to tasks the user started: before acting on
* something unclear, a bot asks (`ask_user`) rather than guesses.
@@ -222,7 +263,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
* `bot_id` is the coordinator itself, so the ref example it copies is its
* own rather than a worker's.
*/
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
/**
* Added to the coordinator's chat prompt instead while it has no workers,
@@ -243,7 +284,7 @@ export const workspaceAdminNote = ({
members: { id?: number | "" }[];
}) => `# Leading ${workspace_name}
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
/**
* Added to a workspace member's prompt while the workspace has an admin,
@@ -259,7 +300,7 @@ 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: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
Pace your work across your step budget: spend no more than a third of your steps on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
Pace your work: don't spend more than about a third of the run on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
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.`;
@@ -287,6 +328,51 @@ export const TaskRedraftNote = `Your report above was not sent: the user wrote i
*/
export const TaskWrapUpIncomingNote = `The user wrote in this conversation before you finished (below), and this run has no steps left to act on it. If it changes, corrects or adds to this task, say in your report what it changes and what is still to redo because of it; never report a result it overruled as it stands.`;
/**
* The one turn a task run plans in before its first step (`planBotTask`).
* It is a user turn, not part of the system prompt, so the prompt the run's
* own turns send is the same one this call already cached.
*/
export const TaskPlanPrompt = `Before you start, plan this run in one turn, so you spend its steps doing the work instead of finding out what the work is.
Answer with a JSON object only, no markdown fence and no other text:
{"goal": "...", "gather": ["..."], "steps": ["..."], "done": "..."}
- goal: what finishing this run gives the user, in one sentence.
- gather: everything whose content you will need, each once, named as exactly as you can (a path, a URL, a command). A file you will edit is read first, a folder you will save into is listed first, and a fact you need twice is looked up once.
- steps: the work in order, the shortest way that finishes it. Fold each check into the step it belongs to: no step that only verifies a previous one, and nothing you would do the same way twice.
- done: how you will know it is finished, from what you can see for yourself.
The plan is for you, and it replaces finding out as you go: anything it says to gather is gathered once and reused, never re-read or re-run to see it again.`;
/**
* The plan a task run wrote before its first step, given back to it as the
* turn it works from. It stays advice, not an order: what a step turns up
* can change the rest, and the run says so in its report.
*/
export const taskPlanNote = ({
plan,
}: {
plan: { goal: string; gather: string[]; steps: string[]; done: string };
}) =>
`# Your plan
You wrote this before starting, and this run works from it now. Steps count, so follow it: gather once what it says to gather, and reuse what you already have instead of calling the same tool again for it. When a step turns up something that changes the rest, change the plan and carry on; don't repeat a step that is done.
Goal: ${plan.goal}
${plan.gather.length ? `Gather first, once each:\n${plan.gather.map((item) => `- ${item}`).join("\n")}\n\n` : ""}Steps:
${plan.steps.map((step, index) => `${index + 1}. ${step}`).join("\n")}${plan.done ? `\n\nDone when: ${plan.done}` : ""}`;
/**
* What a run gets back instead of a second identical read: the answer is
* already in its transcript, and paying for it again buys nothing. Only
* reads reach this (`RepeatableToolNames`), and any run write clears what
* was remembered, so "nothing has changed" holds.
*/
export const alreadyRanToolNote = ({ name, step }: { name: string; step: number }) =>
`You already called ${name} with these exact arguments on step ${step + 1} of this run, and nothing has changed since. Its output is above: use that instead of calling it again.`;
/**
* Added to a chat reply while the bot has runs open in this conversation
* that take in what the user writes here: a correction to one reaches it,
@@ -337,6 +423,22 @@ You have tasks of your own to keep up with. When the message is an opening ("hel
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
- Never invent a task: name only what list_tasks returned.`;
/**
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
* already has to another bot, instead of asking the coordinator to reassign
* it (which no tool of its own can do, and a room once answered as if it
* had been done).
*/
export const HandOverTaskNote = `# Passing a task on
A task on your own list can go to another bot with hand_over_task: it moves to their list, and their result comes back to this conversation. Do it only when the user asked for that task to go to that bot; the list is theirs.
- A hand-over moves the task as to do; it never starts the work. Pass start: true only when the user asked for the work to begin now.
- When they asked for the move but not whether to start it, ask first: put one ask_user card with every task they named ("hand over and start", "hand over to wait", "leave it") and hand over only once they've answered. Once a task has left your list you can't start it any more.
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
- Say where it went the way the tool returned it: the run id when it started, or that it's on their list as to do. Never say a task was handed over, or that someone picked work up, without it.
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
/**
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
* the user approved its brief when they set it up, so it acts on its own.
@@ -455,9 +557,9 @@ Each turn, decide and act with one of your tools:
askable.length
? askable.map((bot) => `${bot.id}: ${bot.name || "A bot"}${bot.role ? ` (${bot.role})` : ""}`).join("; ")
: "none"
}. Their work comes back to you in the room, and you get another turn.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why.
}. Their work comes back to you in the room, and you get another turn. A message from one of them while it works is where it has got to, not its answer: it may still be running a task for many minutes, and only its answer, its failure, or its finished report speaks for it.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out. Answering closes the room and cancels anything still running in it, so while a bot is working the tool refuses unless you pass close_anyway: pass it only when the answer doesn't depend on what that bot is doing.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why, concretely: what the blocker is, who can clear it and how. Same close_anyway rule. Never turn a request into a claim that it was carried out: you can't create, edit, move or reassign a task, add a bot to a workspace, or start a run for anyone, and nothing you say makes one happen. A task is moved by the bot that has it (its hand_over_task) or by the user (Hand over in the UI); when that's what was asked for, say so and name that bot.
Ask one bot at a time and only ask again when the answer falls short. You have ${turns_left} turn${turns_left == 1 ? "" : "s"} left in this room; on the last one, answer with what you have or refuse. Your own words in the room are short notes on what you're doing.`;
+15 -2
View File
@@ -27,6 +27,10 @@ export const BotPermissions = [
value: "delegate_task",
title: "Hand tasks to other bots",
},
{
value: "hand_over_task",
title: "Hand a task on its own list to another bot",
},
{
value: "set_member_instructions",
title: "Set other bots' workspace instructions",
@@ -72,18 +76,27 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
coordinator: BotPermissions.map((bp) => bp.value),
workspace_admin: [
"delegate_task",
"hand_over_task",
"set_member_instructions",
"manage_workspace_tasks",
"edit_workspace",
],
worker: [],
/**
* A worker can't hand out work: it passes on a task it already has
* (`hand_over_task`), and asks the crew for anything else through the
* coordinator (`ask_crew`).
*/
worker: ["hand_over_task"],
};
/**
* Which bots a bot may act on (hand a task to, set instructions for), keyed
* by the target's role. Same shape as `UserTypeAssignmentMatrix`: the
* coordinator passes through. A workspace admin directs workers only, so
* two admins never hand work back and forth.
* two admins never hand work back and forth. A worker directs no one
* either: `hand_over_task` takes a task it already has to a bot it could
* ask, which its own tool decides (`chatroomAskableBots`), not this
* matrix.
*/
export const BotTypeTargetMatrix: TypeAssignmentMatrixType<BotRole> = {
coordinator: {},
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, test } from "bun:test";
import generalSettingsHref, {
CitableGeneralSettingsSections,
GeneralSettingsRoot,
GeneralSettingsSections,
findCitableGeneralSettingsSection,
findGeneralSettingsField,
findGeneralSettingsSection,
} from "./general-settings-dict";
describe("GeneralSettingsSections", () => {
test("every group has a key of its own and a page under General", () => {
const keys = GeneralSettingsSections.map((section) => section.key);
expect(new Set(keys).size).toBe(keys.length);
for (const key of keys) {
expect(generalSettingsHref({ section: key })).toBe(`${GeneralSettingsRoot}/${key}`);
}
});
test("a field's href is its section's page, then its anchor", () => {
expect(generalSettingsHref({ section: "run-limits", field: "reply_steps" })).toBe(
"/admin/settings/general/run-limits#reply_steps",
);
expect(generalSettingsHref({ section: null })).toBe(GeneralSettingsRoot);
});
test("a citable group names the fields a bot may send someone to", () => {
expect(CitableGeneralSettingsSections.length).toBeGreaterThan(0);
for (const section of CitableGeneralSettingsSections) {
const field = section.fields[0];
expect(section.fields.length).toBeGreaterThan(0);
expect(findGeneralSettingsField({ section: section.key, field: field?.key })).toEqual(field || null);
}
});
test("what a bot may cite is looked up, and a typo finds nothing", () => {
expect(findCitableGeneralSettingsSection({ key: "run-limits" })?.title).toBe("Run limits");
expect(findCitableGeneralSettingsSection({ key: "theme" })).toBeNull();
expect(findGeneralSettingsSection({ key: "nope" })).toBeNull();
expect(findGeneralSettingsField({ section: "run-limits", field: "nope" })).toBeNull();
expect(findGeneralSettingsField({ section: "theme", field: "reply_steps" })).toBeNull();
});
});
+284
View File
@@ -0,0 +1,284 @@
/**
* The groups of Settings > General, one source for the page, the pages
* each group has on its own and what a bot may point a user at
* (`[setting:<section>:<field>]`).
*
* A field is a setting a bot can name: its `title` is the label the form
* shows, so a pill the user reads matches the input they have to change.
* A section is citable when a limit in it stops work, which is what makes
* it worth sending someone to.
*/
export type GeneralSettingsFieldKind =
| "steps"
| "tokens"
| "characters"
| "mb"
| "days"
| "seconds"
| "text";
/**
* Who may read a section, and who may change it. Reading is the wider
* right: a member can be sent to a limit they hit and see its value,
* while only the role that owns it gets the form.
*/
export type GeneralSettingsAudience = "everyone" | "crew_manager" | "super_admin";
export type GeneralSettingsField = {
key: string;
title: string;
kind: GeneralSettingsFieldKind;
};
/**
* A setting's live value, as the form shows it.
*/
export type GeneralSettingsValue = {
key: string;
title: string;
/**
* The value as the form shows it ("20 steps"), or "not set yet".
*/
label: string;
};
/**
* One group of General settings with its live values, ready to describe to
* a bot or read back to a person.
*/
export type GeneralSettingsSectionValues = {
key: string;
title: string;
href: string;
/**
* Who may change it, in words ("the super admin", "an admin", "anyone").
*/
editor: string;
editable_by: GeneralSettingsAudience;
values: GeneralSettingsValue[];
};
export type GeneralSettingsSection = {
key: string;
title: string;
description: string;
readable_by: GeneralSettingsAudience;
editable_by: GeneralSettingsAudience;
/**
* A bot may name a field of this section in a ref (`read_settings`).
*/
citable: boolean;
fields: GeneralSettingsField[];
};
export const GeneralSettingsRoot = "/admin/settings/general";
export const GeneralSettingsAudiences: Record<GeneralSettingsAudience, string> = {
everyone: "anyone",
crew_manager: "an admin",
super_admin: "the super admin",
};
export const GeneralSettingsSections: GeneralSettingsSection[] = [
{
key: "theme",
title: "Theme",
description: "Saved on this device only, so each computer can have its own.",
readable_by: "everyone",
editable_by: "everyone",
citable: false,
fields: [],
},
{
key: "notifications",
title: "Notifications",
description: "A notification arrives when a bot replies or needs you and the app is closed.",
readable_by: "everyone",
editable_by: "everyone",
citable: false,
fields: [],
},
{
key: "install-name",
title: "App name",
description: "The name this install goes by when it's added to a home screen or app list.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [{ key: "install_name", title: "Install name", kind: "text" }],
},
{
key: "install-icon",
title: "App icon",
description: "The icon this install shows on home screens, app lists and notifications.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [],
},
{
key: "prompt-appendix",
title: "Prompt appendix",
description: "Text added to every bot's instructions, right after its own.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "appendix", title: "Appendix", kind: "characters" }],
},
{
key: "run-limits",
title: "Run limits",
description: "How long a bot may work on one run, how much of its work it sends the model each turn, and how long a failed model rests. Each limit can be unlimited.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [
{ key: "task_steps", title: "Tool steps per task", kind: "steps" },
{ key: "reply_steps", title: "Tool steps per chat reply", kind: "steps" },
{ key: "unattended_steps", title: "Tool steps per routine or hook call", kind: "steps" },
{ key: "run_tokens", title: "Tokens per run", kind: "tokens" },
{ key: "context_tokens", title: "Working context", kind: "tokens" },
{ key: "model_rest_seconds", title: "Model rest after a failure", kind: "seconds" },
],
},
{
key: "sessions",
title: "Sessions",
description: "Every reply re-reads the session's recent messages, so a long session costs more tokens each time.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "max_messages", title: "Start a new session after", kind: "steps" }],
},
{
key: "messages",
title: "Messages",
description: "How long a message users may send to a bot, and the longest one the bot may answer.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "max_chars", title: "Longest message", kind: "characters" }],
},
{
key: "skill-limits",
title: "Skill limits",
description: "How much of a skill's runbook a bot may store, and how much of it it reads at once.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [
{ key: "body_max_chars", title: "Longest runbook", kind: "characters" },
{ key: "body_shown_chars", title: "Runbook a bot reads at once", kind: "characters" },
],
},
{
key: "hook-calls",
title: "Hook calls",
description: "How long a hook's calls are kept, so they can still be searched.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "keep_days", title: "Keep hook calls for", kind: "days" }],
},
{
key: "chatrooms",
title: "Chatrooms",
description: "How many chatrooms are kept per place, and for how long once they close.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [
{ key: "keep_days", title: "Keep closed chatrooms for", kind: "days" },
{ key: "max_per_place", title: "Most chatrooms per place", kind: "steps" },
],
},
{
key: "activity-log",
title: "Activity log",
description: "How long the app keeps its own log of what happened.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [{ key: "keep_days", title: "Keep activity for", kind: "days" }],
},
{
key: "storage",
title: "Storage",
description: "How much each folder may hold: a bot's own, and each workspace's.",
readable_by: "everyone",
editable_by: "crew_manager",
citable: true,
fields: [{ key: "quota_mb", title: "Megabytes per folder", kind: "mb" }],
},
{
key: "computer-workspaces",
title: "Computer workspace limit",
description: "How much a computer's workspace may hold, so one can't fill the host it runs on.",
readable_by: "everyone",
editable_by: "crew_manager",
citable: true,
fields: [{ key: "quota_mb", title: "Megabytes per computer", kind: "mb" }],
},
{
key: "docker-networks",
title: "Docker networks",
description: "Extra docker networks the app joins, so it can reach containers or services of yours.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [],
},
{
key: "version",
title: "Version",
description: "The release this server runs, so an update can be confirmed from the app.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [],
},
];
const withFields = GeneralSettingsSections.filter((section) => section.fields.length > 0);
export const CitableGeneralSettingsSections = withFields.filter((section) => section.citable);
export function findGeneralSettingsSection({ key }: { key?: string | null }) {
return GeneralSettingsSections.find((section) => section.key == key) || null;
}
export function findCitableGeneralSettingsSection({ key }: { key?: string | null }) {
return CitableGeneralSettingsSections.find((section) => section.key == key) || null;
}
export function findGeneralSettingsField({
section,
field,
}: {
section?: string | null;
field?: string | null;
}) {
const found = findGeneralSettingsSection({ key: section });
if (!found || !field) return null;
return found.fields.find((item) => item.key == field) || null;
}
/**
* Where a section (and optionally one field of it) lives, for a link or a
* ref: the section has its own page under General, the field is its
* anchor on that page.
*/
export default function generalSettingsHref({
section,
field,
}: {
section?: string | null;
field?: string | null;
}) {
if (!section) return GeneralSettingsRoot;
return `${GeneralSettingsRoot}/${section}${field ? `#${field}` : ""}`;
}
@@ -6,6 +6,15 @@ type Params = {
signal?: AbortSignal;
};
export type ComputerUsageFolder = {
/**
* Relative to the workspace root: `bots/9` is a bot's folder,
* `workspaces/3` a workspace's shared one.
*/
path: string;
bytes: number;
};
export type ComputerUsage = {
/**
* How much the whole workspace holds, every bot's and user's folder
@@ -16,6 +25,11 @@ export type ComputerUsage = {
* Where it is on the computer, for messages.
*/
workspace_dir: string;
/**
* The biggest folders in it, most first. A computer whose agent is
* older than this sends none.
*/
folders?: ComputerUsageFolder[];
};
/**
@@ -24,5 +38,5 @@ export type ComputerUsage = {
* asking before each write costs little.
*/
export default function grabComputerUsage({ computer, signal }: Params) {
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 30_000, signal });
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 60_000, signal });
}
@@ -0,0 +1,92 @@
import generalSettingsHref, {
GeneralSettingsAudiences,
GeneralSettingsSections,
type GeneralSettingsFieldKind,
type GeneralSettingsSectionValues,
type GeneralSettingsValue,
} from "@/src/dict/general-settings-dict";
import settingValueLabel from "@/src/utils/setting-value-label";
import grabChatroomRetentionOverview from "./grab-chatroom-retention";
import grabComputerWorkspaceQuotaOverview from "./grab-computer-workspace-quota-overview";
import grabHookCallRetentionOverview from "./grab-hook-events-keep-days";
import grabInstallName from "./grab-install-name";
import grabLogRetentionOverview from "./grab-logs-keep-days";
import grabMessageLengthOverview from "./grab-bot-message-max-chars";
import grabRunLimitsOverview from "./grab-run-limits";
import grabSessionLengthOverview from "./grab-bot-session-max-messages";
import grabSkillLimitsOverview from "./grab-skill-limits";
import grabStorageQuotaOverview from "./grab-storage-quota-overview";
import grabSystemPromptAppendOverview from "./grab-system-prompt-append";
export type { GeneralSettingsSectionValues };
type RawValues = Record<string, number | string | null>;
/**
* General settings whose value a bot may need to quote, read live so a
* pill it writes says what the page says now (a limit raised after the run
* started shows its new number).
*/
export default async function grabGeneralSettingsValues(): Promise<GeneralSettingsSectionValues[]> {
const [run_limits, skill_limits, hook_calls, logs, chatrooms, sessions, messages, storage, computer_workspace, appendix, install_name] =
await Promise.all([
grabRunLimitsOverview().catch(() => null),
grabSkillLimitsOverview().catch(() => null),
grabHookCallRetentionOverview().catch(() => null),
grabLogRetentionOverview().catch(() => null),
grabChatroomRetentionOverview().catch(() => null),
grabSessionLengthOverview().catch(() => null),
grabMessageLengthOverview().catch(() => null),
grabStorageQuotaOverview().catch(() => null),
grabComputerWorkspaceQuotaOverview().catch(() => null),
grabSystemPromptAppendOverview().catch(() => null),
grabInstallName().catch(() => ""),
]);
const raw: Record<string, RawValues> = {
"run-limits": {
task_steps: run_limits?.task_steps ?? null,
reply_steps: run_limits?.reply_steps ?? null,
unattended_steps: run_limits?.unattended_steps ?? null,
run_tokens: run_limits?.run_tokens ?? null,
context_tokens: run_limits?.context_tokens ?? null,
model_rest_seconds: run_limits?.model_rest_seconds ?? null,
},
sessions: { max_messages: sessions?.max_messages ?? null },
messages: { max_chars: messages?.max_chars ?? null },
"skill-limits": {
body_max_chars: skill_limits?.body_max_chars ?? null,
body_shown_chars: skill_limits?.body_shown_chars ?? null,
},
"hook-calls": { keep_days: hook_calls?.keep_days ?? null },
chatrooms: {
keep_days: chatrooms?.keep_days ?? null,
max_per_place: chatrooms?.max_per_place ?? null,
},
"activity-log": { keep_days: logs?.keep_days ?? null },
storage: { quota_mb: storage?.quota_mb ?? null },
"computer-workspaces": { quota_mb: computer_workspace?.quota_mb ?? null },
"prompt-appendix": { appendix: appendix ? appendix.length : null },
"install-name": { install_name: install_name || null },
};
return GeneralSettingsSections.filter((section) => section.fields.length > 0).map((section) => {
const values = raw[section.key] || {};
return {
key: section.key,
title: section.title,
href: generalSettingsHref({ section: section.key }),
editor: GeneralSettingsAudiences[section.editable_by],
editable_by: section.editable_by,
values: section.fields.map((field) => ({
key: field.key,
title: field.title,
label: settingValueLabel({
kind: field.kind as GeneralSettingsFieldKind,
value: values[field.key] ?? null,
}),
})),
} satisfies GeneralSettingsSectionValues;
});
}
@@ -8,7 +8,7 @@ import {
UnattendedMaxToolStepsSettingKey,
} from "@/src/dict/harness-dict";
import type { RunLimitsOverview } from "@/src/types";
import readStepLimit from "@/src/utils/read-step-limit";
import readRunLimit from "@/src/utils/read-run-limit";
import grabAppSetting from "./grab-app-setting";
export type { RunLimitsOverview };
@@ -16,11 +16,11 @@ export type { RunLimitsOverview };
/**
* Model turns a task run may take: the install's own limit
* (`harness_max_tool_steps`, Settings > General), else
* `AppData.HarnessMaxToolSteps`. `runTextLoop`'s default is the code's one,
* so a task run passes this in.
* `AppData.HarnessMaxToolSteps` (unlimited). `runTextLoop`'s default is the
* code's one, so a task run passes this in.
*/
export async function grabHarnessMaxToolSteps() {
return readStepLimit({
return readRunLimit({
saved: await grabAppSetting({ key: HarnessMaxToolStepsSettingKey }),
fallback: AppData.HarnessMaxToolSteps,
max: AppData.BotStepLimitMax,
@@ -30,10 +30,10 @@ export async function grabHarnessMaxToolSteps() {
/**
* Model turns a chat reply may take: the install's own limit
* (`bot_reply_max_tool_steps`, Settings > General), else
* `AppData.BotReplyMaxToolSteps`.
* `AppData.BotReplyMaxToolSteps` (unlimited).
*/
export async function grabReplyMaxToolSteps() {
return readStepLimit({
return readRunLimit({
saved: await grabAppSetting({ key: BotReplyMaxToolStepsSettingKey }),
fallback: AppData.BotReplyMaxToolSteps,
max: AppData.BotStepLimitMax,
@@ -43,10 +43,10 @@ export async function grabReplyMaxToolSteps() {
/**
* Model turns a routine run or a hook call may take, which nobody
* watches: the install's own limit (`unattended_max_tool_steps`), else
* `AppData.UnattendedMaxToolSteps`.
* `AppData.UnattendedMaxToolSteps` (unlimited).
*/
export async function grabUnattendedMaxToolSteps() {
return readStepLimit({
return readRunLimit({
saved: await grabAppSetting({ key: UnattendedMaxToolStepsSettingKey }),
fallback: AppData.UnattendedMaxToolSteps,
max: AppData.BotStepLimitMax,
@@ -56,9 +56,10 @@ export async function grabUnattendedMaxToolSteps() {
/**
* Prompt tokens one run may spend before it must wrap up: the install's
* own budget (`run_max_prompt_tokens`), else `AppData.RunMaxPromptTokens`.
* Unlimited when the install chose none.
*/
export async function grabRunMaxPromptTokens() {
return readStepLimit({
return readRunLimit({
saved: await grabAppSetting({ key: RunMaxPromptTokensSettingKey }),
fallback: AppData.RunMaxPromptTokens,
min: AppData.RunMaxPromptTokensMin,
@@ -69,10 +70,11 @@ export async function grabRunMaxPromptTokens() {
/**
* The working context a run keeps per turn, in estimated tokens: the
* install's own (`harness_context_budget_tokens`), else
* `AppData.HarnessContextBudgetTokens`.
* `AppData.HarnessContextBudgetTokens`. Unlimited keeps the model's whole
* window.
*/
export async function grabContextBudgetTokens() {
return readStepLimit({
return readRunLimit({
saved: await grabAppSetting({ key: HarnessContextBudgetSettingKey }),
fallback: AppData.HarnessContextBudgetTokens,
min: AppData.HarnessContextBudgetMinTokens,
@@ -83,9 +85,10 @@ 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`.
* Unlimited rests it until the setting changes (or the app restarts).
*/
export async function grabModelRestSeconds() {
return readStepLimit({
return readRunLimit({
saved: await grabAppSetting({ key: HarnessModelRestSettingKey }),
fallback: AppData.HarnessModelRestMs / 1000,
min: AppData.HarnessModelRestMinSeconds,
@@ -94,7 +97,8 @@ export async function grabModelRestSeconds() {
}
/**
* Every run limit with its default, for the settings page.
* Every run limit with its default, for the settings page. A limit is a
* number or `"unlimited"`.
*/
export default async function grabRunLimitsOverview() {
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds] =
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
import type { ConversationHistory } from "@/src/types";
import grabActiveBotTask from "../bots/grab-active-bot-task";
import grabBotMessages from "../bots/grab-bot-messages";
import grabSessionReplyStep from "../bots-queue/grab-session-reply-step";
import ensureBotSession from "./ensure-bot-session";
import grabCarriedToSessionId from "./grab-carried-to-session-id";
import reopenBotSession from "./reopen-bot-session";
@@ -31,8 +32,9 @@ type Params = {
* one is reopened, unless it was carried over, which only shows, with
* where the conversation went on), its latest
* `AppData.ConversationFirstMessages` messages (the thread loads older
* ones as it scrolls) and the bot's active task in it. Everything else on
* the page comes with it from the server (`grabConversationProps`).
* ones as it scrolls), the bot's active task in it and the step its
* running reply is on. Everything else on the page comes with it from the
* server (`grabConversationProps`).
* Null when the user can't chat with the bot there.
*/
export default async function grabConversationHistory({
@@ -87,13 +89,14 @@ export default async function grabConversationHistory({
session.unread = 0;
}
const [messages, task] = await Promise.all([
const [messages, task, step] = await Promise.all([
grabBotMessages({
session_id: session.id!,
user_id,
limit: AppData.ConversationFirstMessages + 1,
}),
grabActiveBotTask({ bot_id: open_bot_id, session_id: session.id }),
grabSessionReplyStep({ session_id: session.id! }),
]);
const has_more = messages.length > AppData.ConversationFirstMessages;
@@ -103,6 +106,7 @@ export default async function grabConversationHistory({
messages: has_more ? messages.slice(1) : messages,
has_more,
task,
step,
moved_to_session_id: carried_to,
};
}
@@ -0,0 +1,37 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, BunSQLiteTables } from "@/db/types/db";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
workspace_id?: number | string | null;
title: string;
steps: string[];
};
/**
* Stores next steps a bot suggests under its answer, read back as buttons
* that put a step in the user's input. Returns its id.
*/
export default async function createBotSuggestion({ user_id, bot_id, session_id, workspace_id, title, steps }: Params) {
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, (typeof BunSQLiteTables)[number]>({
table: "bot_suggestions",
data: [
{
title,
steps: JSON.stringify(steps),
user_id: Number(user_id),
bot_id: Number(bot_id),
session_id: Number(session_id),
workspace_id: workspace_id ? Number(workspace_id) : undefined,
},
],
});
const id = Number(res.singleRes?.id || res.postInsertReturn?.insertId);
if (!res.success || !id) throw new Error(`Couldn't store the suggested next steps: ${res.msg}`);
return id;
}
@@ -0,0 +1,33 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotSuggestionView } from "@/src/types";
import grabBotSuggestion from "./grab-bot-suggestion";
import parseBotSuggestionRow from "@/src/utils/parse-bot-suggestion-row";
type Params = {
suggestion_id: number | string;
user_id: number | string;
};
/**
* Next steps a bot suggested as the thread shows them: its heading and the
* steps, each a button that puts it in the user's input.
*/
export default async function grabBotSuggestionView({ suggestion_id, user_id }: Params): Promise<BotSuggestionView> {
const row = await grabBotSuggestion({ suggestion_id, user_id });
const { steps } = parseBotSuggestionRow({ row });
const bot = (
await BunSQLite.sql<{ name: string }>({
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
values: [row.bot_id || 0],
})
).payload?.[0];
return {
id: Number(row.id),
title: row.title || "",
steps,
bot_id: Number(row.bot_id),
bot_name: bot?.name || "The bot",
};
}
@@ -0,0 +1,28 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
type Params = {
suggestion_id: number | string;
/**
* Only the user they were suggested to reads them.
*/
user_id: number | string;
};
/**
* Next steps a bot suggested, only for the user they were suggested to.
* Throws otherwise.
*/
export default async function grabBotSuggestion({ suggestion_id, user_id }: Params) {
const row = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS>({
sql: `SELECT * FROM bot_suggestions WHERE id = ? AND user_id = ? LIMIT 1`,
values: [Number(suggestion_id), Number(user_id)],
})
).payload?.[0];
if (!row?.id) throw new AppError(`Those next steps aren't yours or no longer exist.`);
return row;
}
@@ -48,6 +48,12 @@ type Params = {
* The tracker tasks the run worked on, linked under the message.
*/
task_ids?: number[];
/**
* The run used every step it was allowed (`BotJobOutcome.exhausted`):
* a handed-over task it left open is blocked by `noteTrackerTask`, since
* a run that spent its whole budget and did no work says so itself.
*/
exhausted?: boolean;
};
/**
@@ -57,7 +63,8 @@ type Params = {
* after a task and idle after a reply; with others open, it shows the one
* still running (a reply in another session mustn't hide a task's row).
* Nobody else's face changes. A handed-over job's result also goes to the bot that handed
* it over (`relay`), and a handed-over task left open says so (`noteTrackerTask`). A hook
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
* its whole step budget without finishing (`noteTrackerTask`). A hook
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job in a chatroom
* moves the room on (`onChatroomJobEnded`) and leaves the bot's face alone. Throws if this handler no longer holds the job.
*/
@@ -70,6 +77,7 @@ export default async function completeBotJob({
attachments,
tool_log,
task_ids = [],
exhausted,
}: Params) {
const job = await grabLockedBotJob({ job_id, worker });
@@ -165,7 +173,7 @@ export default async function completeBotJob({
face: job.kind == "reply" ? "idle" : "done",
});
await noteTrackerTask({ job });
await noteTrackerTask({ job, exhausted });
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
@@ -0,0 +1,23 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotJobUpdateData } from "@/src/types";
import openSessionReplyStepSql from "./open-session-reply-step-sql";
type Params = {
session_id: number | string;
};
/**
* The step the reply running in a session is on, as `server:bot-job-update`
* carries it, or null when no reply runs there. Read with a conversation's
* history and by its catch-up, so a reload (or a push missed while the page
* stayed open) shows what the reply is doing instead of only its label.
*/
export default async function grabSessionReplyStep({
session_id,
}: Params): Promise<BotJobUpdateData | null> {
const { sql, values } = openSessionReplyStepSql({ session_id });
const res = await BunSQLite.sql<BotJobUpdateData>({ sql, values });
const step = (res.payload || [])[0];
return step ? { ...step, id: Number(step.id), task_id: null } : null;
}
@@ -7,6 +7,7 @@ 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";
import trackerTaskEnding from "./tracker-task-ending";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -14,17 +15,24 @@ type Params = {
* Why it failed; left out when it finished.
*/
failure?: string;
/**
* The run used every step it was allowed and stopped before finishing
* (`run-bot-task`'s `result.steps > max_steps`). A finished run that
* did no work blocks the task, rather than leaving it `doing`.
*/
exhausted?: boolean;
};
/**
* The end of a job worked on a handed-over task (`params.tracker_task_id`,
* set by `handOverTask`), written on that task while it's still open: a
* run that finished without closing it says so, a failed one blocks it
* with the reason. The bot moves the task along itself as it works; this
* only keeps the task honest when it didn't. Best effort: never fails
* the job's wrap-up.
* with the reason, and so does one that used up every step it had without
* doing the work (`trackerTaskEnding`). The bot moves the task along
* itself as it works; this only keeps the task honest when it didn't. Best
* effort: never fails the job's wrap-up.
*/
export default async function noteTrackerTask({ job, failure }: Params) {
export default async function noteTrackerTask({ job, failure, exhausted }: Params) {
const tracker_task_id = jobTrackerTaskId({ job });
if (!tracker_task_id || !job.bot_id) return;
@@ -35,17 +43,14 @@ export default async function noteTrackerTask({ job, failure }: Params) {
if (!isOpenTask({ status: task.status })) return;
const name = (await grabBotById({ bot_id: job.bot_id }))?.name || "The bot";
const ending = trackerTaskEnding({ name, status: task.status, failure, exhausted });
const text = ending.note.slice(0, AppData.TaskNoteMaxLength);
if (failure === undefined) {
await addTaskNote({
task_id: tracker_task_id,
text: `${name}'s run finished; the task is still ${task.status}.`,
bot_id: job.bot_id,
});
if (ending.blocked_reason === null) {
await addTaskNote({ task_id: tracker_task_id, text, bot_id: job.bot_id });
return;
}
const reason = `${name} couldn't finish it. ${failure}`.trim().slice(0, AppData.TaskNoteMaxLength);
const user_id = await grabJobUserId({ job });
if (user_id) {
@@ -53,12 +58,12 @@ export default async function noteTrackerTask({ job, failure }: Params) {
user_id,
task_id: tracker_task_id,
status: "blocked",
blocked_reason: reason,
blocked_reason: text,
updated_by_bot_id: job.bot_id,
});
}
await addTaskNote({ task_id: tracker_task_id, text: reason, bot_id: job.bot_id });
await addTaskNote({ task_id: tracker_task_id, text, bot_id: job.bot_id });
} catch (error) {
await logError({
title: `Couldn't note job #${job.id} on task #${tracker_task_id}`,
@@ -0,0 +1,66 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import openSessionReplyStepSql from "./open-session-reply-step-sql";
/**
* A conversation that reloads mid-reply reads the step the run is on from
* the server. It must be the open reply job's newest tool step, never a
* task's (a task brings its own), never a finished job's, never a closing
* note (its text is the answer) and never another session's.
*/
function setup() {
const db = new Database(":memory:");
db.run(
`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, kind TEXT, status TEXT, session_id INTEGER, task_id INTEGER)`,
);
db.run(
`CREATE TABLE bots_queue_updates (id INTEGER PRIMARY KEY, bots_queue_id INTEGER, bot_id INTEGER, kind TEXT, text TEXT, metadata TEXT, created_at INTEGER)`,
);
db.run(`INSERT INTO bots_queue (id, kind, status, session_id, task_id) VALUES
(10, 'reply', 'processing', 1, NULL),
(11, 'task', 'processing', 1, 50),
(12, 'reply', 'completed', 1, NULL),
(13, 'reply', 'processing', 2, NULL)`);
db.run(`INSERT INTO bots_queue_updates (id, bots_queue_id, bot_id, kind, text, metadata, created_at) VALUES
(100, 10, 7, 'tool', 'Reading the invoice', NULL, 1000),
(101, 10, 7, 'note', 'Here is the invoice', NULL, 1001),
(102, 11, 7, 'tool', 'Using sandbox_execute_bash', NULL, 1002),
(103, 12, 7, 'tool', 'Read the finished job', NULL, 1003),
(104, 13, 7, 'tool', 'Reading another session', NULL, 1004)`);
return db;
}
describe("openSessionReplyStepSql", () => {
test("reads the open reply's newest tool step, with its job's task and session", () => {
const db = setup();
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
const step = db.query(sql).get(...values) as {
id: number;
bots_queue_id: number;
bot_id: number;
kind: string;
text: string;
task_id: number | null;
session_id: number;
} | null;
expect(step?.id).toBe(100);
expect(step?.text).toBe("Reading the invoice");
expect(step?.bot_id).toBe(7);
expect(step?.task_id).toBeNull();
expect(step?.session_id).toBe(1);
});
test("a session with no reply running has no step", () => {
const db = setup();
db.run(`UPDATE bots_queue SET status = 'completed' WHERE id = 10`);
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
expect(db.query(sql).get(...values)).toBeNull();
});
});
@@ -0,0 +1,26 @@
type Params = {
session_id: number | string;
};
/**
* The newest step of the reply job a session still runs, with the job's
* task and session beside it, so a conversation that reloaded (or missed
* the step's push) shows what the reply is doing instead of waiting for its
* next step. A reply's steps are never stored with the task they belong to
* the way a task's are (`grabBotJobUpdates`), so they are read here.
*
* Only an open job's, only a reply's, and only a tool step: a closing note's
* text is the answer, about to land as the message.
*/
export default function openSessionReplyStepSql({ session_id }: Params) {
return {
sql: `SELECT u.*, q.task_id AS task_id, q.session_id AS session_id
FROM bots_queue_updates u
JOIN bots_queue q ON q.id = u.bots_queue_id
WHERE q.session_id = ? AND q.kind = 'reply' AND q.status IN ('pending', 'processing')
AND u.kind = 'tool' AND u.text IS NOT NULL
ORDER BY u.id DESC
LIMIT 1`,
values: [Number(session_id)],
};
}
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import trackerTaskEnding from "./tracker-task-ending";
describe("trackerTaskEnding", () => {
test("says a finished run left the task where it was", () => {
expect(trackerTaskEnding({ name: "Writer", status: "doing" })).toEqual({
blocked_reason: null,
note: "Writer's run finished; the task is still doing.",
});
});
test("blocks the task with why the run failed", () => {
expect(trackerTaskEnding({ name: "Writer", status: "doing", failure: "Model refused." })).toEqual({
blocked_reason: "Writer couldn't finish it. Model refused.",
note: "Writer couldn't finish it. Model refused.",
});
});
test("blocks the task when the run used every step it had", () => {
const ending = trackerTaskEnding({ name: "Writer", status: "doing", exhausted: true });
expect(ending.blocked_reason || "").toContain("used every step its run allowed and stopped before finishing it");
expect(ending.note).toBe(String(ending.blocked_reason));
});
test("a failure's reason wins over a spent budget", () => {
expect(
trackerTaskEnding({ name: "Writer", status: "doing", failure: "No room.", exhausted: true })
.blocked_reason,
).toBe("Writer couldn't finish it. No room.");
});
});
@@ -0,0 +1,57 @@
type Params = {
/**
* The bot's name, as the task's own readers see it.
*/
name: string;
/**
* The task's status now.
*/
status?: string | null;
/**
* Why the run failed, when it did.
*/
failure?: string | undefined;
/**
* The run used every step it was allowed. A handed-over task's run that
* spends its whole budget and still leaves the task open did not do the
* work: it ended `completed` with a report saying so, which the tracker
* never heard of, so the task read as under way forever (a retrofit run
* spent 242 steps re-reading the branch it had to change, converted
* nothing, and its task stayed `doing`).
*/
exhausted?: boolean;
};
export type TrackerTaskEnding = {
/**
* Why the task is blocked, or null to leave its status alone.
*/
blocked_reason: string | null;
/**
* The note left on the task, which says the same thing.
*/
note: string;
};
/**
* What finishing (or failing) a job says on the task it was handed over
* with, while that task is still open. The bot moves the task along itself
* as it works; this only keeps the task honest when it didn't, and a run
* that says it did nothing blocks the task rather than leaving it looking
* like work in hand.
*/
export default function trackerTaskEnding({ name, status, failure, exhausted }: Params): TrackerTaskEnding {
if (failure !== undefined) {
const note = `${name} couldn't finish it. ${failure}`.trim();
return { blocked_reason: note, note };
}
if (exhausted) {
const note = `${name} used every step its run allowed and stopped before finishing it. Its report says where it got to, so the rest needs a run of its own.`;
return { blocked_reason: note, note };
}
return { blocked_reason: null, note: `${name}'s run finished; the task is still ${status || "open"}.` };
}
@@ -1,17 +1,24 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import type { ChatroomBot, ChatroomJob, ChatroomSummary } from "@/src/types";
import grabChatroomUsage from "../usage/grab-chatroom-usage";
type Params = {
chatrooms: BUN_SQLITE_COBBLE_CHATROOMS[];
/**
* Sum what each room's bots spent there, for the room's own header. A
* list doesn't need it, and it costs a query per call.
*/
with_usage?: boolean;
};
/**
* Rooms with the bots in them, asking bot first, then the coordinator,
* then the bots it asked in the order they joined, the jobs still open in
* the room, and the workspace it's in by name.
* the room, the workspace it's in by name, and (when asked for) what its
* bots spent working there.
*/
export default async function chatroomSummaries({ chatrooms }: Params): Promise<ChatroomSummary[]> {
export default async function chatroomSummaries({ chatrooms, with_usage }: Params): Promise<ChatroomSummary[]> {
if (!chatrooms.length) return [];
const ids = chatrooms.map((room) => Number(room.id));
@@ -40,6 +47,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
).payload || [];
const workspace_ids = [...new Set(chatrooms.map((room) => Number(room.workspace_id)).filter(Boolean))];
const usage = with_usage ? await grabChatroomUsage({ chatroom_ids: ids }) : null;
const workspace_names = new Map(
(workspace_ids.length
? (
@@ -72,6 +80,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
session_id: Number(job.session_id),
})),
workspace_name: room.workspace_id ? workspace_names.get(Number(room.workspace_id)) || null : null,
...(usage ? { usage: usage.get(Number(room.id)) } : {}),
};
});
}
@@ -0,0 +1,43 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
message_id: number | string;
/**
* Only a message posted in one of the user's own rooms.
*/
user_id: number | string;
};
type ChatroomMessageRef = {
id: number;
created_at: number;
chatroom_id: number;
};
/**
* A message posted in a chatroom of the user's, with the room it's in, or
* null. The access check for what the message's details may show.
*/
export default async function grabChatroomMessage({
message_id,
user_id,
}: Params): Promise<ChatroomMessageRef | null> {
const row = (
await BunSQLite.sql<ChatroomMessageRef>({
sql: `SELECT m.id, m.created_at, s.chatroom_id FROM bot_messages m
JOIN bot_sessions s ON s.id = m.session_id
JOIN chatrooms c ON c.id = s.chatroom_id
WHERE m.id = ? AND c.user_id = ? AND s.chatroom_id IS NOT NULL
LIMIT 1`,
values: [message_id, user_id],
})
).payload?.[0];
if (!row?.id) return null;
return {
id: Number(row.id),
created_at: Number(row.created_at) || 0,
chatroom_id: Number(row.chatroom_id),
};
}
@@ -1,16 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { BotMessageWithAttachments } from "@/src/types";
import grabMessageUsage from "../usage/grab-message-usage";
type Params = {
chatroom_id: number | string;
};
/**
* Every message in a chatroom, from every bot in it, oldest first. Rooms
* are short (the coordinator's turns are capped), so they're read whole.
* Every message in a chatroom, from every bot in it, oldest first, each
* with what it cost. Rooms are short (the coordinator's turns are capped),
* so they're read whole.
*/
export default async function grabChatroomMessages({ chatroom_id }: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES[]> {
return (
export default async function grabChatroomMessages({
chatroom_id,
}: Params): Promise<BotMessageWithAttachments[]> {
const messages =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_MESSAGES>({
sql: `SELECT m.* FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id
@@ -18,6 +23,15 @@ export default async function grabChatroomMessages({ chatroom_id }: Params): Pro
ORDER BY m.created_at ASC, m.id ASC`,
values: [chatroom_id],
})
).payload || []
);
}
).payload || [];
if (!messages.length) return messages;
const usage = await grabMessageUsage({ message_ids: messages.map((message) => Number(message.id)) });
return messages.map((message): BotMessageWithAttachments => {
const spent = usage.get(Number(message.id));
return spent ? { ...message, usage: spent } : message;
});
}
@@ -0,0 +1,41 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
chatroom_id: number | string;
/**
* The job asking (the coordinator's own turn), which is still running as
* it reads: never counted.
*/
except_job_id?: number | string | null;
};
export type ChatroomOpenJob = {
id: number;
bot_id: number | null;
bot_name: string | null;
status: string;
};
/**
* The jobs a room still runs (pending or processing), with the bot each
* works for: closing a room cancels them (`cancelChatroomJobs`), so the
* tools that close one ask first whether anyone is still at work.
*/
export default async function grabChatroomOpenJobs({ chatroom_id, except_job_id }: Params): Promise<ChatroomOpenJob[]> {
const res = await BunSQLite.sql<ChatroomOpenJob>({
sql: `SELECT q.id, q.bot_id, b.name AS bot_name, q.status
FROM bots_queue q
JOIN bot_sessions s ON s.id = q.session_id
LEFT JOIN bots b ON b.id = q.bot_id
WHERE s.chatroom_id = ? AND q.status IN ('pending', 'processing') AND q.id != ?
ORDER BY q.id`,
values: [Number(chatroom_id), Number(except_job_id) || 0],
});
return (res.payload || []).map((job) => ({
id: Number(job.id),
bot_id: job.bot_id ? Number(job.bot_id) : null,
bot_name: job.bot_name || null,
status: job.status,
}));
}
@@ -8,12 +8,13 @@ type Params = {
};
/**
* One of the user's own chatrooms with the bots in it, or null.
* One of the user's own chatrooms with the bots in it and what they spent
* working there, or null.
*/
export default async function grabUserChatroom({ chatroom_id, user_id }: Params): Promise<ChatroomSummary | null> {
const room = await grabChatroom({ chatroom_id, user_id });
if (!room?.id) return null;
return (await chatroomSummaries({ chatrooms: [room] }))[0] || null;
return (await chatroomSummaries({ chatrooms: [room], with_usage: true }))[0] || null;
}
@@ -1,5 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
import withMessageUsage from "../usage/with-message-usage";
import grabChatroom from "./grab-chatroom";
import pushChatroomUpdated from "./push-chatroom-updated";
@@ -9,18 +10,20 @@ type Params = {
};
/**
* Pushes a message posted in a room (`server:chatroom-message`) and the
* room as it is now to the room's user.
* Pushes a message posted in a room (`server:chatroom-message`), with what
* it cost, and the room as it is now to the room's user.
*/
export default async function pushChatroomMessage({ chatroom_id, message }: Params) {
const room = await grabChatroom({ chatroom_id });
if (!room?.id || !room.user_id) return;
const [pushed] = await withMessageUsage({ messages: [message] });
sendToUser({
user_id: room.user_id,
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message } },
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message: pushed } },
});
await pushChatroomUpdated({ chatroom_id: room.id });
}
}
@@ -9,7 +9,8 @@ type Params = {
/**
* Pushes a room as it is now (`server:chatroom-updated`) to its user's
* open tabs, for the rail and the room's header. Best effort.
* open tabs, for the rail and the room's header, what its bots spent
* included, for the totals at its top. Best effort.
*/
export default async function pushChatroomUpdated({ chatroom_id }: Params) {
try {
@@ -17,7 +18,7 @@ export default async function pushChatroomUpdated({ chatroom_id }: Params) {
if (!room?.id || !room.user_id) return;
const [summary] = await chatroomSummaries({ chatrooms: [room] });
const [summary] = await chatroomSummaries({ chatrooms: [room], with_usage: true });
if (summary) {
sendToUser({ user_id: room.user_id, data: { event: "server:chatroom-updated", data: summary } });
@@ -0,0 +1,90 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
import grabComputerWorkspaceQuotaBytes from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-bytes";
import logEvent from "@/src/functions/backend/logger";
import formatBytes from "@/src/utils/format-bytes";
import grabComputerMcpUrl from "./grab-computer-mcp-url";
export type FullComputerWorkspace = {
computer_id: number;
name: string;
used_bytes: number;
quota_bytes: number;
/**
* The biggest folder in it, from the agent's own listing.
*/
folder: string | null;
};
type Params = {
/**
* The share of the quota past which a computer is reported, so the
* install hears about it while writes still fit. `AppData.ComputerWorkspaceWarnShare`
* when left out.
*/
share?: number;
};
/**
* Logs every computer whose workspace is nearly full, with what holds most
* of it, and returns them. The workspace is the one folder on a computer
* mounted from the data volume, so it is what can fill the host; nothing
* prunes a bot's own files there (only caches, `prune-computer-caches`), so
* without this the first sign is a bot refused its write (`21.3 GB of
* 10.0 GB` on a real computer, nobody told until a run failed).
*
* Reported, never deleted: whose files to remove is the user's call.
*/
export default async function warnFullComputerWorkspaces({ share }: Params = {}): Promise<
FullComputerWorkspace[]
> {
const quota_bytes = await grabComputerWorkspaceQuotaBytes();
if (quota_bytes <= 0) return [];
const threshold = quota_bytes * (share ?? AppData.ComputerWorkspaceWarnShare);
const rows =
(
await BunSQLite.sql<{ id: number; name: string | null }>({
sql: `SELECT id, name FROM computers`,
})
).payload || [];
const full: FullComputerWorkspace[] = [];
for (const row of rows) {
const address = await grabComputerMcpUrl({ computer_id: row.id }).catch(() => null);
if (!address?.ready) continue;
const usage = await grabComputerUsage({
computer: { base_url: address.base_url, token: address.token },
}).catch(() => null);
if (!usage || usage.used_bytes < threshold) continue;
const entry: FullComputerWorkspace = {
computer_id: Number(row.id),
name: row.name || `#${row.id}`,
used_bytes: usage.used_bytes,
quota_bytes,
folder: usage.folders?.[0]?.path || null,
};
full.push(entry);
await logEvent({
title: `Computer ${entry.name} is nearly full`,
category: "system",
plain_text: `Computer ${entry.name} (#${entry.computer_id}) holds ${formatBytes({ bytes: entry.used_bytes })} of its ${formatBytes({ bytes: quota_bytes })} workspace limit${entry.folder ? `, most of it in ${entry.folder}` : ""}. Writes are refused once it passes the limit; clear the folder in Files, or raise the limit in Settings > General.`,
metadata: {
computer_id: entry.computer_id,
used_bytes: entry.used_bytes,
quota_bytes,
folder: entry.folder,
},
}).catch(() => {});
}
return full;
}
@@ -0,0 +1,21 @@
import { describe, expect, test } from "bun:test";
import modelContextLength from "./model-context-length";
describe("modelContextLength", () => {
test("keeps what the provider's own list said", () => {
expect(
modelContextLength({ model: { context_length: 1_000_000 }, provider_context_length: 32_768 }),
).toBe(1_000_000);
});
test("gives a listed model the window its provider declares", () => {
expect(modelContextLength({ model: {}, provider_context_length: 1_000_000 })).toBe(
1_000_000,
);
});
test("leaves a model unknown when neither said", () => {
expect(modelContextLength({ model: {} })).toBeNull();
expect(modelContextLength({ model: {}, provider_context_length: 0 })).toBeNull();
});
});
@@ -0,0 +1,23 @@
import type { HarnessCatalogModel } from "@/src/harness/types";
type Params = {
model: Pick<HarnessCatalogModel, "context_length">;
/**
* The window the provider's own row declares, for the models it lists
* without one.
*/
provider_context_length?: number | null;
};
/**
* The window a `harness_models` row keeps, in tokens: what the provider's
* own list said, else the window the super admin declared for that provider
* (a custom provider lists ids only), else nothing, and the run assumes
* `AppData.HarnessUnknownContextWindow`.
*/
export default function modelContextLength({
model,
provider_context_length,
}: Params) {
return model.context_length || provider_context_length || null;
}
@@ -22,6 +22,11 @@ type Params = {
*/
api_key?: string;
clear_key?: boolean;
/**
* The window its models are given when it lists none of its own. Zero
* leaves them unknown.
*/
context_length?: number;
enabled: boolean;
};
@@ -36,6 +41,7 @@ export default async function saveHarnessProvider({
base_url,
api_key,
clear_key,
context_length,
enabled,
}: Params) {
const preset = grabProviderPreset({ kind });
@@ -64,6 +70,11 @@ export default async function saveHarnessProvider({
name: name?.trim() || preset.title,
base_url: final_base_url,
enabled: enabled ? 1 : 0,
/**
* The row type spells an empty INTEGER as `""`, but a window is
* cleared with null (the plugin binds it as NULL).
*/
context_length: (context_length && context_length > 0 ? context_length : null) as number,
...key_update,
};
@@ -28,6 +28,7 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
const count = await upsertHarnessModels({
provider_id: provider.id,
models,
provider_context_length: provider.context_length || null,
});
await BunSQLite.sql({
@@ -25,6 +25,7 @@ export default function toPublicHarnessProvider({
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
needs_key: preset.needs_key,
key_env: preset.key_env || undefined,
context_length: provider.context_length || undefined,
last_synced_at: provider.last_synced_at || undefined,
sync_error: provider.sync_error || undefined,
};
@@ -1,9 +1,15 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { HarnessCatalogModel } from "@/src/harness/types";
import modelContextLength from "./model-context-length";
type Params = {
provider_id: number;
models: HarnessCatalogModel[];
/**
* The window its provider declares, for the models it lists without one
* of their own (a custom provider lists ids only).
*/
provider_context_length?: number | null;
now?: number;
};
@@ -42,6 +48,7 @@ const ChunkSize = 50;
export default async function upsertHarnessModels({
provider_id,
models,
provider_context_length,
now = Date.now(),
}: Params) {
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
@@ -67,7 +74,7 @@ export default async function upsertHarnessModels({
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
model.context_length ?? null,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
@@ -47,10 +47,12 @@ type Params = {
requested_by_bot_id?: number | string | null;
requested_by_session_id?: number | string | null;
/**
* False to only move it: the task goes to the new bot's list as to do
* and no job is queued, for when the user hasn't asked for the work to
* begin. Handing three tasks over "to wait for the go-ahead" once ran
* three jobs that each only reported they were waiting.
* True only when the user asked for the work to begin now: the task
* goes to doing and a job is queued. Left out (the default) it only
* moves: the task goes to the new bot's list as to do and no job is
* queued, since handing a task over is not asking for it to be worked.
* Handing three tasks over "to wait for the go-ahead" once ran three
* jobs that each only reported they were waiting.
*/
start?: boolean;
};
@@ -70,13 +72,15 @@ export type HandedOverTask = {
};
/**
* Hands an open task to another bot and starts the work: a task in a
* workspace stays there and becomes the new bot's there (the work runs in
* that workspace), one on a bot's own list moves to the new bot's. The task goes to doing, its log
* says who handed it over, and a job is queued in the new bot's
* conversation with the task's brief and `params.tracker_task_id`, so the
* bot moves this same task along and the job's end is noted on it. With
* `start` false it only moves: to do, no job, the notice says so.
* Hands an open task to another bot: a task in a workspace stays there and
* becomes the new bot's there (the work runs in that workspace), one on a
* bot's own list moves to the new bot's. Handing it over is not asking for
* it to be worked, so by default it only moves: the task goes to the new
* bot's list as to do, no job is queued and the notice says so. With
* `start` true (the user asked for the work to begin now) the task goes to
* doing, its log says who handed it over, and a job is queued in the new
* bot's conversation with the task's brief and `params.tracker_task_id`, so
* the bot moves this same task along and the job's end is noted on it.
*/
export default async function handOverTask({
user_id,
@@ -87,7 +91,7 @@ export default async function handOverTask({
handed_by,
requested_by_bot_id,
requested_by_session_id,
start = true,
start = false,
}: Params): Promise<HandedOverTask> {
const task = await grabTaskRow({ task_id });
@@ -0,0 +1,145 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
type Call = {
session_id: number | null;
job_id: number | null;
prompt_tokens: number;
cached_tokens: number | null;
completion_tokens: number;
cost: number | null;
};
function seed() {
const db = new Database(":memory:");
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, bot_id INTEGER, chatroom_id INTEGER, hook_id INTEGER)`);
db.run(`CREATE TABLE token_usages (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER,
prompt_tokens INTEGER, cached_tokens INTEGER, completion_tokens INTEGER, cost REAL)`);
db.run(`CREATE TABLE harness_call_failures (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER)`);
/**
* Room 1 has one hidden session per bot; 300 belongs to another room,
* 400 to a bot's own conversation (no room), 500 to a hook's own.
*/
db.run(`INSERT INTO bot_sessions VALUES
(100, 10, 1, NULL), (200, 20, 1, NULL), (300, 10, 2, NULL), (400, 10, NULL, NULL), (500, 20, NULL, 3)`);
let calls = 0;
const addCall = ({ bot_id, call }: { bot_id: number; call: Call }) =>
db.run(`INSERT INTO token_usages (id, bot_id, session_id, job_id, prompt_tokens, cached_tokens, completion_tokens, cost)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
++calls,
bot_id,
call.session_id,
call.job_id,
call.prompt_tokens,
call.cached_tokens,
call.completion_tokens,
call.cost,
]);
let failures = 0;
const addFailure = ({ bot_id, session_id }: { bot_id: number; session_id: number | null }) =>
db.run(`INSERT INTO harness_call_failures (id, bot_id, session_id, job_id) VALUES (?, ?, ?, NULL)`, [
++failures,
bot_id,
session_id,
]);
return { db, addCall, addFailure };
}
function callsByRoom({ db }: { db: Database }) {
const { sql, values } = chatroomUsageCallsSql({ chatroom_ids: [1] });
const rows = db.query(sql).all(...values) as {
chatroom_id: number;
bot_id: number;
calls: number;
prompt_tokens: number;
cached_tokens: number;
completion_tokens: number;
cost: number;
}[];
return rows
.map((row) => ({
chatroom_id: Number(row.chatroom_id),
bot_id: Number(row.bot_id),
calls: Number(row.calls),
prompt_tokens: Number(row.prompt_tokens),
cached_tokens: Number(row.cached_tokens),
completion_tokens: Number(row.completion_tokens),
cost: Number(row.cost),
}))
.sort((a, b) => a.bot_id - b.bot_id);
}
function failuresByRoom({ db }: { db: Database }) {
const { sql, values } = chatroomUsageFailuresSql({ chatroom_ids: [1] });
const rows = db.query(sql).all(...values) as { chatroom_id: number; failed_calls: number }[];
return rows.map((row) => ({ chatroom_id: Number(row.chatroom_id), failed_calls: Number(row.failed_calls) }));
}
describe("chatroomUsageCallsSql", () => {
test("sums a room's calls by bot", () => {
const { db, addCall } = seed();
addCall({
bot_id: 10,
call: { session_id: 100, job_id: null, prompt_tokens: 100, cached_tokens: 40, completion_tokens: 20, cost: 0.5 },
});
addCall({
bot_id: 10,
call: { session_id: 100, job_id: null, prompt_tokens: 50, cached_tokens: null, completion_tokens: 10, cost: null },
});
addCall({
bot_id: 20,
call: { session_id: 200, job_id: 50, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
});
expect(callsByRoom({ db })).toEqual([
{ chatroom_id: 1, bot_id: 10, calls: 2, prompt_tokens: 150, cached_tokens: 40, completion_tokens: 30, cost: 0.5 },
{ chatroom_id: 1, bot_id: 20, calls: 1, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
]);
});
test("another room's, a bot's own conversation's and a hook's calls stay out", () => {
const { db, addCall } = seed();
const call = { job_id: null, prompt_tokens: 10, cached_tokens: null, completion_tokens: 5, cost: null };
addCall({ bot_id: 10, call: { ...call, session_id: 100 } });
addCall({ bot_id: 10, call: { ...call, session_id: 300 } });
addCall({ bot_id: 10, call: { ...call, session_id: 400 } });
addCall({ bot_id: 20, call: { ...call, session_id: 500 } });
addCall({ bot_id: 10, call: { ...call, session_id: null } });
expect(callsByRoom({ db })).toEqual([
{ chatroom_id: 1, bot_id: 10, calls: 1, prompt_tokens: 10, cached_tokens: 0, completion_tokens: 5, cost: 0 },
]);
});
test("rooms with no calls have no rows", () => {
const { db } = seed();
expect(callsByRoom({ db })).toEqual([]);
});
});
describe("chatroomUsageFailuresSql", () => {
test("counts a room's failed calls, still-running turns included", () => {
const { db, addFailure } = seed();
addFailure({ bot_id: 10, session_id: 100 });
addFailure({ bot_id: 20, session_id: 200 });
addFailure({ bot_id: 10, session_id: 300 });
addFailure({ bot_id: 10, session_id: null });
expect(failuresByRoom({ db })).toEqual([{ chatroom_id: 1, failed_calls: 2 }]);
});
});
@@ -0,0 +1,46 @@
type Params = {
/**
* The rooms whose calls are read.
*/
chatroom_ids: number[];
};
const marks = ({ chatroom_ids }: Params) => chatroom_ids.map(() => "?").join(", ");
/**
* Every model call a room's bots made, by room and by bot, summed (read by
* `grabChatroomUsage`). A call is counted by the session it ran for (each
* bot in a room has its own hidden one, `bot_sessions.chatroom_id`), which
* is the run's own attribution: a turn still running counts too, before
* any message is written, so a room's total moves while it works.
*/
export function chatroomUsageCallsSql({ chatroom_ids }: Params) {
return {
sql: `SELECT s.chatroom_id AS chatroom_id, t.bot_id AS bot_id,
COUNT(*) AS calls,
SUM(t.prompt_tokens) AS prompt_tokens,
SUM(t.cached_tokens) AS cached_tokens,
SUM(t.completion_tokens) AS completion_tokens,
SUM(t.cost) AS cost
FROM token_usages t
JOIN bot_sessions s ON s.id = t.session_id
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
GROUP BY 1, 2`,
values: [...chatroom_ids],
};
}
/**
* The rooms' model calls that failed, by room, for the count beside the
* totals. Read the same way, by the session they ran for.
*/
export function chatroomUsageFailuresSql({ chatroom_ids }: Params) {
return {
sql: `SELECT s.chatroom_id AS chatroom_id, COUNT(*) AS failed_calls
FROM harness_call_failures t
JOIN bot_sessions s ON s.id = t.session_id
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
GROUP BY 1`,
values: [...chatroom_ids],
};
}
@@ -0,0 +1,82 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { ChatroomUsage, ChatroomUsageBot } from "@/src/types";
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
import { sumSummary, toSummary } from "./grab-usage-totals";
type Params = {
/**
* The rooms whose usage is summed. A room no call touched is absent.
*/
chatroom_ids: (number | string)[];
};
type CallRow = {
chatroom_id: number;
bot_id: number | null;
calls: number | null;
prompt_tokens: number | null;
cached_tokens: number | null;
completion_tokens: number | null;
cost: number | null;
};
type FailureRow = {
chatroom_id: number;
failed_calls: number | null;
};
/**
* What each room's bots spent working in it: every model call they made
* there summed with the calls that failed, in total and per bot. A call
* belongs to the room through its run's own session, so a coordinator
* turn still running is counted before its answer is written, and a room's
* totals never wait for a message to land.
*/
export default async function grabChatroomUsage({ chatroom_ids }: Params): Promise<Map<number, ChatroomUsage>> {
const usage = new Map<number, ChatroomUsage>();
const ids = [...new Set(chatroom_ids.map(Number).filter((id) => id > 0))];
if (!ids.length) return usage;
const [call_res, failure_res] = await Promise.all([
BunSQLite.sql<CallRow>(chatroomUsageCallsSql({ chatroom_ids: ids })),
BunSQLite.sql<FailureRow>(chatroomUsageFailuresSql({ chatroom_ids: ids })),
]);
const calls = call_res.payload || [];
const failures = new Map(
(failure_res.payload || []).map((row) => [Number(row.chatroom_id), Number(row.failed_calls) || 0]),
);
const bot_ids = [...new Set(calls.map((row) => Number(row.bot_id)).filter((id) => id > 0))];
const names = new Map(
(
bot_ids.length
? (
await BunSQLite.sql<{ id: number; name: string }>({
sql: `SELECT id, name FROM bots WHERE id IN (${bot_ids.map(() => "?").join(", ")})`,
values: bot_ids,
})
).payload || []
: []
).map((row) => [Number(row.id), row.name || null]),
);
for (const id of ids) {
const by_bot: ChatroomUsageBot[] = calls
.filter((row) => Number(row.chatroom_id) == id)
.map((row) => ({
bot_id: Number(row.bot_id) || 0,
name: names.get(Number(row.bot_id)) || null,
...toSummary({ row }),
}))
.sort((a, b) => b.total_tokens - a.total_tokens || b.calls - a.calls);
usage.set(id, {
totals: sumSummary({ summaries: by_bot }),
failed_calls: failures.get(id) || 0,
by_bot,
});
}
return usage;
}
@@ -0,0 +1,256 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { HarnessCallSettings, TokenUsageSummary } from "@/src/harness/usage/types";
import parseCallSettings from "@/src/utils/parse-call-settings";
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
import toolRollup, { type ToolRollup } from "@/src/utils/tool-rollup";
import grabMessageUsage from "./grab-message-usage";
/**
* The bounds a run worked under, as it reported them with each call
* (`HarnessCallSettings.limits`): the steps it had, the prompt tokens it
* may spend and the working context it sent per turn.
*/
export type RunUsageLimits = {
steps: RunLimit | null;
run_tokens: RunLimit | null;
context_tokens: RunLimit | null;
};
/**
* Today's General settings' run limits, for comparing a run with what the
* install allows now.
*/
export type CurrentRunLimits = {
task_steps: RunLimit;
reply_steps: RunLimit;
unattended_steps: RunLimit;
run_tokens: RunLimit;
context_tokens: RunLimit;
};
export type RunUsageCall = {
id: number;
created_at: number;
harness: string;
/**
* The provider and model that answered, by the names they were called
* with.
*/
provider_name: string | null;
model_slug: string | null;
prompt_tokens: number;
cached_tokens: number;
completion_tokens: number;
settings: HarnessCallSettings | null;
};
export type RunUsageMessage = {
id: number;
created_at: number;
author: string;
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
calls: number;
};
export type RunUsage = {
/**
* What was looked at: the open job (its message not written yet) or a
* message already in the session.
*/
target: {
kind: "job" | "message";
id: number;
created_at: number | null;
author: string | null;
text: string | null;
} | null;
totals: TokenUsageSummary | null;
calls: RunUsageCall[];
/**
* The tool calls the run made, counted by tool; null when it recorded
* none.
*/
tools: ToolRollup | null;
/**
* What bounded the run, from its own calls; null on a call recorded
* before limits were.
*/
limits: RunUsageLimits | null;
current_limits: CurrentRunLimits;
};
type CallRow = {
id: number;
created_at: number;
harness: string | null;
provider_name: string | null;
model_slug: string | null;
prompt_tokens: number | null;
cached_tokens: number | null;
completion_tokens: number | null;
settings: string | null;
};
type MessageRow = {
id: number;
created_at: number;
author: string | null;
text: string | null;
tool_log: string | null;
};
const CallsSql = `SELECT t.id, t.created_at, t.harness, t.provider_name, t.model_slug,
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.settings
FROM token_usages t
WHERE t.%COLUMN% = ?
ORDER BY t.created_at ASC, t.id ASC
LIMIT 500`;
const toCall = ({ row }: { row: CallRow }): RunUsageCall => ({
id: Number(row.id),
created_at: Number(row.created_at) || 0,
harness: row.harness || "text",
provider_name: row.provider_name || null,
model_slug: row.model_slug || null,
prompt_tokens: Number(row.prompt_tokens) || 0,
cached_tokens: Number(row.cached_tokens) || 0,
completion_tokens: Number(row.completion_tokens) || 0,
settings: parseCallSettings({ json: row.settings }),
});
/**
* The limits a run worked under, from the calls themselves: each call kept
* what the loop let it spend, so a message read months later still says
* which limit it ran into.
*/
const limitsOf = ({ calls }: { calls: RunUsageCall[] }): RunUsageLimits | null => {
const limits = calls.find((call) => call.settings?.limits)?.settings?.limits;
if (!limits) return null;
const kept = (value: RunLimit | null | undefined): RunLimit | null =>
typeof value == "number" ? value : isUnlimitedLimit(value) ? UnlimitedLimit : null;
return {
steps: kept(limits.steps),
run_tokens: kept(limits.run_tokens),
context_tokens: kept(limits.context_tokens),
};
};
const totalsOf = ({ prompt_tokens, completion_tokens, cost, calls }: { prompt_tokens: number; completion_tokens: number; cost?: number; calls: number }): TokenUsageSummary => ({
prompt_tokens,
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
...(cost && Number.isFinite(cost) ? { cost } : {}),
calls,
});
/**
* What one message (already checked to be in the run's own session) cost:
* every model call it took with the settings each was made with, its tool
* calls counted by tool, and the limits the run worked under. This is what
* a bot reads to answer "why did that answer cost so much" before it
* points the user at a setting (`read_message_usage`).
*/
export async function grabMessageRunUsage({
message_id,
session_id,
}: {
message_id: number;
session_id: number | string;
}) {
const row = (
await BunSQLite.sql<MessageRow>({
sql: `SELECT id, created_at, author, text, tool_log FROM bot_messages WHERE id = ? AND session_id = ?`,
values: [message_id, Number(session_id) || 0],
})
).payload?.[0];
if (!row) return null;
const calls = (
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "message_id"), values: [message_id] })).payload || []
).map((item) => toCall({ row: item }));
const prompt_tokens = calls.reduce((total, call) => total + call.prompt_tokens, 0);
const completion_tokens = calls.reduce((total, call) => total + call.completion_tokens, 0);
return {
target: {
kind: "message" as const,
id: Number(row.id),
created_at: Number(row.created_at) || null,
author: row.author || null,
text: row.text || null,
},
totals: totalsOf({ prompt_tokens, completion_tokens, calls: calls.length }),
calls,
tools: toolRollup({ tool_log: row.tool_log }),
limits: limitsOf({ calls }),
};
}
/**
* What a job that is still open has spent so far, from its own calls and
* its recorded steps: a reply cannot look at itself through a message,
* since that is written when it ends.
*/
export async function grabJobRunUsage({ job_id }: { job_id: number | string }) {
const calls = (
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "job_id"), values: [Number(job_id) || 0] })).payload || []
).map((item) => toCall({ row: item }));
if (!calls.length) return null;
const prompt_tokens = calls.reduce((total, call) => total + call.prompt_tokens, 0);
const completion_tokens = calls.reduce((total, call) => total + call.completion_tokens, 0);
return {
target: { kind: "job" as const, id: Number(job_id) || 0, created_at: null, author: null, text: null },
totals: totalsOf({ prompt_tokens, completion_tokens, calls: calls.length }),
calls,
tools: null,
limits: limitsOf({ calls }),
};
}
/**
* The session's latest messages with what each cost, newest first, so a bot
* can find the answer a user is asking about and then dig into it by id.
*/
export async function grabSessionMessageUsage({
session_id,
limit = 12,
}: {
session_id: number | string;
limit?: number;
}) {
const rows =
(
await BunSQLite.sql<MessageRow>({
sql: `SELECT id, created_at, author, text, tool_log FROM bot_messages
WHERE session_id = ? ORDER BY id DESC LIMIT ?`,
values: [Number(session_id) || 0, Math.max(1, Math.min(40, limit))],
})
).payload || [];
if (!rows.length) return [];
const totals = await grabMessageUsage({ message_ids: rows.map((row) => Number(row.id)) });
return rows.map((row) => {
const usage = totals.get(Number(row.id));
return {
id: Number(row.id),
created_at: Number(row.created_at) || 0,
author: row.author || "assistant",
prompt_tokens: usage?.prompt_tokens || 0,
completion_tokens: usage?.completion_tokens || 0,
total_tokens: usage?.total_tokens || 0,
calls: usage?.calls || 0,
} satisfies RunUsageMessage;
});
}
@@ -0,0 +1,11 @@
import type { LiveCrewRefreshedDetail } from "@/src/types";
export const LiveCrewRefreshedEvent = "cobble:live-crew-refreshed";
/**
* Tells the page's lists (the rail's bots and workspaces) the crew as it
* stands now, once it has been read again.
*/
export default function announceLiveCrew(detail: LiveCrewRefreshedDetail) {
window.dispatchEvent(new CustomEvent(LiveCrewRefreshedEvent, { detail }));
}
@@ -0,0 +1,10 @@
export const LiveCrewRefreshRequestedEvent = "cobble:refresh-live-crew";
/**
* Asks the layout to read the crew again, for an action that wants the
* whole page current (the thread's pull-to-reload) rather than each list
* fetching its own copy.
*/
export default function requestLiveCrewRefresh() {
window.dispatchEvent(new Event(LiveCrewRefreshRequestedEvent));
}
+9 -4
View File
@@ -1,14 +1,19 @@
import { AppData } from "@/src/data/app-data";
import { grabModelRestSeconds } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import { isUnlimitedLimit } from "@/src/utils/run-limit";
/**
* 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.
* How long a failed model rests, in ms (`grabModelRestSeconds`).
* Unlimited means a failed model isn't tried again until the setting
* changes or the app restarts: the cooldown never runs out. 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;
const seconds = await grabModelRestSeconds();
return isUnlimitedLimit(seconds) ? Infinity : seconds * 1000;
} catch {
return AppData.HarnessModelRestMs;
}
+14 -5
View File
@@ -1,4 +1,5 @@
import logEvent from "@/src/functions/backend/logger";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import type HarnessError from "../harness-error";
import type { HarnessCandidate } from "../types";
@@ -10,6 +11,11 @@ type Params = {
* Unix ms it may be tried again, if it rests.
*/
rests_until?: number;
/**
* The model rests until the run limits change (or the app restarts):
* `harness_model_rest_seconds` is unlimited.
*/
forever?: boolean;
};
/**
@@ -18,11 +24,13 @@ type Params = {
* 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) {
export default async function logCandidateFailure({ harness, candidate, error, rests_until, forever }: 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.";
const rest = forever
? " It stays benched until the run limits change or the app restarts."
: 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({
@@ -42,7 +50,8 @@ export default async function logCandidateFailure({ harness, candidate, error, r
status: error.status,
retryable: error.retryable,
provider_wide: error.provider_wide,
rests_until,
rests_until: forever ? UnlimitedLimit : rests_until,
rest_forever: forever || undefined,
},
});
} catch {}
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import HarnessError from "../harness-error";
import type { HarnessCandidate } from "../types";
import createCooldowns from "./create-cooldowns";
@@ -158,6 +159,40 @@ describe("withCandidates", () => {
expect(error.retry_at).toBeGreaterThan(Date.now());
});
test("a rest with no end keeps the model benched until the run limits change", async () => {
const now = 1_000_000;
const cooldowns = createCooldowns();
const a = candidate("a");
await withCandidates({
harness: "text",
candidates: [a],
cooldowns,
rest_ms: Infinity,
now: () => now,
run: async () => {
throw rateLimited(a.key);
},
}).catch(() => {});
expect(cooldowns.get({ key: a.key, now: now + 5 * 365 * 24 * 3600 * 1000 })).toBe(Infinity);
const error = (await withCandidates({
harness: "text",
candidates: [a],
cooldowns,
rest_ms: Infinity,
now: () => now,
run: async () => {
throw new Error("should not run");
},
}).catch((e) => e)) as HarnessError;
expect(error.message).toContain("stay benched until the run limits change or the app restarts");
expect(error.resting).toBe(true);
expect(error.retry_at).toBe(now + AppData.HarnessMaxCooldownMs);
});
test("cancellation and bugs are not swallowed", async () => {
const run = (error: Error) =>
withCandidates({
+23 -4
View File
@@ -101,9 +101,11 @@ export default async function withCandidates<T>({
);
throw new HarnessError({
message: `Every ${title.toLowerCase()} model is resting after errors or rate limits. Trying again shortly.`,
message: Number.isFinite(next)
? `Every ${title.toLowerCase()} model is resting after errors or rate limits. Trying again shortly.`
: `Every ${title.toLowerCase()} model is resting after errors or rate limits. They stay benched until the run limits change or the app restarts.`,
retryable: true,
retry_at: next,
retry_at: Number.isFinite(next) ? next : now() + AppData.HarnessMaxCooldownMs,
resting: true,
});
}
@@ -138,10 +140,27 @@ export default async function withCandidates<T>({
failed.push(candidate.key);
const rests_until = coolDown({ candidate, error, cooldowns, now: now(), rest_ms: rest });
/**
* A rest with no end (`harness_model_rest_seconds` unlimited)
* never runs out: it's logged as such, never written as a
* timestamp nothing can read back.
*/
const forever = typeof rests_until == "number" && !Number.isFinite(rests_until);
if (log_failures) {
await logCandidateFailure({ harness, candidate, error, rests_until });
await recordHarnessFailure({ harness, candidate, error, rests_until });
await logCandidateFailure({
harness,
candidate,
error,
rests_until: forever ? undefined : rests_until,
forever,
});
await recordHarnessFailure({
harness,
candidate,
error,
rests_until: forever ? undefined : rests_until,
});
}
}
}
+8
View File
@@ -14,6 +14,7 @@ import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-
import textSeesImages from "@/src/utils/text-sees-images";
import grabChatParams from "./grab-chat-params";
import flattenSentParams from "../usage/flatten-sent-params";
import type { HarnessCallLimits } from "../usage/types";
import prepareMessagesForModel from "./prepare-messages-for-model";
import stripThinkTags from "./strip-think-tags";
@@ -29,6 +30,11 @@ export type GenerateTextParams = {
*/
prefer_key?: string;
max_tokens?: number;
/**
* The run's own bounds, kept with the call's usage
* (`HarnessCallLimits`) so the answer says later which limit shaped it.
*/
limits?: HarnessCallLimits;
/**
* Overrides the saved generation settings (media reading wants 0).
*/
@@ -76,6 +82,7 @@ export default async function generateText({
candidates,
prefer_key,
max_tokens,
limits,
params,
signal = new AbortController().signal,
media_cache = new Map(),
@@ -108,6 +115,7 @@ export default async function generateText({
...(saved_params ? { settings_source: saved_params.source } : {}),
params: flattenSentParams({ params: answer.sent_params }),
...(max_tokens ? { max_tokens } : {}),
...(limits ? { limits } : {}),
},
}),
}),
+250 -3
View File
@@ -1,7 +1,8 @@
import { describe, expect, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { alreadyRanToolNote, DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
@@ -207,6 +208,34 @@ describe("runTextLoop", () => {
});
});
test("a run with no step limit keeps going, and records that its limits were off", async () => {
memory.length = 0;
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const turns = 30;
const { generate, seen } = scripted(Array.from({ length: turns }, () => loop_call));
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
max_steps: UnlimitedLimit,
generate,
resolveCandidates,
});
expect(seen).toHaveLength(turns + 1);
expect(result.steps).toBe(turns + 1);
expect(result.text).toBe("Done.");
expect(JSON.stringify(seen)).not.toContain("left in this run");
expect(seen[0]!.limits).toEqual({
steps: UnlimitedLimit,
run_tokens: UnlimitedLimit,
context_tokens: UnlimitedLimit,
});
});
test("at the wrap up, offers only the tools that save, then answers without any", async () => {
const save: HarnessTool<{ path: string }> = {
name: "write_file",
@@ -286,6 +315,83 @@ describe("runTextLoop", () => {
expect(result.text).toBe("Report saved.");
});
test("hands the work it can't finish to start_task at the wrap up", async () => {
const hand_off: HarnessTool<{ brief: string }> = {
name: "start_task",
description: "Queues a run.",
schema: z.object({ brief: z.string() }),
run: async ({ args }) => `Run #7 queued: ${args.brief}`,
};
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted([
loop_call,
{
tool_calls: [{ id: "t", name: "start_task", arguments: `{"brief":"write the piece"}` }],
},
{ text: "Research done; the writing is queued as a run." },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "write the guide" }],
tools: [remember, hand_off],
max_steps: 1,
generate,
resolveCandidates,
});
expect(seen).toHaveLength(3);
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["start_task"]);
expect(seen[1]!.messages.at(-1)!.content).toContain(
"one turn to hand the work on: start_task is still yours",
);
expect(seen[2]!.tools).toBe(undefined);
expect(result.tool_uses).toEqual([
{ name: "remember", ok: true },
{ name: "start_task", ok: true },
]);
expect(result.text).toBe("Research done; the writing is queued as a run.");
});
test("offers the saving tools and the hand off together", async () => {
const save: HarnessTool<{ path: string }> = {
name: "write_file",
description: "Saves a file.",
schema: z.object({ path: z.string() }),
run: async ({ args }) => `Saved ${args.path}.`,
};
const hand_off: HarnessTool<{ brief: string }> = {
name: "start_task",
description: "Queues a run.",
schema: z.object({ brief: z.string() }),
run: async ({ args }) => `Run #7 queued: ${args.brief}`,
};
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted([
loop_call,
{ text: "Saved what I have." },
]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "audit the disk" }],
tools: [remember, save, hand_off],
max_steps: 1,
generate,
resolveCandidates,
});
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["write_file", "start_task"]);
const prompt = String(seen[1]!.messages.at(-1)!.content);
expect(prompt).toContain("one turn to save what the user needs: write_file");
expect(prompt).toContain("call start_task with a complete brief of what's left");
});
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
const max_steps = AppData.HarnessStepsLowMinSteps;
const loop_call = {
@@ -318,8 +424,8 @@ describe("runTextLoop", () => {
* A 200 step audit once measured to its last step with the report
* unwritten: the warning has to reach it with real room left.
*/
expect(stepsLowWarningLeft({ max_steps: AppData.HarnessMaxToolSteps })).toBe(
Math.ceil(AppData.HarnessMaxToolSteps * AppData.HarnessStepsLowWarnShare),
expect(stepsLowWarningLeft({ max_steps: 200 })).toBe(
Math.ceil(200 * AppData.HarnessStepsLowWarnShare),
);
expect(stepsLowWarningLeft({ max_steps: 20 })).toBe(AppData.HarnessStepsLowWarning);
});
@@ -739,3 +845,144 @@ describe("runTextLoop", () => {
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
});
});
describe("runTextLoop repeated reads", () => {
const readCall = ({ id, path }: { id: string; path: string }) => ({
id,
name: "read_file",
arguments: JSON.stringify({ path }),
});
/**
* A read that counts how often it actually ran, and a write that only
* exists to change what a read would say.
*/
const makeTools = () => {
const counts = { reads: 0, writes: 0 };
const read: HarnessTool<{ path: string }> = {
name: "read_file",
description: "Reads a file.",
schema: z.object({ path: z.string() }),
run: async ({ args }) => {
counts.reads++;
return `contents of ${args.path} (read ${counts.reads})`;
},
};
const write: HarnessTool<{ path: string }> = {
name: "write_file",
description: "Writes a file.",
schema: z.object({ path: z.string() }),
run: async () => {
counts.writes++;
return "Saved.";
},
};
return { tools: [read, write], counts };
};
test("answers a read repeated word for word from the first", async () => {
const { tools, counts } = makeTools();
const { generate, seen } = scripted([
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
{ text: null, tool_calls: [readCall({ id: "c2", path: "a.md" })] },
{ text: "Done.", tool_calls: [] },
]);
const result = await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read a.md twice." }],
tools,
generate,
resolveCandidates,
});
expect(counts.reads).toBe(1);
expect(result.tool_uses.map((use) => use.ok)).toEqual([true, true]);
const results = seen[2]!.messages.filter((message) => message.role == "tool");
expect(results.map((message) => message.role == "tool" && message.content)).toEqual([
"contents of a.md (read 1)",
alreadyRanToolNote({ name: "read_file", step: 0 }),
]);
});
test("reads again after something may have written", async () => {
const { tools, counts } = makeTools();
const { generate, seen } = scripted([
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
{ text: null, tool_calls: [{ id: "c2", name: "write_file", arguments: `{"path":"a.md"}` }] },
{ text: null, tool_calls: [readCall({ id: "c3", path: "a.md" })] },
{ text: "Done.", tool_calls: [] },
]);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Update a.md." }],
tools,
generate,
resolveCandidates,
});
expect(counts.reads).toBe(2);
expect(counts.writes).toBe(1);
const results = seen[3]!.messages.filter((message) => message.role == "tool");
expect(results.map((message) => message.role == "tool" && message.content)).toEqual([
"contents of a.md (read 1)",
"Saved.",
"contents of a.md (read 2)",
]);
});
test("reads a different file on its own", async () => {
const { tools, counts } = makeTools();
const { generate } = scripted([
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" }), readCall({ id: "c2", path: "b.md" })] },
{ text: "Done.", tool_calls: [] },
]);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read both." }],
tools,
generate,
resolveCandidates,
});
expect(counts.reads).toBe(2);
});
test("keeps its own answers apart from other runs", async () => {
const { tools, counts } = makeTools();
const turns = [
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
{ text: "Done.", tool_calls: [] },
];
const first = scripted(turns);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read a.md." }],
tools,
generate: first.generate,
resolveCandidates,
});
const second = scripted(turns);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read a.md." }],
tools,
generate: second.generate,
resolveCandidates,
});
expect(counts.reads).toBe(2);
});
});
+146 -44
View File
@@ -1,7 +1,10 @@
import { AppData } from "@/src/data/app-data";
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
import HarnessError from "../harness-error";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import loadToolsTool from "../tools/load-tools-tool";
import repeatToolCallKey from "../tools/repeat-tool-call-key";
import runToolCall from "../tools/run-tool-call";
import toolDefinition from "../tools/tool-definition";
import type {
@@ -44,19 +47,19 @@ type Params = {
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
*/
tools?: HarnessTool[];
max_steps?: number;
max_steps?: RunLimit;
/**
* Prompt tokens the run may spend in all (`grabRunMaxPromptTokens`):
* once its turns have sent this many, the next one is the wrap up.
* Left out, only `max_steps` ends it.
* Unlimited or left out, only the run's other bounds end it.
*/
max_prompt_tokens?: number;
max_prompt_tokens?: RunLimit;
/**
* The working context (`grabContextBudgetTokens`): the most each turn
* sends before old tool output is trimmed, whatever the model's
* window. Left out, the window decides.
* window. Unlimited or left out, the window decides.
*/
context_budget?: number;
context_budget?: RunLimit;
signal?: AbortSignal;
/**
* Called after each model turn, before its tools run. Use it for
@@ -117,12 +120,29 @@ export type TextLoopResult = {
};
/**
* The only tools the wrap up may still call: saving the work. A run that
* spent every step measuring can write the report the user waits for
* rather than throw its findings away (`write_file`, and `import_file`
* for what it pulled off a computer).
* The wrap-up tools that save the work. A run that spent every step
* measuring can write the report the user waits for rather than throw its
* findings away (`write_file`, and `import_file` for what it pulled off a
* computer).
*/
export const WrapUpToolNames = ["write_file", "import_file"];
export const WrapUpSaveToolNames = ["write_file", "import_file"];
/**
* The wrap-up tool that hands the work on. A chat reply has a step
* budget (`AppData.BotReplyMaxToolSteps`, unlimited unless the install
* sets one), and a reply that used it all researching leaves the writing
* undone; the next reply starts from the same budget, so the run queues
* the rest as a task (`start_task`) while it can still call a tool,
* rather than saying it will do it later. The app runs it as soon as the
* reply is out.
*/
export const WrapUpHandOffToolNames = ["start_task"];
/**
* Every tool the wrap up may still call (`WrapUpSaveToolNames` and
* `WrapUpHandOffToolNames`): those the run has, in its own order.
*/
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames];
/**
* Saving turns a wrap up may take: the first, and one more when it reached
@@ -134,26 +154,50 @@ export const WrapUpSavingTurns = 2;
* Told on the last step, with the app's record of the tools the run
* called (`describeToolUses`): out of steps, a model tends to report the
* work it planned as done. `tokens` when the run's token budget ended it
* rather than its steps. `saving` names the tools it may still call, if
* any: its one saving round, after which it answers with none.
* rather than its steps. `saving` and `hand_off` name the tools it may
* still call, if any: its one last round, after which it answers with
* none.
*/
export const wrapUpPrompt = ({
uses,
reason = "steps",
saving = [],
hand_off = [],
}: {
uses: HarnessToolUse[];
reason?: "steps" | "tokens";
saving?: string[];
hand_off?: string[];
}) =>
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${
saving.length
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable) and nothing else, then report. After this turn no tool is left, so anything unsaved is lost.`
: `Don't call any more tools.`
} Report what you did, what is left, and anything you need from the user.
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${wrapUpToolsPrompt({
saving,
hand_off,
})} Report what you did, what is left, and anything you need from the user.
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
/**
* What the wrap up may still call, said in one line: save the work, hand
* on what it can't finish, or neither.
*/
const wrapUpToolsPrompt = ({ saving, hand_off }: { saving: string[]; hand_off: string[] }) => {
if (!saving.length && !hand_off.length) return `Don't call any more tools.`;
return [
saving.length
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable) and nothing else, then report.`
: "",
saving.length
? `If real work is left that this run can't finish, call ${hand_off.join(" or ")} with a complete brief of what's left: it runs after this turn and posts its own result.`
: hand_off.length
? `You have one turn to hand the work on: ${hand_off.join(" or ")} is still yours. If real work is left, call it with a complete brief of what's left: it runs after this turn and posts its own result.`
: "",
`After this turn no tool is left, so anything unsaved is lost, and so is work you only say you'll do later.`,
]
.filter(Boolean)
.join(" ");
};
/**
* Steps left when a run is warned, once, to save: a share of the run for
* long ones, since 5 steps is the whole budget of a short one and no time
@@ -195,8 +239,11 @@ Don't repeat tool calls you have already made.`;
* go back to it, and so on until it answers without calling a tool. Tools
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
* model is asked to wrap up: one turn with only the saving tools
* (`WrapUpToolNames`), then one with none. An answer `review` finds fault
* model is asked to wrap up: one turn with only the wrap-up tools
* (`WrapUpToolNames`: what saves the work, and `start_task` for the rest),
* then one with none. With neither set (unlimited), the run ends when the
* model answers without calling a tool, or when its job's deadline or its
* abort signal ends it. An answer `review` finds fault
* with is written again once.
*
* Every turn resends everything, so the run keeps it small: only the
@@ -262,17 +309,45 @@ export default async function runTextLoop({
};
const tool_uses: HarnessToolUse[] = [];
/**
* The tools a wrap up may still call: only the ones that save the work.
* A run that spent every step measuring can then still write the report
* the user is waiting for, which is what two runs in a row failed to do
* (they measured to the last step and had no tool left to save with).
* The reads this run already made, by the call they answer
* (`repeatToolCallKey`) and the step it was. A read repeated word for
* word gets this answer instead of being run again, and anything that
* may have written forgets them: a file read once, then edited, is
* read again.
*/
const save_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
const save_definitions = save_tools.map((tool) => all_definitions.get(tool.name)!);
const warn_at = stepsLowWarningLeft({ max_steps });
const repeated_reads = new Map<string, number>();
/**
* The tools a wrap up may still call: what saves the work, and
* `start_task` for the work it can't finish. A run that spent every
* step measuring can then still write the report the user is waiting
* for, which is what two runs in a row failed to do (they measured to
* the last step and had no tool left to save with), and a reply out of
* steps hands the rest to a task instead of promising it.
*/
const wrap_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
const save_tools = wrap_tools.filter((tool) => WrapUpSaveToolNames.includes(tool.name));
const hand_off_tools = wrap_tools.filter((tool) => WrapUpHandOffToolNames.includes(tool.name));
const wrap_definitions = wrap_tools.map((tool) => all_definitions.get(tool.name)!);
/**
* What bounds this run, recorded with every call it makes, so a reply
* can be told later which limit shaped it (`read_message_usage`).
* `null` only ever means an old record; new runs say `"unlimited"`.
*/
const call_limits = {
steps: max_steps,
run_tokens: max_prompt_tokens ?? UnlimitedLimit,
context_tokens: context_budget ?? UnlimitedLimit,
};
/**
* A step count to count against, for the loop itself: an unlimited run
* counts on to the model's own answer (or the job's deadline).
*/
const step_ceiling = isUnlimitedLimit(max_steps) ? Infinity : max_steps;
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
let prefer_key: string | undefined;
let reviewed = false;
let warned_steps = max_steps < AppData.HarnessStepsLowMinSteps;
let warned_steps = isUnlimitedLimit(max_steps) || max_steps < AppData.HarnessStepsLowMinSteps;
/**
* The wrap up is announced once, and may save until it has: a run told
* to stop with its report unwritten gets a turn to write it (at most
@@ -280,22 +355,31 @@ export default async function runTextLoop({
*/
let wrap_up_announced = false;
let saving_turns = 0;
let saved = false;
/**
* The wrap up had its one round of tools (saving, or handing the work
* on): the next turn offers none, so the run always ends.
*/
let used_wrap_turn = false;
for (let index = 0; index <= max_steps + 1 + WrapUpSavingTurns; index++) {
for (let index = 0; index <= step_ceiling + 1 + WrapUpSavingTurns; index++) {
if (signal.aborted) {
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
}
const out_of_steps = index >= max_steps;
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens);
const out_of_steps = index >= step_ceiling;
const out_of_tokens = Boolean(
typeof max_prompt_tokens == "number" &&
max_prompt_tokens > 0 &&
usage.prompt_tokens >= max_prompt_tokens,
);
const wrap_up = out_of_steps || out_of_tokens;
/**
* The saving turn: only the tools that save the work. Without one
* of them, or once it saved, the wrap up is the old one, with no
* tools at all, so the run always ends.
* The saving turn: only the tools a wrap up has left. Without one
* of them, or once it had its round, the wrap up is the old one,
* with no tools at all, so the run always ends.
*/
const wrap_up_saving = wrap_up && !saved && saving_turns < WrapUpSavingTurns && save_tools.length > 0;
const wrap_up_saving =
wrap_up && !used_wrap_turn && saving_turns < WrapUpSavingTurns && wrap_tools.length > 0;
if (wrap_up && !wrap_up_announced) {
wrap_up_announced = true;
@@ -308,13 +392,14 @@ export default async function runTextLoop({
uses: tool_uses,
reason: out_of_steps ? "steps" : "tokens",
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
}),
});
}
if (wrap_up_saving) saving_turns++;
const definitions = wrap_up_saving ? save_definitions : wrap_up ? [] : definitionsNow();
const definitions = wrap_up_saving ? wrap_definitions : wrap_up ? [] : definitionsNow();
/**
* Sized for the model the run is on (or will start on). A fallback
@@ -325,8 +410,8 @@ export default async function runTextLoop({
fitTranscriptToContext({
system: run_system,
transcript,
context_length: model?.context_length || AppData.HarnessAutoMinContext,
budget_tokens: context_budget,
context_length: model?.context_length || AppData.HarnessUnknownContextWindow,
budget_tokens: typeof context_budget == "number" ? context_budget : undefined,
tools_chars: JSON.stringify(definitions).length,
});
@@ -339,6 +424,7 @@ export default async function runTextLoop({
media_cache,
bot_id,
workspace_id,
limits: call_limits,
});
prefer_key = answer.candidate.key;
@@ -351,7 +437,7 @@ export default async function runTextLoop({
* saving ones, and the last turn offers none.
*/
const tool_calls = (wrap_up ? (wrap_up_saving ? answer.tool_calls : []) : answer.tool_calls).filter(
(call) => !wrap_up || save_tools.some((tool) => tool.name == call.name),
(call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name),
);
/**
@@ -362,7 +448,7 @@ export default async function runTextLoop({
if (wrap_up_saving && answer.tool_calls.length && !tool_calls.length) {
pushUserTurn({
transcript,
content: `Only ${save_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
content: `Only ${wrap_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
});
continue;
}
@@ -412,12 +498,18 @@ export default async function runTextLoop({
};
}
if (wrap_up_saving) saved = true;
if (wrap_up_saving) used_wrap_turn = true;
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
for (const call of tool_calls) {
const { text: content, images } = await runToolCall({ call, tools: run_tools, signal });
const repeat_key = repeatToolCallKey({ call });
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
const { text: content, images } =
already_read !== undefined
? { text: alreadyRanToolNote({ name: call.name, step: already_read }), images: [] }
: await runToolCall({ call, tools: run_tools, signal });
/**
* A deferred tool called without loading it ran all the same;
@@ -428,6 +520,14 @@ export default async function runTextLoop({
}
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
if (!repeat_key) {
repeated_reads.clear();
} else if (already_read === undefined) {
if (content.startsWith("Error:")) repeated_reads.delete(repeat_key);
else repeated_reads.set(repeat_key, index);
}
transcript.push({ role: "tool", tool_call_id: call.id, content });
if (images.length) shown.push({ tool_name: call.name, images });
@@ -454,10 +554,12 @@ export default async function runTextLoop({
/**
* Steps left before the wrap up, once the next turn is taken.
* An unlimited run is never told it's nearly out: it has no budget
* to be near the end of.
*/
const left = max_steps - (index + 1);
const left = step_ceiling - (index + 1);
if (!warned_steps && left <= warn_at) {
if (!warned_steps && !isUnlimitedLimit(max_steps) && left <= warn_at) {
warned_steps = true;
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
}
@@ -0,0 +1,87 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
/**
* The task being handed over, and what `handOverTask` answered with it:
* what a hand-over passes on is the whole point of these tests, so the
* helper is mocked and its arguments recorded.
*/
let task = {
id: 27,
title: "Rewrite the pricing page",
bot_id: 4,
workspace_id: 3,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
let handedArgs: Record<string, unknown> | null = null;
let handed: Record<string, unknown> = {};
mock.module("@/src/functions/backend/db/tasks/grab-run-task", () => ({
default: async () => task,
}));
mock.module("@/src/functions/backend/db/tasks/hand-over-task", () => ({
default: async (args: Record<string, unknown>) => {
handedArgs = args;
return handed;
},
}));
const delegateTaskTool = (await import("./delegate-task-tool")).default;
afterAll(() => {
mock.restore();
});
const worker = { id: 5, name: "Researcher", role: "research", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const signal = new AbortController().signal;
function tool() {
return delegateTaskTool({
user_id: 1,
requester_id: 1,
session_id: 10,
requester_name: "Coordinator",
workers: [worker],
workspaces: [],
grabTargets: async () => [worker],
});
}
beforeEach(() => {
task = {
id: 27,
title: "Rewrite the pricing page",
bot_id: 4,
workspace_id: 3,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
handedArgs = null;
handed = { task, job_id: null, bot_name: "Researcher", workspace_id: 3, joined: "" };
});
describe("delegateTaskTool, handing over a task on a list", () => {
test("moves it as to do by default: no run is queued", async () => {
const answer = await tool().run({ args: { bot_id: 5, task_id: 27 }, signal });
expect(handedArgs?.start).toBe(false);
expect(handedArgs?.task_id).toBe(27);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("starts it only with start: true, when the user asked for that", async () => {
handed = { task, job_id: 318, bot_name: "Researcher", workspace_id: 3, joined: "" };
const answer = await tool().run({ args: { bot_id: 5, task_id: 27, start: true }, signal });
expect(handedArgs?.start).toBe(true);
expect(String(answer)).toContain("is with Researcher now (job #318)");
expect(String(answer)).toContain("marked doing");
});
test("says a hand-over starts nothing, and to ask before it moves", () => {
expect(tool().description).toContain("Handing a task over never starts it");
expect(tool().description).toContain("ask first with ask_user");
});
});
@@ -96,11 +96,11 @@ describe("delegateTaskTool", () => {
expect(tool.description).toContain("task_id");
});
test("can hand a task over without starting it", () => {
test("hands a task over as to do unless told to start it", () => {
const tool = coordinatorTool();
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: false }).success).toBe(true);
expect(tool.description).toContain("start: false");
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: true }).success).toBe(true);
expect(tool.description).toContain("start: true");
});
test("without a task_id, still needs a title and instructions", async () => {
+5 -4
View File
@@ -69,7 +69,8 @@ type Args = {
*/
task_id?: number;
/**
* With `task_id`: false to only move the task, nothing started.
* The user asked for that task's work to begin now (with `task_id`):
* left out it only moves, to do, and no run is spent.
*/
start?: boolean;
title?: string;
@@ -114,7 +115,7 @@ export default function delegateTaskTool({
return {
name: "delegate_task",
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there), goes to doing, and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. When the user hasn't asked for that task's work to begin yet (they want it moved, or to decide first), add start: false: it only moves to their list as to do, and no run is spent on reporting that they're waiting. Crew: ${crew}.${
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there) and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. Handing a task over never starts it: it lands there as to do, and only start: true (when the user asked for the work to begin now) marks it doing and queues the run. When the user asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it) and hand over only once they've answered. A new brief with no task_id always runs at once. Crew: ${crew}.${
workspace_id
? ` You are working in a workspace, so the task runs there: in this workspace's context.`
: ` Leave workspace_id out to run it in the crew member's own chat: only its own memory, files and directly assigned computers apply there, and the user finds the result by talking to it on its own. Add workspace_id to run it in one of the user's workspaces instead: the workspace's shared context, the member's instructions and memory there, its files and its computers (the workspace's own and the member's) all apply, and the result lands in its conversation in that workspace, beside the project it belongs to. Pick a workspace when the work belongs to that project; the member is added to it when it isn't in it yet. Workspaces: ${places || "none"}.`
@@ -125,7 +126,7 @@ export default function delegateTaskTool({
start: z
.boolean()
.optional()
.describe("With task_id: false to only move the task (to do, nothing runs) until the user says to start"),
.describe("With task_id: true to start the work at once, only when the user asked for it; left out it only moves (to do, nothing runs)"),
title: z.string().min(1).max(80).optional(),
instructions: z.string().min(1).max(8000).optional(),
workspace_id: z
@@ -198,7 +199,7 @@ export default function delegateTaskTool({
handed_by: requester_name,
requested_by_bot_id: requester_id,
requested_by_session_id: session_id,
start: args.start !== false,
start: args.start === true,
});
onTask?.({ task_id: Number(task.id) });
@@ -37,6 +37,9 @@ mock.module("@/src/functions/backend/db/workspaces/grab-user-workspaces", () =>
mock.module("@/src/functions/backend/db/bots/grab-crew-workers", () => ({
default: async () => workers,
}));
mock.module("@/src/functions/backend/db/chatrooms/chatroom-askable-bots", () => ({
default: async () => workers,
}));
const grabBotChatTools = (await import("./grab-bot-chat-tools")).default;
@@ -66,6 +69,32 @@ async function names({ workspace_id }: { workspace_id: number | null }) {
return tools.map((tool) => tool.name);
}
/**
* The same list for a plain worker: no work to hand out, only its own task to
* pass on, to a bot it could ask (`chatroomAskableBots`).
*/
async function workerNames({ workspace_id, allowed = ["hand_over_task"] }: { workspace_id: number | null; allowed?: string[] }) {
const worker = {
bot_types: [],
is_coordinator: false,
admin_workspace_ids: [],
is_workspace_admin: false,
can: (permission: string) => allowed.includes(permission),
};
const tools = await grabBotChatTools({
bot: { id: 5, kind: "worker", name: "SEO Expert" },
powers: worker,
user_id: 1,
computers: [],
session_id: 43,
workspace_id,
onPropose: () => {},
});
return tools.map((tool) => tool.name);
}
describe("grabBotChatTools", () => {
test("the coordinator in a workspace reaches the install's skills, servers and tools", async () => {
workers = [{ id: 5, name: "A worker", kind: "worker" }];
@@ -93,4 +122,23 @@ describe("grabBotChatTools", () => {
expect(list).toContain("list_extensions");
expect(list).toContain("propose_skill");
});
test("a worker gets no work to hand out, only its own task to pass on", async () => {
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
const list = await workerNames({ workspace_id: 11 });
expect(list).toContain("hand_over_task");
expect(list).not.toContain("delegate_task");
expect(list).not.toContain("manage_workspace_tasks");
});
test("a worker whose types don't allow it gets neither", async () => {
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
const list = await workerNames({ workspace_id: 11, allowed: [] });
expect(list).not.toContain("hand_over_task");
expect(list).not.toContain("delegate_task");
});
});
+32 -7
View File
@@ -24,6 +24,8 @@ import updateWorkspaceTool from "./update-workspace-tool";
import listWorkspacePeopleTool from "./list-workspace-people-tool";
import setUserWorkspaceRoleTool from "./set-user-workspace-role-tool";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import chatroomAskableBots from "@/src/functions/backend/db/chatrooms/chatroom-askable-bots";
import handOverTaskTool from "./hand-over-task-tool";
import setWorkspaceInstructionsTool from "./set-workspace-instructions-tool";
import startTaskTool from "./start-task-tool";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -111,9 +113,10 @@ type Params = {
* workspace's crew (a bot's core prompt is asked for from wherever the
* user is), plus set_bot_type to make a worker a workspace's admin. A
* workspace admin, in the workspace it leads, gets
* `grabWorkspaceAdminTools`. Every gate reads the bot's types (`powers`),
* never `bots.kind`. Anything else on a computer goes through a task,
* never mid-reply.
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
* a computer goes through a task, never mid-reply.
*/
export default async function grabBotChatTools({
bot,
@@ -169,12 +172,34 @@ export default async function grabBotChatTools({
];
if (!powers.is_coordinator) {
if (!workspace_id || !powers.is_workspace_admin) return tools;
if (workspace_id && powers.is_workspace_admin) {
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
return tools;
}
/**
* Only what it already has goes: the bots it may hand to are the
* ones it could ask for this user, read again when it does.
*/
if (session_id && powers.can("hand_over_task")) {
const workers = await chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id });
tools.push(
handOverTaskTool({
user_id,
bot,
session_id,
powers,
workers,
grabTargets: () => chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id }),
onTask,
}),
);
}
return tools;
}
+4
View File
@@ -12,6 +12,8 @@ import updateMemoryTool from "./update-memory-tool";
import reactToMessageTool from "./react-to-message-tool";
import setPictureTool from "./set-picture-tool";
import askCrewTool from "./ask-crew-tool";
import readMessageUsageTool from "./settings/read-message-usage-tool";
import readSettingsTool from "./settings/read-settings-tool";
import type { StorageScope } from "@/src/utils/storage-access";
type Params = {
@@ -93,6 +95,8 @@ export default async function grabBotTools({
}: Params): Promise<HarnessTool[]> {
return [
setPictureTool({ user_id, bot_id, scopes, is_coordinator }),
readSettingsTool(),
readMessageUsageTool({ session_id }),
updateMemoryTool({ user_id, bot_id, workspace_id }),
updateInstructionsTool({ user_id, bot_id, workspace_id }),
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
@@ -0,0 +1,179 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
/**
* What `grabRunTask` answers: the task it would act on.
*/
let task: BUN_SQLITE_COBBLE_TASKS = {
id: 43,
title: "Cut the LCP on the homepage",
bot_id: 2,
workspace_id: 2,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
/**
* What `handOverTask` answers, and with which arguments it was called: a
* worker's hand-over has to carry the bot that had the task and the session
* the result is reported back to.
*/
let handed: Record<string, unknown> = {};
let handedArgs: Record<string, unknown> | null = null;
mock.module("@/src/functions/backend/db/tasks/grab-run-task", () => ({
default: async () => task,
}));
mock.module("@/src/functions/backend/db/tasks/hand-over-task", () => ({
default: async (args: Record<string, unknown>) => {
handedArgs = args;
return handed;
},
}));
const handOverTaskTool = (await import("./hand-over-task-tool")).default;
afterAll(() => {
mock.restore();
});
const bot = { id: 2, name: "SEO Expert", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const engineer = { id: 6, name: "Software Engineer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const designer = { id: 3, name: "Graphic Designer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const powers = {
bot_types: [],
is_coordinator: false,
admin_workspace_ids: [],
is_workspace_admin: false,
can: (permission: string) => permission == "hand_over_task",
} as unknown as BotRunPowers;
beforeEach(() => {
task = { id: 43, title: "Cut the LCP on the homepage", bot_id: 2, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
handedArgs = null;
});
function build({ targets = [engineer, designer], onTask }: { targets?: BUN_SQLITE_COBBLE_BOTS[]; onTask?: (params: { task_id: number }) => void } = {}) {
return handOverTaskTool({
user_id: 1,
bot,
session_id: 43,
powers,
workers: targets,
grabTargets: async () => targets,
onTask,
});
}
describe("handOverTaskTool", () => {
test("takes a task of its own and one of the bots it can ask", () => {
const tool = build();
expect(tool.name).toBe("hand_over_task");
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6 }).success).toBe(true);
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6, start: false }).success).toBe(true);
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6, start: true }).success).toBe(true);
expect(tool.schema?.safeParse({ bot_id: 6 }).success).toBe(false);
});
test("names the crew it can hand to", () => {
const tool = build();
expect(tool.description).toContain("6: Software Engineer; 3: Graphic Designer");
});
test("tells the bot to ask before the task leaves its list, and that a hand-over starts nothing", () => {
const tool = build();
expect(tool.description).toContain("Handing it over never starts it");
expect(tool.description).toContain("ask first with ask_user");
});
test("hands the task over with the bot and session to report back to", async () => {
const answer = await build().run({ args: { task_id: 43, bot_id: 6, start: true }, signal: new AbortController().signal });
expect(handedArgs?.task_id).toBe(43);
expect(handedArgs?.to_bot_id).toBe(6);
expect(handedArgs?.user_id).toBe(1);
expect(handedArgs?.handed_by).toBe("SEO Expert");
expect(handedArgs?.requested_by_bot_id).toBe(2);
expect(handedArgs?.requested_by_session_id).toBe(43);
expect(handedArgs?.start).toBe(true);
expect(String(answer)).toContain("is with Software Engineer now (job #312)");
expect(String(answer)).toContain("it's off your list");
expect(String(answer)).toContain("their result is reported back here");
});
test("the same task, not a copy: it reports the new bot's joined note", async () => {
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "It joined the workspace." };
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(String(answer)).toContain("It joined the workspace.");
});
test("moves it as to do unless the user asked to start it", async () => {
handed = { task, job_id: null, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(handedArgs?.start).toBe(false);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("an explicit start: false asks for the same move", async () => {
handed = { task, job_id: null, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
const answer = await build().run({ args: { task_id: 43, bot_id: 6, start: false }, signal: new AbortController().signal });
expect(handedArgs?.start).toBe(false);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("reports the task it touched, so the message links it", async () => {
const touched: number[] = [];
await build({ onTask: ({ task_id }) => touched.push(task_id) }).run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(touched).toEqual([43]);
});
test("refuses a task that isn't its own", async () => {
task = { id: 44, title: "Someone else's", bot_id: 9, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
"isn't on your own list (it's another bot's), so it isn't yours to hand over",
);
expect(handedArgs).toBeNull();
});
test("refuses a workspace-wide task", async () => {
task = { id: 44, title: "Everyone's", bot_id: null, workspace_id: 2, status: "todo" } as unknown as BUN_SQLITE_COBBLE_TASKS;
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow("(it's workspace-wide)");
});
test("refuses a bot it can't ask, and lists the ones it can", async () => {
await expect(build().run({ args: { task_id: 43, bot_id: 99 }, signal: new AbortController().signal })).rejects.toThrow(
"No bot has id 99 among the ones you can hand to. Bot: 6: Software Engineer; 3: Graphic Designer.",
);
expect(handedArgs).toBeNull();
});
test("with no crew says so", async () => {
const tool = build({ targets: [] });
expect(tool.description).toContain("Crew you can hand to: none.");
await expect(tool.run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
"No bot has id 6 among the ones you can hand to. Bot: none.",
);
});
});
@@ -0,0 +1,130 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import handOverTask from "@/src/functions/backend/db/tasks/hand-over-task";
import type { HarnessTool } from "../../types";
type Params = {
user_id: number | string;
/**
* The bot passing its own task on: the worker that has it, or a
* workspace's admin.
*/
bot: BUN_SQLITE_COBBLE_BOTS;
/**
* The session it hands over from: the new bot's result is reported
* back there (`relayJobToRequester`).
*/
session_id: number | string;
/**
* The run's reach over the task tracker (`grabBotRunPowers`), beside the
* check that the task is this bot's own.
*/
powers: BotRunPowers;
/**
* The bots it may hand to, for the description (`chatroomAskableBots`).
*/
workers: BUN_SQLITE_COBBLE_BOTS[];
/**
* Reads the bots it may hand to when it does, so a bot added mid-run is
* there: the ones it could ask (`chatroomAskableBots`).
*/
grabTargets: () => Promise<BUN_SQLITE_COBBLE_BOTS[]>;
/**
* Called with the task it hands over, so the message the run posts links
* to it (`bot_messages.task_ids`).
*/
onTask?: (params: { task_id: number }) => void;
};
type Args = {
task_id: number;
bot_id: number;
/**
* True only when the user asked for the work to begin now. Left out the
* task only moves: it goes to the other bot's list as to do and no job
* is queued.
*/
start?: boolean;
};
/**
* Lets a bot give a task on its own list to another bot (`handOverTask`):
* the narrow hand-over of `delegate_task`, for the runs that have no right
* to hand out work. It only ever moves a task the run already has, only an
* open one, and only to a bot it could ask for the same user, so it can't
* create a task for someone else or widen a run's reach. The task keeps its
* place (a workspace's stays there) and moves as to do: it never starts the
* work unless the user asked for that (`start`), and when they only asked
* for the move the bot asks first. The other bot works that same task, and
* the result is reported back in this session.
*/
export default function handOverTaskTool({ user_id, bot, session_id, powers, workers, grabTargets, onTask }: Params): HarnessTool<Args> {
const bot_id = bot.id || 0;
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
return {
name: "hand_over_task",
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_crew; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
schema: z.object({
task_id: z.number().int().describe("An open task on your own list (list_tasks)"),
bot_id: z.number().int(),
start: z
.boolean()
.optional()
.describe("true to start the work at once, only when the user asked for it; left out it only moves (to do, nothing runs)"),
}),
run: async ({ args }) => {
const task = await grabRunTask({
task_id: args.task_id,
bot_id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
});
/**
* A workspace-wide task is nobody's: handing it to one bot would
* take it away from the rest of the crew.
*/
if (Number(task.bot_id || 0) != bot_id) {
throw new Error(
`Task #${task.id} isn't on your own list (it's ${
task.workspace_id && !task.bot_id ? "workspace-wide" : "another bot's"
}), so it isn't yours to hand over.`,
);
}
const fresh = await grabTargets();
if (!fresh.some((target) => target.id == args.bot_id)) {
throw new Error(
`No bot has id ${args.bot_id} among the ones you can hand to. Bot: ${
fresh.map((target) => `${target.id}: ${target.name}`).join("; ") || "none"
}.`,
);
}
const handed = await handOverTask({
user_id,
task_id: Number(task.id),
to_bot_id: args.bot_id,
instructions: undefined,
handed_by: bot.name || "The bot that had it",
requested_by_bot_id: bot_id,
requested_by_session_id: session_id,
start: args.start === true,
});
onTask?.({ task_id: Number(task.id) });
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in its own chat";
if (!handed.job_id) {
return `Task #${task.id} "${task.title}" is on ${handed.bot_name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.${handed.joined ? ` ${handed.joined}` : ""}`;
}
return `Task #${task.id} "${task.title}" is with ${handed.bot_name} now (job #${handed.job_id})${where}, marked doing, and it's off your list.${handed.joined} They work that same task; their result is reported back here.`;
},
};
}
@@ -0,0 +1,92 @@
import { z } from "zod";
import grabRunLimitsOverview from "@/src/functions/backend/db/app-settings/grab-run-limits";
import {
grabJobRunUsage,
grabMessageRunUsage,
grabSessionMessageUsage,
type CurrentRunLimits,
} from "@/src/functions/backend/db/usage/grab-run-usage";
import { grabHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
import describeRunUsage, { describeMessageUsageList } from "@/src/utils/describe-run-usage";
import type { HarnessTool } from "../../../types";
type Params = {
session_id?: number | string | null;
};
type Args = {
message_id?: number;
job_id?: number;
latest?: boolean;
};
/**
* What a run or one of its answers cost, call by call: the model, the
* prompt and completion tokens, the cached part, the settings each call was
* made with, and the limits the run worked under against today's. With no
* ids it lists the conversation's latest messages so a bot can find the one
* a user is asking about, then read it by id.
*/
export default function readMessageUsageTool({ session_id }: Params): HarnessTool<Args> {
return {
name: "read_message_usage",
description: `Look at what model calls a run cost, to answer "why did that cost so much" or "why was that reply cut short".
With no arguments it lists this conversation's latest messages with their token totals and ids. Pass a message_id to dig into one: every call it took (provider and model, prompt and completion tokens, how much came from the model's cache), the limits the run worked under as recorded then, today's limits for comparison, and the tools it called, counted.
Long runs cost more than the work suggests because every turn resends the prompt, the tool definitions and the whole transcript: many steps, or a long session re-read each time, is the usual cause. When you have read the calls, say what happened and, when a setting explains it, name that setting with its value and the ref from read_settings so the user can change it. Never guess a figure: report only what you read.`,
schema: z.object({
message_id: z
.number()
.int()
.positive()
.optional()
.describe("The message to read (ids come from this conversation's list, or from a past session you read)."),
job_id: z
.number()
.int()
.positive()
.optional()
.describe("A run's job id, for a run whose message isn't written yet. Leave it out to read the run you are in."),
latest: z.boolean().optional().describe("List the conversation's latest messages again."),
}),
run: async ({ args }) => {
const limits = await grabRunLimitsOverview().catch(() => null);
const current_limits: CurrentRunLimits = {
task_steps: limits?.task_steps ?? limits?.task_default ?? 0,
reply_steps: limits?.reply_steps ?? limits?.reply_default ?? 0,
unattended_steps: limits?.unattended_steps ?? limits?.unattended_default ?? 0,
run_tokens: limits?.run_tokens ?? limits?.run_tokens_default ?? 0,
context_tokens: limits?.context_tokens ?? limits?.context_tokens_default ?? 0,
};
const scope = grabHarnessUsageScope();
const run_session_id = Number(scope?.session_id) || Number(session_id) || 0;
if (!args.message_id && !args.job_id && args.latest) {
return describeMessageUsageList({ messages: await grabSessionMessageUsage({ session_id: run_session_id }) });
}
if (args.message_id) {
const usage = await grabMessageRunUsage({ message_id: args.message_id, session_id: run_session_id });
if (!usage) {
return `Message #${args.message_id} isn't in this conversation. Read the list by calling again with latest: true, or read a past session first.`;
}
return describeRunUsage({ usage: { ...usage, current_limits } });
}
const job_id = args.job_id || Number(scope?.job_id) || 0;
if (!job_id) return describeMessageUsageList({ messages: await grabSessionMessageUsage({ session_id: run_session_id }) });
const usage = await grabJobRunUsage({ job_id });
if (!usage) {
return `No model calls recorded for run #${job_id} yet.`;
}
return describeRunUsage({ usage: { ...usage, current_limits } });
},
};
}
@@ -0,0 +1,48 @@
import { z } from "zod";
import { CitableGeneralSettingsSections } from "@/src/dict/general-settings-dict";
import grabGeneralSettingsValues from "@/src/functions/backend/db/app-settings/grab-general-settings-values";
import describeGeneralSettings from "@/src/utils/describe-general-settings";
import type { HarnessTool } from "../../../types";
type Args = {
section?: string;
};
/**
* The General settings a run's limits come from, read live, with the ref
* that points a reader at each one. A bot that hit a limit (steps used up,
* a folder full, a message too long) and one answering "why did that cost
* so much" both need to name the same page and value.
*/
export default function readSettingsTool(): HarnessTool<Args> {
return {
name: "read_settings",
description: `Read Settings > General as it is now: the app's run limits (steps per task, per chat reply and per routine or hook call, tokens per run, working context), session length, message length, skill limits, retention days and storage quotas, each with who may change it and the ref to write.
Use it when a limit stopped you or shaped your answer, and when the user asks why something is capped, why a reply was cut short or why a message was refused: say the setting, its value as the form shows it and who can change it, then write its ref exactly as given (e.g. [setting:run-limits:reply_steps]) - the chat shows that as a pill that opens the page and the field.
You never change these settings yourself, and never say one was changed.`,
schema: z.object({
section: z
.string()
.optional()
.describe("One section's key, to read only that (e.g. run-limits, storage). Leave it out for all of them."),
}),
run: async ({ args }) => {
const everything = await grabGeneralSettingsValues();
const citable = everything.filter((section) =>
CitableGeneralSettingsSections.some((known) => known.key == section.key),
);
if (!args.section) return describeGeneralSettings({ sections: citable });
const one = citable.find((section) => section.key == args.section);
if (!one) {
return `There is no citable setting section "${args.section}". The ones you can name: ${citable.map((section) => section.key).join(", ")}.`;
}
return describeGeneralSettings({ sections: [one] });
},
};
}
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import suggestNextStepsTool from "./suggest-next-steps-tool";
const refs: string[] = [];
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
describe("suggestNextStepsTool", () => {
test("takes a set of steps with an optional heading", () => {
expect(tool.schema?.safeParse({ title: "What I can do next", steps: ["Write the report", "Email the team"] }).success).toBe(true);
expect(tool.schema?.safeParse({ steps: ["Write the report"] }).success).toBe(true);
});
test("needs at least one step and no duplicates", () => {
expect(tool.schema?.safeParse({ steps: [] }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: ["Write the report", "write the report"] }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: [" "] }).success).toBe(false);
});
test("caps how many steps one row holds and how long each is", () => {
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
});
});
@@ -0,0 +1,71 @@
import { z } from "zod";
import createBotSuggestion from "@/src/functions/backend/db/bot-suggestions/create-bot-suggestion";
import { AppData } from "@/src/data/app-data";
import { BotSuggestionStepsSchema } from "@/src/schemas/bot-suggestion-schema";
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
import type { HarnessTool } from "../../../types";
type Params = {
user_id: number | string;
bot_id: number | string;
/**
* The conversation they show in.
*/
session_id: number | string;
workspace_id?: number | string | null;
/**
* Called with the suggestions' ref, so the message always carries
* their buttons.
*/
onSuggest: (params: { ref: string }) => void;
};
type Args = {
title?: string;
steps: z.infer<typeof BotSuggestionStepsSchema>;
};
/**
* Offers the user concrete next steps as buttons under the bot's answer.
* Clicking one puts it in their input; nothing waits on it, unlike
* `ask_user`, so the reply goes on as usual. Once per run, so every
* suggestion lands in one row.
*/
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
let suggested = false;
return {
name: "suggest_next_steps",
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and carry on as if they may ignore it. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
schema: z.object({
title: z
.string()
.trim()
.max(AppData.BotSuggestionTitleMaxChars)
.optional()
.describe(`A short heading for the row, e.g. "What I can do next" (defaults to "Next steps")`),
steps: BotSuggestionStepsSchema.describe("The suggested steps, best first, each written as the message the user would send"),
}),
run: async ({ args }) => {
if (suggested) {
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
}
const id = await createBotSuggestion({
user_id,
bot_id,
session_id,
workspace_id,
title: args.title?.trim() || "",
steps: args.steps,
});
suggested = true;
onSuggest({ ref: botSuggestionRef({ id }) });
const count = args.steps.length;
return `Suggested ${count} next step${count == 1 ? "" : "s"}: the buttons are under your message, and clicking one puts it in the user's input. They need do nothing; don't wait for them and don't repeat the steps in your text.`;
},
};
}
@@ -0,0 +1,87 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
/**
* Jobs still running in the room. Closing cancels them, so the tool has to
* refuse over one: a coordinator once answered while the Software Engineer
* ran the work it had been asked for, the run died with "The chatroom
* closed", and the answer said the tasks were picked up.
*/
let open: { id: number; bot_id: number | null; bot_name: string | null; status: string }[] = [];
let closedArgs: Record<string, unknown> | null = null;
let closed = true;
mock.module("@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs", () => ({
default: async () => open,
}));
mock.module("@/src/functions/backend/db/chatrooms/share-room-files", () => ({
default: async ({ answer }: { answer: string }) => answer,
}));
mock.module("@/src/functions/backend/db/chatrooms/close-chatroom", () => ({
default: async (args: Record<string, unknown>) => {
closedArgs = args;
return closed;
},
}));
const answerRequesterTool = (await import("./answer-requester-tool")).default;
afterAll(() => {
mock.restore();
});
const room = { id: 3, status: "open", requester_bot_id: 2 } as BUN_SQLITE_COBBLE_CHATROOMS;
beforeEach(() => {
open = [];
closedArgs = null;
closed = true;
});
function build(onClosed?: () => void) {
return answerRequesterTool({ chatroom: room, job_id: 300, onClosed });
}
describe("answerRequesterTool", () => {
test("answers and closes the room when nothing else runs", async () => {
const acted: string[] = [];
const answer = await build(() => acted.push("closed")).run({ args: { answer: "The plan." }, signal: new AbortController().signal });
expect(String(answer)).toContain("The room is closed");
expect(closedArgs?.status).toBe("answered");
expect(closedArgs?.outcome).toBe("The plan.");
expect(closedArgs?.job_id).toBe(300);
expect(acted).toEqual(["closed"]);
});
test("refuses while a member job still runs, naming it", async () => {
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
await expect(build().run({ args: { answer: "Done." }, signal: new AbortController().signal })).rejects.toThrow(
"Still working here: Software Engineer (run #295, processing). Answering closes the room and cancels that run",
);
expect(closedArgs).toBeNull();
});
test("close_anyway answers over it", async () => {
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
await build().run({ args: { answer: "Not needed after all.", close_anyway: true }, signal: new AbortController().signal });
expect(closedArgs?.status).toBe("answered");
});
test("a room already closed is reported, not acted on", async () => {
closed = false;
const acted: string[] = [];
await expect(build(() => acted.push("closed")).run({ args: { answer: "Late." }, signal: new AbortController().signal })).rejects.toThrow(
"This room is already closed.",
);
expect(acted).toEqual([]);
});
});
@@ -1,7 +1,9 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
import shareRoomFiles from "@/src/functions/backend/db/chatrooms/share-room-files";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
import type { HarnessTool } from "../../types";
type Params = {
@@ -18,22 +20,38 @@ type Params = {
type Args = {
answer: string;
/**
* Closes over a job still running in the room, cancelling it.
*/
close_anyway?: boolean;
};
/**
* The coordinator sends the answer back to the bot that asked, closing the
* room as answered (`closeChatroom`). Files it names that the asker can't
* read are copied to it first and their refs pointed at the copies
* (`shareRoomFiles`).
* (`shareRoomFiles`). While a member's job still runs it refuses, unless
* `close_anyway` says the answer doesn't depend on it: closing cancels that
* job and the work with it.
*/
export default function answerRequesterTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
return {
name: "answer_requester",
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown.`,
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown. Closing cancels whatever still runs in the room, so while a bot is working this refuses: read where it stands first, or pass close_anyway when the answer doesn't depend on its work.`,
schema: z.object({
answer: z.string().trim().min(1).max(12000),
close_anyway: z
.boolean()
.optional()
.describe("Close over a run still working here, cancelling it: only when the answer doesn't depend on it"),
}),
run: async ({ args }) => {
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
if (open.length && !args.close_anyway) {
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Answering" }));
}
const outcome = await shareRoomFiles({ chatroom, answer: args.answer });
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "answered", outcome, job_id });
@@ -1,6 +1,8 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
import type { HarnessTool } from "../../types";
type Params = {
@@ -17,20 +19,35 @@ type Params = {
type Args = {
reason: string;
/**
* Closes over a job still running in the room, cancelling it.
*/
close_anyway?: boolean;
};
/**
* The coordinator turns the request down, telling the bot that asked why,
* and closes the room as refused (`closeChatroom`).
* and closes the room as refused (`closeChatroom`). While a member's job
* still runs it refuses, unless `close_anyway` (closing cancels it).
*/
export default function refuseRequestTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
return {
name: "refuse_request",
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it.`,
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it. Closing cancels whatever still runs in the room, so while a bot is working this refuses: pass close_anyway when the refusal doesn't depend on its work.`,
schema: z.object({
reason: z.string().trim().min(1).max(4000),
close_anyway: z
.boolean()
.optional()
.describe("Close over a run still working here, cancelling it: only when the refusal doesn't depend on it"),
}),
run: async ({ args }) => {
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
if (open.length && !args.close_anyway) {
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Turning it down" }));
}
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "refused", outcome: args.reason, job_id });
if (!closed) {
@@ -1,8 +1,10 @@
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
import grabComputerUsage, { type ComputerUsageFolder } from "@/src/functions/backend/computers/grab-computer-usage";
import grabComputerWorkspaceQuotaBytes from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-bytes";
import generalSettingsRef from "@/src/utils/general-settings-ref";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import formatBytes from "@/src/utils/format-bytes";
import computerWorkspaceSpace from "./computer-workspace-space";
type Params = {
computer: ComputerApi;
@@ -56,27 +58,54 @@ export default async function computerWorkspaceRoomError({ computer, dirs, incom
if (!usage) return null;
if (workspaceHasRoom({ used_bytes: usage.used_bytes, quota_bytes, incoming_bytes })) return null;
return computerWorkspaceFullMessage({ used_bytes: usage.used_bytes, quota_bytes, dirs });
return computerWorkspaceFullMessage({
used_bytes: usage.used_bytes,
quota_bytes,
dirs,
folders: usage.folders,
});
}
/**
* The setting that bounds a computer's workspace, as the ref a bot writes
* when it reports the refusal.
*/
const computerWorkspaceQuotaRef = generalSettingsRef({
section: "computer-workspaces",
field: "quota_mb",
});
/**
* What a bot is told when the workspace is full: what is used, what the
* limit is, and what to do instead. `dir` is where its own work is, the one
* folder it may safely clear.
* limit is, where the space went (`computerWorkspaceSpace`), and what to do
* instead. `dirs` is where its own work is, the one folder it may safely
* clear.
*/
export function computerWorkspaceFullMessage({
used_bytes,
quota_bytes,
dirs,
folders,
}: {
used_bytes: number;
quota_bytes: number;
dirs: ComputerRunDirs;
folders?: ComputerUsageFolder[];
}) {
const space = computerWorkspaceSpace({ folders, dirs });
const advice = space && !space.clearable
? `Nothing was written. The room has to come back from that folder: name it in your report, with what you needed to write, so the user can clear it through Files or raise the limit (${computerWorkspaceQuotaRef}). Anything you can delete in ${dirs.bot_dir ?? dirs.cwd} still helps, and importing what matters into your files and removing it here frees that much.`
: `Nothing was written. Free space first with computer_bash: delete what you no longer need in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and then remove it here.`;
return [
`No room left on this computer: its workspace holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}.`,
`Nothing was written. Free space first with computer_bash: delete what you no longer need in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and then remove it here.`,
].join(" ");
`The limit is Settings > General's megabytes per computer (${computerWorkspaceQuotaRef}, ${Math.round(quota_bytes / (1024 * 1024)).toLocaleString("en-US")} MB now): only the super admin can raise it.`,
space?.description || "",
advice,
]
.filter(Boolean)
.join(" ");
}
/**
@@ -88,12 +117,16 @@ export function computerWorkspaceFullNote({
used_bytes,
quota_bytes,
dirs,
folders,
}: {
used_bytes: number;
quota_bytes: number;
dirs: ComputerRunDirs;
folders?: ComputerUsageFolder[];
}) {
return `[This computer's workspace now holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}: writes through computer_write_file and computer_edit_file are refused until there is room. Free space in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and remove it here.]`;
const space = computerWorkspaceSpace({ folders, dirs });
return `[This computer's workspace now holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}${space ? `: ${space.description}` : ""} Writes through computer_write_file and computer_edit_file are refused until there is room. Free space in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and remove it here.]`;
}
/**
@@ -110,5 +143,10 @@ export async function computerWorkspaceFullWarning({ computer, dirs, signal }: O
if (!usage) return null;
if (workspaceHasRoom({ used_bytes: usage.used_bytes, quota_bytes, incoming_bytes: 0 })) return null;
return computerWorkspaceFullNote({ used_bytes: usage.used_bytes, quota_bytes, dirs });
return computerWorkspaceFullNote({
used_bytes: usage.used_bytes,
quota_bytes,
dirs,
folders: usage.folders,
});
}
@@ -0,0 +1,66 @@
import { describe, expect, test } from "bun:test";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkspaceSpace from "./computer-workspace-space";
const worker: ComputerRunDirs = {
workspace: "/home/gem/workspace",
cwd: "/home/cb-9/workspace/users/1",
bot_dir: "/home/cb-9/workspace",
shared_dir: null,
roots: ["/home/cb-9/workspace"],
user_id: 1,
run_as: { bot_id: 9, workspace_id: null },
};
const coordinator: ComputerRunDirs = {
...worker,
bot_dir: "/home/gem/workspace/bots/2",
run_as: null,
};
const folders = (path: string) => [{ path, bytes: 22_000_000_000 }];
describe("computerWorkspaceSpace", () => {
test("says nothing without a folder to name", () => {
expect(computerWorkspaceSpace({ dirs: worker })).toBe(null);
expect(computerWorkspaceSpace({ folders: [], dirs: worker })).toBe(null);
});
test("names the run's own folder as one it may clear", () => {
const space = computerWorkspaceSpace({ folders: folders("bots/9"), dirs: worker });
expect(space?.clearable).toBe(true);
expect(space?.description).toContain("your own folder (bots/9");
});
test("names the workspace's shared folder as one it may clear", () => {
const space = computerWorkspaceSpace({
folders: folders("workspaces/3"),
dirs: { ...worker, shared_dir: "/home/cb-9/workspace/workspaces/3", run_as: { bot_id: 9, workspace_id: 3 } },
});
expect(space?.clearable).toBe(true);
expect(space?.description).toContain("this workspace's shared folder (workspaces/3");
});
test("a worker is told when the space is another bot's folder", () => {
const space = computerWorkspaceSpace({ folders: folders("bots/3"), dirs: worker });
expect(space?.clearable).toBe(false);
expect(space?.description).toContain("another bot's folder");
});
test("a worker is told when the space is a workspace it isn't in", () => {
const space = computerWorkspaceSpace({ folders: folders("workspaces/4"), dirs: worker });
expect(space?.clearable).toBe(false);
expect(space?.description).toContain("another workspace's folder");
});
test("the coordinator may clear any folder it is shown", () => {
const space = computerWorkspaceSpace({ folders: folders("bots/3"), dirs: coordinator });
expect(space?.clearable).toBe(true);
expect(space?.description).toContain("which you can reach as the coordinator");
});
});
@@ -0,0 +1,71 @@
import type { ComputerUsageFolder } from "@/src/functions/backend/computers/grab-computer-usage";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import formatBytes from "@/src/utils/format-bytes";
type Params = {
/**
* The biggest folders in the workspace, most first (`grabComputerUsage`).
*/
folders?: ComputerUsageFolder[];
dirs: ComputerRunDirs;
};
export type WorkspaceSpace = {
/**
* What the run is told about the folder holding the space, one sentence.
*/
description: string;
/**
* Whether that folder is one the run may clear: its own, the shared one
* in a workspace, or anything at all for the coordinator. A worker
* can't touch another bot's folder, so clearing it itself is not an
* option it should be pointed at.
*/
clearable: boolean;
};
/**
* Where a computer's workspace went: its biggest folder, named with whose
* it is. The workspace is one folder for every bot and user on that
* computer, so a bot told only "it's full" reported a limit it could never
* reach from its own folder (a bot's `du` showed 25 MB while the volume
* held 21.3 GB, most of it another bot's screenshots), which is what this
* answers.
*/
export default function computerWorkspaceSpace({ folders, dirs }: Params): WorkspaceSpace | null {
const biggest = folders?.[0];
if (!biggest) return null;
const size = formatBytes({ bytes: biggest.bytes });
const shared = dirs.shared_dir ? dirs.shared_dir.replace(/\/+$/, "").split("/").slice(-2).join("/") : "";
if (biggest.path == `bots/${dirs.run_as?.bot_id}`) {
return {
description: `Most of it is in your own folder (${biggest.path}, ${size}), so clearing it is yours to do.`,
clearable: true,
};
}
if (shared && biggest.path == shared) {
return {
description: `Most of it is in this workspace's shared folder (${biggest.path}, ${size}).`,
clearable: true,
};
}
if (!dirs.run_as) {
return {
description: `Most of it is in ${biggest.path} (${size}), which you can reach as the coordinator, so clearing it is yours to do.`,
clearable: true,
};
}
const [group] = biggest.path.split("/");
const owner = group == "workspaces" ? "workspace" : "bot";
return {
description: `Most of it is in ${biggest.path} (${size}), another ${owner}'s folder (this computer has one workspace for every bot and user), which you can't clear.`,
clearable: false,
};
}
@@ -0,0 +1,44 @@
import { describe, expect, test } from "bun:test";
import repeatToolCallKey from "./repeat-tool-call-key";
const call = ({ name, arguments: args }: { name: string; arguments: string }) => ({ id: "1", name, arguments: args });
describe("repeatToolCallKey", () => {
test("matches the same read whatever order the arguments came in", () => {
const first = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"a.md","offset":1}` }) });
const second = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"offset":1,"path":"a.md"}` }) });
expect(first).not.toBeNull();
expect(second).toBe(first);
});
test("tells different arguments and different tools apart", () => {
const first = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"a.md"}` }) });
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"b.md"}` }) })).not.toBe(first);
expect(repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"path":"a.md"}` }) })).not.toBe(first);
});
test("reads arguments left out as an empty object", () => {
expect(repeatToolCallKey({ call: call({ name: "list_tasks", arguments: "" }) })).toBe("list_tasks:{}");
expect(repeatToolCallKey({ call: call({ name: "list_tasks", arguments: " " }) })).toBe("list_tasks:{}");
});
test("never repeats a tool that may write", () => {
expect(repeatToolCallKey({ call: call({ name: "computer_bash", arguments: `{"command":"ls"}` }) })).toBeNull();
expect(repeatToolCallKey({ call: call({ name: "write_file", arguments: `{"path":"a.md"}` }) })).toBeNull();
expect(repeatToolCallKey({ call: call({ name: "computer_write_file", arguments: `{"path":"a.md"}` }) })).toBeNull();
});
test("leaves arguments it can't read alone", () => {
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: "{nope" }) })).toBeNull();
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: `["a.md"]` }) })).toBeNull();
});
test("sorts keys inside nested arguments too", () => {
const first = repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"where":{"b":1,"a":2}}` }) });
const second = repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"where":{"a":2,"b":1}}` }) });
expect(second).toBe(first);
});
});
+43
View File
@@ -0,0 +1,43 @@
import type { HarnessToolCall } from "../types";
import isRepeatableTool from "./repeatable-tool-names";
/**
* What makes two calls the same call: the tool and its arguments, whatever
* order the model wrote their keys in (a model re-reads a file it read
* before with the same fields in another order). Null for a tool whose
* answer may change, and for arguments that aren't a JSON object, which
* `runToolCall` turns down anyway.
*/
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
if (!isRepeatableTool({ name: call.name })) return null;
let args: unknown;
try {
args = call.arguments.trim() ? JSON.parse(call.arguments) : {};
} catch {
return null;
}
if (!args || typeof args != "object" || Array.isArray(args)) return null;
return `${call.name}:${JSON.stringify(sortKeys({ value: args }))}`;
}
/**
* The value with every object's keys sorted, so two spellings of the same
* arguments compare equal.
*/
function sortKeys({ value }: { value: unknown }): unknown {
if (Array.isArray(value)) return value.map((item) => sortKeys({ value: item }));
if (value && typeof value == "object") {
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
.map(([key, inner]) => [key, sortKeys({ value: inner })]),
);
}
return value;
}
@@ -0,0 +1,42 @@
import { ReadKnowledgebaseDocumentToolName, SearchKnowledgebaseToolName } from "@/src/dict/knowledgebase-dict";
/**
* Tools that only read. Called twice with the same arguments in one run
* they answer the same thing, so `runTextLoop` answers the second call from
* the first instead of running it again (`repeatToolCallKey`): a run that
* re-reads the same file or re-lists the same folder stops paying for it
* twice, in the call and in the transcript it resends every turn.
*
* Only reads belong here. A write, a command, or anything else with a side
* effect clears everything remembered, so a read is reused only while
* nothing has run that could have changed its answer.
*/
export const RepeatableToolNames: readonly string[] = [
"read_file",
"list_files",
"computer_read_file",
SearchKnowledgebaseToolName,
ReadKnowledgebaseDocumentToolName,
"list_tasks",
"list_extensions",
"list_graphics",
"read_graphic",
"list_hooks",
"read_hook_call",
"search_hook_calls",
"list_schedules",
"list_workspace_bots",
"list_workspace_people",
"find_bot",
"find_workspace",
"search_past_sessions",
"read_past_session",
"search_computers",
];
/**
* Whether a tool call may be answered from an earlier identical one.
*/
export default function isRepeatableTool({ name }: { name: string }) {
return RepeatableToolNames.includes(name);
}
+19
View File
@@ -1,3 +1,5 @@
import type { RunLimit } from "@/src/utils/run-limit";
/**
* Who and what a model call was for. Every harness call that reports its
* usage is written down with this (`/api/auth/crud` no: `token_usages`),
@@ -61,6 +63,23 @@ export type HarnessCallSettings = {
* resting after an earlier failure, in order.
*/
resting?: string[];
/**
* The bounds the run worked under: the steps it had, the prompt tokens
* it may spend and the working context it sent per turn. Kept with the
* call so a message read later still says which limit shaped it.
*/
limits?: HarnessCallLimits;
};
/**
* A run's own bounds on one call (`HarnessCallSettings.limits`). Null: the
* run didn't say, so the number isn't known (not "unlimited");
* `"unlimited"`: the run had no limit of that kind.
*/
export type HarnessCallLimits = {
steps: RunLimit | null;
run_tokens: RunLimit | null;
context_tokens: RunLimit | null;
};
export type HarnessUsageCall = {
+17 -3
View File
@@ -1,18 +1,30 @@
"use client";
import { useEffect, useState } from "react";
import { AppData } from "@/src/data/app-data";
/**
* Changes after a reason the socket may have died: the browser went back
* online, the page was restored, or a hidden tab became visible again.
* online, the page was restored, a hidden tab became visible again, or
* another window was focused (a phone locked while the socket closed).
* twui's `useWebSocket` gives up after three attempts, so the socket is
* remounted instead of waiting for a reload.
* remounted instead of waiting for a reload. A second trigger within
* `AppData.RefocusGapMs` is the same return.
*/
export default function useConnectionEpoch() {
const [epoch, setEpoch] = useState(0);
useEffect(() => {
const bump = () => setEpoch((value) => value + 1);
let last = 0;
const bump = () => {
const now = Date.now();
if (now - last < AppData.RefocusGapMs) return;
last = now;
setEpoch((value) => value + 1);
};
const onVisible = () => {
if (document.visibilityState == "visible") bump();
@@ -20,11 +32,13 @@ export default function useConnectionEpoch() {
window.addEventListener("online", bump);
window.addEventListener("pageshow", bump);
window.addEventListener("focus", bump);
document.addEventListener("visibilitychange", onVisible);
return () => {
window.removeEventListener("online", bump);
window.removeEventListener("pageshow", bump);
window.removeEventListener("focus", bump);
document.removeEventListener("visibilitychange", onVisible);
};
}, []);
+33 -3
View File
@@ -1,10 +1,12 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import { LiveCrewRefreshedEvent } from "@/src/functions/frontend/announce-live-crew";
import type {
BotCreatedData,
BotRemovedData,
BotUpdatedData,
BotWithLastMessage,
LiveCrewRefreshedDetail,
} from "@/src/types";
import useServerEvent from "./use-server-event";
@@ -23,7 +25,10 @@ type Params = {
/**
* The crew, kept current from server pushes: faces and status lines,
* latest messages, and unread for conversations that aren't open.
* latest messages, and unread for conversations that aren't open. A task
* step's push never reaches a page that was in the background, so the
* whole list is also read again when the user comes back
* (`cobble:live-crew-refreshed`).
*/
export default function useLiveBots({ bots, open_bot_id, workspace_id = null }: Params) {
const [live, setLive] = useState(bots);
@@ -132,5 +137,30 @@ export default function useLiveBots({ bots, open_bot_id, workspace_id = null }:
},
});
useEffect(() => {
const onRefresh = (event: Event) => {
const detail = (event as CustomEvent<LiveCrewRefreshedDetail>).detail;
if (!detail) return;
/**
* The list read for another place: this one keeps what it has.
*/
if ((detail.workspace_id || null) != (workspace_id ? Number(workspace_id) : null)) {
return;
}
setLive(
detail.bots.map((bot) =>
bot.id == open_bot_id ? { ...bot, unread: 0 } : bot,
),
);
};
window.addEventListener(LiveCrewRefreshedEvent, onRefresh);
return () => window.removeEventListener(LiveCrewRefreshedEvent, onRefresh);
}, [workspace_id, open_bot_id]);
return live;
}
}

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