Compare commits

...
2 Commits
Author SHA1 Message Date
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
41 changed files with 1712 additions and 178 deletions
+6 -5
View File
@@ -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
@@ -121,6 +121,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
- 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 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, 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.
@@ -143,7 +144,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.
@@ -163,7 +164,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`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -216,7 +217,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. 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.
- **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`, 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`).
@@ -229,7 +230,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- 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`).
- 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
+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),
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.7",
"version": "0.18.8",
"module": "index.ts",
"type": "module",
"private": true,
+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 });
+92 -55
View File
@@ -23,6 +23,7 @@ import {
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
taskPlanNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -66,6 +67,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";
@@ -401,62 +404,91 @@ export default async function runBotTask({
}
}
const 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,
RequestScopeNote({ can_ask }),
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");
/*
* 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,
RequestScopeNote({ can_ask }),
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,
@@ -494,6 +526,11 @@ export default async function runBotTask({
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: result.steps > max_steps,
};
} finally {
await extensions?.close();
@@ -0,0 +1,19 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
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: AppData.HarnessMaxToolSteps })).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", () => {
expect(shouldPlanBotTask({ max_steps: AppData.HarnessMaxToolSteps, in_chatroom: true })).toBe(false);
});
});
+24
View File
@@ -0,0 +1,24 @@
import { AppData } from "@/src/data/app-data";
/**
* 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.
*
* 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: number;
in_chatroom?: boolean;
}) {
if (in_chatroom) return false;
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>;
+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) };
}
+18 -1
View File
@@ -110,7 +110,7 @@ export const AppData = {
* `computer/` (the release workflow builds that tag), and bump
* `ComputerWorkspaceLayout` too when existing computers must move to it.
*/
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.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 +167,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,
@@ -870,6 +877,16 @@ export const AppData = {
* hour of tool calls, and a huge limit still ends with a report.
*/
BotStepLimitMax: 1000,
/**
* 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.
+45
View File
@@ -308,6 +308,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,
@@ -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 });
}
@@ -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 });
@@ -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,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"}.` };
}
@@ -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;
}
+219 -1
View File
@@ -1,7 +1,7 @@
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 { 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";
@@ -286,6 +286,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 = {
@@ -739,3 +816,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);
});
});
+105 -30
View File
@@ -1,7 +1,9 @@
import { AppData } from "@/src/data/app-data";
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
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 {
@@ -117,12 +119,28 @@ 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 gets
* `AppData.BotReplyMaxToolSteps` steps, and a reply that used them 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 +152,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 +237,9 @@ 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. An answer `review` finds fault
* with is written again once.
*
* Every turn resends everything, so the run keeps it small: only the
@@ -262,13 +305,25 @@ 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 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)!);
const warn_at = stepsLowWarningLeft({ max_steps });
let prefer_key: string | undefined;
let reviewed = false;
@@ -280,7 +335,11 @@ 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++) {
if (signal.aborted) {
@@ -291,11 +350,12 @@ export default async function runTextLoop({
const out_of_tokens = Boolean(max_prompt_tokens && 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 +368,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
@@ -351,7 +412,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 +423,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 +473,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 +495,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 });
@@ -1,8 +1,9 @@
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 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 +57,44 @@ 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,
});
}
/**
* 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. 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(" ");
space?.description || "",
advice,
]
.filter(Boolean)
.join(" ");
}
/**
@@ -88,12 +106,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 +132,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);
}
@@ -37,7 +37,9 @@ export default function MessageActions({ message }: Props) {
message_id={message.id}
onReact={onReact}
/>
{message.author == "bot" ? <MessageDetailsModal message_id={Number(message.id)} /> : null}
{message.author == "bot" ? (
<MessageDetailsModal message_id={Number(message.id)} tool_log={message.tool_log} />
) : null}
</>
) : null}
</Row>
@@ -10,17 +10,22 @@ import MessageDetailsCallRow from "./message-details-call-row";
import MessageDetailsFailureRow from "./message-details-failure-row";
import MessageDetailsHeading from "./message-details-heading";
import MessageDetailsModelRow from "./message-details-model-row";
import MessageToolsRollup from "./message-tools-rollup";
type Props = {
details: MessageDetails;
/**
* The message's `tool_log`: what its run did, tool by tool.
*/
tool_log?: string | null;
};
/**
* How a message was generated: the provider and model that answered and
* what it spent, then the job that ran it, every model it used, every
* call in order and every call that failed, with why.
* what it spent, then the job that ran it, what its tools did, every model
* it used, every call in order and every call that failed, with why.
*/
export default function MessageDetailsBody({ details }: Props) {
export default function MessageDetailsBody({ details, tool_log }: Props) {
const { totals, models, calls, failures, failed_calls, job } = details;
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
@@ -63,6 +68,8 @@ export default function MessageDetailsBody({ details }: Props) {
</>
) : null}
<MessageToolsRollup tool_log={tool_log} />
{models.length ? (
<>
<MessageDetailsHeading>{models.length > 1 ? "Models used" : "Model used"}</MessageDetailsHeading>
@@ -12,14 +12,19 @@ import MessageDetailsBody from "./message-details-body";
type Props = {
message_id: number;
/**
* Its `tool_log`: what the run behind it did, shown in the modal and
* passed along to the copied report.
*/
tool_log?: string | null;
};
/**
* The info button under a bot message, and the modal it opens: which
* provider and model generated it, the run behind it, and every model
* call with its tokens and cost. Loaded when it opens.
* provider and model generated it, the run behind it, what its tools did,
* and every model call with its tokens and cost. Loaded when it opens.
*/
export default function MessageDetailsModal({ message_id }: Props) {
export default function MessageDetailsModal({ message_id, tool_log }: Props) {
const [open, set_open] = useState(false);
const { details, loading, error } = useMessageDetails({ message_id, enabled: open });
@@ -47,7 +52,7 @@ export default function MessageDetailsModal({ message_id }: Props) {
<Stack className="mt-4 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
{details ? (
<MessageDetailsBody details={details} />
<MessageDetailsBody details={details} tool_log={tool_log} />
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{loading || !error ? "Loading details..." : error}
@@ -0,0 +1,33 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import type { ToolRollupEntry } from "@/src/utils/tool-rollup";
type Props = {
tool: ToolRollupEntry;
};
/**
* One tool in a message's rollup: its name as the run called it, what the
* app calls that, and how many calls it made, of which how many failed.
*/
export default function MessageToolRow({ tool }: Props) {
return (
<Row className="w-full py-1.5 gap-3! flex-nowrap items-baseline border-0 border-b border-solid border-hairline last:border-b-0">
<Span
className="grow min-w-0 font-mono text-[12px] leading-4 text-ink truncate"
title={`${tool.label} (${tool.name})`}
>
{tool.name}
</Span>
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary tabular-nums">{tool.label}</Span>
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums">
{tool.count == 1 ? "1 call" : `${tool.count} calls`}
</Span>
{tool.failed ? (
<Span className="w-14 shrink-0 text-right text-[11px] leading-4 text-ink-secondary tabular-nums">
{`${tool.failed} failed`}
</Span>
) : null}
</Row>
);
}
@@ -0,0 +1,37 @@
import type { ToolRollupEntry } from "@/src/utils/tool-rollup";
import toolRollup from "@/src/utils/tool-rollup";
import MessageDetailRow from "./message-detail-row";
import MessageDetailsHeading from "./message-details-heading";
import MessageToolRow from "./message-tool-row";
type Props = {
/**
* The message's `tool_log` (`{ name, ok }` per call).
*/
tool_log?: string | null;
};
/**
* What a message's run actually did, by tool: the one reading that tells a
* run which worked from one that spent 242 model calls and changed
* nothing. The app's own record (`bot_messages.tool_log`), so it can't
* claim work the run didn't make.
*/
export default function MessageToolsRollup({ tool_log }: Props) {
const rollup = toolRollup({ tool_log });
if (!rollup || !rollup.tools.length) return null;
return (
<>
<MessageDetailsHeading>Tools used</MessageDetailsHeading>
<MessageDetailRow
label="Tool calls"
value={rollup.failed ? `${rollup.calls} (${rollup.failed} failed)` : String(rollup.calls)}
/>
{rollup.tools.map((tool: ToolRollupEntry) => (
<MessageToolRow key={tool.name} tool={tool} />
))}
</>
);
}
+43
View File
@@ -0,0 +1,43 @@
import {
JobStepBrowserToolInfix,
JobStepToolLabels,
JobStepToolPrefixLabels,
} from "@/src/dict/bot-queue-dict";
type Params = {
/**
* A tool's name, e.g. `computer_bash` or `<server>__<tool>`.
*/
name: string;
};
/**
* What a tool call does, in plain words: the app's own label for the tools
* it ships (`JobStepToolLabels`), a family's for anything matching its
* prefix (`JobStepToolPrefixLabels`: every browser tool reads "Using the
* browser"), else the name in words. Used for the live step line and for a
* message's tool rollup, so the two never drift.
*/
export default function toolLabel({ name }: Params) {
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})`;
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, test } from "bun:test";
import toolRollup from "./tool-rollup";
const log = (...uses: { name: string; ok?: boolean }[]) => JSON.stringify(uses);
describe("toolRollup", () => {
test("no record of a run", () => {
expect(toolRollup({ tool_log: null })).toBe(null);
expect(toolRollup({ tool_log: "" })).toBe(null);
expect(toolRollup({ tool_log: "not json" })).toBe(null);
expect(toolRollup({ tool_log: `{"a":1}` })).toBe(null);
});
test("counts calls by tool, most used first", () => {
const rollup = toolRollup({
tool_log: log(
{ name: "computer_bash", ok: true },
{ name: "start_task", ok: true },
{ name: "computer_bash", ok: true },
{ name: "computer_bash", ok: false },
),
});
expect(rollup).toEqual({
calls: 4,
failed: 1,
tools: [
{ name: "computer_bash", label: "Running a command", count: 3, failed: 1 },
{ name: "start_task", label: "Starting a task", count: 1, failed: 0 },
],
});
});
test("labels a browser tool and an unknown one", () => {
const rollup = toolRollup({
tool_log: log({ name: "browser_navigate", ok: true }, { name: "exa__search", ok: true }),
});
expect(rollup?.tools).toEqual([
{ name: "browser_navigate", label: "Using the browser", count: 1, failed: 0 },
{ name: "exa__search", label: "Using Exa (search)", count: 1, failed: 0 },
]);
});
test("skips a use with no name", () => {
const rollup = toolRollup({ tool_log: JSON.stringify([{ ok: true }, { name: "write_file" }]) });
expect(rollup?.calls).toBe(1);
expect(rollup?.tools.map((tool) => tool.name)).toEqual(["write_file"]);
});
});
+85
View File
@@ -0,0 +1,85 @@
import toolLabel from "@/src/utils/tool-label";
type Params = {
/**
* A bot message's `tool_log` (JSON list of `{ name, ok }`).
*/
tool_log?: string | null;
};
export type ToolRollupEntry = {
/**
* The tool's name, as the run called it.
*/
name: string;
/**
* What it does, in words (`toolLabel`).
*/
label: string;
count: number;
/**
* How many of its calls came back an error.
*/
failed: number;
};
export type ToolRollup = {
calls: number;
failed: number;
/**
* Every tool the run called, most used first.
*/
tools: ToolRollupEntry[];
};
type ToolUse = {
name?: unknown;
ok?: unknown;
};
/**
* A message's tool calls counted by tool: 242 calls of a run that converted
* nothing read "242 model calls, 10.1M tokens" without it, and the same
* reads "210 computer_bash, 12 start_task" with it. Null when the message
* has no record of a run (a user message, an interim one, an older one).
*/
export default function toolRollup({ tool_log }: Params): ToolRollup | null {
if (!tool_log) return null;
let uses: unknown;
try {
uses = JSON.parse(tool_log);
} catch {
return null;
}
if (!Array.isArray(uses)) return null;
const counts = new Map<string, { count: number; failed: number }>();
for (const use of uses as ToolUse[]) {
const name = typeof use?.name == "string" ? use.name : "";
if (!name) continue;
const entry = counts.get(name) || { count: 0, failed: 0 };
entry.count++;
if (use.ok === false) entry.failed++;
counts.set(name, entry);
}
const tools = [...counts].map(([name, entry]) => ({
name,
label: toolLabel({ name }),
count: entry.count,
failed: entry.failed,
}));
return {
calls: tools.reduce((total, tool) => total + tool.count, 0),
failed: tools.reduce((total, tool) => total + tool.failed, 0),
tools: tools.sort((left, right) => right.count - left.count || left.name.localeCompare(right.name)),
};
}