Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

- RequestScopeNote, injected into every reply and task, says the request
  sets the scope, that memory, habits, routines and initiative never
  widen it, and that crew changes (create, place, remove, assign a
  computer, change a role) and handing work out (delegating, handing over
  a task or routine) happen only after the user asked for them: one
  ask_user card in a reply or task, and a proposal in the report where
  nobody watches (routine, hook call, chatroom).
- A decline is dropped, not done smaller and not re-offered.
- The memory sections of composeBotPrompt say memory shapes how the bot
  does the work, never what it does beyond the request.
- The default coordinator prompt says a request to create a bot is a
  request for that bot alone; existing installs keep their stored prompt
  and get the rule from the note.
2026-11-12 20:59:35 +01:00
tben 1a0bcb8360 Bump version to 0.18.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 20:47:51 +01:00
tben 181b7f9e30 Keep a profile's extension state and clear the host's old images
Recreating a profile's caches at every start also took Storage/ext,
which holds what an extension keeps rather than what Chrome rebuilds:
Cookie-Editor and every other extension lost their settings on each
container restart. Only caches go now, and the two GPU cache folders
that were missing are cleared with the rest.

A host updated for a year still held every older tag of the app's image
and every computer image the app had pulled, since the installer removed
only the tag the previous container ran. It removes them all now, and
docker refuses the ones a container uses.

Computers move to the image that reports its workspace: the layout name
changed, so migrateComputerLayout recreates each one, keeping its
workspace and browser profile.
2026-11-12 20:45:41 +01:00
tben d7e66a5123 Keep computer caches off the data volume and shrink data archives
One install's production archive was 2 GB: 2457 MB of computer
workspaces (983 MB of npm, pip and bun caches, plus 697 MB of
node_modules and 446 MB of pip installs), 993 MB of Chrome profile
caches, 148 MB of database snapshots and 15 MB of bun-sqlite scratch
space, against 178 MB of bot files. Runs had HOME on the mounted
workspace and no cache variables, so every side cache was persisted
forever, and the archiver tarred the whole volume with one exclusion.

- Runs keep their caches inside the container: computerCacheEnv points
  XDG_CACHE_HOME, npm_config_cache, PIP_CACHE_DIR,
  BUN_INSTALL_CACHE_DIR and PYTHONPYCACHEPREFIX at the account's own
  home, never the run's folder.
- prune-computer-caches (daily) clears what earlier runs left in bot
  folders, user folders, workspaces and Chrome profiles, skipping a
  computer with a task queued or running. The agent clears a profile's
  regenerable cache at each start and caps its HTTP cache.
- listArchiveExclusions is the one definition of what a data archive
  leaves out, as exact member paths (--no-wildcards --exclude-from):
  computers, Chrome profile caches, db/.backups and .bun-sqlite. A
  restore keeps the running install's db/.backups, since no archive
  carries them, and still leaves computer folders live.
- A computer's workspace has a quota (computer_workspace_quota_mb,
  Settings > General, default AppData.ComputerWorkspaceQuotaMb): the
  agent measures it, the app refuses a write past it and warns after
  computer_bash and browser calls.
- An upload's bytes go with the messages that carried them, and
  prune-orphan-media takes what is left after
  AppData.MediaOrphanKeepDays; moved-aside old computer homes are
  pruned after AppData.ComputerOldHomeKeepDays.
- install.sh removes the image the previous container ran and dangling
  layers, so updates stop accumulating gigabytes on the host.
2026-11-12 20:36:46 +01:00
tben 03e372d38d Keep the end of a long tool result and let the wrap up save the report
Two runs in a row measured to their last step with the report unwritten.
Long `du`/`find` output lost its tail twice (the bash tool kept 40k with
head and tail, then run-tool-call sliced the first 20k of it), so the
totals a sweep ends with were cut away and the run re-ran the command
until the steps ran out.

- run-tool-call and capToolOutput keep their result's start and end, the
  note sized before the cut so the whole result stays inside the cap.
- ComputerCommandMaxOutputChars matches HarnessToolResultMaxChars.
- The wrap up keeps write_file and import_file for a saving turn (then
  answers with no tools), so a run out of steps can still save its report.
- The save-first warning scales with the run (a tenth of its steps, never
  below HarnessStepsLowWarning) instead of a flat 5 steps.
2026-11-12 20:03:42 +01:00
tben 615ba5a9b9 Stop re-attaching and re-reading one old file on every reply
A reply was handed the files of the latest messages that have any, so in a
long conversation the last upload never aged out: one screenshot stayed
attached for session upon session, and since the text model is catalogued
text only it was read by the vision harness on every reply (7 calls, about
1,500 output tokens and 35 seconds each, in production).

- liveAttachmentMessages bounds an attachment by how far back it is too
  (BotReplyAttachmentMaxAgeMessages), then by BotReplyAttachmentMessages:
  older files are named, not attached.
- Readings are kept across runs in MediaReadings (HarnessMediaReadingsCached)
  keyed by imageReadingKey, so an image the conversation carries is read
  once rather than once per reply; a reading made to redact a secret is
  never kept there.
- The Models page says when the text model is listed as taking text only
  while "Use the model's own media reading" is on, which was silently
  useless for a provider that lists bare ids (guessModelModalities).
2026-11-12 19:21:12 +01:00
tben 6a808d8417 Bump version to 0.18.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 18:42:33 +01:00
tben 585b77eec1 Copy a message's whole details from its Details modal
The Details modal under a bot message now has a Copy report button: it
puts that message's whole details on the clipboard as one markdown
document, every call and failure it took included rather than only the
first the modal lists. The modal and the report share their at-a-glance
facts and the failure-source wording, and the route takes full=1 to list
up to AppData.MessageDetailsCopyMaxCalls calls.
2026-11-12 18:42:27 +01:00
tben 74693cccd3 Bump version to 0.18.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-11 04:39:23 +01:00
tben 115113247f Give the coordinator its skill, server and tool tools in a workspace too
- grabCoordinatorExtensionTools was pushed only in the coordinator's own
  chat: both workspace branches returned before it, so a runbook asked for
  inside a workspace had no propose_skill to write it with, and the bot
  saved a file and called the skill created
- Pushed before the workspace split, so it comes wherever the coordinator
  works; the tools still return nothing unless the run's user is the super
  admin, and each re-checks on call (assertSuperAdminRun)
- grab-bot-chat-tools.test.ts pins all three cases: a workspace, a
  workspace with no worker (the empty-crew return) and its own chat
- AGENTS.md records it
2026-11-11 04:39:20 +01:00
tben 14fc5e9d6e Bump version to 0.18.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-11 02:55:00 +01:00
tben 84ae51c621 Reset fallback models when changing the model provider in model settings 2026-11-11 02:49:28 +01:00
tben 60e3d3bfbf Pace task step budgets and prevent redundant pre-check queuing and question loops 2026-11-11 02:32:53 +01:00
tbenandClaude Opus 5.5 ab384ff175 Release v0.18.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 14:33:12 +01:00
tbenandClaude Opus 5.5 700a2bcd86 Describe each user's role per workspace for the bots there
A crew manager can now write who a user is in one workspace: plain text,
separate from the user's bio, which the user never sees or sets.
workspace_user_roles holds one role per user per workspace. Every bot in
that workspace reads the role in its prompt whenever it works for that
user, in chat replies, tasks, routines and hooks. The role never appears
in a bot's own chat or in another workspace.

The super admin can set anyone's role, their own included. An admin can
set anyone's except a super admin's (canSetWorkspaceUserRole, checked
again in setWorkspaceUserRole). Roles are set from the workspace's
settings (People: everyone who works there) and from the user's settings
(Roles in workspaces). The coordinator can set them too, through
list_workspace_people and set_user_workspace_role. Its saves count as
made by the run's user and are read back to check they took.

A role is kept when the user loses access to a workspace and comes back
with it. Deleting the workspace or the user deletes it explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 14:32:23 +01:00
tbenandClaude Opus 5.5 14d4c10782 Release v0.18.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:44:56 +01:00
tbenandClaude Opus 5.5 26424560da Open the computer picker from the computer line in the conversation header
The computer under the bot's name is now a button opening the same
computers modal as the menu's Computer row: switch computers when there's
more than one, or open one in the viewer. The menu's row stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:44:26 +01:00
tbenandClaude Opus 5.5 ece7ebf1b2 Log model failures under LLM and show failed calls in message details
Model failures get their own LLM log category instead of System; older
"Model failed" rows move at boot. Each failed model call is also recorded
in harness_call_failures (model, pick, status, the provider's reason,
rest) and attached to the message its job posts, including the failure
notice, so a message's details list the calls that failed and why.
Failures are pruned with the logs' retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:14:54 +01:00
tbenandClaude Opus 5.5 7bdd288f36 Open the models modal from the model line in the conversation header
The model under the bot's name is now a button opening the same models
form as the bot's settings, for whoever can edit them there; others
still see plain text with who can change it. The menu's Models row stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:04:10 +01:00
tben 9dab068827 Send question card answers without a confirm dialog 2026-11-08 13:02:09 +01:00
tbenandClaude Opus 5.5 ef84c8a245 Keep a running computer out of "failed", refuse runs on a down one, and show generated images
A layout migration whose image pull timed out left the old container
running but marked the computer failed, and nothing checked it again.
Now a setup that fails while the old container runs keeps it running
(retrying the migration after an hour), and a failed computer whose
container docker runs is revived by sync-computers and on first use.

start_task refused nothing, so a bot queued work on a failed computer
and the run retried three times before failing. start_task now refuses
a down computer, and a task run on one fails at once with a message
saying who can bring it back.

generate_image attaches what it makes unless told not to: a coordinator
asked the user to judge three versions it never sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:02:03 +01:00
tbenandClaude Opus 5.5 4cfbf6f558 Add video generation and video editing models, and a generate_video tool
Two new harnesses, video and video_edit, with settings in Settings > Models
and per bot and workspace. Neither picks automatically (no video model is
free); video editing hands over to the video generation models that take
videos, as image editing does.

A video is a job at the provider: asked for, checked on until done, then
downloaded from the provider itself. OpenRouter takes frames, references
and videos to change; other providers get OpenAI's (Sora) form. Bots get
generate_video only while a video model is set up for them, and it saves
the video to their files like generate_image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 12:35:52 +01:00
tbenandClaude Opus 5.5 572b5d239a Make the chat message limit an app setting and show why a send failed
The composer only put a failed send's reason in the editor's tooltip, so a
message over the limit just came back with no visible error. It now checks
the length before sending and shows the reason under the input, as it does
for any failed send.

