Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6532abc715 | ||
|
|
be4eb13a7c | ||
|
|
86d171729f | ||
|
|
38648fc083 | ||
|
|
6414d4e675 | ||
|
|
ae64ef195d | ||
|
|
06a4b7bb36 | ||
|
|
2c8023ee4b | ||
|
|
c0e79ee39c | ||
|
|
bc9739509c | ||
|
|
4d6c330954 |
@@ -95,11 +95,11 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images/PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **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`.
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
@@ -115,7 +115,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
@@ -127,7 +127,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
|
||||
|
||||
### Chatrooms (`chatrooms`)
|
||||
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions; their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
|
||||
### Workspaces
|
||||
|
||||
@@ -141,7 +141,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
|
||||
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: `--disable-gpu`, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at `LightweightFrameRate` fps), extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Chrome reads only one `--disable-features=`/`--enable-features=`, so `browserArgs` merges the agent's with the extra flags' (`mergeFeatureFlags`). Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
|
||||
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
|
||||
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
|
||||
- **Folders:** a run works only in `bots/<bot>/users/<user>` (cwd, `HOME`), `bots/<bot>` and `workspaces/<workspace>` (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`), and Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
|
||||
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
|
||||
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
|
||||
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
|
||||
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
|
||||
@@ -210,7 +210,8 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`), trims old tool output to fit context. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **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.
|
||||
|
||||
+8
-2
@@ -55,7 +55,13 @@ commands. Every worker bot works as its own account, `cb-<bot id>` (uid and
|
||||
gid `100000 + id`, no sudo), made by the agent the first time the app acts
|
||||
for it (`run_as`). Its folder `bots/<id>` is its own (`2770`), and a
|
||||
workspace's folder `workspaces/<id>` (root's) belongs to the group `cw-<id>`
|
||||
its bots join. `gem`, and so Chrome, can't open either: the app passes a
|
||||
its bots join. A worker works through its home: `/home/cb-<id>/workspace`
|
||||
is a link to `bots/<id>` (the only part of its home that's kept, since the
|
||||
home itself lives in the container), its users' folders are `users/<user>`
|
||||
in it, and in a workspace `workspaces/<workspace id>` in it is a link to
|
||||
that workspace's folder. The agent checks both links on every request for
|
||||
the worker and puts back one that's gone (whatever sits in its place is
|
||||
moved aside). `gem`, and so Chrome, can't open either: the app passes a
|
||||
worker's uploads, downloads and files saved by name through a folder of the
|
||||
call's own, copied by the worker's account (`sudo -u`), and a worker can't
|
||||
open `file:` URLs. Its env files live in its own home.
|
||||
@@ -116,7 +122,7 @@ tag; the release workflow builds a tag once (a dispatch with
|
||||
bun run build:computer # builds AppData.ComputerImage for this machine
|
||||
docker run -d --name cobble-computer-dev --shm-size 2g \
|
||||
--security-opt seccomp=unconfined --cap-add NET_ADMIN -p 8170:8080 \
|
||||
ghcr.io/moduletrace/cobble-computer:1.2.0
|
||||
ghcr.io/moduletrace/cobble-computer:1.3.0
|
||||
```
|
||||
|
||||
A computer run by hand like that has no token, so anyone who reaches its port
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { chmod, chown, mkdir, stat } from "node:fs/promises";
|
||||
import { chmod, chown, lstat, mkdir, readlink, rename, stat, symlink, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { AgentConfig } from "./config";
|
||||
import commandArgv from "./command-argv";
|
||||
import log from "./log";
|
||||
import type { RunUser } from "./run-user-for";
|
||||
|
||||
@@ -20,19 +21,28 @@ let queue: Promise<unknown> = Promise.resolve();
|
||||
* Makes a worker's account and, in a workspace, its group (idempotent,
|
||||
* one at a time), and hands it its folders: its home (private), the bot's
|
||||
* folder (its own) and the workspace's (its group's). Neither gem nor any
|
||||
* other worker can read them; the coordinator, as gem, uses sudo.
|
||||
* other worker can read them; the coordinator, as gem, uses sudo. Then,
|
||||
* on every call, makes sure of the links the worker works through
|
||||
* (`keepLinks`): only the bot's folder is kept, so a write through a link
|
||||
* that's gone would land somewhere a recreate wipes.
|
||||
*/
|
||||
export default function ensureRunUser({ run_user }: { run_user: RunUser }) {
|
||||
export default async function ensureRunUser({ run_user }: { run_user: RunUser }) {
|
||||
const key = `${run_user.uid}:${run_user.workspace?.gid || 0}`;
|
||||
|
||||
if (ready.has(key)) return Promise.resolve();
|
||||
if (!ready.has(key)) {
|
||||
await serially(async () => {
|
||||
if (ready.has(key)) return;
|
||||
|
||||
const next = queue.then(async () => {
|
||||
if (ready.has(key)) return;
|
||||
await setUp({ run_user });
|
||||
ready.add(key);
|
||||
});
|
||||
}
|
||||
|
||||
await setUp({ run_user });
|
||||
ready.add(key);
|
||||
});
|
||||
if (!(await linksInPlace({ run_user }))) await serially(() => keepLinks({ run_user }));
|
||||
}
|
||||
|
||||
function serially(work: () => Promise<void>) {
|
||||
const next = queue.then(work);
|
||||
|
||||
queue = next.catch(() => {});
|
||||
|
||||
@@ -71,6 +81,65 @@ async function setUp({ run_user }: { run_user: RunUser }) {
|
||||
* bots share it through the group.
|
||||
*/
|
||||
if (workspace) await shareFolder({ dir: workspace.dir, uid: 0, gid: workspace.gid });
|
||||
|
||||
await keepLinks({ run_user });
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the worker's links lead where they should: `workspace` in its
|
||||
* home to the bot's folder, and in a workspace, `workspaces/<id>` in the
|
||||
* bot's folder to the workspace's shared one. Only reads.
|
||||
*/
|
||||
async function linksInPlace({ run_user }: { run_user: RunUser }) {
|
||||
if (!(await isLinkTo({ link: run_user.kept_dir, target: run_user.bot_dir }))) return false;
|
||||
|
||||
return !run_user.workspace || isLinkTo({ link: run_user.workspace.link, target: run_user.workspace.dir });
|
||||
}
|
||||
|
||||
async function isLinkTo({ link, target }: { link: string; target: string }) {
|
||||
const info = await lstat(link).catch(() => null);
|
||||
|
||||
return !!info?.isSymbolicLink() && (await readlink(link).catch(() => "")) == target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the worker's links back where they're missing or lead elsewhere.
|
||||
* Whatever else sits in a link's place is moved aside, never deleted.
|
||||
* The home's link is made as root (the home is a real folder in root's
|
||||
* /home, so nothing in its path is the worker's to swap); the shared
|
||||
* folder's, inside the bot's folder (the worker's own), by the worker's
|
||||
* account, so a link it left there can't send root anywhere.
|
||||
*/
|
||||
async function keepLinks({ run_user }: { run_user: RunUser }) {
|
||||
const { kept_dir, bot_dir, workspace } = run_user;
|
||||
|
||||
if (!(await isLinkTo({ link: kept_dir, target: bot_dir }))) {
|
||||
const info = await lstat(kept_dir).catch(() => null);
|
||||
|
||||
if (info?.isSymbolicLink()) await unlink(kept_dir);
|
||||
else if (info) await rename(kept_dir, `${kept_dir}.before-${Date.now()}`);
|
||||
|
||||
await symlink(bot_dir, kept_dir);
|
||||
}
|
||||
|
||||
if (workspace && !(await isLinkTo({ link: workspace.link, target: workspace.dir }))) {
|
||||
const link = quoted({ text: workspace.link });
|
||||
const target = quoted({ text: workspace.dir });
|
||||
const argv = commandArgv({
|
||||
command: [
|
||||
`umask 007`,
|
||||
`mkdir -p "$(dirname ${link})"`,
|
||||
`if [ -L ${link} ]; then ln -sfn ${target} ${link}; elif [ -e ${link} ]; then mv ${link} ${link}.before-$(date +%s) && ln -s ${target} ${link}; else ln -s ${target} ${link}; fi`,
|
||||
].join(" && "),
|
||||
as: { uid: run_user.uid, gid: run_user.gid },
|
||||
});
|
||||
|
||||
await run(argv.file, argv.args, { cwd: "/", timeout: 30_000 });
|
||||
}
|
||||
}
|
||||
|
||||
function quoted({ text }: { text: string }) {
|
||||
return `'${text.replaceAll("'", `'\\''`)}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,7 @@ describe("runUserFor", () => {
|
||||
uid: 100_007,
|
||||
gid: 100_007,
|
||||
home: "/home/cb-7",
|
||||
kept_dir: "/home/cb-7/workspace",
|
||||
bot_dir: "/home/gem/workspace/bots/7",
|
||||
workspace: null,
|
||||
});
|
||||
@@ -18,6 +19,7 @@ describe("runUserFor", () => {
|
||||
name: "cw-12",
|
||||
gid: 10_000_012,
|
||||
dir: "/home/gem/workspace/workspaces/12",
|
||||
link: "/home/gem/workspace/bots/3/workspaces/12",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,21 +9,28 @@ export type RunUser = {
|
||||
* Its home, in the container (the env files live there).
|
||||
*/
|
||||
home: string;
|
||||
/**
|
||||
* `workspace` in its home: a link to `bot_dir`, the only part of its
|
||||
* home that's kept. The app names every worker path through it.
|
||||
*/
|
||||
kept_dir: string;
|
||||
/**
|
||||
* The bot's folder in the workspace, owned by the account.
|
||||
*/
|
||||
bot_dir: string;
|
||||
/**
|
||||
* The workspace the run is in: its shared folder belongs to this group,
|
||||
* which the account joins.
|
||||
* which the account joins, and `link` (`workspaces/<id>` in the bot's
|
||||
* folder) leads to it.
|
||||
*/
|
||||
workspace: { name: string; gid: number; dir: string } | null;
|
||||
workspace: { name: string; gid: number; dir: string; link: string } | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The account a worker bot's commands run as on this computer
|
||||
* (`cb-<bot id>`, no sudo) and, in a workspace, the group its bots share
|
||||
* (`cw-<id>`). Throws for an id that isn't a whole number in range.
|
||||
* (`cw-<id>`). Keep alike the app's `computerWorkerAccount` and
|
||||
* `computerRunDirs`. Throws for an id that isn't a whole number in range.
|
||||
*/
|
||||
export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown; workspace_id?: unknown }): RunUser {
|
||||
const bot = runId({ value: bot_id });
|
||||
@@ -38,18 +45,22 @@ export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown;
|
||||
|
||||
const id = AgentConfig.WorkerIdBase + bot;
|
||||
const name = `cb-${bot}`;
|
||||
const home = `/home/${name}`;
|
||||
const bot_dir = path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot));
|
||||
|
||||
return {
|
||||
name,
|
||||
uid: id,
|
||||
gid: id,
|
||||
home: `/home/${name}`,
|
||||
bot_dir: path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot)),
|
||||
home,
|
||||
kept_dir: path.posix.join(home, "workspace"),
|
||||
bot_dir,
|
||||
workspace: workspace
|
||||
? {
|
||||
name: `cw-${workspace}`,
|
||||
gid: AgentConfig.WorkspaceGroupBase + workspace,
|
||||
dir: path.posix.join(AgentConfig.WorkspaceDir, "workspaces", String(workspace)),
|
||||
link: path.posix.join(bot_dir, "workspaces", String(workspace)),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
|
||||
@@ -4289,6 +4289,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`,
|
||||
|
||||
@@ -2638,6 +2638,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
|
||||
*/
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.14.2",
|
||||
"version": "0.16.0",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -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" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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(", ")}.` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
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";
|
||||
@@ -108,6 +108,7 @@ export default async function runBotReply({
|
||||
const history = await grabBotMessages({
|
||||
session_id,
|
||||
limit: AppData.BotReplyHistoryMessages,
|
||||
user_id,
|
||||
});
|
||||
|
||||
const answered_id = await grabAnsweredMessageId({ session_id });
|
||||
@@ -425,6 +426,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,
|
||||
|
||||
@@ -18,7 +18,12 @@ import {
|
||||
AskCrewNote,
|
||||
WorkspaceLearningNote,
|
||||
} 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";
|
||||
@@ -79,6 +84,7 @@ export default async function runBotTask({
|
||||
user_id,
|
||||
job,
|
||||
params,
|
||||
computer_shared,
|
||||
signal,
|
||||
report,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
@@ -97,6 +103,7 @@ export default async function runBotTask({
|
||||
const computer = job.computer_id
|
||||
? await openComputerTools({
|
||||
computer_id: job.computer_id,
|
||||
browser: !computer_shared,
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
workspace_id,
|
||||
@@ -324,9 +331,13 @@ export default async function runBotTask({
|
||||
|
||||
/**
|
||||
* The install's limit, or less when the brief's writer set a
|
||||
* budget (`start_task` `max_steps`).
|
||||
* budget (`start_task` `max_steps`). A routine run or a hook call,
|
||||
* which nobody watches, gets the smaller unattended limit (never
|
||||
* more than a task's).
|
||||
*/
|
||||
const install_steps = await grabHarnessMaxToolSteps();
|
||||
const task_steps = await grabHarnessMaxToolSteps();
|
||||
const install_steps =
|
||||
scheduled || hooked ? Math.min(task_steps, await grabUnattendedMaxToolSteps()) : task_steps;
|
||||
const budget = Math.floor(Number(params.max_steps) || 0);
|
||||
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
|
||||
|
||||
@@ -335,8 +346,8 @@ export default async function runBotTask({
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
budget > 0
|
||||
? `This run has at most ${max_steps} steps (model turns), set when it was queued. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
budget > 0 || scheduled || hooked
|
||||
? `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
: "",
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
@@ -358,7 +369,9 @@ export default async function runBotTask({
|
||||
? ""
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
|
||||
powers.is_coordinator || hooked ? "" : AskCrewNote,
|
||||
computer
|
||||
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.`
|
||||
@@ -394,6 +407,8 @@ export default async function runBotTask({
|
||||
],
|
||||
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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { FilePreviewKind } from "@/src/utils/file-preview-kind";
|
||||
import FilePreviewNotice from "./file-preview-notice";
|
||||
import ImageViewer from "./image-viewer";
|
||||
import FilePreviewText from "./file-preview-text";
|
||||
|
||||
type Props = {
|
||||
@@ -13,7 +13,8 @@ type Props = {
|
||||
|
||||
/**
|
||||
* The preview itself, by kind. Media the browser draws itself (images,
|
||||
* PDFs, audio, video) load from the file's URL; text kinds are read into
|
||||
* PDFs, audio, video) load from the file's URL, an image in a viewer with
|
||||
* zoom and fits (`ImageViewer`); text kinds are read into
|
||||
* the page (`FilePreviewText`). Nothing here runs the file: an SVG shows
|
||||
* through `<img>`, which runs no script, and an HTML page in a frame
|
||||
* sandboxed twice (the attribute here and the `sandbox` CSP the media
|
||||
@@ -22,11 +23,7 @@ type Props = {
|
||||
*/
|
||||
export default function FilePreviewBody({ kind, name, url, size }: Props) {
|
||||
if (kind == "image") {
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full items-center justify-center p-4 overflow-auto bg-sunken">
|
||||
<Img src={url} alt={name} className="max-w-full max-h-full object-contain" />
|
||||
</Stack>
|
||||
);
|
||||
return <ImageViewer url={url} name={name} />;
|
||||
}
|
||||
|
||||
if (kind == "pdf") {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import type { FilePreviewItem } from "@/src/types";
|
||||
import isPlainClick from "@/src/utils/is-plain-click";
|
||||
import FilePreviewModal from "./file-preview-modal";
|
||||
|
||||
@@ -8,6 +9,11 @@ type Props = {
|
||||
url: string;
|
||||
media_type?: string | null;
|
||||
size?: number;
|
||||
/**
|
||||
* The images it sits among (`imagePreviewGallery`), for Previous and
|
||||
* Next in the preview.
|
||||
*/
|
||||
gallery?: FilePreviewItem[];
|
||||
title?: string;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
@@ -18,7 +24,7 @@ type Props = {
|
||||
* plain click. It stays a real link to the bytes, so a middle click or
|
||||
* Ctrl/Cmd click still opens the file in a new tab.
|
||||
*/
|
||||
export default function FilePreviewLink({ name, url, media_type, size, title, className, children }: Props) {
|
||||
export default function FilePreviewLink({ name, url, media_type, size, gallery, title, className, children }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
@@ -44,6 +50,7 @@ export default function FilePreviewLink({ name, url, media_type, size, title, cl
|
||||
url={url}
|
||||
media_type={media_type}
|
||||
size={size}
|
||||
gallery={gallery}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
@@ -5,15 +6,27 @@ import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Download, SquareArrowOutUpRight } from "lucide-react";
|
||||
import useGalleryKeys from "@/src/hooks/use-gallery-keys";
|
||||
import usePreloadImages from "@/src/hooks/use-preload-images";
|
||||
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
|
||||
import type { FilePreviewItem } from "@/src/types";
|
||||
import filePreviewKind from "@/src/utils/file-preview-kind";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import galleryIndex from "@/src/utils/gallery-index";
|
||||
import FilePreviewBody from "./file-preview-body";
|
||||
import FilePreviewStepper from "./file-preview-stepper";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
url: string;
|
||||
media_type?: string | null;
|
||||
size?: number;
|
||||
/**
|
||||
* The images it was opened among (a folder's, a message's). When the
|
||||
* file is one of them, Previous and Next (and the arrow keys) step
|
||||
* through them without closing the preview.
|
||||
*/
|
||||
gallery?: FilePreviewItem[];
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
@@ -24,16 +37,29 @@ const ActionClassName =
|
||||
* A file over the page: markdown rendered, a CSV as a table, an image,
|
||||
* PDF, audio or video in place, other text as code, with ways to download
|
||||
* it or open it in a new tab. A file it can't show offers those only.
|
||||
* Opened from a gallery, it steps through its images; each one opens fresh
|
||||
* (fitted, scrolled to the top), and its neighbours load ahead.
|
||||
*/
|
||||
export default function FilePreviewModal({
|
||||
name,
|
||||
url,
|
||||
media_type,
|
||||
size,
|
||||
onClose,
|
||||
}: Props) {
|
||||
export default function FilePreviewModal({ gallery, onClose, ...opened }: Props) {
|
||||
const [index, set_index] = useState(() => galleryIndex({ gallery, url: opened.url }));
|
||||
const stepping = Boolean(gallery && index >= 0 && gallery.length > 1);
|
||||
const shown: FilePreviewItem = (stepping && gallery?.[index]) || opened;
|
||||
const { name, url, media_type, size } = shown;
|
||||
const kind = filePreviewKind({ name, media_type });
|
||||
const base_name = name.split("/").pop() || name;
|
||||
const count = gallery?.length || 0;
|
||||
const step = ({ by }: { by: number }) =>
|
||||
set_index((current) => Math.min(count - 1, Math.max(0, current + by)));
|
||||
|
||||
useTopModalEscape({ onClose });
|
||||
useGalleryKeys({
|
||||
enabled: stepping,
|
||||
onPrevious: () => step({ by: -1 }),
|
||||
onNext: () => step({ by: 1 }),
|
||||
});
|
||||
usePreloadImages({
|
||||
urls: stepping ? [gallery?.[index + 1]?.url || "", gallery?.[index - 1]?.url || ""] : [],
|
||||
});
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -57,6 +83,14 @@ export default function FilePreviewModal({
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
{stepping ? (
|
||||
<FilePreviewStepper
|
||||
index={index}
|
||||
count={count}
|
||||
onPrevious={() => step({ by: -1 })}
|
||||
onNext={() => step({ by: 1 })}
|
||||
/>
|
||||
) : null}
|
||||
<Link
|
||||
href={url}
|
||||
download={base_name}
|
||||
@@ -78,6 +112,7 @@ export default function FilePreviewModal({
|
||||
</Link>
|
||||
</Row>
|
||||
<FilePreviewBody
|
||||
key={url}
|
||||
kind={kind}
|
||||
name={base_name}
|
||||
url={url}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import RowIconButton from "./row-icon-button";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* The shown file's place in the gallery, from 0.
|
||||
*/
|
||||
index: number;
|
||||
count: number;
|
||||
onPrevious: () => void;
|
||||
onNext: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Previous and Next through a preview's gallery (the images of a folder or
|
||||
* a message), with where the shown one stands: "3 of 12". The arrow keys
|
||||
* do the same.
|
||||
*/
|
||||
export default function FilePreviewStepper({ index, count, onPrevious, onNext }: Props) {
|
||||
return (
|
||||
<Row className="shrink-0 gap-0! flex-nowrap items-center">
|
||||
<RowIconButton
|
||||
icon={ChevronLeft}
|
||||
title="Previous image (Left arrow)"
|
||||
disabled={index <= 0}
|
||||
onClick={onPrevious}
|
||||
/>
|
||||
<Span className="min-w-16 text-center text-[13px] leading-[18px] tabular-nums text-ink-secondary">
|
||||
{`${index + 1} of ${count}`}
|
||||
</Span>
|
||||
<RowIconButton
|
||||
icon={ChevronRight}
|
||||
title="Next image (Right arrow)"
|
||||
disabled={index >= count - 1}
|
||||
onClick={onNext}
|
||||
/>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import FilePreviewBody from "./file-preview-body";
|
||||
import FilePreviewLink from "./file-preview-link";
|
||||
import FilePreviewMarkdown from "./file-preview-markdown";
|
||||
import FilePreviewTable from "./file-preview-table";
|
||||
import FilePreviewStepper from "./file-preview-stepper";
|
||||
import FolderPreviewLink from "./folder-preview-link";
|
||||
|
||||
test("a markdown file renders as a document, raw HTML left out", () => {
|
||||
const html = renderToString(
|
||||
@@ -51,3 +53,36 @@ test("a file link stays a real link to the bytes until clicked", () => {
|
||||
expect(html).toContain('href="/media/9"');
|
||||
expect(html).toContain("Preview report.md");
|
||||
});
|
||||
|
||||
test("an image opens in the viewer, with its zoom and fit controls", () => {
|
||||
const html = renderToString(<FilePreviewBody kind="image" name="page.png" url="/media/5" />);
|
||||
|
||||
expect(html).toContain('src="/media/5"');
|
||||
expect(html).toContain("Zoom in (+)");
|
||||
expect(html).toContain("Zoom out (-)");
|
||||
expect(html).toContain("Fit width");
|
||||
expect(html).toContain("Actual size");
|
||||
});
|
||||
|
||||
test("a folder link stays a real link to the files browser until clicked", () => {
|
||||
const html = renderToString(
|
||||
<FolderPreviewLink spec={{ volume: "bots", owner_id: 3 }} path="reports" href="/admin/files?volume=bots&owner=3&path=reports" title="Open reports">
|
||||
reports
|
||||
</FolderPreviewLink>,
|
||||
);
|
||||
|
||||
expect(html).toContain('href="/admin/files?volume=bots&owner=3&path=reports"');
|
||||
expect(html).toContain("Open reports");
|
||||
});
|
||||
|
||||
test("a gallery's stepper says where the image stands and stops at the ends", () => {
|
||||
const first = renderToString(<FilePreviewStepper index={0} count={3} onPrevious={() => {}} onNext={() => {}} />);
|
||||
const last = renderToString(<FilePreviewStepper index={2} count={3} onPrevious={() => {}} onNext={() => {}} />);
|
||||
|
||||
expect(first).toContain("1 of 3");
|
||||
expect(first).toContain("Previous image");
|
||||
expect(first).toContain("Next image");
|
||||
expect(last).toContain("3 of 3");
|
||||
expect((first.match(/disabled=""/g) || []).length).toBe(1);
|
||||
expect((last.match(/disabled=""/g) || []).length).toBe(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import isPlainClick from "@/src/utils/is-plain-click";
|
||||
import type { StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import FolderPreviewModal from "./folder-preview-modal";
|
||||
|
||||
type Props = {
|
||||
spec: StorageSpec;
|
||||
path: string;
|
||||
/**
|
||||
* The folder in the files browser, where a modified click goes.
|
||||
*/
|
||||
href: string;
|
||||
title?: string;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* A link to a folder that opens it over the page (`FolderPreviewModal`) on
|
||||
* a plain click. It stays a real link to the files browser, so a middle
|
||||
* click or Ctrl/Cmd click still opens the folder there in a new tab.
|
||||
*/
|
||||
export default function FolderPreviewLink({ spec, path, href, title, className, children }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Link
|
||||
href={href}
|
||||
title={title}
|
||||
onClick={(event) => {
|
||||
if (!isPlainClick({ event })) return;
|
||||
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
}}
|
||||
className={className}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
{open ? <FolderPreviewModal spec={spec} path={path} onClose={() => setOpen(false)} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { SquareArrowOutUpRight } from "lucide-react";
|
||||
import useDebouncedValue from "@/src/hooks/use-debounced-value";
|
||||
import useStorageFolder from "@/src/hooks/use-storage-folder";
|
||||
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
|
||||
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
|
||||
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
|
||||
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import FilesBreadcrumbRow from "./files-breadcrumb-row";
|
||||
import FilesSearchInput from "./files-search-input";
|
||||
import StorageEntryRow from "./storage-entry-row";
|
||||
|
||||
type Props = {
|
||||
spec: StorageSpec;
|
||||
/**
|
||||
* The folder it opens on, inside the volume (empty at the top).
|
||||
*/
|
||||
path: string;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* A folder over the page, as the files browser shows it: its entries,
|
||||
* the trail back up and a search by name. A folder inside opens in place,
|
||||
* a file opens in its own preview over this one (an image stepping
|
||||
* through the folder's other images), and "Open in Files" goes
|
||||
* to the same folder in the files browser. The listing loads through the
|
||||
* files browser's API, so the same access rules hold.
|
||||
*/
|
||||
export default function FolderPreviewModal({ spec, path: start_path, onClose }: Props) {
|
||||
const [path, set_path] = useState(start_path);
|
||||
const [search, set_search] = useState("");
|
||||
const query = useDebouncedValue({ value: search.trim() });
|
||||
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
|
||||
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
|
||||
|
||||
const gallery = useMemo(
|
||||
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
|
||||
[folder],
|
||||
);
|
||||
|
||||
useTopModalEscape({ onClose });
|
||||
|
||||
const openFolder = (next_path: string) => {
|
||||
set_path(next_path);
|
||||
set_search("");
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
setOpen={(next_open) => {
|
||||
if (!next_open) onClose();
|
||||
}}
|
||||
className="max-w-3xl! w-[95vw] h-[85vh] p-0 bg-paper flex flex-col overflow-hidden"
|
||||
>
|
||||
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
<H2
|
||||
title={path || name}
|
||||
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
|
||||
>
|
||||
{name}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{folderSummary({ folder })}
|
||||
</Span>
|
||||
</Stack>
|
||||
<Link
|
||||
href={storageSpecHref({ spec, path })}
|
||||
title="Open this folder in Files"
|
||||
className="shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline"
|
||||
>
|
||||
<SquareArrowOutUpRight size={16} aria-hidden />
|
||||
<Span className="hidden sm:inline">Open in Files</Span>
|
||||
</Link>
|
||||
</Row>
|
||||
<Stack className="w-full gap-0! items-stretch px-5">
|
||||
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
|
||||
<FilesSearchInput value={search} onChange={set_search} />
|
||||
</Stack>
|
||||
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
|
||||
{folder?.entries.length ? (
|
||||
folder.entries.map((entry) => (
|
||||
<StorageEntryRow
|
||||
key={entry.path}
|
||||
entry={entry}
|
||||
selected={entry.kind == "folder" && entry.path == path}
|
||||
gallery={gallery}
|
||||
onOpenFolder={openFolder}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{emptyFolderText({ folder, search, loading, error })}
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export type ImageViewerTool = {
|
||||
id: string;
|
||||
icon: LucideIcon;
|
||||
/**
|
||||
* What it does, with its key, for the tooltip and screen readers.
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* Shown beside the icon on wider screens; icon only without one.
|
||||
*/
|
||||
label?: string;
|
||||
pressed?: boolean;
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One control on the image preview's toolbar: a zoom, or a preset that
|
||||
* shows as pressed while it is the one in use.
|
||||
*/
|
||||
export default function ImageViewerToolButton({ icon: Icon, title, label, pressed, disabled, onClick }: ImageViewerTool) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
title={title}
|
||||
aria-label={title}
|
||||
aria-pressed={pressed}
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className={twMerge("gap-1.5! text-ink-secondary hover:text-ink", pressed && "bg-ink/5 text-ink")}
|
||||
>
|
||||
<Icon size={16} aria-hidden />
|
||||
{label ? <Span className="hidden sm:inline text-[13px] leading-[18px]">{label}</Span> : null}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { MoveHorizontal, Scan, Shrink, ZoomIn, ZoomOut } from "lucide-react";
|
||||
import {
|
||||
ImageViewerMaxScale,
|
||||
ImageViewerMinScale,
|
||||
type ImageViewerMode,
|
||||
} from "@/src/dict/image-viewer-dict";
|
||||
import ImageViewerToolButton, { type ImageViewerTool } from "./image-viewer-tool-button";
|
||||
|
||||
type Props = {
|
||||
mode: ImageViewerMode;
|
||||
scale: number;
|
||||
natural: { width: number; height: number } | null;
|
||||
onZoom: (direction: "in" | "out") => void;
|
||||
onChoose: (mode: Exclude<ImageViewerMode, "custom">) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The image preview's controls: zoom out and in around the zoom level,
|
||||
* the presets (whole, the frame's width, actual size), and the picture's
|
||||
* own size in pixels.
|
||||
*/
|
||||
export default function ImageViewerToolbar({ mode, scale, natural, onZoom, onChoose }: Props) {
|
||||
const loaded = Boolean(natural);
|
||||
const zoom_out: ImageViewerTool = {
|
||||
id: "out",
|
||||
icon: ZoomOut,
|
||||
title: "Zoom out (-)",
|
||||
disabled: !loaded || scale <= ImageViewerMinScale,
|
||||
onClick: () => onZoom("out"),
|
||||
};
|
||||
const zoom_in: ImageViewerTool = {
|
||||
id: "in",
|
||||
icon: ZoomIn,
|
||||
title: "Zoom in (+)",
|
||||
disabled: !loaded || scale >= ImageViewerMaxScale,
|
||||
onClick: () => onZoom("in"),
|
||||
};
|
||||
const preset_tools: ImageViewerTool[] = [
|
||||
{
|
||||
id: "fit",
|
||||
icon: Shrink,
|
||||
title: "Show the whole image (0)",
|
||||
label: "Fit",
|
||||
pressed: mode == "fit",
|
||||
disabled: !loaded,
|
||||
onClick: () => onChoose("fit"),
|
||||
},
|
||||
{
|
||||
id: "width",
|
||||
icon: MoveHorizontal,
|
||||
title: "Fit the width and scroll down (W)",
|
||||
label: "Fit width",
|
||||
pressed: mode == "width",
|
||||
disabled: !loaded,
|
||||
onClick: () => onChoose("width"),
|
||||
},
|
||||
{
|
||||
id: "actual",
|
||||
icon: Scan,
|
||||
title: "Actual size, one image pixel per screen pixel (1)",
|
||||
label: "Actual size",
|
||||
pressed: mode == "actual",
|
||||
disabled: !loaded,
|
||||
onClick: () => onChoose("actual"),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-1! flex-wrap items-center px-3 py-1.5 border-0 border-b border-solid border-hairline bg-paper">
|
||||
<ImageViewerToolButton {...zoom_out} />
|
||||
<Span className="min-w-12 text-center text-[13px] leading-[18px] font-bold tabular-nums text-ink">
|
||||
{loaded ? `${Math.round(scale * 100)}%` : "..."}
|
||||
</Span>
|
||||
<ImageViewerToolButton {...zoom_in} />
|
||||
<Span className="inline-block mx-1 h-5 w-px bg-hairline" aria-hidden />
|
||||
{preset_tools.map((tool) => (
|
||||
<ImageViewerToolButton key={tool.id} {...tool} />
|
||||
))}
|
||||
{natural ? (
|
||||
<Span className="ml-auto pl-2 text-[12px] leading-4 tabular-nums text-ink-secondary">
|
||||
{`${natural.width} x ${natural.height} px`}
|
||||
<Span className="hidden md:inline">{" · Ctrl + scroll to zoom, drag to move"}</Span>
|
||||
</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { RefObject } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import useImageViewer from "@/src/hooks/use-image-viewer";
|
||||
import useImageViewerGestures from "@/src/hooks/use-image-viewer-gestures";
|
||||
import FilePreviewNotice from "./file-preview-notice";
|
||||
import ImageViewerToolbar from "./image-viewer-toolbar";
|
||||
|
||||
type Props = {
|
||||
url: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* An image in the file preview, to inspect rather than glance at: zoom
|
||||
* (buttons, keys, Ctrl/Cmd + wheel or a pinch at the pointer), fit whole,
|
||||
* fit the width (a full-page screenshot opens that way and scrolls down),
|
||||
* actual size, double click to zoom into a spot, drag to move around.
|
||||
* The picture is sized with its `width` attribute, so no style is set,
|
||||
* and centred with auto margins, which (unlike flex centring) never push
|
||||
* the top of a picture taller than the frame out of reach.
|
||||
*/
|
||||
export default function ImageViewer({ url, name }: Props) {
|
||||
const viewer = useImageViewer();
|
||||
const { dragging, pointerHandlers } = useImageViewerGestures(viewer);
|
||||
const width = viewer.natural ? Math.max(1, Math.floor(viewer.natural.width * viewer.scale)) : undefined;
|
||||
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full gap-0! items-stretch">
|
||||
<ImageViewerToolbar
|
||||
mode={viewer.mode}
|
||||
scale={viewer.scale}
|
||||
natural={viewer.natural}
|
||||
onZoom={(direction) => viewer.zoom({ direction })}
|
||||
onChoose={(mode) => viewer.choose({ mode })}
|
||||
/>
|
||||
<Stack
|
||||
componentRef={viewer.container_ref as RefObject<HTMLDivElement>}
|
||||
{...pointerHandlers}
|
||||
onDoubleClick={(event) => viewer.toggle({ point: { x: event.clientX, y: event.clientY } })}
|
||||
className={twMerge(
|
||||
"relative grow min-h-0 w-full gap-0! items-stretch overflow-auto overscroll-contain bg-sunken select-none",
|
||||
viewer.scale < 1 && "cursor-zoom-in",
|
||||
dragging && "cursor-grabbing",
|
||||
)}
|
||||
>
|
||||
<Stack className="shrink-0 w-max min-w-full min-h-full gap-0! items-start p-4">
|
||||
<Img
|
||||
ref={viewer.image_ref}
|
||||
src={url}
|
||||
alt={name}
|
||||
loading="eager"
|
||||
draggable={false}
|
||||
width={width}
|
||||
onLoad={viewer.onImageLoad}
|
||||
imgErrComp={<FilePreviewNotice message="This image couldn't be loaded. Download it to open it." />}
|
||||
className={twMerge(
|
||||
"block shrink-0 m-auto h-auto object-contain",
|
||||
width ? "max-w-none max-h-none" : "max-w-full max-h-full",
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+7
-2
@@ -4,7 +4,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { FolderOpen } from "lucide-react";
|
||||
import type { MediaType, StorageEntry } from "@/src/types";
|
||||
import type { FilePreviewItem, MediaType, StorageEntry } from "@/src/types";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import AttachmentIcon from "@/src/pages/admin/bots/[bot_id]/(partials)/attachment-icon";
|
||||
@@ -13,6 +13,10 @@ import FilePreviewLink from "@/src/components/general/file-preview-link";
|
||||
type Props = {
|
||||
entry: StorageEntry;
|
||||
selected?: boolean;
|
||||
/**
|
||||
* The folder's images, so an image's preview steps through the rest.
|
||||
*/
|
||||
gallery?: FilePreviewItem[];
|
||||
onOpenFolder: (path: string) => void;
|
||||
};
|
||||
|
||||
@@ -21,7 +25,7 @@ type Props = {
|
||||
* file preview (its own media record when it is one of the bot's files, else
|
||||
* the browser's streaming route).
|
||||
*/
|
||||
export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props) {
|
||||
export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder }: Props) {
|
||||
const is_folder = entry.kind == "folder";
|
||||
|
||||
return (
|
||||
@@ -57,6 +61,7 @@ export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props
|
||||
url={entry.url || ""}
|
||||
media_type={entry.media_type}
|
||||
size={entry.size}
|
||||
gallery={gallery}
|
||||
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
|
||||
>
|
||||
{entry.name}
|
||||
+59
-3
@@ -110,7 +110,7 @@ export const AppData = {
|
||||
* `computer/` (the release workflow builds that tag), and bump
|
||||
* `ComputerWorkspaceLayout` too when existing computers must move to it.
|
||||
*/
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.2.0",
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.3.0",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -174,9 +174,12 @@ export const AppData = {
|
||||
* (`migrateComputerLayout`), keeping its workspace and browser profile.
|
||||
* `cobble-computer` moved every computer off the AIO sandbox;
|
||||
* `cobble-computer-accounts` gave worker bots their own accounts (the
|
||||
* container gets `NET_ADMIN` to keep them off its services).
|
||||
* container gets `NET_ADMIN` to keep them off its services);
|
||||
* `cobble-computer-homes` has workers work in their own home
|
||||
* (`/home/cb-<bot>/workspace`, a link the agent keeps to their folder),
|
||||
* which an older agent would make a folder that isn't kept.
|
||||
*/
|
||||
ComputerWorkspaceLayout: "cobble-computer-accounts",
|
||||
ComputerWorkspaceLayout: "cobble-computer-homes",
|
||||
ComputerUserUid: 1000,
|
||||
ComputerUserGid: 1000,
|
||||
/**
|
||||
@@ -398,10 +401,63 @@ export const AppData = {
|
||||
* through `grabHarnessMaxToolSteps`.
|
||||
*/
|
||||
HarnessMaxToolSteps: 200,
|
||||
/**
|
||||
* Model turns a routine run or a hook call may take: nobody watches
|
||||
* them, and one routine run once spent 39M tokens checking a site. The
|
||||
* install may save its own (`unattended_max_tool_steps`), read through
|
||||
* `grabUnattendedMaxToolSteps`; a brief's own `max_steps` can only
|
||||
* lower it.
|
||||
*/
|
||||
UnattendedMaxToolSteps: 40,
|
||||
/**
|
||||
* Prompt tokens one run may spend in all (every turn resends the
|
||||
* prompt): past it the next turn is the wrap up. A safety net under the
|
||||
* step limit, for runs whose turns are large. The install may save its
|
||||
* own (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
|
||||
*/
|
||||
RunMaxPromptTokens: 4_000_000,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
* output is trimmed, whatever the model's window. Every turn resends
|
||||
* all of it, so a run that only trims at a 1M window pays for its whole
|
||||
* history on every step. The install may save its own
|
||||
* (`harness_context_budget_tokens`), read through
|
||||
* `grabContextBudgetTokens`.
|
||||
*/
|
||||
HarnessContextBudgetTokens: 80_000,
|
||||
/**
|
||||
* The least a saved working context may be: below it a run would trim
|
||||
* the output it is reading right now.
|
||||
*/
|
||||
HarnessContextBudgetMinTokens: 20_000,
|
||||
HarnessContextBudgetMaxTokens: 1_000_000,
|
||||
/**
|
||||
* Run token budgets the settings page accepts.
|
||||
*/
|
||||
RunMaxPromptTokensMin: 100_000,
|
||||
RunMaxPromptTokensMax: 100_000_000,
|
||||
/**
|
||||
* Longest tool result handed back to the model.
|
||||
*/
|
||||
HarnessToolResultMaxChars: 20000,
|
||||
/**
|
||||
* Longest result of a browser tool (`browser_*`, the computer's or a
|
||||
* user's own browser): page snapshots and `browser_evaluate` output
|
||||
* were the heaviest results a run kept resending.
|
||||
*/
|
||||
HarnessBrowserResultMaxChars: 12000,
|
||||
/**
|
||||
* Extension tools (MCP servers, a user's browsers) are listed by name
|
||||
* and loaded with `load_tools` only when their definitions together
|
||||
* pass this many characters; below it they're simply all given.
|
||||
*/
|
||||
HarnessDeferToolsMinChars: 6000,
|
||||
/**
|
||||
* How much of a deferred tool's description its line in the list
|
||||
* shows.
|
||||
*/
|
||||
HarnessDeferredToolLineChars: 140,
|
||||
/**
|
||||
* Images one tool call may hand back (the rest are dropped), and how
|
||||
* many of the newest tool images stay in a run's transcript: every
|
||||
|
||||
@@ -53,9 +53,10 @@ describe("harness prompts", () => {
|
||||
dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }),
|
||||
});
|
||||
|
||||
expect(note).toContain("[folder:computer:8:bots/3/users/7/seo/coderank/raw]");
|
||||
expect(note).toContain("/home/gem/workspace/bots/3/users/7");
|
||||
expect(note).toContain("/home/gem/workspace/workspaces/2");
|
||||
expect(note).toContain("[folder:computer:8:home/cb-3/workspace/users/7/seo/coderank/raw]");
|
||||
expect(note).toContain("starts in /home/cb-3/workspace/users/7 (also ~ and $HOME)");
|
||||
expect(note).toContain("/home/cb-3/workspace/workspaces/2: shared");
|
||||
expect(note).toContain("only /home/cb-3/workspace and the browser's logins survive it (the rest of your account's home, /home/cb-3, doesn't)");
|
||||
expect(note).toContain("request_install");
|
||||
expect(note).not.toContain("sudo apt-get");
|
||||
});
|
||||
@@ -67,6 +68,8 @@ describe("harness prompts", () => {
|
||||
});
|
||||
|
||||
expect(note).toContain("sudo apt-get");
|
||||
expect(note).toContain("/home/gem/workspace/bots/1/users/7");
|
||||
expect(note).toContain("only /home/gem/workspace and the browser's logins survive it. ");
|
||||
expect(note).not.toContain("request_install");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import botRef from "@/src/utils/bot-ref";
|
||||
import folderRef from "@/src/utils/folder-ref";
|
||||
import { computerWorkspaceRelative, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
|
||||
/**
|
||||
* Prompts the helper harnesses send. The text model gets their output in
|
||||
@@ -32,6 +33,12 @@ export const ToolImagesNote = `The images the tool calls above returned (screens
|
||||
*/
|
||||
export const DroppedToolImageNote = `[An earlier image from a tool, no longer shown to save space. Take it again if you still need it.]`;
|
||||
|
||||
/**
|
||||
* Stands in for a page snapshot a newer snapshot of the same browser
|
||||
* replaced (`supersedeToolOutputs`): the page it showed is gone.
|
||||
*/
|
||||
export const SupersededSnapshotNote = `[An older page snapshot, replaced by the newer one further down. Take another if you need the page again.]`;
|
||||
|
||||
/**
|
||||
* The folder-ref example a note shows, always over the running bot's own
|
||||
* folder: a literal owner id in the prompt teaches the bot to name another
|
||||
@@ -54,6 +61,7 @@ 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.
|
||||
- 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.
|
||||
@@ -109,14 +117,16 @@ export const ComputerFilesNote = ({
|
||||
can_import?: boolean;
|
||||
}) => `# Files on the computer
|
||||
|
||||
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~), and a path outside your folders is refused.
|
||||
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~ and $HOME), and a path outside your folders is refused.
|
||||
|
||||
- ${dirs.cwd}: this user's work. Everything for them goes here.
|
||||
- ${dirs.bot_dir}: only what is the same for every user you work for (other users' folders in it are not yours).${
|
||||
dirs.shared_dir ? `\n- ${dirs.shared_dir}: shared with every bot in this workspace.` : ""
|
||||
}
|
||||
- The browser downloads to its own folder: move what you download into your folder straight away.
|
||||
- A computer can be restarted or rebuilt at any time, and only ${AppData.ComputerWorkspaceDir} and the browser's logins survive it. ${
|
||||
- A computer can be restarted or rebuilt at any time, and only ${dirs.run_as ? dirs.bot_dir : AppData.ComputerWorkspaceDir} and the browser's logins survive it${
|
||||
dirs.run_as ? ` (the rest of your account's home, ${computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).home}, doesn't)` : ""
|
||||
}. ${
|
||||
dirs.run_as
|
||||
? `You work as your own account, without sudo, and the browser can't open your folders' files (file: URLs): to look at a page you made, serve its folder on localhost (python3 -m http.server --bind 127.0.0.1, in the background) and open that. Python and Node packages you install yourself (pip install --user, npm install -g) go to ~/.local in this user's folder, so they stay. A system package (apt) needs the coordinator: in a task, ask with request_install, then end your run saying you're waiting for it; you're woken with the answer. System packages may be gone after a rebuild: check for one first (command -v) and ask again when it's missing.`
|
||||
: `Programs you install (sudo apt-get install -y, pip, npm -g) may be gone afterwards: check for one first (command -v) and install it again when it's missing.`
|
||||
@@ -124,7 +134,7 @@ You work only in your own folders on the computer, never elsewhere in it: every
|
||||
|
||||
What you make there (downloads, screenshots, a crawl, raw evidence, logs) is kept with the computer, not in your files, and it is not searchable.
|
||||
|
||||
- The user can open any of it: name a folder on the computer as a folder ref, its path from the computer's workspace (${AppData.ComputerWorkspaceDir}), e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${computerWorkspaceRelative({ absolute: dirs.cwd })}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
|
||||
- The user can open any of it: name a folder on the computer as a folder ref with its full path as you see it, e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${dirs.cwd}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
|
||||
${
|
||||
can_import
|
||||
? `- import_file copies a file or a folder off the computer into your own files, in one go, and the copy is searchable straight away. Import the finished work (the report, the spreadsheet, the final document), attach it when it is what they asked for, and name it with its [file:ID] ref.\n- The raw evidence can stay on the computer: import it only when the user needs it kept, or when the computer may be rebuilt.\n`
|
||||
|
||||
@@ -173,6 +173,10 @@ export const BotMessageReactions = [
|
||||
title: "Like",
|
||||
value: "👍",
|
||||
},
|
||||
{
|
||||
title: "Dislike",
|
||||
value: "👎",
|
||||
},
|
||||
{
|
||||
title: "Love",
|
||||
value: "❤️",
|
||||
|
||||
@@ -121,6 +121,7 @@ export const JobStepToolLabels: Record<string, string> = {
|
||||
update_memory: "Updating memory",
|
||||
update_instructions: "Updating instructions",
|
||||
load_skill: "Reading a skill",
|
||||
load_tools: "Loading tools",
|
||||
send_message: "Sending a message",
|
||||
create_graphic: "Drawing a graphic",
|
||||
update_graphic: "Redrawing a graphic",
|
||||
|
||||
@@ -107,6 +107,24 @@ 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";
|
||||
|
||||
/**
|
||||
* Vendors preferred for automatic picks, best first. Free models from any
|
||||
* other vendor come after these, and only if they look competent.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* How the image preview sizes a picture: `fit` shows it whole, `width`
|
||||
* fills the frame's width and scrolls down (a full-page screenshot),
|
||||
* `actual` is one image pixel per screen pixel, `custom` is wherever the
|
||||
* user zoomed to. The fits never blow a small picture up past its own size.
|
||||
*/
|
||||
export const ImageViewerModes = ["fit", "width", "actual", "custom"] as const;
|
||||
|
||||
export type ImageViewerMode = (typeof ImageViewerModes)[number];
|
||||
|
||||
/**
|
||||
* The stops the zoom buttons (and `+`/`-`) step through, from
|
||||
* `ImageViewerMinScale` to `ImageViewerMaxScale`.
|
||||
*/
|
||||
export const ImageViewerZoomSteps = [
|
||||
0.05, 0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 0.9, 1, 1.25, 1.5, 2, 3, 4, 6, 8, 12, 16,
|
||||
] as const;
|
||||
|
||||
export const ImageViewerMinScale = 0.05;
|
||||
|
||||
export const ImageViewerMaxScale = 16;
|
||||
|
||||
/**
|
||||
* A picture this much taller (relative to its width) than the frame opens
|
||||
* at the frame's width rather than whole: shrunk to fit, a page screenshot
|
||||
* is a thin unreadable strip.
|
||||
*/
|
||||
export const ImageViewerTallRatio = 2;
|
||||
@@ -1,9 +1,17 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
|
||||
import { HarnessMaxToolStepsSettingKey } from "@/src/dict/harness-dict";
|
||||
import {
|
||||
HarnessContextBudgetSettingKey,
|
||||
HarnessMaxToolStepsSettingKey,
|
||||
RunMaxPromptTokensSettingKey,
|
||||
UnattendedMaxToolStepsSettingKey,
|
||||
} from "@/src/dict/harness-dict";
|
||||
import type { RunLimitsOverview } from "@/src/types";
|
||||
import readStepLimit from "@/src/utils/read-step-limit";
|
||||
import grabAppSetting from "./grab-app-setting";
|
||||
|
||||
export type { RunLimitsOverview };
|
||||
|
||||
/**
|
||||
* Model turns a task run may take: the install's own limit
|
||||
* (`harness_max_tool_steps`, Settings > General), else
|
||||
@@ -32,44 +40,74 @@ export async function grabReplyMaxToolSteps() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Both limits with their defaults, for the settings page.
|
||||
* Model turns a routine run or a hook call may take, which nobody
|
||||
* watches: the install's own limit (`unattended_max_tool_steps`), else
|
||||
* `AppData.UnattendedMaxToolSteps`.
|
||||
*/
|
||||
export async function grabUnattendedMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: UnattendedMaxToolStepsSettingKey }),
|
||||
fallback: AppData.UnattendedMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt tokens one run may spend before it must wrap up: the install's
|
||||
* own budget (`run_max_prompt_tokens`), else `AppData.RunMaxPromptTokens`.
|
||||
*/
|
||||
export async function grabRunMaxPromptTokens() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: RunMaxPromptTokensSettingKey }),
|
||||
fallback: AppData.RunMaxPromptTokens,
|
||||
min: AppData.RunMaxPromptTokensMin,
|
||||
max: AppData.RunMaxPromptTokensMax,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The working context a run keeps per turn, in estimated tokens: the
|
||||
* install's own (`harness_context_budget_tokens`), else
|
||||
* `AppData.HarnessContextBudgetTokens`.
|
||||
*/
|
||||
export async function grabContextBudgetTokens() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: HarnessContextBudgetSettingKey }),
|
||||
fallback: AppData.HarnessContextBudgetTokens,
|
||||
min: AppData.HarnessContextBudgetMinTokens,
|
||||
max: AppData.HarnessContextBudgetMaxTokens,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Every run limit with its default, for the settings page.
|
||||
*/
|
||||
export default async function grabRunLimitsOverview() {
|
||||
const [task_steps, reply_steps] = await Promise.all([
|
||||
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens] = await Promise.all([
|
||||
grabHarnessMaxToolSteps(),
|
||||
grabReplyMaxToolSteps(),
|
||||
grabUnattendedMaxToolSteps(),
|
||||
grabRunMaxPromptTokens(),
|
||||
grabContextBudgetTokens(),
|
||||
]);
|
||||
|
||||
const overview: RunLimitsOverview = {
|
||||
task_steps,
|
||||
reply_steps,
|
||||
unattended_steps,
|
||||
run_tokens,
|
||||
context_tokens,
|
||||
task_default: AppData.HarnessMaxToolSteps,
|
||||
reply_default: AppData.BotReplyMaxToolSteps,
|
||||
unattended_default: AppData.UnattendedMaxToolSteps,
|
||||
run_tokens_default: AppData.RunMaxPromptTokens,
|
||||
context_tokens_default: AppData.HarnessContextBudgetTokens,
|
||||
max: AppData.BotStepLimitMax,
|
||||
run_tokens_min: AppData.RunMaxPromptTokensMin,
|
||||
run_tokens_max: AppData.RunMaxPromptTokensMax,
|
||||
context_tokens_min: AppData.HarnessContextBudgetMinTokens,
|
||||
context_tokens_max: AppData.HarnessContextBudgetMaxTokens,
|
||||
};
|
||||
|
||||
return overview;
|
||||
}
|
||||
|
||||
export type RunLimitsOverview = {
|
||||
/**
|
||||
* The limit a task run uses right now.
|
||||
*/
|
||||
task_steps: number;
|
||||
/**
|
||||
* The limit a chat reply uses right now.
|
||||
*/
|
||||
reply_steps: number;
|
||||
/**
|
||||
* What a task run uses when the install saved no limit.
|
||||
*/
|
||||
task_default: number;
|
||||
/**
|
||||
* What a chat reply uses when the install saved no limit.
|
||||
*/
|
||||
reply_default: number;
|
||||
/**
|
||||
* The most the settings page accepts.
|
||||
*/
|
||||
max: number;
|
||||
};
|
||||
|
||||
@@ -152,7 +152,7 @@ export default async function completeBotJob({
|
||||
face: "needs-you",
|
||||
status_line: BotNeedsYouStatusLine,
|
||||
})
|
||||
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id }))
|
||||
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id, conversations_only: true }))
|
||||
? await restoreRunningFace({ bot_id: job.bot_id, user_id })
|
||||
: await setBotFace({
|
||||
bot_id: job.bot_id,
|
||||
|
||||
@@ -6,15 +6,21 @@ type Params = {
|
||||
* Only jobs in this user's conversations.
|
||||
*/
|
||||
user_id: number | string;
|
||||
/**
|
||||
* Leave out jobs in chatrooms, which never show on the bot's face.
|
||||
*/
|
||||
conversations_only?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many of a bot's jobs for one user are still pending or processing.
|
||||
*/
|
||||
export default async function countOpenBotJobs({ bot_id, user_id }: Params) {
|
||||
export default async function countOpenBotJobs({ bot_id, user_id, conversations_only }: Params) {
|
||||
const res = await BunSQLite.sql<{ open: number }>({
|
||||
sql: `SELECT COUNT(*) AS open FROM bots_queue WHERE bot_id = ? AND status IN ('pending', 'processing')
|
||||
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL)`,
|
||||
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL${
|
||||
conversations_only ? " AND chatroom_id IS NULL" : ""
|
||||
})`,
|
||||
values: [bot_id, user_id],
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,8 @@ type Params = {
|
||||
* The face a bot should show one user while other jobs for them are
|
||||
* still running: thinking while a reply runs (it's short, and its chat
|
||||
* needs the row), else working on a task (in its workspace, if it runs in
|
||||
* one). Null when none is running.
|
||||
* one). Null when none is running. Work in a chatroom or a hook's thread
|
||||
* never counts: it shows there, never on the face.
|
||||
*/
|
||||
export default async function grabRunningBotJobFace({
|
||||
bot_id,
|
||||
@@ -26,7 +27,7 @@ export default async function grabRunningBotJobFace({
|
||||
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
|
||||
LEFT JOIN workspaces w ON w.id = q.workspace_id
|
||||
WHERE q.bot_id = ? AND q.status = 'processing'
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL)
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL AND chatroom_id IS NULL)
|
||||
ORDER BY q.id`,
|
||||
values: [bot_id, user_id],
|
||||
})
|
||||
|
||||
@@ -23,6 +23,7 @@ type CallRow = {
|
||||
model_slug: string | null;
|
||||
model_name: string | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
settings: string | null;
|
||||
@@ -53,7 +54,7 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
|
||||
await BunSQLite.sql<CallRow>({
|
||||
sql: `SELECT t.id, t.created_at, t.harness, t.provider_id, t.provider_name,
|
||||
p.kind AS provider_kind, t.model_slug, m.name AS model_name,
|
||||
t.prompt_tokens, t.completion_tokens, t.cost, t.settings, t.job_id
|
||||
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.cost, t.settings, t.job_id
|
||||
FROM token_usages t
|
||||
LEFT JOIN harness_providers p ON p.id = t.provider_id
|
||||
LEFT JOIN harness_models m ON m.id = t.model_id
|
||||
@@ -73,6 +74,7 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
|
||||
model_slug: row.model_slug || null,
|
||||
model_name: row.model_name || null,
|
||||
prompt_tokens: Number(row.prompt_tokens) || 0,
|
||||
cached_tokens: Number(row.cached_tokens) || 0,
|
||||
completion_tokens: Number(row.completion_tokens) || 0,
|
||||
cost: Number.isFinite(Number(row.cost)) && row.cost !== null ? Number(row.cost) : null,
|
||||
settings: parseCallSettings({ json: row.settings }),
|
||||
|
||||
@@ -42,6 +42,7 @@ export default async function grabUsageModels({ start, end, limit }: Params): Pr
|
||||
harness: string | null;
|
||||
calls: number | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
}>({
|
||||
@@ -52,6 +53,7 @@ export default async function grabUsageModels({ start, end, limit }: Params): Pr
|
||||
u.harness,
|
||||
COUNT(*) AS calls,
|
||||
SUM(u.prompt_tokens) AS prompt_tokens,
|
||||
SUM(u.cached_tokens) AS cached_tokens,
|
||||
SUM(u.completion_tokens) AS completion_tokens,
|
||||
SUM(u.cost) AS cost
|
||||
FROM token_usages u
|
||||
|
||||
@@ -12,6 +12,10 @@ type Params = {
|
||||
type UsageRow = {
|
||||
calls: number | null;
|
||||
prompt_tokens: number | null;
|
||||
/**
|
||||
* Left out by the queries that don't sum it.
|
||||
*/
|
||||
cached_tokens?: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
};
|
||||
@@ -34,6 +38,7 @@ export default async function grabUsageTotals({ start, end }: Params): Promise<U
|
||||
sql: `SELECT harness,
|
||||
COUNT(*) AS calls,
|
||||
SUM(prompt_tokens) AS prompt_tokens,
|
||||
SUM(cached_tokens) AS cached_tokens,
|
||||
SUM(completion_tokens) AS completion_tokens,
|
||||
SUM(cost) AS cost
|
||||
FROM token_usages
|
||||
@@ -59,12 +64,14 @@ export default async function grabUsageTotals({ start, end }: Params): Promise<U
|
||||
*/
|
||||
export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): TokenUsageSummary {
|
||||
let prompt_tokens = 0;
|
||||
let cached_tokens = 0;
|
||||
let completion_tokens = 0;
|
||||
let cost = 0;
|
||||
let calls = 0;
|
||||
|
||||
for (const summary of summaries) {
|
||||
prompt_tokens += summary.prompt_tokens;
|
||||
cached_tokens += summary.cached_tokens || 0;
|
||||
completion_tokens += summary.completion_tokens;
|
||||
cost += summary.cost || 0;
|
||||
calls += summary.calls;
|
||||
@@ -72,6 +79,7 @@ export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): T
|
||||
|
||||
return {
|
||||
prompt_tokens,
|
||||
...(cached_tokens > 0 ? { cached_tokens } : {}),
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(cost > 0 ? { cost } : {}),
|
||||
@@ -84,11 +92,13 @@ export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): T
|
||||
*/
|
||||
export function toSummary({ row }: { row: UsageRow }): TokenUsageSummary {
|
||||
const prompt_tokens = Number(row.prompt_tokens) || 0;
|
||||
const cached_tokens = Number(row.cached_tokens) || 0;
|
||||
const completion_tokens = Number(row.completion_tokens) || 0;
|
||||
const cost = Number(row.cost);
|
||||
|
||||
return {
|
||||
prompt_tokens,
|
||||
...(cached_tokens > 0 ? { cached_tokens } : {}),
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(Number.isFinite(cost) && cost > 0 ? { cost } : {}),
|
||||
|
||||
@@ -51,6 +51,15 @@ describe("readChatResponse", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("reads the cached prompt tokens, in either spelling", () => {
|
||||
const answer = (usage: Record<string, unknown>) =>
|
||||
read({ choices: [{ message: { content: "Hi." } }], usage: { prompt_tokens: 100, completion_tokens: 2, ...usage } }).usage;
|
||||
|
||||
expect(answer({ prompt_tokens_details: { cached_tokens: 80 } })?.cached_tokens).toBe(80);
|
||||
expect(answer({ prompt_cache_hit_tokens: 60 })?.cached_tokens).toBe(60);
|
||||
expect(answer({})?.cached_tokens).toBe(undefined);
|
||||
});
|
||||
|
||||
test("joins content parts and treats empty text as none", () => {
|
||||
expect(
|
||||
read({
|
||||
|
||||
@@ -77,6 +77,13 @@ export default function readChatResponse({
|
||||
usage: json.usage
|
||||
? {
|
||||
prompt_tokens: json.usage.prompt_tokens,
|
||||
/**
|
||||
* OpenAI's and OpenRouter's spelling; some providers
|
||||
* (DeepSeek's own API) say `prompt_cache_hit_tokens`.
|
||||
*/
|
||||
cached_tokens:
|
||||
Number(json.usage.prompt_tokens_details?.cached_tokens ?? json.usage.prompt_cache_hit_tokens) ||
|
||||
undefined,
|
||||
completion_tokens: json.usage.completion_tokens,
|
||||
cost: json.usage.cost,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTool } from "../types";
|
||||
import { LoadToolsToolName } from "../tools/load-tools-tool";
|
||||
|
||||
/**
|
||||
* The system prompt's list of the tools a run may load (`load_tools`):
|
||||
* each by name with the start of its description, so the model knows
|
||||
* what is there without every definition riding along on each turn.
|
||||
*/
|
||||
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
|
||||
const lines = tools.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`);
|
||||
|
||||
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with the names you need (one call can load several), then call them. Don't load what you won't use.\n${lines.join("\n")}`;
|
||||
}
|
||||
|
||||
function shortDescription({ text }: { text: string }) {
|
||||
const line = text.trim().split("\n")[0]!.trim();
|
||||
const max = AppData.HarnessDeferredToolLineChars;
|
||||
|
||||
return line.length > max ? `${line.slice(0, max - 3).trimEnd()}...` : line;
|
||||
}
|
||||
@@ -25,10 +25,10 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
test("trims the oldest tool output first, keeping the newest", () => {
|
||||
const transcript = run();
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 20000 });
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 26000 });
|
||||
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters");
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters of earlier computer_bash output");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
expect(transcript[6]!.content).toBe("recent");
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
@@ -44,4 +44,69 @@ describe("fitTranscriptToContext", () => {
|
||||
expect(result.trimmed).toBe(0);
|
||||
expect(transcript[1]!.content).toBe(big);
|
||||
});
|
||||
|
||||
test("keeps to the working context even when the window is far larger", () => {
|
||||
const transcript = run();
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript,
|
||||
context_length: 1_000_000,
|
||||
budget_tokens: 15000,
|
||||
});
|
||||
|
||||
expect(result.budget).toBe(15000);
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed:");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
});
|
||||
|
||||
test("cuts in one block, down to well under the budget, then leaves it alone", () => {
|
||||
const transcript = run();
|
||||
const first = fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 18000 });
|
||||
|
||||
expect(first.trimmed).toBe(1);
|
||||
|
||||
transcript.push(
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "4", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "4", content: "x".repeat(9000) },
|
||||
);
|
||||
|
||||
const second = fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 18000 });
|
||||
|
||||
expect(second.trimmed).toBe(0);
|
||||
});
|
||||
|
||||
test("counts the tool definitions against the budget", () => {
|
||||
const transcript = run();
|
||||
const without = fitTranscriptToContext({ system: "s", transcript: run(), context_length: 1_000_000, budget_tokens: 25000 });
|
||||
const with_tools = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript,
|
||||
context_length: 1_000_000,
|
||||
budget_tokens: 25000,
|
||||
tools_chars: 30000,
|
||||
});
|
||||
|
||||
expect(without.trimmed).toBe(0);
|
||||
expect(with_tools.trimmed).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("cuts long tool call arguments once the results are gone", () => {
|
||||
const long = JSON.stringify({ path: "a.html", content: "y".repeat(30000) });
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "Write the page." },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_write_file", arguments: long }] },
|
||||
{ role: "tool", tool_call_id: "1", content: "Written." },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "ok" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 5000 });
|
||||
|
||||
const call = (transcript[1] as { tool_calls: { arguments: string }[] }).tool_calls[0]!;
|
||||
|
||||
expect(JSON.parse(call.arguments).trimmed).toContain(`${long.length} characters`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,17 @@ type Params = {
|
||||
* The model's context window, in tokens.
|
||||
*/
|
||||
context_length: number;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most the prompt
|
||||
* may be per turn, whatever the window. Left out, only the window
|
||||
* limits it.
|
||||
*/
|
||||
budget_tokens?: number;
|
||||
/**
|
||||
* Characters of the tool definitions sent with every turn: they count
|
||||
* against the budget like the prompt.
|
||||
*/
|
||||
tools_chars?: number;
|
||||
/**
|
||||
* The newest messages, never trimmed: the model needs them to go on.
|
||||
*/
|
||||
@@ -21,6 +32,12 @@ type Params = {
|
||||
* Share of the window the prompt may fill; the rest is for the answer.
|
||||
*/
|
||||
const PromptShare = 0.7;
|
||||
/**
|
||||
* Once over budget, trimming goes on down to this share of it. Cutting in
|
||||
* one block, rather than one message each turn, keeps the start of the
|
||||
* prompt the same for many turns, which is what providers cache.
|
||||
*/
|
||||
const TrimToShare = 0.6;
|
||||
/**
|
||||
* Rough characters per token, on the low side so the estimate errs high.
|
||||
*/
|
||||
@@ -29,44 +46,129 @@ const CharsPerToken = 3;
|
||||
* What an image or audio part is counted as, in tokens.
|
||||
*/
|
||||
const MediaTokens = 1500;
|
||||
/**
|
||||
* Tool call arguments longer than this (a file written whole) are cut on
|
||||
* the second pass, after the tool results.
|
||||
*/
|
||||
const ArgumentsKeepChars = 1500;
|
||||
|
||||
/**
|
||||
* Keeps a long tool run inside the model's context window: while the
|
||||
* estimated prompt is over budget, the oldest tool results (then the
|
||||
* oldest assistant texts) are replaced with a note of what was cut.
|
||||
* Returns how many messages were trimmed.
|
||||
* Keeps a long tool run inside its working context: once the estimated
|
||||
* prompt (system, tool definitions, transcript) passes the budget (the
|
||||
* working context, or 70% of the window when that is smaller), the
|
||||
* oldest tool results, then long tool call arguments, then the oldest
|
||||
* assistant texts are replaced with a note of what was cut, down to 60%
|
||||
* of the budget. Returns how many messages were trimmed.
|
||||
*/
|
||||
export default function fitTranscriptToContext({
|
||||
system,
|
||||
transcript,
|
||||
context_length,
|
||||
budget_tokens,
|
||||
tools_chars = 0,
|
||||
keep_last = 4,
|
||||
}: Params) {
|
||||
const budget = Math.floor(context_length * PromptShare);
|
||||
let total = estimateTokens({ text: system }) + transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
const window_budget = Math.floor(context_length * PromptShare);
|
||||
const budget = budget_tokens && budget_tokens > 0 ? Math.min(window_budget, budget_tokens) : window_budget;
|
||||
let total =
|
||||
estimateTokens({ text: system }) +
|
||||
Math.ceil(tools_chars / CharsPerToken) +
|
||||
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
let trimmed = 0;
|
||||
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget };
|
||||
|
||||
const target = Math.floor(budget * TrimToShare);
|
||||
const trimmable = transcript.length - keep_last;
|
||||
const names = toolNames({ transcript });
|
||||
|
||||
for (const role of ["tool", "assistant"] as const) {
|
||||
for (let index = 0; index < trimmable && total > budget; index++) {
|
||||
const message = transcript[index]!;
|
||||
const replace = ({ index, message }: { index: number; message: HarnessMessage }) => {
|
||||
const before = messageTokens({ message: transcript[index]! });
|
||||
|
||||
if (message.role != role || typeof message.content != "string") continue;
|
||||
if (message.content.startsWith("[Trimmed:")) continue;
|
||||
transcript[index] = message;
|
||||
total += messageTokens({ message }) - before;
|
||||
trimmed++;
|
||||
};
|
||||
|
||||
const before = messageTokens({ message });
|
||||
const note = `[Trimmed: ${message.content.length} characters of earlier ${role == "tool" ? "tool output" : "notes"} to fit the context.]`;
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
transcript[index] = { ...message, content: note } as HarnessMessage;
|
||||
total += messageTokens({ message: transcript[index]! }) - before;
|
||||
trimmed++;
|
||||
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
|
||||
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier ${name ? `${name} output` : "tool output"} to fit the working context. Call it again if you still need it.]`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "assistant" || !message.tool_calls?.some((call) => call.arguments.length > ArgumentsKeepChars)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
tool_calls: message.tool_calls.map((call) =>
|
||||
call.arguments.length > ArgumentsKeepChars
|
||||
? {
|
||||
...call,
|
||||
arguments: JSON.stringify({
|
||||
trimmed: `${call.arguments.length} characters of arguments cut to fit the working context`,
|
||||
}),
|
||||
}
|
||||
: call,
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "assistant" || typeof message.content != "string" || isTrimmed({ text: message.content })) {
|
||||
continue;
|
||||
}
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier notes to fit the working context.]`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { trimmed, estimated_tokens: total, budget };
|
||||
}
|
||||
|
||||
/**
|
||||
* The tool each call id went to, for the note that replaces its result.
|
||||
*/
|
||||
function toolNames({ transcript }: { transcript: HarnessMessage[] }) {
|
||||
const names = new Map<string, string>();
|
||||
|
||||
for (const message of transcript) {
|
||||
if (message.role != "assistant") continue;
|
||||
|
||||
for (const call of message.tool_calls || []) names.set(call.id, call.name);
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
function isTrimmed({ text }: { text: string }) {
|
||||
return text.startsWith("[Trimmed:");
|
||||
}
|
||||
|
||||
function messageTokens({ message }: { message: HarnessMessage }) {
|
||||
let tokens = 4;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { DroppedToolImageNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
|
||||
@@ -443,4 +443,105 @@ describe("runTextLoop", () => {
|
||||
expect(result.text).toBe("Out of steps.");
|
||||
expect(reviews).toBe(0);
|
||||
});
|
||||
|
||||
test("wraps up once the run has spent its token budget", async () => {
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
usage: { prompt_tokens: 600, completion_tokens: 1 },
|
||||
};
|
||||
const { generate, seen } = scripted([loop_call, loop_call, { text: "Stopping here.", ...loop_call }]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen[2]!.tools).toBe(undefined);
|
||||
expect(seen[2]!.messages.at(-1)!.content).toContain("This run has used all the tokens it may spend.");
|
||||
expect(result.text).toBe("Stopping here.");
|
||||
});
|
||||
|
||||
test("keeps only the newest page snapshot in the transcript", async () => {
|
||||
let page = 0;
|
||||
const snapshot: HarnessTool = {
|
||||
name: "browser_snapshot",
|
||||
description: "Reads the page.",
|
||||
schema: z.object({}),
|
||||
run: async () => `page ${++page}`,
|
||||
};
|
||||
const snap = (id: string) => ({ tool_calls: [{ id, name: "browser_snapshot", arguments: "{}" }] });
|
||||
const { generate, seen } = scripted([snap("a"), snap("b")]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Look." }],
|
||||
tools: [snapshot],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const tool_turns = seen[2]!.messages.filter((message) => message.role == "tool");
|
||||
|
||||
expect(tool_turns.map((message) => message.content)).toEqual([SupersededSnapshotNote, "page 2"]);
|
||||
});
|
||||
|
||||
test("lists deferred tools by name and gives their definitions once loaded", async () => {
|
||||
const big = "Does a thing. ".repeat(Math.ceil(AppData.HarnessDeferToolsMinChars / 14));
|
||||
const used: string[] = [];
|
||||
const extension = (name: string): HarnessTool => ({
|
||||
name,
|
||||
description: big,
|
||||
parameters: { type: "object", properties: {} },
|
||||
deferred: true,
|
||||
run: async () => {
|
||||
used.push(name);
|
||||
return "done";
|
||||
},
|
||||
});
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "1", name: "load_tools", arguments: `{"names":["srv__a"]}` }] },
|
||||
{ tool_calls: [{ id: "2", name: "srv__a", arguments: "{}" }] },
|
||||
{ tool_calls: [{ id: "3", name: "srv__b", arguments: "{}" }] },
|
||||
{ text: "Done." },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, extension("srv__a"), extension("srv__b")],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const names = (index: number) => seen[index]!.tools!.map((tool) => tool.name);
|
||||
|
||||
expect(names(0)).toEqual(["remember", "load_tools"]);
|
||||
expect(String(seen[0]!.messages[0]!.content)).toContain("Tools you can load");
|
||||
expect(String(seen[0]!.messages[0]!.content)).toContain("- srv__a: Does a thing.");
|
||||
expect(names(1)).toEqual(["remember", "load_tools", "srv__a"]);
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain("Loaded: srv__a.");
|
||||
expect(names(3)).toEqual(["remember", "load_tools", "srv__a", "srv__b"]);
|
||||
expect(used).toEqual(["srv__a", "srv__b"]);
|
||||
});
|
||||
|
||||
test("gives small deferred tools straight away", async () => {
|
||||
const small: HarnessTool = { ...remember, name: "srv__small", deferred: true };
|
||||
const { generate, seen } = scripted([{ text: "Hi." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, small],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "srv__small"]);
|
||||
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../harness-error";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import type {
|
||||
@@ -12,11 +13,13 @@ import type {
|
||||
HarnessToolUse,
|
||||
HarnessUsage,
|
||||
} from "../types";
|
||||
import deferredToolsNote from "./deferred-tools-note";
|
||||
import describeToolUses from "./describe-tool-uses";
|
||||
import dropOldToolImages from "./drop-old-tool-images";
|
||||
import fitTranscriptToContext from "./fit-transcript-to-context";
|
||||
import generateText from "./generate-text";
|
||||
import pushUserTurn from "./push-user-turn";
|
||||
import supersedeToolOutputs from "./supersede-tool-outputs";
|
||||
import toolImagesTurn from "./tool-images-turn";
|
||||
|
||||
export type TextLoopStep = {
|
||||
@@ -35,8 +38,25 @@ type Params = {
|
||||
* The conversation so far, ending with what to do now.
|
||||
*/
|
||||
messages: HarnessMessage[];
|
||||
/**
|
||||
* The run's tools. Deferred ones (`HarnessTool.deferred`) are listed
|
||||
* by name and loaded with `load_tools`, when together they're large
|
||||
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
|
||||
*/
|
||||
tools?: HarnessTool[];
|
||||
max_steps?: number;
|
||||
/**
|
||||
* Prompt tokens the run may spend in all (`grabRunMaxPromptTokens`):
|
||||
* once its turns have sent this many, the next one is the wrap up.
|
||||
* Left out, only `max_steps` ends it.
|
||||
*/
|
||||
max_prompt_tokens?: number;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most each turn
|
||||
* sends before old tool output is trimmed, whatever the model's
|
||||
* window. Left out, the window decides.
|
||||
*/
|
||||
context_budget?: number;
|
||||
signal?: AbortSignal;
|
||||
/**
|
||||
* Called after each model turn, before its tools run. Use it for
|
||||
@@ -91,10 +111,11 @@ export type TextLoopResult = {
|
||||
/**
|
||||
* Told on the last step, with the app's record of the tools the run
|
||||
* called (`describeToolUses`): out of steps, a model tends to report the
|
||||
* work it planned as done.
|
||||
* work it planned as done. `tokens` when the run's token budget ended it
|
||||
* rather than its steps.
|
||||
*/
|
||||
export const wrapUpPrompt = ({ uses }: { uses: HarnessToolUse[] }) =>
|
||||
`You've used every step this run allows. Don't call any more tools. Report what you did, what is left, and anything you need from the user.
|
||||
export const wrapUpPrompt = ({ uses, reason = "steps" }: { uses: HarnessToolUse[]; reason?: "steps" | "tokens" }) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} Don't call any more tools. Report what you did, what is left, and anything you need from the user.
|
||||
|
||||
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
|
||||
|
||||
@@ -121,14 +142,23 @@ Don't repeat tool calls you have already made.`;
|
||||
* The text harness at work: the model answers or calls tools, tool results
|
||||
* go back to it, and so on until it answers without calling a tool. Tools
|
||||
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
|
||||
* `max_steps` turns the model is asked to wrap up without tools. An answer
|
||||
* `review` finds fault with is written again once.
|
||||
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
|
||||
* model is asked to wrap up without tools. An answer `review` finds fault
|
||||
* with is written again once.
|
||||
*
|
||||
* Every turn resends everything, so the run keeps it small: only the
|
||||
* newest page snapshot of each browser stays (`supersedeToolOutputs`),
|
||||
* old tool output is trimmed to the working context
|
||||
* (`fitTranscriptToContext`), and deferred tools are listed by name until
|
||||
* loaded.
|
||||
*/
|
||||
export default async function runTextLoop({
|
||||
system,
|
||||
messages,
|
||||
tools = [],
|
||||
max_steps = AppData.HarnessMaxToolSteps,
|
||||
max_prompt_tokens,
|
||||
context_budget,
|
||||
signal = new AbortController().signal,
|
||||
onStep,
|
||||
incoming,
|
||||
@@ -139,10 +169,39 @@ export default async function runTextLoop({
|
||||
resolveCandidates = () => resolveHarnessCandidates({ harness: "text", bot_id, workspace_id }),
|
||||
}: Params): Promise<TextLoopResult> {
|
||||
const candidates = await resolveCandidates();
|
||||
const definitions = tools.map((tool) => toolDefinition({ tool }));
|
||||
/**
|
||||
* Deferred tools wait to be loaded only when their definitions
|
||||
* together are worth keeping out of every turn.
|
||||
*/
|
||||
const deferrable = tools.filter((tool) => tool.deferred);
|
||||
const defer =
|
||||
deferrable.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0) >=
|
||||
AppData.HarnessDeferToolsMinChars;
|
||||
/**
|
||||
* Loaded deferred tools, in the order they were loaded: their
|
||||
* definitions go after the others, so the start of the list (and of
|
||||
* the prompt, which providers cache) stays the same.
|
||||
*/
|
||||
const loaded: string[] = [];
|
||||
const run_tools: HarnessTool[] = defer
|
||||
? [
|
||||
...tools,
|
||||
loadToolsTool({
|
||||
deferred: deferrable,
|
||||
isLoaded: (name) => loaded.includes(name),
|
||||
onLoad: (names) => loaded.push(...names),
|
||||
}),
|
||||
]
|
||||
: tools;
|
||||
const all_definitions = new Map(run_tools.map((tool) => [tool.name, toolDefinition({ tool })]));
|
||||
const definitionsNow = () => [
|
||||
...run_tools.filter((tool) => !defer || !tool.deferred).map((tool) => all_definitions.get(tool.name)!),
|
||||
...loaded.map((name) => all_definitions.get(name)!),
|
||||
];
|
||||
const run_system = defer ? `${system}\n\n${deferredToolsNote({ tools: deferrable })}` : system;
|
||||
const media_cache = new Map<string, string>();
|
||||
const transcript: HarnessMessage[] = [...messages];
|
||||
const usage: Required<HarnessUsage> = {
|
||||
const usage: Required<Omit<HarnessUsage, "cached_tokens">> = {
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
cost: 0,
|
||||
@@ -156,12 +215,18 @@ export default async function runTextLoop({
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
}
|
||||
|
||||
const wrap_up = index == max_steps;
|
||||
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens);
|
||||
const wrap_up = index == max_steps || out_of_tokens;
|
||||
|
||||
if (wrap_up) {
|
||||
pushUserTurn({ transcript, content: wrapUpPrompt({ uses: tool_uses }) });
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
content: wrapUpPrompt({ uses: tool_uses, reason: index == max_steps ? "steps" : "tokens" }),
|
||||
});
|
||||
}
|
||||
|
||||
const definitions = definitionsNow();
|
||||
|
||||
/**
|
||||
* Sized for the model the run is on (or will start on). A fallback
|
||||
* with a smaller window gets a 400 and the next model is tried.
|
||||
@@ -169,13 +234,15 @@ export default async function runTextLoop({
|
||||
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
|
||||
|
||||
fitTranscriptToContext({
|
||||
system,
|
||||
system: run_system,
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessAutoMinContext,
|
||||
budget_tokens: context_budget,
|
||||
tools_chars: wrap_up ? 0 : JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
const answer = await generate({
|
||||
messages: [{ role: "system", content: system }, ...transcript],
|
||||
messages: [{ role: "system", content: run_system }, ...transcript],
|
||||
tools: wrap_up || !definitions.length ? undefined : definitions,
|
||||
candidates,
|
||||
prefer_key,
|
||||
@@ -240,7 +307,15 @@ export default async function runTextLoop({
|
||||
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
|
||||
|
||||
for (const call of tool_calls) {
|
||||
const { text: content, images } = await runToolCall({ call, tools, signal });
|
||||
const { text: content, images } = await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
* it stays loaded from here on.
|
||||
*/
|
||||
if (defer && deferrable.some((tool) => tool.name == call.name) && !loaded.includes(call.name)) {
|
||||
loaded.push(call.name);
|
||||
}
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
@@ -254,6 +329,8 @@ export default async function runTextLoop({
|
||||
* setting allows it (`textSeesImages`); otherwise `generateText`
|
||||
* has them read first.
|
||||
*/
|
||||
supersedeToolOutputs({ transcript });
|
||||
|
||||
if (shown.length) {
|
||||
pushUserTurn({ transcript, content: toolImagesTurn({ shown }) });
|
||||
dropOldToolImages({
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { SupersededSnapshotNote } from "@/src/data/harness-prompts";
|
||||
import type { HarnessMessage } from "../types";
|
||||
import supersedeToolOutputs from "./supersede-tool-outputs";
|
||||
|
||||
const call = (id: string, name: string): HarnessMessage => ({
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [{ id, name, arguments: "{}" }],
|
||||
});
|
||||
|
||||
const result = (id: string, content: string): HarnessMessage => ({ role: "tool", tool_call_id: id, content });
|
||||
|
||||
describe("supersedeToolOutputs", () => {
|
||||
test("keeps only the newest snapshot of each browser", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "Check the site." },
|
||||
call("1", "browser_snapshot"),
|
||||
result("1", "page one"),
|
||||
call("2", "browser_click"),
|
||||
result("2", "clicked"),
|
||||
call("3", "pc__browser_snapshot"),
|
||||
result("3", "my page"),
|
||||
call("4", "browser_snapshot"),
|
||||
result("4", "page two"),
|
||||
];
|
||||
|
||||
expect(supersedeToolOutputs({ transcript })).toBe(1);
|
||||
expect(transcript[2]!.content).toBe(SupersededSnapshotNote);
|
||||
expect(transcript[4]!.content).toBe("clicked");
|
||||
expect(transcript[6]!.content).toBe("my page");
|
||||
expect(transcript[8]!.content).toBe("page two");
|
||||
expect(supersedeToolOutputs({ transcript })).toBe(0);
|
||||
});
|
||||
|
||||
test("a failed snapshot replaces nothing", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
call("1", "browser_snapshot"),
|
||||
result("1", "page one"),
|
||||
call("2", "browser_snapshot"),
|
||||
result("2", "Error: the browser is closed."),
|
||||
];
|
||||
|
||||
expect(supersedeToolOutputs({ transcript })).toBe(0);
|
||||
expect(transcript[1]!.content).toBe("page one");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { SupersededSnapshotNote } from "@/src/data/harness-prompts";
|
||||
import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
import type { HarnessMessage } from "../types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Changed in place, so the run keeps the savings.
|
||||
*/
|
||||
transcript: HarnessMessage[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Keeps only the newest page snapshot of each browser in a run's
|
||||
* transcript: a snapshot shows the page as it was, and the next one
|
||||
* replaces it, so resending the old ones on every turn only costs tokens.
|
||||
* Older ones become a note. A failed snapshot replaces nothing. Returns
|
||||
* how many were replaced.
|
||||
*/
|
||||
export default function supersedeToolOutputs({ transcript }: Params) {
|
||||
const names = new Map<string, string>();
|
||||
|
||||
for (const message of transcript) {
|
||||
if (message.role != "assistant") continue;
|
||||
|
||||
for (const call of message.tool_calls || []) names.set(call.id, call.name);
|
||||
}
|
||||
|
||||
const newest = new Map<string, number>();
|
||||
|
||||
transcript.forEach((message, index) => {
|
||||
if (message.role != "tool" || !isSnapshot({ message, names })) return;
|
||||
|
||||
newest.set(names.get(message.tool_call_id)!, index);
|
||||
});
|
||||
|
||||
let replaced = 0;
|
||||
|
||||
transcript.forEach((message, index) => {
|
||||
if (message.role != "tool" || !isSnapshot({ message, names })) return;
|
||||
if (newest.get(names.get(message.tool_call_id)!) == index) return;
|
||||
|
||||
transcript[index] = { ...message, content: SupersededSnapshotNote };
|
||||
replaced++;
|
||||
});
|
||||
|
||||
return replaced;
|
||||
}
|
||||
|
||||
/**
|
||||
* A successful snapshot that is still shown in full.
|
||||
*/
|
||||
function isSnapshot({ message, names }: { message: HarnessMessage & { role: "tool" }; names: Map<string, string> }) {
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
return (
|
||||
Boolean(name) &&
|
||||
isBrowserTool({ name: name!, action: "browser_snapshot" }) &&
|
||||
!message.content.startsWith("Error:") &&
|
||||
message.content != SupersededSnapshotNote
|
||||
);
|
||||
}
|
||||
@@ -42,7 +42,7 @@ type Args = {
|
||||
export default function askCrewTool({ user_id, bot_id, session_id, workspace_id, onChatroom }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "ask_crew",
|
||||
description: `Ask another bot for something you need (what it knows, a file it has, work in its line) through the coordinator. The coordinator reads your request, asks the bot best placed to answer and sends the answer back here as a message, which wakes you to act on it: don't wait or check on it. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
|
||||
description: `Ask another bot for something you need (what it knows, a file it has, work in its line) through the coordinator. The coordinator reads your request, asks the bot best placed to answer and sends the answer back here as a message, which wakes you to act on it: don't wait or check on it. If a task you'd start needs the answer, don't start it in the same reply: it would run without it, so start it once the answer wakes you. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
|
||||
workspace_id ? "You're in a workspace, so only its members can be asked." : "Any bot the user works with can be asked."
|
||||
} The request and everything said about it is kept in a chatroom the user can read.`,
|
||||
schema: z.object({
|
||||
|
||||
@@ -114,15 +114,21 @@ export default async function openBotBrowsers({
|
||||
if (names.has(name)) continue;
|
||||
|
||||
names.add(name);
|
||||
tools.push(
|
||||
mcpHarnessTool({
|
||||
/**
|
||||
* Deferred: listed by name until the run loads them
|
||||
* (`load_tools`), so a turn that doesn't browse doesn't carry
|
||||
* every browser tool's definition.
|
||||
*/
|
||||
tools.push({
|
||||
...mcpHarnessTool({
|
||||
name,
|
||||
tool: { ...tool, description: `${browser.name}: ${tool.description}` },
|
||||
client,
|
||||
redact,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
}),
|
||||
);
|
||||
deferred: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
|
||||
/**
|
||||
* The shell that puts a command in the run's folder on the computer:
|
||||
* creates its folders (the user's in the bot's, and the workspace's shared
|
||||
* one), moves into the user's and makes it `HOME`, so `~` and every
|
||||
* relative path land there. A worker (its own account, no sudo) also
|
||||
* gets `umask 007`, so its files stay its workspace group's and nobody
|
||||
* else's, and installs into that home that work without root
|
||||
* (`pip install --user`, `npm install -g` into `~/.local`, on `PATH`).
|
||||
* Ends with `; `, ready to prefix a command.
|
||||
* creates the user's folder in the bot's, moves into it and makes it
|
||||
* `HOME`, so `~` and every relative path land there. The coordinator also
|
||||
* creates the workspace's shared folder. A worker's shared folder is a
|
||||
* link in its own (`workspaces/<id>`, made by the computer's agent) to the
|
||||
* real one; when it's gone the link is put back, never a folder made in
|
||||
* its place, which would keep the workspace's work from its other bots. A
|
||||
* worker (its own account, no sudo) also gets `umask 007`, so its files
|
||||
* stay its workspace group's and nobody else's, and installs into that
|
||||
* home that work without root (`pip install --user`, `npm install -g` into
|
||||
* `~/.local`, on `PATH`). Ends with `; `, ready to prefix a command.
|
||||
*/
|
||||
export default function computerDirsShell({ dirs }: { dirs: ComputerRunDirs }) {
|
||||
const cwd = shellQuote({ text: dirs.cwd });
|
||||
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
|
||||
.map((dir) => shellQuote({ text: dir }))
|
||||
.join(" ");
|
||||
|
||||
if (!dirs.run_as) return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
|
||||
if (!dirs.run_as) {
|
||||
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
|
||||
.map((dir) => shellQuote({ text: dir }))
|
||||
.join(" ");
|
||||
|
||||
return `umask 007 && mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
|
||||
return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
|
||||
}
|
||||
|
||||
const shared = dirs.shared_dir ? sharedLinkShell({ link: dirs.shared_dir }) : "";
|
||||
|
||||
return `umask 007 && ${shared}mkdir -p ${cwd} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
|
||||
}
|
||||
|
||||
function sharedLinkShell({ link }: { link: string }) {
|
||||
const quoted = shellQuote({ text: link });
|
||||
const parent = shellQuote({ text: link.replace(/\/[^/]+$/, "") });
|
||||
const target = shellQuote({ text: computerWorkspacePath({ absolute: link }) });
|
||||
|
||||
return `{ [ -e ${quoted} ] || [ -L ${quoted} ] || { mkdir -p ${parent} && ln -s ${target} ${quoted}; }; } && `;
|
||||
}
|
||||
|
||||
@@ -95,9 +95,8 @@ export default function importFileTool({
|
||||
* Workspace-relative from here on, which is what a folder ref
|
||||
* names.
|
||||
*/
|
||||
const source = computerWorkspaceRelative({
|
||||
absolute: resolveComputerPath({ path: args.path, dirs }),
|
||||
});
|
||||
const shown = resolveComputerPath({ path: args.path, dirs });
|
||||
const source = computerWorkspaceRelative({ absolute: shown });
|
||||
|
||||
if (!source) return `Give a file or folder inside your folder, e.g. "seo/coderank/raw".`;
|
||||
|
||||
@@ -110,13 +109,14 @@ export default function importFileTool({
|
||||
const kind = await sourceKind({ computer: target, source, run_as: dirs.run_as, signal });
|
||||
|
||||
if (kind == "missing") {
|
||||
return `Nothing at ${onComputer({ source })} on this computer. Check it with search_computers or the computer's own tools before importing.`;
|
||||
return `Nothing at ${shown} on this computer. Check it with search_computers or the computer's own tools before importing.`;
|
||||
}
|
||||
|
||||
if (kind == "folder") {
|
||||
return importFolder({
|
||||
computer: target,
|
||||
source,
|
||||
shown,
|
||||
name: (args.name || source.split("/").pop() || "import").trim(),
|
||||
scope: own,
|
||||
bot_id,
|
||||
@@ -130,6 +130,7 @@ export default function importFileTool({
|
||||
return importOneFile({
|
||||
computer: target,
|
||||
source,
|
||||
shown,
|
||||
name: (args.name || source.split("/").pop() || "import").trim(),
|
||||
scope: own,
|
||||
bot_id,
|
||||
@@ -146,7 +147,14 @@ export default function importFileTool({
|
||||
|
||||
type ImportTarget = {
|
||||
computer: ComputerApi;
|
||||
/**
|
||||
* Relative to the computer's workspace, where it really is.
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* Its path as the run sees it, for what the bot is told.
|
||||
*/
|
||||
shown: string;
|
||||
name: string;
|
||||
scope: StorageScope;
|
||||
bot_id: number | string;
|
||||
@@ -180,7 +188,7 @@ async function importOneFile({
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!download.ok) return importFailure({ reason: download.reason, size: download.size, path: target.source });
|
||||
if (!download.ok) return importFailure({ reason: download.reason, size: download.size, shown: target.shown });
|
||||
|
||||
const previous = await grabBotFileRow({
|
||||
scope: target.scope.scope,
|
||||
@@ -206,11 +214,11 @@ async function importOneFile({
|
||||
return [
|
||||
previous?.id
|
||||
? `You already had ${saved.path} (same ref, no second copy): its bytes are now this file, ${formatSize({ bytes: download.size })} byte for byte.`
|
||||
: `Copied ${onComputer({ source: target.source })} into your files as ${saved.path} [file:${saved.id}], ${formatSize({ bytes: download.size })} byte for byte.`,
|
||||
: `Copied ${target.shown} into your files as ${saved.path} [file:${saved.id}], ${formatSize({ bytes: download.size })} byte for byte.`,
|
||||
`The original is still on the computer, in ${folderRef({
|
||||
volume: "computer",
|
||||
owner_id: target.computer_id,
|
||||
path: sourceFolder({ path: target.source }),
|
||||
path: sourceFolder({ path: target.shown }),
|
||||
})}`,
|
||||
"Name the copy with its [file:ID] ref when you tell the user about it.",
|
||||
].join("\n");
|
||||
@@ -239,22 +247,22 @@ async function importFolder({
|
||||
return importFailure({
|
||||
reason: archive.reason,
|
||||
size: archive.size,
|
||||
path: target.source,
|
||||
shown: target.shown,
|
||||
});
|
||||
}
|
||||
|
||||
const saved = await unpackArchive({ archive: archive.bytes, folder: name.replace(/\/+$/, ""), scope, bot_id, user_id });
|
||||
|
||||
if (!saved.length) return `The folder ${onComputer({ source: target.source })} is empty, so nothing was imported.`;
|
||||
if (!saved.length) return `The folder ${target.shown} is empty, so nothing was imported.`;
|
||||
|
||||
return [
|
||||
`Copied ${saved.length} file(s) from ${onComputer({ source: target.source })} into your files under ${name}/:`,
|
||||
`Copied ${saved.length} file(s) from ${target.shown} into your files under ${name}/:`,
|
||||
...saved.slice(0, 20).map((file) => `- ${file.path} [file:${file.id}]`),
|
||||
saved.length > 20 ? `(and ${saved.length - 20} more)` : "",
|
||||
`The originals are still on the computer, in ${folderRef({
|
||||
volume: "computer",
|
||||
owner_id: computer_id,
|
||||
path: target.source,
|
||||
path: target.shown,
|
||||
})}`,
|
||||
"Name the copies that matter with their [file:ID] refs.",
|
||||
]
|
||||
@@ -306,23 +314,26 @@ async function sourceKind({
|
||||
function importFailure({
|
||||
reason,
|
||||
size,
|
||||
path: source,
|
||||
shown,
|
||||
}: {
|
||||
reason: "missing" | "too_big" | "cut_short";
|
||||
size: number;
|
||||
path: string;
|
||||
/**
|
||||
* The path as the run sees it.
|
||||
*/
|
||||
shown: string;
|
||||
}) {
|
||||
const limit = formatSize({ bytes: AppData.BotFileImportMaxBytes });
|
||||
|
||||
if (reason == "missing") {
|
||||
return `Nothing at ${onComputer({ source })} on this computer. Check it with search_computers or the computer's own tools before importing.`;
|
||||
return `Nothing at ${shown} on this computer. Check it with search_computers or the computer's own tools before importing.`;
|
||||
}
|
||||
|
||||
if (reason == "too_big") {
|
||||
return `${onComputer({ source })} is ${formatSize({ bytes: size })}, over the ${limit} limit, so nothing was copied. Zip it on the computer first, or import the files that matter on their own.`;
|
||||
return `${shown} is ${formatSize({ bytes: size })}, over the ${limit} limit, so nothing was copied. Zip it on the computer first, or import the files that matter on their own.`;
|
||||
}
|
||||
|
||||
return `The copy of ${onComputer({ source })} came back with ${formatSize({ bytes: size })} of its bytes, so it was thrown away rather than saved. Try again; if it keeps happening, the file is changing while it is read.`;
|
||||
return `The copy of ${shown} came back with ${formatSize({ bytes: size })} of its bytes, so it was thrown away rather than saved. Try again; if it keeps happening, the file is changing while it is read.`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -47,6 +47,13 @@ type Params = {
|
||||
* Without it, or without a user, the bot can't capture secrets.
|
||||
*/
|
||||
onSecretRef?: (params: { ref: string }) => void;
|
||||
/**
|
||||
* False for a run sharing the computer with the one that holds it
|
||||
* (`processBotJob`): only its shell and files, since the browser is
|
||||
* one Chrome and two runs driving it would take each other's tabs.
|
||||
* Defaults to true.
|
||||
*/
|
||||
browser?: boolean;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
@@ -83,6 +90,7 @@ export default async function openComputerTools({
|
||||
workspace_id,
|
||||
dirs,
|
||||
onSecretRef,
|
||||
browser = true,
|
||||
signal,
|
||||
}: Params): Promise<OpenComputer> {
|
||||
const target = await grabComputerMcpUrl({ computer_id });
|
||||
@@ -117,16 +125,20 @@ export default async function openComputerTools({
|
||||
const secrets: { key: string; value: string }[] = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
|
||||
const client = await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal });
|
||||
const client = browser
|
||||
? await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal })
|
||||
: null;
|
||||
const context: ComputerToolContext = { computer: target, dirs, shell_path: paths.shell_path, redact };
|
||||
|
||||
try {
|
||||
const browser_tools = await grabMcpTools({
|
||||
client,
|
||||
exclude: ComputerMcpExcludedTools,
|
||||
redact,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
});
|
||||
const browser_tools = client
|
||||
? await grabMcpTools({
|
||||
client,
|
||||
exclude: ComputerMcpExcludedTools,
|
||||
redact,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
})
|
||||
: [];
|
||||
|
||||
return {
|
||||
name: target.name,
|
||||
@@ -160,10 +172,12 @@ export default async function openComputerTools({
|
||||
],
|
||||
envs: envs.map((env) => ({ key: env.key, description: env.description })),
|
||||
redact,
|
||||
close: () => client.close().catch(() => {}),
|
||||
close: async () => {
|
||||
await client?.close().catch(() => {});
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await client.close().catch(() => {});
|
||||
await client?.close().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,16 +12,18 @@ const echoTool = (name: string): HarnessTool => ({
|
||||
});
|
||||
|
||||
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
|
||||
const cwd = "/home/gem/workspace/bots/3/users/7";
|
||||
const cwd = "/home/cb-3/workspace/users/7";
|
||||
const shared = "/home/cb-3/workspace/workspaces/2";
|
||||
const signal = new AbortController().signal;
|
||||
const call = async (name: string, args: Record<string, unknown>) =>
|
||||
JSON.parse((await withComputerDirs({ tool: echoTool(name), dirs }).run({ args, signal })) as string);
|
||||
|
||||
describe("withComputerDirs", () => {
|
||||
test("uploads resolve paths and refuse outside ones", async () => {
|
||||
expect((await call("browser_file_upload", { paths: ["a.pdf", "/home/gem/workspace/workspaces/2/b.png"] })).paths).toEqual([
|
||||
expect((await call("browser_file_upload", { paths: ["a.pdf", `${shared}/b.png`, "/home/gem/workspace/workspaces/2/c.png"] })).paths).toEqual([
|
||||
`${cwd}/a.pdf`,
|
||||
"/home/gem/workspace/workspaces/2/b.png",
|
||||
`${shared}/b.png`,
|
||||
`${shared}/c.png`,
|
||||
]);
|
||||
await expect(call("browser_file_upload", { paths: ["/home/gem/.bashrc"] })).rejects.toThrow();
|
||||
await expect(call("browser_file_upload", { paths: ["../../../4/x"] })).rejects.toThrow();
|
||||
@@ -50,9 +52,7 @@ describe("withComputerDirs", () => {
|
||||
|
||||
test("a file saved by name lands in the run's folders", async () => {
|
||||
expect((await call("browser_take_screenshot", { filename: "shot.png" })).filename).toBe(`${cwd}/shot.png`);
|
||||
expect((await call("browser_snapshot", { filename: "/home/gem/workspace/workspaces/2/page.md" })).filename).toBe(
|
||||
"/home/gem/workspace/workspaces/2/page.md",
|
||||
);
|
||||
expect((await call("browser_snapshot", { filename: `${shared}/page.md` })).filename).toBe(`${shared}/page.md`);
|
||||
await expect(call("browser_console_messages", { filename: "/home/gem/workspace/bots/4/log.txt" })).rejects.toThrow();
|
||||
});
|
||||
|
||||
@@ -63,9 +63,15 @@ describe("withComputerDirs", () => {
|
||||
});
|
||||
|
||||
describe("computerDirsShell", () => {
|
||||
test("a worker's: its umask, the folders, moved in, installs into its home", () => {
|
||||
test("a worker's: its umask, the shared link put back, its folder, moved in, installs into its home", () => {
|
||||
expect(computerDirsShell({ dirs })).toBe(
|
||||
`umask 007 && mkdir -p '${cwd}' '/home/gem/workspace/workspaces/2' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
`umask 007 && { [ -e '${shared}' ] || [ -L '${shared}' ] || { mkdir -p '/home/cb-3/workspace/workspaces' && ln -s '/home/gem/workspace/workspaces/2' '${shared}'; }; } && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
);
|
||||
});
|
||||
|
||||
test("a worker outside a workspace: no shared link", () => {
|
||||
expect(computerDirsShell({ dirs: computerRunDirs({ bot_id: 3, user_id: 7 }) })).toBe(
|
||||
`umask 007 && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -56,7 +56,8 @@ export type OpenBotExtensions = {
|
||||
/**
|
||||
* The MCP servers' and custom tools' tools a bot gets on one run
|
||||
* (`grabBotExtensions`), as harness tools. MCP tools are built from each
|
||||
* server's last listing (`<slug>__<tool>`) and connect on their first call,
|
||||
* server's last listing (`<slug>__<tool>`), deferred until the run loads
|
||||
* them (`HarnessTool.deferred`), and connect on their first call,
|
||||
* so a run that doesn't use them never waits on them. Secret env values are
|
||||
* blanked out of every result. Call `close` when the run ends.
|
||||
*/
|
||||
@@ -106,15 +107,21 @@ export default async function openBotExtensions({
|
||||
const open = openMcpServer({ server, envs, signal });
|
||||
opened.push(open);
|
||||
|
||||
/**
|
||||
* Deferred: listed by name until the run loads them (`load_tools`).
|
||||
* One server's definitions alone ran to 30,000 characters, sent
|
||||
* with every turn of every run.
|
||||
*/
|
||||
for (const tool of listed) {
|
||||
add(
|
||||
mcpHarnessTool({
|
||||
add({
|
||||
...mcpHarnessTool({
|
||||
name: mcpToolName({ slug: server.slug, name: tool.name }),
|
||||
tool: { ...tool, description: `${server.name}: ${tool.description}` },
|
||||
client: open.client,
|
||||
redact,
|
||||
}),
|
||||
);
|
||||
deferred: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { z } from "zod";
|
||||
import type { HarnessTool } from "../types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The run's deferred tools (`HarnessTool.deferred`).
|
||||
*/
|
||||
deferred: HarnessTool[];
|
||||
/**
|
||||
* Whether a tool is already loaded.
|
||||
*/
|
||||
isLoaded: (name: string) => boolean;
|
||||
/**
|
||||
* Loads them: their definitions go with every turn from the next one.
|
||||
*/
|
||||
onLoad: (names: string[]) => void;
|
||||
};
|
||||
|
||||
export const LoadToolsToolName = "load_tools";
|
||||
|
||||
/**
|
||||
* Brings deferred tools into the run (`runTextLoop`): the model sees them
|
||||
* listed by name in its prompt and loads the ones it needs, rather than
|
||||
* every turn carrying every extension's definitions. A name ending in `*`
|
||||
* loads every deferred tool it starts.
|
||||
*/
|
||||
export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): HarnessTool<{ names: string[] }> {
|
||||
return {
|
||||
name: LoadToolsToolName,
|
||||
description: `Loads tools from the "Tools you can load" list in your instructions, so you can call them from your next step. Give their exact names; "<prefix>*" loads every listed tool starting with the prefix (e.g. one server's). Load only what you're about to use.`,
|
||||
schema: z.object({
|
||||
names: z.array(z.string().trim().min(1).max(200)).min(1).max(40),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const found = new Set<string>();
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const name of args.names) {
|
||||
const matches = name.endsWith("*")
|
||||
? deferred.filter((tool) => tool.name.startsWith(name.slice(0, -1)))
|
||||
: deferred.filter((tool) => tool.name == name);
|
||||
|
||||
if (!matches.length) missing.push(name);
|
||||
|
||||
for (const tool of matches) found.add(tool.name);
|
||||
}
|
||||
|
||||
const fresh = [...found].filter((name) => !isLoaded(name));
|
||||
const already = [...found].filter((name) => isLoaded(name));
|
||||
|
||||
if (fresh.length) onLoad(fresh);
|
||||
|
||||
return [
|
||||
fresh.length ? `Loaded: ${fresh.join(", ")}. Call them from your next step.` : "",
|
||||
already.length ? `Already loaded: ${already.join(", ")}.` : "",
|
||||
missing.length ? `Not in the list: ${missing.join(", ")}. Use the exact names under "Tools you can load".` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -65,6 +65,19 @@ describe("runToolCall", () => {
|
||||
expect(result).toEndWith("[Cut: 5 more characters.]");
|
||||
});
|
||||
|
||||
test("cuts a browser tool's result sooner, saying how to see the rest", async () => {
|
||||
const browser: HarnessTool<{ text: string }> = { ...echo, name: "pc__browser_evaluate" };
|
||||
const long = "x".repeat(AppData.HarnessBrowserResultMaxChars + 7);
|
||||
const { text } = await runToolCall({
|
||||
call: { id: "1", name: browser.name, arguments: JSON.stringify({ text: long }) },
|
||||
tools: [browser],
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(text).toStartWith("x".repeat(AppData.HarnessBrowserResultMaxChars) + "\n[Cut: 7 more characters.");
|
||||
expect(text).toContain("Narrow the call");
|
||||
});
|
||||
|
||||
test("passes images on, capped and marked as a tool's", async () => {
|
||||
const result = await run("shot", "{}");
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
import TaskTimeoutError from "@/src/utils/task-timeout-error";
|
||||
import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "../harness-error";
|
||||
@@ -35,7 +36,7 @@ export default async function runToolCall({ call, tools, signal }: Params): Prom
|
||||
if (typeof text == "string") return { text, images: [] };
|
||||
|
||||
return {
|
||||
text: truncate({ text: text.text }),
|
||||
text: truncate({ text: text.text, name: call.name }),
|
||||
images: text.images
|
||||
.slice(0, AppData.HarnessToolMaxImages)
|
||||
.map((image) => ({ ...image, from_tool: true })),
|
||||
@@ -85,7 +86,7 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}),
|
||||
});
|
||||
|
||||
return typeof output == "string" ? truncate({ text: output }) : output;
|
||||
return typeof output == "string" ? truncate({ text: output, name: call.name }) : output;
|
||||
} catch (error: unknown) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
@@ -99,10 +100,16 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}
|
||||
}
|
||||
|
||||
function truncate({ text }: { text: string }) {
|
||||
const max = AppData.HarnessToolResultMaxChars;
|
||||
/**
|
||||
* A result past its tool's cap is cut there. Browser tools get the
|
||||
* smaller cap: a page snapshot or an evaluate over a whole page was the
|
||||
* heaviest thing a run kept resending.
|
||||
*/
|
||||
function truncate({ text, name }: { text: string; name: string }) {
|
||||
const browser = isBrowserTool({ name });
|
||||
const max = browser ? AppData.HarnessBrowserResultMaxChars : AppData.HarnessToolResultMaxChars;
|
||||
|
||||
if (text.length <= max) return text;
|
||||
|
||||
return `${text.slice(0, max)}\n[Cut: ${text.length - max} more characters.]`;
|
||||
return `${text.slice(0, max)}\n[Cut: ${text.length - max} more characters.${browser ? " Narrow the call (a selector, an element ref, a smaller evaluate) to see the rest." : ""}]`;
|
||||
}
|
||||
|
||||
@@ -101,6 +101,12 @@ export type HarnessTool<Args = any> = {
|
||||
description: string;
|
||||
schema?: z.ZodType<Args>;
|
||||
parameters?: Record<string, unknown>;
|
||||
/**
|
||||
* Listed by name only until the model loads it with `load_tools`
|
||||
* (`runTextLoop`): an extension's or a user browser's tools, whose
|
||||
* definitions would otherwise ride along on every turn.
|
||||
*/
|
||||
deferred?: boolean;
|
||||
run: (params: { args: Args; signal: AbortSignal }) => Promise<HarnessToolOutput>;
|
||||
};
|
||||
|
||||
@@ -176,6 +182,11 @@ export type HarnessCandidate = {
|
||||
|
||||
export type HarnessUsage = {
|
||||
prompt_tokens?: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its cache
|
||||
* (billed lower), when it says.
|
||||
*/
|
||||
cached_tokens?: number;
|
||||
completion_tokens?: number;
|
||||
/**
|
||||
* In the provider's currency (USD for OpenRouter), when reported.
|
||||
|
||||
@@ -42,12 +42,23 @@ describe("buildUsageCall", () => {
|
||||
model_id: 41,
|
||||
model_slug: "deepseek/deepseek-chat",
|
||||
prompt_tokens: 1200,
|
||||
cached_tokens: 0,
|
||||
completion_tokens: 340,
|
||||
cost: 0.0042,
|
||||
settings: { model_source: "auto" },
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps how much of the prompt the provider served from its cache", () => {
|
||||
const call = buildUsageCall({
|
||||
harness: "text",
|
||||
candidate: candidate(),
|
||||
usage: { prompt_tokens: 1200, cached_tokens: 900, completion_tokens: 340 },
|
||||
});
|
||||
|
||||
expect(call.cached_tokens).toBe(900);
|
||||
});
|
||||
|
||||
test("keeps the settings sent and the models that failed first", () => {
|
||||
const call = buildUsageCall({
|
||||
harness: "text",
|
||||
|
||||
@@ -31,6 +31,7 @@ export default function buildUsageCall({ harness, candidate, usage, settings, fa
|
||||
model_id: modelIdOf(candidate),
|
||||
model_slug: candidate.model.slug,
|
||||
prompt_tokens: Number(usage?.prompt_tokens) || 0,
|
||||
cached_tokens: Number(usage?.cached_tokens) || 0,
|
||||
completion_tokens: Number(usage?.completion_tokens) || 0,
|
||||
cost: typeof usage?.cost == "number" && Number.isFinite(usage.cost) ? usage.cost : undefined,
|
||||
settings: {
|
||||
|
||||
@@ -50,6 +50,7 @@ export default async function recordHarnessUsage({ scope, call }: Params) {
|
||||
model_id: call.model_id,
|
||||
model_slug: call.model_slug,
|
||||
prompt_tokens: Math.max(0, Math.round(call.prompt_tokens || 0)),
|
||||
cached_tokens: Math.max(0, Math.round(call.cached_tokens || 0)),
|
||||
completion_tokens: Math.max(0, Math.round(call.completion_tokens || 0)),
|
||||
cost: typeof call.cost == "number" && Number.isFinite(call.cost) ? call.cost : undefined,
|
||||
settings: call.settings ? JSON.stringify(call.settings) : undefined,
|
||||
|
||||
@@ -64,6 +64,10 @@ export type HarnessUsageCall = {
|
||||
model_id?: number;
|
||||
model_slug?: string;
|
||||
prompt_tokens: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its cache.
|
||||
*/
|
||||
cached_tokens?: number;
|
||||
completion_tokens: number;
|
||||
cost?: number;
|
||||
settings?: HarnessCallSettings;
|
||||
@@ -75,6 +79,11 @@ export type HarnessUsageCall = {
|
||||
*/
|
||||
export type TokenUsageSummary = {
|
||||
prompt_tokens: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the providers served from their
|
||||
* cache. Left out when none were (or none said).
|
||||
*/
|
||||
cached_tokens?: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
function typingInField({ target }: { target: EventTarget | null }) {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
|
||||
if (target.isContentEditable) return true;
|
||||
|
||||
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The left and right arrow keys step a preview's gallery back and forth,
|
||||
* except while typing in a field or with a modifier held.
|
||||
*/
|
||||
export default function useGalleryKeys({
|
||||
enabled,
|
||||
onPrevious,
|
||||
onNext,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
onPrevious: () => void;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
const handlers_ref = useRef({ onPrevious, onNext });
|
||||
|
||||
handlers_ref.current = { onPrevious, onNext };
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
|
||||
|
||||
if (typingInField({ target: event.target })) return;
|
||||
|
||||
if (event.key == "ArrowLeft") handlers_ref.current.onPrevious();
|
||||
else if (event.key == "ArrowRight") handlers_ref.current.onNext();
|
||||
else return;
|
||||
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKey);
|
||||
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [enabled]);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useEffect, useRef, useState, type PointerEvent, type RefObject } from "react";
|
||||
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
|
||||
import type { ImageViewerPoint } from "./use-image-viewer";
|
||||
|
||||
type Params = {
|
||||
container_ref: RefObject<HTMLDivElement | null>;
|
||||
scale_ref: RefObject<number>;
|
||||
zoom: (params: { direction: "in" | "out"; point?: ImageViewerPoint }) => void;
|
||||
zoomTo: (params: { scale: number; point?: ImageViewerPoint }) => void;
|
||||
choose: (params: { mode: Exclude<ImageViewerMode, "custom">; point?: ImageViewerPoint }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* How much one wheel pixel zooms (a trackpad pinch arrives as small
|
||||
* Ctrl+wheel steps, a mouse wheel as large ones).
|
||||
*/
|
||||
const WheelZoomRate = 0.0025;
|
||||
|
||||
function typingInField({ target }: { target: EventTarget | null }) {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
|
||||
if (target.isContentEditable) return true;
|
||||
|
||||
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The image preview's hands: Ctrl/Cmd + wheel (and a trackpad pinch) zooms
|
||||
* at the pointer, a plain wheel scrolls, dragging with the mouse moves a
|
||||
* picture bigger than the frame, and the keys `+` `-` zoom, `0` fits, `w`
|
||||
* fits the width and `1` shows actual size.
|
||||
*/
|
||||
export default function useImageViewerGestures({ container_ref, scale_ref, zoom, zoomTo, choose }: Params) {
|
||||
const drag_ref = useRef<{ x: number; y: number; left: number; top: number } | null>(null);
|
||||
const [dragging, set_dragging] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const container = container_ref.current;
|
||||
|
||||
if (!container) return;
|
||||
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (!event.ctrlKey && !event.metaKey) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const pixels = event.deltaMode == 1 ? event.deltaY * 16 : event.deltaY;
|
||||
const factor = Math.exp(-pixels * WheelZoomRate);
|
||||
|
||||
zoomTo({ scale: scale_ref.current * factor, point: { x: event.clientX, y: event.clientY } });
|
||||
};
|
||||
|
||||
container.addEventListener("wheel", onWheel, { passive: false });
|
||||
|
||||
return () => container.removeEventListener("wheel", onWheel);
|
||||
}, [container_ref, scale_ref, zoomTo]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
|
||||
if (typingInField({ target: event.target })) return;
|
||||
|
||||
if (event.key == "+" || event.key == "=") zoom({ direction: "in" });
|
||||
else if (event.key == "-" || event.key == "_") zoom({ direction: "out" });
|
||||
else if (event.key == "0") choose({ mode: "fit" });
|
||||
else if (event.key == "w" || event.key == "W") choose({ mode: "width" });
|
||||
else if (event.key == "1") choose({ mode: "actual" });
|
||||
else return;
|
||||
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKey);
|
||||
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [zoom, choose]);
|
||||
|
||||
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const container = container_ref.current;
|
||||
|
||||
if (!container || event.pointerType != "mouse" || event.button != 0) return;
|
||||
|
||||
const overflows =
|
||||
container.scrollWidth > container.clientWidth || container.scrollHeight > container.clientHeight;
|
||||
|
||||
if (!overflows) return;
|
||||
|
||||
event.preventDefault();
|
||||
container.setPointerCapture(event.pointerId);
|
||||
drag_ref.current = {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
left: container.scrollLeft,
|
||||
top: container.scrollTop,
|
||||
};
|
||||
set_dragging(true);
|
||||
};
|
||||
|
||||
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const container = container_ref.current;
|
||||
const drag = drag_ref.current;
|
||||
|
||||
if (!container || !drag) return;
|
||||
|
||||
container.scrollLeft = drag.left - (event.clientX - drag.x);
|
||||
container.scrollTop = drag.top - (event.clientY - drag.y);
|
||||
};
|
||||
|
||||
const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (!drag_ref.current) return;
|
||||
|
||||
drag_ref.current = null;
|
||||
set_dragging(false);
|
||||
container_ref.current?.releasePointerCapture(event.pointerId);
|
||||
};
|
||||
|
||||
return {
|
||||
dragging,
|
||||
pointerHandlers: {
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel: onPointerUp,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
|
||||
import imageViewerClampScale from "@/src/utils/image-viewer-clamp-scale";
|
||||
import imageViewerDefaultMode from "@/src/utils/image-viewer-default-mode";
|
||||
import imageViewerFitScale from "@/src/utils/image-viewer-fit-scale";
|
||||
import imageViewerZoomStep from "@/src/utils/image-viewer-zoom-step";
|
||||
|
||||
type Size = { width: number; height: number };
|
||||
|
||||
/**
|
||||
* A point on the screen (client coordinates) a zoom keeps still.
|
||||
*/
|
||||
export type ImageViewerPoint = { x: number; y: number };
|
||||
|
||||
/**
|
||||
* Where a zoom lands: the part of the picture under a point stays under it,
|
||||
* or the view goes back to the top left.
|
||||
*/
|
||||
type Anchor = { fx: number; fy: number; ax: number; ay: number } | "top";
|
||||
|
||||
/**
|
||||
* The frame's padding on each side (the frame's `p-4`), left out of the
|
||||
* room a fit has.
|
||||
*/
|
||||
const FramePadding = 16;
|
||||
|
||||
function clampUnit({ value }: { value: number }) {
|
||||
if (!Number.isFinite(value)) return 0.5;
|
||||
|
||||
return Math.min(1, Math.max(0, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* The image preview's state: how big the picture is drawn and where the
|
||||
* frame is scrolled. A preset (`fit`, `width`, `actual`) follows the frame
|
||||
* as it resizes; a zoom keeps the part of the picture under the pointer
|
||||
* (or the frame's middle) where it was, so the user can walk into a detail.
|
||||
*/
|
||||
export default function useImageViewer() {
|
||||
const container_ref = useRef<HTMLDivElement>(null);
|
||||
const image_ref = useRef<HTMLImageElement>(null);
|
||||
const anchor_ref = useRef<Anchor | null>(null);
|
||||
const [natural, set_natural] = useState<Size | null>(null);
|
||||
const [frame, set_frame] = useState<Size>({ width: 0, height: 0 });
|
||||
const [mode, set_mode] = useState<ImageViewerMode | null>(null);
|
||||
const [custom_scale, set_custom_scale] = useState(1);
|
||||
const [tick, set_tick] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const container = container_ref.current;
|
||||
|
||||
if (!container || typeof ResizeObserver == "undefined") return;
|
||||
|
||||
const measure = () =>
|
||||
set_frame({
|
||||
width: Math.max(0, container.clientWidth - FramePadding * 2),
|
||||
height: Math.max(0, container.clientHeight - FramePadding * 2),
|
||||
});
|
||||
|
||||
measure();
|
||||
|
||||
const observer = new ResizeObserver(measure);
|
||||
|
||||
observer.observe(container);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode || !natural || !frame.width) return;
|
||||
|
||||
set_mode(imageViewerDefaultMode({ natural, frame }));
|
||||
}, [mode, natural, frame]);
|
||||
|
||||
const shown_mode: ImageViewerMode = mode || "fit";
|
||||
const scale = !natural
|
||||
? 1
|
||||
: shown_mode == "custom"
|
||||
? custom_scale
|
||||
: imageViewerFitScale({ mode: shown_mode, natural, frame });
|
||||
const scale_ref = useRef(scale);
|
||||
|
||||
scale_ref.current = scale;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const anchor = anchor_ref.current;
|
||||
const container = container_ref.current;
|
||||
const image = image_ref.current;
|
||||
|
||||
anchor_ref.current = null;
|
||||
|
||||
if (!anchor || !container || !image) return;
|
||||
|
||||
if (anchor == "top") {
|
||||
container.scrollTo({ left: 0, top: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
container.scrollLeft = image.offsetLeft + anchor.fx * image.offsetWidth - anchor.ax;
|
||||
container.scrollTop = image.offsetTop + anchor.fy * image.offsetHeight - anchor.ay;
|
||||
}, [scale, tick]);
|
||||
|
||||
/**
|
||||
* Which part of the picture is under a point (the frame's middle when
|
||||
* none is given), to keep it there after the zoom.
|
||||
*/
|
||||
const captureAnchor = useCallback(({ point }: { point?: ImageViewerPoint }): Anchor | null => {
|
||||
const container = container_ref.current;
|
||||
const image = image_ref.current;
|
||||
|
||||
if (!container || !image) return null;
|
||||
|
||||
const box = container.getBoundingClientRect();
|
||||
const at = point || {
|
||||
x: box.left + container.clientLeft + container.clientWidth / 2,
|
||||
y: box.top + container.clientTop + container.clientHeight / 2,
|
||||
};
|
||||
const rect = image.getBoundingClientRect();
|
||||
|
||||
return {
|
||||
fx: clampUnit({ value: (at.x - rect.left) / (rect.width || 1) }),
|
||||
fy: clampUnit({ value: (at.y - rect.top) / (rect.height || 1) }),
|
||||
ax: at.x - box.left - container.clientLeft,
|
||||
ay: at.y - box.top - container.clientTop,
|
||||
};
|
||||
}, []);
|
||||
|
||||
const zoomTo = useCallback(
|
||||
({ scale: next, point }: { scale: number; point?: ImageViewerPoint }) => {
|
||||
anchor_ref.current = captureAnchor({ point });
|
||||
set_custom_scale(imageViewerClampScale({ scale: next }));
|
||||
set_mode("custom");
|
||||
set_tick((value) => value + 1);
|
||||
},
|
||||
[captureAnchor],
|
||||
);
|
||||
|
||||
const zoom = useCallback(
|
||||
({ direction, point }: { direction: "in" | "out"; point?: ImageViewerPoint }) =>
|
||||
zoomTo({ scale: imageViewerZoomStep({ scale: scale_ref.current, direction }), point }),
|
||||
[zoomTo],
|
||||
);
|
||||
|
||||
/**
|
||||
* A preset. Fitting starts from the top left (a page screenshot reads
|
||||
* from its top); actual size keeps the point (or the middle) in view.
|
||||
*/
|
||||
const choose = useCallback(
|
||||
({ mode: next, point }: { mode: Exclude<ImageViewerMode, "custom">; point?: ImageViewerPoint }) => {
|
||||
anchor_ref.current = next == "actual" ? captureAnchor({ point }) : "top";
|
||||
set_mode(next);
|
||||
set_tick((value) => value + 1);
|
||||
},
|
||||
[captureAnchor],
|
||||
);
|
||||
|
||||
/**
|
||||
* A double click: into actual size at that point from anything
|
||||
* smaller, else back to the picture's own fit.
|
||||
*/
|
||||
const toggle = useCallback(
|
||||
({ point }: { point: ImageViewerPoint }) => {
|
||||
if (scale_ref.current < 1) return choose({ mode: "actual", point });
|
||||
|
||||
if (!natural) return;
|
||||
|
||||
choose({ mode: imageViewerDefaultMode({ natural, frame }) });
|
||||
},
|
||||
[choose, natural, frame],
|
||||
);
|
||||
|
||||
const onImageLoad = useCallback(() => {
|
||||
const image = image_ref.current;
|
||||
|
||||
if (!image?.naturalWidth || !image.naturalHeight) return;
|
||||
|
||||
set_natural({ width: image.naturalWidth, height: image.naturalHeight });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (image_ref.current?.complete) onImageLoad();
|
||||
}, [onImageLoad]);
|
||||
|
||||
return {
|
||||
container_ref,
|
||||
image_ref,
|
||||
natural,
|
||||
mode: shown_mode,
|
||||
scale,
|
||||
scale_ref,
|
||||
zoom,
|
||||
zoomTo,
|
||||
choose,
|
||||
toggle,
|
||||
onImageLoad,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Starts loading images the user is likely to open next (a gallery's
|
||||
* neighbours), so stepping to one shows it at once.
|
||||
*/
|
||||
export default function usePreloadImages({ urls }: { urls: string[] }) {
|
||||
const key = urls.join("\n");
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof Image == "undefined") return;
|
||||
|
||||
const images = urls.filter(Boolean).map((url) => {
|
||||
const image = new Image();
|
||||
|
||||
image.decoding = "async";
|
||||
image.src = url;
|
||||
|
||||
return image;
|
||||
});
|
||||
|
||||
return () => {
|
||||
for (const image of images) image.src = "";
|
||||
};
|
||||
}, [key]);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useId, useRef } from "react";
|
||||
|
||||
/**
|
||||
* The open modals that close on Escape one at a time, oldest first.
|
||||
*/
|
||||
const OpenModals: string[] = [];
|
||||
|
||||
/**
|
||||
* Escape closes only the modal on top. twui's modal closes every open one
|
||||
* on the same key press, so a file opened from a folder (or a folder from
|
||||
* a file) would take both away. Listening first, on the window's capture
|
||||
* phase, the modal on top closes itself and the press goes no further.
|
||||
*/
|
||||
export default function useTopModalEscape({ onClose }: { onClose: () => void }) {
|
||||
const id = useId();
|
||||
const close_ref = useRef(onClose);
|
||||
|
||||
close_ref.current = onClose;
|
||||
|
||||
useEffect(() => {
|
||||
OpenModals.push(id);
|
||||
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key != "Escape" || OpenModals.at(-1) != id) return;
|
||||
|
||||
event.stopPropagation();
|
||||
close_ref.current();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
|
||||
const index = OpenModals.lastIndexOf(id);
|
||||
|
||||
if (index >= 0) OpenModals.splice(index, 1);
|
||||
};
|
||||
}, [id]);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { useContext, useEffect, useMemo, useState } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
@@ -14,6 +14,7 @@ import HeaderIconButton from "@/src/components/general/header-icon-button";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import useDebouncedValue from "@/src/hooks/use-debounced-value";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
|
||||
import useBotFiles from "../(hooks)/use-bot-files";
|
||||
import FileRow from "./file-row";
|
||||
import HeaderMenuItem from "./header-menu-item";
|
||||
@@ -83,6 +84,10 @@ export default function BotFilesModal({ bot, workspace, menu, on_open }: Props)
|
||||
};
|
||||
|
||||
const files = data?.files || [];
|
||||
const gallery = useMemo(
|
||||
() => imagePreviewGallery({ items: files.map((file) => ({ ...file, name: file.path || file.name })) }),
|
||||
[data],
|
||||
);
|
||||
const usage = data?.usage;
|
||||
|
||||
return (
|
||||
@@ -146,6 +151,7 @@ export default function BotFilesModal({ bot, workspace, menu, on_open }: Props)
|
||||
file={file}
|
||||
can_manage={can_manage}
|
||||
busy={busy_id == file.id}
|
||||
gallery={gallery}
|
||||
onDelete={() =>
|
||||
run({
|
||||
url: `/api/admin/bots/delete-file`,
|
||||
|
||||
@@ -3,7 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import type { MediaType, PublicBotFile } from "@/src/types";
|
||||
import type { FilePreviewItem, MediaType, PublicBotFile } from "@/src/types";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import FilePreviewLink from "@/src/components/general/file-preview-link";
|
||||
import AttachmentIcon from "./attachment-icon";
|
||||
@@ -15,6 +15,10 @@ type Props = {
|
||||
*/
|
||||
can_manage: boolean;
|
||||
busy?: boolean;
|
||||
/**
|
||||
* The listed images, so an image's preview steps through the rest.
|
||||
*/
|
||||
gallery?: FilePreviewItem[];
|
||||
onDelete: () => void;
|
||||
};
|
||||
|
||||
@@ -22,7 +26,7 @@ type Props = {
|
||||
* One file in the files modal: its type, path, size and age, and what can
|
||||
* be done with it.
|
||||
*/
|
||||
export default function FileRow({ file, can_manage, busy, onDelete }: Props) {
|
||||
export default function FileRow({ file, can_manage, busy, gallery, onDelete }: Props) {
|
||||
return (
|
||||
<Row className="w-full gap-3! flex-nowrap items-start py-2 border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<Row className="mt-0.5 text-ink-secondary">
|
||||
@@ -34,6 +38,7 @@ export default function FileRow({ file, can_manage, busy, onDelete }: Props) {
|
||||
url={file.url}
|
||||
media_type={file.media_type}
|
||||
size={file.size}
|
||||
gallery={gallery}
|
||||
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
|
||||
>
|
||||
{file.path || file.name}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { FolderOpen } from "lucide-react";
|
||||
import FolderPreviewLink from "@/src/components/general/folder-preview-link";
|
||||
import { folderRefUrl } from "@/src/utils/folder-ref";
|
||||
import { storagePathName, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
|
||||
@@ -11,11 +11,13 @@ type Props = {
|
||||
|
||||
/**
|
||||
* A folder a bot named in a message (`folderRef`): the name it ends with,
|
||||
* linked into the files browser, where the user can look at everything in
|
||||
* it. Nothing is downloaded: a folder ref never serves bytes, and this chip
|
||||
* never guesses from the name whether it is a file or a folder, because the
|
||||
* ref itself already says it is a folder. A file the bot saved is a file
|
||||
* ref (`fileRef`) and opens the file instead.
|
||||
* opening the folder over the chat (`FolderPreviewModal`), where each file
|
||||
* opens in its own preview. It stays a link to the same folder in the
|
||||
* files browser, for a middle or Ctrl/Cmd click and the modal's "Open in
|
||||
* Files". Nothing is downloaded: a folder ref never serves bytes, and this
|
||||
* chip never guesses from the name whether it is a file or a folder,
|
||||
* because the ref itself already says it is a folder. A file the bot saved
|
||||
* is a file ref (`fileRef`) and opens the file instead.
|
||||
*
|
||||
* Written without a literal ref in this comment on purpose: Tailwind scans
|
||||
* every page and partial, reads a bracketed `name:value` as an
|
||||
@@ -26,13 +28,15 @@ export default function FolderRefChip({ spec, path }: Props) {
|
||||
const name = storagePathName({ volume: spec.volume, path });
|
||||
|
||||
return (
|
||||
<Link
|
||||
<FolderPreviewLink
|
||||
spec={spec}
|
||||
path={path}
|
||||
href={folderRefUrl({ volume: spec.volume, owner_id: spec.owner_id, path })}
|
||||
title={`Open ${path || name} in Files`}
|
||||
title={`Open ${path || name}`}
|
||||
className="inline-flex h-6 max-w-full gap-1.5 items-center px-1.5 align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink hover:opacity-80"
|
||||
>
|
||||
<FolderOpen size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="truncate">{name}</Span>
|
||||
</Link>
|
||||
</FolderPreviewLink>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { BotMessageAttachment } from "@/src/types";
|
||||
import type { BotMessageAttachment, FilePreviewItem } from "@/src/types";
|
||||
import FilePreviewLink from "@/src/components/general/file-preview-link";
|
||||
import AttachmentIcon from "./attachment-icon";
|
||||
|
||||
/**
|
||||
* One file on a message: an image as a thumbnail, anything else as a
|
||||
* named chip. Both open the file in the preview.
|
||||
* named chip. Both open the file in the preview; an image steps through
|
||||
* the message's other images (`gallery`).
|
||||
*/
|
||||
export default function MessageAttachment({
|
||||
name,
|
||||
media_type,
|
||||
url,
|
||||
thumbnail_url,
|
||||
}: BotMessageAttachment) {
|
||||
gallery,
|
||||
}: BotMessageAttachment & { gallery?: FilePreviewItem[] }) {
|
||||
if (media_type == "image") {
|
||||
return (
|
||||
<FilePreviewLink name={name} url={url} media_type={media_type} title={name} className="block">
|
||||
<FilePreviewLink name={name} url={url} media_type={media_type} gallery={gallery} title={name} className="block">
|
||||
<Img
|
||||
src={thumbnail_url || url}
|
||||
alt={name}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import type { BotMessageAttachment } from "@/src/types";
|
||||
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
|
||||
import MessageAttachment from "./message-attachment";
|
||||
|
||||
type Props = {
|
||||
@@ -7,15 +8,18 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* A message's files, right-aligned above its bubble.
|
||||
* A message's files, right-aligned above its bubble. Its images make one
|
||||
* gallery, so opening one steps through the others.
|
||||
*/
|
||||
export default function MessageAttachments({ attachments }: Props) {
|
||||
if (!attachments?.length) return null;
|
||||
|
||||
const gallery = imagePreviewGallery({ items: attachments });
|
||||
|
||||
return (
|
||||
<Row className="max-w-[80%] gap-2! justify-end">
|
||||
{attachments.map((attachment) => (
|
||||
<MessageAttachment key={attachment.id} {...attachment} />
|
||||
<MessageAttachment key={attachment.id} {...attachment} gallery={gallery} />
|
||||
))}
|
||||
</Row>
|
||||
);
|
||||
|
||||
@@ -49,7 +49,7 @@ export default function MessageDetailsCallRow({ call, index, first_at }: Props)
|
||||
</Span>
|
||||
<Span
|
||||
className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums"
|
||||
title={`${call.prompt_tokens.toLocaleString()} in, ${call.completion_tokens.toLocaleString()} out · ${costLabel({ cost: call.cost })}`}
|
||||
title={`${call.prompt_tokens.toLocaleString()} in${call.cached_tokens ? ` (${call.cached_tokens.toLocaleString()} cached)` : ""}, ${call.completion_tokens.toLocaleString()} out · ${costLabel({ cost: call.cost })}`}
|
||||
>
|
||||
{`${formatTokens({ tokens: call.prompt_tokens })} / ${formatTokens({ tokens: call.completion_tokens })}`}
|
||||
</Span>
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { useMemo } from "react";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { StorageFolderPayload, StorageSpecOption } from "@/src/types";
|
||||
import type { StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import { emptyFolderText, folderSummary } from "../(functions)/folder-text";
|
||||
import FilesBreadcrumbRow from "../(partials)/files-breadcrumb-row";
|
||||
import FilesSearchInput from "../(partials)/files-search-input";
|
||||
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
|
||||
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
|
||||
import FilesBreadcrumbRow from "@/src/components/general/files-breadcrumb-row";
|
||||
import FilesSearchInput from "@/src/components/general/files-search-input";
|
||||
import FilesVolumeRow from "../(partials)/files-volume-row";
|
||||
import StorageEntryRow from "../(partials)/storage-entry-row";
|
||||
import StorageEntryRow from "@/src/components/general/storage-entry-row";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Paper from "@moduletrace/twui/elements/Paper";
|
||||
|
||||
@@ -42,6 +44,11 @@ export default function FilesBrowser({
|
||||
onOpenFolder,
|
||||
onOpenVolume,
|
||||
}: Props) {
|
||||
const gallery = useMemo(
|
||||
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
|
||||
[folder],
|
||||
);
|
||||
|
||||
return (
|
||||
<Row className="w-full mt-6 gap-6! flex-wrap items-start lg:flex-nowrap">
|
||||
<Stack className="w-full lg:w-[180px] shrink-0 items-stretch">
|
||||
@@ -98,6 +105,7 @@ export default function FilesBrowser({
|
||||
entry.kind == "folder" &&
|
||||
entry.path == path
|
||||
}
|
||||
gallery={gallery}
|
||||
onOpenFolder={onOpenFolder}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -3,7 +3,7 @@ import useDebouncedValue from "@/src/hooks/use-debounced-value";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { StorageSpecOption } from "@/src/types";
|
||||
import { parseStorageSpec, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import useStorageFolder from "../(hooks)/use-storage-folder";
|
||||
import useStorageFolder from "@/src/hooks/use-storage-folder";
|
||||
import FilesBrowser from "./files-browser";
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
value: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
suffix: string;
|
||||
info: string;
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One number of the run limits form. It only reads `value` when it
|
||||
* mounts: the form remounts it (its `key`) after a save or a discard.
|
||||
*/
|
||||
export default function RunLimitInput({ label, value, min = 0, max, suffix, info, onChange }: Props) {
|
||||
return (
|
||||
<Input
|
||||
label={label}
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={1}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
suffix={suffix}
|
||||
info={info}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -2,24 +2,43 @@ import { useState } from "react";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { RunLimitsOverview } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import SettingsSaveBar from "../../(partials)/settings-save-bar";
|
||||
import RunLimitInput from "./run-limit-input";
|
||||
|
||||
type Props = {
|
||||
limits?: RunLimitsOverview | null;
|
||||
};
|
||||
|
||||
type Values = {
|
||||
task_steps: string;
|
||||
reply_steps: string;
|
||||
unattended_steps: string;
|
||||
run_tokens: string;
|
||||
context_tokens: string;
|
||||
};
|
||||
|
||||
const valuesOf = (limits?: RunLimitsOverview | null): Values => ({
|
||||
task_steps: String(limits?.task_steps ?? ""),
|
||||
reply_steps: String(limits?.reply_steps ?? ""),
|
||||
unattended_steps: String(limits?.unattended_steps ?? ""),
|
||||
run_tokens: String(limits?.run_tokens ?? ""),
|
||||
context_tokens: String(limits?.context_tokens ?? ""),
|
||||
});
|
||||
|
||||
const count = (value?: number) => (value ?? 0).toLocaleString("en-US");
|
||||
|
||||
/**
|
||||
* How many model turns a task run and a chat reply may take, saved on its
|
||||
* own without a reload. Zero puts the code's default back for that one.
|
||||
* How long a bot may work on one run (model turns per task, reply and
|
||||
* routine or hook call, the prompt tokens one run may spend) and how much
|
||||
* of its work it resends per turn, saved on its own without a reload. Zero
|
||||
* puts the code's default back for that one.
|
||||
*/
|
||||
export default function RunLimitsForm({ limits }: Props) {
|
||||
const [overview, setOverview] = useState(limits || undefined);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [task_steps, setTaskSteps] = useState(String(limits?.task_steps ?? ""));
|
||||
const [reply_steps, setReplySteps] = useState(String(limits?.reply_steps ?? ""));
|
||||
const [values, setValues] = useState<Values>(valuesOf(limits));
|
||||
/**
|
||||
* The inputs only read `defaultValue` when they mount, so discarding or
|
||||
* saving remounts them with the saved numbers.
|
||||
@@ -32,7 +51,16 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
success?: boolean;
|
||||
}>();
|
||||
|
||||
const change = (key: keyof Values) => (value: string) => {
|
||||
setValues((current) => ({ ...current, [key]: value }));
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (loading) return;
|
||||
if (!window.confirm("Save these run limits? They apply to every bot's next run.")) return;
|
||||
|
||||
setLoading(true);
|
||||
setStatus(undefined);
|
||||
|
||||
@@ -41,8 +69,11 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
{
|
||||
method: "POST",
|
||||
body: {
|
||||
task_steps: Number(task_steps) || 0,
|
||||
reply_steps: Number(reply_steps) || 0,
|
||||
task_steps: Number(values.task_steps) || 0,
|
||||
reply_steps: Number(values.reply_steps) || 0,
|
||||
unattended_steps: Number(values.unattended_steps) || 0,
|
||||
run_tokens: Number(values.run_tokens) || 0,
|
||||
context_tokens: Number(values.context_tokens) || 0,
|
||||
},
|
||||
},
|
||||
).catch(() => null);
|
||||
@@ -58,19 +89,17 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
}
|
||||
|
||||
setOverview(res.singleRes);
|
||||
setTaskSteps(String(res.singleRes.task_steps));
|
||||
setReplySteps(String(res.singleRes.reply_steps));
|
||||
setValues(valuesOf(res.singleRes));
|
||||
setFormKey((key) => key + 1);
|
||||
setDirty(false);
|
||||
setStatus({
|
||||
success: true,
|
||||
msg: `Saved: ${res.singleRes.task_steps} steps per task, ${res.singleRes.reply_steps} per reply.`,
|
||||
msg: `Saved: ${res.singleRes.task_steps} steps per task, ${res.singleRes.reply_steps} per reply, ${res.singleRes.unattended_steps} per routine or hook call.`,
|
||||
});
|
||||
};
|
||||
|
||||
const discard = () => {
|
||||
setTaskSteps(String(overview?.task_steps ?? ""));
|
||||
setReplySteps(String(overview?.reply_steps ?? ""));
|
||||
setValues(valuesOf(overview));
|
||||
setFormKey((key) => key + 1);
|
||||
setDirty(false);
|
||||
setStatus(undefined);
|
||||
@@ -84,43 +113,47 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
}}
|
||||
className="w-full gap-3! items-stretch"
|
||||
>
|
||||
<Stack className="w-full gap-3! items-stretch">
|
||||
<Input
|
||||
key={`task-${form_key}`}
|
||||
<Stack key={form_key} className="w-full gap-3! items-stretch">
|
||||
<RunLimitInput
|
||||
label="Tool steps per task"
|
||||
type="number"
|
||||
min={0}
|
||||
value={values.task_steps}
|
||||
max={overview?.max}
|
||||
step={1}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={task_steps}
|
||||
onChange={(event) => {
|
||||
setTaskSteps(event.target.value);
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
suffix={`steps`}
|
||||
suffix="steps"
|
||||
onChange={change("task_steps")}
|
||||
info={`How many turns the model may take before it must stop and report, when it works on a task. 0 uses the default (${overview?.task_default ?? ""}).`}
|
||||
/>
|
||||
<Input
|
||||
key={`reply-${form_key}`}
|
||||
<RunLimitInput
|
||||
label="Tool steps per chat reply"
|
||||
type="number"
|
||||
min={0}
|
||||
value={values.reply_steps}
|
||||
max={overview?.max}
|
||||
step={1}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={reply_steps}
|
||||
onChange={(event) => {
|
||||
setReplySteps(event.target.value);
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
suffix={`steps`}
|
||||
suffix="steps"
|
||||
onChange={change("reply_steps")}
|
||||
info={`How many turns a chat reply may take before it answers. Long work belongs in a task. 0 uses the default (${overview?.reply_default ?? ""}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Tool steps per routine or hook call"
|
||||
value={values.unattended_steps}
|
||||
max={overview?.max}
|
||||
suffix="steps"
|
||||
onChange={change("unattended_steps")}
|
||||
info={`Routine runs and hook calls work with nobody watching, so they stop sooner. Never more than the task limit. 0 uses the default (${overview?.unattended_default ?? ""}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Tokens per run"
|
||||
value={values.run_tokens}
|
||||
max={overview?.run_tokens_max}
|
||||
suffix="tokens"
|
||||
onChange={change("run_tokens")}
|
||||
info={`Every turn sends the prompt again, so a run's prompt tokens add up fast. Once a task or reply has sent this many, its next turn is its last and it reports. Between ${count(overview?.run_tokens_min)} and ${count(overview?.run_tokens_max)}; 0 uses the default (${count(overview?.run_tokens_default)}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Working context"
|
||||
value={values.context_tokens}
|
||||
max={overview?.context_tokens_max}
|
||||
suffix="tokens"
|
||||
onChange={change("context_tokens")}
|
||||
info={`How much a run sends per turn (its prompt, its tools and what it has done so far) before the oldest tool output is cut, whatever the model's window. Smaller costs less per turn; larger lets a bot keep more of what it read. Between ${count(overview?.context_tokens_min)} and ${count(overview?.context_tokens_max)}; 0 uses the default (${count(overview?.context_tokens_default)}).`}
|
||||
/>
|
||||
</Stack>
|
||||
<SettingsSaveBar
|
||||
dirty={dirty}
|
||||
|
||||
@@ -16,7 +16,7 @@ export default function RunLimitsSection() {
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Run limits"
|
||||
description="How many turns a bot may take with its tools before it must stop and report. A task may take far more than a chat reply, since it does the long work."
|
||||
description="How long a bot may work on one run before it must stop and report, and how much of its work it sends the model each turn. A task may take far more than a chat reply, since it does the long work."
|
||||
id="run-limits"
|
||||
>
|
||||
<RunLimitsForm limits={pageProps?.run_limits} />
|
||||
|
||||
@@ -39,7 +39,10 @@ export default function UsageModelRow({ row }: Props) {
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate">
|
||||
{formatTokens({ tokens: row.calls })}
|
||||
</Span>
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate">
|
||||
<Span
|
||||
className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate"
|
||||
title={row.cached_tokens ? `${row.cached_tokens.toLocaleString()} of them from the provider's cache` : undefined}
|
||||
>
|
||||
{formatTokens({ tokens: row.prompt_tokens })}
|
||||
</Span>
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate">
|
||||
|
||||
@@ -22,7 +22,7 @@ export default function UsageTotals({ usage }: Props) {
|
||||
<UsageStat
|
||||
label="Tokens"
|
||||
value={formatTokens({ tokens: totals.total_tokens })}
|
||||
hint={`${formatTokens({ tokens: totals.prompt_tokens })} in, ${formatTokens({ tokens: totals.completion_tokens })} out`}
|
||||
hint={`${formatTokens({ tokens: totals.prompt_tokens })} in${cachedShare({ cached: totals.cached_tokens, prompt: totals.prompt_tokens })}, ${formatTokens({ tokens: totals.completion_tokens })} out`}
|
||||
/>
|
||||
<UsageStat
|
||||
label="Model calls"
|
||||
@@ -43,6 +43,16 @@ export default function UsageTotals({ usage }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of what was sent the providers served from their cache, when
|
||||
* they said: " (40% cached)".
|
||||
*/
|
||||
function cachedShare({ cached, prompt }: { cached?: number; prompt: number }) {
|
||||
if (!cached || !prompt) return "";
|
||||
|
||||
return ` (${Math.round((cached / prompt) * 100)}% cached)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* How this period compares with the one before it: a share up or down, or
|
||||
* that there is nothing to compare with yet.
|
||||
|
||||
@@ -5,7 +5,12 @@ import grabRunLimitsOverview, {
|
||||
import saveAppSetting from "@/src/functions/backend/db/app-settings/save-app-setting";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
|
||||
import { HarnessMaxToolStepsSettingKey } from "@/src/dict/harness-dict";
|
||||
import {
|
||||
HarnessContextBudgetSettingKey,
|
||||
HarnessMaxToolStepsSettingKey,
|
||||
RunMaxPromptTokensSettingKey,
|
||||
UnattendedMaxToolStepsSettingKey,
|
||||
} from "@/src/dict/harness-dict";
|
||||
import { SaveRunLimitsRequestSchema } from "@/src/schemas/harness-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
@@ -13,8 +18,10 @@ import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Super admin only: how many model turns a task run and a chat reply may
|
||||
* take. Zero puts the code's default back for that one.
|
||||
* Super admin only: how many model turns a task run, a chat reply and a
|
||||
* routine run or hook call may take, the prompt tokens one run may spend
|
||||
* and the working context it keeps. Zero puts the code's default back for
|
||||
* that one.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>> = async ({
|
||||
req,
|
||||
@@ -27,7 +34,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
|
||||
|
||||
if (!user?.id) throw new AppError(`Only a super admin can change the run limits.`);
|
||||
|
||||
const { task_steps, reply_steps } = parseWithSchema({
|
||||
const { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens } = parseWithSchema({
|
||||
schema: SaveRunLimitsRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
@@ -40,13 +47,25 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
|
||||
key: BotReplyMaxToolStepsSettingKey,
|
||||
value: reply_steps > 0 ? String(reply_steps) : null,
|
||||
});
|
||||
await saveAppSetting({
|
||||
key: UnattendedMaxToolStepsSettingKey,
|
||||
value: unattended_steps > 0 ? String(unattended_steps) : null,
|
||||
});
|
||||
await saveAppSetting({
|
||||
key: RunMaxPromptTokensSettingKey,
|
||||
value: run_tokens > 0 ? String(run_tokens) : null,
|
||||
});
|
||||
await saveAppSetting({
|
||||
key: HarnessContextBudgetSettingKey,
|
||||
value: context_tokens > 0 ? String(context_tokens) : null,
|
||||
});
|
||||
|
||||
await logEvent({
|
||||
title: "Bot run limits changed",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} set the tool step limits to ${task_steps || "default"} per task and ${reply_steps || "default"} per chat reply.`,
|
||||
metadata: { task_steps, reply_steps },
|
||||
plain_text: `User #${user.id} set the tool step limits to ${task_steps || "default"} per task, ${reply_steps || "default"} per chat reply and ${unattended_steps || "default"} per routine or hook call, the tokens per run to ${run_tokens || "default"} and the working context to ${context_tokens || "default"}.`,
|
||||
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
|
||||
@@ -105,9 +105,32 @@ export type SaveBotHarnessSettingsRequest = z.infer<
|
||||
* The General settings' run limits: model turns a task run and a chat reply
|
||||
* may take. Zero puts the code's default back.
|
||||
*/
|
||||
/**
|
||||
* A token figure on the run limits form: 0 puts the default back, anything
|
||||
* else must sit inside its range.
|
||||
*/
|
||||
const tokenLimit = ({ min, max, label }: { min: number; max: number; label: string }) =>
|
||||
z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.refine((value) => value == 0 || (value >= min && value <= max), {
|
||||
message: `${label} must be 0 (the default) or between ${min.toLocaleString("en-US")} and ${max.toLocaleString("en-US")} tokens.`,
|
||||
});
|
||||
|
||||
export const SaveRunLimitsRequestSchema = z.object({
|
||||
task_steps: z.coerce.number().int().min(0).max(AppData.BotStepLimitMax),
|
||||
reply_steps: z.coerce.number().int().min(0).max(AppData.BotStepLimitMax),
|
||||
unattended_steps: z.coerce.number().int().min(0).max(AppData.BotStepLimitMax).default(0),
|
||||
run_tokens: tokenLimit({
|
||||
min: AppData.RunMaxPromptTokensMin,
|
||||
max: AppData.RunMaxPromptTokensMax,
|
||||
label: "Tokens per run",
|
||||
}).default(0),
|
||||
context_tokens: tokenLimit({
|
||||
min: AppData.HarnessContextBudgetMinTokens,
|
||||
max: AppData.HarnessContextBudgetMaxTokens,
|
||||
label: "Working context",
|
||||
}).default(0),
|
||||
});
|
||||
|
||||
export type SaveRunLimitsRequest = z.infer<typeof SaveRunLimitsRequestSchema>;
|
||||
|
||||
+66
-9
@@ -1249,6 +1249,52 @@ export type LogRetentionOverview = {
|
||||
/**
|
||||
* The install's skill limits (Settings > General, `grab-skill-limits.ts`).
|
||||
*/
|
||||
/**
|
||||
* Every run limit with the code's defaults and the ranges the settings
|
||||
* page accepts (`grabRunLimitsOverview`).
|
||||
*/
|
||||
export type RunLimitsOverview = {
|
||||
/**
|
||||
* The limit a task run uses right now.
|
||||
*/
|
||||
task_steps: number;
|
||||
/**
|
||||
* The limit a chat reply uses right now.
|
||||
*/
|
||||
reply_steps: number;
|
||||
/**
|
||||
* The limit a routine run or hook call uses right now.
|
||||
*/
|
||||
unattended_steps: number;
|
||||
/**
|
||||
* The prompt tokens one run may spend right now.
|
||||
*/
|
||||
run_tokens: number;
|
||||
/**
|
||||
* The working context a run keeps right now, in tokens.
|
||||
*/
|
||||
context_tokens: number;
|
||||
/**
|
||||
* What each uses when the install saved nothing.
|
||||
*/
|
||||
task_default: number;
|
||||
reply_default: number;
|
||||
unattended_default: number;
|
||||
run_tokens_default: number;
|
||||
context_tokens_default: number;
|
||||
/**
|
||||
* The most steps the settings page accepts.
|
||||
*/
|
||||
max: number;
|
||||
/**
|
||||
* The range the settings page accepts for each token figure.
|
||||
*/
|
||||
run_tokens_min: number;
|
||||
run_tokens_max: number;
|
||||
context_tokens_min: number;
|
||||
context_tokens_max: number;
|
||||
};
|
||||
|
||||
export type SkillLimitsOverview = {
|
||||
/**
|
||||
* The longest runbook a skill may save right now.
|
||||
@@ -1427,6 +1473,18 @@ export type BotFileScopesPayload = {
|
||||
/**
|
||||
* One entry in a folder the files browser shows: a file or a subfolder.
|
||||
*/
|
||||
/**
|
||||
* One file the preview can show: its name, where its bytes are, and what
|
||||
* kind of media it is. A list of them is a preview's gallery (the images
|
||||
* of a folder or a message), stepped through with Previous and Next.
|
||||
*/
|
||||
export type FilePreviewItem = {
|
||||
name: string;
|
||||
url: string;
|
||||
media_type?: string | null;
|
||||
size?: number;
|
||||
};
|
||||
|
||||
export type StorageEntry = {
|
||||
name: string;
|
||||
/**
|
||||
@@ -1678,6 +1736,10 @@ export type MessageDetailsCall = {
|
||||
*/
|
||||
model_name: string | null;
|
||||
prompt_tokens: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its cache.
|
||||
*/
|
||||
cached_tokens: number;
|
||||
completion_tokens: number;
|
||||
cost: number | null;
|
||||
/**
|
||||
@@ -2021,16 +2083,11 @@ export type PagePropsType = {
|
||||
text: string;
|
||||
} | null;
|
||||
/**
|
||||
* Model turns a task run and a chat reply may take, with the code's
|
||||
* defaults (the General settings page).
|
||||
* Model turns a task, a chat reply and a routine or hook call may take,
|
||||
* the prompt tokens one run may spend and the working context it keeps,
|
||||
* with the code's defaults (the General settings page).
|
||||
*/
|
||||
run_limits?: {
|
||||
task_steps: number;
|
||||
reply_steps: number;
|
||||
task_default: number;
|
||||
reply_default: number;
|
||||
max: number;
|
||||
} | null;
|
||||
run_limits?: RunLimitsOverview | null;
|
||||
/**
|
||||
* The longest runbook a skill may save and how much of it a bot reads
|
||||
* at once, with the code's defaults (the General settings page).
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import isBrowserTool from "./browser-tool-name";
|
||||
|
||||
describe("isBrowserTool", () => {
|
||||
test("knows the computer's and a user's browser tools", () => {
|
||||
expect(isBrowserTool({ name: "browser_evaluate" })).toBe(true);
|
||||
expect(isBrowserTool({ name: "my_debian_pc_chromium__browser_navigate" })).toBe(true);
|
||||
expect(isBrowserTool({ name: "computer_bash" })).toBe(false);
|
||||
expect(isBrowserTool({ name: "exa_search__web_fetch_exa" })).toBe(false);
|
||||
expect(isBrowserTool({ name: "notbrowser_x" })).toBe(false);
|
||||
});
|
||||
|
||||
test("matches one action exactly", () => {
|
||||
expect(isBrowserTool({ name: "browser_snapshot", action: "browser_snapshot" })).toBe(true);
|
||||
expect(isBrowserTool({ name: "pc__browser_snapshot", action: "browser_snapshot" })).toBe(true);
|
||||
expect(isBrowserTool({ name: "browser_snapshot_x", action: "browser_snapshot" })).toBe(false);
|
||||
expect(isBrowserTool({ name: "browser_click", action: "browser_snapshot" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Whether a tool is a browser's: the computer's Playwright MCP
|
||||
* (`browser_*`) or a user's own browser (`<slug>__browser_*`). With
|
||||
* `action`, whether it is that browser tool exactly (`browser_snapshot`
|
||||
* matches `browser_snapshot` and `my_pc__browser_snapshot`).
|
||||
*/
|
||||
export default function isBrowserTool({ name, action }: { name: string; action?: string }) {
|
||||
const match = name.match(/(?:^|__)(browser_[a-z0-9_]+)$/i);
|
||||
|
||||
if (!match) return false;
|
||||
|
||||
return action ? match[1] == action : true;
|
||||
}
|
||||
@@ -2,25 +2,30 @@ import { describe, expect, test } from "bun:test";
|
||||
import computerRunDirs, { computerWorkspaceRelative, resolveComputerPath } from "./computer-work-dirs";
|
||||
|
||||
const W = "/home/gem/workspace";
|
||||
const H = "/home/cb-3/workspace";
|
||||
|
||||
describe("computerRunDirs", () => {
|
||||
test("a worker gets its own folder, the user's inside it", () => {
|
||||
test("a worker works in its kept folder at home, the user's inside it", () => {
|
||||
const dirs = computerRunDirs({ bot_id: 3, user_id: 7 });
|
||||
|
||||
expect(dirs.cwd).toBe(`${W}/bots/3/users/7`);
|
||||
expect(dirs.roots).toEqual([`${W}/bots/3`]);
|
||||
expect(dirs.cwd).toBe(`${H}/users/7`);
|
||||
expect(dirs.bot_dir).toBe(H);
|
||||
expect(dirs.roots).toEqual([H]);
|
||||
expect(dirs.shared_dir).toBeNull();
|
||||
});
|
||||
|
||||
test("in a workspace the shared folder joins", () => {
|
||||
test("in a workspace the shared folder joins, inside its own", () => {
|
||||
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
|
||||
|
||||
expect(dirs.roots).toEqual([`${W}/bots/3`, `${W}/workspaces/2`]);
|
||||
expect(dirs.shared_dir).toBe(`${H}/workspaces/2`);
|
||||
expect(dirs.roots).toEqual([H, `${H}/workspaces/2`]);
|
||||
});
|
||||
|
||||
test("the coordinator reaches the whole workspace", () => {
|
||||
const dirs = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1 });
|
||||
test("the coordinator works in the computer's workspace and reaches all of it", () => {
|
||||
const dirs = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1, workspace_id: 2 });
|
||||
|
||||
expect(dirs.cwd).toBe(`${W}/bots/1/users/1`);
|
||||
expect(dirs.shared_dir).toBe(`${W}/workspaces/2`);
|
||||
expect(dirs.roots).toEqual([W]);
|
||||
});
|
||||
|
||||
@@ -35,27 +40,41 @@ describe("resolveComputerPath", () => {
|
||||
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
|
||||
|
||||
test("relative paths and ~ land in the user's folder", () => {
|
||||
expect(resolveComputerPath({ path: "seo/raw", dirs })).toBe(`${W}/bots/3/users/7/seo/raw`);
|
||||
expect(resolveComputerPath({ path: "~/a.txt", dirs })).toBe(`${W}/bots/3/users/7/a.txt`);
|
||||
expect(resolveComputerPath({ path: "~", dirs })).toBe(`${W}/bots/3/users/7`);
|
||||
expect(resolveComputerPath({ path: "", dirs })).toBe(`${W}/bots/3/users/7`);
|
||||
expect(resolveComputerPath({ path: "seo/raw", dirs })).toBe(`${H}/users/7/seo/raw`);
|
||||
expect(resolveComputerPath({ path: "~/a.txt", dirs })).toBe(`${H}/users/7/a.txt`);
|
||||
expect(resolveComputerPath({ path: "~", dirs })).toBe(`${H}/users/7`);
|
||||
expect(resolveComputerPath({ path: "", dirs })).toBe(`${H}/users/7`);
|
||||
});
|
||||
|
||||
test("absolute paths inside the roots pass", () => {
|
||||
expect(resolveComputerPath({ path: `${W}/bots/3/notes.md`, dirs })).toBe(`${W}/bots/3/notes.md`);
|
||||
expect(resolveComputerPath({ path: `${W}/workspaces/2/x/`, dirs })).toBe(`${W}/workspaces/2/x`);
|
||||
expect(resolveComputerPath({ path: `${H}/notes.md`, dirs })).toBe(`${H}/notes.md`);
|
||||
expect(resolveComputerPath({ path: `${H}/workspaces/2/x/`, dirs })).toBe(`${H}/workspaces/2/x`);
|
||||
expect(resolveComputerPath({ path: "workspaces/2", dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }) })).toBe(
|
||||
`${H}/users/7/workspaces/2`,
|
||||
);
|
||||
});
|
||||
|
||||
test("the real paths they link to pass too, given back as the bot sees them", () => {
|
||||
expect(resolveComputerPath({ path: `${W}/bots/3/users/7/a`, dirs })).toBe(`${H}/users/7/a`);
|
||||
expect(resolveComputerPath({ path: `${W}/workspaces/2/x`, dirs })).toBe(`${H}/workspaces/2/x`);
|
||||
});
|
||||
|
||||
test("anything outside is refused", () => {
|
||||
for (const path of [
|
||||
"/home/gem/x.txt",
|
||||
"/home/cb-3/.cobble/env",
|
||||
"/home/cb-3",
|
||||
"/etc/passwd",
|
||||
"../../../4/a",
|
||||
"../8/secret",
|
||||
"../../..",
|
||||
`${W}/bots/4`,
|
||||
"/home/cb-4/workspace",
|
||||
`${H}/users/8/a`,
|
||||
`${W}/bots/3/users/8/a`,
|
||||
`${W}/bots/30`,
|
||||
`${W}/workspaces/5`,
|
||||
`${H}/workspaces/5`,
|
||||
"~/../../../../x",
|
||||
"a\0b",
|
||||
]) {
|
||||
@@ -63,19 +82,29 @@ describe("resolveComputerPath", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the bot-wide folder and its users folder itself pass", () => {
|
||||
expect(resolveComputerPath({ path: "..", dirs })).toBe(`${W}/bots/3/users`);
|
||||
expect(resolveComputerPath({ path: "../..", dirs })).toBe(`${W}/bots/3`);
|
||||
test("outside a workspace no workspace folder is the run's", () => {
|
||||
const alone = computerRunDirs({ bot_id: 3, user_id: 7 });
|
||||
|
||||
expect(() => resolveComputerPath({ path: `${H}/workspaces/2`, dirs: alone })).toThrow();
|
||||
});
|
||||
|
||||
test("the coordinator reaches any bot's folder", () => {
|
||||
test("the bot-wide folder and its users folder itself pass", () => {
|
||||
expect(resolveComputerPath({ path: "..", dirs })).toBe(`${H}/users`);
|
||||
expect(resolveComputerPath({ path: "../..", dirs })).toBe(H);
|
||||
});
|
||||
|
||||
test("the coordinator reaches any bot's folder, by either spelling", () => {
|
||||
const coordinator = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1 });
|
||||
|
||||
expect(resolveComputerPath({ path: `${W}/bots/3/report.md`, dirs: coordinator })).toBe(`${W}/bots/3/report.md`);
|
||||
expect(resolveComputerPath({ path: `${H}/report.md`, dirs: coordinator })).toBe(`${W}/bots/3/report.md`);
|
||||
expect(() => resolveComputerPath({ path: "/home/gem/.config", dirs: coordinator })).toThrow();
|
||||
expect(() => resolveComputerPath({ path: "/home/cb-3/.cobble", dirs: coordinator })).toThrow();
|
||||
});
|
||||
|
||||
test("workspace-relative names", () => {
|
||||
expect(computerWorkspaceRelative({ absolute: `${W}/bots/3/users/7/seo` })).toBe("bots/3/users/7/seo");
|
||||
expect(computerWorkspaceRelative({ absolute: `${H}/users/7/seo` })).toBe("bots/3/users/7/seo");
|
||||
expect(computerWorkspaceRelative({ absolute: `${H}/workspaces/2/x` })).toBe("workspaces/2/x");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import path from "node:path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
|
||||
|
||||
/**
|
||||
* Where one run may work on a computer, every path absolute inside the
|
||||
* computer's workspace (`AppData.ComputerWorkspaceDir`, the only directory
|
||||
* mounted from the data volume).
|
||||
* Where one run may work on a computer, every path absolute and as the run
|
||||
* sees it. Only the computer's workspace (`AppData.ComputerWorkspaceDir`)
|
||||
* is mounted from the data volume. A worker sees its folders through its
|
||||
* own home: `/home/cb-<bot>/workspace` is a link to `bots/<bot>` in the
|
||||
* workspace, and `workspaces/<id>` in it a link to the workspace's shared
|
||||
* folder (`computerWorkspacePath` turns either spelling into the real
|
||||
* one). The coordinator works in the workspace itself.
|
||||
*/
|
||||
export type ComputerRunDirs = {
|
||||
/**
|
||||
@@ -13,16 +19,18 @@ export type ComputerRunDirs = {
|
||||
*/
|
||||
workspace: string;
|
||||
/**
|
||||
* Where the run starts and where a relative path lands: the user's
|
||||
* folder in the bot's (`bots/<bot>/users/<user>`).
|
||||
* Where the run starts, its `HOME`, and where a relative path lands:
|
||||
* the user's folder in the bot's (`users/<user>`).
|
||||
*/
|
||||
cwd: string;
|
||||
/**
|
||||
* The bot's own folder (`bots/<bot>`).
|
||||
* The bot's own folder: a worker's `/home/cb-<bot>/workspace`, the
|
||||
* coordinator's `bots/<bot>` in the workspace.
|
||||
*/
|
||||
bot_dir: string;
|
||||
/**
|
||||
* The workspace's shared folder (`workspaces/<id>`), in a workspace.
|
||||
* The workspace's shared folder, in a workspace: a worker's
|
||||
* `workspaces/<id>` inside its own, the coordinator's in the workspace.
|
||||
*/
|
||||
shared_dir: string | null;
|
||||
/**
|
||||
@@ -62,9 +70,11 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The folders a run works in on a computer: the user's own inside the
|
||||
* bot's (`bots/<bot>/users/<user>`, where it starts), the bot's own
|
||||
* (`bots/<bot>`, for work that is the same for every user) and, in a
|
||||
* workspace, the folder its bots share (`workspaces/<id>`).
|
||||
* bot's (`users/<user>`, where it starts), the bot's own (for work that is
|
||||
* the same for every user) and, in a workspace, the folder its bots share.
|
||||
* A worker's are under `/home/cb-<bot>/workspace` (its account's home
|
||||
* stays in the container, only that folder is kept); the coordinator's
|
||||
* are in the computer's workspace (`bots/<bot>`, `workspaces/<id>`).
|
||||
*/
|
||||
export default function computerRunDirs({
|
||||
bot_id,
|
||||
@@ -73,10 +83,14 @@ export default function computerRunDirs({
|
||||
workspace_id,
|
||||
}: Params): ComputerRunDirs {
|
||||
const workspace = AppData.ComputerWorkspaceDir;
|
||||
const bot_dir = path.posix.join(workspace, "bots", String(Number(bot_id)));
|
||||
const is_coordinator = bot_kind == "coordinator";
|
||||
const in_workspace = Number(workspace_id) > 0;
|
||||
const bot_dir = is_coordinator
|
||||
? path.posix.join(workspace, "bots", String(Number(bot_id)))
|
||||
: computerWorkerAccount({ bot_id }).workspace;
|
||||
const cwd = path.posix.join(bot_dir, "users", String(Number(user_id)));
|
||||
const shared_dir = Number(workspace_id) > 0
|
||||
? path.posix.join(workspace, "workspaces", String(Number(workspace_id)))
|
||||
const shared_dir = in_workspace
|
||||
? path.posix.join(is_coordinator ? workspace : bot_dir, "workspaces", String(Number(workspace_id)))
|
||||
: null;
|
||||
|
||||
return {
|
||||
@@ -84,13 +98,11 @@ export default function computerRunDirs({
|
||||
cwd,
|
||||
bot_dir,
|
||||
shared_dir,
|
||||
roots: bot_kind == "coordinator"
|
||||
? [workspace]
|
||||
: [bot_dir, ...(shared_dir ? [shared_dir] : [])],
|
||||
roots: is_coordinator ? [workspace] : [bot_dir, ...(shared_dir ? [shared_dir] : [])],
|
||||
user_id: Number(user_id),
|
||||
run_as: bot_kind == "coordinator"
|
||||
run_as: is_coordinator
|
||||
? null
|
||||
: { bot_id: Number(bot_id), workspace_id: Number(workspace_id) > 0 ? Number(workspace_id) : null },
|
||||
: { bot_id: Number(bot_id), workspace_id: in_workspace ? Number(workspace_id) : null },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -105,8 +117,11 @@ export function isInsideDir({ parent, child }: { parent: string; child: string }
|
||||
* Turns a path a bot gave a computer tool into the absolute one it means,
|
||||
* only when it is one of the run's: a relative path (or `~`, which the
|
||||
* run's shells read as its folder) lands in `cwd`, an absolute one must be
|
||||
* inside `roots`, and another user's folder in a bot's is refused. Throws
|
||||
* an `AppError` the bot gets back as the tool's error.
|
||||
* inside `roots`, and another user's folder in a bot's is refused. Checked
|
||||
* on the real path (`computerWorkspacePath`), so a worker may also give
|
||||
* one under the computer's workspace (what `pwd -P` or a script's own cwd
|
||||
* prints), and returned as the run sees it (`computerRunPath`). Throws an
|
||||
* `AppError` the bot gets back as the tool's error.
|
||||
*/
|
||||
export function resolveComputerPath({
|
||||
path: requested,
|
||||
@@ -130,22 +145,47 @@ export function resolveComputerPath({
|
||||
: path.posix.join(dirs.cwd, raw || "."),
|
||||
).replace(/(.)\/+$/, "$1");
|
||||
|
||||
if (!isComputerPathAllowed({ absolute, dirs })) {
|
||||
const real = computerWorkspacePath({ absolute });
|
||||
|
||||
if (!isComputerPathAllowed({ real, dirs })) {
|
||||
throw new AppError(
|
||||
`${absolute} is outside your folders on this computer. Work in ${dirs.cwd} (this user's), ${dirs.roots.join(" or ")} for work every user shares.`,
|
||||
);
|
||||
}
|
||||
|
||||
return absolute;
|
||||
return computerRunPath({ real, dirs });
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an absolute, normalized path is one the run may touch.
|
||||
* A real path on the computer (`computerWorkspacePath`) as the run sees
|
||||
* it: for a worker, its folder and the workspace's shared one through its
|
||||
* own home (`/home/cb-<bot>/workspace/...`).
|
||||
*/
|
||||
function isComputerPathAllowed({ absolute, dirs }: { absolute: string; dirs: ComputerRunDirs }) {
|
||||
if (!dirs.roots.some((root) => isInsideDir({ parent: root, child: absolute }))) return false;
|
||||
export function computerRunPath({ real, dirs }: { real: string; dirs: ComputerRunDirs }) {
|
||||
if (!dirs.run_as) return real;
|
||||
|
||||
const relative = path.posix.relative(dirs.workspace, absolute).split("/");
|
||||
for (const dir of [dirs.shared_dir, dirs.bot_dir]) {
|
||||
if (!dir) continue;
|
||||
|
||||
const dir_real = computerWorkspacePath({ absolute: dir });
|
||||
|
||||
if (isInsideDir({ parent: dir_real, child: real })) {
|
||||
return `${dir}${real.slice(dir_real.length)}`;
|
||||
}
|
||||
}
|
||||
|
||||
return real;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a real, normalized path is one the run may touch.
|
||||
*/
|
||||
function isComputerPathAllowed({ real, dirs }: { real: string; dirs: ComputerRunDirs }) {
|
||||
const roots = dirs.roots.map((root) => computerWorkspacePath({ absolute: root }));
|
||||
|
||||
if (!roots.some((root) => isInsideDir({ parent: root, child: real }))) return false;
|
||||
|
||||
const relative = path.posix.relative(dirs.workspace, real).split("/");
|
||||
|
||||
/**
|
||||
* `bots/<bot>/users/<user>/...`: only the run's own user.
|
||||
@@ -158,9 +198,10 @@ function isComputerPathAllowed({ absolute, dirs }: { absolute: string; dirs: Com
|
||||
}
|
||||
|
||||
/**
|
||||
* A path inside the computer's workspace as a folder ref or the files
|
||||
* browser names it: relative to the workspace root, no leading slash.
|
||||
* A path inside the computer's workspace as the files browser names it:
|
||||
* relative to the workspace root, no leading slash. A worker's
|
||||
* `/home/cb-<bot>/workspace/...` is read as the real path it links to.
|
||||
*/
|
||||
export function computerWorkspaceRelative({ absolute }: { absolute: string }) {
|
||||
return path.posix.relative(AppData.ComputerWorkspaceDir, absolute);
|
||||
return path.posix.relative(AppData.ComputerWorkspaceDir, computerWorkspacePath({ absolute }));
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* A worker bot's own account on a computer, as the computer's agent makes
|
||||
* it (`computer/agent/run-user-for.ts`; keep both alike): `cb-<bot id>`,
|
||||
* without sudo, its home inside the container (the env files live there).
|
||||
* without sudo. Its home stays inside the container (the env files live
|
||||
* there); only `workspace` in it is kept, a link the agent makes to the
|
||||
* bot's folder on the computer's mounted workspace (`bots/<bot id>`).
|
||||
*/
|
||||
export default function computerWorkerAccount({ bot_id }: { bot_id: number | string }) {
|
||||
const name = `cb-${Number(bot_id)}`;
|
||||
const home = `/home/${name}`;
|
||||
|
||||
return { name, home: `/home/${name}` };
|
||||
return { name, home, workspace: `${home}/workspace` };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import computerWorkspacePath from "./computer-workspace-path";
|
||||
|
||||
const W = "/home/gem/workspace";
|
||||
|
||||
describe("computerWorkspacePath", () => {
|
||||
test("a worker's kept folder is the bot's folder in the workspace", () => {
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace" })).toBe(`${W}/bots/3`);
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/users/7/a/" })).toBe(`${W}/bots/3/users/7/a`);
|
||||
});
|
||||
|
||||
test("a workspace folder inside it is the shared one", () => {
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/workspaces/2/x" })).toBe(`${W}/workspaces/2/x`);
|
||||
expect(computerWorkspacePath({ absolute: `${W}/bots/3/workspaces/2` })).toBe(`${W}/workspaces/2`);
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/workspaces" })).toBe(`${W}/bots/3/workspaces`);
|
||||
});
|
||||
|
||||
test("the rest of a worker's home and other paths stay as they are", () => {
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/.cobble/env" })).toBe("/home/cb-3/.cobble/env");
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace2" })).toBe("/home/cb-3/workspace2");
|
||||
expect(computerWorkspacePath({ absolute: `${W}/bots/3/users/7` })).toBe(`${W}/bots/3/users/7`);
|
||||
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/../../gem/x" })).toBe("/home/gem/x");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
/**
|
||||
* The real place of an absolute path on a computer, inside its mounted
|
||||
* workspace (`AppData.ComputerWorkspaceDir`). A worker sees its folders
|
||||
* through its home: `/home/cb-<bot>/workspace` is a link to `bots/<bot>`,
|
||||
* and `workspaces/<id>` inside that a link to the workspace's shared
|
||||
* `workspaces/<id>`, so both spellings (and the shared folder reached
|
||||
* through the bot's link) come out as the one real path. Anything else is
|
||||
* returned normalized, as it is.
|
||||
*/
|
||||
export default function computerWorkspacePath({ absolute }: { absolute: string }) {
|
||||
const workspace = AppData.ComputerWorkspaceDir;
|
||||
const normal = normalizeAbsolute({ absolute });
|
||||
const home = normal.match(/^\/home\/cb-(\d+)\/workspace(\/.*)?$/);
|
||||
const real = home ? `${workspace}/bots/${Number(home[1])}${home[2] || ""}` : normal;
|
||||
const shared = real.match(new RegExp(`^${escapeRegExp(workspace)}/bots/\\d+/workspaces/(\\d+)(/.*)?$`));
|
||||
|
||||
return shared ? `${workspace}/workspaces/${Number(shared[1])}${shared[2] || ""}` : real;
|
||||
}
|
||||
|
||||
/**
|
||||
* `path.posix.normalize` for an absolute path, without `node:path` (folder
|
||||
* refs read this in the browser): `.` and `..` resolved, slashes merged,
|
||||
* no trailing one.
|
||||
*/
|
||||
function normalizeAbsolute({ absolute }: { absolute: string }) {
|
||||
const segments: string[] = [];
|
||||
|
||||
for (const segment of absolute.split("/")) {
|
||||
if (!segment || segment == ".") continue;
|
||||
|
||||
if (segment == "..") segments.pop();
|
||||
else segments.push(segment);
|
||||
}
|
||||
|
||||
return `/${segments.join("/")}`;
|
||||
}
|
||||
|
||||
function escapeRegExp(text: string) {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
@@ -105,3 +105,22 @@ describe("linkComputerRefs", () => {
|
||||
expect(parseFolderRefHref({ href: linked.match(/\((#file-[^)]+)\)/)?.[1] })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("computer folder refs written as the bot sees them", () => {
|
||||
test("a worker's kept folder and the computer's workspace open their real place", () => {
|
||||
const open = (path: string) => parseFolderRefHref({ href: folderRefHref({ volume: "computer", owner_id: 3, path }) })?.path;
|
||||
|
||||
expect(open("/home/cb-7/workspace/users/1/seo")).toBe("bots/7/users/1/seo");
|
||||
expect(open("home/cb-7/workspace/workspaces/2/brief")).toBe("workspaces/2/brief");
|
||||
expect(open("/home/gem/workspace/bots/7/notes")).toBe("bots/7/notes");
|
||||
expect(open("/home/gem/workspace")).toBe("");
|
||||
expect(open("bots/7/users/1")).toBe("bots/7/users/1");
|
||||
expect(open("seo/raw")).toBe("seo/raw");
|
||||
});
|
||||
|
||||
test("other volumes keep the path as written", () => {
|
||||
expect(parseFolderRefHref({ href: folderRefHref({ volume: "bot", owner_id: 3, path: "home/cb-7/workspace" }) })?.path).toBe(
|
||||
"home/cb-7/workspace",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+21
-2
@@ -9,6 +9,8 @@
|
||||
* (`fileRef`), which is what downloads. There is no guessing from the
|
||||
* name's extension: the ref says which one it is.
|
||||
*/
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import computerWorkspacePath from "./computer-workspace-path";
|
||||
import {
|
||||
isStorageVolume,
|
||||
parseStorageSpec,
|
||||
@@ -38,6 +40,23 @@ function cleanPath({ path }: { path?: string | null }) {
|
||||
return (path || "").trim().replace(/^\/+|\/+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* A path in a folder ref, as the files browser names it. On a computer a
|
||||
* bot may write the folder as it sees it there (`/home/cb-3/workspace/...`,
|
||||
* `/home/gem/workspace/...`): that becomes its real place in the
|
||||
* computer's workspace (`computerWorkspacePath`), relative to it.
|
||||
*/
|
||||
function refPath({ volume, path }: { volume: string; path: string }) {
|
||||
if (volume != "computers") return path;
|
||||
|
||||
const workspace = AppData.ComputerWorkspaceDir;
|
||||
const real = computerWorkspacePath({ absolute: `/${path}` });
|
||||
|
||||
if (real == workspace) return "";
|
||||
|
||||
return real.startsWith(`${workspace}/`) ? real.slice(workspace.length + 1) : path;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a bot names a folder in a message. The path is written as it is; the
|
||||
* chat encodes it into the link.
|
||||
@@ -91,7 +110,7 @@ export function parseFolderRefHref({
|
||||
|
||||
return {
|
||||
spec: { volume, owner_id: Math.trunc(owner_id) },
|
||||
path: rest.join(":").replace(/^\/+|\/+$/g, ""),
|
||||
path: refPath({ volume, path: rest.join(":").replace(/^\/+|\/+$/g, "") }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -114,5 +133,5 @@ export function folderRefUrl({ volume, owner_id, path }: RefParams) {
|
||||
|
||||
if (!spec) return StorageBrowserPath;
|
||||
|
||||
return storageSpecHref({ spec, path });
|
||||
return storageSpecHref({ spec, path: refPath({ volume: known, path: cleanPath({ path }) }) });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { FilePreviewItem } from "@/src/types";
|
||||
|
||||
/**
|
||||
* Where a file stands in a gallery, by its URL, or -1 when it isn't in it
|
||||
* (the preview then shows it alone, without Previous and Next).
|
||||
*/
|
||||
export default function galleryIndex({ gallery, url }: { gallery?: FilePreviewItem[]; url: string }) {
|
||||
if (!gallery?.length || !url) return -1;
|
||||
|
||||
return gallery.findIndex((item) => item.url == url);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ function call(overrides: Partial<MessageDetailsCall>): MessageDetailsCall {
|
||||
model_slug: "deepseek/deepseek-v4",
|
||||
model_name: "DeepSeek V4",
|
||||
prompt_tokens: 100,
|
||||
cached_tokens: 0,
|
||||
completion_tokens: 10,
|
||||
cost: null,
|
||||
settings: null,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user