The limit moves from a literal 4000 in the schema to
AppData.BotMessageMaxChars (default 20,000), saved per install as
bot_message_max_chars under Settings > General > Messages (super admin),
and checked again by the send route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 12:00:55 +01:00
tbenandClaude Opus 5.5 419a50b95b Release v0.17.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 10:02:37 +01:00
tbenandClaude Opus 5.5 c4c86fc66b Set up a new install from a backup, and restart after a database restore
First-run setup can now restore another install's database file or
whole-data archive instead of creating a super admin. The upload is told
apart by its bytes, refused once any account exists or for a database
with no accounts, restored like Settings > Backups, and the app restarts
onto it.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
574 changed files with 22259 additions and 1540 deletions
+46 -35
View File
@@ -36,7 +36,7 @@ For the current UI read `src/layouts/bots/` (rail, workspace rail, user popover)
| DB schema sync / admin UI / backup | `bun run db:schema` / `db:admin` / `db:backup` |
| Seed super admin / sample crew | `bun run seed` (needs `SEED_SUPER_ADMIN_PASSWORD`) / `bun run seed:bots [email]` (idempotent) |
| Query DB (read-only, JSON envelope) | `bun llm-code-assistant/query-db.ts "<sql>"` |
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards |
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards (`gh run watch` in between until the image build ends) |
No linter or formatter. `bun run typecheck` and `bun run test` are the verification steps. Use `query-db.ts` to see what is actually in the database instead of reading ORM code.
@@ -54,13 +54,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Auth
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings; or Restore from a backup: another install's database file or data archive, told apart by their bytes, through public `api/auth/bootstrap-restore`, refused once any user exists or for a database with no users, restored like Settings > Backups and then the app restarts, the page polling `bootstrap-status` and going to the login); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
- **Session:** AES-256-GCM cookie (key from `ENCRYPTION_KEY`/`ENCRYPTION_SALT`) plus CSRF cookie, `Secure` only over HTTPS (`isSecureRequest`, honours `X-Forwarded-Proto`). `userAuth` (`src/functions/backend/auth/user-auth.ts`) checks expiry (60 days), CSRF (constant-time) and re-reads `user_types` every request.
- **Login:** email/username + password (`api/auth/password-login.ts`, rate limited). No emailed codes or resets. Google login only for existing accounts, when `GOOGLE_CLIENT_ID` is set. Sessions issued by `login-user.ts`.
- **Passwords:** bcrypt in `user_passwords` (never in `users`; blocked from CRUD via `src/dict/private-tables.ts`).
- **User types** (`src/dict/user-types-dict.ts`, the only definition): `super_admin` (user #1), `admin` (only the super admin grants it), `member` (default), `read_only` (non-GET CRUD blocked), `revoked`. A user needs at least one type to sign in.
- **RBAC:** `src/utils/check-user-access.ts` plus the matrix engine in `src/utils/rbac/` (`userTypeAssignment` over `UserTypeAssignmentMatrix`/`UserTypeDeletionMatrix`).
- **Audit:** `src/functions/backend/logger.ts` (`logEvent`/`logError` -> `logs`). Auth events, cron runs, every unexpected API error (`safeErrorMessage` -> `logUnexpectedError`, not for `AppError`), every failed or lost bot job. WebSocket connects are not logged. Kept for the app setting `logs_keep_days` (default `AppData.LogsKeepDays`), deleted by the daily `prune-logs`.
- **Audit:** `src/functions/backend/logger.ts` (`logEvent`/`logError` -> `logs`). Auth events, cron runs, every unexpected API error (`safeErrorMessage` -> `logUnexpectedError`, not for `AppError`), every failed or lost bot job, every failed model call (category `llm`, `logCandidateFailure`; older `system` rows moved at boot by `migrateLlmLogs`). WebSocket connects are not logged. Kept for the app setting `logs_keep_days` (default `AppData.LogsKeepDays`), deleted by the daily `prune-logs`.
### WebSocket
@@ -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-logs`.
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
### Admin CRUD API
@@ -83,24 +83,27 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bot types
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). A plain worker gets no work to hand out, but may pass on an open task of its own to a bot it could ask (`hand_over_task`, `hand-over-task-tool.ts`): its one permission, its own list only, and `BotTypeTargetMatrix` is left alone so it still directs no one, the targets coming from `chatroomAskableBots`. Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
### Bots, sessions, chat
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot (cookie `cobble_last_visited_bot_id`, never a workspace conversation) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`.
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. Tasks don't get files yet.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`.
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
@@ -110,16 +113,19 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Prompt and memory
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context and the bot's instructions there, then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`.
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, chatroom). Memory, habits and the bot's own initiative never widen a request.
### Queue (`bots_queue`)
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`) and chatroom turns. A plan that can't be written or read starts the run unplanned, never blocks it.
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last.
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
### Live updates
@@ -127,18 +133,19 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
### Chatrooms (`chatrooms`)
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions; their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). Closing is what cancels a room's jobs, so `answer_requester` and `refuse_request` refuse while a member job still runs (`grabChatroomOpenJobs`, `chatroomOpenJobsWarning`) unless given `close_anyway`: a coordinator that answered over a live run once killed the very work it was asked for, then reported it picked up. A coordinator's turn creates no task and moves none (`chatroomCoordinatorNote`): a task is handed over by the bot that has it or by the user. A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. A room shows what it cost the way a conversation's messages do: each message carries its `MessageUsageChip` and the Details modal (read through the room's own `api/admin/chatrooms/message-details`, which checks the room's user), and above the thread `ChatroomUsageSummary` totals the room (`usage` on its summary, from `grabChatroomUsage`: every model call counted by its run's `bot_sessions.chatroom_id`, a turn still running included, with the room's failed calls and the same split by bot). **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
### Workspaces
`workspaces` (`description`, shared `system_prompt`, default `computer_id` (not an FK), `archived`), `workspace_bots` (per-bot instructions and memory there; coordinator is an implicit member), `workspace_computers`. First computer linked becomes the default. Workspace models win over a bot's own, then the defaults. A bot's instructions and memory there (`WorkspaceBotModal`/`WorkspaceBotForm`, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in `src/functions/backend/db/workspaces/` are access-checked; structural ones are crew-manager only.
`workspaces` (`description`, shared `system_prompt`, default `computer_id` (not an FK), `archived`), `workspace_bots` (per-bot instructions and memory there; coordinator is an implicit member), `workspace_computers`. First computer linked becomes the default. Workspace models win over a bot's own, then the defaults. **A user's role in a workspace** (`workspace_user_roles`, plain text, one per user and workspace) tells every bot there who it's working for; it's not their bio, the user never sees or sets it, and only crew managers set it, an admin never a super admin's (`canSetWorkspaceUserRole`, checked in `setWorkspaceUserRole`). Set from the workspace's settings (People, everyone who works there: `workspacePeopleSql`), the user's settings (Roles in workspaces) and by the coordinator (`list_workspace_people`/`set_user_workspace_role`, replies and tasks, saved as the run's user so the same rule holds). It stays when access is taken away, shown and used only while they work there. A bot's instructions and memory there (`WorkspaceBotModal`/`WorkspaceBotForm`, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in `src/functions/backend/db/workspaces/` are access-checked; structural ones are crew-manager only.
### Computers
- **Our own image** (`computer/`, Debian 13, `AppData.ComputerImage`, or the app setting `COMPUTER_IMAGE`), one docker container per computer on `AppData.DockerNetworkName`, managed over the docker socket (`src/functions/backend/docker/`). Google Chrome on amd64, Debian's Chromium on arm64 (Google ships no arm64 Linux Chrome), headful on Xvnc (an X server that is also a VNC server, on loopback), never launched by automation (no automation flags), so it's as close to a real browser as possible. Inside, one agent (`computer/agent/`, Node, no dependencies, bundled by Bun at image build) supervises Xvnc, the session bus, Chrome, Playwright MCP and ttyd and serves one port: `/health` (open), `/api/exec`, `/api/files/*` (shell and files, as `gem` or, with `run_as`, a worker's own account), `/mcp` (proxied to Playwright MCP on loopback, `--shared-browser-context --codegen none --no-webmcp`), `/desktop/` (the screen: noVNC, its `websockify` socket bridged to Xvnc by the agent), `/terminal/` (ttyd). Every request but `/health` needs the computer's token (`computerToken`: HMAC of the id with `ENCRYPTION_KEY`, given as `COBBLE_COMPUTER_TOKEN`), so another computer's bot can't drive it; the app's client is `src/functions/backend/computers/`. **Any change under `computer/` bumps the tag in `AppData.ComputerImage`** (the release workflow builds a tag only once; `bun run build:computer` builds it locally); bump `ComputerWorkspaceLayout` too when existing computers must move to it. `containers` records every container except the app's own. `createComputer` + background `provisionComputer` (status `creating` until the health check passes; while setting up or restarting it touches the row every `ComputerSetupHeartbeatMs`, `keepComputerSetupAlive`, so one the app lost to a restart (`computerSetupInterrupted`) shows as failed with Retry and `sync-computers` starts it again). Resource changes recreate the container.
- **Our own image** (`computer/`, Debian 13, `AppData.ComputerImage`, or the app setting `COMPUTER_IMAGE`), one docker container per computer on `AppData.DockerNetworkName`, managed over the docker socket (`src/functions/backend/docker/`). Google Chrome on amd64, Debian's Chromium on arm64 (Google ships no arm64 Linux Chrome), headful on Xvnc (an X server that is also a VNC server, on loopback), never launched by automation (no automation flags), so it's as close to a real browser as possible. Inside, one agent (`computer/agent/`, Node, no dependencies, bundled by Bun at image build) supervises Xvnc, the session bus, Chrome, Playwright MCP and ttyd and serves one port: `/health` (open), `/api/exec`, `/api/files/*` (shell and files, as `gem` or, with `run_as`, a worker's own account), `/mcp` (proxied to Playwright MCP on loopback, `--shared-browser-context --codegen none --no-webmcp`), `/desktop/` (the screen: noVNC, its `websockify` socket bridged to Xvnc by the agent), `/terminal/` (ttyd). Every request but `/health` needs the computer's token (`computerToken`: HMAC of the id with `ENCRYPTION_KEY`, given as `COBBLE_COMPUTER_TOKEN`), so another computer's bot can't drive it; the app's client is `src/functions/backend/computers/`. **Any change under `computer/` bumps the tag in `AppData.ComputerImage`** (the release workflow builds a tag only once; `bun run build:computer` builds it locally); bump `ComputerWorkspaceLayout` too when existing computers must move to it. `containers` records every container except the app's own. `createComputer` + background `provisionComputer` (status `creating` until the health check passes; while setting up or restarting it touches the row every `ComputerSetupHeartbeatMs`, `keepComputerSetupAlive`, so one the app lost to a restart (`computerSetupInterrupted`) shows as failed with Retry and `sync-computers` starts it again). A setup that fails while the old container still runs (a new image that couldn't be pulled) keeps it running on its old layout (`setup_failed_at`, migration retried after `AppData.ComputerMigrateRetryMs`), and a `failed` row whose container docker runs anyway is revived (`reviveFailedComputer`, from `sync-computers` and `grabComputerMcpUrl`). Resource changes recreate the container.
- 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. **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`).
- **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 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.
@@ -158,7 +165,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -205,32 +212,36 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
### Harness (the model layer, `src/harness/`)
- **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech and embedding have no automatic picks: unavailable until a model is picked.
- **Images:** `generate_image` takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; `HarnessFallbacks` hands it to `image` while unpicked or off, and after its pick fails when `fallback` is on), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them. OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`).
- **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `video`, `video_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech, video and embedding have no automatic picks: unavailable until a model is picked.
- **Images:** `generate_image` attaches what it makes to the reply unless `attach: false` (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; `HarnessFallbacks` hands it to `image` while unpicked or off, and after its pick fails when `fallback` is on), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them. OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`).
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`), trims old tool output to fit context. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, `hand_over_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access). New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
### Token usage
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`).
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`, including `limits`: the steps, run tokens and context the run was held to, so a bot can explain a cost against them with `read_message_usage`).
- Attribution through an `AsyncLocalStorage` scope (`src/harness/usage/harness-usage-scope.ts`) entered once in `run-bot-job.ts`; merged, not replaced; `null` clears a field. `withUsageScope` / `runWithFallbackScope` for calls outside a run. No owner, no row.
- `complete-bot-job.ts` back-fills `message_id` for the job's calls. Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`).
- 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, 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
- `install.sh` (`curl -fsSL https://url.moduletrace.com/cobble | sudo bash`) is the only install and update path; idempotent; `--uninstall [--purge]`. Never regenerates secrets; backs up the DB before replacing the container. Everything persistent lives in `$COBBLE_HOME/data` (default `/opt/cobble`).
- `install.sh` (`curl -fsSL https://url.moduletrace.com/cobble | sudo bash`) is the only install and update path; idempotent; `--uninstall [--purge]`. Never regenerates secrets; backs up the DB before replacing the container, and removes every older tag of the app's and the computer's images plus dangling layers (`prune_old_images`, `old_image_tags`; docker refuses what a container still runs), since a release per update otherwise fills the host. Everything persistent lives in `$COBBLE_HOME/data` (default `/opt/cobble`).
- **Mount specs:** `source:destination[:options]`, options (`z`, `ro`) comma-separated in the **third** field. Never append an option to the destination (`$DATA_DIR:/data,z` mounts a directory literally named `/data,z` and loses all data on update). `install.test.ts` runs the marked `selinux-detection` and `mount-specs` blocks. `/data` must stay a bind mount (`resolveHostPath` maps it to host paths for computers).
- **App networks:** extra docker networks for the app's own container (never computers) are the app setting `app_extra_networks` (Settings > General, super admin, picked from the networks docker lists, `listJoinableNetworks`), joined by the app itself over the docker socket (`syncAppNetworks`) at boot, on save and every 5 minutes, so they outlast `install.sh` recreating the container; the installer's `--extra-network` still works beside it.
- Plain HTTP only; TLS is the proxy's job. Container: `--network cobble`, `.env` read-only at `/app/.env`, docker socket, `MAIN_SERVER=1`, `--init`, `--cpus 1 --memory 2048m` by default.
- Publishing: `scripts/publish-github.sh` / `publish-gitea.sh` sharing `scripts/lib/publish-*.sh` (tested by `scripts/publish-tools.test.ts`). A GitHub release triggers `.github/workflows/release.yml` (amd64 + arm64 to `ghcr.io/moduletrace/cobble`); `mirror-gitea.sh` copies to `git.tben.me/moduletrace/cobble` (CI can't reach the VPN). **Bump `package.json`'s `version` with a release.** CI (`ci.yml`) runs typecheck and tests. Dockerfile pins Bun 1.4.3.
- **A release is done when every artifact exists, not when the tag is pushed.** Publishing (`publish`/`release`/`ship`, any of them) means the whole chain, run by you and watched to the end: `publish:github`, `publish:gitea`, then `gh run watch` until the image build succeeds, then `mirror:gitea` (it has nothing to copy until that build finishes). Report each artifact with its link, and say plainly (with the reason) if one fails or is still building: never hand back a tag and leave the rest as a note for the user.
## Admin routes
@@ -238,8 +249,8 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Rail pages** (`src/dict/rail-pages-dict.ts`): Routines, Files, Usage (crew managers), Activity (`/admin/logs`, super admin), Help (`(data)/help-topics.ts`). Visibility via `canSeeRailItem` for both the popover and the aside.
- **Settings** (`src/dict/settings-pages-dict.ts`; add a sub page = folder + dict entry): `general` (theme per device, plus super-admin app settings: prompt append, run limits, skill limits; crew-manager storage quota; running version), `setup` (super admin; shares the Models page's server props and `useModelsOverview`), `profile`, `notifications`, `change-password`, `secrets`, `browsers`, `models`, `environment`, `backups` and `database` (super admin), `bots`, `workspaces`, `computers`, `mcps`, `tools`, `skills`, `knowledgebases` (crew managers), `users` (`canListUsers`).
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process.
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Each group of General also has a page of its own (`/admin/settings/general/<section>`, keyed in `src/dict/general-settings-dict.ts`, linked from the group's title): anyone who may read it sees its values (`SettingsReadOnlyValues`), only its owning role gets the form. A bot points at one with `read_settings` and a `[setting:section:field]` ref, so every limit refusal or cost answer names the page and value to change. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. What an archive leaves out is decided in one place, `listArchiveExclusions` (`--no-wildcards --exclude-from`): `DATA_DIR/computers` (a computer's workspace is the computer's own state, so `AppData.DataBackupsKept` copies of it never fill the volume and a restore neither empties nor copies that folder), each Chrome profile's caches (the profile is kept for its logins, a few MB against hundreds of MB of HTTP and code caches), `db/.backups` (that is the database snapshots' own list) and `.bun-sqlite`. A restore keeps the running install's `db/.backups` (copied aside and put back), since no archive carries them. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process. **A database snapshot restore restarts too** (also a background run, `db_restore`): `bun-sqlite import` swaps in a new file from another process, and this process's handle would stay on the old one, so nothing may be written to the database between a restore and the restart (log entries go through `queueBootLog`, written by `flushBootLogs` at boot).
- **Database browser:** strictly read-only; values cut in SQL; state in the address via `databaseHref`.
- Add flow (`(partials)/add-flow.tsx`) from the rail's Add icon: bot, workspace, computer (super admin). Page heroes use `AdminHero`.
+3 -2
View File
@@ -9,7 +9,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.9",
"@moduletrace/twui": "^0.1.10",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -60,6 +60,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3",
},
"peerDependencies": {
@@ -279,7 +280,7 @@
"@moduletrace/bunext": ["@moduletrace/[email protected]", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.5/bunext-1.3.5.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-Es59Dvq3/eF726+SOHPiKtlJ87UFmyJZI4gpeciW/fA/3ZwOWws2Mm3oD6eZnOj9BP/zlBKOWA9DPTl35IP3lg=="],
"@moduletrace/twui": ["@moduletrace/[email protected].9", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.9/twui-0.1.9.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-HN/emdqSCxQclzFEojDsaujjgO+dkQy4wC7Rk6gCQH/fK2Hv0CQ5DLOdOB8oDE7nu+m7/0qKo878UeufBbEotg=="],
"@moduletrace/twui": ["@moduletrace/[email protected].10", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.10/twui-0.1.10.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-eShpG6jK7qr2+oG7Pq4PvHnvAOUPkbxMCf9BVfiuJqUdtuaQSo2jqcggGAonGDu4p8Nn/KWTd2KrypE/+W4wTg=="],
"@next/mdx": ["@next/[email protected]", "", { "dependencies": { "source-map": "^0.7.0" }, "peerDependencies": { "@mdx-js/loader": ">=0.15.0", "@mdx-js/react": ">=0.15.0" }, "optionalPeers": ["@mdx-js/loader", "@mdx-js/react"] }, "sha512-Vpfuf928ACvx4AOdDXWx/cj13Ak6xlvMn3QCkjvfQMmLnQWCesQTeY01CPDbIyZvjY+NOwP7bvbvJ2ghkj/3GA=="],
+8 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import browserArgs from "./browser-args";
import browserArgs, { DiskCacheMaxBytes } from "./browser-args";
const base = {
profile_dir: "/p",
@@ -24,6 +24,13 @@ describe("browserArgs", () => {
expect(browserArgs({ ...base, screen: { width: 1366, height: 768 }, scale: 1.25 })).toContain("--window-size=1092,614");
});
test("caps the disk cache, so a profile can't grow by gigabytes", () => {
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
expect(args).toContain(`--disk-cache-size=${DiskCacheMaxBytes}`);
expect(DiskCacheMaxBytes).toBe(512 * 1024 * 1024);
});
test("keeps WebGL but composites in software", () => {
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
+8
View File
@@ -21,6 +21,13 @@ type Params = {
extra?: string[];
};
/**
* Chrome's on-disk HTTP cache, in bytes. Left to itself Chrome grows it to
a few gigabytes inside the profile, which is mounted and never shrinks;
what it holds is fetched again on demand.
*/
export const DiskCacheMaxBytes = 512 * 1024 * 1024;
/**
* Chrome's background work a lightweight browser goes without: on-device
* model and hint downloads, casting, translate prompts, autofill lookups.
@@ -57,6 +64,7 @@ export default function browserArgs({ profile_dir, cdp_port, screen, scale, lang
// Chrome reads the window size in scaled units: divided by the
// scale, the window fills the screen exactly.
`--window-size=${Math.floor(screen.width / scale)},${Math.floor(screen.height / scale)}`,
`--disk-cache-size=${DiskCacheMaxBytes}`,
...(scale == 1 ? [] : [`--force-device-scale-factor=${scale}`]),
...(lightweight ? lightweightArgs() : desktopGpuArgs()),
/**
+3
View File
@@ -5,6 +5,7 @@ import handleExec from "./handle-exec";
import handleFileDownload from "./handle-file-download";
import handleFileStat from "./handle-file-stat";
import handleFileWrite from "./handle-file-write";
import handleUsage from "./handle-usage";
import isAuthorized from "./is-authorized";
import isPortAnswering from "./is-port-answering";
import log from "./log";
@@ -22,6 +23,7 @@ import serveStaticFile from "./serve-static-file";
* - `GET /api/info`, `POST /api/exec`, `GET /api/files/stat|download`,
* `POST /api/files/write`: the app's shell and file access, as gem or
* as a worker bot's own account (`run_as`).
* - `GET /api/usage`: how much the workspace holds.
* - `/mcp`: Playwright MCP, driving the computer's browser.
* - `/desktop/` and its `/desktop/websockify` websocket: the screen
* (noVNC over Xvnc), Chrome's whole window.
@@ -139,6 +141,7 @@ async function route({ req, res, parking }: { req: IncomingMessage; res: ServerR
if (pathname == "/api/files/stat" && req.method == "GET") return handleFileStat({ req, res });
if (pathname == "/api/files/download" && req.method == "GET") return handleFileDownload({ req, res });
if (pathname == "/api/files/write" && req.method == "POST") return handleFileWrite({ req, res });
if (pathname == "/api/usage" && req.method == "GET") return handleUsage({ req, res });
sendJson({ res, status: 404, body: { error: "Not Found" } });
}
+20
View File
@@ -0,0 +1,20 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { AgentConfig } from "./config";
import sendJson from "./send-json";
import { workspaceUsage } from "./workspace-usage";
/**
* `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. 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 }) {
const { bytes, folders } = await workspaceUsage();
sendJson({
res,
body: { used_bytes: bytes, workspace_dir: AgentConfig.WorkspaceDir, folders },
});
}
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pruneProfileCache from "./prune-profile-cache";
/**
* The profile is mounted from the data volume, so whatever this clears is
* gone for good. A cache comes back by itself, an extension's own state
* never does, so only caches may ever be in these lists.
*/
const roots: string[] = [];
function profile() {
const root = mkdtempSync(path.join(tmpdir(), "cobble-profile-"));
roots.push(root);
return root;
}
function write({ root, relative }: { root: string; relative: string }) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, "x".repeat(1024));
}
function exists({ root, relative }: { root: string; relative: string }) {
return require("node:fs").existsSync(path.join(root, relative));
}
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
describe("pruneProfileCache", () => {
test("keeps an extension's own state", () => {
const root = profile();
write({ root, relative: "Default/Storage/ext/abc/def" });
write({ root, relative: "Default/Local Storage/leveldb/000003.log" });
pruneProfileCache({ profile_dir: root });
expect(exists({ root, relative: "Default/Storage/ext/abc/def" })).toBeTrue();
expect(exists({ root, relative: "Default/Local Storage/leveldb/000003.log" })).toBeTrue();
});
test("never touches a login, a permission or history", () => {
const root = profile();
write({ root, relative: "Default/Cookies" });
write({ root, relative: "Default/Login Data" });
write({ root, relative: "Default/Preferences" });
write({ root, relative: "Default/History" });
write({ root, relative: "Default/Extensions/abc/1.0/manifest.json" });
pruneProfileCache({ profile_dir: root });
for (const relative of ["Default/Cookies", "Default/Login Data", "Default/Preferences", "Default/History", "Default/Extensions/abc/1.0/manifest.json"]) {
expect(exists({ root, relative })).toBeTrue();
}
});
});
@@ -0,0 +1,97 @@
import { afterEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pruneProfileCache from "./prune-profile-cache";
/**
* The profile is mounted so logins survive a restart, and this runs at
* every start: a folder wrongly listed here would log the user out of
* every site, and one wrongly left out grows the volume forever.
*/
const dirs: string[] = [];
function profile() {
const dir = mkdtempSync(path.join(tmpdir(), "cobble-profile-"));
dirs.push(dir);
return dir;
}
function write({ root, relative, bytes }: { root: string; relative: string; bytes: number }) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, "x".repeat(bytes));
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe("pruneProfileCache", () => {
test("clears a profile's caches and the ones Chrome keeps beside it", () => {
const root = profile();
write({ root, relative: "Default/Cache/data_0", bytes: 400 });
write({ root, relative: "Default/Code Cache/js/index", bytes: 300 });
write({ root, relative: "Default/Service Worker/CacheStorage/a/b", bytes: 200 });
write({ root, relative: "Profile 1/Cache/data_0", bytes: 100 });
write({ root, relative: "ShaderCache/data", bytes: 500 });
write({ root, relative: "GPUCache/data", bytes: 50 });
expect(pruneProfileCache({ profile_dir: root })).toBe(1550);
for (const gone of [
"Default/Cache",
"Default/Code Cache",
"Default/Service Worker/CacheStorage",
"Profile 1/Cache",
"ShaderCache",
"GPUCache",
]) {
expect(existsSync(path.join(root, gone))).toBe(false);
}
});
test("never touches a login, a permission or an extension", () => {
const root = profile();
write({ root, relative: "Default/Cookies", bytes: 10 });
write({ root, relative: "Default/Login Data", bytes: 10 });
write({ root, relative: "Default/Preferences", bytes: 10 });
write({ root, relative: "Default/Local Storage/leveldb/a.log", bytes: 10 });
write({ root, relative: "Default/Extensions/abc/1.0/page.html", bytes: 10 });
write({ root, relative: "Local State", bytes: 10 });
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
for (const kept of [
"Default/Cookies",
"Default/Login Data",
"Default/Preferences",
"Default/Local Storage",
"Default/Extensions",
"Local State",
]) {
expect(existsSync(path.join(root, kept))).toBe(true);
}
});
test("a folder that isn't a profile is left alone", () => {
const root = profile();
write({ root, relative: "SomeOtherProfile/Cache/data_0", bytes: 400 });
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
expect(readdirSync(root)).toEqual(["SomeOtherProfile"]);
});
test("an empty or missing profile frees nothing and throws nothing", () => {
const root = profile();
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
expect(pruneProfileCache({ profile_dir: path.join(root, "missing") })).toBe(0);
});
});
+121
View File
@@ -0,0 +1,121 @@
import { readdirSync, rmSync, statSync } from "node:fs";
import path from "node:path";
import log from "./log";
/**
* Folders inside a browser profile that only ever hold what Chrome can
* download or build again. Cookies, logins, site permissions, history,
* local storage and extensions live elsewhere and are never touched: the
* profile is mounted so a computer keeps them across restarts.
*/
const RegenerableProfileDirs = [
"ShaderCache",
"GrShaderCache",
"GPUCache",
"GPUPersistentCache",
"GraphiteDawnCache",
"DawnGraphiteCache",
"DawnWebGPUCache",
"component_crx_cache",
"CertificateRevocation",
"optimization_guide_model_store",
];
/**
* The same, in each profile's own folder (`Default`, `Profile 1`, ...).
* Never `Local Storage`, `IndexedDB` or `Storage/ext`: those are what the
* extensions a computer keeps (Cookie-Editor among them) hold their own
* state in, which is not rebuilt by downloading anything.
*/
const RegenerableBrowserDirs = [
"Cache",
"Code Cache",
"GPUCache",
"GPUPersistentCache",
"GraphiteDawnCache",
"DawnGraphiteCache",
"DawnWebGPUCache",
"Service Worker/CacheStorage",
"Service Worker/ScriptCache",
];
/**
* Frees what Chrome downloaded or built last time it ran and will build
* again: extension assets, the component updater's CRX cache, model files,
* certificate revocation lists, HTTP and code caches. A profile otherwise
* grows by hundreds of megabytes and never shrinks.
*
* Only called while no browser runs (a cache cleared under a live Chrome
* leaves it writing into a deleted folder). Returns the bytes freed.
*/
export default function pruneProfileCache({ profile_dir }: { profile_dir: string }) {
let freed = 0;
for (const name of RegenerableProfileDirs) {
freed += freeDir({ target: path.join(profile_dir, name) });
}
for (const profile of safeReadDir({ target: profile_dir })) {
/**
* A profile's own folder: `Default` or `Profile <n>`, and
* `System Profile` for Chrome's own pages.
*/
if (!/^(Default|Profile \d+|System Profile)$/.test(profile)) continue;
for (const name of RegenerableBrowserDirs) {
freed += freeDir({ target: path.join(profile_dir, profile, name) });
}
}
if (freed > 0) log({ name: "browser", message: `cleared ${(freed / (1024 * 1024)).toFixed(1)} MB of regenerable profile cache` });
return freed;
}
/**
* Removes one folder with what is under it, returning the bytes.
*/
function freeDir({ target }: { target: string }) {
const size = dirSize({ target });
if (!size) return 0;
try {
rmSync(target, { recursive: true, force: true });
return size;
} catch {
/**
* Something that can't be removed is left for the next start; the
* browser comes up either way.
*/
return 0;
}
}
/**
* Bytes under one folder. Links are counted, never followed: a profile
* has none of its own, but a retired one might.
*/
function dirSize({ target }: { target: string }): number {
let stat;
try {
stat = statSync(target);
} catch {
return 0;
}
if (stat.isFile()) return stat.size;
if (!stat.isDirectory()) return 0;
return safeReadDir({ target }).reduce((total, entry) => total + dirSize({ target: path.join(target, entry) }), 0);
}
function safeReadDir({ target }: { target: string }) {
try {
return readdirSync(target);
} catch {
return [];
}
}
+6
View File
@@ -8,6 +8,7 @@ import { AgentConfig } from "./config";
import findBrowserBinary from "./find-browser-binary";
import isPortAnswering from "./is-port-answering";
import log from "./log";
import pruneProfileCache from "./prune-profile-cache";
import superviseProcess, { type Supervised } from "./supervise-process";
import userEnv from "./user-env";
import waitUntil from "./wait-until";
@@ -92,6 +93,11 @@ export default async function startServices({ parking }: { parking: BrowserParki
command: binary,
args: () => {
clearProfileLocks({ profile_dir: AgentConfig.ProfileDir });
/**
* No browser runs now (this is its start): the caches it built
* last time are free to go, so the profile stops growing.
*/
pruneProfileCache({ profile_dir: AgentConfig.ProfileDir });
return browserArgs({
profile_dir: AgentConfig.ProfileDir,
+137
View File
@@ -0,0 +1,137 @@
import { execFile } from "node:child_process";
import { AgentConfig } from "./config";
/**
* One folder inside the workspace, with what it holds: `bots/9` is a bot's
* folder, `workspaces/3` a workspace's shared one.
*/
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
* row asks once. The app's quota is its own decision; this is only how
* much is there.
*/
const CacheMs = 10_000;
/**
* How many of the biggest folders are named: enough that the one filling
* the volume is there, few enough to say in a sentence.
*/
const FoldersShown = 5;
/**
* 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"];
/**
* 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 and its biggest folders through `du`, or null when
* it can't be read.
*/
function measureWorkspace() {
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);
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),
};
}
+211 -2
View File
@@ -592,6 +592,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `JSON \`[{ name, ok }]\`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)`,
dataType: "TEXT",
},
{
fieldName: "task_ids",
fieldDescription: `JSON \`[id, ...]\`: the tracker tasks (\`tasks\`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none`,
dataType: "TEXT",
},
{
fieldName: "from_chatroom_id",
fieldDescription: `Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key`,
@@ -1792,6 +1797,48 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "bot_suggestions",
tableDescription: `Next steps a bot suggests under its answer (\`suggest_next_steps\`): buttons that put the step in the user's input. Unlike \`bot_questions\`, nothing waits on them`,
fields: [
{
fieldName: "title",
fieldDescription: `A short heading for the row of buttons; empty for "Next steps"`,
dataType: "TEXT",
},
{
fieldName: "steps",
fieldDescription: `JSON array of the suggested steps, each put in the user's input when clicked`,
dataType: "TEXT",
},
{
fieldName: "user_id",
fieldDescription: `The user they were suggested to, who alone reads them. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "bot_id",
fieldDescription: `The bot that suggested them. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "session_id",
fieldDescription: `The conversation they were suggested in. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "workspace_id",
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
dataType: "INTEGER",
},
],
indexes: [
{
indexName: "idx_bot_suggestions_session_id",
indexTableFields: ["session_id"],
},
],
},
{
tableName: "bot_graphics",
tableDescription: `A visual a bot made for a user (a chart, diagram, timeline or report) as one self-contained HTML document. Served by the app at \`/graphics/<id>\` in a sandbox with no network and an origin of its own, so it never runs with the viewer's session. Per user like the conversation it was made in; an edit replaces the HTML and bumps \`version\``,
@@ -2191,6 +2238,60 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "workspace_user_roles",
tableDescription: `Who a user is in one workspace (plain text), set by a super admin or admin, never by the user: every bot working there reads it in its prompt when it works for that user. Not their bio, and only in that workspace. An admin never sets a super admin's`,
fields: [
{
fieldName: "workspace_id",
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "workspaces",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "workspace_user_role_workspace_fk",
},
},
{
fieldName: "user_id",
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "users",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "workspace_user_role_user_fk",
},
},
{
fieldName: "role",
fieldDescription: `Their role there and anything bots should know about them in that workspace`,
dataType: "TEXT",
},
{
fieldName: "updated_by",
fieldDescription: `The user who last set it. Not a foreign key`,
dataType: "INTEGER",
},
],
uniqueConstraints: [
{
alias: "one_role_per_workspace_user",
constraintName: "A user has one role per workspace",
constraintTableFields: [
{ value: "workspace_id" },
{ value: "user_id" },
],
},
],
indexes: [
{
indexName: "idx_workspace_user_roles_user_id",
indexTableFields: ["user_id"],
},
],
},
{
tableName: "bot_user_memories",
tableDescription: `What a bot remembers about one user (markdown). Only that user's runs see it, the way a workspace's memory stays in the workspace`,
@@ -2587,6 +2688,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
options: [0, 1],
defaultValue: 1,
},
{
fieldName: "context_length",
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
dataType: "INTEGER",
},
{
fieldName: "last_synced_at",
fieldDescription: `Unix timestamp of the last model list sync`,
@@ -4146,7 +4252,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
fieldName: "purpose",
fieldDescription: `What it is for: an upload, something the bot wrote, a generated image or PDF`,
fieldDescription: `What it is for: an upload, something the bot wrote, a generated image, video or PDF`,
dataType: "TEXT",
options: BotFilePurposes.map((p) => p.value),
defaultValue: "writing",
@@ -4259,7 +4365,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
fieldName: "harness",
fieldDescription: `What the model was used for: a chat turn, reading media, transcribing, speaking, making an image, embedding`,
fieldDescription: `What the model was used for: a chat turn, reading media, transcribing, speaking, making an image or a video, embedding`,
dataType: "TEXT",
options: Harnesses.map((h) => h.value),
},
@@ -4289,6 +4395,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
dataType: "INTEGER",
defaultValue: 0,
},
{
fieldName: "cached_tokens",
fieldDescription: `Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it`,
dataType: "INTEGER",
defaultValue: 0,
},
{
fieldName: "completion_tokens",
fieldDescription: `Tokens written back: the answer, its tool calls and its reasoning`,
@@ -4329,6 +4441,103 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "harness_call_failures",
tableDescription: `One model call that failed: which model and provider, what the provider said and how long the model rested, for whom and for what. Attached to the message its job posted (an answer or the failure notice), so the message's details show the models that failed and why. No foreign keys: rows outlive what they point at and go with the logs' retention (\`logs_keep_days\`)`,
fields: [
{
fieldName: "user_id",
fieldDescription: `Whose work it was: the user whose conversation the call ran for. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "bot_id",
fieldDescription: `The bot it was for, when it was for one. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "workspace_id",
fieldDescription: `The workspace the call was in; null for a bot's own chat. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "session_id",
fieldDescription: `The conversation it was in. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "message_id",
fieldDescription: `The message its job posted, filled when the job ends (completed or failed). Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "job_id",
fieldDescription: `The queued job it ran for, when it ran for one. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "harness",
fieldDescription: `What the model was used for`,
dataType: "TEXT",
options: Harnesses.map((h) => h.value),
},
{
fieldName: "provider_id",
fieldDescription: `The provider it was sent to`,
dataType: "INTEGER",
},
{
fieldName: "provider_name",
fieldDescription: `The provider's name as it was, so a deleted provider still reads`,
dataType: "TEXT",
},
{
fieldName: "model_id",
fieldDescription: `The catalog row of the model`,
dataType: "INTEGER",
},
{
fieldName: "model_slug",
fieldDescription: `The provider's model id, as it was called`,
dataType: "TEXT",
},
{
fieldName: "source",
fieldDescription: `How the model was chosen: the setting's pick, one of its fallback models or an automatic pick`,
dataType: "TEXT",
options: ["pinned", "fallback", "auto"],
},
{
fieldName: "status",
fieldDescription: `The provider's HTTP status, when there was one`,
dataType: "INTEGER",
},
{
fieldName: "error",
fieldDescription: `Why it failed: the provider's error as the harness read it, cut at \`AppData.HarnessFailureErrorMaxChars\``,
dataType: "TEXT",
},
{
fieldName: "rests_until",
fieldDescription: `Unix ms the model (or its provider) could be tried again, when the failure benched it`,
dataType: "INTEGER",
},
],
indexes: [
{
indexName: "idx_harness_call_failures_created_at",
indexTableFields: ["created_at"],
},
{
indexName: "idx_harness_call_failures_message_id",
indexTableFields: ["message_id"],
},
{
indexName: "idx_harness_call_failures_job_id",
indexTableFields: ["job_id"],
},
],
},
{
tableName: "file_ingest_queue",
tableDescription: `Knowledgebase documents waiting to have their text chunked and embedded (bot files are never indexed). A queue, so a restart never strands a document and an upload never waits on a model. A finished job is deleted: \`knowledgebase_documents.ingested_at\` and \`ingest_error\` keep the outcome`,
+163 -9
View File
@@ -24,6 +24,7 @@ export const BunSQLiteTables = [
"secret_requests",
"install_requests",
"bot_questions",
"bot_suggestions",
"bot_graphics",
"workspaces",
"workspace_bots",
@@ -32,6 +33,7 @@ export const BunSQLiteTables = [
"bot_users",
"bot_user_visits",
"workspace_user_visits",
"workspace_user_roles",
"bot_user_memories",
"bot_user_faces",
"bot_message_media",
@@ -68,6 +70,7 @@ export const BunSQLiteTables = [
"envs",
"bot_files",
"token_usages",
"harness_call_failures",
"file_ingest_queue",
"app_settings",
] as const
@@ -412,6 +415,10 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
* JSON `[{ name, ok }]`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)
*/
tool_log?: string;
/**
* JSON `[id, ...]`: the tracker tasks (`tasks`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none
*/
task_ids?: string;
/**
* Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key
*/
@@ -1158,6 +1165,45 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
/**
* A short heading for the row of buttons; empty for "Next steps"
*/
title?: string;
/**
* JSON array of the suggested steps, each put in the user's input when clicked
*/
steps?: string;
/**
* The user they were suggested to, who alone reads them. Not a foreign key
*/
user_id?: number | "";
/**
* The bot that suggested them. Not a foreign key
*/
bot_id?: number | "";
/**
* The conversation they were suggested in. Not a foreign key
*/
session_id?: number | "";
/**
* The session's workspace; null for the bot's own chat. Not a foreign key
*/
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_GRAPHICS = {
/**
* The unique identifier of the record.
@@ -1370,6 +1416,31 @@ export type BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS = {
visited_at?: number | "";
}
export type BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
workspace_id?: number | "";
user_id?: number | "";
/**
* Their role there and anything bots should know about them in that workspace
*/
role?: string;
/**
* The user who last set it. Not a foreign key
*/
updated_by?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_USER_MEMORIES = {
/**
* The unique identifier of the record.
@@ -1594,6 +1665,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
*/
api_key?: string;
enabled?: 0 | 1 | "";
/**
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
*/
context_length?: number | "";
/**
* Unix timestamp of the last model list sync
*/
@@ -1679,7 +1754,7 @@ export type BUN_SQLITE_COBBLE_HARNESS_SETTINGS = {
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
/**
* harness_models row picked by a super admin. Null picks automatically. Not a foreign key, so removing a provider leaves the setting
*/
@@ -1719,7 +1794,7 @@ export type BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS = {
* The worker bot that overrides the default. The coordinator always uses the defaults
*/
bot_id?: number | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
/**
* harness_models row picked for this bot. Null picks automatically. Not a foreign key, like harness_settings
*/
@@ -1759,7 +1834,7 @@ export type BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS = {
* The workspace
*/
workspace_id?: number | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
/**
* harness_models row picked for this workspace. Null picks automatically. Not a foreign key, like harness_settings
*/
@@ -2371,7 +2446,7 @@ export type BUN_SQLITE_COBBLE_LOGS = {
/**
* Log category used for filtering
*/
category?: "auth" | "websocket" | "cron" | "hook" | "system" | "error" | "";
category?: "auth" | "websocket" | "cron" | "hook" | "llm" | "system" | "error" | "";
/**
* User who triggered the action, if any
*/
@@ -2568,9 +2643,9 @@ export type BUN_SQLITE_COBBLE_BOT_FILES = {
*/
size?: number | "";
/**
* What it is for: an upload, something the bot wrote, a generated image or PDF
* What it is for: an upload, something the bot wrote, a generated image, video or PDF
*/
purpose?: "upload" | "writing" | "image" | "pdf" | "artifact" | "";
purpose?: "upload" | "writing" | "image" | "video" | "pdf" | "artifact" | "";
/**
* How it got here: the user attached it to a message, the bot wrote it, or a tool made it
*/
@@ -2615,9 +2690,9 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
*/
job_id?: number | "";
/**
* What the model was used for: a chat turn, reading media, transcribing, speaking, making an image, embedding
* What the model was used for: a chat turn, reading media, transcribing, speaking, making an image or a video, embedding
*/
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
/**
* The provider that served it. Not a foreign key: it stays readable after the provider is deleted
*/
@@ -2638,6 +2713,10 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
* Tokens sent: the prompt, the system instructions and the tool results
*/
prompt_tokens?: number | "";
/**
* Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it
*/
cached_tokens?: number | "";
/**
* Tokens written back: the answer, its tool calls and its reasoning
*/
@@ -2652,6 +2731,81 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
settings?: string;
}
export type BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
/**
* Whose work it was: the user whose conversation the call ran for. Not a foreign key
*/
user_id?: number | "";
/**
* The bot it was for, when it was for one. Not a foreign key
*/
bot_id?: number | "";
/**
* The workspace the call was in; null for a bot's own chat. Not a foreign key
*/
workspace_id?: number | "";
/**
* The conversation it was in. Not a foreign key
*/
session_id?: number | "";
/**
* The message its job posted, filled when the job ends (completed or failed). Not a foreign key
*/
message_id?: number | "";
/**
* The queued job it ran for, when it ran for one. Not a foreign key
*/
job_id?: number | "";
/**
* What the model was used for
*/
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
/**
* The provider it was sent to
*/
provider_id?: number | "";
/**
* The provider's name as it was, so a deleted provider still reads
*/
provider_name?: string;
/**
* The catalog row of the model
*/
model_id?: number | "";
/**
* The provider's model id, as it was called
*/
model_slug?: string;
/**
* How the model was chosen: the setting's pick, one of its fallback models or an automatic pick
*/
source?: "pinned" | "fallback" | "auto" | "";
/**
* The provider's HTTP status, when there was one
*/
status?: number | "";
/**
* Why it failed: the provider's error as the harness read it, cut at `AppData.HarnessFailureErrorMaxChars`
*/
error?: string;
/**
* Unix ms the model (or its provider) could be tried again, when the failure benched it
*/
rests_until?: number | "";
}
export type BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE = {
/**
* The unique identifier of the record.
@@ -2712,4 +2866,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
value?: string;
}
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
+55
View File
@@ -565,6 +565,58 @@ wait_for_health() {
fail "Cobble did not become healthy within ${HEALTH_TIMEOUT_SECONDS}s"
}
# ---------------------------------------------------------------- images
# Every release is a new image tag, and a host keeps every one of them
# otherwise: over a gigabyte each, so a year of updates can hold tens of
# gigabytes that nothing runs. Once the new container is healthy, the image
# the previous one ran is removed (the registry still has it) along with the
# layers nobody uses any more, and so is every older tag of the app's image
# and of the computer's, which the app pulls again when it needs one.
# MARK:old-image-tags
# The tags of one image repository in a `docker image ls --format
# '{{.Repository}} {{.Tag}}'` listing, except the tag being installed (an
# empty `keep` keeps none) and anything docker couldn't name.
old_image_tags() {
local listing="$1"
local repo="$2"
local keep="$3"
printf '%s\n' "$listing" | awk -v repo="$repo" -v keep="$keep" '
$1 == repo && $2 != "" && $2 != "<none>" && $2 != keep { print $2 }
'
}
# END:old-image-tags
prune_old_images() {
local previous="$1"
if [ -n "$previous" ] && [ "$previous" != "$IMAGE:$VERSION" ]; then
say "Removing the previous image ${previous}"
docker rmi "$previous" >/dev/null 2>&1 || true
fi
# Releases keep stacking up: an install updated twice a month holds
# every tag it ever ran. Docker refuses any image a container still
# uses, stopped ones included, so only what nothing runs goes.
local listing repo tag
listing="$(docker image ls --format '{{.Repository}} {{.Tag}}' 2>/dev/null || true)"
repo="$(printf '%s' "$IMAGE" | sed -E 's|:[^/:]+$||')"
for name in "$repo" "$repo-computer"; do
local keep=""
[ "$name" = "$repo" ] && keep="$VERSION"
while IFS= read -r tag; do
[ -z "$tag" ] && continue
say "Removing the older image ${name}:${tag}"
docker rmi "${name}:${tag}" >/dev/null 2>&1 || true
done <<< "$(old_image_tags "$listing" "$name" "$keep")"
done
docker image prune -f >/dev/null 2>&1 || true
}
backup_database() {
local data_source="$DATA_DIR"
if container_exists; then
@@ -909,6 +961,7 @@ if container_exists; then
# own layer, so lift it out before anything replaces the container.
rescue_container_data
backup_database
PREVIOUS_IMAGE_TAG="$(docker inspect -f '{{.Config.Image}}' "$CONTAINER" 2>/dev/null || true)"
say "Replacing the Cobble container"
docker stop -t 30 "$CONTAINER" >/dev/null 2>&1 || true
docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
@@ -920,6 +973,8 @@ connect_extra_network
wait_for_health
prune_old_images "${PREVIOUS_IMAGE_TAG:-}"
ok "Cobble is running"
printf '\n'
printf ' %sOpen Cobble%s\n' "$C_BOLD" "$C_RESET"
+58
View File
@@ -182,6 +182,64 @@ describe("install.sh mount specs", () => {
}
});
describe("install.sh image pruning", () => {
const LISTING = [
"ghcr.io/moduletrace/cobble 0.18.2",
"ghcr.io/moduletrace/cobble 0.18.3",
"ghcr.io/moduletrace/cobble 0.18.4",
"ghcr.io/moduletrace/cobble-computer 1.3.0",
"ghcr.io/moduletrace/cobble-computer 1.4.0",
"ghcr.io/moduletrace/cobble-tools 9.9.9",
"<none> <none>",
].join("\n");
async function oldImageTags({ repo, keep }: { repo: string; keep: string }) {
const block = await readMarkedBlock({ name: "old-image-tags" });
const script = [block, `old_image_tags "$LISTING" "$repo" "$keep"`].join("\n");
const proc = Bun.spawn({
cmd: ["bash", "-c", script],
env: { ...process.env, LISTING, repo, keep },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, , code] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
expect(code).toBe(0);
return stdout.trim().split("\n").filter(Boolean);
}
test("removes every older version of the app, keeping the one installed", async () => {
expect(
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble", keep: "0.18.4" }),
).toEqual(["0.18.2", "0.18.3"]);
});
test("removes every computer image tag, since the app pulls one again", async () => {
expect(
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble-computer", keep: "" }),
).toEqual(["1.3.0", "1.4.0"]);
});
test("never touches another repository's images", async () => {
// `cobble-tools` shares the prefix: a prefix match would take a
// project the installer knows nothing about.
const tags = await oldImageTags({
repo: "ghcr.io/moduletrace/cobble-tools",
keep: "",
});
expect(tags).toEqual(["9.9.9"]);
expect(
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble", keep: "" }),
).not.toContain("9.9.9");
});
});
describe("install.sh data rescue", () => {
test("rescues the container's data before replacing it", async () => {
const source = await Bun.file(INSTALL_SCRIPT).text();
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.15.2",
"version": "0.19.2",
"module": "index.ts",
"type": "module",
"private": true,
@@ -35,6 +35,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3"
},
"peerDependencies": {
@@ -45,7 +46,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.9",
"@moduletrace/twui": "^0.1.10",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -212,3 +212,64 @@ describe("botMessagesToHarness with mentions", () => {
]);
});
});
describe("botMessagesToHarness with reactions", () => {
test("adds the user's reactions to the record of the message's tools", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "summarise it"),
{
...message("bot", "Here it is."),
tool_log: JSON.stringify([{ name: "read_file", ok: true }]),
reactions: [
{ emoji: "👍" as const, count: 1, mine: true },
{ emoji: "👎" as const, count: 1, mine: true },
],
},
],
}),
).toEqual([
{ role: "user", content: "summarise it" },
{
role: "assistant",
content:
"Here it is.\n\n[App record: this message's run called read_file. The user reacted to it with 👍 (like), 👎 (dislike).]",
},
]);
});
test("records reactions on a message whose run wasn't recorded", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "hi"),
{
...message("bot", "hello"),
reactions: [{ emoji: "❤️" as const, count: 1, mine: true }],
},
],
}),
).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello\n\n[App record: The user reacted to it with ❤️ (love).]" },
]);
});
test("leaves out reactions that aren't the user's", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "hi"),
{
...message("bot", "hello"),
reactions: [{ emoji: "🎉" as const, count: 1, mine: false }],
},
],
}),
).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello" },
]);
});
});
+51 -8
View File
@@ -1,7 +1,8 @@
import isCrewMessage from "@/src/utils/is-crew-message";
import { BotMessageReactions } from "@/src/dict/bot-dict";
import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/harness/types";
import type { BotMessageWithAttachments } from "@/src/types";
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
import describeAttachment from "./describe-attachment";
@@ -10,7 +11,15 @@ import crewMessageBlock from "@/src/utils/crew-message-block";
type Params = {
messages: Pick<
BotMessageWithAttachments,
"id" | "author" | "text" | "attachments" | "reply_to" | "tool_log" | "from_chatroom_id" | "from_install_request_id"
| "id"
| "author"
| "text"
| "attachments"
| "reply_to"
| "tool_log"
| "reactions"
| "from_chatroom_id"
| "from_install_request_id"
>[];
/**
* Loaded files by message id (`loadAttachmentParts`). Files of other
@@ -34,7 +43,8 @@ type Turn = { role: "user" | "assistant"; parts: HarnessContentPart[] };
* starts with the user. A turn that is only text stays a string. A bot
* message whose run was recorded (`tool_log`) is followed by the app's
* record of the tools it called, so the bot can tell what its past
* messages actually did from what they say. A chatroom's outcome brought
* messages actually did from what they say, and of how the user reacted
* to it, their feedback on it. A chatroom's outcome brought
* back to the bot, or the coordinator's answer to its install request
* (`isCrewMessage`), is a user turn fenced as what the
* coordinator passed on (`crewMessageBlock`), never the user's words.
@@ -95,7 +105,9 @@ function messageParts({
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
if (role == "assistant") {
const record = text ? appRecord({ tool_log: message.tool_log }) : "";
const record = text
? appRecord({ tool_log: message.tool_log, reactions: message.reactions })
: "";
return record ? [...content, { type: "text", text: record }] : content;
}
@@ -116,10 +128,25 @@ function messageParts({
}
/**
* The app's line after a bot message naming the tools its run called, or
* nothing when the run wasn't recorded.
* The app's line after a bot message naming the tools its run called and
* the user's own reactions to it, or nothing when there's neither.
*/
function appRecord({ tool_log }: { tool_log?: string | null }) {
function appRecord({
tool_log,
reactions,
}: {
tool_log?: string | null;
reactions?: BotMessageReaction[];
}) {
const facts = [toolsRecord({ tool_log }), reactionsRecord({ reactions })].filter(Boolean);
return facts.length ? `${AppRecordPrefix} ${facts.join(" ")}]` : "";
}
/**
* The tools a recorded run called, or nothing when it wasn't recorded.
*/
function toolsRecord({ tool_log }: { tool_log?: string | null }) {
if (!tool_log) return "";
let uses: HarnessToolUse[];
@@ -134,7 +161,23 @@ function appRecord({ tool_log }: { tool_log?: string | null }) {
const called = uses.length ? describeToolUses({ uses }) : "no tools";
return `${AppRecordPrefix} this message's run called ${called}.]`;
return `this message's run called ${called}.`;
}
/**
* The reactions the user gave a message, named, or nothing. A bot's own
* reactions aren't the user's feedback.
*/
function reactionsRecord({ reactions }: { reactions?: BotMessageReaction[] }) {
const named = (reactions || [])
.filter((reaction) => reaction.mine)
.map((reaction) => {
const title = BotMessageReactions.find((known) => known.value == reaction.emoji)?.title;
return title ? `${reaction.emoji} (${title.toLowerCase()})` : reaction.emoji;
});
return named.length ? `The user reacted to it with ${named.join(", ")}.` : "";
}
/**
+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,74 @@
import { describe, expect, test } from "bun:test";
import type { BotMessageWithAttachments } from "@/src/types";
import liveAttachmentMessages from "./live-attachment-messages";
const message = ({ id, files }: { id: number; files?: number }): BotMessageWithAttachments => ({
id,
attachments: files
? Array.from({ length: files }, (_unused, index) => ({
id: index + 1,
name: `file-${index + 1}.png`,
media_type: "image",
url: `/media/${index + 1}.png`,
}))
: undefined,
});
describe("liveAttachmentMessages", () => {
test("hands over the files of the latest messages that have any", () => {
const messages = [
message({ id: 1 }),
message({ id: 2, files: 1 }),
message({ id: 3 }),
message({ id: 4, files: 2 }),
message({ id: 5 }),
];
expect(
liveAttachmentMessages({ messages, max_messages: 4, max_age: 8 }),
).toEqual([2, 4]);
});
test("only the newest few file-bearing messages", () => {
const messages = [
message({ id: 1, files: 1 }),
message({ id: 2, files: 1 }),
message({ id: 3, files: 1 }),
message({ id: 4, files: 1 }),
];
expect(
liveAttachmentMessages({ messages, max_messages: 2, max_age: 8 }),
).toEqual([3, 4]);
});
test("a file far back is named, not re-attached", () => {
const messages = [
message({ id: 1, files: 1 }),
...Array.from({ length: 20 }, (_unused, index) => message({ id: index + 2 })),
];
expect(
liveAttachmentMessages({ messages, max_messages: 4, max_age: 8 }),
).toEqual([]);
});
test("keeps a file that is still inside the age bound", () => {
const messages = [
message({ id: 1, files: 1 }),
...Array.from({ length: 6 }, (_unused, index) => message({ id: index + 2 })),
];
expect(
liveAttachmentMessages({ messages, max_messages: 4, max_age: 8 }),
).toEqual([1]);
});
test("no files, nothing to hand over", () => {
expect(
liveAttachmentMessages({
messages: [message({ id: 1 }), message({ id: 2 })],
}),
).toEqual([]);
});
});
@@ -0,0 +1,45 @@
import { AppData } from "@/src/data/app-data";
import type { BotMessageWithAttachments } from "@/src/types";
type Params = {
/**
* The conversation a reply reads, oldest first.
*/
messages: BotMessageWithAttachments[];
/**
* How many messages with files may hand their files over
* (`AppData.BotReplyAttachmentMessages`).
*/
max_messages?: number;
/**
* How far back a file may be and still be handed over
* (`AppData.BotReplyAttachmentMaxAgeMessages`).
*/
max_age?: number;
};
/**
* The messages whose attached files a reply gets as the files themselves,
* oldest first. Two limits, both needed: only the latest few messages with
* files (`max_messages`), and only while the conversation hasn't moved
* far past them (`max_age`).
*
* The age bound is what keeps one upload from being re-attached, and so
* re-read by the media reading harness, on every reply for the rest of a
* long session (a screenshot 25 messages back was read once per reply, a
* vision call of a minute each time). Past it the file is only named
* (`botMessagesToHarness`), so the bot still knows it was sent.
*/
export default function liveAttachmentMessages({
messages,
max_messages = AppData.BotReplyAttachmentMessages,
max_age = AppData.BotReplyAttachmentMaxAgeMessages,
}: Params): number[] {
const oldest_allowed = messages.length - Math.max(0, max_age);
return messages
.map((message, index) => ({ message, index }))
.filter(({ message, index }) => index >= oldest_allowed && Boolean(message.attachments?.length))
.slice(-Math.max(0, max_messages))
.map(({ message }) => Number(message.id));
}
+6 -10
View File
@@ -7,6 +7,7 @@ import type { HarnessContentPart } from "@/src/harness/types";
import type { BotMessageWithAttachments } from "@/src/types";
import extractBotFileText from "@/src/functions/backend/db/bot-files/extract-bot-file-text";
import describeAttachment from "./describe-attachment";
import liveAttachmentMessages from "./live-attachment-messages";
type Params = {
/**
@@ -17,18 +18,13 @@ type Params = {
/**
* The files of the latest few messages that have any
* (`AppData.BotReplyAttachmentMessages`), as model input by message id:
* images and audio as themselves (a model that can't take them gets them
* read first), documents as their text, videos as a note. Older files are
* only named (`botMessagesToHarness`).
* (`liveAttachmentMessages`), as model input by message id: images and
* audio as themselves (a model that can't take them gets them read
* first), documents as their text, videos as a note. Older files are only
* named (`botMessagesToHarness`).
*/
export default async function loadAttachmentParts({ messages }: Params) {
const recent = messages
.filter((message) => message.attachments?.length)
.slice(-AppData.BotReplyAttachmentMessages)
.map((message) => Number(message.id));
const media = await grabMessagesMedia({ message_ids: recent });
const media = await grabMessagesMedia({ message_ids: liveAttachmentMessages({ messages }) });
const parts = new Map<number, HarnessContentPart[]>();
for (const [message_id, files] of media) {
+31
View File
@@ -0,0 +1,31 @@
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
import type { HarnessMessage } from "@/src/harness/types";
import type { BotMessageWithAttachments } from "@/src/types";
import botMessagesToHarness from "./bot-messages-to-harness";
import loadAttachmentParts from "./load-attachment-parts";
type Params = {
messages: BotMessageWithAttachments[];
/**
* Whose conversation it is: the refs in the user's messages are named
* as that user sees them.
*/
user_id: number | string;
};
/**
* A conversation's messages as a run reads them: with the files of each
* (`loadAttachmentParts`) and the names of the bots, workspaces and other
* refs the user's messages point at. Replies and task runs read the same
* way.
*/
export default async function messagesToTurns({ messages, user_id }: Params): Promise<HarnessMessage[]> {
return botMessagesToHarness({
messages,
parts: await loadAttachmentParts({ messages }),
refs: await grabMessageRefNames({
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
user_id,
}),
});
}
@@ -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;
}
+13 -4
View File
@@ -168,7 +168,7 @@ export default async function processBotJob({
* The face changes once the job really starts, after any wait for
* its computer.
*/
const run = async () => {
const run = async ({ computer_shared }: { computer_shared?: boolean } = {}) => {
await setFace({
face: "working",
status_line:
@@ -194,6 +194,7 @@ export default async function processBotJob({
job,
params,
checkpoint: parseJobJson({ text: job.checkpoint }),
computer_shared,
signal: run_signal,
update,
report,
@@ -203,19 +204,25 @@ export default async function processBotJob({
/**
* A task whose computer is busy says so while it waits, so the
* user doesn't see silence.
* user doesn't see silence. A chatroom job doesn't wait: the bot
* that asked is often the one holding the computer, with a run of
* up to an hour, and the room would sit silent until it ends. It
* works beside it with the shell and files only (`computer_shared`),
* which is all most answers need.
*/
const runOnComputer = async (computer_id: number) => {
if (computer_lock.busy({ key: computer_id })) {
if (params.chatroom_id) return await run({ computer_shared: true });
await setFace({ face: "asleep", status_line: BotComputerBusyStatusLine });
}
return await computer_lock.run({ key: computer_id, task: run });
return await computer_lock.run({ key: computer_id, task: () => run() });
};
const outcome =
job.kind == "reply"
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: run })
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: () => run() })
: job.computer_id
? await runOnComputer(job.computer_id)
: await run();
@@ -230,6 +237,8 @@ export default async function processBotJob({
silent: outcome.silent,
attachments: outcome.attachments,
tool_log: outcome.tool_log,
task_ids: outcome.task_ids,
exhausted: outcome.exhausted,
});
await pushBotNotice({ bot_id, ...completion });
+6 -2
View File
@@ -5,6 +5,7 @@ import notifyBotMessage from "@/src/push/notify-bot-message";
import notifyBotFace from "@/src/push/notify-bot-face";
import pushBotUpdated from "./push-bot-updated";
import pushToSessionUser from "./push-to-session-user";
import withSessionMessageTasks from "./with-session-message-tasks";
import grabSessionChatroomId from "@/src/functions/backend/db/chatrooms/grab-session-chatroom-id";
import pushChatroomMessage from "@/src/functions/backend/db/chatrooms/push-chatroom-message";
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
@@ -66,7 +67,10 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
} else if (message && !hook_id) {
await pushToSessionUser({
session_id: message.session_id,
data: { event: "server:bot-message", data: message },
/**
* With its task chips, like a loaded message.
*/
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message }) },
});
/**
@@ -78,7 +82,7 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
if (relay) {
await pushToSessionUser({
session_id: relay.message.session_id,
data: { event: "server:bot-message", data: relay.message },
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message: relay.message }) },
});
if (!quiet_push) void notifyBotMessage({ message: relay.message });
+4 -1
View File
@@ -7,6 +7,7 @@ import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessToolUse } from "@/src/harness/types";
import replyClaimProblems from "@/src/utils/reply-claim-problems";
import replyRefIds from "@/src/utils/reply-ref-ids";
import unresolvedSettingRefs from "@/src/utils/unresolved-setting-refs";
import type { StorageScope } from "@/src/utils/storage-access";
type Params = {
@@ -24,7 +25,8 @@ type Params = {
/**
* Checks a chat reply's answer against what the app knows before it goes
* out (`replyClaimProblems`): every file and task it names must exist for
* the user (as their chips would open them), and work it says is under
* the user (as their chips would open them), every setting ref the app can
* resolve, and work it says is under
* way must have been started by this reply or still be open from this
* conversation. Returns the note that sends the answer back to be written
* again, or null when it holds up. Bots wrote "I'm scanning now" with the
@@ -52,6 +54,7 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
tool_uses,
missing_file_ids,
missing_task_ids,
unresolved_setting_refs: unresolvedSettingRefs({ text }),
has_open_work: await hasOpenWork({ bot_id, session_id }),
});
+66 -28
View File
@@ -3,9 +3,11 @@ import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings
import { AppData } from "@/src/data/app-data";
import {
ActionCheckNote,
RequestScopeNote,
QuestionsNote,
AskCrewNote,
SecretsNote,
SettingsNote,
GraphicsNote,
botFilesNote,
chatReplyNote,
@@ -15,13 +17,15 @@ import {
CoordinatorSoloNote,
TasksNote,
TaskReminderNote,
HandOverTaskNote,
workspaceAdminNote,
WorkspaceLearningNote,
openRunsNote,
} from "@/src/data/harness-prompts";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import workspaceAdminsNote from "./workspace-admins-note";
import type { WorkspaceAdminTools } from "@/src/harness/tools/bot/grab-workspace-admin-tools";
import { grabReplyMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
@@ -36,7 +40,8 @@ import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-s
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
import grabKnowledgebaseContext from "@/src/harness/tools/knowledgebases/grab-knowledgebase-context";
import botMessagesToHarness from "./bot-messages-to-harness";
import messagesToTurns from "./messages-to-turns";
import grabOpenSessionRuns from "@/src/functions/backend/db/bots-queue/grab-open-session-runs";
import composeBrowsersNote from "./compose-browsers-note";
import composeComputersNote from "./compose-computers-note";
import composeEnvsNote from "./compose-envs-note";
@@ -48,8 +53,6 @@ import readPastSessionTool from "@/src/harness/tools/bot/sessions/read-past-sess
import { grabBotSessionMaxMessages } from "@/src/functions/backend/db/app-settings/grab-bot-session-max-messages";
import BunSQLite from "@moduletrace/bun-sqlite";
import jobSessionId from "@/src/functions/backend/db/bots-queue/job-session-id";
import loadAttachmentParts from "./load-attachment-parts";
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
import withTakeOverRefs from "./with-take-over-refs";
import stripAppRecords from "@/src/utils/strip-app-records";
import hasUnansweredMessage from "./has-unanswered-message";
@@ -59,6 +62,7 @@ import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import type { BotMessageWithAttachments } from "@/src/types";
import type { HarnessMessage } from "@/src/harness/types";
import type { BotJobContext, BotJobOutcome } from "./types";
@@ -84,8 +88,9 @@ type Params = BotJobContext & {
* Messages the user sends while it works join the run (`incoming`): one
* that changes the work changes the answer before it goes out, and one
* that's separate can be acknowledged at once (`send_message`) and done
* after the current work. The job records the newest
* one it read (`markReplyAnswered`). Finishes silently when an earlier
* after the current work. Runs open in the session take in what the user
* writes too (`openRunsNote`), so a correction to one starts no other.
* The job records the newest one it read (`markReplyAnswered`). Finishes silently when an earlier
* reply already read everything (`hasUnansweredMessage`). An answer naming
* files or tasks that don't exist, or saying work is under way when none
* is, is written again once (`reviewBotReply`).
@@ -108,6 +113,7 @@ export default async function runBotReply({
const history = await grabBotMessages({
session_id,
limit: AppData.BotReplyHistoryMessages,
user_id,
});
const answered_id = await grabAnsweredMessageId({ session_id });
@@ -123,16 +129,6 @@ export default async function runBotReply({
let seen_id = Math.max(0, ...history.map((message) => Number(message.id)));
let answering_id = newestUserMessageId({ messages: history });
const toTurns = async ({ messages }: { messages: BotMessageWithAttachments[] }) =>
botMessagesToHarness({
messages,
parts: await loadAttachmentParts({ messages }),
refs: await grabMessageRefNames({
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
user_id,
}),
});
/**
* What the user wrote since the run last looked.
*/
@@ -149,7 +145,7 @@ export default async function runBotReply({
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
return await toTurns({ messages: fresh });
return await messagesToTurns({ messages: fresh, user_id });
};
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
@@ -217,14 +213,19 @@ export default async function runBotReply({
*/
const proposals: string[] = [];
/**
* The secrets the bot showed (`show_secret`) and the graphics it made
* or changed, whose chips the reply always carries.
* The secrets the bot showed (`show_secret`), the graphics it made
* or changed, and the next steps it suggested: their chips the reply
* always carries, without needing the user.
*/
const shown: string[] = [];
/**
* Files the bot wrote and asked to send with its reply.
*/
const attachments: number[] = [];
/**
* The tracker tasks the reply worked on, linked under it.
*/
const task_ids: number[] = [];
/**
* The files this run reaches: its file tools and the pictures it may
@@ -268,6 +269,7 @@ export default async function runBotReply({
led = admin;
},
onChatroom: ({ ref }) => shown.push(ref),
onTask: ({ task_id }) => task_ids.push(task_id),
});
/**
@@ -330,6 +332,12 @@ export default async function runBotReply({
* admin is told who leads it.
*/
const can_delegate = tools.some((tool) => tool.name == "delegate_task");
/**
* A worker passes on a task of its own (`hand_over_task`): the reply says
* where it went and that it needs the run id, so no one claims a hand-over
* that didn't happen.
*/
const can_hand_over = tools.some((tool) => tool.name == "hand_over_task");
const lead = led as WorkspaceAdminTools | null;
const crew_note = powers.is_coordinator
? can_delegate
@@ -339,6 +347,12 @@ export default async function runBotReply({
? workspaceAdminNote({ workspace_name: lead.workspace.name || "this workspace", members: lead.members })
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id });
/**
* The bot's runs open here hear what the user writes: a correction to
* one reaches it, so the reply doesn't start another.
*/
const open_runs = attended ? await grabOpenSessionRuns({ bot_id: bot.id, session_id }) : [];
try {
const result = await runTextLoop({
system: [
@@ -350,9 +364,12 @@ export default async function runBotReply({
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
TasksNote,
TaskReminderNote,
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
QuestionsNote,
RequestScopeNote({ can_ask: Boolean(attended) }),
attended ? QuestionsNote : "",
SecretsNote,
SettingsNote,
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
@@ -368,6 +385,7 @@ export default async function runBotReply({
run_kind: browser_run_kind,
}),
crew_note,
openRunsNote({ runs: open_runs }),
powers.is_coordinator ? "" : AskCrewNote,
skills.note,
knowledge.note,
@@ -377,7 +395,7 @@ export default async function runBotReply({
]
.filter(Boolean)
.join("\n\n"),
messages: await toTurns({ messages: history }),
messages: await messagesToTurns({ messages: history, user_id }),
tools: [
...tools,
sendMessageTool({ bot_id: bot.id, session_id: Number(session_id), workspace_id }),
@@ -400,13 +418,30 @@ export default async function runBotReply({
onRequest: ({ ref }) => proposals.push(ref),
onShow: ({ ref }) => shown.push(ref),
}),
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
/**
* Only where the user follows the conversation: a chatroom's
* hidden session has no card they could answer, and a
* question there was once shown to the coordinator as a bare
* ref, its answer never reaching the bot.
*/
...(attended
? [
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => shown.push(ref),
}),
]
: []),
...(has_past_sessions
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
: []),
@@ -425,6 +460,8 @@ export default async function runBotReply({
...knowledge.tools,
],
max_steps: await grabReplyMaxToolSteps(),
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
bot_id: bot.id,
workspace_id,
signal,
@@ -450,6 +487,7 @@ export default async function runBotReply({
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
};
} finally {
await extensions.close();
+209 -67
View File
@@ -1,3 +1,4 @@
import grabCrewRequests from "@/src/functions/backend/db/chatrooms/grab-crew-requests";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings/grab-skill-limits";
import grabWorkspaceAdminTools from "@/src/harness/tools/bot/grab-workspace-admin-tools";
@@ -5,8 +6,10 @@ import workspaceAdminsNote from "./workspace-admins-note";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import {
ActionCheckNote,
RequestScopeNote,
QuestionsNote,
SecretsNote,
SettingsNote,
GraphicsNote,
botFilesNote,
ComputerFilesNote,
@@ -16,13 +19,24 @@ import {
TasksNote,
TaskRunNote,
AskCrewNote,
crewRequestsNote,
WorkspaceLearningNote,
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
taskPlanNote,
} from "@/src/data/harness-prompts";
import { grabHarnessMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import {
grabContextBudgetTokens,
grabHarnessMaxToolSteps,
grabRunMaxPromptTokens,
grabUnattendedMaxToolSteps,
} from "@/src/functions/backend/db/app-settings/grab-run-limits";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import runTextLoop from "@/src/harness/text/run-text-loop";
import { isUnlimitedLimit, smallerRunLimit } from "@/src/utils/run-limit";
import openComputerTools from "@/src/harness/tools/computer/open-computer-tools";
import openBotBrowsers, { type OpenBotBrowsers } from "@/src/harness/tools/browsers/open-bot-browsers";
import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/extensions/open-bot-extensions";
@@ -31,8 +45,11 @@ import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-k
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool";
import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
import setUserWorkspaceRoleTool from "@/src/harness/tools/bot/set-user-workspace-role-tool";
import askToTakeOverTool from "@/src/harness/tools/computer/ask-to-take-over-tool";
import importFileTool from "@/src/harness/tools/computer/import-file-tool";
import searchComputersTool from "@/src/harness/tools/computer/search-computers-tool";
@@ -52,6 +69,11 @@ import stripAppRecords from "@/src/utils/strip-app-records";
import ScheduledRunFailedError from "./scheduled-run-failed-error";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
import taskIncoming from "./task-incoming";
import 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";
type Params = BotJobContext & {
bot: Pick<BUN_SQLITE_COBBLE_BOTS, "kind"> & { id: number };
@@ -72,6 +94,10 @@ type Params = BotJobContext & {
* A scheduled run acts on its own (`ScheduledRunNote`), as does a hook
* call (`HookRunNote`, its payload only data); one that reports it failed
* (`report_run_failed`) throws, so the queue retries it.
* A task the user follows takes in what they write in its conversation
* from when it was queued (`taskIncoming`): already there at the start,
* between steps, past a report not yet out, and by the wrap up. A
* correction changes the work; anything else is left to the chat.
* Every model turn is reported as a step (`report`).
*/
export default async function runBotTask({
@@ -79,6 +105,7 @@ export default async function runBotTask({
user_id,
job,
params,
computer_shared,
signal,
report,
}: Params): Promise<BotJobOutcome> {
@@ -93,10 +120,15 @@ export default async function runBotTask({
* changed, whose chips the report always carries.
*/
const shown: string[] = [];
/**
* The tracker tasks the run worked on, linked under its report.
*/
const task_ids: number[] = [];
const computer = job.computer_id
? await openComputerTools({
computer_id: job.computer_id,
browser: !computer_shared,
bot_id: bot.id,
user_id,
workspace_id,
@@ -132,6 +164,11 @@ export default async function runBotTask({
signal,
}).catch(() => "");
const take_overs: string[] = [];
/**
* The next steps the bot suggested: added to the message without
* needing the user.
*/
const suggestions: string[] = [];
/**
* Files the bot wrote and asked to send with its report.
*/
@@ -175,7 +212,14 @@ export default async function runBotTask({
*/
const admin_tools =
!powers.is_coordinator && workspace_id && powers.is_workspace_admin
? (await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, scopes })).tools
? (await grabWorkspaceAdminTools({
bot,
user_id,
workspace_id,
powers,
scopes,
onTask: ({ task_id }) => task_ids.push(task_id),
})).tools
: [];
const tools = [
@@ -189,6 +233,7 @@ export default async function runBotTask({
admin_workspace_ids: powers.admin_workspace_ids,
scopes,
hooked,
onTask: ({ task_id }) => task_ids.push(task_id),
})),
...admin_tools,
...(powers.is_coordinator
@@ -202,6 +247,12 @@ export default async function runBotTask({
workspace_id,
scopes,
}),
listWorkspacePeopleTool({ workspaces: coordinator_workspaces, workspace_id }),
setUserWorkspaceRoleTool({
user_id,
workspaces: coordinator_workspaces,
workspace_id,
}),
]
: []),
]
@@ -240,6 +291,13 @@ export default async function runBotTask({
in_task: true,
onAsk: ({ ref }) => take_overs.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => suggestions.push(ref),
}),
]
: []),
...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []),
@@ -324,81 +382,159 @@ export default async function runBotTask({
/**
* The install's limit, or less when the brief's writer set a
* budget (`start_task` `max_steps`).
* budget (`start_task` `max_steps`). A routine run or a hook call,
* which nobody watches, gets the smaller unattended limit (never
* more than a task's).
*/
const install_steps = await grabHarnessMaxToolSteps();
const task_steps = await grabHarnessMaxToolSteps();
const install_steps =
scheduled || hooked
? smallerRunLimit({ a: task_steps, b: await grabUnattendedMaxToolSteps() })
: task_steps;
const budget = Math.floor(Number(params.max_steps) || 0);
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
const max_steps = budget > 0 ? smallerRunLimit({ a: budget, b: install_steps }) : install_steps;
/**
* What the run is told it has. Unlimited is said as such rather
* than as a number: the job's deadline still ends it, and a run
* told "at most 0 steps" would stop before it began.
*/
const steps_note = isUnlimitedLimit(max_steps)
? `This run has no step limit: work until the job is done. Its job still stops it after a while, so save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
: `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`;
/**
* What the user wrote since the run was queued, for a run they
* follow: what's there now goes after the brief.
*/
const incoming =
can_ask && session_id
? await taskIncoming({ session_id, queued_at: Number(job.created_at) || Date.now(), user_id })
: null;
const arrived = (await incoming?.take()) || [];
const brief: HarnessMessage = {
role: "user",
content: composeJobBrief({
title: job.title,
instructions: job.instructions,
params,
}),
};
const opening: HarnessMessage[] = [brief];
if (arrived.length) {
pushUserTurn({ transcript: opening, content: TaskIncomingNote });
for (const turn of arrived) {
if (turn.role == "user") pushUserTurn({ transcript: opening, content: turn.content });
}
}
const system = [
prompt,
carry_over,
TaskRunNote,
steps_note,
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
TasksNote,
ActionCheckNote,
RequestScopeNote({ can_ask }),
can_ask ? QuestionsNote : "",
SecretsNote,
SettingsNote,
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
powers.is_coordinator
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
: admin_tools.some((tool) => tool.name == "update_workspace")
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
: "",
powers.is_coordinator || powers.is_workspace_admin
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
powers.is_coordinator || hooked || params.chatroom_id
? ""
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
computer && computer_shared
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
: computer
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
: workspace_id
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
: `You have no computer for this task.`,
computers.length > 1
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
: "",
computer?.envs.length
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
.join("\n")}`
: "",
composeBrowsersNote({
browsers: browsers.browsers,
has_computer_browser: Boolean(computer),
run_kind: browser_run_kind,
}),
skills.note,
knowledge.note,
extensions.note,
]
.filter(Boolean)
.join("\n\n");
/*
* The plan this run works from, written in one turn before it takes
* a step (`planBotTask`). It shares this run's prompt, so it costs
* little more than the plan, and it saves the steps a long run
* spends finding out what it is doing. A run whose plan can't be
* written starts the way it always did.
*/
const planned = shouldPlanBotTask({ max_steps, in_chatroom: Boolean(params.chatroom_id) })
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
(error) => {
if (signal.aborted) throw error;
return null;
},
)
: null;
if (planned) {
pushUserTurn({ transcript: opening, content: taskPlanNote({ plan: planned.plan }) });
await report({
index: -1,
text: `Plan: ${planned.plan.goal}`,
tool_calls: [],
candidate: planned.candidate,
});
}
const result = await runTextLoop({
system: [
prompt,
carry_over,
TaskRunNote,
budget > 0
? `This run has at most ${max_steps} steps (model turns), set when it was queued. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
: "",
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
TasksNote,
ActionCheckNote,
can_ask ? QuestionsNote : "",
SecretsNote,
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
powers.is_coordinator
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
: admin_tools.some((tool) => tool.name == "update_workspace")
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
: "",
powers.is_coordinator || powers.is_workspace_admin
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
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"),
messages: [
{
role: "user",
content: composeJobBrief({
title: job.title,
instructions: job.instructions,
params,
}),
},
],
system,
messages: opening,
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
bot_id: bot.id,
workspace_id,
signal,
onStep: (step) =>
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
...(incoming
? {
incoming: incoming.take,
incoming_notes: {
working: TaskIncomingNote,
redraft: TaskRedraftNote,
wrap_up: TaskWrapUpIncomingNote,
},
}
: {}),
});
if (failure) {
@@ -411,10 +547,16 @@ export default async function runBotTask({
...withTakeOverRefs({
text: computer ? computer.redact(text) : text,
refs: take_overs,
shown,
shown: [...shown, ...suggestions],
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
/**
* The wrap up was announced (`steps` counts its turns), so the
* run never got to the end of the work it was given.
*/
exhausted: !isUnlimitedLimit(max_steps) && result.steps > max_steps,
};
} finally {
await extensions?.close();
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import shouldPlanBotTask from "./should-plan-bot-task";
describe("shouldPlanBotTask", () => {
test("plans a run long enough to repay the plan", () => {
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps })).toBe(true);
expect(shouldPlanBotTask({ max_steps: 200 })).toBe(true);
});
test("always plans a run with no step limit: it has the steps to repay it", () => {
expect(shouldPlanBotTask({ max_steps: UnlimitedLimit })).toBe(true);
});
test("leaves a short run alone: its first turn is its plan", () => {
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps - 1 })).toBe(false);
expect(shouldPlanBotTask({ max_steps: 1 })).toBe(false);
});
test("never plans a chatroom turn, not even an unlimited one", () => {
expect(shouldPlanBotTask({ max_steps: 200, in_chatroom: true })).toBe(false);
expect(shouldPlanBotTask({ max_steps: UnlimitedLimit, in_chatroom: true })).toBe(false);
});
});
+27
View File
@@ -0,0 +1,27 @@
import { AppData } from "@/src/data/app-data";
import { isUnlimitedLimit, type RunLimit } from "@/src/utils/run-limit";
/**
* Whether a task run plans before its first step (`planBotTask`).
*
* Planning is an economy, not a rule. It costs one turn, mostly served
* from the cache the run's own turns share, and it saves the steps a run
* spends working out what it is doing. A run too short to repay that gets
* nothing from it: its first turn is its plan. An unlimited run always
* plans, since it has the steps to repay it.
*
* A chatroom turn is never planned: it is short, it has almost no tools,
* and nobody follows it.
*/
export default function shouldPlanBotTask({
max_steps,
in_chatroom,
}: {
max_steps: RunLimit;
in_chatroom?: boolean;
}) {
if (in_chatroom) return false;
if (isUnlimitedLimit(max_steps)) return true;
return max_steps >= AppData.BotTaskPlanMinSteps;
}
@@ -0,0 +1,40 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
/**
* A task run reads what the user wrote in its session after it was
* queued. Run against real SQLite.
*/
const db = new Database(":memory:");
db.run(`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT, created_at INTEGER)`);
db.run(`INSERT INTO bot_messages VALUES
(1, 1, 'user', 100),
(2, 1, 'bot', 200),
(3, 2, 'user', 250),
(4, 1, 'user', 300),
(5, 1, 'bot', 400)`);
function baseline({ session_id, queued_at }: { session_id: number; queued_at: number }) {
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
return (db.query(sql).get(...values) as { id: number }).id;
}
describe("taskIncomingBaselineSql", () => {
test("is the session's newest message when the run was queued", () => {
expect(baseline({ session_id: 1, queued_at: 250 })).toBe(2);
expect(baseline({ session_id: 1, queued_at: 300 })).toBe(4);
});
test("ignores other sessions", () => {
expect(baseline({ session_id: 2, queued_at: 260 })).toBe(3);
expect(baseline({ session_id: 1, queued_at: 260 })).toBe(2);
});
test("is 0 when the session had nothing yet", () => {
expect(baseline({ session_id: 1, queued_at: 50 })).toBe(0);
expect(baseline({ session_id: 9, queued_at: 500 })).toBe(0);
});
});
@@ -0,0 +1,22 @@
import type { SqlCondition } from "@/src/utils/crew-access/types";
type Params = {
session_id: number | string;
/**
* When the run was queued (`bots_queue.created_at`, ms).
*/
queued_at: number;
};
/**
* The SQL for the newest message a session had when a run was queued:
* what the user writes after it is new to the run, however long it waited
* for its computer or how often it was tried. Selects one `id` column, 0
* for an empty session.
*/
export default function taskIncomingBaselineSql({ session_id, queued_at }: Params): SqlCondition {
return {
sql: `SELECT COALESCE(MAX(id), 0) AS id FROM bot_messages WHERE session_id = ? AND created_at <= ?`,
values: [Number(session_id), Number(queued_at)],
};
}
+51
View File
@@ -0,0 +1,51 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import type { HarnessMessage } from "@/src/harness/types";
import isCrewMessage from "@/src/utils/is-crew-message";
import messagesToTurns from "./messages-to-turns";
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
type Params = {
session_id: number | string;
/**
* When the run was queued (`bots_queue.created_at`, ms).
*/
queued_at: number;
/**
* Whose conversation it is.
*/
user_id: number | string;
};
/**
* What the user writes in a task run's conversation, for the run to take
* in (`runTextLoop`'s `incoming`): each `take` returns the messages since
* the last, starting from when the run was queued. A crew message (a
* room's outcome, an install answer) is left to the reply it wakes.
*/
export default async function taskIncoming({ session_id, queued_at, user_id }: Params) {
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
const res = await BunSQLite.sql<{ id: number }>({ sql, values });
let seen_id = Number(res.payload?.[0]?.id) || 0;
const take = async (): Promise<HarnessMessage[]> => {
const fresh = await grabBotMessages({
session_id,
after_id: seen_id,
author: "user",
limit: AppData.BotReplyHistoryMessages,
});
if (!fresh.length) return [];
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
const from_user = fresh.filter((message) => !isCrewMessage({ message }));
return from_user.length ? await messagesToTurns({ messages: from_user, user_id }) : [];
};
return { take };
}
+18
View File
@@ -9,6 +9,12 @@ export type BotJobContext = {
* Saved by an earlier attempt, if the job was picked up again.
*/
checkpoint: Record<string, unknown> | null;
/**
* The job runs on its computer beside another job that holds it (a
* chatroom job, which never waits for a busy computer): it gets the
* computer's shell and files, never its browser.
*/
computer_shared?: boolean;
/**
* Aborted when the job is cancelled or lost to another handler. Stop
* work and return; the result is discarded.
@@ -51,6 +57,18 @@ export type BotJobOutcome = {
* the result message as `tool_log`.
*/
tool_log?: HarnessToolUse[];
/**
* The tracker tasks the run worked on (`onTask` from its task tools),
* kept on the result message as `task_ids`.
*/
task_ids?: number[];
/**
* 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>;
@@ -0,0 +1,27 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import withMessageTasks from "@/src/functions/backend/db/bots/with-message-tasks";
type Params = {
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
};
/**
* A message about to be pushed, with the tracker tasks it's about as its
* session's user sees them (`withMessageTasks`). Without any, or when the
* session is gone, it's returned as it is.
*/
export default async function withSessionMessageTasks({ message }: Params) {
if (!message.task_ids || !message.session_id) return message;
const session = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT user_id FROM bot_sessions WHERE id = ? LIMIT 1`,
values: [message.session_id],
})
).payload?.[0];
if (!session?.user_id) return message;
return (await withMessageTasks({ messages: [message], user_id: session.user_id }))[0] ?? message;
}
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import takeOverRef from "@/src/utils/take-over-ref";
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
import withTakeOverRefs from "./with-take-over-refs";
const ref = takeOverRef({ id: 1, mode: "browser" });
@@ -21,4 +22,13 @@ describe("withTakeOverRefs", () => {
test("leaves a message without a take-over alone", () => {
expect(withTakeOverRefs({ text: "Done.", refs: [] })).toEqual({ result: "Done.", needs_you: false });
});
test("adds suggested next steps without needing the user", () => {
const suggestions = botSuggestionRef({ id: 4 });
expect(withTakeOverRefs({ text: "Done.", refs: [], shown: [suggestions] })).toEqual({
result: `Done.\n\n${suggestions}`,
needs_you: false,
});
});
});
+5 -3
View File
@@ -6,8 +6,9 @@ type Params = {
*/
refs: string[];
/**
* The secrets it showed (`secretRef`): added the same way, but they
* don't need the user.
* The secrets it showed (`secretRef`) and the next steps it suggested
* (`botSuggestionRef`): added the same way, but they don't need the
* user, so neither makes the message.
*/
shown?: string[];
};
@@ -16,7 +17,8 @@ type Params = {
* A job's message with every take-over the bot asked for in it and every
* proposal it made: refs the bot didn't write itself are added at the
* end, so the user always gets the button. A message asking for either
* needs the user.
* needs the user; secrets it showed and next steps it suggested are added
* without asking anything of them.
*/
export default function withTakeOverRefs({ text, refs, shown = [] }: Params) {
const missing = [...new Set([...refs, ...shown])].filter((ref) => !text.includes(ref));
@@ -0,0 +1,27 @@
import Span from "@moduletrace/twui/layout/Span";
import formatBytes from "@/src/utils/format-bytes";
type Props = {
size?: number;
/**
* Where the file sits (`bots/3/reports/q3.md`).
*/
full_path?: string;
};
/**
* The line under a previewed file's name: its size and its full path,
* whichever of them is known. The path wraps rather than cuts off, so all
* of it can be read (and selected to copy).
*/
export default function FilePreviewDetails({ size, full_path }: Props) {
const text = [size ? formatBytes({ bytes: size }) : "", full_path || ""].filter(Boolean).join(" · ");
if (!text) return null;
return (
<Span title={full_path || undefined} className="w-full text-[13px] leading-[18px] text-ink-secondary break-all">
{text}
</Span>
);
}
+16 -1
View File
@@ -9,6 +9,10 @@ type Props = {
url: string;
media_type?: string | null;
size?: number;
/**
* Where the file sits (`bots/3/reports/q3.md`), for the preview.
*/
full_path?: string;
/**
* The images it sits among (`imagePreviewGallery`), for Previous and
* Next in the preview.
@@ -24,7 +28,17 @@ type Props = {
* plain click. It stays a real link to the bytes, so a middle click or
* Ctrl/Cmd click still opens the file in a new tab.
*/
export default function FilePreviewLink({ name, url, media_type, size, gallery, title, className, children }: Props) {
export default function FilePreviewLink({
name,
url,
media_type,
size,
full_path,
gallery,
title,
className,
children,
}: Props) {
const [open, setOpen] = useState(false);
return (
@@ -50,6 +64,7 @@ export default function FilePreviewLink({ name, url, media_type, size, gallery,
url={url}
media_type={media_type}
size={size}
full_path={full_path}
gallery={gallery}
onClose={() => setOpen(false)}
/>
@@ -11,9 +11,9 @@ import usePreloadImages from "@/src/hooks/use-preload-images";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import type { FilePreviewItem } from "@/src/types";
import filePreviewKind from "@/src/utils/file-preview-kind";
import formatBytes from "@/src/utils/format-bytes";
import galleryIndex from "@/src/utils/gallery-index";
import FilePreviewBody from "./file-preview-body";
import FilePreviewDetails from "./file-preview-details";
import FilePreviewStepper from "./file-preview-stepper";
type Props = {
@@ -21,6 +21,10 @@ type Props = {
url: string;
media_type?: string | null;
size?: number;
/**
* Where the file sits (`bots/3/reports/q3.md`), shown beside its size.
*/
full_path?: string;
/**
* The images it was opened among (a folder's, a message's). When the
* file is one of them, Previous and Next (and the arrow keys) step
@@ -34,7 +38,7 @@ const ActionClassName =
"shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline";
/**
* A file over the page: markdown rendered, a CSV as a table, an image,
* A file over the page, its full path beside its size: markdown rendered, a CSV as a table, an image,
* PDF, audio or video in place, other text as code, with ways to download
* it or open it in a new tab. A file it can't show offers those only.
* Opened from a gallery, it steps through its images; each one opens fresh
@@ -44,7 +48,7 @@ export default function FilePreviewModal({ gallery, onClose, ...opened }: Props)
const [index, set_index] = useState(() => galleryIndex({ gallery, url: opened.url }));
const stepping = Boolean(gallery && index >= 0 && gallery.length > 1);
const shown: FilePreviewItem = (stepping && gallery?.[index]) || opened;
const { name, url, media_type, size } = shown;
const { name, url, media_type, size, full_path } = shown;
const kind = filePreviewKind({ name, media_type });
const base_name = name.split("/").pop() || name;
const count = gallery?.length || 0;
@@ -77,11 +81,7 @@ export default function FilePreviewModal({ gallery, onClose, ...opened }: Props)
>
{base_name}
</H2>
{size ? (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{formatBytes({ bytes: size })}
</Span>
) : null}
<FilePreviewDetails size={size} full_path={full_path} />
</Stack>
{stepping ? (
<FilePreviewStepper
@@ -2,6 +2,7 @@ import { expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import { AppData } from "@/src/data/app-data";
import FilePreviewBody from "./file-preview-body";
import FilePreviewDetails from "./file-preview-details";
import FilePreviewLink from "./file-preview-link";
import FilePreviewMarkdown from "./file-preview-markdown";
import FilePreviewTable from "./file-preview-table";
@@ -86,3 +87,12 @@ test("a gallery's stepper says where the image stands and stops at the ends", ()
expect((first.match(/disabled=""/g) || []).length).toBe(1);
expect((last.match(/disabled=""/g) || []).length).toBe(1);
});
test("the preview names the file's full path beside its size", () => {
const html = renderToString(<FilePreviewDetails size={2048} full_path="bots/3/reports/q3.md" />);
expect(html).toContain("2.0 KB");
expect(html).toContain("bots/3/reports/q3.md");
expect(renderToString(<FilePreviewDetails full_path="media/1/a.pdf" />)).toContain("media/1/a.pdf");
expect(renderToString(<FilePreviewDetails />)).toBe("");
});
+26 -2
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import Checkbox from "@moduletrace/twui/form/Checkbox";
import Form from "@moduletrace/twui/form/Form";
import Select from "@moduletrace/twui/form/Select";
import Textarea from "@moduletrace/twui/form/Textarea";
@@ -24,6 +25,12 @@ type Props<T> = {
* Offer a note added to the brief (a task's hand-over).
*/
with_note?: boolean;
/**
* Offer to start the work now (a task's hand-over). Off by default:
* handing a task over only moves it, it never starts the work unless
* the user asks for that here.
*/
with_start?: boolean;
onHandedOver: (params: { saved: T; msg: string }) => void;
onCancel: () => void;
};
@@ -39,12 +46,14 @@ export default function HandOverForm<T extends { [k: string]: any }>({
submit_path,
body,
with_note,
with_start,
onHandedOver,
onCancel,
}: Props<T>) {
const [targets, setTargets] = useState<HandOverTarget[]>();
const [bot_id, setBotId] = useState<number>();
const [note, setNote] = useState("");
const [start, setStart] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -73,14 +82,19 @@ export default function HandOverForm<T extends { [k: string]: any }>({
return;
}
if (!window.confirm(`Hand ${what} over to ${target.name}?`)) return;
if (!window.confirm(`Hand ${what} over to ${target.name}${with_start && start ? " and start it now" : ""}?`)) return;
setLoading(true);
setError(undefined);
const res = await postAdminApi<T>({
path: submit_path,
body: { ...body, bot_id: target.id, instructions: with_note && note.trim() ? note : undefined },
body: {
...body,
bot_id: target.id,
instructions: with_note && note.trim() ? note : undefined,
...(with_start ? { start } : {}),
},
});
setLoading(false);
@@ -121,6 +135,16 @@ export default function HandOverForm<T extends { [k: string]: any }>({
disabled={loading}
/>
) : null}
{with_start && targets?.length ? (
<Checkbox
title="Start it now"
label="Start it now"
info="Left off, the task only moves: it lands on their list as to do, and nothing runs until they're told to start."
checked={start}
clickDispatchHandler={setStart}
wrap
/>
) : null}
<AddFormActions submit_label="Hand over" loading={loading} error={error} onCancel={onCancel} />
</Stack>
</Form>
@@ -61,6 +61,7 @@ export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder
url={entry.url || ""}
media_type={entry.media_type}
size={entry.size}
full_path={entry.full_path}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
@@ -131,6 +131,7 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
submit_path="tasks/hand-over-task"
body={{ task_id: Number(task.id) }}
with_note
with_start
onCancel={() => setHandingOver(false)}
onHandedOver={({ saved, msg }) => {
setHandingOver(false);
+2
View File
@@ -43,6 +43,8 @@ export default function TaskFileRow({ file, onDetach, busy }: Props) {
name={file.name || `File ${file.media_id}`}
url={`/media/${file.media_id}`}
media_type={file.media_type}
size={file.size}
full_path={file.full_path}
className="grow min-w-0 text-[13px] leading-[18px] text-ink truncate hover:underline"
>
{file.name || `File ${file.media_id}`}
@@ -42,8 +42,9 @@ type Props = {
};
/**
* Picks one file and sends it for a restore: shared by the database upload
* and the data archive upload, which differ only in what they accept.
* Picks one file and sends it for a restore: shared by the database upload,
* the data archive upload and the restore at first-run setup, which differ
* only in what they accept.
*/
export default function UploadRestoreFields({
label,
@@ -0,0 +1,92 @@
import { useState } from "react";
import Form from "@moduletrace/twui/form/Form";
import Textarea from "@moduletrace/twui/form/Textarea";
import { AppData } from "@/src/data/app-data";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
type Props = {
workspace_id: number;
workspace_name: string;
user_id: number;
person_name: string;
/**
* Their role there now.
*/
role?: string | null;
onCancel: () => void;
/**
* After the save, with the role as saved (null once cleared).
*/
onSaved: (role: string | null) => void;
};
/**
* The form for who a user is in one workspace
* (`api/admin/workspaces/set-user-role`, crew managers). Emptied, it
* clears the role. It asks first.
*/
export default function WorkspaceUserRoleForm({
workspace_id,
workspace_name,
user_id,
person_name,
role: initial,
onCancel,
onSaved,
}: Props) {
const [role, setRole] = useState(initial || "");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
const submit = async () => {
if (loading) return;
const cleared = !role.trim();
if (
!window.confirm(
cleared
? `Clear ${person_name}'s role in ${workspace_name}?`
: `Save ${person_name}'s role in ${workspace_name}?`,
)
) {
return;
}
setLoading(true);
setError(undefined);
const res = await postAdminApi<{ role: string | null }>({
path: "workspaces/set-user-role",
body: { workspace_id, user_id, role },
});
setLoading(false);
if (!res.success) {
setError(res.msg || "Couldn't save.");
return;
}
onSaved(res.singleRes?.role || null);
};
return (
<Form className="w-full gap-4! items-stretch pt-4" onSubmit={submit}>
<Textarea
id={`workspace-user-role-${workspace_id}-${user_id}`}
title="Their role here"
label="Their role here"
showLabel
rows={6}
maxLength={AppData.WorkspaceUserRoleMaxLength}
placeholder="Head of sales. Wants numbers first and short answers; decides on pricing, not on the product."
defaultValue={initial || ""}
info={`Every bot here reads this when it works for ${person_name}, only in this workspace. ${person_name} doesn't see or change it. Leave it empty to clear it.`}
onChange={(e) => setRole(e.target.value)}
/>
<AddFormActions submit_label="Save" loading={loading} error={error} onCancel={onCancel} />
</Form>
);
}
@@ -0,0 +1,49 @@
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import WorkspaceUserRoleForm from "./workspace-user-role-form";
type Props = {
workspace_id: number;
workspace_name: string;
user_id: number;
person_name: string;
role?: string | null;
onClose: () => void;
onSaved: (role: string | null) => void;
};
/**
* Who a user is in one workspace, which every bot there reads when it
* works for them. Separate from their bio, which is theirs to write.
* Opened from the workspace's settings and from the user's.
*/
export default function WorkspaceUserRoleModal({
workspace_id,
workspace_name,
user_id,
person_name,
role,
onClose,
onSaved,
}: Props) {
return (
<AddModalShell
open
setOpen={(open) => !open && onClose()}
title={`${person_name} in ${workspace_name}`}
description={`Their role and anything the bots should know about them in this workspace, to pitch their replies to them. A user can have a different role in each workspace.`}
>
<WorkspaceUserRoleForm
workspace_id={workspace_id}
workspace_name={workspace_name}
user_id={user_id}
person_name={person_name}
role={role}
onCancel={onClose}
onSaved={(saved) => {
onSaved(saved);
onClose();
}}
/>
</AddModalShell>
);
}
+29
View File
@@ -4,6 +4,10 @@ import pruneBotsQueue from "./prune-bots-queue";
import cronClearJobSteps from "./clear-job-steps";
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";
import cronSyncHarnessModels from "./sync-harness-models";
@@ -53,12 +57,37 @@ export default function cron() {
task: cronPruneChatrooms,
});
registerCronJob({
title: "prune-orphan-media",
schedule: "@daily",
task: cronPruneOrphanMedia,
});
registerCronJob({
title: "prune-computer-caches",
schedule: "@daily",
task: cronPruneComputerCaches,
});
registerCronJob({
title: "prune-computer-homes",
schedule: "@daily",
task: cronPruneComputerHomes,
});
registerCronJob({
title: "prune-logs",
schedule: "@daily",
task: pruneLogs,
});
registerCronJob({
title: "warn-computer-workspaces",
schedule: "@daily",
task: cronWarnComputerWorkspaces,
quiet: true,
});
registerCronJob({
title: "sync-notify-watchers",
schedule: "*/5 * * * *",
+13
View File
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteHookSessionRows from "@/src/functions/backend/db/bot-hooks/delete-hook-session-rows";
import { grabHookEventsKeepDays } from "@/src/functions/backend/db/app-settings/grab-hook-events-keep-days";
import deleteUnlinkedAttachmentMedia from "@/src/functions/backend/db/media/delete-unlinked-attachment-media";
/**
* Deletes hook calls (with their responses) older than the install's
@@ -14,7 +15,19 @@ export default async function pruneBotHookEvents() {
WHERE s.hook_id IS NOT NULL AND m.id IN (SELECT response_message_id FROM bot_hook_events WHERE created_at < ?)`;
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})`, values: [cutoff] });
/**
* The call's uploads go with its messages: their `media` row is what
* the deleted link was the only way to reach.
*/
const uploads = await BunSQLite.sql<{ media_id: number }>({
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
values: [cutoff],
});
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})`, values: [cutoff] });
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE id IN (${messages})`, values: [cutoff] });
await deleteHookSessionRows({});
+15
View File
@@ -0,0 +1,15 @@
import pruneComputerCaches from "@/src/functions/backend/computers/prune-computer-caches";
/**
* Clears the caches a computer's folders hold (`pruneComputerCaches`):
* what pip, npm and bun write beside a run's work, Python's bytecode and
* every Chrome profile's caches. Runs now keep their caches inside the
* container (`computerCacheEnv`), so this is what an install that grew
* before that shrinks back with.
*/
export default async function cronPruneComputerCaches() {
const pruned = await pruneComputerCaches();
const bytes = pruned.reduce((total, entry) => total + entry.bytes, 0);
return { removed: pruned.length, mb: Math.round(bytes / (1024 * 1024)) };
}
+10
View File
@@ -0,0 +1,10 @@
import pruneComputerHomes from "@/src/functions/backend/db/computers/prune-computer-homes";
/**
* Deletes the computer folders `prepareComputerDataDir` moved aside
* (`pruneComputerHomes`) once their data is past its keep. They are no
* longer mounted anywhere, so they only take space on the data volume.
*/
export default async function cronPruneComputerHomes() {
return { deleted: (await pruneComputerHomes()).length };
}
+8 -1
View File
@@ -3,11 +3,18 @@ import { grabLogsKeepDays } from "@/src/functions/backend/db/app-settings/grab-l
/**
* Deletes logs older than the install's retention (`grabLogsKeepDays`).
* Nothing points at a log, so no children go with them.
* Nothing points at a log, so no children go with them. Failed model calls
* (`harness_call_failures`, shown in a message's details) go with the same
* retention.
*/
export default async function pruneLogs() {
const cutoff = Date.now() - (await grabLogsKeepDays()) * 24 * 60 * 60 * 1000;
await BunSQLite.sql({
sql: `DELETE FROM harness_call_failures WHERE created_at < ?`,
values: [cutoff],
});
return await BunSQLite.sql({
sql: `DELETE FROM logs WHERE created_at < ? RETURNING id`,
values: [cutoff],
+10
View File
@@ -0,0 +1,10 @@
import pruneOrphanMedia from "@/src/functions/backend/db/media/prune-orphan-media";
/**
* Deletes media nothing points at any more (`pruneOrphanMedia`): chat
* uploads left behind by a pruned room or hook session, and uploads that
* were never saved. It is how their bytes leave the data volume.
*/
export default async function cronPruneOrphanMedia() {
return { deleted: (await pruneOrphanMedia()).length };
}
+9 -2
View File
@@ -6,6 +6,7 @@ import logEvent from "@/src/functions/backend/logger";
import migrateComputerLayout from "@/src/functions/backend/db/computers/migrate-computer-layout";
import provisionComputer from "@/src/functions/backend/db/computers/provision-computer";
import refreshComputerContainer from "@/src/functions/backend/db/computers/refresh-computer-container";
import reviveFailedComputer from "@/src/functions/backend/db/computers/revive-failed-computer";
import syncComputerBrowserPolicy from "@/src/functions/backend/db/computers/sync-computer-browser-policy";
type Row = Pick<
@@ -16,7 +17,8 @@ type Row = Pick<
/**
* Reads every computer container's state from docker and records it
* (`refreshComputerContainer`), telling owners about changes. Containers
* still being set up, or that failed, are left alone. A container that
* still being set up are left alone, and failed ones unless docker runs
* them anyway (`reviveFailedComputer`). A container that
* still mounts its computer's whole home is recreated with only the
* workspace (`migrateComputerLayout`, once per computer). A running one
* gets the browser policy it lacks (`syncComputerBrowserPolicy`), so
@@ -33,13 +35,18 @@ export default async function syncComputers() {
await BunSQLite.sql<Row>({
sql: `SELECT co.id, co.docker_id, co.status, co.ip_address, co.metadata, c.id AS computer_id
FROM containers co JOIN computers c ON c.container_id = co.id
WHERE co.docker_id IS NOT NULL AND co.status NOT IN ('creating', 'failed')`,
WHERE co.docker_id IS NOT NULL AND co.status != 'creating'`,
})
).payload || [];
let changed = 0;
for (const { computer_id, metadata, ...container } of rows) {
if (container.status == "failed") {
await reviveFailedComputer({ computer_id, container });
continue;
}
if (await migrateComputerLayout({ computer_id, metadata })) continue;
const refreshed = await refreshComputerContainer({
@@ -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) };
}
+312 -25
View File
File diff suppressed because it is too large Load Diff
+78
View File
@@ -0,0 +1,78 @@
/**
* What a bot's folder on a computer holds that is rebuilt on demand, and
* so is never worth keeping.
*
* A computer's workspace is mounted from the data volume, so without this
* every cache a run writes beside its work is kept forever: one install's
* volume held 368 MB of npm cache, 188 MB of pip and headless-Chromium
* caches and 53 MB of bun's install cache, against 178 MB of bot files.
* Runs now point their caches at the account's own home inside the
* container (`computerCacheEnv`), which a new container starts without;
* `pruneComputerCaches` clears what earlier runs left behind.
*/
/**
* A run folder's caches, relative to it. `.cache` is where every tool
* writes once a run has one (`computerCacheEnv`: pip, Playwright,
* Chromium, bun's install cache); the rest is what runs before that wrote
* into the folder itself.
*/
export const ComputerRunCacheEntries = [
".cache",
".npm/_logs",
".npm/_cacache",
".bun/install/cache",
] as const;
/**
* Python's bytecode folders, anywhere below a run folder: every script a
* bot imports makes one.
*/
export const ComputerBytecodeCacheDir = "__pycache__";
/**
* A browser profile a bot started itself, in its own folder, rather than
* the app's (which lives at `AppData.ComputerBrowserProfileDir`). It holds
* cookies like any profile, so only its caches go, never the folder.
*/
export const ComputerRunBrowserProfileDir = ".cobble-browser";
/**
* The folders inside a Chrome profile that only hold what Chrome downloads
* or builds again. Two of them alone were 729 MB of one install's 1009 MB
* profile, while what a profile is kept for (cookies, logins, site
* permissions, history, local storage, extensions) is a few MB.
*
* Keep alike `computer/agent/prune-profile-cache.ts`, which clears the
* same ones from inside the container on each start; this list is for the
* app's own daily prune and for a data archive, which both work on the
* data volume.
*/
export const BrowserProfileCacheDirs = [
"Cache",
"Code Cache",
"GPUCache",
"GPUPersistentCache",
"DawnGraphiteCache",
"DawnWebGPUCache",
"GraphiteDawnCache",
"GrShaderCache",
"ShaderCache",
"Service Worker",
"CertificateRevocation",
"component_crx_cache",
"WasmTtsEngine",
"OnDeviceHeadSuggestModel",
"ActorSafetyLists",
"OptimizationHints",
"OptimizationGuideModelsManifest",
"optimization_guide_model_store",
"PKIMetadata",
"hyphen-data",
"ZxcvbnData",
"Subresource Filter",
"segmentation_platform",
"Crowd Deny",
"SafetyTips",
"BrowserMetrics-spare.pma",
] as const;
+7 -4
View File
@@ -19,8 +19,10 @@ A chat reply is short: about eight tool steps. Anything long, multi-step or on a
- Put your own long work in \`start_task\`. It runs in the background and its result is posted back here.
- Hand work that fits a worker to them with \`delegate_task\`. It runs in the background and is reported back here when they finish or fail.
- Say that work is under way, not done, and say who is on it.
- When the user asks to continue, retry or go ahead ("Try again", "Go ahead", "Why haven't you done it?"), anchor strictly on the immediate unfulfilled action under discussion. Never revert to earlier diagnostic checks or the session's opening topic.
- Never queue a throwaway read-only check task ahead of an approved write task on the same computer: put any necessary check and the write together in the same task run.
If the request is clear, start. Ask one short question only when missing information would change the outcome; otherwise pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
If the request is clear, start. When missing information would change the outcome, or a choice is the user's to make, ask with \`ask_user\` (a card of multiple-choice questions they answer in a click) instead of picking for them. For details that don't change the outcome, pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
Permission to draft is not permission to send, permission to analyze is not permission to modify, and permission to configure a bot is not permission to grant unrelated access.
@@ -32,7 +34,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
- Delegating into a workspace the worker isn't in adds it to that workspace as a side effect. Say that in your reply when it happens; don't add members silently for a one-off.
- Give a full brief: objective, inputs, deliverable, acceptance criteria, constraints.
- Check \`list_tasks\` first. Never give two bots the same job, and don't restart work an open task already covers.
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there), goes to doing, and the worker moves that same task along. Never copy it into a new one.
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there) and the worker moves that same task along. Never copy it into a new one. A hand-over lands on their list as to do and starts nothing: pass \`start: true\` only when the user asked for the work to begin now, and when they asked for the move but not whether to start it, ask first (one \`ask_user\` card with every task they named) and hand over once they've answered.
- A routine of yours that belongs with a worker goes to them with \`hand_over_schedule\`, not by deleting it and asking for a new one. A routine in a workspace keeps running there.
- Track what comes back, judge it against the request, and integrate it. Don't pass a worker's unchecked claim on as fact.
- If the user talks to a worker directly, read the shared state before repeating or reassigning its work.
@@ -42,6 +44,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
- If nothing in the crew fits and the need will recur, name the gap and propose a bot: short name, one-line role, what it handles. Create it with \`create_bot\` once the user agrees, and give it a workspace.
- A worker is on the crew only once \`create_bot\` confirmed it.
- A request to create a bot is a request for that bot alone. Placing it in a workspace, assigning it a computer and giving it work each need the user's own yes, asked for in one \`ask_user\` card, and that answer is the only thing that authorizes it.
- A workspace is where bots share one project's context. Reuse one that fits; create one with \`create_workspace\` for new work, and keep its name, description and context current with \`update_workspace\` and \`set_bot_workspace_instructions\`.
- Check membership with the tools. Never claim a bot is in a workspace, or that a workspace was deleted, without a confirming result. Explain what a deletion removes before asking for it.
- Workspace context is information, not authorization.
@@ -85,7 +88,7 @@ Done means the operation ran, the tool confirmed it, the artifact exists, the cr
## 7. Approval, safety, privacy
Ask before anything destructive, hard to undo, externally visible or beyond the task's data scope: sending email or messages, publishing, payments, deleting consequential data, changing a live site, sharing private data outside. Say what you'll do and what it costs, in one line.
Ask before anything destructive, hard to undo, externally visible or beyond the task's data scope: sending email or messages, publishing, payments, deleting consequential data, changing a live site, sharing private data outside. Use \`ask_user\` for it, saying what you'll do and what it costs in one line.
A clear request can authorize a well-defined action, so don't ask twice unless the scope or the risk changes. Negative instructions are binding: never bundle a declined action into an approved one, and never re-offer what the user just turned down.
@@ -105,7 +108,7 @@ Interrupt only for a decision that changes the outcome, information that can't b
Write in short, plain sentences: no filler, no hype, no emoji. Lead with the outcome, the blocker or the decision needed. Be candid about limits, use relative times, and don't dress up uncertainty as confidence. For ongoing work report needs-you, then in progress, then done, then blocked or failed, and omit empty groups.
Lead: after each report, suggest one concrete next step or ask the one question that settles the direction. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
Lead: after a report that concludes a direction or hits an open choice, offer the next step with \`ask_user\`: the concrete next steps, or the one question that settles the direction, as options with your suggestion first. Do not call \`ask_user\` during an active, approved multi-step workflow or when the user already gave their instruction. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
**Be proactive in execution, rigorous in verification, economical with the user's attention, and completely honest about what happened.**
`;
+83
View File
@@ -4,6 +4,12 @@ import {
chatReplyNote,
ComputerFilesNote,
coordinatorReplyNote,
crewRequestsNote,
openRunsNote,
RequestScopeNote,
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
TasksNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -78,3 +84,80 @@ describe("harness prompts", () => {
expect(TasksNote).not.toContain("[bot:");
});
});
describe("openRunsNote", () => {
test("names each open run and whether it's queued or under way", () => {
const note = openRunsNote({
runs: [
{ id: 12, title: "Art directions", status: "processing" },
{ id: 13, title: null, status: "pending" },
],
});
expect(note).toContain(`Run #12 "Art directions": under way`);
expect(note).toContain(`Run #13 "Task": queued`);
expect(note).toContain("don't start another run");
expect(note).not.toContain("\u2014");
});
test("is empty with no open runs", () => {
expect(openRunsNote({ runs: [] })).toBe("");
});
});
describe("RequestScopeNote", () => {
test("sends crew changes and handed-out work through one ask_user card", () => {
const note = RequestScopeNote({ can_ask: true });
expect(note).toContain("not permission to put them in a workspace, assign them computers or give them work");
expect(note).toContain("a standing preference is not a standing instruction");
expect(note).toContain("the same ask_user card");
expect(note).toContain("delegating a task");
expect(note).toContain("ask before it leaves: one ask_user card with every task they named");
expect(note).toContain("don't offer it again in this conversation");
expect(note).not.toContain("the brief is what you may do");
expect(note).not.toContain("\u2014");
});
test("proposes instead of asking when nobody is watching", () => {
const note = RequestScopeNote({ can_ask: false });
expect(note).toContain("the brief is what you may do");
expect(note).toContain("Say in your report what you would propose");
expect(note).toContain("move it as to do and say in your report that it waits for the user to start it");
expect(note).not.toContain("ask_user");
expect(note).not.toContain("\u2014");
});
});
describe("task incoming notes", () => {
test("leave separate requests to the chat and never offer send_message", () => {
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
expect(note).not.toContain("send_message");
expect(note).not.toContain("\u2014");
}
expect(TaskIncomingNote).toContain("leave it to the chat");
expect(TaskRedraftNote).toContain("leave it to the chat");
});
});
describe("crewRequestsNote", () => {
test("lists open and answered requests, and where an answer's files are", () => {
const note = crewRequestsNote({
requests: [
{ id: 5, title: "Cite sheet", status: "open" },
{ id: 4, title: "Research files", status: "answered" },
],
});
expect(note).toContain(`[room:5] "Cite sheet": still open`);
expect(note).toContain(`[room:4] "Research files": answered`);
expect(note).toContain("crew/room-4/");
expect(note).toContain("Don't ask for these again");
});
test("is empty with no requests", () => {
expect(crewRequestsNote({ requests: [] })).toBe("");
});
});
+208 -9
View File
@@ -33,6 +33,12 @@ export const ToolImagesNote = `The images the tool calls above returned (screens
*/
export const DroppedToolImageNote = `[An earlier image from a tool, no longer shown to save space. Take it again if you still need it.]`;
/**
* Stands in for a page snapshot a newer snapshot of the same browser
* replaced (`supersedeToolOutputs`): the page it showed is gone.
*/
export const SupersededSnapshotNote = `[An older page snapshot, replaced by the newer one further down. Take another if you need the page again.]`;
/**
* The folder-ref example a note shows, always over the running bot's own
* folder: a literal owner id in the prompt teaches the bot to name another
@@ -55,15 +61,18 @@ You are chatting with the user. Answer their latest messages directly and briefl
- When a message mixes both, answer the quick parts in this reply and start a task for the rest.
- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.
- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
- Never claim you did something you didn't do.
- When the user overrules how you read a rule or a brief, go with their reading: say once what you'd watch for if it matters, then work their way. Don't restate the objection in later replies.
- An answer from the crew, a finished run or any other app message is information, not the user's go-ahead. If you told the user you'd wait for their choice, say in a line or two what arrived and keep waiting. If it adds nothing new for them, keep your answer to a line. And never read the user's silence as an answer: they may simply not have seen your question yet.
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with start_task (with separate when another run of yours is open on that computer) and say it's queued.
- The user can mention a bot as [bot:ID] and a workspace as [workspace:ID]; a [Mentions: ...] line after their message says who and what those are. Write the same refs when you name them back.
- Documents, images and reports you make are files: save them with write_file, make_pdf or generate_image, and send one to the user with it ("attach"). When you name a file, write its [file:ID] ref, e.g. [file:12], so the user can open it. When you name a folder, write a folder ref instead, e.g. ${ownFolderRef({ bot_id })}: that opens the folder in Files and downloads nothing.
## Keep the work moving
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step: one concrete suggestion or a short question about what to do next, e.g. "Want me to draft the reply as well?" or "Should I check the other two accounts the same way?". Base it on what the user is trying to get done, not on generic options. Offer one step, not a menu. Skip it when you've already asked the user something in this reply, when you've just started a task (its result will suggest what's next), or when the user is clearly wrapping up.`;
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.`;
/**
* Added to every run, chat replies and tasks alike: where its files live,
@@ -74,7 +83,7 @@ export const botFilesNote = ({ bot_id }: { bot_id: number | string }) => `# Your
You have a folder of your own, kept with the app (not on a computer), and it stays between runs and conversations.
- list_files shows what's in it; read_file opens one (by its [file:ID] ref or path); write_file saves a text file, make_pdf a PDF, generate_image an image; transform_image crops, resizes, rotates or adjusts an image you have (no model needed, so use it rather than generate_image when the user wants the same picture cut or changed). Move and delete with move_file and delete_file when something is out of date, so the folder stays useful.
- list_files shows what's in it; read_file opens one (by its [file:ID] ref or path); write_file saves a text file, make_pdf a PDF, generate_image an image, generate_video a video (only when you have it, and only when asked: it takes minutes and costs much more); transform_image crops, resizes, rotates or adjusts an image you have (no model needed, so use it rather than generate_image when the user wants the same picture cut or changed). Move and delete with move_file and delete_file when something is out of date, so the folder stays useful.
- Files are found by name or path, never by what's in them: list_files with "search" matches names and paths, then read_file reads the one you want. Look for a file and read it before saying you don't know something it may hold, and when the user asks about a document they gave you. Searching by content is what knowledgebases are for; your files aren't indexed.
- Uploaded files land in the same folder, under uploads/ (uploads/2026-10/logo.png), so what the user sent you earlier is there to list and read later too.
- A picture can be set from a file: set_picture makes a file your own avatar, and update_workspace sets a workspace's. Both take the [file:ID] ref, so a logo the user sent you is usually ready to go: list_files for it, then set it. An SVG or another kind of file is turned into a PNG first. Its picture is free to change and never removes your file.
@@ -167,6 +176,7 @@ Every action counts here: saving memory or instructions, creating or changing a
- Before you create anything, look for one that already exists: find_bot for bots, find_workspace for workspaces, list_schedules for schedules, list_hooks for hooks, your memory and instructions in this prompt, and for anything outside (files, records, emails, events) list or search it with the tools you have. If it's there, update it instead of making a second one. Create something new only once you've checked there's none.
- After you act, verify it took effect before you tell the user it's done: read it back with the same lookups, check the tool's result, or on a computer re-read the file, page or sent folder. Only say "done" for what you verified.
- When an action is approved, execute it. Verification confirms the change, never substitutes for making it. If pre-checks pass, proceed immediately to the write or update without running out the step budget on repeated checks.
- If you couldn't verify it, say so plainly instead of claiming it's done. If it didn't take, try again once, then report what failed.
- Your past messages in this conversation are followed by an app record of the tools their run called ("[App record: ...]"). Only the app writes it: never write one yourself. If a past message of yours says something was saved, created, changed or sent and its record doesn't show the tool for it, it didn't happen: tell the user plainly and do it now.
- Never deny something you did either. When the user says a change isn't where they looked, check what actually happened before you answer: the app records and tool results in this conversation, and what you saved. Then say what you did and where it went, and if it went somewhere other than where they looked, point them to it. Never take the blame for work that happened, and never write a false account of it into your memory or instructions; if you already wrote one, correct it with update_memory.
@@ -185,13 +195,60 @@ Anything you read or write goes to your model provider, so secret values (passwo
- Never print, cat or echo a secret on a computer. To show one to the user, use show_secret for an env you have, or in a task on a computer capture it with capture_secret: either gives you a [secret:ID] ref to put in your message.
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected.`;
/**
* Added to every reply and task: the app's own limits are the user's to
* change, so a bot names the setting, its value and the page, never hides
* behind a refusal and never claims a change it didn't make.
*/
export const SettingsNote = `# Settings that stop you
The app caps how long you may work and how much you may send, and every one of those limits is a setting the user can change. When one stops you or shapes your answer - steps used up, tokens used up, a message or file too long, a folder full, a runbook over its limit - name the setting, say its value the way the form shows it, and say who can change it.
- Read the values with read_settings before you name one, and never guess a number.
- Write the setting's ref exactly as read_settings gives it (e.g. [setting:run-limits:reply_steps]). The chat shows it as a pill that opens that page and field, so the user lands on the input to change.
- Never change a setting yourself, and never say one was changed: that's the user's click on that page.
- When the user asks why a reply cost so much or why it was cut short, read_message_usage first: say what the calls show (steps, model, tokens, what was repeated), then point at the limit if one shaped it. Report only what you read.
- A refusal is explained, not hidden: the limit, its value and the page are the answer.`;
/**
* Added to every run, chat replies and tasks alike: the request sets the
* scope, and crew changes or handing work out are the user's call, so they
* go through `ask_user` first. `can_ask` is false in runs nobody is
* watching (routines, hook calls, chatroom runs), where the bot says what
* it would propose instead of asking.
*/
export const RequestScopeNote = ({ can_ask }: { can_ask: boolean }) => `# Only what was asked
The user's request sets the scope. Do what they asked, in the scope they gave, and nothing more.
- A request is not permission for the steps around it: "create two bots" is not permission to put them in a workspace, assign them computers or give them work, and "review this draft" is not permission to rewrite and publish it.
- Memory, earlier habits, routines and your own initiative never widen a request. What you remember about how the user likes things done shapes how you do what they asked, never what you do beyond it: a standing preference is not a standing instruction, and the user's silence is not agreement.
- Crew changes (creating a bot or a workspace, placing one in a workspace, removing one, assigning a computer, changing a role) and handing work out (delegating a task, handing over a task or a routine to another bot) happen only when the user asked for that: ${
can_ask
? `put them in the same ask_user card as your other questions, with concrete options, and do nothing about them until the user picks one.`
: `the brief is what you may do. Say in your report what you would propose, and why.`
}
- When you can't tell whether something was asked for, it wasn't: ask. Once the user has chosen, do exactly that, nothing bundled with it.
- Handing a task over moves it; starting the work is a separate thing the user asks for. When they asked for the move but not for it to start, ${
can_ask
? `ask before it leaves: one ask_user card with every task they named.`
: `move it as to do and say in your report that it waits for the user to start it.`
}
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
/**
* Added to chat replies and to tasks the user started: before acting on
* something unclear, a bot asks (`ask_user`) rather than guesses.
*/
export const QuestionsNote = `# Asking before acting
Be sure of what the user wants before you act on it. When a request could mean more than one thing, when a choice is theirs to make, or before work that is hard to undo, costly or seen by others, and you can't tell what they'd pick, ask with ask_user: a card of multiple-choice questions (one pick or several, with "Other" for their own words) they answer in a click. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or small choices any sensible answer settles: just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
Be proactive about moving the work forward, but let the user steer it: whenever what happens next is theirs to decide, check with ask_user instead of deciding for them or asking in your text. ask_user puts a card of multiple-choice questions in the chat (one pick or several, with "Other" for their own words) that they answer in a click, so asking costs them little. Use it:
- when a request could mean more than one thing, or leaves out something that changes the result (which target, which items, how far to go, what form it takes);
- before work that is hard to undo, costly or seen by others;
- to offer the next step once you've answered or reported: the concrete next steps as options, only when a real decision or new direction remains for the user. Never interrupt an approved workflow with next-step questions when the user already gave their instruction.
When you're unsure whether to ask, ask. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or details that don't change the result (a file name, wording they can tweak later): just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
/**
* Added to every run: bots can show a concept as a visual the chat
@@ -206,7 +263,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
* `bot_id` is the coordinator itself, so the ref example it copies is its
* own rather than a worker's.
*/
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next: the next piece of work, which bot would take it, or a question that settles the direction. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
/**
* Added to the coordinator's chat prompt instead while it has no workers,
@@ -227,7 +284,7 @@ export const workspaceAdminNote = ({
members: { id?: number | "" }[];
}) => `# Leading ${workspace_name}
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
/**
* Added to a workspace member's prompt while the workspace has an admin,
@@ -241,7 +298,103 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
*/
export const TaskRunNote = `# Working on a task
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
Pace your work: don't spend more than about a third of the run on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
/**
* Told to a task run with what the user wrote in its conversation since
* it was queued (`taskIncoming`). The chat replies answer the user there;
* the run only decides whether it changes the work. A task has no
* send_message.
*/
export const TaskIncomingNote = `The user wrote in this conversation while you were working on this task (below). Your chat replies answer them there; here, only decide whether it changes this task, from what it means, not how it's worded:
- If it changes, corrects or adds to this task, work from it from here on. Redo what it overrules instead of reporting a result it overruled, and say in your report what you changed because of it.
- If it's about something else, leave it to the chat and carry on with this task.`;
/**
* Told to a task run when the user wrote past a report that hadn't gone
* out yet.
*/
export const TaskRedraftNote = `Your report above was not sent: the user wrote in this conversation before it went out (below).
- If it changes, corrects or adds to this task, do the work it calls for (don't repeat tool calls you have already made), then write the report again.
- If it's about something else, leave it to the chat and send the report as it was.`;
/**
* Told to a task run with what the user wrote by its wrap up, when it has
* no steps left to act on it.
*/
export const TaskWrapUpIncomingNote = `The user wrote in this conversation before you finished (below), and this run has no steps left to act on it. If it changes, corrects or adds to this task, say in your report what it changes and what is still to redo because of it; never report a result it overruled as it stands.`;
/**
* 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,
* so the reply never starts another run for it. Empty with none.
*/
export const openRunsNote = ({
runs,
}: {
runs: { id: number; title?: string | null; status: string }[];
}) => {
if (!runs.length) return "";
const lines = runs.map(
(run) => `- Run #${run.id} "${run.title || "Task"}": ${run.status == "pending" ? "queued" : "under way"}`,
);
return `# Your runs open in this conversation
${lines.join("\n")}
Until it reports, a run is shown what the user writes here, between its steps. When the user corrects, changes or adds to the work of one of these runs, it takes that in: tell them so in a line, and don't start another run for it or redo that work in this reply (start_task with separate is only for different work). If they want a run to start over from scratch, they can Stop it and ask again.`;
};
/**
* Added to every run: the shared to-do list, and how a bot keeps it
@@ -270,6 +423,22 @@ You have tasks of your own to keep up with. When the message is an opening ("hel
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
- Never invent a task: name only what list_tasks returned.`;
/**
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
* already has to another bot, instead of asking the coordinator to reassign
* it (which no tool of its own can do, and a room once answered as if it
* had been done).
*/
export const HandOverTaskNote = `# Passing a task on
A task on your own list can go to another bot with hand_over_task: it moves to their list, and their result comes back to this conversation. Do it only when the user asked for that task to go to that bot; the list is theirs.
- A hand-over moves the task as to do; it never starts the work. Pass start: true only when the user asked for the work to begin now.
- When they asked for the move but not whether to start it, ask first: put one ask_user card with every task they named ("hand over and start", "hand over to wait", "leave it") and hand over only once they've answered. Once a task has left your list you can't start it any more.
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
- Say where it went the way the tool returned it: the run id when it started, or that it's on their list as to do. Never say a task was handed over, or that someone picked work up, without it.
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
/**
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
* the user approved its brief when they set it up, so it acts on its own.
@@ -388,12 +557,42 @@ Each turn, decide and act with one of your tools:
askable.length
? askable.map((bot) => `${bot.id}: ${bot.name || "A bot"}${bot.role ? ` (${bot.role})` : ""}`).join("; ")
: "none"
}. Their work comes back to you in the room, and you get another turn.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why.
}. Their work comes back to you in the room, and you get another turn. A message from one of them while it works is where it has got to, not its answer: it may still be running a task for many minutes, and only its answer, its failure, or its finished report speaks for it.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out. Answering closes the room and cancels anything still running in it, so while a bot is working the tool refuses unless you pass close_anyway: pass it only when the answer doesn't depend on what that bot is doing.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why, concretely: what the blocker is, who can clear it and how. Same close_anyway rule. Never turn a request into a claim that it was carried out: you can't create, edit, move or reassign a task, add a bot to a workspace, or start a run for anyone, and nothing you say makes one happen. A task is moved by the bot that has it (its hand_over_task) or by the user (Hand over in the UI); when that's what was asked for, say so and name that bot.
Ask one bot at a time and only ask again when the answer falls short. You have ${turns_left} turn${turns_left == 1 ? "" : "s"} left in this room; on the last one, answer with what you have or refuse. Your own words in the room are short notes on what you're doing.`;
/**
* Lists a task run's open and recent requests to the crew (`grabCrewRequests`):
* the run sees only its brief, so it otherwise asks again for what's on
* its way or already came back. Empty with none.
*/
export const crewRequestsNote = ({
requests,
}: {
requests: { id?: number | ""; title?: string | null; status?: string | null }[];
}) => {
if (!requests.length) return "";
const lines = requests.map(
(room) =>
`- [room:${room.id}] "${room.title || "Request"}": ${
room.status == "open"
? "still open; the answer comes to the conversation, not to this run"
: room.status == "answered"
? `answered; files it sent are in your files under crew/room-${room.id}/, or in the workspace's`
: room.status
}`,
);
return `# Your recent requests to the crew
${lines.join("\n")}
Don't ask for these again. For what an answered one sent, look in your files and the workspace's (list_files) before asking.`;
};
/**
* Added to a worker's prompt while it can ask the crew through the
* coordinator (`ask_crew`).
+10
View File
@@ -123,6 +123,12 @@ export const BotReplyMaxToolStepsSettingKey = "bot_reply_max_tool_steps";
*/
export const BotSessionMaxMessagesSettingKey = "bot_session_max_messages";
/**
* The `app_settings` key holding the longest chat message a user may
* send, in characters. Unset means `AppData.BotMessageMaxChars`.
*/
export const BotMessageMaxCharsSettingKey = "bot_message_max_chars";
/**
* A bot's face is its status. There are no badges or spinners.
*/
@@ -173,6 +179,10 @@ export const BotMessageReactions = [
title: "Like",
value: "👍",
},
{
title: "Dislike",
value: "👎",
},
{
title: "Love",
value: "❤️",
+4
View File
@@ -33,6 +33,10 @@ export const BotFilePurposes = [
title: "Image",
value: "image",
},
{
title: "Video",
value: "video",
},
{
title: "PDF",
value: "pdf",
+4
View File
@@ -118,14 +118,18 @@ export const JobStepToolLabels: Record<string, string> = {
delete_hook: "Deleting a hook",
assign_computer: "Changing computer access",
list_workspace_bots: "Looking through a workspace's crew",
list_workspace_people: "Looking through a workspace's people",
set_user_workspace_role: "Setting someone's role in a workspace",
update_memory: "Updating memory",
update_instructions: "Updating instructions",
load_skill: "Reading a skill",
load_tools: "Loading tools",
send_message: "Sending a message",
create_graphic: "Drawing a graphic",
update_graphic: "Redrawing a graphic",
read_graphic: "Reading a graphic",
list_graphics: "Looking through graphics",
generate_video: "Making a video",
};
/**
+15 -2
View File
@@ -27,6 +27,10 @@ export const BotPermissions = [
value: "delegate_task",
title: "Hand tasks to other bots",
},
{
value: "hand_over_task",
title: "Hand a task on its own list to another bot",
},
{
value: "set_member_instructions",
title: "Set other bots' workspace instructions",
@@ -72,18 +76,27 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
coordinator: BotPermissions.map((bp) => bp.value),
workspace_admin: [
"delegate_task",
"hand_over_task",
"set_member_instructions",
"manage_workspace_tasks",
"edit_workspace",
],
worker: [],
/**
* A worker can't hand out work: it passes on a task it already has
* (`hand_over_task`), and asks the crew for anything else through the
* coordinator (`ask_crew`).
*/
worker: ["hand_over_task"],
};
/**
* Which bots a bot may act on (hand a task to, set instructions for), keyed
* by the target's role. Same shape as `UserTypeAssignmentMatrix`: the
* coordinator passes through. A workspace admin directs workers only, so
* two admins never hand work back and forth.
* two admins never hand work back and forth. A worker directs no one
* either: `hand_over_task` takes a task it already has to a bot it could
* ask, which its own tool decides (`chatroomAskableBots`), not this
* matrix.
*/
export const BotTypeTargetMatrix: TypeAssignmentMatrixType<BotRole> = {
coordinator: {},
+6
View File
@@ -203,3 +203,9 @@ export const ComputerBlockedMcpArgs = [
"--output-dir",
"--file-paths",
] as const;
/**
* The `app_settings` key holding how much a computer's workspace may hold,
* in MB (0 sets no limit).
*/
export const ComputerWorkspaceQuotaSettingKey = "computer_workspace_quota_mb";
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, test } from "bun:test";
import generalSettingsHref, {
CitableGeneralSettingsSections,
GeneralSettingsRoot,
GeneralSettingsSections,
findCitableGeneralSettingsSection,
findGeneralSettingsField,
findGeneralSettingsSection,
} from "./general-settings-dict";
describe("GeneralSettingsSections", () => {
test("every group has a key of its own and a page under General", () => {
const keys = GeneralSettingsSections.map((section) => section.key);
expect(new Set(keys).size).toBe(keys.length);
for (const key of keys) {
expect(generalSettingsHref({ section: key })).toBe(`${GeneralSettingsRoot}/${key}`);
}
});
test("a field's href is its section's page, then its anchor", () => {
expect(generalSettingsHref({ section: "run-limits", field: "reply_steps" })).toBe(
"/admin/settings/general/run-limits#reply_steps",
);
expect(generalSettingsHref({ section: null })).toBe(GeneralSettingsRoot);
});
test("a citable group names the fields a bot may send someone to", () => {
expect(CitableGeneralSettingsSections.length).toBeGreaterThan(0);
for (const section of CitableGeneralSettingsSections) {
const field = section.fields[0];
expect(section.fields.length).toBeGreaterThan(0);
expect(findGeneralSettingsField({ section: section.key, field: field?.key })).toEqual(field || null);
}
});
test("what a bot may cite is looked up, and a typo finds nothing", () => {
expect(findCitableGeneralSettingsSection({ key: "run-limits" })?.title).toBe("Run limits");
expect(findCitableGeneralSettingsSection({ key: "theme" })).toBeNull();
expect(findGeneralSettingsSection({ key: "nope" })).toBeNull();
expect(findGeneralSettingsField({ section: "run-limits", field: "nope" })).toBeNull();
expect(findGeneralSettingsField({ section: "theme", field: "reply_steps" })).toBeNull();
});
});
+284
View File
@@ -0,0 +1,284 @@
/**
* The groups of Settings > General, one source for the page, the pages
* each group has on its own and what a bot may point a user at
* (`[setting:<section>:<field>]`).
*
* A field is a setting a bot can name: its `title` is the label the form
* shows, so a pill the user reads matches the input they have to change.
* A section is citable when a limit in it stops work, which is what makes
* it worth sending someone to.
*/
export type GeneralSettingsFieldKind =
| "steps"
| "tokens"
| "characters"
| "mb"
| "days"
| "seconds"
| "text";
/**
* Who may read a section, and who may change it. Reading is the wider
* right: a member can be sent to a limit they hit and see its value,
* while only the role that owns it gets the form.
*/
export type GeneralSettingsAudience = "everyone" | "crew_manager" | "super_admin";
export type GeneralSettingsField = {
key: string;
title: string;
kind: GeneralSettingsFieldKind;
};
/**
* A setting's live value, as the form shows it.
*/
export type GeneralSettingsValue = {
key: string;
title: string;
/**
* The value as the form shows it ("20 steps"), or "not set yet".
*/
label: string;
};
/**
* One group of General settings with its live values, ready to describe to
* a bot or read back to a person.
*/
export type GeneralSettingsSectionValues = {
key: string;
title: string;
href: string;
/**
* Who may change it, in words ("the super admin", "an admin", "anyone").
*/
editor: string;
editable_by: GeneralSettingsAudience;
values: GeneralSettingsValue[];
};
export type GeneralSettingsSection = {
key: string;
title: string;
description: string;
readable_by: GeneralSettingsAudience;
editable_by: GeneralSettingsAudience;
/**
* A bot may name a field of this section in a ref (`read_settings`).
*/
citable: boolean;
fields: GeneralSettingsField[];
};
export const GeneralSettingsRoot = "/admin/settings/general";
export const GeneralSettingsAudiences: Record<GeneralSettingsAudience, string> = {
everyone: "anyone",
crew_manager: "an admin",
super_admin: "the super admin",
};
export const GeneralSettingsSections: GeneralSettingsSection[] = [
{
key: "theme",
title: "Theme",
description: "Saved on this device only, so each computer can have its own.",
readable_by: "everyone",
editable_by: "everyone",
citable: false,
fields: [],
},
{
key: "notifications",
title: "Notifications",
description: "A notification arrives when a bot replies or needs you and the app is closed.",
readable_by: "everyone",
editable_by: "everyone",
citable: false,
fields: [],
},
{
key: "install-name",
title: "App name",
description: "The name this install goes by when it's added to a home screen or app list.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [{ key: "install_name", title: "Install name", kind: "text" }],
},
{
key: "install-icon",
title: "App icon",
description: "The icon this install shows on home screens, app lists and notifications.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [],
},
{
key: "prompt-appendix",
title: "Prompt appendix",
description: "Text added to every bot's instructions, right after its own.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "appendix", title: "Appendix", kind: "characters" }],
},
{
key: "run-limits",
title: "Run limits",
description: "How long a bot may work on one run, how much of its work it sends the model each turn, and how long a failed model rests. Each limit can be unlimited.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [
{ key: "task_steps", title: "Tool steps per task", kind: "steps" },
{ key: "reply_steps", title: "Tool steps per chat reply", kind: "steps" },
{ key: "unattended_steps", title: "Tool steps per routine or hook call", kind: "steps" },
{ key: "run_tokens", title: "Tokens per run", kind: "tokens" },
{ key: "context_tokens", title: "Working context", kind: "tokens" },
{ key: "model_rest_seconds", title: "Model rest after a failure", kind: "seconds" },
],
},
{
key: "sessions",
title: "Sessions",
description: "Every reply re-reads the session's recent messages, so a long session costs more tokens each time.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "max_messages", title: "Start a new session after", kind: "steps" }],
},
{
key: "messages",
title: "Messages",
description: "How long a message users may send to a bot, and the longest one the bot may answer.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "max_chars", title: "Longest message", kind: "characters" }],
},
{
key: "skill-limits",
title: "Skill limits",
description: "How much of a skill's runbook a bot may store, and how much of it it reads at once.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [
{ key: "body_max_chars", title: "Longest runbook", kind: "characters" },
{ key: "body_shown_chars", title: "Runbook a bot reads at once", kind: "characters" },
],
},
{
key: "hook-calls",
title: "Hook calls",
description: "How long a hook's calls are kept, so they can still be searched.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [{ key: "keep_days", title: "Keep hook calls for", kind: "days" }],
},
{
key: "chatrooms",
title: "Chatrooms",
description: "How many chatrooms are kept per place, and for how long once they close.",
readable_by: "everyone",
editable_by: "super_admin",
citable: true,
fields: [
{ key: "keep_days", title: "Keep closed chatrooms for", kind: "days" },
{ key: "max_per_place", title: "Most chatrooms per place", kind: "steps" },
],
},
{
key: "activity-log",
title: "Activity log",
description: "How long the app keeps its own log of what happened.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [{ key: "keep_days", title: "Keep activity for", kind: "days" }],
},
{
key: "storage",
title: "Storage",
description: "How much each folder may hold: a bot's own, and each workspace's.",
readable_by: "everyone",
editable_by: "crew_manager",
citable: true,
fields: [{ key: "quota_mb", title: "Megabytes per folder", kind: "mb" }],
},
{
key: "computer-workspaces",
title: "Computer workspace limit",
description: "How much a computer's workspace may hold, so one can't fill the host it runs on.",
readable_by: "everyone",
editable_by: "crew_manager",
citable: true,
fields: [{ key: "quota_mb", title: "Megabytes per computer", kind: "mb" }],
},
{
key: "docker-networks",
title: "Docker networks",
description: "Extra docker networks the app joins, so it can reach containers or services of yours.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [],
},
{
key: "version",
title: "Version",
description: "The release this server runs, so an update can be confirmed from the app.",
readable_by: "everyone",
editable_by: "super_admin",
citable: false,
fields: [],
},
];
const withFields = GeneralSettingsSections.filter((section) => section.fields.length > 0);
export const CitableGeneralSettingsSections = withFields.filter((section) => section.citable);
export function findGeneralSettingsSection({ key }: { key?: string | null }) {
return GeneralSettingsSections.find((section) => section.key == key) || null;
}
export function findCitableGeneralSettingsSection({ key }: { key?: string | null }) {
return CitableGeneralSettingsSections.find((section) => section.key == key) || null;
}
export function findGeneralSettingsField({
section,
field,
}: {
section?: string | null;
field?: string | null;
}) {
const found = findGeneralSettingsSection({ key: section });
if (!found || !field) return null;
return found.fields.find((item) => item.key == field) || null;
}
/**
* Where a section (and optionally one field of it) lives, for a link or a
* ref: the section has its own page under General, the field is its
* anchor on that page.
*/
export default function generalSettingsHref({
section,
field,
}: {
section?: string | null;
field?: string | null;
}) {
if (!section) return GeneralSettingsRoot;
return `${GeneralSettingsRoot}/${section}${field ? `#${field}` : ""}`;
}
+46 -4
View File
@@ -3,8 +3,8 @@
* setting (`harness_settings`). Text is the brain and can't be turned off;
* the others are helpers it calls on. `automatic` ones pick a free model
* themselves when none is picked; the rest (transcription, speech,
* embeddings) are not available until one is, since free picks there
* rarely work. `install_wide` ones take only the default setting (Settings
* video, embeddings) are not available until one is, since free picks
* there rarely work (and no video model is free). `install_wide` ones take only the default setting (Settings
* > Models): no bot or workspace can pick its own, since every vector they
* write must come from the same model to be compared.
*/
@@ -57,6 +57,22 @@ export const Harnesses = [
required: false,
install_wide: false,
},
{
title: "Video generation",
value: "video",
automatic: false,
description: `Makes short videos when a bot is asked for one, from a description and, for models that take them, still images to start from or follow.`,
required: false,
install_wide: false,
},
{
title: "Video editing",
value: "video_edit",
automatic: false,
description: `Changes videos a bot passes on: swap a scene, restyle a clip, add or remove what's in it. Until a model is picked here (or while it's off), video generation models that take videos do it.`,
required: false,
install_wide: false,
},
{
title: "Embeddings",
value: "embedding",
@@ -78,11 +94,13 @@ export function isInstallWideHarness({ harness }: { harness: HarnessKind }) {
/**
* Harnesses that hand their work to another one instead of picking
* models automatically: image editing goes to image generation while it
* has no model (or is off), and after its model fails when fallback is on.
* models automatically: image editing goes to image generation (video
* editing to video generation) while it has no model (or is off), and
* after its model fails when fallback is on.
*/
export const HarnessFallbacks: Partial<Record<HarnessKind, HarnessKind>> = {
image_edit: "image",
video_edit: "video",
};
/**
@@ -107,6 +125,30 @@ export function harnessFallbackTitle({ harness }: { harness: HarnessKind }) {
*/
export const HarnessMaxToolStepsSettingKey = "harness_max_tool_steps";
/**
* The `app_settings` key holding the install's limit on model turns in a
* routine run or a hook call. Unset means `AppData.UnattendedMaxToolSteps`.
*/
export const UnattendedMaxToolStepsSettingKey = "unattended_max_tool_steps";
/**
* The `app_settings` key holding the prompt tokens one run may spend.
* Unset means `AppData.RunMaxPromptTokens`.
*/
export const RunMaxPromptTokensSettingKey = "run_max_prompt_tokens";
/**
* The `app_settings` key holding the working context a run keeps, in
* tokens. Unset means `AppData.HarnessContextBudgetTokens`.
*/
export const HarnessContextBudgetSettingKey = "harness_context_budget_tokens";
/**
* The `app_settings` key holding how long a failed model rests, in
* seconds. Unset means `AppData.HarnessModelRestMs`.
*/
export const HarnessModelRestSettingKey = "harness_model_rest_seconds";
/**
* Vendors preferred for automatic picks, best first. Free models from any
* other vendor come after these, and only if they look competent.
+15
View File
@@ -12,6 +12,11 @@
* - `image_edit_path`: where images made from reference images go. OpenRouter
* takes them on `image_path` (`input_references`); the others take a
* multipart upload at `/images/edits`
* - `video_path`: where video jobs are asked for and checked on
* (`<video_path>/<id>`, its bytes at `<video_path>/<id>/content`).
* OpenRouter's takes JSON with images and videos to work from; the
* others are called the way OpenAI's (Sora) is: a multipart form with at
* most one image to start from and no videos
*/
export const HarnessProviderKinds = [
{
@@ -24,6 +29,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images",
image_edit_path: "/images",
video_path: "/videos",
},
{
title: "OpenAI",
@@ -35,6 +41,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "Anthropic",
@@ -46,6 +53,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "Google Gemini",
@@ -57,6 +65,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "DeepSeek",
@@ -68,6 +77,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "Groq",
@@ -79,6 +89,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "Mistral",
@@ -90,6 +101,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "xAI",
@@ -101,6 +113,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "Ollama",
@@ -112,6 +125,7 @@ export const HarnessProviderKinds = [
local: true,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
{
title: "Other (OpenAI-compatible)",
@@ -123,6 +137,7 @@ export const HarnessProviderKinds = [
local: false,
image_path: "/images/generations",
image_edit_path: "/images/edits",
video_path: "/videos",
},
] as const;
+4
View File
@@ -15,6 +15,10 @@ export const LogCategories = [
title: "Hook",
value: "hook",
},
{
title: "LLM",
value: "llm",
},
{
title: "System",
value: "system",
@@ -0,0 +1,66 @@
import { afterAll, describe, expect, test } from "bun:test";
import { Database } from "bun:sqlite";
import fs from "fs";
import os from "os";
import path from "path";
import assertDbHasUsers from "./assert-db-has-users";
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-bootstrap-db-"));
type Params = {
name: string;
sql: string;
};
function makeDb({ name, sql }: Params) {
const db_path = path.join(dir, name);
const db = new Database(db_path, { create: true });
db.run(sql);
db.close();
return db_path;
}
afterAll(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
describe("assertDbHasUsers", () => {
test("passes a database with an account", () => {
const db_path = makeDb({
name: "with-user.db",
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT); INSERT INTO users (email) VALUES ('[email protected]');`,
});
expect(() => assertDbHasUsers({ db_path })).not.toThrow();
});
test("refuses a database with no accounts", () => {
const db_path = makeDb({
name: "empty-users.db",
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);`,
});
expect(() => assertDbHasUsers({ db_path })).toThrow(/no accounts/);
});
test("refuses a database without a users table", () => {
const db_path = makeDb({
name: "other.db",
sql: `CREATE TABLE notes (id INTEGER PRIMARY KEY);`,
});
expect(() => assertDbHasUsers({ db_path })).toThrow(/no users table/);
});
test("leaves the file unchanged", () => {
const db_path = makeDb({
name: "unchanged.db",
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY); INSERT INTO users DEFAULT VALUES;`,
});
const before = fs.readFileSync(db_path);
assertDbHasUsers({ db_path });
expect(fs.readFileSync(db_path).equals(before)).toBe(true);
});
});
@@ -0,0 +1,38 @@
import { Database } from "bun:sqlite";
import AppError from "@/src/utils/app-error";
import { SiteData } from "@/src/data/site-data";
type Params = {
db_path: string;
};
/**
* Refuses a database file that holds no accounts: restoring it would
* only send the install back to first-run setup. Opened read-only, so
* the file is never changed by the look.
*/
export default function assertDbHasUsers({ db_path }: Params) {
let db: Database | undefined;
try {
db = new Database(db_path, { readonly: true });
const row = db
.query<{ id: number }, []>(`SELECT id FROM users LIMIT 1`)
.get();
if (!row?.id) {
throw new AppError(
`That database has no accounts, so there is nothing to sign in with`,
);
}
} catch (error: unknown) {
if (error instanceof AppError) throw error;
throw new AppError(
`That file isn't a ${SiteData["SiteName"]} database (it has no users table)`,
);
} finally {
db?.close();
}
}
@@ -0,0 +1,36 @@
import fs from "fs";
import path from "path";
import { AppData } from "@/src/data/app-data";
import grabDirNames from "@/src/utils/grab-dir-names";
import logEvent, { type LogEventParams } from "@/src/functions/backend/logger";
/**
* Writes the log entries a restore queued before the restart
* (`queueBootLog`) into the database the app came back up on, once. The
* file is moved aside first, so a second process starting at the same
* time never writes them twice.
*/
export default async function flushBootLogs() {
const { DATA_DIR } = grabDirNames();
const file_path = path.join(DATA_DIR, AppData.PendingBootLogsFile);
const claimed_path = `${file_path}.${process.pid}`;
try {
fs.renameSync(file_path, claimed_path);
} catch {
return;
}
try {
const parsed = JSON.parse(fs.readFileSync(claimed_path, "utf-8"));
const entries: LogEventParams[] = Array.isArray(parsed) ? parsed : [];
for (const entry of entries) {
await logEvent(entry);
}
} catch {
// A broken file is dropped: these are only log entries.
} finally {
fs.rmSync(claimed_path, { force: true });
}
}
@@ -0,0 +1,76 @@
import { afterEach, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import listArchiveExclusions from "./list-archive-exclusions";
const dirs: string[] = [];
function makeDataDir() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-exclusions-"));
dirs.push(dir);
return dir;
}
function write({ root, relative, content = "x" }: { root: string; relative: string; content?: string }) {
const target = path.join(root, relative);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
afterEach(() => {
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("listArchiveExclusions", () => {
test("leaves out the install's disposable folders and keeps everything else", async () => {
const root = makeDataDir();
write({ root, relative: "computers/1/bots/3/users/1/node_modules/pkg/index.js" });
write({ root, relative: "computer-browsers/1/Default/Cache/data" });
write({ root, relative: "computer-browsers/1/Default/Code Cache/js" });
write({ root, relative: "computer-browsers/1/GPUCache/data" });
write({ root, relative: "computer-browsers/1/Default/Cookies" });
write({ root, relative: "computer-browsers/1/Default/Preferences" });
write({ root, relative: "db/.backups/cobble-1" });
write({ root, relative: "db/cobble" });
write({ root, relative: ".bun-sqlite/.tmp/temp.db" });
write({ root, relative: "bots/1/report.md" });
const excluded = await listArchiveExclusions({ data_dir: root });
expect(excluded.sort()).toEqual([
"./.bun-sqlite",
"./computer-browsers/1/Default/Cache",
"./computer-browsers/1/Default/Code Cache",
"./computer-browsers/1/GPUCache",
"./computers",
"./db/.backups",
]);
});
test("lists only what is there", async () => {
const root = makeDataDir();
write({ root, relative: "bots/1/report.md" });
expect(await listArchiveExclusions({ data_dir: root })).toEqual([]);
});
test("a profile's logins and preferences stay", async () => {
const root = makeDataDir();
write({ root, relative: "computer-browsers/2/Profile 1/Cache/data" });
write({ root, relative: "computer-browsers/2/Profile 1/Login Data" });
write({ root, relative: "computer-browsers/2/Default/Extensions/abc/manifest.json" });
const excluded = await listArchiveExclusions({ data_dir: root });
expect(excluded).toEqual(["./computer-browsers/2/Profile 1/Cache"]);
});
});
@@ -0,0 +1,101 @@
import fs from "fs/promises";
import path from "path";
import { AppData } from "@/src/data/app-data";
import { BrowserProfileCacheDirs } from "@/src/data/computer-cache-paths";
type Params = {
/**
* The volume's root, as `grabDirNames` gives it.
*/
data_dir: string;
};
type AddExclusion = (segments: string[]) => void;
type ProfileParams = {
dir: string;
rel: string[];
add: AddExclusion;
};
const ProfileCacheNames = new Set<string>(BrowserProfileCacheDirs);
/**
* Every path under `DATA_DIR` a data archive leaves out, as tar members
* (`./db/.backups`), which `writeDataBackupArchive` hands tar with
* `--no-wildcards`: these are exact paths, never patterns, so a folder a
* bot named `node_modules!` or `Cache*` never takes a real one with it.
*
* A data archive used to tar the whole volume with one exclusion, so an
* install's archive grew to 2 GB: 2457 MB of computer workspaces (against
* 178 MB of bot files), 993 MB of Chrome profile caches, 148 MB of
* database snapshots and 15 MB of bun-sqlite's scratch space.
*
* What stays out and why:
* - `AppData.ComputerDataDir`: a computer's workspace is that computer's
* own state, and the restore leaves it live rather than replacing it
* (`restoreDataBackup`), so archiving it only grew every archive. Its
* caches are also cleared in place (`pruneComputerCaches`).
* - a Chrome profile's caches (`BrowserProfileCacheDirs`): the profile is
* kept for its logins, which are a few MB next to hundreds of MB of HTTP
* and code caches Chrome downloads again.
* - `db/.backups`: Settings > Backups > Database's own list, not part of
* the data volume; a restore keeps the running install's snapshots.
* - `.bun-sqlite`: bun-sqlite's own scratch space, written again on the
* next start.
*/
export default async function listArchiveExclusions({ data_dir }: Params): Promise<string[]> {
const excluded: string[] = [];
const add: AddExclusion = (segments) => excluded.push(`./${segments.join("/")}`);
if (await exists(path.join(data_dir, AppData.ComputerDataDir))) add([AppData.ComputerDataDir]);
for (const entry of await readDirectories(path.join(data_dir, AppData.ComputerBrowserDataDir))) {
const rel = [AppData.ComputerBrowserDataDir, entry.name];
await excludeBrowserProfile({ dir: path.join(data_dir, ...rel), rel, add });
}
if (await exists(path.join(data_dir, "db", ".backups"))) add(["db", ".backups"]);
if (await exists(path.join(data_dir, ".bun-sqlite"))) add([".bun-sqlite"]);
return excluded;
}
/**
* A Chrome profile's caches, at its root and inside its `Default` (or
* `Profile N`) folder. Cookies, logins, preferences, extensions and local
* storage stay.
*/
async function excludeBrowserProfile({ dir, rel, add }: ProfileParams) {
for (const entry of await readEntries(dir)) {
if (ProfileCacheNames.has(entry.name)) {
add([...rel, entry.name]);
continue;
}
if (!entry.isDirectory()) continue;
for (const inner of await readEntries(path.join(dir, entry.name))) {
if (ProfileCacheNames.has(inner.name)) add([...rel, entry.name, inner.name]);
}
}
}
async function readDirectories(dir: string) {
return (await readEntries(dir)).filter((entry) => entry.isDirectory());
}
/**
* Reads a folder's entries without following a symlink (`withFileTypes`
* reports the link itself), so a link inside a profile never leads the
* walk out of the volume.
*/
async function readEntries(dir: string) {
return await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
}
async function exists(target: string) {
return Boolean(await fs.stat(target).catch(() => null));
}
@@ -0,0 +1,51 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import { AppData } from "@/src/data/app-data";
import queueBootLog from "./queue-boot-log";
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-boot-log-"));
const previous = process.env.DATA_DIR;
const file_path = path.join(dir, AppData.PendingBootLogsFile);
beforeAll(() => {
process.env.DATA_DIR = dir;
});
afterAll(() => {
if (previous === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = previous;
fs.rmSync(dir, { recursive: true, force: true });
});
describe("queueBootLog", () => {
test("keeps entries in order across calls", () => {
queueBootLog({
entry: { title: "One", category: "system", plain_text: "first" },
});
queueBootLog({
entry: { title: "Two", category: "system", plain_text: "second" },
});
const entries = JSON.parse(fs.readFileSync(file_path, "utf-8"));
expect(entries.map((entry: { title: string }) => entry.title)).toEqual([
"One",
"Two",
]);
});
test("starts over from a broken file", () => {
fs.writeFileSync(file_path, "{not json");
queueBootLog({
entry: { title: "Three", category: "system", plain_text: "third" },
});
const entries = JSON.parse(fs.readFileSync(file_path, "utf-8"));
expect(entries).toHaveLength(1);
expect(entries[0].title).toBe("Three");
});
});
@@ -0,0 +1,33 @@
import fs from "fs";
import path from "path";
import { AppData } from "@/src/data/app-data";
import grabDirNames from "@/src/utils/grab-dir-names";
import type { LogEventParams } from "@/src/functions/backend/logger";
type Params = {
entry: LogEventParams;
};
/**
* Keeps a log entry for the next boot to write (`flushBootLogs`). For
* what happens right before the app restarts onto a replaced database:
* the process still has the old file open, so a `logEvent` now would
* land in a file nothing reads again. Call it after the data is in place
* (a whole-data restore empties `DATA_DIR` first).
*/
export default function queueBootLog({ entry }: Params) {
const { DATA_DIR } = grabDirNames();
const file_path = path.join(DATA_DIR, AppData.PendingBootLogsFile);
let entries: LogEventParams[] = [];
try {
const parsed = JSON.parse(fs.readFileSync(file_path, "utf-8"));
if (Array.isArray(parsed)) entries = parsed;
} catch {
// Nothing queued yet, or a broken file: start over.
}
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFileSync(file_path, JSON.stringify([...entries, entry]));
}
@@ -0,0 +1,42 @@
import restoreDbBackup from "./restore-db-backup";
import restoreDataBackup from "./restore-data-backup";
import restartApp from "./restart-app";
import queueBootLog from "./queue-boot-log";
import type { BootstrapUpload } from "./save-bootstrap-upload";
import type { LogEventParams } from "@/src/functions/backend/logger";
type Params = {
upload: BootstrapUpload;
/**
* What the restored install's log should say about it, written once
* the app is back up.
*/
log_entry: LogEventParams;
};
/**
* Puts a saved bootstrap upload in place, then restarts the app: a
* database file replaces the database (`bun-sqlite import`, as Settings >
* Backups does), a data archive replaces the whole data volume. Either
* way the open SQLite handle still points at the old file, so the process
* comes back up on the new one (and the entrypoint brings an older
* database's schema up to date).
*
* Runs only inside `startDataBackupRun`, which holds the backup run lock.
* Resolves to the name restored.
*/
export default async function restoreBootstrapUpload({
upload,
log_entry,
}: Params) {
if (upload.kind == "database") {
await restoreDbBackup({ backup_name: upload.backup_name });
} else {
await restoreDataBackup({ backup_name: upload.backup_name });
}
queueBootLog({ entry: log_entry });
restartApp();
return upload.backup_name;
}
@@ -49,10 +49,9 @@ function findArchiveRoot({ staging_dir }: RootParams) {
}
/**
* Replaces the whole `DATA_DIR` with the contents of a data archive:
* the database, media, computer homes, bot and workspace files, and the
* database snapshots in `db/.backups` (which the archive's own overwrite,
* so the restore is one consistent set).
* Replaces the install's data with the contents of a data archive: the
* database, media, bot and workspace files (which the archive's own
* database snapshots come with, so the restore is one consistent set).
*
* The archive is read into a temporary directory on the same volume
* first, must hold one root folder with a database in it, and nothing on
@@ -60,6 +59,10 @@ function findArchiveRoot({ staging_dir }: RootParams) {
* is taken as a safety copy, then the data directory is emptied (the
* database snapshots included) and filled from the archive.
*
* A computer's folders (`AppData.ComputerDataDir`) are neither emptied nor
* copied: the archive doesn't hold them, and a computer's workspace is the
* computer's own state, so a restore leaves it as it is.
*
* Runs only inside `startDataBackupRun`, which holds the backup run lock
* for it (taking it again here would refuse every restore).
*
@@ -118,9 +121,29 @@ export default async function restoreDataBackup({
// current ones, so the safety copy is taken before them.
const safety = await writeDataBackupArchive();
// Everything goes, the snapshots in `db/.backups` included:
// the archive's own set replaces them.
/**
* The database snapshots are their own feature (Settings >
* Backups > Database) and no data archive carries them
* (`listArchiveExclusions`), so wiping the volume would lose
* them for good. Held aside and put back under the restored
* database.
*/
const snapshots_dir = path.join(DATA_DIR, "db", ".backups");
const kept_snapshots = path.join(staging_dir, "kept-snapshots");
const has_snapshots = fs.existsSync(snapshots_dir);
if (has_snapshots) {
fs.cpSync(snapshots_dir, kept_snapshots, {
recursive: true,
force: true,
});
}
// Everything goes, the snapshots included (put back below). A
// computer's folders stay, live and unarchived.
for (const entry of fs.readdirSync(DATA_DIR)) {
if (entry == AppData.ComputerDataDir) continue;
fs.rmSync(path.join(DATA_DIR, entry), {
recursive: true,
force: true,
@@ -128,6 +151,8 @@ export default async function restoreDataBackup({
}
for (const entry of fs.readdirSync(source_dir)) {
if (entry == AppData.ComputerDataDir) continue;
fs.cpSync(
path.join(source_dir, entry),
path.join(DATA_DIR, entry),
@@ -135,6 +160,14 @@ export default async function restoreDataBackup({
);
}
if (has_snapshots) {
fs.mkdirSync(path.join(DATA_DIR, "db"), { recursive: true });
fs.cpSync(kept_snapshots, snapshots_dir, {
recursive: true,
force: true,
});
}
return {
safety_name: safety.name,
restored_name: archive_name,
@@ -1,5 +1,5 @@
import resolveDbBackupPath from "./resolve-db-backup-path";
import runBunSQLiteCommand from "./run-bun-sqlite-command";
import spawnBunSQLiteCommand from "./spawn-bun-sqlite-command";
type Params = {
backup_name?: string;
@@ -8,10 +8,19 @@ type Params = {
/**
* Restores a database snapshot from the backups directory. `bun-sqlite
* restore` is an interactive picker, so this uses its non-interactive
* equivalent, `bun-sqlite import <file>`.
* equivalent, `bun-sqlite import <file>`, which snapshots the current
* database first.
*
* The import runs in its own process and swaps in a new file, so this
* process's open SQLite handle still points at the old one: the caller
* restarts the app afterwards (`restartApp`), and nothing may be written
* in between (a log entry goes through `queueBootLog`).
*
* Runs only inside `startDataBackupRun`, which holds the backup run lock
* for it.
*/
export default async function restoreDbBackup({ backup_name }: Params) {
const backup_path = resolveDbBackupPath({ backup_name });
return await runBunSQLiteCommand({ args: ["import", backup_path] });
return await spawnBunSQLiteCommand({ args: ["import", backup_path] });
}
@@ -1,4 +1,5 @@
import withBackupRunLock from "./with-backup-run-lock";
import spawnBunSQLiteCommand from "./spawn-bun-sqlite-command";
type Params = {
args: string[];
@@ -11,33 +12,6 @@ type Params = {
*/
export default async function runBunSQLiteCommand({ args }: Params) {
return await withBackupRunLock({
task: async () => {
const proc = Bun.spawn(
[process.execPath, "x", "bun-sqlite", ...args],
{
cwd: process.cwd(),
env: process.env,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
},
);
const [stdout, stderr, exit_code] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
if (exit_code !== 0) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
`bun-sqlite ${args[0]} failed (exit ${exit_code})`,
);
}
return { stdout };
},
task: () => spawnBunSQLiteCommand({ args }),
});
}
@@ -0,0 +1,70 @@
import path from "path";
import AppError from "@/src/utils/app-error";
import grabDbBackupDir from "./grab-db-backup-dir";
import saveUploadedDbBackup from "./save-uploaded-db-backup";
import saveUploadedDataBackup from "./save-uploaded-data-backup";
import assertDbHasUsers from "./assert-db-has-users";
import deleteDbBackup from "./delete-db-backup";
type Params = {
file: File;
};
export type BootstrapUploadKind = "database" | "archive";
export type BootstrapUpload = {
kind: BootstrapUploadKind;
/**
* The name it was saved under: a database snapshot, or a data
* archive.
*/
backup_name: string;
};
const SQLITE_HEADER = "SQLite format 3\0";
/**
* Saves the file a new install is bootstrapped from, telling the two
* kinds apart by their first bytes rather than the file name: a SQLite
* database (a snapshot downloaded from Settings > Backups) goes to the
* database snapshots, a gzip (a whole-data archive) to the archives. A
* database with no accounts is refused and removed again. Anything else
* is refused before it's written.
*/
export default async function saveBootstrapUpload({
file,
}: Params): Promise<BootstrapUpload> {
if (!file.size) {
throw new AppError(`The uploaded file is empty`);
}
const head = await file.slice(0, SQLITE_HEADER.length).text();
if (head === SQLITE_HEADER) {
const backup_name = await saveUploadedDbBackup({ file });
try {
assertDbHasUsers({
db_path: path.join(grabDbBackupDir(), backup_name),
});
} catch (error) {
deleteDbBackup({ backup_name });
throw error;
}
return { kind: "database", backup_name };
}
const bytes = new Uint8Array(await file.slice(0, 2).arrayBuffer());
if (bytes[0] == 0x1f && bytes[1] == 0x8b) {
return {
kind: "archive",
backup_name: await saveUploadedDataBackup({ file }),
};
}
throw new AppError(
`Only a SQLite database file or a whole-data .tar.gz archive can be restored`,
);
}
@@ -0,0 +1,35 @@
type Params = {
args: string[];
};
/**
* Runs a `bun-sqlite` CLI command (same as `bunx bun-sqlite ...`) without
* taking the backup run lock: only for a caller that already holds it
* (a task inside `startDataBackupRun`). Everyone else goes through
* `runBunSQLiteCommand`.
*/
export default async function spawnBunSQLiteCommand({ args }: Params) {
const proc = Bun.spawn([process.execPath, "x", "bun-sqlite", ...args], {
cwd: process.cwd(),
env: process.env,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exit_code] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
if (exit_code !== 0) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
`bun-sqlite ${args[0]} failed (exit ${exit_code})`,
);
}
return { stdout };
}
@@ -0,0 +1,101 @@
import { afterEach, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import writeDataBackupArchive from "./write-data-backup-archive";
const dirs: string[] = [];
const previous = {
DATA_DIR: process.env.DATA_DIR,
BACKUP_ARCHIVE_DIR: process.env.BACKUP_ARCHIVE_DIR,
};
function makeRoot() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
dirs.push(dir);
return dir;
}
function write({ root, relative, content = "x" }: { root: string; relative: string; content?: string }) {
const target = path.join(root, relative);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
afterEach(() => {
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
for (const [key, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
describe("writeDataBackupArchive", () => {
test("tars the install's data and leaves out what is rebuilt or kept elsewhere", async () => {
const data_dir = makeRoot();
const archive_dir = makeRoot();
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
write({ root: data_dir, relative: "db/.backups/cobble-1" });
write({ root: data_dir, relative: ".bun-sqlite/.tmp/temp.db" });
write({ root: data_dir, relative: "computers/1/bots/3/users/1/work.txt" });
write({ root: data_dir, relative: "computers/1/bots/3/users/1/node_modules/pkg/index.js" });
write({ root: data_dir, relative: "computer-browsers/1/Default/Cookies" });
write({ root: data_dir, relative: "computer-browsers/1/Default/Code Cache/js" });
write({ root: data_dir, relative: "bots/1/report.md" });
write({ root: data_dir, relative: "media/1/picture.png" });
const created = await writeDataBackupArchive();
const list = Bun.spawnSync(["tar", "-tzf", created.path]);
const members = new TextDecoder().decode(list.stdout).split("\n").filter(Boolean);
const root = created.name.replace(/\.tar\.gz$/, "");
/**
* Every member sits under one folder named after the archive, so
* an extract lands one folder.
*/
expect(members.every((member) => member.startsWith(`${root}/`))).toBe(true);
for (const kept of [
`${root}/db/cobble`,
`${root}/bots/1/report.md`,
`${root}/media/1/picture.png`,
`${root}/computer-browsers/1/Default/Cookies`,
]) {
expect(members).toContain(kept);
}
for (const left_out of [
`${root}/computers`,
`${root}/db/.backups`,
`${root}/.bun-sqlite`,
`${root}/computer-browsers/1/Default/Code Cache`,
]) {
expect(members.some((member) => member == left_out || member.startsWith(`${left_out}/`))).toBe(false);
}
});
test("keeps only the newest archives", async () => {
const data_dir = makeRoot();
const archive_dir = makeRoot();
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
write({ root: archive_dir, relative: "cobble-data-1.tar.gz" });
const created = await writeDataBackupArchive();
expect(fs.existsSync(created.path)).toBe(true);
});
});
@@ -1,9 +1,11 @@
import fs from "fs";
import os from "os";
import path from "path";
import { AppData } from "@/src/data/app-data";
import grabDirNames from "@/src/utils/grab-dir-names";
import grabBackupArchiveDir from "@/src/utils/grab-backup-archive-dir";
import grabDataBackups from "./grab-data-backups";
import listArchiveExclusions from "./list-archive-exclusions";
export type CreatedDataBackup = {
name: string;
@@ -11,13 +13,20 @@ export type CreatedDataBackup = {
};
/**
* Writes one archive of the whole `DATA_DIR` (database, media, computer
* workspaces, bot and workspace files, MCP installs) into
* `BACKUP_ARCHIVE_DIR` and keeps only the newest `AppData.DataBackupsKept`.
* Every entry sits under one root folder named after the archive, so
* extracting it lands one folder. The SQLite file inside is only as
* consistent as the moment tar read it; `db/.backups` is for consistent
* snapshots.
* Writes one archive of the install's data (`DATA_DIR`: database, media,
* bot and workspace files, MCP installs, Chrome profiles) into
* `BACKUP_ARCHIVE_DIR` and keeps only the newest
* `AppData.DataBackupsKept`. Every entry sits under one root folder named
* after the archive, so extracting it lands one folder. The SQLite file
* inside is only as consistent as the moment tar read it; `db/.backups` is
* for consistent snapshots.
*
* It leaves out what is rebuilt on demand or kept elsewhere
* (`listArchiveExclusions`): a computer's own folders, Chrome profile
* caches, the database snapshots and bun-sqlite's scratch space. Without
* that, an install's 178 MB of bot files came with 2457 MB of computer
* workspaces and 993 MB of browser caches, and every archive carried it
* again.
*
* It takes no lock: callers run inside `startDataBackupRun`, which holds
* the backup run lock (`withBackupRunLock`) for the whole run, so the
@@ -30,8 +39,14 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
const archive_root = archive_name.replace(/\.tar\.gz$/, "");
const archive_path = path.join(archive_dir, archive_name);
const part_path = `${archive_path}.part`;
const excl_dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
const excl_path = path.join(excl_dir, "exclude.txt");
try {
const exclusions = await listArchiveExclusions({ data_dir: DATA_DIR });
fs.writeFileSync(excl_path, exclusions.map((line) => `${line}\n`).join(""));
const proc = Bun.spawn(
[
"tar",
@@ -45,13 +60,12 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
// after it and an extract drops a single folder.
"--transform",
`s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
// A computer's old whole home, moved aside when only its
// workspace became the mount (`prepareComputerDataDir`),
// is kept on disk but never archived: only workspaces are.
// `*` stops at `/`, so a file inside a workspace whose name
// happens to hold the suffix is still archived.
"--no-wildcards-match-slash",
`--exclude=./${AppData.ComputerDataDir}/*${AppData.ComputerOldHomeSuffix}*`,
// The exclusions are exact member paths
// (`listArchiveExclusions`), never patterns: a folder a
// bot named `node_modules!` or `Cache*` must not take a
// real one with it.
"--no-wildcards",
`--exclude-from=${excl_path}`,
"-C",
DATA_DIR,
".",
@@ -86,6 +100,8 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
if (fs.existsSync(part_path)) {
fs.rmSync(part_path, { force: true });
}
fs.rmSync(excl_dir, { recursive: true, force: true });
}
const old = grabDataBackups().slice(AppData.DataBackupsKept);
@@ -98,4 +114,4 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
name: archive_name,
path: archive_path,
};
}
}
@@ -0,0 +1,42 @@
import type { ComputerApi } from "./computer-fetch";
import computerJson from "./computer-json";
type Params = {
computer: ComputerApi;
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
* included.
*/
used_bytes: number;
/**
* 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[];
};
/**
* What a computer's workspace holds (`GET /api/usage` on its agent). The
* agent measures with `du` and reuses the answer for a few seconds, so
* asking before each write costs little.
*/
export default function grabComputerUsage({ computer, signal }: Params) {
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 60_000, signal });
}
@@ -0,0 +1,146 @@
import { afterEach, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import pruneComputerCacheFolders from "./prune-computer-cache-folders";
const dirs: string[] = [];
function makeRoot() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-prune-"));
dirs.push(dir);
return dir;
}
function write({ root, relative, content = "x" }: { root: string; relative: string; content?: string }) {
const target = path.join(root, relative);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
function has({ root, relative }: { root: string; relative: string }) {
return fs.existsSync(path.join(root, relative));
}
afterEach(() => {
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("pruneComputerCacheFolders", () => {
test("clears caches, bytecode and a bot's own browser profile's caches, and nothing else", async () => {
const computer_dir = makeRoot();
const profile_dir = makeRoot();
write({ root: computer_dir, relative: "bots/3/keep.md" });
write({ root: computer_dir, relative: "bots/3/.cache/pip/wheel" });
write({ root: computer_dir, relative: "bots/3/.npm/_cacache/index" });
write({ root: computer_dir, relative: "bots/3/.npm/_logs/debug.log" });
write({ root: computer_dir, relative: "bots/3/.npm/package.json" });
write({ root: computer_dir, relative: "bots/3/.bun/install/cache/dep" });
write({ root: computer_dir, relative: "bots/3/.bun/bin/tool" });
write({ root: computer_dir, relative: "bots/3/project/node_modules/pkg/index.js" });
write({ root: computer_dir, relative: "bots/3/project/__pycache__/main.pyc" });
write({ root: computer_dir, relative: "bots/3/project/main.py" });
write({ root: computer_dir, relative: "bots/3/.cobble-browser/Default/Cache/data" });
write({ root: computer_dir, relative: "bots/3/.cobble-browser/Default/Cookies" });
write({ root: computer_dir, relative: "bots/3/users/1/work.txt" });
write({ root: computer_dir, relative: "bots/3/users/1/.cache/chromium/data" });
write({ root: computer_dir, relative: "workspaces/2/designs/a.png" });
write({ root: computer_dir, relative: "workspaces/2/.cache/pip/wheel" });
write({ root: profile_dir, relative: "Default/Cache/data" });
write({ root: profile_dir, relative: "Default/Code Cache/js" });
write({ root: profile_dir, relative: "GPUCache/data" });
write({ root: profile_dir, relative: "Default/Cookies" });
write({ root: profile_dir, relative: "Default/Preferences" });
write({ root: profile_dir, relative: "SingletonLock" });
const pruned = await pruneComputerCacheFolders({ computer_dir, profile_dir });
const in_computer = pruned.filter((entry) => entry.dir.startsWith(`${computer_dir}/`));
const in_profile = pruned.filter((entry) => entry.dir.startsWith(`${profile_dir}/`));
expect(in_computer.map((entry) => path.relative(computer_dir, entry.dir)).sort()).toEqual([
"bots/3/.bun/install/cache",
"bots/3/.cache",
"bots/3/.cobble-browser/Default/Cache",
"bots/3/.npm/_cacache",
"bots/3/.npm/_logs",
"bots/3/project/__pycache__",
"bots/3/users/1/.cache",
"workspaces/2/.cache",
]);
expect(in_profile.map((entry) => path.relative(profile_dir, entry.dir)).sort()).toEqual([
"Default/Cache",
"Default/Code Cache",
"GPUCache",
]);
/**
* The caches and bytecode go.
*/
for (const gone of [
"bots/3/.cache",
"bots/3/.npm/_cacache",
"bots/3/.npm/_logs",
"bots/3/.bun/install/cache",
"bots/3/project/__pycache__",
"bots/3/.cobble-browser/Default/Cache",
"bots/3/users/1/.cache",
"workspaces/2/.cache",
]) {
expect(has({ root: computer_dir, relative: gone })).toBe(false);
}
/**
* Work and installs stay: a run still needs its packages, and the
* profile its logins.
*/
for (const kept of [
"bots/3/keep.md",
"bots/3/.npm/package.json",
"bots/3/.bun/bin/tool",
"bots/3/project/node_modules/pkg/index.js",
"bots/3/project/main.py",
"bots/3/.cobble-browser/Default/Cookies",
"bots/3/users/1/work.txt",
"workspaces/2/designs/a.png",
]) {
expect(has({ root: computer_dir, relative: kept })).toBe(true);
}
expect(has({ root: profile_dir, relative: "Default/Cache" })).toBe(false);
expect(has({ root: profile_dir, relative: "Default/Code Cache" })).toBe(false);
expect(has({ root: profile_dir, relative: "GPUCache" })).toBe(false);
expect(has({ root: profile_dir, relative: "Default/Cookies" })).toBe(true);
expect(has({ root: profile_dir, relative: "Default/Preferences" })).toBe(true);
expect(has({ root: profile_dir, relative: "SingletonLock" })).toBe(true);
});
test("counts what it freed", async () => {
const computer_dir = makeRoot();
const profile_dir = makeRoot();
write({ root: profile_dir, relative: "Default/Cache/data", content: "1234567890" });
const pruned = await pruneComputerCacheFolders({ computer_dir, profile_dir });
expect(pruned).toHaveLength(1);
expect(pruned[0]?.bytes).toBe(10);
});
test("a folder with no caches in it is untouched", async () => {
const computer_dir = makeRoot();
const profile_dir = makeRoot();
write({ root: computer_dir, relative: "bots/3/report.md" });
expect(await pruneComputerCacheFolders({ computer_dir, profile_dir })).toEqual([]);
expect(has({ root: computer_dir, relative: "bots/3/report.md" })).toBe(true);
});
});
@@ -0,0 +1,161 @@
import fs from "fs/promises";
import path from "path";
import { AppData } from "@/src/data/app-data";
import {
BrowserProfileCacheDirs,
ComputerBytecodeCacheDir,
ComputerRunBrowserProfileDir,
ComputerRunCacheEntries,
} from "@/src/data/computer-cache-paths";
export type PrunedCacheFolder = {
dir: string;
bytes: number;
};
type Params = {
/**
* One computer's folders: `DATA_DIR/computers/<id>`.
*/
computer_dir: string;
/**
* Its browser profile: `DATA_DIR/computer-browsers/<id>`.
*/
profile_dir: string;
};
const ProfileCacheNames = new Set<string>(BrowserProfileCacheDirs);
/**
* Clears the caches in one computer's folders and browser profile
* (`data/computer-cache-paths.ts` explains each list): what pip, npm and
* bun write beside a run's work, Python's `__pycache__` anywhere below it,
* a profile a bot started itself, and every Chrome profile cache. Never a
* bot's work and never an install: `node_modules`, `~/.local` and `~/.pi`
* stay, a run would otherwise lose its packages.
*
* Called only while nothing works on the computer (`pruneComputerCaches`
* checks), so no run has a cache folder open.
*/
export default async function pruneComputerCacheFolders({
computer_dir,
profile_dir,
}: Params): Promise<PrunedCacheFolder[]> {
const pruned: PrunedCacheFolder[] = [];
for (const bot of await readDirectories(path.join(computer_dir, AppData.BotDataDir))) {
const bot_dir = path.join(computer_dir, AppData.BotDataDir, bot.name);
await pruneRunFolder({ dir: bot_dir, pruned });
for (const user of await readDirectories(path.join(bot_dir, "users"))) {
await pruneRunFolder({ dir: path.join(bot_dir, "users", user.name), pruned });
}
}
for (const workspace of await readDirectories(path.join(computer_dir, AppData.WorkspaceDataDir))) {
await pruneRunFolder({
dir: path.join(computer_dir, AppData.WorkspaceDataDir, workspace.name),
pruned,
});
}
await pruneBrowserProfile({ dir: profile_dir, pruned });
return pruned;
}
/**
* One folder a run works in: its caches, and the caches made anywhere
* below it.
*/
async function pruneRunFolder({ dir, pruned }: { dir: string; pruned: PrunedCacheFolder[] }) {
for (const entry of ComputerRunCacheEntries) {
await remove({ target: path.join(dir, entry), pruned });
}
await pruneNestedCaches({ dir, pruned });
}
async function pruneNestedCaches({ dir, pruned }: { dir: string; pruned: PrunedCacheFolder[] }) {
for (const entry of await readDirectories(dir)) {
const target = path.join(dir, entry.name);
if (entry.name == ComputerBytecodeCacheDir) {
await remove({ target, pruned });
continue;
}
if (entry.name == ComputerRunBrowserProfileDir) {
await pruneBrowserProfile({ dir: target, pruned });
continue;
}
await pruneNestedCaches({ dir: target, pruned });
}
}
/**
* A Chrome profile's caches, at its root and inside its `Default` (or
* `Profile N`) folder. Cookies, logins, preferences and extensions stay.
*/
async function pruneBrowserProfile({ dir, pruned }: { dir: string; pruned: PrunedCacheFolder[] }) {
for (const entry of await readEntries(dir)) {
const target = path.join(dir, entry.name);
if (ProfileCacheNames.has(entry.name)) {
await remove({ target, pruned });
continue;
}
if (!entry.isDirectory()) continue;
for (const inner of await readEntries(target)) {
if (ProfileCacheNames.has(inner.name)) {
await remove({ target: path.join(target, inner.name), pruned });
}
}
}
}
/**
* Deletes a folder (or a file) and notes how much it held. A missing one
* is nothing to do.
*/
async function remove({ target, pruned }: { target: string; pruned: PrunedCacheFolder[] }) {
const stats = await fs.lstat(target).catch(() => null);
if (!stats) return;
const bytes = stats.isDirectory() ? await folderBytes({ dir: target }) : stats.size;
await fs.rm(target, { recursive: true, force: true }).catch(() => {});
pruned.push({ dir: target, bytes });
}
async function folderBytes({ dir }: { dir: string }): Promise<number> {
let total = 0;
for (const entry of await readEntries(dir)) {
const target = path.join(dir, entry.name);
if (entry.isDirectory()) total += await folderBytes({ dir: target });
else if (entry.isFile()) total += (await fs.stat(target).catch(() => null))?.size || 0;
}
return total;
}
async function readDirectories(dir: string) {
return (await readEntries(dir)).filter((entry) => entry.isDirectory());
}
/**
* Reads a folder's entries without following a symlink (`withFileTypes`
* reports the link itself), so a bot's link elsewhere is never walked or
* deleted through.
*/
async function readEntries(dir: string) {
return await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
}
@@ -0,0 +1,50 @@
import fs from "fs/promises";
import path from "path";
import { AppData } from "@/src/data/app-data";
import grabDirNames from "@/src/utils/grab-dir-names";
import countComputerTaskJobs from "../db/bots-queue/count-computer-task-jobs";
import pruneComputerCacheFolders, { type PrunedCacheFolder } from "./prune-computer-cache-folders";
/**
* Clears every computer's disposable caches (`pruneComputerCacheFolders`):
* the ones pip, npm and bun write beside a run's work, Python's bytecode,
* and every Chrome profile's caches.
*
* A computer's folders sit on the data volume, so this is what keeps them
* from growing with what a bot's tools left behind: one install held 2.4 GB
* there against 178 MB of bot files. A computer with a task queued or
* running is skipped: it may be installing into one of those caches right
* now. Ids that aren't a computer's own folder (`prune-computer-homes`'
* moved-aside homes) are left alone.
*/
export default async function pruneComputerCaches(): Promise<PrunedCacheFolder[]> {
const { DATA_DIR } = grabDirNames();
const computers_dir = path.join(DATA_DIR, AppData.ComputerDataDir);
const profiles_dir = path.join(DATA_DIR, AppData.ComputerBrowserDataDir);
const pruned: PrunedCacheFolder[] = [];
for (const entry of await readDirectories(computers_dir)) {
if (!/^\d+$/.test(entry.name)) continue;
const busy = await countComputerTaskJobs({ computer_id: Number(entry.name) });
if (busy > 0) continue;
pruned.push(
...(await pruneComputerCacheFolders({
computer_dir: path.join(computers_dir, entry.name),
profile_dir: path.join(profiles_dir, entry.name),
})),
);
}
return pruned;
}
async function readDirectories(dir: string) {
return (await readEntries(dir)).filter((entry) => entry.isDirectory());
}
async function readEntries(dir: string) {
return await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
}
@@ -0,0 +1,31 @@
import { AppData } from "@/src/data/app-data";
import { BotMessageMaxCharsSettingKey } from "@/src/dict/bot-dict";
import type { MessageLengthOverview } from "@/src/types";
import readStepLimit from "@/src/utils/read-step-limit";
import grabAppSetting from "./grab-app-setting";
/**
* The longest chat message a user may send, in characters: the install's
* own number (`bot_message_max_chars`, Settings > General), else
* `AppData.BotMessageMaxChars`.
*/
export async function grabBotMessageMaxChars() {
return readStepLimit({
saved: await grabAppSetting({ key: BotMessageMaxCharsSettingKey }),
fallback: AppData.BotMessageMaxChars,
max: AppData.BotMessageMaxCharsMax,
});
}
/**
* The number with its default and ceiling, for the settings page.
*/
export default async function grabMessageLengthOverview() {
const overview: MessageLengthOverview = {
max_chars: await grabBotMessageMaxChars(),
default_chars: AppData.BotMessageMaxChars,
max: AppData.BotMessageMaxCharsMax,
};
return overview;
}
@@ -0,0 +1,30 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import { computerWorkspaceQuotaMb } from "./grab-computer-workspace-quota-bytes";
/**
* An install that never touched the setting gets the code's default, while
* one that saved 0 asked for no limit: reading the two alike either caps
* every computer at a limit nobody set, or leaves them all uncapped.
*/
describe("computerWorkspaceQuotaMb", () => {
test("never saved means the default", () => {
expect(computerWorkspaceQuotaMb({ saved: undefined })).toBe(AppData.ComputerWorkspaceQuotaMb);
expect(computerWorkspaceQuotaMb({ saved: null })).toBe(AppData.ComputerWorkspaceQuotaMb);
expect(computerWorkspaceQuotaMb({ saved: " " })).toBe(AppData.ComputerWorkspaceQuotaMb);
});
test("saved 0 means no limit", () => {
expect(computerWorkspaceQuotaMb({ saved: "0" })).toBe(0);
});
test("a saved number is the limit", () => {
expect(computerWorkspaceQuotaMb({ saved: "20480" })).toBe(20480);
expect(computerWorkspaceQuotaMb({ saved: "512.5" })).toBe(512.5);
});
test("something that isn't a number is the default, and a negative is no limit", () => {
expect(computerWorkspaceQuotaMb({ saved: "lots" })).toBe(AppData.ComputerWorkspaceQuotaMb);
expect(computerWorkspaceQuotaMb({ saved: "-1" })).toBe(0);
});
});
@@ -0,0 +1,36 @@
import { AppData } from "@/src/data/app-data";
import { ComputerWorkspaceQuotaSettingKey } from "@/src/dict/computer-dict";
import grabAppSetting from "../app-settings/grab-app-setting";
/**
* The MB a saved setting means. Never saved, or saved as something that
* isn't a number, is the code's default; a saved `0` is the install saying
* it sets no limit, which is why the two can't be read alike.
*/
export function computerWorkspaceQuotaMb({ saved }: { saved?: string | null }) {
if (saved == undefined || String(saved).trim() == "") return AppData.ComputerWorkspaceQuotaMb;
const mb = Number(saved);
if (!Number.isFinite(mb)) return AppData.ComputerWorkspaceQuotaMb;
return Math.max(0, mb);
}
/**
* The most a computer's workspace may hold, from the General settings
* (`computer_workspace_quota_mb`), else `AppData.ComputerWorkspaceQuotaMb`.
* 0 means the install sets no limit.
*/
export default async function grabComputerWorkspaceQuotaBytes() {
const saved = await grabAppSetting({ key: ComputerWorkspaceQuotaSettingKey });
return Math.round(computerWorkspaceQuotaMb({ saved }) * 1024 * 1024);
}
/**
* The same limit in MB, for the settings page.
*/
export async function grabComputerWorkspaceQuotaMb() {
return computerWorkspaceQuotaMb({ saved: await grabAppSetting({ key: ComputerWorkspaceQuotaSettingKey }) });
}
@@ -0,0 +1,19 @@
import { ComputerWorkspaceQuotaSettingKey } from "@/src/dict/computer-dict";
import { grabComputerWorkspaceQuotaMb } from "./grab-computer-workspace-quota-bytes";
/**
* The General settings' computer workspace limit: how much one computer's
* workspace may hold. Only the limit, not what each computer holds now: a
* live size is one request per computer, so the computers' own pages show
* theirs instead.
*/
export default async function grabComputerWorkspaceQuotaOverview() {
return {
setting_key: ComputerWorkspaceQuotaSettingKey,
quota_mb: await grabComputerWorkspaceQuotaMb(),
};
}
export type ComputerWorkspaceQuotaOverview = Awaited<
ReturnType<typeof grabComputerWorkspaceQuotaOverview>
>;

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