Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0885e12a8b | ||
|
|
7da9003e7b | ||
|
|
b609d72888 | ||
|
|
8e1084263c | ||
|
|
e4e19ade1b | ||
|
|
5b09e7a8db | ||
|
|
1a2e7a25bb | ||
|
|
c892cda0eb | ||
|
|
b8fd60608d |
@@ -68,7 +68,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Cron
|
||||
|
||||
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `prune-logs`.
|
||||
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
|
||||
|
||||
### Admin CRUD API
|
||||
|
||||
@@ -94,12 +94,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face and task (`session-messages`, `use-reply-catch-up`), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`.
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
|
||||
@@ -121,7 +122,8 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`) and chatroom turns. A plan that can't be written or read starts the run unplanned, never blocks it.
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
|
||||
@@ -143,7 +145,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
|
||||
- Only `/home/gem/workspace` is mounted, from `DATA_DIR/computers/<id>` (with `bots/`, `workspaces/`, marker `AppData.ComputerWorkspaceMarker`), plus the browser profile; the rest of home lives in the container.
|
||||
- **Browser profile:** `DATA_DIR/computer-browsers/<id>` mounted at `~/.cobble-browser`, which the agent starts Chrome with (`--user-data-dir`, `--password-store=basic` so the cookies' key is the same in every container), so logins, extensions and site permissions survive restarts and recreates. Seed prefs (`computer-browser-preferences.ts`) are written only when missing; stale `Singleton*` links are removed before each provision and before each Chrome start. The agent stops Chrome with TERM on `docker stop`, so the profile is saved. **Its regenerable cache is cleared at every start** (`pruneProfileCache`: HTTP and code caches, shader/GPU caches, extension assets, the component updater's CRX cache, only while no browser runs) and the HTTP cache is capped at `DiskCacheMaxBytes` (`--disk-cache-size`), so the mounted profile holds logins rather than gigabytes. **An idle browser is parked:** the virtual screen has no GPU or window manager, so the tab in front is always on show and drawn in software at full rate (one animated site took a core or two); after `COBBLE_BROWSER_PARK_AFTER_SECONDS` (default 180) without a `/mcp` call or screen view the agent puts a blank tab in front of each site on show (`createBrowserParking`, over its own CDP client), and the next `/mcp` call or view brings them back first. Pages are composited in software (`--disable-gpu-compositing`, WebGL unchanged) and the policy sets `TabDiscardingExceptions: ["*"]` so a parked tab never reloads. Bumping `AppData.ComputerWorkspaceLayout` recreates every computer once (`migrateComputerLayout`, skipped while a job runs on it). Default extensions (`ComputerBrowserExtensions`: Cookie-Editor, `normal_installed`: can be turned off, not removed) come from a managed policy written as root into the running container (`syncComputerBrowserPolicy`, on provision and every `sync-computers` run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (`pickReachableAddress`).
|
||||
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: `--disable-gpu`, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at `LightweightFrameRate` fps), extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Chrome reads only one `--disable-features=`/`--enable-features=`, so `browserArgs` merges the agent's with the extra flags' (`mergeFeatureFlags`). Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
|
||||
- **The workspace has a limit** (`computer_workspace_quota_mb`, Settings > General, default `AppData.ComputerWorkspaceQuotaMb`, 0 = none): it is the one folder on a computer mounted from the data volume, so it is what can fill the host. The agent only measures it (`GET /api/usage` -> `grabComputerUsage`, `du` cached 10s); the app refuses a write that would pass it (`computerWorkspaceRoomError` in `computer_write_file`/`computer_edit_file`), reports it after `computer_bash` and after a browser call that wrote a file (`computerWorkspaceFullWarning`, screenshots and downloads included) and bash still works, since it is how a bot cleans up. A run's caches go to the account's own home inside the container, never its folder (`computerCacheEnv`).
|
||||
- **The workspace has a limit** (`computer_workspace_quota_mb`, Settings > General, default `AppData.ComputerWorkspaceQuotaMb`, 0 = none): it is the one folder on a computer mounted from the data volume, so it is what can fill the host. The agent measures it (`GET /api/usage` -> `grabComputerUsage`, `du` cached 10s, per-folder figures with it: `bots/<id>` and `workspaces/<id>`, highest first); the app refuses a write that would pass it (`computerWorkspaceRoomError` in `computer_write_file`/`computer_edit_file`), reports it after `computer_bash` and after a browser call that wrote a file (`computerWorkspaceFullWarning`, screenshots and downloads included) and bash still works, since it is how a bot cleans up. A refusal names the folder holding the space and whether the run can clear it (`computerWorkspaceSpace`: its own folder or its workspace's, else another bot's, which it can only report); nothing prunes that folder, so the daily `warn-computer-workspaces` cron logs an install past the quota rather than letting it fill quietly. A run's caches go to the account's own home inside the container, never its folder (`computerCacheEnv`).
|
||||
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
|
||||
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
|
||||
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
|
||||
@@ -163,7 +165,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
|
||||
|
||||
### Tasks (the to-do tracker)
|
||||
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
|
||||
### Envs
|
||||
|
||||
@@ -215,21 +217,21 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`) for a saving turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
|
||||
|
||||
### Token usage
|
||||
|
||||
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`).
|
||||
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`, including `limits`: the steps, run tokens and context the run was held to, so a bot can explain a cost against them with `read_message_usage`).
|
||||
- Attribution through an `AsyncLocalStorage` scope (`src/harness/usage/harness-usage-scope.ts`) entered once in `run-bot-job.ts`; merged, not replaced; `null` clears a field. `withUsageScope` / `runWithFallbackScope` for calls outside a run. No owner, no row.
|
||||
- Every failed model call also writes a `harness_call_failures` row (`recordHarnessFailure`, beside the log in `withCandidates`: model, pick, HTTP status, the provider's reason, rest), same attribution, no foreign keys, pruned with the logs' retention by `prune-logs`.
|
||||
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons).
|
||||
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons, and the run's calls counted by tool from `bot_messages.tool_log` in `MessageToolsRollup`: 242 model calls read differently once it says `computer_bash` 210, `start_task` 0).
|
||||
- `/admin/usage` (crew managers). **Days are local, not UTC:** group with `date(created_at / 1000, 'unixepoch', 'localtime')`; never name a local day with `toISOString().slice(0, 10)` (`bucket-usage-days.test.ts` pins this). Bars use static `h-*` classes from `(data)/usage-bar-heights.ts`.
|
||||
|
||||
### Installer and release
|
||||
@@ -246,7 +248,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
|
||||
- **Rail pages** (`src/dict/rail-pages-dict.ts`): Routines, Files, Usage (crew managers), Activity (`/admin/logs`, super admin), Help (`(data)/help-topics.ts`). Visibility via `canSeeRailItem` for both the popover and the aside.
|
||||
- **Settings** (`src/dict/settings-pages-dict.ts`; add a sub page = folder + dict entry): `general` (theme per device, plus super-admin app settings: prompt append, run limits, skill limits; crew-manager storage quota; running version), `setup` (super admin; shares the Models page's server props and `useModelsOverview`), `profile`, `notifications`, `change-password`, `secrets`, `browsers`, `models`, `environment`, `backups` and `database` (super admin), `bots`, `workspaces`, `computers`, `mcps`, `tools`, `skills`, `knowledgebases` (crew managers), `users` (`canListUsers`).
|
||||
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
|
||||
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Each group of General also has a page of its own (`/admin/settings/general/<section>`, keyed in `src/dict/general-settings-dict.ts`, linked from the group's title): anyone who may read it sees its values (`SettingsReadOnlyValues`), only its owning role gets the form. A bot points at one with `read_settings` and a `[setting:section:field]` ref, so every limit refusal or cost answer names the page and value to change. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
|
||||
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. What an archive leaves out is decided in one place, `listArchiveExclusions` (`--no-wildcards --exclude-from`): `DATA_DIR/computers` (a computer's workspace is the computer's own state, so `AppData.DataBackupsKept` copies of it never fill the volume and a restore neither empties nor copies that folder), each Chrome profile's caches (the profile is kept for its logins, a few MB against hundreds of MB of HTTP and code caches), `db/.backups` (that is the database snapshots' own list) and `.bun-sqlite`. A restore keeps the running install's `db/.backups` (copied aside and put back), since no archive carries them. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process. **A database snapshot restore restarts too** (also a background run, `db_restore`): `bun-sqlite import` swaps in a new file from another process, and this process's handle would stay on the old one, so nothing may be written to the database between a restore and the restart (log entries go through `queueBootLog`, written by `flushBootLogs` at boot).
|
||||
- **Database browser:** strictly read-only; values cut in SQL; state in the address via `databaseHref`.
|
||||
- Add flow (`(partials)/add-flow.tsx`) from the rail's Add icon: bot, workspace, computer (super admin). Page heroes use `AdminHero`.
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"@types/sanitize-html": "^2.16.2",
|
||||
"@types/turndown": "^5.0.6",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"marked": "17.0.6",
|
||||
"tailwindcss": "^4.3.3",
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -4,11 +4,17 @@ import sendJson from "./send-json";
|
||||
import { workspaceUsage } from "./workspace-usage";
|
||||
|
||||
/**
|
||||
* `GET /api/usage`: how much the computer's workspace holds
|
||||
* (`workspaceUsage`). Only the size: what may be written there is the
|
||||
* `GET /api/usage`: what the computer's workspace holds, and its biggest
|
||||
* folders (`workspaceUsage`). Only sizes: what may be written there is the
|
||||
* app's call (`grabComputerWorkspaceQuotaBytes`), so changing the limit
|
||||
* needs no new container.
|
||||
* needs no new container. The folders are how a full one is told apart from
|
||||
* a bot's own overrun, which the app says in its refusal.
|
||||
*/
|
||||
export default async function handleUsage({ res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
sendJson({ res, body: { used_bytes: await workspaceUsage(), workspace_dir: AgentConfig.WorkspaceDir } });
|
||||
const { bytes, folders } = await workspaceUsage();
|
||||
|
||||
sendJson({
|
||||
res,
|
||||
body: { used_bytes: bytes, workspace_dir: AgentConfig.WorkspaceDir, folders },
|
||||
});
|
||||
}
|
||||
@@ -2,11 +2,34 @@ import { execFile } from "node:child_process";
|
||||
import { AgentConfig } from "./config";
|
||||
|
||||
/**
|
||||
* When the workspace was last measured, and what it held: the whole
|
||||
* folder, every bot's and user's included, since that is what grows on the
|
||||
* data volume.
|
||||
* One folder inside the workspace, with what it holds: `bots/9` is a bot's
|
||||
* folder, `workspaces/3` a workspace's shared one.
|
||||
*/
|
||||
let measured = { bytes: 0, at: 0 };
|
||||
export type WorkspaceFolderUsage = {
|
||||
/**
|
||||
* Relative to the workspace root, e.g. `bots/9`.
|
||||
*/
|
||||
path: string;
|
||||
bytes: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the workspace holds, and the biggest folders in it. The whole
|
||||
* folder, every bot's and user's included, is what grows on the data
|
||||
* volume; the folders are what says whose it is.
|
||||
*/
|
||||
export type WorkspaceUsage = {
|
||||
bytes: number;
|
||||
folders: WorkspaceFolderUsage[];
|
||||
};
|
||||
|
||||
/**
|
||||
* When the workspace was last measured, and what it held. A measurement
|
||||
* that fails keeps the last one: reporting 0 would let writes through a
|
||||
* quota the app can't see (and `du` on a workspace full of small files can
|
||||
* outlast its timeout).
|
||||
*/
|
||||
let measured: { usage: WorkspaceUsage; at: number } | null = null;
|
||||
|
||||
/**
|
||||
* Measuring walks the whole workspace, so a run writing several files in a
|
||||
@@ -16,29 +39,99 @@ let measured = { bytes: 0, at: 0 };
|
||||
const CacheMs = 10_000;
|
||||
|
||||
/**
|
||||
* How many bytes the workspace holds, measured with `du` (which reads the
|
||||
* folders in C) and reused for `CacheMs`.
|
||||
* How many of the biggest folders are named: enough that the one filling
|
||||
* the volume is there, few enough to say in a sentence.
|
||||
*/
|
||||
export async function workspaceUsage() {
|
||||
if (measured.at && Date.now() - measured.at < CacheMs) return measured.bytes;
|
||||
const FoldersShown = 5;
|
||||
|
||||
measured = { bytes: await measureWorkspace(), at: Date.now() };
|
||||
/**
|
||||
* The workspace's folders whose size is reported: a bot's, a workspace's,
|
||||
* and anything else sitting at the top.
|
||||
*/
|
||||
const GroupedFolders = ["bots", "workspaces"];
|
||||
|
||||
return measured.bytes;
|
||||
/**
|
||||
* What the workspace holds, measured with `du` (which reads the folders in
|
||||
* C) and reused for `CacheMs`.
|
||||
*/
|
||||
export async function workspaceUsage(): Promise<WorkspaceUsage> {
|
||||
if (measured && Date.now() - measured.at < CacheMs) return measured.usage;
|
||||
|
||||
const usage = await measureWorkspace();
|
||||
|
||||
if (!usage) return measured?.usage || { bytes: 0, folders: [] };
|
||||
|
||||
measured = { usage, at: Date.now() };
|
||||
|
||||
return usage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace's size through `du` (bytes), 0 when it can't be read: a
|
||||
* missing folder holds nothing.
|
||||
* The workspace's size and its biggest folders through `du`, or null when
|
||||
* it can't be read.
|
||||
*/
|
||||
function measureWorkspace() {
|
||||
return new Promise<number>((resolve) => {
|
||||
execFile("du", ["-s", "-B1", "--", AgentConfig.WorkspaceDir], { timeout: 30_000 }, (error, stdout) => {
|
||||
if (error) return resolve(0);
|
||||
return new Promise<WorkspaceUsage | null>((resolve) => {
|
||||
execFile(
|
||||
"du",
|
||||
["-B1", "--max-depth=2", "--", AgentConfig.WorkspaceDir],
|
||||
{ timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
|
||||
(error, stdout) => {
|
||||
if (error) return resolve(null);
|
||||
|
||||
const bytes = Number(String(stdout).trim().split(/\s+/)[0]);
|
||||
|
||||
resolve(Number.isFinite(bytes) && bytes > 0 ? bytes : 0);
|
||||
});
|
||||
resolve(parseDu(String(stdout)));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `du`'s lines (`<bytes>\t<path>`) as the whole workspace and the folders
|
||||
* that make it up: each bot's and each workspace's own, and whatever else
|
||||
* sits at the top. A passthrough folder (`bots`, `workspaces`) is only
|
||||
* counted through its children.
|
||||
*/
|
||||
function parseDu(stdout: string): WorkspaceUsage {
|
||||
const root = AgentConfig.WorkspaceDir.replace(/\/+$/, "");
|
||||
const deep: WorkspaceFolderUsage[] = [];
|
||||
const shallow = new Map<string, number>();
|
||||
let bytes = 0;
|
||||
|
||||
for (const line of stdout.split("\n")) {
|
||||
const [size, path] = line.split("\t");
|
||||
const value = Number(size);
|
||||
|
||||
if (!path || !Number.isFinite(value) || value <= 0) continue;
|
||||
if (path == root) {
|
||||
bytes = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
const relative = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : "";
|
||||
const [top, second] = relative.split("/");
|
||||
|
||||
if (!top || !GroupedFolders.includes(top)) {
|
||||
shallow.set(relative, value);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (second) deep.push({ path: relative, bytes: value });
|
||||
else shallow.set(relative, value);
|
||||
}
|
||||
|
||||
const folders = [...deep, ...[...shallow].map(([path, value]) => ({ path, bytes: value }))];
|
||||
|
||||
/**
|
||||
* A passthrough folder with children is only counted through them: its
|
||||
* own total would show every bot's folder twice.
|
||||
*/
|
||||
const grouped = new Set(deep.map((folder) => folder.path.split("/")[0]));
|
||||
|
||||
return {
|
||||
bytes: bytes || folders.reduce((total, folder) => total + folder.bytes, 0),
|
||||
folders: folders
|
||||
.filter((folder) => !(shallow.has(folder.path) && grouped.has(folder.path)))
|
||||
.sort((left, right) => right.bytes - left.bytes)
|
||||
.slice(0, FoldersShown),
|
||||
};
|
||||
}
|
||||
@@ -1797,6 +1797,48 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_suggestions",
|
||||
tableDescription: `Next steps a bot suggests under its answer (\`suggest_next_steps\`): buttons that put the step in the user's input. Unlike \`bot_questions\`, nothing waits on them`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "title",
|
||||
fieldDescription: `A short heading for the row of buttons; empty for "Next steps"`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "steps",
|
||||
fieldDescription: `JSON array of the suggested steps, each put in the user's input when clicked`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `The user they were suggested to, who alone reads them. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot that suggested them. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The conversation they were suggested in. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_suggestions_session_id",
|
||||
indexTableFields: ["session_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_graphics",
|
||||
tableDescription: `A visual a bot made for a user (a chart, diagram, timeline or report) as one self-contained HTML document. Served by the app at \`/graphics/<id>\` in a sandbox with no network and an origin of its own, so it never runs with the viewer's session. Per user like the conversation it was made in; an edit replaces the HTML and bumps \`version\``,
|
||||
@@ -2646,6 +2688,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
options: [0, 1],
|
||||
defaultValue: 1,
|
||||
},
|
||||
{
|
||||
fieldName: "context_length",
|
||||
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "last_synced_at",
|
||||
fieldDescription: `Unix timestamp of the last model list sync`,
|
||||
|
||||
+45
-1
@@ -24,6 +24,7 @@ export const BunSQLiteTables = [
|
||||
"secret_requests",
|
||||
"install_requests",
|
||||
"bot_questions",
|
||||
"bot_suggestions",
|
||||
"bot_graphics",
|
||||
"workspaces",
|
||||
"workspace_bots",
|
||||
@@ -1164,6 +1165,45 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
/**
|
||||
* A short heading for the row of buttons; empty for "Next steps"
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* JSON array of the suggested steps, each put in the user's input when clicked
|
||||
*/
|
||||
steps?: string;
|
||||
/**
|
||||
* The user they were suggested to, who alone reads them. Not a foreign key
|
||||
*/
|
||||
user_id?: number | "";
|
||||
/**
|
||||
* The bot that suggested them. Not a foreign key
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The conversation they were suggested in. Not a foreign key
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The session's workspace; null for the bot's own chat. Not a foreign key
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_GRAPHICS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -1625,6 +1665,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
|
||||
*/
|
||||
api_key?: string;
|
||||
enabled?: 0 | 1 | "";
|
||||
/**
|
||||
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
|
||||
*/
|
||||
context_length?: number | "";
|
||||
/**
|
||||
* Unix timestamp of the last model list sync
|
||||
*/
|
||||
@@ -2822,4 +2866,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.18.7",
|
||||
"version": "0.18.10",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
@@ -35,6 +35,7 @@
|
||||
"@types/sanitize-html": "^2.16.2",
|
||||
"@types/turndown": "^5.0.6",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"marked": "17.0.6",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
/**
|
||||
* The plan a task run writes for itself before its first step
|
||||
* (`planBotTask`). Validated because it comes back from a model: anything
|
||||
* that doesn't fit starts the run unplanned instead of steered by
|
||||
* nonsense.
|
||||
*/
|
||||
export const BotTaskPlanSchema = z.object({
|
||||
goal: z.string().trim().min(1).max(AppData.BotTaskPlanTextMaxChars),
|
||||
gather: z.array(z.string().trim().min(1)).max(AppData.BotTaskPlanMaxGather).default([]),
|
||||
steps: z.array(z.string().trim().min(1)).min(1).max(AppData.BotTaskPlanMaxSteps),
|
||||
done: z.string().trim().max(AppData.BotTaskPlanTextMaxChars).default(""),
|
||||
});
|
||||
|
||||
export type BotTaskPlan = z.infer<typeof BotTaskPlanSchema>;
|
||||
@@ -1,10 +1,6 @@
|
||||
import {
|
||||
JobStepBrowserToolInfix,
|
||||
JobStepToolLabels,
|
||||
JobStepToolPrefixLabels,
|
||||
type BotJobUpdateKind,
|
||||
} from "@/src/dict/bot-queue-dict";
|
||||
import type { BotJobUpdateKind } from "@/src/dict/bot-queue-dict";
|
||||
import type { TextLoopStep } from "@/src/harness/text/run-text-loop";
|
||||
import toolLabel from "@/src/utils/tool-label";
|
||||
|
||||
/**
|
||||
* Longest step line kept: the chat shows one line per step.
|
||||
@@ -54,27 +50,3 @@ function firstLine({ text }: { text: string | null }) {
|
||||
|
||||
return line.length > MaxStepChars ? `${line.slice(0, MaxStepChars - 1)}…` : line;
|
||||
}
|
||||
|
||||
function toolLabel({ name }: { name: string }) {
|
||||
if (name.includes(JobStepBrowserToolInfix)) return JobStepToolPrefixLabels.browser_ as string;
|
||||
|
||||
const prefix = Object.keys(JobStepToolPrefixLabels).find((p) => name.startsWith(p));
|
||||
|
||||
return JobStepToolLabels[name] || (prefix && JobStepToolPrefixLabels[prefix]) || `Using ${readableToolName({ name })}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A tool name in words: `get_weather` reads "get weather", and an MCP
|
||||
* server's `<slug>__<tool>` reads "Exa search (web search exa)".
|
||||
*/
|
||||
function readableToolName({ name }: { name: string }) {
|
||||
const words = (part: string) => part.replace(/_+/g, " ").trim();
|
||||
const [server, ...rest] = name.split("__");
|
||||
const tool = words(rest.join(" "));
|
||||
|
||||
if (!tool) return words(name);
|
||||
|
||||
const server_words = words(server || "");
|
||||
|
||||
return `${server_words.charAt(0).toUpperCase()}${server_words.slice(1)} (${tool})`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import parseBotTaskPlan from "./parse-bot-task-plan";
|
||||
|
||||
const plan = {
|
||||
goal: "Ship the release notes",
|
||||
gather: ["docs/changelog.md"],
|
||||
steps: ["Read the changelog", "Write the notes", "Publish them"],
|
||||
done: "The notes are on the site",
|
||||
};
|
||||
|
||||
describe("parseBotTaskPlan", () => {
|
||||
test("reads a plan", () => {
|
||||
expect(parseBotTaskPlan({ text: JSON.stringify(plan) })).toEqual(plan);
|
||||
});
|
||||
|
||||
test("tolerates a code fence and a sentence around the object", () => {
|
||||
const fenced = `Here is the plan:\n\`\`\`json\n${JSON.stringify(plan)}\n\`\`\`\nReady.`;
|
||||
|
||||
expect(parseBotTaskPlan({ text: fenced })).toEqual(plan);
|
||||
});
|
||||
|
||||
test("fills what a plan may leave out", () => {
|
||||
expect(parseBotTaskPlan({ text: `{"goal":"G","steps":["one"]}` })).toEqual({
|
||||
goal: "G",
|
||||
gather: [],
|
||||
steps: ["one"],
|
||||
done: "",
|
||||
});
|
||||
});
|
||||
|
||||
test("is null when it isn't a plan", () => {
|
||||
expect(parseBotTaskPlan({})).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: null })).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: "" })).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: "I will just do it." })).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: "{nope" })).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: `{"goal":"G"}` })).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: `{"goal":"","steps":["one"]}` })).toBeNull();
|
||||
expect(parseBotTaskPlan({ text: `{"goal":"G","steps":[]}` })).toBeNull();
|
||||
});
|
||||
|
||||
test("caps how much a plan may ask for", () => {
|
||||
const too_many = {
|
||||
goal: "G",
|
||||
steps: Array.from({ length: AppData.BotTaskPlanMaxSteps + 1 }, (_, index) => `step ${index}`),
|
||||
};
|
||||
|
||||
expect(parseBotTaskPlan({ text: JSON.stringify(too_many) })).toBeNull();
|
||||
expect(
|
||||
parseBotTaskPlan({
|
||||
text: JSON.stringify({ ...too_many, steps: too_many.steps.slice(1), goal: "x".repeat(AppData.BotTaskPlanTextMaxChars + 1) }),
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { BotTaskPlanSchema, type BotTaskPlan } from "./bot-task-plan-schema";
|
||||
|
||||
/**
|
||||
* Reads the plan a planning turn answered with. Models wrap JSON in a code
|
||||
* fence or a sentence whatever the prompt says, so the object is cut out
|
||||
* of the answer first. Null when it isn't a plan: the run then starts the
|
||||
* way it always did, since a plan is an economy and never a gate.
|
||||
*/
|
||||
export default function parseBotTaskPlan({ text }: { text?: string | null }): BotTaskPlan | null {
|
||||
if (!text) return null;
|
||||
|
||||
const start = text.indexOf("{");
|
||||
const end = text.lastIndexOf("}");
|
||||
|
||||
if (start < 0 || end <= start) return null;
|
||||
|
||||
let value: unknown;
|
||||
|
||||
try {
|
||||
value = JSON.parse(text.slice(start, end + 1));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = BotTaskPlanSchema.safeParse(value);
|
||||
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { TaskPlanPrompt } from "@/src/data/harness-prompts";
|
||||
import type { HarnessCandidate, HarnessMessage } from "@/src/harness/types";
|
||||
import type { GenerateTextParams } from "@/src/harness/text/generate-text";
|
||||
import planBotTask from "./plan-bot-task";
|
||||
|
||||
const candidate = {
|
||||
key: "1:m",
|
||||
provider: { id: 1, kind: "openrouter", base_url: "https://x.test" },
|
||||
model: { slug: "m", input_modalities: ["text"], output_modalities: ["text"], supports_tools: true },
|
||||
source: "auto",
|
||||
} as HarnessCandidate;
|
||||
|
||||
const plan = {
|
||||
goal: "Ship the release notes",
|
||||
gather: ["docs/changelog.md"],
|
||||
steps: ["Read the changelog", "Write the notes"],
|
||||
done: "The notes are on the site",
|
||||
};
|
||||
|
||||
function fakeGenerate({ text }: { text: string }) {
|
||||
const seen: GenerateTextParams[] = [];
|
||||
|
||||
const generate = (async (params: GenerateTextParams) => {
|
||||
seen.push(structuredClone({ ...params, signal: undefined }));
|
||||
|
||||
return { text, tool_calls: [], candidate };
|
||||
}) as unknown as typeof import("@/src/harness/text/generate-text").default;
|
||||
|
||||
return { generate, seen };
|
||||
}
|
||||
|
||||
const messages: HarnessMessage[] = [{ role: "user", content: "Write the release notes." }];
|
||||
|
||||
describe("planBotTask", () => {
|
||||
test("asks for the plan in one turn on the prompt the run sends anyway", async () => {
|
||||
const { generate, seen } = fakeGenerate({ text: JSON.stringify(plan) });
|
||||
|
||||
const planned = await planBotTask({
|
||||
system: "You are a bot.",
|
||||
messages,
|
||||
signal: new AbortController().signal,
|
||||
bot_id: 3,
|
||||
workspace_id: 7,
|
||||
generate,
|
||||
});
|
||||
|
||||
expect(planned).toEqual({ plan, candidate });
|
||||
expect(seen.length).toBe(1);
|
||||
expect(seen[0]!.messages[0]).toEqual({ role: "system", content: "You are a bot." });
|
||||
expect(String(seen[0]!.messages[1]!.role)).toBe("user");
|
||||
expect(String(seen[0]!.messages[1]!.content)).toContain("Write the release notes.");
|
||||
expect(String(seen[0]!.messages[1]!.content)).toContain(TaskPlanPrompt);
|
||||
expect(seen[0]!.bot_id).toBe(3);
|
||||
expect(seen[0]!.workspace_id).toBe(7);
|
||||
expect(seen[0]!.tools).toBeUndefined();
|
||||
});
|
||||
|
||||
test("leaves the run's own opening as it was", async () => {
|
||||
const { generate } = fakeGenerate({ text: JSON.stringify(plan) });
|
||||
|
||||
await planBotTask({ system: "You are a bot.", messages, signal: new AbortController().signal, generate });
|
||||
|
||||
expect(messages).toEqual([{ role: "user", content: "Write the release notes." }]);
|
||||
});
|
||||
|
||||
test("is null when the answer isn't a plan, so the run starts unplanned", async () => {
|
||||
const { generate } = fakeGenerate({ text: "I'll figure it out as I go." });
|
||||
|
||||
const planned = await planBotTask({
|
||||
system: "You are a bot.",
|
||||
messages,
|
||||
signal: new AbortController().signal,
|
||||
generate,
|
||||
});
|
||||
|
||||
expect(planned).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { TaskPlanPrompt } from "@/src/data/harness-prompts";
|
||||
import generateText from "@/src/harness/text/generate-text";
|
||||
import pushUserTurn from "@/src/harness/text/push-user-turn";
|
||||
import type { HarnessCandidate, HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotTaskPlan } from "./bot-task-plan-schema";
|
||||
import parseBotTaskPlan from "./parse-bot-task-plan";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The system prompt the run's own turns send, unchanged: this turn
|
||||
* shares its cached prefix, so the plan costs little more than the
|
||||
* plan itself.
|
||||
*/
|
||||
system: string;
|
||||
/**
|
||||
* What the run opens with (its brief, and what the user wrote since).
|
||||
* Planned from a copy: the run's own opening is left as it is.
|
||||
*/
|
||||
messages: HarnessMessage[];
|
||||
signal: AbortSignal;
|
||||
bot_id?: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
generate?: typeof generateText;
|
||||
};
|
||||
|
||||
/**
|
||||
* Asks the run's model for the plan before the run takes a step
|
||||
* (`TaskPlanPrompt`). One turn, no tools: a plan that takes steps to write
|
||||
* is the wandering it exists to avoid.
|
||||
*
|
||||
* Null when the answer isn't a plan, so the run starts unplanned rather
|
||||
* than steered by one it can't read.
|
||||
*/
|
||||
export default async function planBotTask({
|
||||
system,
|
||||
messages,
|
||||
signal,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
generate = generateText,
|
||||
}: Params): Promise<{ plan: BotTaskPlan; candidate: HarnessCandidate } | null> {
|
||||
const planning = structuredClone(messages);
|
||||
|
||||
pushUserTurn({ transcript: planning, content: TaskPlanPrompt });
|
||||
|
||||
const answer = await generate({
|
||||
messages: [{ role: "system", content: system }, ...planning],
|
||||
signal,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
});
|
||||
|
||||
const plan = parseBotTaskPlan({ text: answer.text });
|
||||
|
||||
return plan ? { plan, candidate: answer.candidate } : null;
|
||||
}
|
||||
@@ -238,6 +238,7 @@ export default async function processBotJob({
|
||||
attachments: outcome.attachments,
|
||||
tool_log: outcome.tool_log,
|
||||
task_ids: outcome.task_ids,
|
||||
exhausted: outcome.exhausted,
|
||||
});
|
||||
|
||||
await pushBotNotice({ bot_id, ...completion });
|
||||
|
||||
@@ -7,6 +7,7 @@ import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import replyClaimProblems from "@/src/utils/reply-claim-problems";
|
||||
import replyRefIds from "@/src/utils/reply-ref-ids";
|
||||
import unresolvedSettingRefs from "@/src/utils/unresolved-setting-refs";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
@@ -24,7 +25,8 @@ type Params = {
|
||||
/**
|
||||
* Checks a chat reply's answer against what the app knows before it goes
|
||||
* out (`replyClaimProblems`): every file and task it names must exist for
|
||||
* the user (as their chips would open them), and work it says is under
|
||||
* the user (as their chips would open them), every setting ref the app can
|
||||
* resolve, and work it says is under
|
||||
* way must have been started by this reply or still be open from this
|
||||
* conversation. Returns the note that sends the answer back to be written
|
||||
* again, or null when it holds up. Bots wrote "I'm scanning now" with the
|
||||
@@ -52,6 +54,7 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
tool_uses,
|
||||
missing_file_ids,
|
||||
missing_task_ids,
|
||||
unresolved_setting_refs: unresolvedSettingRefs({ text }),
|
||||
has_open_work: await hasOpenWork({ bot_id, session_id }),
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
QuestionsNote,
|
||||
AskCrewNote,
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
GraphicsNote,
|
||||
botFilesNote,
|
||||
chatReplyNote,
|
||||
@@ -60,6 +61,7 @@ import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
@@ -210,8 +212,9 @@ export default async function runBotReply({
|
||||
*/
|
||||
const proposals: string[] = [];
|
||||
/**
|
||||
* The secrets the bot showed (`show_secret`) and the graphics it made
|
||||
* or changed, whose chips the reply always carries.
|
||||
* The secrets the bot showed (`show_secret`), the graphics it made
|
||||
* or changed, and the next steps it suggested: their chips the reply
|
||||
* always carries, without needing the user.
|
||||
*/
|
||||
const shown: string[] = [];
|
||||
/**
|
||||
@@ -358,6 +361,7 @@ export default async function runBotReply({
|
||||
RequestScopeNote({ can_ask: true }),
|
||||
QuestionsNote,
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
|
||||
GraphicsNote,
|
||||
workspace_id ? WorkspaceLearningNote : "",
|
||||
@@ -413,6 +417,13 @@ export default async function runBotReply({
|
||||
workspace_id,
|
||||
onAsk: ({ ref }) => proposals.push(ref),
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => shown.push(ref),
|
||||
}),
|
||||
...(has_past_sessions
|
||||
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
|
||||
: []),
|
||||
|
||||
+121
-58
@@ -9,6 +9,7 @@ import {
|
||||
RequestScopeNote,
|
||||
QuestionsNote,
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
GraphicsNote,
|
||||
botFilesNote,
|
||||
ComputerFilesNote,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
TaskIncomingNote,
|
||||
TaskRedraftNote,
|
||||
TaskWrapUpIncomingNote,
|
||||
taskPlanNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import {
|
||||
grabContextBudgetTokens,
|
||||
@@ -34,6 +36,7 @@ import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-comp
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
import runTextLoop from "@/src/harness/text/run-text-loop";
|
||||
import { isUnlimitedLimit, smallerRunLimit } from "@/src/utils/run-limit";
|
||||
import openComputerTools from "@/src/harness/tools/computer/open-computer-tools";
|
||||
import openBotBrowsers, { type OpenBotBrowsers } from "@/src/harness/tools/browsers/open-bot-browsers";
|
||||
import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/extensions/open-bot-extensions";
|
||||
@@ -42,6 +45,7 @@ import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-k
|
||||
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool";
|
||||
import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
|
||||
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
|
||||
@@ -66,6 +70,8 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
import taskIncoming from "./task-incoming";
|
||||
import planBotTask from "./plan-bot-task";
|
||||
import shouldPlanBotTask from "./should-plan-bot-task";
|
||||
import pushUserTurn from "@/src/harness/text/push-user-turn";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
|
||||
@@ -158,6 +164,11 @@ export default async function runBotTask({
|
||||
signal,
|
||||
}).catch(() => "");
|
||||
const take_overs: string[] = [];
|
||||
/**
|
||||
* The next steps the bot suggested: added to the message without
|
||||
* needing the user.
|
||||
*/
|
||||
const suggestions: string[] = [];
|
||||
/**
|
||||
* Files the bot wrote and asked to send with its report.
|
||||
*/
|
||||
@@ -280,6 +291,13 @@ export default async function runBotTask({
|
||||
in_task: true,
|
||||
onAsk: ({ ref }) => take_overs.push(ref),
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => suggestions.push(ref),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []),
|
||||
@@ -370,9 +388,19 @@ export default async function runBotTask({
|
||||
*/
|
||||
const task_steps = await grabHarnessMaxToolSteps();
|
||||
const install_steps =
|
||||
scheduled || hooked ? Math.min(task_steps, await grabUnattendedMaxToolSteps()) : task_steps;
|
||||
scheduled || hooked
|
||||
? smallerRunLimit({ a: task_steps, b: await grabUnattendedMaxToolSteps() })
|
||||
: task_steps;
|
||||
const budget = Math.floor(Number(params.max_steps) || 0);
|
||||
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
|
||||
const max_steps = budget > 0 ? smallerRunLimit({ a: budget, b: install_steps }) : install_steps;
|
||||
/**
|
||||
* What the run is told it has. Unlimited is said as such rather
|
||||
* than as a number: the job's deadline still ends it, and a run
|
||||
* told "at most 0 steps" would stop before it began.
|
||||
*/
|
||||
const steps_note = isUnlimitedLimit(max_steps)
|
||||
? `This run has no step limit: work until the job is done. Its job still stops it after a while, so save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
: `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`;
|
||||
|
||||
/**
|
||||
* What the user wrote since the run was queued, for a run they
|
||||
@@ -401,62 +429,92 @@ export default async function runBotTask({
|
||||
}
|
||||
}
|
||||
|
||||
const system = [
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
steps_note,
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
install_request_id ? InstallRequestNote : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
TasksNote,
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask }),
|
||||
can_ask ? QuestionsNote : "",
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
GraphicsNote,
|
||||
workspace_id ? WorkspaceLearningNote : "",
|
||||
powers.is_coordinator
|
||||
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
|
||||
: admin_tools.some((tool) => tool.name == "update_workspace")
|
||||
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
|
||||
: "",
|
||||
powers.is_coordinator || powers.is_workspace_admin
|
||||
? ""
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
|
||||
powers.is_coordinator || hooked ? "" : AskCrewNote,
|
||||
powers.is_coordinator || hooked || params.chatroom_id
|
||||
? ""
|
||||
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
|
||||
computer && computer_shared
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
|
||||
: computer
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
|
||||
: workspace_id
|
||||
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
|
||||
: `You have no computer for this task.`,
|
||||
computers.length > 1
|
||||
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
|
||||
: "",
|
||||
computer?.envs.length
|
||||
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
|
||||
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
|
||||
.join("\n")}`
|
||||
: "",
|
||||
composeBrowsersNote({
|
||||
browsers: browsers.browsers,
|
||||
has_computer_browser: Boolean(computer),
|
||||
run_kind: browser_run_kind,
|
||||
}),
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
extensions.note,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
/*
|
||||
* The plan this run works from, written in one turn before it takes
|
||||
* a step (`planBotTask`). It shares this run's prompt, so it costs
|
||||
* little more than the plan, and it saves the steps a long run
|
||||
* spends finding out what it is doing. A run whose plan can't be
|
||||
* written starts the way it always did.
|
||||
*/
|
||||
const planned = shouldPlanBotTask({ max_steps, in_chatroom: Boolean(params.chatroom_id) })
|
||||
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
|
||||
(error) => {
|
||||
if (signal.aborted) throw error;
|
||||
|
||||
return null;
|
||||
},
|
||||
)
|
||||
: null;
|
||||
|
||||
if (planned) {
|
||||
pushUserTurn({ transcript: opening, content: taskPlanNote({ plan: planned.plan }) });
|
||||
await report({
|
||||
index: -1,
|
||||
text: `Plan: ${planned.plan.goal}`,
|
||||
tool_calls: [],
|
||||
candidate: planned.candidate,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
`This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`,
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
install_request_id ? InstallRequestNote : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
TasksNote,
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask }),
|
||||
can_ask ? QuestionsNote : "",
|
||||
SecretsNote,
|
||||
GraphicsNote,
|
||||
workspace_id ? WorkspaceLearningNote : "",
|
||||
powers.is_coordinator
|
||||
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
|
||||
: admin_tools.some((tool) => tool.name == "update_workspace")
|
||||
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
|
||||
: "",
|
||||
powers.is_coordinator || powers.is_workspace_admin
|
||||
? ""
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
|
||||
powers.is_coordinator || hooked ? "" : AskCrewNote,
|
||||
powers.is_coordinator || hooked || params.chatroom_id
|
||||
? ""
|
||||
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
|
||||
computer && computer_shared
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
|
||||
: computer
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
|
||||
: workspace_id
|
||||
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
|
||||
: `You have no computer for this task.`,
|
||||
computers.length > 1
|
||||
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
|
||||
: "",
|
||||
computer?.envs.length
|
||||
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
|
||||
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
|
||||
.join("\n")}`
|
||||
: "",
|
||||
composeBrowsersNote({
|
||||
browsers: browsers.browsers,
|
||||
has_computer_browser: Boolean(computer),
|
||||
run_kind: browser_run_kind,
|
||||
}),
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
extensions.note,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
system,
|
||||
messages: opening,
|
||||
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
|
||||
max_steps,
|
||||
@@ -489,11 +547,16 @@ export default async function runBotTask({
|
||||
...withTakeOverRefs({
|
||||
text: computer ? computer.redact(text) : text,
|
||||
refs: take_overs,
|
||||
shown,
|
||||
shown: [...shown, ...suggestions],
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
/**
|
||||
* The wrap up was announced (`steps` counts its turns), so the
|
||||
* run never got to the end of the work it was given.
|
||||
*/
|
||||
exhausted: !isUnlimitedLimit(max_steps) && result.steps > max_steps,
|
||||
};
|
||||
} finally {
|
||||
await extensions?.close();
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import shouldPlanBotTask from "./should-plan-bot-task";
|
||||
|
||||
describe("shouldPlanBotTask", () => {
|
||||
test("plans a run long enough to repay the plan", () => {
|
||||
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps })).toBe(true);
|
||||
expect(shouldPlanBotTask({ max_steps: 200 })).toBe(true);
|
||||
});
|
||||
|
||||
test("always plans a run with no step limit: it has the steps to repay it", () => {
|
||||
expect(shouldPlanBotTask({ max_steps: UnlimitedLimit })).toBe(true);
|
||||
});
|
||||
|
||||
test("leaves a short run alone: its first turn is its plan", () => {
|
||||
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps - 1 })).toBe(false);
|
||||
expect(shouldPlanBotTask({ max_steps: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("never plans a chatroom turn, not even an unlimited one", () => {
|
||||
expect(shouldPlanBotTask({ max_steps: 200, in_chatroom: true })).toBe(false);
|
||||
expect(shouldPlanBotTask({ max_steps: UnlimitedLimit, in_chatroom: true })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { isUnlimitedLimit, type RunLimit } from "@/src/utils/run-limit";
|
||||
|
||||
/**
|
||||
* Whether a task run plans before its first step (`planBotTask`).
|
||||
*
|
||||
* Planning is an economy, not a rule. It costs one turn, mostly served
|
||||
* from the cache the run's own turns share, and it saves the steps a run
|
||||
* spends working out what it is doing. A run too short to repay that gets
|
||||
* nothing from it: its first turn is its plan. An unlimited run always
|
||||
* plans, since it has the steps to repay it.
|
||||
*
|
||||
* A chatroom turn is never planned: it is short, it has almost no tools,
|
||||
* and nobody follows it.
|
||||
*/
|
||||
export default function shouldPlanBotTask({
|
||||
max_steps,
|
||||
in_chatroom,
|
||||
}: {
|
||||
max_steps: RunLimit;
|
||||
in_chatroom?: boolean;
|
||||
}) {
|
||||
if (in_chatroom) return false;
|
||||
if (isUnlimitedLimit(max_steps)) return true;
|
||||
|
||||
return max_steps >= AppData.BotTaskPlanMinSteps;
|
||||
}
|
||||
@@ -62,6 +62,13 @@ export type BotJobOutcome = {
|
||||
* kept on the result message as `task_ids`.
|
||||
*/
|
||||
task_ids?: number[];
|
||||
/**
|
||||
* The run used every step it was allowed and stopped before it finished
|
||||
* (its wrap up was announced). A handed-over task stays open only when
|
||||
* the run did no work, so the task is blocked rather than left `doing`
|
||||
* (`noteTrackerTask`).
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
};
|
||||
|
||||
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import takeOverRef from "@/src/utils/take-over-ref";
|
||||
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
|
||||
import withTakeOverRefs from "./with-take-over-refs";
|
||||
|
||||
const ref = takeOverRef({ id: 1, mode: "browser" });
|
||||
@@ -21,4 +22,13 @@ describe("withTakeOverRefs", () => {
|
||||
test("leaves a message without a take-over alone", () => {
|
||||
expect(withTakeOverRefs({ text: "Done.", refs: [] })).toEqual({ result: "Done.", needs_you: false });
|
||||
});
|
||||
|
||||
test("adds suggested next steps without needing the user", () => {
|
||||
const suggestions = botSuggestionRef({ id: 4 });
|
||||
|
||||
expect(withTakeOverRefs({ text: "Done.", refs: [], shown: [suggestions] })).toEqual({
|
||||
result: `Done.\n\n${suggestions}`,
|
||||
needs_you: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,8 +6,9 @@ type Params = {
|
||||
*/
|
||||
refs: string[];
|
||||
/**
|
||||
* The secrets it showed (`secretRef`): added the same way, but they
|
||||
* don't need the user.
|
||||
* The secrets it showed (`secretRef`) and the next steps it suggested
|
||||
* (`botSuggestionRef`): added the same way, but they don't need the
|
||||
* user, so neither makes the message.
|
||||
*/
|
||||
shown?: string[];
|
||||
};
|
||||
@@ -16,7 +17,8 @@ type Params = {
|
||||
* A job's message with every take-over the bot asked for in it and every
|
||||
* proposal it made: refs the bot didn't write itself are added at the
|
||||
* end, so the user always gets the button. A message asking for either
|
||||
* needs the user.
|
||||
* needs the user; secrets it showed and next steps it suggested are added
|
||||
* without asking anything of them.
|
||||
*/
|
||||
export default function withTakeOverRefs({ text, refs, shown = [] }: Params) {
|
||||
const missing = [...new Set([...refs, ...shown])].filter((ref) => !text.includes(ref));
|
||||
|
||||
@@ -6,6 +6,7 @@ import pruneBotHookEvents from "./prune-bot-hook-events";
|
||||
import cronPruneChatrooms from "./prune-chatrooms";
|
||||
import cronPruneComputerCaches from "./prune-computer-caches";
|
||||
import cronPruneComputerHomes from "./prune-computer-homes";
|
||||
import cronWarnComputerWorkspaces from "./warn-computer-workspaces";
|
||||
import cronPruneOrphanMedia from "./prune-orphan-media";
|
||||
import pruneLogs from "./prune-logs";
|
||||
import syncNotifyWatchers from "./sync-notify-watchers";
|
||||
@@ -80,6 +81,13 @@ export default function cron() {
|
||||
task: pruneLogs,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "warn-computer-workspaces",
|
||||
schedule: "@daily",
|
||||
task: cronWarnComputerWorkspaces,
|
||||
quiet: true,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "sync-notify-watchers",
|
||||
schedule: "*/5 * * * *",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import warnFullComputerWorkspaces from "@/src/functions/backend/db/computers/warn-full-computer-workspaces";
|
||||
|
||||
/**
|
||||
* Reports every computer whose workspace is nearly full
|
||||
* (`warnFullComputerWorkspaces`): it is the one folder on a computer
|
||||
* mounted from the data volume, so it is what can fill the host, and a bot
|
||||
* only ever finds out when a write is refused mid-run.
|
||||
*/
|
||||
export default async function cronWarnComputerWorkspaces() {
|
||||
const full = await warnFullComputerWorkspaces();
|
||||
|
||||
return { nearly_full: full.map((entry) => entry.computer_id) };
|
||||
}
|
||||
+96
-32
@@ -1,3 +1,4 @@
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { SiteData } from "./site-data";
|
||||
|
||||
export const AppData = {
|
||||
@@ -110,7 +111,7 @@ export const AppData = {
|
||||
* `computer/` (the release workflow builds that tag), and bump
|
||||
* `ComputerWorkspaceLayout` too when existing computers must move to it.
|
||||
*/
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.0",
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.1",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -167,6 +168,13 @@ export const AppData = {
|
||||
* first (`computerWorkspaceRoomError`). 0 sets no limit.
|
||||
*/
|
||||
ComputerWorkspaceQuotaMb: 10240,
|
||||
/**
|
||||
* The share of the workspace quota past which `warn-computer-workspaces`
|
||||
* reports a computer, so the install hears about it while writes still
|
||||
* fit: a bot only ever learns of a full workspace when its own write is
|
||||
* refused, mid-run.
|
||||
*/
|
||||
ComputerWorkspaceWarnShare: 0.8,
|
||||
/**
|
||||
* How long a media row nothing points at stays before
|
||||
* `prune-orphan-media` deletes it. Long enough that an upload in flight,
|
||||
@@ -303,7 +311,7 @@ export const AppData = {
|
||||
* conversation forever. The lock is outlived by the heartbeat, so this
|
||||
* is the only thing that stops a live but stuck run.
|
||||
*/
|
||||
BotJobAttemptTimeoutMs: 60 * 60 * 1000,
|
||||
BotJobAttemptTimeoutMs: 2 * 60 * 60 * 1000,
|
||||
/**
|
||||
* A failed scheduled run is tried again after this, doubling each time
|
||||
* (`scheduledRunRetryAt`), so a short outage doesn't sink the run.
|
||||
@@ -405,11 +413,13 @@ export const AppData = {
|
||||
/**
|
||||
* Tasks (the crew's to-do list, `tasks`): the longest title, brief and
|
||||
* note, how many one bot or workspace can hold, and how many files one
|
||||
* task carries.
|
||||
* task carries. A brief is where an unattended run's whole plan lives
|
||||
* (they run with `UnattendedMaxToolSteps` and nobody watching), so it
|
||||
* holds a real work order: steps, paths, what to do when a check fails.
|
||||
*/
|
||||
TaskTitleMaxLength: 120,
|
||||
TaskDescriptionMaxLength: 8000,
|
||||
TaskNoteMaxLength: 2000,
|
||||
TaskDescriptionMaxLength: 20000,
|
||||
TaskNoteMaxLength: 4000,
|
||||
TaskMaxPerScope: 200,
|
||||
TaskMediaMaxPerTask: 20,
|
||||
/**
|
||||
@@ -422,8 +432,29 @@ export const AppData = {
|
||||
* Automatic model picks (`rankAutoModels`). A free model from outside
|
||||
* `AutoModelVendorPreference` must have at least this much context, and
|
||||
* this intelligence index or, unscored, this many billion parameters.
|
||||
* It is a floor for models that say what they have, so a model without
|
||||
* a declared window is never filtered on it (`HarnessUnknownContextWindow`
|
||||
* is what a run assumes for one of those).
|
||||
*/
|
||||
HarnessAutoMinContext: 32000,
|
||||
HarnessAutoMinContext: 32_000,
|
||||
/**
|
||||
* The window a run assumes for a model whose catalog never said
|
||||
* (`run-text-loop.ts`): a custom provider lists ids and nothing else,
|
||||
* and at 32000 the base prompt alone (system and tool definitions,
|
||||
* ~25000 tokens here) was already past the 70% working window, so every
|
||||
* turn trimmed the output the run was reading. 70% of this is the
|
||||
* widest such a model is ever given, whatever
|
||||
* `harness_context_budget_tokens` asks for, so it must stay at or above
|
||||
* that budget.
|
||||
*/
|
||||
HarnessUnknownContextWindow: 131_072,
|
||||
/**
|
||||
* A provider's declared window (`harness_providers.context_length`),
|
||||
* handed to the models it lists without one of their own: the least and
|
||||
* most a super admin may set, so a typo can't ask for a 40-token window.
|
||||
*/
|
||||
HarnessProviderContextMin: 1_000,
|
||||
HarnessProviderContextMax: 10_000_000,
|
||||
HarnessAutoMinScore: 12,
|
||||
HarnessAutoMinSizeB: 20,
|
||||
/**
|
||||
@@ -462,27 +493,33 @@ export const AppData = {
|
||||
*/
|
||||
HarnessTextFallbackModelsMax: 3,
|
||||
/**
|
||||
* Model turns in one text run before it must stop and report. The
|
||||
* install may save its own limit (the `harness_max_tool_steps` setting,
|
||||
* Settings > General), which wins over this one; a task run reads it
|
||||
* through `grabHarnessMaxToolSteps`.
|
||||
* Model turns in one text run before it must stop and report.
|
||||
* Unlimited by default: a run is bounded by the job's deadline and its
|
||||
* token budget instead, and stops when the work is done. The install
|
||||
* may save its own limit, or keep it unlimited (the
|
||||
* `harness_max_tool_steps` setting, Settings > General), which wins
|
||||
* over this one; a task run reads it through
|
||||
* `grabHarnessMaxToolSteps`.
|
||||
*/
|
||||
HarnessMaxToolSteps: 200,
|
||||
HarnessMaxToolSteps: UnlimitedLimit,
|
||||
/**
|
||||
* Model turns a routine run or a hook call may take: nobody watches
|
||||
* them, and one routine run once spent 39M tokens checking a site. The
|
||||
* install may save its own (`unattended_max_tool_steps`), read through
|
||||
* them, and one routine run once spent 39M tokens checking a site.
|
||||
* Unlimited by default, like a task's: the token budget and the job's
|
||||
* deadline end it. The install may save its own
|
||||
* (`unattended_max_tool_steps`), read through
|
||||
* `grabUnattendedMaxToolSteps`; a brief's own `max_steps` can only
|
||||
* lower it.
|
||||
*/
|
||||
UnattendedMaxToolSteps: 40,
|
||||
UnattendedMaxToolSteps: UnlimitedLimit,
|
||||
/**
|
||||
* Prompt tokens one run may spend in all (every turn resends the
|
||||
* prompt): past it the next turn is the wrap up. A safety net under the
|
||||
* step limit, for runs whose turns are large. The install may save its
|
||||
* own (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
|
||||
* prompt): past it the next turn is the wrap up. The one bound that
|
||||
* always holds, since step limits are unlimited by default, for runs
|
||||
* whose turns are large. The install may save its own
|
||||
* (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
|
||||
*/
|
||||
RunMaxPromptTokens: 4_000_000,
|
||||
RunMaxPromptTokens: 40_000_000,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
@@ -492,12 +529,13 @@ export const AppData = {
|
||||
* (`harness_context_budget_tokens`), read through
|
||||
* `grabContextBudgetTokens`.
|
||||
*/
|
||||
HarnessContextBudgetTokens: 80_000,
|
||||
HarnessContextBudgetTokens: 200_000,
|
||||
/**
|
||||
* The least a saved working context may be: below it a run would trim
|
||||
* the output it is reading right now.
|
||||
* the output it is reading right now (one full tool result is ~20000
|
||||
* tokens, and the system prompt and tool definitions sit on top).
|
||||
*/
|
||||
HarnessContextBudgetMinTokens: 20_000,
|
||||
HarnessContextBudgetMinTokens: 40_000,
|
||||
HarnessContextBudgetMaxTokens: 1_000_000,
|
||||
/**
|
||||
* Run token budgets the settings page accepts.
|
||||
@@ -505,15 +543,17 @@ export const AppData = {
|
||||
RunMaxPromptTokensMin: 100_000,
|
||||
RunMaxPromptTokensMax: 100_000_000,
|
||||
/**
|
||||
* Longest tool result handed back to the model.
|
||||
* Longest tool result handed back to the model. Above
|
||||
* `BotFileReadMaxChars` so a full read arrives whole, note and all: a
|
||||
* 45 KB article body read in pieces is a body the run never holds.
|
||||
*/
|
||||
HarnessToolResultMaxChars: 20000,
|
||||
HarnessToolResultMaxChars: 60_000,
|
||||
/**
|
||||
* Longest result of a browser tool (`browser_*`, the computer's or a
|
||||
* user's own browser): page snapshots and `browser_evaluate` output
|
||||
* were the heaviest results a run kept resending.
|
||||
*/
|
||||
HarnessBrowserResultMaxChars: 12000,
|
||||
HarnessBrowserResultMaxChars: 16_000,
|
||||
/**
|
||||
* Extension tools (MCP servers, a user's browsers) are listed by name
|
||||
* and loaded with `load_tools` only when their definitions together
|
||||
@@ -614,7 +654,7 @@ export const AppData = {
|
||||
* and a larger cap only meant the tool's own head-and-tail note was
|
||||
* thrown away by the second cut.
|
||||
*/
|
||||
ComputerCommandMaxOutputChars: 20_000,
|
||||
ComputerCommandMaxOutputChars: 40_000,
|
||||
ComputerReadFileMaxLines: 2000,
|
||||
ComputerReadFileMaxLineChars: 2000,
|
||||
ComputerReadFileMaxBytes: 10 * 1024 * 1024,
|
||||
@@ -847,11 +887,12 @@ export const AppData = {
|
||||
WorkspaceActivityItems: 6,
|
||||
/**
|
||||
* Tool turns a chat reply may take. Long work goes to a task instead.
|
||||
* The install may save its own limit (the `bot_reply_max_tool_steps`
|
||||
* setting, Settings > General), which wins over this one; a reply
|
||||
* reads it through `grabReplyMaxToolSteps`.
|
||||
* Unlimited by default, like a task's: the job's deadline and the
|
||||
* token budget end it. The install may save its own limit (the
|
||||
* `bot_reply_max_tool_steps` setting, Settings > General), which wins
|
||||
* over this one; a reply reads it through `grabReplyMaxToolSteps`.
|
||||
*/
|
||||
BotReplyMaxToolSteps: 20,
|
||||
BotReplyMaxToolSteps: UnlimitedLimit,
|
||||
/**
|
||||
* From this many characters, a bot message whose run called no tools
|
||||
* shows "No tools used" under it (`MessageNoToolsChip`): a long report
|
||||
@@ -869,14 +910,24 @@ export const AppData = {
|
||||
* chat reply. A typo in the settings page can't turn one run into an
|
||||
* hour of tool calls, and a huge limit still ends with a report.
|
||||
*/
|
||||
BotStepLimitMax: 1000,
|
||||
BotStepLimitMax: 10000,
|
||||
/**
|
||||
* The least steps a task run needs before it plans first (`planBotTask`):
|
||||
* a shorter run's own first turn already is its plan. How long a plan
|
||||
* may be is capped here too, since a model writes it. A plan is an
|
||||
* economy, never a gate: a run whose plan can't be written just starts.
|
||||
*/
|
||||
BotTaskPlanMinSteps: 10,
|
||||
BotTaskPlanMaxSteps: 12,
|
||||
BotTaskPlanMaxGather: 8,
|
||||
BotTaskPlanTextMaxChars: 400,
|
||||
/**
|
||||
* Chat attachments: per file, per message, and how much of a
|
||||
* document's text a reply reads.
|
||||
*/
|
||||
BotAttachmentMaxBytes: 20 * 1024 * 1024,
|
||||
BotAttachmentMaxFiles: 6,
|
||||
BotAttachmentMaxTextChars: 20000,
|
||||
BotAttachmentMaxTextChars: 40_000,
|
||||
/**
|
||||
* How much of a document's text is kept on its `media` row. A ceiling
|
||||
* on the column itself: without it a 20 MB PDF left 20 MB of text in
|
||||
@@ -926,6 +977,19 @@ export const AppData = {
|
||||
* Longest answer a user may type into a question's "Other".
|
||||
*/
|
||||
BotQuestionOtherMaxChars: 1000,
|
||||
/**
|
||||
* Most next steps one `suggest_next_steps` row offers.
|
||||
*/
|
||||
BotSuggestionMaxSteps: 4,
|
||||
/**
|
||||
* Longest one suggested next step may be (the text that fills the
|
||||
* user's input).
|
||||
*/
|
||||
BotSuggestionStepMaxChars: 120,
|
||||
/**
|
||||
* Longest heading a bot may give its suggested next steps.
|
||||
*/
|
||||
BotSuggestionTitleMaxChars: 120,
|
||||
/**
|
||||
* Longest dictation the composer records before it stops on its own.
|
||||
*/
|
||||
@@ -959,7 +1023,7 @@ export const AppData = {
|
||||
* hands back at once (the rest comes with an offset).
|
||||
*/
|
||||
BotFileWriteMaxChars: 200_000,
|
||||
BotFileReadMaxChars: 40_000,
|
||||
BotFileReadMaxChars: 55_000,
|
||||
BotFileListMaxItems: 200,
|
||||
BotFileNameMaxChars: 120,
|
||||
BotFilePathMaxChars: 400,
|
||||
|
||||
@@ -195,6 +195,21 @@ Anything you read or write goes to your model provider, so secret values (passwo
|
||||
- Never print, cat or echo a secret on a computer. To show one to the user, use show_secret for an env you have, or in a task on a computer capture it with capture_secret: either gives you a [secret:ID] ref to put in your message.
|
||||
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected.`;
|
||||
|
||||
/**
|
||||
* Added to every reply and task: the app's own limits are the user's to
|
||||
* change, so a bot names the setting, its value and the page, never hides
|
||||
* behind a refusal and never claims a change it didn't make.
|
||||
*/
|
||||
export const SettingsNote = `# Settings that stop you
|
||||
|
||||
The app caps how long you may work and how much you may send, and every one of those limits is a setting the user can change. When one stops you or shapes your answer - steps used up, tokens used up, a message or file too long, a folder full, a runbook over its limit - name the setting, say its value the way the form shows it, and say who can change it.
|
||||
|
||||
- Read the values with read_settings before you name one, and never guess a number.
|
||||
- Write the setting's ref exactly as read_settings gives it (e.g. [setting:run-limits:reply_steps]). The chat shows it as a pill that opens that page and field, so the user lands on the input to change.
|
||||
- Never change a setting yourself, and never say one was changed: that's the user's click on that page.
|
||||
- When the user asks why a reply cost so much or why it was cut short, read_message_usage first: say what the calls show (steps, model, tokens, what was repeated), then point at the limit if one shaped it. Report only what you read.
|
||||
- A refusal is explained, not hidden: the limit, its value and the page are the answer.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: the request sets the
|
||||
* scope, and crew changes or handing work out are the user's call, so they
|
||||
@@ -280,7 +295,7 @@ export const TaskRunNote = `# Working on a task
|
||||
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
|
||||
|
||||
Pace your work across your step budget: spend no more than a third of your steps on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
|
||||
Pace your work: don't spend more than about a third of the run on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
|
||||
|
||||
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
|
||||
@@ -308,6 +323,51 @@ export const TaskRedraftNote = `Your report above was not sent: the user wrote i
|
||||
*/
|
||||
export const TaskWrapUpIncomingNote = `The user wrote in this conversation before you finished (below), and this run has no steps left to act on it. If it changes, corrects or adds to this task, say in your report what it changes and what is still to redo because of it; never report a result it overruled as it stands.`;
|
||||
|
||||
/**
|
||||
* The one turn a task run plans in before its first step (`planBotTask`).
|
||||
* It is a user turn, not part of the system prompt, so the prompt the run's
|
||||
* own turns send is the same one this call already cached.
|
||||
*/
|
||||
export const TaskPlanPrompt = `Before you start, plan this run in one turn, so you spend its steps doing the work instead of finding out what the work is.
|
||||
|
||||
Answer with a JSON object only, no markdown fence and no other text:
|
||||
{"goal": "...", "gather": ["..."], "steps": ["..."], "done": "..."}
|
||||
|
||||
- goal: what finishing this run gives the user, in one sentence.
|
||||
- gather: everything whose content you will need, each once, named as exactly as you can (a path, a URL, a command). A file you will edit is read first, a folder you will save into is listed first, and a fact you need twice is looked up once.
|
||||
- steps: the work in order, the shortest way that finishes it. Fold each check into the step it belongs to: no step that only verifies a previous one, and nothing you would do the same way twice.
|
||||
- done: how you will know it is finished, from what you can see for yourself.
|
||||
|
||||
The plan is for you, and it replaces finding out as you go: anything it says to gather is gathered once and reused, never re-read or re-run to see it again.`;
|
||||
|
||||
/**
|
||||
* The plan a task run wrote before its first step, given back to it as the
|
||||
* turn it works from. It stays advice, not an order: what a step turns up
|
||||
* can change the rest, and the run says so in its report.
|
||||
*/
|
||||
export const taskPlanNote = ({
|
||||
plan,
|
||||
}: {
|
||||
plan: { goal: string; gather: string[]; steps: string[]; done: string };
|
||||
}) =>
|
||||
`# Your plan
|
||||
|
||||
You wrote this before starting, and this run works from it now. Steps count, so follow it: gather once what it says to gather, and reuse what you already have instead of calling the same tool again for it. When a step turns up something that changes the rest, change the plan and carry on; don't repeat a step that is done.
|
||||
|
||||
Goal: ${plan.goal}
|
||||
|
||||
${plan.gather.length ? `Gather first, once each:\n${plan.gather.map((item) => `- ${item}`).join("\n")}\n\n` : ""}Steps:
|
||||
${plan.steps.map((step, index) => `${index + 1}. ${step}`).join("\n")}${plan.done ? `\n\nDone when: ${plan.done}` : ""}`;
|
||||
|
||||
/**
|
||||
* What a run gets back instead of a second identical read: the answer is
|
||||
* already in its transcript, and paying for it again buys nothing. Only
|
||||
* reads reach this (`RepeatableToolNames`), and any run write clears what
|
||||
* was remembered, so "nothing has changed" holds.
|
||||
*/
|
||||
export const alreadyRanToolNote = ({ name, step }: { name: string; step: number }) =>
|
||||
`You already called ${name} with these exact arguments on step ${step + 1} of this run, and nothing has changed since. Its output is above: use that instead of calling it again.`;
|
||||
|
||||
/**
|
||||
* Added to a chat reply while the bot has runs open in this conversation
|
||||
* that take in what the user writes here: a correction to one reaches it,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import generalSettingsHref, {
|
||||
CitableGeneralSettingsSections,
|
||||
GeneralSettingsRoot,
|
||||
GeneralSettingsSections,
|
||||
findCitableGeneralSettingsSection,
|
||||
findGeneralSettingsField,
|
||||
findGeneralSettingsSection,
|
||||
} from "./general-settings-dict";
|
||||
|
||||
describe("GeneralSettingsSections", () => {
|
||||
test("every group has a key of its own and a page under General", () => {
|
||||
const keys = GeneralSettingsSections.map((section) => section.key);
|
||||
|
||||
expect(new Set(keys).size).toBe(keys.length);
|
||||
|
||||
for (const key of keys) {
|
||||
expect(generalSettingsHref({ section: key })).toBe(`${GeneralSettingsRoot}/${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a field's href is its section's page, then its anchor", () => {
|
||||
expect(generalSettingsHref({ section: "run-limits", field: "reply_steps" })).toBe(
|
||||
"/admin/settings/general/run-limits#reply_steps",
|
||||
);
|
||||
expect(generalSettingsHref({ section: null })).toBe(GeneralSettingsRoot);
|
||||
});
|
||||
|
||||
test("a citable group names the fields a bot may send someone to", () => {
|
||||
expect(CitableGeneralSettingsSections.length).toBeGreaterThan(0);
|
||||
|
||||
for (const section of CitableGeneralSettingsSections) {
|
||||
const field = section.fields[0];
|
||||
|
||||
expect(section.fields.length).toBeGreaterThan(0);
|
||||
expect(findGeneralSettingsField({ section: section.key, field: field?.key })).toEqual(field || null);
|
||||
}
|
||||
});
|
||||
|
||||
test("what a bot may cite is looked up, and a typo finds nothing", () => {
|
||||
expect(findCitableGeneralSettingsSection({ key: "run-limits" })?.title).toBe("Run limits");
|
||||
expect(findCitableGeneralSettingsSection({ key: "theme" })).toBeNull();
|
||||
expect(findGeneralSettingsSection({ key: "nope" })).toBeNull();
|
||||
expect(findGeneralSettingsField({ section: "run-limits", field: "nope" })).toBeNull();
|
||||
expect(findGeneralSettingsField({ section: "theme", field: "reply_steps" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* The groups of Settings > General, one source for the page, the pages
|
||||
* each group has on its own and what a bot may point a user at
|
||||
* (`[setting:<section>:<field>]`).
|
||||
*
|
||||
* A field is a setting a bot can name: its `title` is the label the form
|
||||
* shows, so a pill the user reads matches the input they have to change.
|
||||
* A section is citable when a limit in it stops work, which is what makes
|
||||
* it worth sending someone to.
|
||||
*/
|
||||
|
||||
export type GeneralSettingsFieldKind =
|
||||
| "steps"
|
||||
| "tokens"
|
||||
| "characters"
|
||||
| "mb"
|
||||
| "days"
|
||||
| "seconds"
|
||||
| "text";
|
||||
|
||||
/**
|
||||
* Who may read a section, and who may change it. Reading is the wider
|
||||
* right: a member can be sent to a limit they hit and see its value,
|
||||
* while only the role that owns it gets the form.
|
||||
*/
|
||||
export type GeneralSettingsAudience = "everyone" | "crew_manager" | "super_admin";
|
||||
|
||||
export type GeneralSettingsField = {
|
||||
key: string;
|
||||
title: string;
|
||||
kind: GeneralSettingsFieldKind;
|
||||
};
|
||||
|
||||
/**
|
||||
* A setting's live value, as the form shows it.
|
||||
*/
|
||||
export type GeneralSettingsValue = {
|
||||
key: string;
|
||||
title: string;
|
||||
/**
|
||||
* The value as the form shows it ("20 steps"), or "not set yet".
|
||||
*/
|
||||
label: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* One group of General settings with its live values, ready to describe to
|
||||
* a bot or read back to a person.
|
||||
*/
|
||||
export type GeneralSettingsSectionValues = {
|
||||
key: string;
|
||||
title: string;
|
||||
href: string;
|
||||
/**
|
||||
* Who may change it, in words ("the super admin", "an admin", "anyone").
|
||||
*/
|
||||
editor: string;
|
||||
editable_by: GeneralSettingsAudience;
|
||||
values: GeneralSettingsValue[];
|
||||
};
|
||||
|
||||
export type GeneralSettingsSection = {
|
||||
key: string;
|
||||
title: string;
|
||||
description: string;
|
||||
readable_by: GeneralSettingsAudience;
|
||||
editable_by: GeneralSettingsAudience;
|
||||
/**
|
||||
* A bot may name a field of this section in a ref (`read_settings`).
|
||||
*/
|
||||
citable: boolean;
|
||||
fields: GeneralSettingsField[];
|
||||
};
|
||||
|
||||
export const GeneralSettingsRoot = "/admin/settings/general";
|
||||
|
||||
export const GeneralSettingsAudiences: Record<GeneralSettingsAudience, string> = {
|
||||
everyone: "anyone",
|
||||
crew_manager: "an admin",
|
||||
super_admin: "the super admin",
|
||||
};
|
||||
|
||||
export const GeneralSettingsSections: GeneralSettingsSection[] = [
|
||||
{
|
||||
key: "theme",
|
||||
title: "Theme",
|
||||
description: "Saved on this device only, so each computer can have its own.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "everyone",
|
||||
citable: false,
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
key: "notifications",
|
||||
title: "Notifications",
|
||||
description: "A notification arrives when a bot replies or needs you and the app is closed.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "everyone",
|
||||
citable: false,
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
key: "install-name",
|
||||
title: "App name",
|
||||
description: "The name this install goes by when it's added to a home screen or app list.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: false,
|
||||
fields: [{ key: "install_name", title: "Install name", kind: "text" }],
|
||||
},
|
||||
{
|
||||
key: "install-icon",
|
||||
title: "App icon",
|
||||
description: "The icon this install shows on home screens, app lists and notifications.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: false,
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
key: "prompt-appendix",
|
||||
title: "Prompt appendix",
|
||||
description: "Text added to every bot's instructions, right after its own.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [{ key: "appendix", title: "Appendix", kind: "characters" }],
|
||||
},
|
||||
{
|
||||
key: "run-limits",
|
||||
title: "Run limits",
|
||||
description: "How long a bot may work on one run, how much of its work it sends the model each turn, and how long a failed model rests. Each limit can be unlimited.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [
|
||||
{ key: "task_steps", title: "Tool steps per task", kind: "steps" },
|
||||
{ key: "reply_steps", title: "Tool steps per chat reply", kind: "steps" },
|
||||
{ key: "unattended_steps", title: "Tool steps per routine or hook call", kind: "steps" },
|
||||
{ key: "run_tokens", title: "Tokens per run", kind: "tokens" },
|
||||
{ key: "context_tokens", title: "Working context", kind: "tokens" },
|
||||
{ key: "model_rest_seconds", title: "Model rest after a failure", kind: "seconds" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "sessions",
|
||||
title: "Sessions",
|
||||
description: "Every reply re-reads the session's recent messages, so a long session costs more tokens each time.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [{ key: "max_messages", title: "Start a new session after", kind: "steps" }],
|
||||
},
|
||||
{
|
||||
key: "messages",
|
||||
title: "Messages",
|
||||
description: "How long a message users may send to a bot, and the longest one the bot may answer.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [{ key: "max_chars", title: "Longest message", kind: "characters" }],
|
||||
},
|
||||
{
|
||||
key: "skill-limits",
|
||||
title: "Skill limits",
|
||||
description: "How much of a skill's runbook a bot may store, and how much of it it reads at once.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [
|
||||
{ key: "body_max_chars", title: "Longest runbook", kind: "characters" },
|
||||
{ key: "body_shown_chars", title: "Runbook a bot reads at once", kind: "characters" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "hook-calls",
|
||||
title: "Hook calls",
|
||||
description: "How long a hook's calls are kept, so they can still be searched.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [{ key: "keep_days", title: "Keep hook calls for", kind: "days" }],
|
||||
},
|
||||
{
|
||||
key: "chatrooms",
|
||||
title: "Chatrooms",
|
||||
description: "How many chatrooms are kept per place, and for how long once they close.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [
|
||||
{ key: "keep_days", title: "Keep closed chatrooms for", kind: "days" },
|
||||
{ key: "max_per_place", title: "Most chatrooms per place", kind: "steps" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "activity-log",
|
||||
title: "Activity log",
|
||||
description: "How long the app keeps its own log of what happened.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: false,
|
||||
fields: [{ key: "keep_days", title: "Keep activity for", kind: "days" }],
|
||||
},
|
||||
{
|
||||
key: "storage",
|
||||
title: "Storage",
|
||||
description: "How much each folder may hold: a bot's own, and each workspace's.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "crew_manager",
|
||||
citable: true,
|
||||
fields: [{ key: "quota_mb", title: "Megabytes per folder", kind: "mb" }],
|
||||
},
|
||||
{
|
||||
key: "computer-workspaces",
|
||||
title: "Computer workspace limit",
|
||||
description: "How much a computer's workspace may hold, so one can't fill the host it runs on.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "crew_manager",
|
||||
citable: true,
|
||||
fields: [{ key: "quota_mb", title: "Megabytes per computer", kind: "mb" }],
|
||||
},
|
||||
{
|
||||
key: "docker-networks",
|
||||
title: "Docker networks",
|
||||
description: "Extra docker networks the app joins, so it can reach containers or services of yours.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: false,
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
key: "version",
|
||||
title: "Version",
|
||||
description: "The release this server runs, so an update can be confirmed from the app.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: false,
|
||||
fields: [],
|
||||
},
|
||||
];
|
||||
|
||||
const withFields = GeneralSettingsSections.filter((section) => section.fields.length > 0);
|
||||
|
||||
export const CitableGeneralSettingsSections = withFields.filter((section) => section.citable);
|
||||
|
||||
export function findGeneralSettingsSection({ key }: { key?: string | null }) {
|
||||
return GeneralSettingsSections.find((section) => section.key == key) || null;
|
||||
}
|
||||
|
||||
export function findCitableGeneralSettingsSection({ key }: { key?: string | null }) {
|
||||
return CitableGeneralSettingsSections.find((section) => section.key == key) || null;
|
||||
}
|
||||
|
||||
export function findGeneralSettingsField({
|
||||
section,
|
||||
field,
|
||||
}: {
|
||||
section?: string | null;
|
||||
field?: string | null;
|
||||
}) {
|
||||
const found = findGeneralSettingsSection({ key: section });
|
||||
|
||||
if (!found || !field) return null;
|
||||
|
||||
return found.fields.find((item) => item.key == field) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a section (and optionally one field of it) lives, for a link or a
|
||||
* ref: the section has its own page under General, the field is its
|
||||
* anchor on that page.
|
||||
*/
|
||||
export default function generalSettingsHref({
|
||||
section,
|
||||
field,
|
||||
}: {
|
||||
section?: string | null;
|
||||
field?: string | null;
|
||||
}) {
|
||||
if (!section) return GeneralSettingsRoot;
|
||||
|
||||
return `${GeneralSettingsRoot}/${section}${field ? `#${field}` : ""}`;
|
||||
}
|
||||
@@ -6,6 +6,15 @@ type Params = {
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type ComputerUsageFolder = {
|
||||
/**
|
||||
* Relative to the workspace root: `bots/9` is a bot's folder,
|
||||
* `workspaces/3` a workspace's shared one.
|
||||
*/
|
||||
path: string;
|
||||
bytes: number;
|
||||
};
|
||||
|
||||
export type ComputerUsage = {
|
||||
/**
|
||||
* How much the whole workspace holds, every bot's and user's folder
|
||||
@@ -16,6 +25,11 @@ export type ComputerUsage = {
|
||||
* Where it is on the computer, for messages.
|
||||
*/
|
||||
workspace_dir: string;
|
||||
/**
|
||||
* The biggest folders in it, most first. A computer whose agent is
|
||||
* older than this sends none.
|
||||
*/
|
||||
folders?: ComputerUsageFolder[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -24,5 +38,5 @@ export type ComputerUsage = {
|
||||
* asking before each write costs little.
|
||||
*/
|
||||
export default function grabComputerUsage({ computer, signal }: Params) {
|
||||
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 30_000, signal });
|
||||
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 60_000, signal });
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import generalSettingsHref, {
|
||||
GeneralSettingsAudiences,
|
||||
GeneralSettingsSections,
|
||||
type GeneralSettingsFieldKind,
|
||||
type GeneralSettingsSectionValues,
|
||||
type GeneralSettingsValue,
|
||||
} from "@/src/dict/general-settings-dict";
|
||||
import settingValueLabel from "@/src/utils/setting-value-label";
|
||||
import grabChatroomRetentionOverview from "./grab-chatroom-retention";
|
||||
import grabComputerWorkspaceQuotaOverview from "./grab-computer-workspace-quota-overview";
|
||||
import grabHookCallRetentionOverview from "./grab-hook-events-keep-days";
|
||||
import grabInstallName from "./grab-install-name";
|
||||
import grabLogRetentionOverview from "./grab-logs-keep-days";
|
||||
import grabMessageLengthOverview from "./grab-bot-message-max-chars";
|
||||
import grabRunLimitsOverview from "./grab-run-limits";
|
||||
import grabSessionLengthOverview from "./grab-bot-session-max-messages";
|
||||
import grabSkillLimitsOverview from "./grab-skill-limits";
|
||||
import grabStorageQuotaOverview from "./grab-storage-quota-overview";
|
||||
import grabSystemPromptAppendOverview from "./grab-system-prompt-append";
|
||||
|
||||
export type { GeneralSettingsSectionValues };
|
||||
|
||||
type RawValues = Record<string, number | string | null>;
|
||||
|
||||
/**
|
||||
* General settings whose value a bot may need to quote, read live so a
|
||||
* pill it writes says what the page says now (a limit raised after the run
|
||||
* started shows its new number).
|
||||
*/
|
||||
export default async function grabGeneralSettingsValues(): Promise<GeneralSettingsSectionValues[]> {
|
||||
const [run_limits, skill_limits, hook_calls, logs, chatrooms, sessions, messages, storage, computer_workspace, appendix, install_name] =
|
||||
await Promise.all([
|
||||
grabRunLimitsOverview().catch(() => null),
|
||||
grabSkillLimitsOverview().catch(() => null),
|
||||
grabHookCallRetentionOverview().catch(() => null),
|
||||
grabLogRetentionOverview().catch(() => null),
|
||||
grabChatroomRetentionOverview().catch(() => null),
|
||||
grabSessionLengthOverview().catch(() => null),
|
||||
grabMessageLengthOverview().catch(() => null),
|
||||
grabStorageQuotaOverview().catch(() => null),
|
||||
grabComputerWorkspaceQuotaOverview().catch(() => null),
|
||||
grabSystemPromptAppendOverview().catch(() => null),
|
||||
grabInstallName().catch(() => ""),
|
||||
]);
|
||||
|
||||
const raw: Record<string, RawValues> = {
|
||||
"run-limits": {
|
||||
task_steps: run_limits?.task_steps ?? null,
|
||||
reply_steps: run_limits?.reply_steps ?? null,
|
||||
unattended_steps: run_limits?.unattended_steps ?? null,
|
||||
run_tokens: run_limits?.run_tokens ?? null,
|
||||
context_tokens: run_limits?.context_tokens ?? null,
|
||||
model_rest_seconds: run_limits?.model_rest_seconds ?? null,
|
||||
},
|
||||
sessions: { max_messages: sessions?.max_messages ?? null },
|
||||
messages: { max_chars: messages?.max_chars ?? null },
|
||||
"skill-limits": {
|
||||
body_max_chars: skill_limits?.body_max_chars ?? null,
|
||||
body_shown_chars: skill_limits?.body_shown_chars ?? null,
|
||||
},
|
||||
"hook-calls": { keep_days: hook_calls?.keep_days ?? null },
|
||||
chatrooms: {
|
||||
keep_days: chatrooms?.keep_days ?? null,
|
||||
max_per_place: chatrooms?.max_per_place ?? null,
|
||||
},
|
||||
"activity-log": { keep_days: logs?.keep_days ?? null },
|
||||
storage: { quota_mb: storage?.quota_mb ?? null },
|
||||
"computer-workspaces": { quota_mb: computer_workspace?.quota_mb ?? null },
|
||||
"prompt-appendix": { appendix: appendix ? appendix.length : null },
|
||||
"install-name": { install_name: install_name || null },
|
||||
};
|
||||
|
||||
return GeneralSettingsSections.filter((section) => section.fields.length > 0).map((section) => {
|
||||
const values = raw[section.key] || {};
|
||||
|
||||
return {
|
||||
key: section.key,
|
||||
title: section.title,
|
||||
href: generalSettingsHref({ section: section.key }),
|
||||
editor: GeneralSettingsAudiences[section.editable_by],
|
||||
editable_by: section.editable_by,
|
||||
values: section.fields.map((field) => ({
|
||||
key: field.key,
|
||||
title: field.title,
|
||||
label: settingValueLabel({
|
||||
kind: field.kind as GeneralSettingsFieldKind,
|
||||
value: values[field.key] ?? null,
|
||||
}),
|
||||
})),
|
||||
} satisfies GeneralSettingsSectionValues;
|
||||
});
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
UnattendedMaxToolStepsSettingKey,
|
||||
} from "@/src/dict/harness-dict";
|
||||
import type { RunLimitsOverview } from "@/src/types";
|
||||
import readStepLimit from "@/src/utils/read-step-limit";
|
||||
import readRunLimit from "@/src/utils/read-run-limit";
|
||||
import grabAppSetting from "./grab-app-setting";
|
||||
|
||||
export type { RunLimitsOverview };
|
||||
@@ -16,11 +16,11 @@ export type { RunLimitsOverview };
|
||||
/**
|
||||
* Model turns a task run may take: the install's own limit
|
||||
* (`harness_max_tool_steps`, Settings > General), else
|
||||
* `AppData.HarnessMaxToolSteps`. `runTextLoop`'s default is the code's one,
|
||||
* so a task run passes this in.
|
||||
* `AppData.HarnessMaxToolSteps` (unlimited). `runTextLoop`'s default is the
|
||||
* code's one, so a task run passes this in.
|
||||
*/
|
||||
export async function grabHarnessMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: HarnessMaxToolStepsSettingKey }),
|
||||
fallback: AppData.HarnessMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
@@ -30,10 +30,10 @@ export async function grabHarnessMaxToolSteps() {
|
||||
/**
|
||||
* Model turns a chat reply may take: the install's own limit
|
||||
* (`bot_reply_max_tool_steps`, Settings > General), else
|
||||
* `AppData.BotReplyMaxToolSteps`.
|
||||
* `AppData.BotReplyMaxToolSteps` (unlimited).
|
||||
*/
|
||||
export async function grabReplyMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: BotReplyMaxToolStepsSettingKey }),
|
||||
fallback: AppData.BotReplyMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
@@ -43,10 +43,10 @@ export async function grabReplyMaxToolSteps() {
|
||||
/**
|
||||
* Model turns a routine run or a hook call may take, which nobody
|
||||
* watches: the install's own limit (`unattended_max_tool_steps`), else
|
||||
* `AppData.UnattendedMaxToolSteps`.
|
||||
* `AppData.UnattendedMaxToolSteps` (unlimited).
|
||||
*/
|
||||
export async function grabUnattendedMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: UnattendedMaxToolStepsSettingKey }),
|
||||
fallback: AppData.UnattendedMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
@@ -56,9 +56,10 @@ export async function grabUnattendedMaxToolSteps() {
|
||||
/**
|
||||
* Prompt tokens one run may spend before it must wrap up: the install's
|
||||
* own budget (`run_max_prompt_tokens`), else `AppData.RunMaxPromptTokens`.
|
||||
* Unlimited when the install chose none.
|
||||
*/
|
||||
export async function grabRunMaxPromptTokens() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: RunMaxPromptTokensSettingKey }),
|
||||
fallback: AppData.RunMaxPromptTokens,
|
||||
min: AppData.RunMaxPromptTokensMin,
|
||||
@@ -69,10 +70,11 @@ export async function grabRunMaxPromptTokens() {
|
||||
/**
|
||||
* The working context a run keeps per turn, in estimated tokens: the
|
||||
* install's own (`harness_context_budget_tokens`), else
|
||||
* `AppData.HarnessContextBudgetTokens`.
|
||||
* `AppData.HarnessContextBudgetTokens`. Unlimited keeps the model's whole
|
||||
* window.
|
||||
*/
|
||||
export async function grabContextBudgetTokens() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: HarnessContextBudgetSettingKey }),
|
||||
fallback: AppData.HarnessContextBudgetTokens,
|
||||
min: AppData.HarnessContextBudgetMinTokens,
|
||||
@@ -83,9 +85,10 @@ export async function grabContextBudgetTokens() {
|
||||
/**
|
||||
* How long a model that failed is passed over, in seconds: the install's
|
||||
* own (`harness_model_rest_seconds`), else `AppData.HarnessModelRestMs`.
|
||||
* Unlimited rests it until the setting changes (or the app restarts).
|
||||
*/
|
||||
export async function grabModelRestSeconds() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: HarnessModelRestSettingKey }),
|
||||
fallback: AppData.HarnessModelRestMs / 1000,
|
||||
min: AppData.HarnessModelRestMinSeconds,
|
||||
@@ -94,7 +97,8 @@ export async function grabModelRestSeconds() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every run limit with its default, for the settings page.
|
||||
* Every run limit with its default, for the settings page. A limit is a
|
||||
* number or `"unlimited"`.
|
||||
*/
|
||||
export default async function grabRunLimitsOverview() {
|
||||
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds] =
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, BunSQLiteTables } from "@/db/types/db";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
title: string;
|
||||
steps: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Stores next steps a bot suggests under its answer, read back as buttons
|
||||
* that put a step in the user's input. Returns its id.
|
||||
*/
|
||||
export default async function createBotSuggestion({ user_id, bot_id, session_id, workspace_id, title, steps }: Params) {
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, (typeof BunSQLiteTables)[number]>({
|
||||
table: "bot_suggestions",
|
||||
data: [
|
||||
{
|
||||
title,
|
||||
steps: JSON.stringify(steps),
|
||||
user_id: Number(user_id),
|
||||
bot_id: Number(bot_id),
|
||||
session_id: Number(session_id),
|
||||
workspace_id: workspace_id ? Number(workspace_id) : undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const id = Number(res.singleRes?.id || res.postInsertReturn?.insertId);
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the suggested next steps: ${res.msg}`);
|
||||
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotSuggestionView } from "@/src/types";
|
||||
import grabBotSuggestion from "./grab-bot-suggestion";
|
||||
import parseBotSuggestionRow from "@/src/utils/parse-bot-suggestion-row";
|
||||
|
||||
type Params = {
|
||||
suggestion_id: number | string;
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested as the thread shows them: its heading and the
|
||||
* steps, each a button that puts it in the user's input.
|
||||
*/
|
||||
export default async function grabBotSuggestionView({ suggestion_id, user_id }: Params): Promise<BotSuggestionView> {
|
||||
const row = await grabBotSuggestion({ suggestion_id, user_id });
|
||||
const { steps } = parseBotSuggestionRow({ row });
|
||||
|
||||
const bot = (
|
||||
await BunSQLite.sql<{ name: string }>({
|
||||
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
|
||||
values: [row.bot_id || 0],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return {
|
||||
id: Number(row.id),
|
||||
title: row.title || "",
|
||||
steps,
|
||||
bot_id: Number(row.bot_id),
|
||||
bot_name: bot?.name || "The bot",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
|
||||
type Params = {
|
||||
suggestion_id: number | string;
|
||||
/**
|
||||
* Only the user they were suggested to reads them.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested, only for the user they were suggested to.
|
||||
* Throws otherwise.
|
||||
*/
|
||||
export default async function grabBotSuggestion({ suggestion_id, user_id }: Params) {
|
||||
const row = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS>({
|
||||
sql: `SELECT * FROM bot_suggestions WHERE id = ? AND user_id = ? LIMIT 1`,
|
||||
values: [Number(suggestion_id), Number(user_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row?.id) throw new AppError(`Those next steps aren't yours or no longer exist.`);
|
||||
|
||||
return row;
|
||||
}
|
||||
@@ -48,6 +48,12 @@ type Params = {
|
||||
* The tracker tasks the run worked on, linked under the message.
|
||||
*/
|
||||
task_ids?: number[];
|
||||
/**
|
||||
* The run used every step it was allowed (`BotJobOutcome.exhausted`):
|
||||
* a handed-over task it left open is blocked by `noteTrackerTask`, since
|
||||
* a run that spent its whole budget and did no work says so itself.
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -57,7 +63,8 @@ type Params = {
|
||||
* after a task and idle after a reply; with others open, it shows the one
|
||||
* still running (a reply in another session mustn't hide a task's row).
|
||||
* Nobody else's face changes. A handed-over job's result also goes to the bot that handed
|
||||
* it over (`relay`), and a handed-over task left open says so (`noteTrackerTask`). A hook
|
||||
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
|
||||
* its whole step budget without finishing (`noteTrackerTask`). A hook
|
||||
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job in a chatroom
|
||||
* moves the room on (`onChatroomJobEnded`) and leaves the bot's face alone. Throws if this handler no longer holds the job.
|
||||
*/
|
||||
@@ -70,6 +77,7 @@ export default async function completeBotJob({
|
||||
attachments,
|
||||
tool_log,
|
||||
task_ids = [],
|
||||
exhausted,
|
||||
}: Params) {
|
||||
const job = await grabLockedBotJob({ job_id, worker });
|
||||
|
||||
@@ -165,7 +173,7 @@ export default async function completeBotJob({
|
||||
face: job.kind == "reply" ? "idle" : "done",
|
||||
});
|
||||
|
||||
await noteTrackerTask({ job });
|
||||
await noteTrackerTask({ job, exhausted });
|
||||
|
||||
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import grabTaskRow, { isOpenTask } from "../tasks/grab-task-scope";
|
||||
import updateTask from "../tasks/update-task";
|
||||
import grabJobUserId from "./grab-job-user-id";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
import trackerTaskEnding from "./tracker-task-ending";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
@@ -14,17 +15,24 @@ type Params = {
|
||||
* Why it failed; left out when it finished.
|
||||
*/
|
||||
failure?: string;
|
||||
/**
|
||||
* The run used every step it was allowed and stopped before finishing
|
||||
* (`run-bot-task`'s `result.steps > max_steps`). A finished run that
|
||||
* did no work blocks the task, rather than leaving it `doing`.
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The end of a job worked on a handed-over task (`params.tracker_task_id`,
|
||||
* set by `handOverTask`), written on that task while it's still open: a
|
||||
* run that finished without closing it says so, a failed one blocks it
|
||||
* with the reason. The bot moves the task along itself as it works; this
|
||||
* only keeps the task honest when it didn't. Best effort: never fails
|
||||
* the job's wrap-up.
|
||||
* with the reason, and so does one that used up every step it had without
|
||||
* doing the work (`trackerTaskEnding`). The bot moves the task along
|
||||
* itself as it works; this only keeps the task honest when it didn't. Best
|
||||
* effort: never fails the job's wrap-up.
|
||||
*/
|
||||
export default async function noteTrackerTask({ job, failure }: Params) {
|
||||
export default async function noteTrackerTask({ job, failure, exhausted }: Params) {
|
||||
const tracker_task_id = jobTrackerTaskId({ job });
|
||||
|
||||
if (!tracker_task_id || !job.bot_id) return;
|
||||
@@ -35,17 +43,14 @@ export default async function noteTrackerTask({ job, failure }: Params) {
|
||||
if (!isOpenTask({ status: task.status })) return;
|
||||
|
||||
const name = (await grabBotById({ bot_id: job.bot_id }))?.name || "The bot";
|
||||
const ending = trackerTaskEnding({ name, status: task.status, failure, exhausted });
|
||||
const text = ending.note.slice(0, AppData.TaskNoteMaxLength);
|
||||
|
||||
if (failure === undefined) {
|
||||
await addTaskNote({
|
||||
task_id: tracker_task_id,
|
||||
text: `${name}'s run finished; the task is still ${task.status}.`,
|
||||
bot_id: job.bot_id,
|
||||
});
|
||||
if (ending.blocked_reason === null) {
|
||||
await addTaskNote({ task_id: tracker_task_id, text, bot_id: job.bot_id });
|
||||
return;
|
||||
}
|
||||
|
||||
const reason = `${name} couldn't finish it. ${failure}`.trim().slice(0, AppData.TaskNoteMaxLength);
|
||||
const user_id = await grabJobUserId({ job });
|
||||
|
||||
if (user_id) {
|
||||
@@ -53,12 +58,12 @@ export default async function noteTrackerTask({ job, failure }: Params) {
|
||||
user_id,
|
||||
task_id: tracker_task_id,
|
||||
status: "blocked",
|
||||
blocked_reason: reason,
|
||||
blocked_reason: text,
|
||||
updated_by_bot_id: job.bot_id,
|
||||
});
|
||||
}
|
||||
|
||||
await addTaskNote({ task_id: tracker_task_id, text: reason, bot_id: job.bot_id });
|
||||
await addTaskNote({ task_id: tracker_task_id, text, bot_id: job.bot_id });
|
||||
} catch (error) {
|
||||
await logError({
|
||||
title: `Couldn't note job #${job.id} on task #${tracker_task_id}`,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import trackerTaskEnding from "./tracker-task-ending";
|
||||
|
||||
describe("trackerTaskEnding", () => {
|
||||
test("says a finished run left the task where it was", () => {
|
||||
expect(trackerTaskEnding({ name: "Writer", status: "doing" })).toEqual({
|
||||
blocked_reason: null,
|
||||
note: "Writer's run finished; the task is still doing.",
|
||||
});
|
||||
});
|
||||
|
||||
test("blocks the task with why the run failed", () => {
|
||||
expect(trackerTaskEnding({ name: "Writer", status: "doing", failure: "Model refused." })).toEqual({
|
||||
blocked_reason: "Writer couldn't finish it. Model refused.",
|
||||
note: "Writer couldn't finish it. Model refused.",
|
||||
});
|
||||
});
|
||||
|
||||
test("blocks the task when the run used every step it had", () => {
|
||||
const ending = trackerTaskEnding({ name: "Writer", status: "doing", exhausted: true });
|
||||
|
||||
expect(ending.blocked_reason || "").toContain("used every step its run allowed and stopped before finishing it");
|
||||
expect(ending.note).toBe(String(ending.blocked_reason));
|
||||
});
|
||||
|
||||
test("a failure's reason wins over a spent budget", () => {
|
||||
expect(
|
||||
trackerTaskEnding({ name: "Writer", status: "doing", failure: "No room.", exhausted: true })
|
||||
.blocked_reason,
|
||||
).toBe("Writer couldn't finish it. No room.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The bot's name, as the task's own readers see it.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The task's status now.
|
||||
*/
|
||||
status?: string | null;
|
||||
/**
|
||||
* Why the run failed, when it did.
|
||||
*/
|
||||
failure?: string | undefined;
|
||||
/**
|
||||
* The run used every step it was allowed. A handed-over task's run that
|
||||
* spends its whole budget and still leaves the task open did not do the
|
||||
* work: it ended `completed` with a report saying so, which the tracker
|
||||
* never heard of, so the task read as under way forever (a retrofit run
|
||||
* spent 242 steps re-reading the branch it had to change, converted
|
||||
* nothing, and its task stayed `doing`).
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
};
|
||||
|
||||
export type TrackerTaskEnding = {
|
||||
/**
|
||||
* Why the task is blocked, or null to leave its status alone.
|
||||
*/
|
||||
blocked_reason: string | null;
|
||||
/**
|
||||
* The note left on the task, which says the same thing.
|
||||
*/
|
||||
note: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What finishing (or failing) a job says on the task it was handed over
|
||||
* with, while that task is still open. The bot moves the task along itself
|
||||
* as it works; this only keeps the task honest when it didn't, and a run
|
||||
* that says it did nothing blocks the task rather than leaving it looking
|
||||
* like work in hand.
|
||||
*/
|
||||
export default function trackerTaskEnding({ name, status, failure, exhausted }: Params): TrackerTaskEnding {
|
||||
if (failure !== undefined) {
|
||||
const note = `${name} couldn't finish it. ${failure}`.trim();
|
||||
|
||||
return { blocked_reason: note, note };
|
||||
}
|
||||
|
||||
if (exhausted) {
|
||||
const note = `${name} used every step its run allowed and stopped before finishing it. Its report says where it got to, so the rest needs a run of its own.`;
|
||||
|
||||
return { blocked_reason: note, note };
|
||||
}
|
||||
|
||||
return { blocked_reason: null, note: `${name}'s run finished; the task is still ${status || "open"}.` };
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
|
||||
import grabComputerWorkspaceQuotaBytes from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-bytes";
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import grabComputerMcpUrl from "./grab-computer-mcp-url";
|
||||
|
||||
export type FullComputerWorkspace = {
|
||||
computer_id: number;
|
||||
name: string;
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
/**
|
||||
* The biggest folder in it, from the agent's own listing.
|
||||
*/
|
||||
folder: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The share of the quota past which a computer is reported, so the
|
||||
* install hears about it while writes still fit. `AppData.ComputerWorkspaceWarnShare`
|
||||
* when left out.
|
||||
*/
|
||||
share?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Logs every computer whose workspace is nearly full, with what holds most
|
||||
* of it, and returns them. The workspace is the one folder on a computer
|
||||
* mounted from the data volume, so it is what can fill the host; nothing
|
||||
* prunes a bot's own files there (only caches, `prune-computer-caches`), so
|
||||
* without this the first sign is a bot refused its write (`21.3 GB of
|
||||
* 10.0 GB` on a real computer, nobody told until a run failed).
|
||||
*
|
||||
* Reported, never deleted: whose files to remove is the user's call.
|
||||
*/
|
||||
export default async function warnFullComputerWorkspaces({ share }: Params = {}): Promise<
|
||||
FullComputerWorkspace[]
|
||||
> {
|
||||
const quota_bytes = await grabComputerWorkspaceQuotaBytes();
|
||||
|
||||
if (quota_bytes <= 0) return [];
|
||||
|
||||
const threshold = quota_bytes * (share ?? AppData.ComputerWorkspaceWarnShare);
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<{ id: number; name: string | null }>({
|
||||
sql: `SELECT id, name FROM computers`,
|
||||
})
|
||||
).payload || [];
|
||||
const full: FullComputerWorkspace[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const address = await grabComputerMcpUrl({ computer_id: row.id }).catch(() => null);
|
||||
|
||||
if (!address?.ready) continue;
|
||||
|
||||
const usage = await grabComputerUsage({
|
||||
computer: { base_url: address.base_url, token: address.token },
|
||||
}).catch(() => null);
|
||||
|
||||
if (!usage || usage.used_bytes < threshold) continue;
|
||||
|
||||
const entry: FullComputerWorkspace = {
|
||||
computer_id: Number(row.id),
|
||||
name: row.name || `#${row.id}`,
|
||||
used_bytes: usage.used_bytes,
|
||||
quota_bytes,
|
||||
folder: usage.folders?.[0]?.path || null,
|
||||
};
|
||||
|
||||
full.push(entry);
|
||||
|
||||
await logEvent({
|
||||
title: `Computer ${entry.name} is nearly full`,
|
||||
category: "system",
|
||||
plain_text: `Computer ${entry.name} (#${entry.computer_id}) holds ${formatBytes({ bytes: entry.used_bytes })} of its ${formatBytes({ bytes: quota_bytes })} workspace limit${entry.folder ? `, most of it in ${entry.folder}` : ""}. Writes are refused once it passes the limit; clear the folder in Files, or raise the limit in Settings > General.`,
|
||||
metadata: {
|
||||
computer_id: entry.computer_id,
|
||||
used_bytes: entry.used_bytes,
|
||||
quota_bytes,
|
||||
folder: entry.folder,
|
||||
},
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
return full;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import modelContextLength from "./model-context-length";
|
||||
|
||||
describe("modelContextLength", () => {
|
||||
test("keeps what the provider's own list said", () => {
|
||||
expect(
|
||||
modelContextLength({ model: { context_length: 1_000_000 }, provider_context_length: 32_768 }),
|
||||
).toBe(1_000_000);
|
||||
});
|
||||
|
||||
test("gives a listed model the window its provider declares", () => {
|
||||
expect(modelContextLength({ model: {}, provider_context_length: 1_000_000 })).toBe(
|
||||
1_000_000,
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves a model unknown when neither said", () => {
|
||||
expect(modelContextLength({ model: {} })).toBeNull();
|
||||
expect(modelContextLength({ model: {}, provider_context_length: 0 })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { HarnessCatalogModel } from "@/src/harness/types";
|
||||
|
||||
type Params = {
|
||||
model: Pick<HarnessCatalogModel, "context_length">;
|
||||
/**
|
||||
* The window the provider's own row declares, for the models it lists
|
||||
* without one.
|
||||
*/
|
||||
provider_context_length?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The window a `harness_models` row keeps, in tokens: what the provider's
|
||||
* own list said, else the window the super admin declared for that provider
|
||||
* (a custom provider lists ids only), else nothing, and the run assumes
|
||||
* `AppData.HarnessUnknownContextWindow`.
|
||||
*/
|
||||
export default function modelContextLength({
|
||||
model,
|
||||
provider_context_length,
|
||||
}: Params) {
|
||||
return model.context_length || provider_context_length || null;
|
||||
}
|
||||
@@ -22,6 +22,11 @@ type Params = {
|
||||
*/
|
||||
api_key?: string;
|
||||
clear_key?: boolean;
|
||||
/**
|
||||
* The window its models are given when it lists none of its own. Zero
|
||||
* leaves them unknown.
|
||||
*/
|
||||
context_length?: number;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
@@ -36,6 +41,7 @@ export default async function saveHarnessProvider({
|
||||
base_url,
|
||||
api_key,
|
||||
clear_key,
|
||||
context_length,
|
||||
enabled,
|
||||
}: Params) {
|
||||
const preset = grabProviderPreset({ kind });
|
||||
@@ -64,6 +70,11 @@ export default async function saveHarnessProvider({
|
||||
name: name?.trim() || preset.title,
|
||||
base_url: final_base_url,
|
||||
enabled: enabled ? 1 : 0,
|
||||
/**
|
||||
* The row type spells an empty INTEGER as `""`, but a window is
|
||||
* cleared with null (the plugin binds it as NULL).
|
||||
*/
|
||||
context_length: (context_length && context_length > 0 ? context_length : null) as number,
|
||||
...key_update,
|
||||
};
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
|
||||
const count = await upsertHarnessModels({
|
||||
provider_id: provider.id,
|
||||
models,
|
||||
provider_context_length: provider.context_length || null,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
|
||||
@@ -25,6 +25,7 @@ export default function toPublicHarnessProvider({
|
||||
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
|
||||
needs_key: preset.needs_key,
|
||||
key_env: preset.key_env || undefined,
|
||||
context_length: provider.context_length || undefined,
|
||||
last_synced_at: provider.last_synced_at || undefined,
|
||||
sync_error: provider.sync_error || undefined,
|
||||
};
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HarnessCatalogModel } from "@/src/harness/types";
|
||||
import modelContextLength from "./model-context-length";
|
||||
|
||||
type Params = {
|
||||
provider_id: number;
|
||||
models: HarnessCatalogModel[];
|
||||
/**
|
||||
* The window its provider declares, for the models it lists without one
|
||||
* of their own (a custom provider lists ids only).
|
||||
*/
|
||||
provider_context_length?: number | null;
|
||||
now?: number;
|
||||
};
|
||||
|
||||
@@ -42,6 +48,7 @@ const ChunkSize = 50;
|
||||
export default async function upsertHarnessModels({
|
||||
provider_id,
|
||||
models,
|
||||
provider_context_length,
|
||||
now = Date.now(),
|
||||
}: Params) {
|
||||
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
|
||||
@@ -67,7 +74,7 @@ export default async function upsertHarnessModels({
|
||||
JSON.stringify(model.input_modalities),
|
||||
JSON.stringify(model.output_modalities),
|
||||
model.supports_tools ? 1 : 0,
|
||||
model.context_length ?? null,
|
||||
modelContextLength({ model, provider_context_length }),
|
||||
model.max_output_tokens ?? null,
|
||||
model.voices ? JSON.stringify(model.voices) : null,
|
||||
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HarnessCallSettings, TokenUsageSummary } from "@/src/harness/usage/types";
|
||||
import parseCallSettings from "@/src/utils/parse-call-settings";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import toolRollup, { type ToolRollup } from "@/src/utils/tool-rollup";
|
||||
import grabMessageUsage from "./grab-message-usage";
|
||||
|
||||
/**
|
||||
* The bounds a run worked under, as it reported them with each call
|
||||
* (`HarnessCallSettings.limits`): the steps it had, the prompt tokens it
|
||||
* may spend and the working context it sent per turn.
|
||||
*/
|
||||
export type RunUsageLimits = {
|
||||
steps: RunLimit | null;
|
||||
run_tokens: RunLimit | null;
|
||||
context_tokens: RunLimit | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Today's General settings' run limits, for comparing a run with what the
|
||||
* install allows now.
|
||||
*/
|
||||
export type CurrentRunLimits = {
|
||||
task_steps: RunLimit;
|
||||
reply_steps: RunLimit;
|
||||
unattended_steps: RunLimit;
|
||||
run_tokens: RunLimit;
|
||||
context_tokens: RunLimit;
|
||||
};
|
||||
|
||||
export type RunUsageCall = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
harness: string;
|
||||
/**
|
||||
* The provider and model that answered, by the names they were called
|
||||
* with.
|
||||
*/
|
||||
provider_name: string | null;
|
||||
model_slug: string | null;
|
||||
prompt_tokens: number;
|
||||
cached_tokens: number;
|
||||
completion_tokens: number;
|
||||
settings: HarnessCallSettings | null;
|
||||
};
|
||||
|
||||
export type RunUsageMessage = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
author: string;
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
calls: number;
|
||||
};
|
||||
|
||||
export type RunUsage = {
|
||||
/**
|
||||
* What was looked at: the open job (its message not written yet) or a
|
||||
* message already in the session.
|
||||
*/
|
||||
target: {
|
||||
kind: "job" | "message";
|
||||
id: number;
|
||||
created_at: number | null;
|
||||
author: string | null;
|
||||
text: string | null;
|
||||
} | null;
|
||||
totals: TokenUsageSummary | null;
|
||||
calls: RunUsageCall[];
|
||||
/**
|
||||
* The tool calls the run made, counted by tool; null when it recorded
|
||||
* none.
|
||||
*/
|
||||
tools: ToolRollup | null;
|
||||
/**
|
||||
* What bounded the run, from its own calls; null on a call recorded
|
||||
* before limits were.
|
||||
*/
|
||||
limits: RunUsageLimits | null;
|
||||
current_limits: CurrentRunLimits;
|
||||
};
|
||||
|
||||
type CallRow = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
harness: string | null;
|
||||
provider_name: string | null;
|
||||
model_slug: string | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
settings: string | null;
|
||||
};
|
||||
|
||||
type MessageRow = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
author: string | null;
|
||||
text: string | null;
|
||||
tool_log: string | null;
|
||||
};
|
||||
|
||||
const CallsSql = `SELECT t.id, t.created_at, t.harness, t.provider_name, t.model_slug,
|
||||
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.settings
|
||||
FROM token_usages t
|
||||
WHERE t.%COLUMN% = ?
|
||||
ORDER BY t.created_at ASC, t.id ASC
|
||||
LIMIT 500`;
|
||||
|
||||
const toCall = ({ row }: { row: CallRow }): RunUsageCall => ({
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || 0,
|
||||
harness: row.harness || "text",
|
||||
provider_name: row.provider_name || null,
|
||||
model_slug: row.model_slug || null,
|
||||
prompt_tokens: Number(row.prompt_tokens) || 0,
|
||||
cached_tokens: Number(row.cached_tokens) || 0,
|
||||
completion_tokens: Number(row.completion_tokens) || 0,
|
||||
settings: parseCallSettings({ json: row.settings }),
|
||||
});
|
||||
|
||||
/**
|
||||
* The limits a run worked under, from the calls themselves: each call kept
|
||||
* what the loop let it spend, so a message read months later still says
|
||||
* which limit it ran into.
|
||||
*/
|
||||
const limitsOf = ({ calls }: { calls: RunUsageCall[] }): RunUsageLimits | null => {
|
||||
const limits = calls.find((call) => call.settings?.limits)?.settings?.limits;
|
||||
|
||||
if (!limits) return null;
|
||||
|
||||
const kept = (value: RunLimit | null | undefined): RunLimit | null =>
|
||||
typeof value == "number" ? value : isUnlimitedLimit(value) ? UnlimitedLimit : null;
|
||||
|
||||
return {
|
||||
steps: kept(limits.steps),
|
||||
run_tokens: kept(limits.run_tokens),
|
||||
context_tokens: kept(limits.context_tokens),
|
||||
};
|
||||
};
|
||||
|
||||
const totalsOf = ({ prompt_tokens, completion_tokens, cost, calls }: { prompt_tokens: number; completion_tokens: number; cost?: number; calls: number }): TokenUsageSummary => ({
|
||||
prompt_tokens,
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(cost && Number.isFinite(cost) ? { cost } : {}),
|
||||
calls,
|
||||
});
|
||||
|
||||
/**
|
||||
* What one message (already checked to be in the run's own session) cost:
|
||||
* every model call it took with the settings each was made with, its tool
|
||||
* calls counted by tool, and the limits the run worked under. This is what
|
||||
* a bot reads to answer "why did that answer cost so much" before it
|
||||
* points the user at a setting (`read_message_usage`).
|
||||
*/
|
||||
export async function grabMessageRunUsage({
|
||||
message_id,
|
||||
session_id,
|
||||
}: {
|
||||
message_id: number;
|
||||
session_id: number | string;
|
||||
}) {
|
||||
const row = (
|
||||
await BunSQLite.sql<MessageRow>({
|
||||
sql: `SELECT id, created_at, author, text, tool_log FROM bot_messages WHERE id = ? AND session_id = ?`,
|
||||
values: [message_id, Number(session_id) || 0],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
const calls = (
|
||||
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "message_id"), values: [message_id] })).payload || []
|
||||
).map((item) => toCall({ row: item }));
|
||||
const prompt_tokens = calls.reduce((total, call) => total + call.prompt_tokens, 0);
|
||||
const completion_tokens = calls.reduce((total, call) => total + call.completion_tokens, 0);
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "message" as const,
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || null,
|
||||
author: row.author || null,
|
||||
text: row.text || null,
|
||||
},
|
||||
totals: totalsOf({ prompt_tokens, completion_tokens, calls: calls.length }),
|
||||
calls,
|
||||
tools: toolRollup({ tool_log: row.tool_log }),
|
||||
limits: limitsOf({ calls }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a job that is still open has spent so far, from its own calls and
|
||||
* its recorded steps: a reply cannot look at itself through a message,
|
||||
* since that is written when it ends.
|
||||
*/
|
||||
export async function grabJobRunUsage({ job_id }: { job_id: number | string }) {
|
||||
const calls = (
|
||||
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "job_id"), values: [Number(job_id) || 0] })).payload || []
|
||||
).map((item) => toCall({ row: item }));
|
||||
|
||||
if (!calls.length) return null;
|
||||
|
||||
const prompt_tokens = calls.reduce((total, call) => total + call.prompt_tokens, 0);
|
||||
const completion_tokens = calls.reduce((total, call) => total + call.completion_tokens, 0);
|
||||
|
||||
return {
|
||||
target: { kind: "job" as const, id: Number(job_id) || 0, created_at: null, author: null, text: null },
|
||||
totals: totalsOf({ prompt_tokens, completion_tokens, calls: calls.length }),
|
||||
calls,
|
||||
tools: null,
|
||||
limits: limitsOf({ calls }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's latest messages with what each cost, newest first, so a bot
|
||||
* can find the answer a user is asking about and then dig into it by id.
|
||||
*/
|
||||
export async function grabSessionMessageUsage({
|
||||
session_id,
|
||||
limit = 12,
|
||||
}: {
|
||||
session_id: number | string;
|
||||
limit?: number;
|
||||
}) {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<MessageRow>({
|
||||
sql: `SELECT id, created_at, author, text, tool_log FROM bot_messages
|
||||
WHERE session_id = ? ORDER BY id DESC LIMIT ?`,
|
||||
values: [Number(session_id) || 0, Math.max(1, Math.min(40, limit))],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
if (!rows.length) return [];
|
||||
|
||||
const totals = await grabMessageUsage({ message_ids: rows.map((row) => Number(row.id)) });
|
||||
|
||||
return rows.map((row) => {
|
||||
const usage = totals.get(Number(row.id));
|
||||
|
||||
return {
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || 0,
|
||||
author: row.author || "assistant",
|
||||
prompt_tokens: usage?.prompt_tokens || 0,
|
||||
completion_tokens: usage?.completion_tokens || 0,
|
||||
total_tokens: usage?.total_tokens || 0,
|
||||
calls: usage?.calls || 0,
|
||||
} satisfies RunUsageMessage;
|
||||
});
|
||||
}
|
||||
@@ -1,14 +1,19 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { grabModelRestSeconds } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import { isUnlimitedLimit } from "@/src/utils/run-limit";
|
||||
|
||||
/**
|
||||
* How long a failed model rests, in ms (`grabModelRestSeconds`). Falls
|
||||
* back to `AppData.HarnessModelRestMs` when the setting can't be read, so
|
||||
* a harness call never fails over it.
|
||||
* How long a failed model rests, in ms (`grabModelRestSeconds`).
|
||||
* Unlimited means a failed model isn't tried again until the setting
|
||||
* changes or the app restarts: the cooldown never runs out. Falls back to
|
||||
* `AppData.HarnessModelRestMs` when the setting can't be read, so a
|
||||
* harness call never fails over it.
|
||||
*/
|
||||
export default async function grabModelRestMs() {
|
||||
try {
|
||||
return (await grabModelRestSeconds()) * 1000;
|
||||
const seconds = await grabModelRestSeconds();
|
||||
|
||||
return isUnlimitedLimit(seconds) ? Infinity : seconds * 1000;
|
||||
} catch {
|
||||
return AppData.HarnessModelRestMs;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import type HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate } from "../types";
|
||||
|
||||
@@ -10,6 +11,11 @@ type Params = {
|
||||
* Unix ms it may be tried again, if it rests.
|
||||
*/
|
||||
rests_until?: number;
|
||||
/**
|
||||
* The model rests until the run limits change (or the app restarts):
|
||||
* `harness_model_rest_seconds` is unlimited.
|
||||
*/
|
||||
forever?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -18,11 +24,13 @@ type Params = {
|
||||
* explained afterwards. Once per failure, and a resting model isn't tried,
|
||||
* so an outage logs at most once per rest per model. Never throws.
|
||||
*/
|
||||
export default async function logCandidateFailure({ harness, candidate, error, rests_until }: Params) {
|
||||
export default async function logCandidateFailure({ harness, candidate, error, rests_until, forever }: Params) {
|
||||
const provider = candidate.provider.name || candidate.provider.kind;
|
||||
const rest = rests_until
|
||||
? ` It rests for ${Math.max(1, Math.round((rests_until - Date.now()) / 1000))} seconds.`
|
||||
: " It isn't benched; the next model takes this call.";
|
||||
const rest = forever
|
||||
? " It stays benched until the run limits change or the app restarts."
|
||||
: rests_until
|
||||
? ` It rests for ${Math.max(1, Math.round((rests_until - Date.now()) / 1000))} seconds.`
|
||||
: " It isn't benched; the next model takes this call.";
|
||||
|
||||
try {
|
||||
await logEvent({
|
||||
@@ -42,7 +50,8 @@ export default async function logCandidateFailure({ harness, candidate, error, r
|
||||
status: error.status,
|
||||
retryable: error.retryable,
|
||||
provider_wide: error.provider_wide,
|
||||
rests_until,
|
||||
rests_until: forever ? UnlimitedLimit : rests_until,
|
||||
rest_forever: forever || undefined,
|
||||
},
|
||||
});
|
||||
} catch {}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate } from "../types";
|
||||
import createCooldowns from "./create-cooldowns";
|
||||
@@ -158,6 +159,40 @@ describe("withCandidates", () => {
|
||||
expect(error.retry_at).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
test("a rest with no end keeps the model benched until the run limits change", async () => {
|
||||
const now = 1_000_000;
|
||||
const cooldowns = createCooldowns();
|
||||
const a = candidate("a");
|
||||
|
||||
await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [a],
|
||||
cooldowns,
|
||||
rest_ms: Infinity,
|
||||
now: () => now,
|
||||
run: async () => {
|
||||
throw rateLimited(a.key);
|
||||
},
|
||||
}).catch(() => {});
|
||||
|
||||
expect(cooldowns.get({ key: a.key, now: now + 5 * 365 * 24 * 3600 * 1000 })).toBe(Infinity);
|
||||
|
||||
const error = (await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [a],
|
||||
cooldowns,
|
||||
rest_ms: Infinity,
|
||||
now: () => now,
|
||||
run: async () => {
|
||||
throw new Error("should not run");
|
||||
},
|
||||
}).catch((e) => e)) as HarnessError;
|
||||
|
||||
expect(error.message).toContain("stay benched until the run limits change or the app restarts");
|
||||
expect(error.resting).toBe(true);
|
||||
expect(error.retry_at).toBe(now + AppData.HarnessMaxCooldownMs);
|
||||
});
|
||||
|
||||
test("cancellation and bugs are not swallowed", async () => {
|
||||
const run = (error: Error) =>
|
||||
withCandidates({
|
||||
|
||||
@@ -101,9 +101,11 @@ export default async function withCandidates<T>({
|
||||
);
|
||||
|
||||
throw new HarnessError({
|
||||
message: `Every ${title.toLowerCase()} model is resting after errors or rate limits. Trying again shortly.`,
|
||||
message: Number.isFinite(next)
|
||||
? `Every ${title.toLowerCase()} model is resting after errors or rate limits. Trying again shortly.`
|
||||
: `Every ${title.toLowerCase()} model is resting after errors or rate limits. They stay benched until the run limits change or the app restarts.`,
|
||||
retryable: true,
|
||||
retry_at: next,
|
||||
retry_at: Number.isFinite(next) ? next : now() + AppData.HarnessMaxCooldownMs,
|
||||
resting: true,
|
||||
});
|
||||
}
|
||||
@@ -138,10 +140,27 @@ export default async function withCandidates<T>({
|
||||
failed.push(candidate.key);
|
||||
|
||||
const rests_until = coolDown({ candidate, error, cooldowns, now: now(), rest_ms: rest });
|
||||
/**
|
||||
* A rest with no end (`harness_model_rest_seconds` unlimited)
|
||||
* never runs out: it's logged as such, never written as a
|
||||
* timestamp nothing can read back.
|
||||
*/
|
||||
const forever = typeof rests_until == "number" && !Number.isFinite(rests_until);
|
||||
|
||||
if (log_failures) {
|
||||
await logCandidateFailure({ harness, candidate, error, rests_until });
|
||||
await recordHarnessFailure({ harness, candidate, error, rests_until });
|
||||
await logCandidateFailure({
|
||||
harness,
|
||||
candidate,
|
||||
error,
|
||||
rests_until: forever ? undefined : rests_until,
|
||||
forever,
|
||||
});
|
||||
await recordHarnessFailure({
|
||||
harness,
|
||||
candidate,
|
||||
error,
|
||||
rests_until: forever ? undefined : rests_until,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-
|
||||
import textSeesImages from "@/src/utils/text-sees-images";
|
||||
import grabChatParams from "./grab-chat-params";
|
||||
import flattenSentParams from "../usage/flatten-sent-params";
|
||||
import type { HarnessCallLimits } from "../usage/types";
|
||||
import prepareMessagesForModel from "./prepare-messages-for-model";
|
||||
import stripThinkTags from "./strip-think-tags";
|
||||
|
||||
@@ -29,6 +30,11 @@ export type GenerateTextParams = {
|
||||
*/
|
||||
prefer_key?: string;
|
||||
max_tokens?: number;
|
||||
/**
|
||||
* The run's own bounds, kept with the call's usage
|
||||
* (`HarnessCallLimits`) so the answer says later which limit shaped it.
|
||||
*/
|
||||
limits?: HarnessCallLimits;
|
||||
/**
|
||||
* Overrides the saved generation settings (media reading wants 0).
|
||||
*/
|
||||
@@ -76,6 +82,7 @@ export default async function generateText({
|
||||
candidates,
|
||||
prefer_key,
|
||||
max_tokens,
|
||||
limits,
|
||||
params,
|
||||
signal = new AbortController().signal,
|
||||
media_cache = new Map(),
|
||||
@@ -108,6 +115,7 @@ export default async function generateText({
|
||||
...(saved_params ? { settings_source: saved_params.source } : {}),
|
||||
params: flattenSentParams({ params: answer.sent_params }),
|
||||
...(max_tokens ? { max_tokens } : {}),
|
||||
...(limits ? { limits } : {}),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
|
||||
@@ -207,6 +208,34 @@ describe("runTextLoop", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a run with no step limit keeps going, and records that its limits were off", async () => {
|
||||
memory.length = 0;
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const turns = 30;
|
||||
const { generate, seen } = scripted(Array.from({ length: turns }, () => loop_call));
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_steps: UnlimitedLimit,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(turns + 1);
|
||||
expect(result.steps).toBe(turns + 1);
|
||||
expect(result.text).toBe("Done.");
|
||||
expect(JSON.stringify(seen)).not.toContain("left in this run");
|
||||
expect(seen[0]!.limits).toEqual({
|
||||
steps: UnlimitedLimit,
|
||||
run_tokens: UnlimitedLimit,
|
||||
context_tokens: UnlimitedLimit,
|
||||
});
|
||||
});
|
||||
|
||||
test("at the wrap up, offers only the tools that save, then answers without any", async () => {
|
||||
const save: HarnessTool<{ path: string }> = {
|
||||
name: "write_file",
|
||||
@@ -286,6 +315,83 @@ describe("runTextLoop", () => {
|
||||
expect(result.text).toBe("Report saved.");
|
||||
});
|
||||
|
||||
test("hands the work it can't finish to start_task at the wrap up", async () => {
|
||||
const hand_off: HarnessTool<{ brief: string }> = {
|
||||
name: "start_task",
|
||||
description: "Queues a run.",
|
||||
schema: z.object({ brief: z.string() }),
|
||||
run: async ({ args }) => `Run #7 queued: ${args.brief}`,
|
||||
};
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted([
|
||||
loop_call,
|
||||
{
|
||||
tool_calls: [{ id: "t", name: "start_task", arguments: `{"brief":"write the piece"}` }],
|
||||
},
|
||||
{ text: "Research done; the writing is queued as a run." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "write the guide" }],
|
||||
tools: [remember, hand_off],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["start_task"]);
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain(
|
||||
"one turn to hand the work on: start_task is still yours",
|
||||
);
|
||||
expect(seen[2]!.tools).toBe(undefined);
|
||||
expect(result.tool_uses).toEqual([
|
||||
{ name: "remember", ok: true },
|
||||
{ name: "start_task", ok: true },
|
||||
]);
|
||||
expect(result.text).toBe("Research done; the writing is queued as a run.");
|
||||
});
|
||||
|
||||
test("offers the saving tools and the hand off together", async () => {
|
||||
const save: HarnessTool<{ path: string }> = {
|
||||
name: "write_file",
|
||||
description: "Saves a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async ({ args }) => `Saved ${args.path}.`,
|
||||
};
|
||||
const hand_off: HarnessTool<{ brief: string }> = {
|
||||
name: "start_task",
|
||||
description: "Queues a run.",
|
||||
schema: z.object({ brief: z.string() }),
|
||||
run: async ({ args }) => `Run #7 queued: ${args.brief}`,
|
||||
};
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted([
|
||||
loop_call,
|
||||
{ text: "Saved what I have." },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "audit the disk" }],
|
||||
tools: [remember, save, hand_off],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["write_file", "start_task"]);
|
||||
const prompt = String(seen[1]!.messages.at(-1)!.content);
|
||||
|
||||
expect(prompt).toContain("one turn to save what the user needs: write_file");
|
||||
expect(prompt).toContain("call start_task with a complete brief of what's left");
|
||||
});
|
||||
|
||||
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
|
||||
const max_steps = AppData.HarnessStepsLowMinSteps;
|
||||
const loop_call = {
|
||||
@@ -318,8 +424,8 @@ describe("runTextLoop", () => {
|
||||
* A 200 step audit once measured to its last step with the report
|
||||
* unwritten: the warning has to reach it with real room left.
|
||||
*/
|
||||
expect(stepsLowWarningLeft({ max_steps: AppData.HarnessMaxToolSteps })).toBe(
|
||||
Math.ceil(AppData.HarnessMaxToolSteps * AppData.HarnessStepsLowWarnShare),
|
||||
expect(stepsLowWarningLeft({ max_steps: 200 })).toBe(
|
||||
Math.ceil(200 * AppData.HarnessStepsLowWarnShare),
|
||||
);
|
||||
expect(stepsLowWarningLeft({ max_steps: 20 })).toBe(AppData.HarnessStepsLowWarning);
|
||||
});
|
||||
@@ -739,3 +845,144 @@ describe("runTextLoop", () => {
|
||||
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop repeated reads", () => {
|
||||
const readCall = ({ id, path }: { id: string; path: string }) => ({
|
||||
id,
|
||||
name: "read_file",
|
||||
arguments: JSON.stringify({ path }),
|
||||
});
|
||||
|
||||
/**
|
||||
* A read that counts how often it actually ran, and a write that only
|
||||
* exists to change what a read would say.
|
||||
*/
|
||||
const makeTools = () => {
|
||||
const counts = { reads: 0, writes: 0 };
|
||||
const read: HarnessTool<{ path: string }> = {
|
||||
name: "read_file",
|
||||
description: "Reads a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async ({ args }) => {
|
||||
counts.reads++;
|
||||
|
||||
return `contents of ${args.path} (read ${counts.reads})`;
|
||||
},
|
||||
};
|
||||
const write: HarnessTool<{ path: string }> = {
|
||||
name: "write_file",
|
||||
description: "Writes a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async () => {
|
||||
counts.writes++;
|
||||
|
||||
return "Saved.";
|
||||
},
|
||||
};
|
||||
|
||||
return { tools: [read, write], counts };
|
||||
};
|
||||
|
||||
test("answers a read repeated word for word from the first", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate, seen } = scripted([
|
||||
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
|
||||
{ text: null, tool_calls: [readCall({ id: "c2", path: "a.md" })] },
|
||||
{ text: "Done.", tool_calls: [] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Read a.md twice." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.reads).toBe(1);
|
||||
expect(result.tool_uses.map((use) => use.ok)).toEqual([true, true]);
|
||||
|
||||
const results = seen[2]!.messages.filter((message) => message.role == "tool");
|
||||
|
||||
expect(results.map((message) => message.role == "tool" && message.content)).toEqual([
|
||||
"contents of a.md (read 1)",
|
||||
alreadyRanToolNote({ name: "read_file", step: 0 }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("reads again after something may have written", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate, seen } = scripted([
|
||||
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
|
||||
{ text: null, tool_calls: [{ id: "c2", name: "write_file", arguments: `{"path":"a.md"}` }] },
|
||||
{ text: null, tool_calls: [readCall({ id: "c3", path: "a.md" })] },
|
||||
{ text: "Done.", tool_calls: [] },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Update a.md." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.reads).toBe(2);
|
||||
expect(counts.writes).toBe(1);
|
||||
|
||||
const results = seen[3]!.messages.filter((message) => message.role == "tool");
|
||||
|
||||
expect(results.map((message) => message.role == "tool" && message.content)).toEqual([
|
||||
"contents of a.md (read 1)",
|
||||
"Saved.",
|
||||
"contents of a.md (read 2)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("reads a different file on its own", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate } = scripted([
|
||||
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" }), readCall({ id: "c2", path: "b.md" })] },
|
||||
{ text: "Done.", tool_calls: [] },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Read both." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.reads).toBe(2);
|
||||
});
|
||||
|
||||
test("keeps its own answers apart from other runs", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const turns = [
|
||||
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
|
||||
{ text: "Done.", tool_calls: [] },
|
||||
];
|
||||
const first = scripted(turns);
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Read a.md." }],
|
||||
tools,
|
||||
generate: first.generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const second = scripted(turns);
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Read a.md." }],
|
||||
tools,
|
||||
generate: second.generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.reads).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import HarnessError from "../harness-error";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey from "../tools/repeat-tool-call-key";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import type {
|
||||
@@ -44,19 +47,19 @@ type Params = {
|
||||
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
|
||||
*/
|
||||
tools?: HarnessTool[];
|
||||
max_steps?: number;
|
||||
max_steps?: RunLimit;
|
||||
/**
|
||||
* Prompt tokens the run may spend in all (`grabRunMaxPromptTokens`):
|
||||
* once its turns have sent this many, the next one is the wrap up.
|
||||
* Left out, only `max_steps` ends it.
|
||||
* Unlimited or left out, only the run's other bounds end it.
|
||||
*/
|
||||
max_prompt_tokens?: number;
|
||||
max_prompt_tokens?: RunLimit;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most each turn
|
||||
* sends before old tool output is trimmed, whatever the model's
|
||||
* window. Left out, the window decides.
|
||||
* window. Unlimited or left out, the window decides.
|
||||
*/
|
||||
context_budget?: number;
|
||||
context_budget?: RunLimit;
|
||||
signal?: AbortSignal;
|
||||
/**
|
||||
* Called after each model turn, before its tools run. Use it for
|
||||
@@ -117,12 +120,29 @@ export type TextLoopResult = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The only tools the wrap up may still call: saving the work. A run that
|
||||
* spent every step measuring can write the report the user waits for
|
||||
* rather than throw its findings away (`write_file`, and `import_file`
|
||||
* for what it pulled off a computer).
|
||||
* The wrap-up tools that save the work. A run that spent every step
|
||||
* measuring can write the report the user waits for rather than throw its
|
||||
* findings away (`write_file`, and `import_file` for what it pulled off a
|
||||
* computer).
|
||||
*/
|
||||
export const WrapUpToolNames = ["write_file", "import_file"];
|
||||
export const WrapUpSaveToolNames = ["write_file", "import_file"];
|
||||
|
||||
/**
|
||||
* The wrap-up tool that hands the work on. A chat reply has a step
|
||||
* budget (`AppData.BotReplyMaxToolSteps`, unlimited unless the install
|
||||
* sets one), and a reply that used it all researching leaves the writing
|
||||
* undone; the next reply starts from the same budget, so the run queues
|
||||
* the rest as a task (`start_task`) while it can still call a tool,
|
||||
* rather than saying it will do it later. The app runs it as soon as the
|
||||
* reply is out.
|
||||
*/
|
||||
export const WrapUpHandOffToolNames = ["start_task"];
|
||||
|
||||
/**
|
||||
* Every tool the wrap up may still call (`WrapUpSaveToolNames` and
|
||||
* `WrapUpHandOffToolNames`): those the run has, in its own order.
|
||||
*/
|
||||
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames];
|
||||
|
||||
/**
|
||||
* Saving turns a wrap up may take: the first, and one more when it reached
|
||||
@@ -134,26 +154,50 @@ export const WrapUpSavingTurns = 2;
|
||||
* Told on the last step, with the app's record of the tools the run
|
||||
* called (`describeToolUses`): out of steps, a model tends to report the
|
||||
* work it planned as done. `tokens` when the run's token budget ended it
|
||||
* rather than its steps. `saving` names the tools it may still call, if
|
||||
* any: its one saving round, after which it answers with none.
|
||||
* rather than its steps. `saving` and `hand_off` name the tools it may
|
||||
* still call, if any: its one last round, after which it answers with
|
||||
* none.
|
||||
*/
|
||||
export const wrapUpPrompt = ({
|
||||
uses,
|
||||
reason = "steps",
|
||||
saving = [],
|
||||
hand_off = [],
|
||||
}: {
|
||||
uses: HarnessToolUse[];
|
||||
reason?: "steps" | "tokens";
|
||||
saving?: string[];
|
||||
hand_off?: string[];
|
||||
}) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${
|
||||
saving.length
|
||||
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable) and nothing else, then report. After this turn no tool is left, so anything unsaved is lost.`
|
||||
: `Don't call any more tools.`
|
||||
} Report what you did, what is left, and anything you need from the user.
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${wrapUpToolsPrompt({
|
||||
saving,
|
||||
hand_off,
|
||||
})} Report what you did, what is left, and anything you need from the user.
|
||||
|
||||
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
|
||||
|
||||
/**
|
||||
* What the wrap up may still call, said in one line: save the work, hand
|
||||
* on what it can't finish, or neither.
|
||||
*/
|
||||
const wrapUpToolsPrompt = ({ saving, hand_off }: { saving: string[]; hand_off: string[] }) => {
|
||||
if (!saving.length && !hand_off.length) return `Don't call any more tools.`;
|
||||
|
||||
return [
|
||||
saving.length
|
||||
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable) and nothing else, then report.`
|
||||
: "",
|
||||
saving.length
|
||||
? `If real work is left that this run can't finish, call ${hand_off.join(" or ")} with a complete brief of what's left: it runs after this turn and posts its own result.`
|
||||
: hand_off.length
|
||||
? `You have one turn to hand the work on: ${hand_off.join(" or ")} is still yours. If real work is left, call it with a complete brief of what's left: it runs after this turn and posts its own result.`
|
||||
: "",
|
||||
`After this turn no tool is left, so anything unsaved is lost, and so is work you only say you'll do later.`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
};
|
||||
|
||||
/**
|
||||
* Steps left when a run is warned, once, to save: a share of the run for
|
||||
* long ones, since 5 steps is the whole budget of a short one and no time
|
||||
@@ -195,8 +239,11 @@ Don't repeat tool calls you have already made.`;
|
||||
* go back to it, and so on until it answers without calling a tool. Tools
|
||||
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
|
||||
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
|
||||
* model is asked to wrap up: one turn with only the saving tools
|
||||
* (`WrapUpToolNames`), then one with none. An answer `review` finds fault
|
||||
* model is asked to wrap up: one turn with only the wrap-up tools
|
||||
* (`WrapUpToolNames`: what saves the work, and `start_task` for the rest),
|
||||
* then one with none. With neither set (unlimited), the run ends when the
|
||||
* model answers without calling a tool, or when its job's deadline or its
|
||||
* abort signal ends it. An answer `review` finds fault
|
||||
* with is written again once.
|
||||
*
|
||||
* Every turn resends everything, so the run keeps it small: only the
|
||||
@@ -262,17 +309,45 @@ export default async function runTextLoop({
|
||||
};
|
||||
const tool_uses: HarnessToolUse[] = [];
|
||||
/**
|
||||
* The tools a wrap up may still call: only the ones that save the work.
|
||||
* A run that spent every step measuring can then still write the report
|
||||
* the user is waiting for, which is what two runs in a row failed to do
|
||||
* (they measured to the last step and had no tool left to save with).
|
||||
* The reads this run already made, by the call they answer
|
||||
* (`repeatToolCallKey`) and the step it was. A read repeated word for
|
||||
* word gets this answer instead of being run again, and anything that
|
||||
* may have written forgets them: a file read once, then edited, is
|
||||
* read again.
|
||||
*/
|
||||
const save_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
|
||||
const save_definitions = save_tools.map((tool) => all_definitions.get(tool.name)!);
|
||||
const warn_at = stepsLowWarningLeft({ max_steps });
|
||||
const repeated_reads = new Map<string, number>();
|
||||
/**
|
||||
* The tools a wrap up may still call: what saves the work, and
|
||||
* `start_task` for the work it can't finish. A run that spent every
|
||||
* step measuring can then still write the report the user is waiting
|
||||
* for, which is what two runs in a row failed to do (they measured to
|
||||
* the last step and had no tool left to save with), and a reply out of
|
||||
* steps hands the rest to a task instead of promising it.
|
||||
*/
|
||||
const wrap_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
|
||||
const save_tools = wrap_tools.filter((tool) => WrapUpSaveToolNames.includes(tool.name));
|
||||
const hand_off_tools = wrap_tools.filter((tool) => WrapUpHandOffToolNames.includes(tool.name));
|
||||
const wrap_definitions = wrap_tools.map((tool) => all_definitions.get(tool.name)!);
|
||||
/**
|
||||
* What bounds this run, recorded with every call it makes, so a reply
|
||||
* can be told later which limit shaped it (`read_message_usage`).
|
||||
* `null` only ever means an old record; new runs say `"unlimited"`.
|
||||
*/
|
||||
const call_limits = {
|
||||
steps: max_steps,
|
||||
run_tokens: max_prompt_tokens ?? UnlimitedLimit,
|
||||
context_tokens: context_budget ?? UnlimitedLimit,
|
||||
};
|
||||
/**
|
||||
* A step count to count against, for the loop itself: an unlimited run
|
||||
* counts on to the model's own answer (or the job's deadline).
|
||||
*/
|
||||
const step_ceiling = isUnlimitedLimit(max_steps) ? Infinity : max_steps;
|
||||
|
||||
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
let warned_steps = max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
let warned_steps = isUnlimitedLimit(max_steps) || max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
/**
|
||||
* The wrap up is announced once, and may save until it has: a run told
|
||||
* to stop with its report unwritten gets a turn to write it (at most
|
||||
@@ -280,22 +355,31 @@ export default async function runTextLoop({
|
||||
*/
|
||||
let wrap_up_announced = false;
|
||||
let saving_turns = 0;
|
||||
let saved = false;
|
||||
/**
|
||||
* The wrap up had its one round of tools (saving, or handing the work
|
||||
* on): the next turn offers none, so the run always ends.
|
||||
*/
|
||||
let used_wrap_turn = false;
|
||||
|
||||
for (let index = 0; index <= max_steps + 1 + WrapUpSavingTurns; index++) {
|
||||
for (let index = 0; index <= step_ceiling + 1 + WrapUpSavingTurns; index++) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
}
|
||||
|
||||
const out_of_steps = index >= max_steps;
|
||||
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens);
|
||||
const out_of_steps = index >= step_ceiling;
|
||||
const out_of_tokens = Boolean(
|
||||
typeof max_prompt_tokens == "number" &&
|
||||
max_prompt_tokens > 0 &&
|
||||
usage.prompt_tokens >= max_prompt_tokens,
|
||||
);
|
||||
const wrap_up = out_of_steps || out_of_tokens;
|
||||
/**
|
||||
* The saving turn: only the tools that save the work. Without one
|
||||
* of them, or once it saved, the wrap up is the old one, with no
|
||||
* tools at all, so the run always ends.
|
||||
* The saving turn: only the tools a wrap up has left. Without one
|
||||
* of them, or once it had its round, the wrap up is the old one,
|
||||
* with no tools at all, so the run always ends.
|
||||
*/
|
||||
const wrap_up_saving = wrap_up && !saved && saving_turns < WrapUpSavingTurns && save_tools.length > 0;
|
||||
const wrap_up_saving =
|
||||
wrap_up && !used_wrap_turn && saving_turns < WrapUpSavingTurns && wrap_tools.length > 0;
|
||||
|
||||
if (wrap_up && !wrap_up_announced) {
|
||||
wrap_up_announced = true;
|
||||
@@ -308,13 +392,14 @@ export default async function runTextLoop({
|
||||
uses: tool_uses,
|
||||
reason: out_of_steps ? "steps" : "tokens",
|
||||
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
|
||||
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
if (wrap_up_saving) saving_turns++;
|
||||
|
||||
const definitions = wrap_up_saving ? save_definitions : wrap_up ? [] : definitionsNow();
|
||||
const definitions = wrap_up_saving ? wrap_definitions : wrap_up ? [] : definitionsNow();
|
||||
|
||||
/**
|
||||
* Sized for the model the run is on (or will start on). A fallback
|
||||
@@ -325,8 +410,8 @@ export default async function runTextLoop({
|
||||
fitTranscriptToContext({
|
||||
system: run_system,
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessAutoMinContext,
|
||||
budget_tokens: context_budget,
|
||||
context_length: model?.context_length || AppData.HarnessUnknownContextWindow,
|
||||
budget_tokens: typeof context_budget == "number" ? context_budget : undefined,
|
||||
tools_chars: JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
@@ -339,6 +424,7 @@ export default async function runTextLoop({
|
||||
media_cache,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
limits: call_limits,
|
||||
});
|
||||
|
||||
prefer_key = answer.candidate.key;
|
||||
@@ -351,7 +437,7 @@ export default async function runTextLoop({
|
||||
* saving ones, and the last turn offers none.
|
||||
*/
|
||||
const tool_calls = (wrap_up ? (wrap_up_saving ? answer.tool_calls : []) : answer.tool_calls).filter(
|
||||
(call) => !wrap_up || save_tools.some((tool) => tool.name == call.name),
|
||||
(call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name),
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -362,7 +448,7 @@ export default async function runTextLoop({
|
||||
if (wrap_up_saving && answer.tool_calls.length && !tool_calls.length) {
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
content: `Only ${save_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
|
||||
content: `Only ${wrap_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -412,12 +498,18 @@ export default async function runTextLoop({
|
||||
};
|
||||
}
|
||||
|
||||
if (wrap_up_saving) saved = true;
|
||||
if (wrap_up_saving) used_wrap_turn = true;
|
||||
|
||||
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
|
||||
|
||||
for (const call of tool_calls) {
|
||||
const { text: content, images } = await runToolCall({ call, tools: run_tools, signal });
|
||||
const repeat_key = repeatToolCallKey({ call });
|
||||
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
|
||||
const { text: content, images } =
|
||||
already_read !== undefined
|
||||
? { text: alreadyRanToolNote({ name: call.name, step: already_read }), images: [] }
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
@@ -428,6 +520,14 @@ export default async function runTextLoop({
|
||||
}
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
|
||||
if (!repeat_key) {
|
||||
repeated_reads.clear();
|
||||
} else if (already_read === undefined) {
|
||||
if (content.startsWith("Error:")) repeated_reads.delete(repeat_key);
|
||||
else repeated_reads.set(repeat_key, index);
|
||||
}
|
||||
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
|
||||
if (images.length) shown.push({ tool_name: call.name, images });
|
||||
@@ -454,10 +554,12 @@ export default async function runTextLoop({
|
||||
|
||||
/**
|
||||
* Steps left before the wrap up, once the next turn is taken.
|
||||
* An unlimited run is never told it's nearly out: it has no budget
|
||||
* to be near the end of.
|
||||
*/
|
||||
const left = max_steps - (index + 1);
|
||||
const left = step_ceiling - (index + 1);
|
||||
|
||||
if (!warned_steps && left <= warn_at) {
|
||||
if (!warned_steps && !isUnlimitedLimit(max_steps) && left <= warn_at) {
|
||||
warned_steps = true;
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import updateMemoryTool from "./update-memory-tool";
|
||||
import reactToMessageTool from "./react-to-message-tool";
|
||||
import setPictureTool from "./set-picture-tool";
|
||||
import askCrewTool from "./ask-crew-tool";
|
||||
import readMessageUsageTool from "./settings/read-message-usage-tool";
|
||||
import readSettingsTool from "./settings/read-settings-tool";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
@@ -93,6 +95,8 @@ export default async function grabBotTools({
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
return [
|
||||
setPictureTool({ user_id, bot_id, scopes, is_coordinator }),
|
||||
readSettingsTool(),
|
||||
readMessageUsageTool({ session_id }),
|
||||
updateMemoryTool({ user_id, bot_id, workspace_id }),
|
||||
updateInstructionsTool({ user_id, bot_id, workspace_id }),
|
||||
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { z } from "zod";
|
||||
import grabRunLimitsOverview from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import {
|
||||
grabJobRunUsage,
|
||||
grabMessageRunUsage,
|
||||
grabSessionMessageUsage,
|
||||
type CurrentRunLimits,
|
||||
} from "@/src/functions/backend/db/usage/grab-run-usage";
|
||||
import { grabHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
|
||||
import describeRunUsage, { describeMessageUsageList } from "@/src/utils/describe-run-usage";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
session_id?: number | string | null;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
message_id?: number;
|
||||
job_id?: number;
|
||||
latest?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a run or one of its answers cost, call by call: the model, the
|
||||
* prompt and completion tokens, the cached part, the settings each call was
|
||||
* made with, and the limits the run worked under against today's. With no
|
||||
* ids it lists the conversation's latest messages so a bot can find the one
|
||||
* a user is asking about, then read it by id.
|
||||
*/
|
||||
export default function readMessageUsageTool({ session_id }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "read_message_usage",
|
||||
description: `Look at what model calls a run cost, to answer "why did that cost so much" or "why was that reply cut short".
|
||||
|
||||
With no arguments it lists this conversation's latest messages with their token totals and ids. Pass a message_id to dig into one: every call it took (provider and model, prompt and completion tokens, how much came from the model's cache), the limits the run worked under as recorded then, today's limits for comparison, and the tools it called, counted.
|
||||
|
||||
Long runs cost more than the work suggests because every turn resends the prompt, the tool definitions and the whole transcript: many steps, or a long session re-read each time, is the usual cause. When you have read the calls, say what happened and, when a setting explains it, name that setting with its value and the ref from read_settings so the user can change it. Never guess a figure: report only what you read.`,
|
||||
schema: z.object({
|
||||
message_id: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("The message to read (ids come from this conversation's list, or from a past session you read)."),
|
||||
job_id: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("A run's job id, for a run whose message isn't written yet. Leave it out to read the run you are in."),
|
||||
latest: z.boolean().optional().describe("List the conversation's latest messages again."),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const limits = await grabRunLimitsOverview().catch(() => null);
|
||||
const current_limits: CurrentRunLimits = {
|
||||
task_steps: limits?.task_steps ?? limits?.task_default ?? 0,
|
||||
reply_steps: limits?.reply_steps ?? limits?.reply_default ?? 0,
|
||||
unattended_steps: limits?.unattended_steps ?? limits?.unattended_default ?? 0,
|
||||
run_tokens: limits?.run_tokens ?? limits?.run_tokens_default ?? 0,
|
||||
context_tokens: limits?.context_tokens ?? limits?.context_tokens_default ?? 0,
|
||||
};
|
||||
const scope = grabHarnessUsageScope();
|
||||
const run_session_id = Number(scope?.session_id) || Number(session_id) || 0;
|
||||
|
||||
if (!args.message_id && !args.job_id && args.latest) {
|
||||
return describeMessageUsageList({ messages: await grabSessionMessageUsage({ session_id: run_session_id }) });
|
||||
}
|
||||
|
||||
if (args.message_id) {
|
||||
const usage = await grabMessageRunUsage({ message_id: args.message_id, session_id: run_session_id });
|
||||
|
||||
if (!usage) {
|
||||
return `Message #${args.message_id} isn't in this conversation. Read the list by calling again with latest: true, or read a past session first.`;
|
||||
}
|
||||
|
||||
return describeRunUsage({ usage: { ...usage, current_limits } });
|
||||
}
|
||||
|
||||
const job_id = args.job_id || Number(scope?.job_id) || 0;
|
||||
|
||||
if (!job_id) return describeMessageUsageList({ messages: await grabSessionMessageUsage({ session_id: run_session_id }) });
|
||||
|
||||
const usage = await grabJobRunUsage({ job_id });
|
||||
|
||||
if (!usage) {
|
||||
return `No model calls recorded for run #${job_id} yet.`;
|
||||
}
|
||||
|
||||
return describeRunUsage({ usage: { ...usage, current_limits } });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { z } from "zod";
|
||||
import { CitableGeneralSettingsSections } from "@/src/dict/general-settings-dict";
|
||||
import grabGeneralSettingsValues from "@/src/functions/backend/db/app-settings/grab-general-settings-values";
|
||||
import describeGeneralSettings from "@/src/utils/describe-general-settings";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Args = {
|
||||
section?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The General settings a run's limits come from, read live, with the ref
|
||||
* that points a reader at each one. A bot that hit a limit (steps used up,
|
||||
* a folder full, a message too long) and one answering "why did that cost
|
||||
* so much" both need to name the same page and value.
|
||||
*/
|
||||
export default function readSettingsTool(): HarnessTool<Args> {
|
||||
return {
|
||||
name: "read_settings",
|
||||
description: `Read Settings > General as it is now: the app's run limits (steps per task, per chat reply and per routine or hook call, tokens per run, working context), session length, message length, skill limits, retention days and storage quotas, each with who may change it and the ref to write.
|
||||
|
||||
Use it when a limit stopped you or shaped your answer, and when the user asks why something is capped, why a reply was cut short or why a message was refused: say the setting, its value as the form shows it and who can change it, then write its ref exactly as given (e.g. [setting:run-limits:reply_steps]) - the chat shows that as a pill that opens the page and the field.
|
||||
|
||||
You never change these settings yourself, and never say one was changed.`,
|
||||
schema: z.object({
|
||||
section: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("One section's key, to read only that (e.g. run-limits, storage). Leave it out for all of them."),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const everything = await grabGeneralSettingsValues();
|
||||
const citable = everything.filter((section) =>
|
||||
CitableGeneralSettingsSections.some((known) => known.key == section.key),
|
||||
);
|
||||
|
||||
if (!args.section) return describeGeneralSettings({ sections: citable });
|
||||
|
||||
const one = citable.find((section) => section.key == args.section);
|
||||
|
||||
if (!one) {
|
||||
return `There is no citable setting section "${args.section}". The ones you can name: ${citable.map((section) => section.key).join(", ")}.`;
|
||||
}
|
||||
|
||||
return describeGeneralSettings({ sections: [one] });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import suggestNextStepsTool from "./suggest-next-steps-tool";
|
||||
|
||||
const refs: string[] = [];
|
||||
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
|
||||
|
||||
describe("suggestNextStepsTool", () => {
|
||||
test("takes a set of steps with an optional heading", () => {
|
||||
expect(tool.schema?.safeParse({ title: "What I can do next", steps: ["Write the report", "Email the team"] }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ steps: ["Write the report"] }).success).toBe(true);
|
||||
});
|
||||
|
||||
test("needs at least one step and no duplicates", () => {
|
||||
expect(tool.schema?.safeParse({ steps: [] }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: ["Write the report", "write the report"] }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: [" "] }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("caps how many steps one row holds and how long each is", () => {
|
||||
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { z } from "zod";
|
||||
import createBotSuggestion from "@/src/functions/backend/db/bot-suggestions/create-bot-suggestion";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotSuggestionStepsSchema } from "@/src/schemas/bot-suggestion-schema";
|
||||
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* The conversation they show in.
|
||||
*/
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Called with the suggestions' ref, so the message always carries
|
||||
* their buttons.
|
||||
*/
|
||||
onSuggest: (params: { ref: string }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
title?: string;
|
||||
steps: z.infer<typeof BotSuggestionStepsSchema>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Offers the user concrete next steps as buttons under the bot's answer.
|
||||
* Clicking one puts it in their input; nothing waits on it, unlike
|
||||
* `ask_user`, so the reply goes on as usual. Once per run, so every
|
||||
* suggestion lands in one row.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
name: "suggest_next_steps",
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and carry on as if they may ignore it. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(AppData.BotSuggestionTitleMaxChars)
|
||||
.optional()
|
||||
.describe(`A short heading for the row, e.g. "What I can do next" (defaults to "Next steps")`),
|
||||
steps: BotSuggestionStepsSchema.describe("The suggested steps, best first, each written as the message the user would send"),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (suggested) {
|
||||
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
|
||||
}
|
||||
|
||||
const id = await createBotSuggestion({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
title: args.title?.trim() || "",
|
||||
steps: args.steps,
|
||||
});
|
||||
|
||||
suggested = true;
|
||||
onSuggest({ ref: botSuggestionRef({ id }) });
|
||||
|
||||
const count = args.steps.length;
|
||||
|
||||
return `Suggested ${count} next step${count == 1 ? "" : "s"}: the buttons are under your message, and clicking one puts it in the user's input. They need do nothing; don't wait for them and don't repeat the steps in your text.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
|
||||
import grabComputerUsage, { type ComputerUsageFolder } from "@/src/functions/backend/computers/grab-computer-usage";
|
||||
import grabComputerWorkspaceQuotaBytes from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-bytes";
|
||||
import generalSettingsRef from "@/src/utils/general-settings-ref";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import computerWorkspaceSpace from "./computer-workspace-space";
|
||||
|
||||
type Params = {
|
||||
computer: ComputerApi;
|
||||
@@ -56,27 +58,54 @@ export default async function computerWorkspaceRoomError({ computer, dirs, incom
|
||||
if (!usage) return null;
|
||||
if (workspaceHasRoom({ used_bytes: usage.used_bytes, quota_bytes, incoming_bytes })) return null;
|
||||
|
||||
return computerWorkspaceFullMessage({ used_bytes: usage.used_bytes, quota_bytes, dirs });
|
||||
return computerWorkspaceFullMessage({
|
||||
used_bytes: usage.used_bytes,
|
||||
quota_bytes,
|
||||
dirs,
|
||||
folders: usage.folders,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The setting that bounds a computer's workspace, as the ref a bot writes
|
||||
* when it reports the refusal.
|
||||
*/
|
||||
const computerWorkspaceQuotaRef = generalSettingsRef({
|
||||
section: "computer-workspaces",
|
||||
field: "quota_mb",
|
||||
});
|
||||
|
||||
/**
|
||||
* What a bot is told when the workspace is full: what is used, what the
|
||||
* limit is, and what to do instead. `dir` is where its own work is, the one
|
||||
* folder it may safely clear.
|
||||
* limit is, where the space went (`computerWorkspaceSpace`), and what to do
|
||||
* instead. `dirs` is where its own work is, the one folder it may safely
|
||||
* clear.
|
||||
*/
|
||||
export function computerWorkspaceFullMessage({
|
||||
used_bytes,
|
||||
quota_bytes,
|
||||
dirs,
|
||||
folders,
|
||||
}: {
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
dirs: ComputerRunDirs;
|
||||
folders?: ComputerUsageFolder[];
|
||||
}) {
|
||||
const space = computerWorkspaceSpace({ folders, dirs });
|
||||
|
||||
const advice = space && !space.clearable
|
||||
? `Nothing was written. The room has to come back from that folder: name it in your report, with what you needed to write, so the user can clear it through Files or raise the limit (${computerWorkspaceQuotaRef}). Anything you can delete in ${dirs.bot_dir ?? dirs.cwd} still helps, and importing what matters into your files and removing it here frees that much.`
|
||||
: `Nothing was written. Free space first with computer_bash: delete what you no longer need in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and then remove it here.`;
|
||||
|
||||
return [
|
||||
`No room left on this computer: its workspace holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}.`,
|
||||
`Nothing was written. Free space first with computer_bash: delete what you no longer need in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and then remove it here.`,
|
||||
].join(" ");
|
||||
`The limit is Settings > General's megabytes per computer (${computerWorkspaceQuotaRef}, ${Math.round(quota_bytes / (1024 * 1024)).toLocaleString("en-US")} MB now): only the super admin can raise it.`,
|
||||
space?.description || "",
|
||||
advice,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,12 +117,16 @@ export function computerWorkspaceFullNote({
|
||||
used_bytes,
|
||||
quota_bytes,
|
||||
dirs,
|
||||
folders,
|
||||
}: {
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
dirs: ComputerRunDirs;
|
||||
folders?: ComputerUsageFolder[];
|
||||
}) {
|
||||
return `[This computer's workspace now holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}: writes through computer_write_file and computer_edit_file are refused until there is room. Free space in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and remove it here.]`;
|
||||
const space = computerWorkspaceSpace({ folders, dirs });
|
||||
|
||||
return `[This computer's workspace now holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}${space ? `: ${space.description}` : ""} Writes through computer_write_file and computer_edit_file are refused until there is room. Free space in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and remove it here.]`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,5 +143,10 @@ export async function computerWorkspaceFullWarning({ computer, dirs, signal }: O
|
||||
if (!usage) return null;
|
||||
if (workspaceHasRoom({ used_bytes: usage.used_bytes, quota_bytes, incoming_bytes: 0 })) return null;
|
||||
|
||||
return computerWorkspaceFullNote({ used_bytes: usage.used_bytes, quota_bytes, dirs });
|
||||
return computerWorkspaceFullNote({
|
||||
used_bytes: usage.used_bytes,
|
||||
quota_bytes,
|
||||
dirs,
|
||||
folders: usage.folders,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import computerWorkspaceSpace from "./computer-workspace-space";
|
||||
|
||||
const worker: ComputerRunDirs = {
|
||||
workspace: "/home/gem/workspace",
|
||||
cwd: "/home/cb-9/workspace/users/1",
|
||||
bot_dir: "/home/cb-9/workspace",
|
||||
shared_dir: null,
|
||||
roots: ["/home/cb-9/workspace"],
|
||||
user_id: 1,
|
||||
run_as: { bot_id: 9, workspace_id: null },
|
||||
};
|
||||
|
||||
const coordinator: ComputerRunDirs = {
|
||||
...worker,
|
||||
bot_dir: "/home/gem/workspace/bots/2",
|
||||
run_as: null,
|
||||
};
|
||||
|
||||
const folders = (path: string) => [{ path, bytes: 22_000_000_000 }];
|
||||
|
||||
describe("computerWorkspaceSpace", () => {
|
||||
test("says nothing without a folder to name", () => {
|
||||
expect(computerWorkspaceSpace({ dirs: worker })).toBe(null);
|
||||
expect(computerWorkspaceSpace({ folders: [], dirs: worker })).toBe(null);
|
||||
});
|
||||
|
||||
test("names the run's own folder as one it may clear", () => {
|
||||
const space = computerWorkspaceSpace({ folders: folders("bots/9"), dirs: worker });
|
||||
|
||||
expect(space?.clearable).toBe(true);
|
||||
expect(space?.description).toContain("your own folder (bots/9");
|
||||
});
|
||||
|
||||
test("names the workspace's shared folder as one it may clear", () => {
|
||||
const space = computerWorkspaceSpace({
|
||||
folders: folders("workspaces/3"),
|
||||
dirs: { ...worker, shared_dir: "/home/cb-9/workspace/workspaces/3", run_as: { bot_id: 9, workspace_id: 3 } },
|
||||
});
|
||||
|
||||
expect(space?.clearable).toBe(true);
|
||||
expect(space?.description).toContain("this workspace's shared folder (workspaces/3");
|
||||
});
|
||||
|
||||
test("a worker is told when the space is another bot's folder", () => {
|
||||
const space = computerWorkspaceSpace({ folders: folders("bots/3"), dirs: worker });
|
||||
|
||||
expect(space?.clearable).toBe(false);
|
||||
expect(space?.description).toContain("another bot's folder");
|
||||
});
|
||||
|
||||
test("a worker is told when the space is a workspace it isn't in", () => {
|
||||
const space = computerWorkspaceSpace({ folders: folders("workspaces/4"), dirs: worker });
|
||||
|
||||
expect(space?.clearable).toBe(false);
|
||||
expect(space?.description).toContain("another workspace's folder");
|
||||
});
|
||||
|
||||
test("the coordinator may clear any folder it is shown", () => {
|
||||
const space = computerWorkspaceSpace({ folders: folders("bots/3"), dirs: coordinator });
|
||||
|
||||
expect(space?.clearable).toBe(true);
|
||||
expect(space?.description).toContain("which you can reach as the coordinator");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { ComputerUsageFolder } from "@/src/functions/backend/computers/grab-computer-usage";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The biggest folders in the workspace, most first (`grabComputerUsage`).
|
||||
*/
|
||||
folders?: ComputerUsageFolder[];
|
||||
dirs: ComputerRunDirs;
|
||||
};
|
||||
|
||||
export type WorkspaceSpace = {
|
||||
/**
|
||||
* What the run is told about the folder holding the space, one sentence.
|
||||
*/
|
||||
description: string;
|
||||
/**
|
||||
* Whether that folder is one the run may clear: its own, the shared one
|
||||
* in a workspace, or anything at all for the coordinator. A worker
|
||||
* can't touch another bot's folder, so clearing it itself is not an
|
||||
* option it should be pointed at.
|
||||
*/
|
||||
clearable: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a computer's workspace went: its biggest folder, named with whose
|
||||
* it is. The workspace is one folder for every bot and user on that
|
||||
* computer, so a bot told only "it's full" reported a limit it could never
|
||||
* reach from its own folder (a bot's `du` showed 25 MB while the volume
|
||||
* held 21.3 GB, most of it another bot's screenshots), which is what this
|
||||
* answers.
|
||||
*/
|
||||
export default function computerWorkspaceSpace({ folders, dirs }: Params): WorkspaceSpace | null {
|
||||
const biggest = folders?.[0];
|
||||
|
||||
if (!biggest) return null;
|
||||
|
||||
const size = formatBytes({ bytes: biggest.bytes });
|
||||
const shared = dirs.shared_dir ? dirs.shared_dir.replace(/\/+$/, "").split("/").slice(-2).join("/") : "";
|
||||
|
||||
if (biggest.path == `bots/${dirs.run_as?.bot_id}`) {
|
||||
return {
|
||||
description: `Most of it is in your own folder (${biggest.path}, ${size}), so clearing it is yours to do.`,
|
||||
clearable: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (shared && biggest.path == shared) {
|
||||
return {
|
||||
description: `Most of it is in this workspace's shared folder (${biggest.path}, ${size}).`,
|
||||
clearable: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (!dirs.run_as) {
|
||||
return {
|
||||
description: `Most of it is in ${biggest.path} (${size}), which you can reach as the coordinator, so clearing it is yours to do.`,
|
||||
clearable: true,
|
||||
};
|
||||
}
|
||||
|
||||
const [group] = biggest.path.split("/");
|
||||
const owner = group == "workspaces" ? "workspace" : "bot";
|
||||
|
||||
return {
|
||||
description: `Most of it is in ${biggest.path} (${size}), another ${owner}'s folder (this computer has one workspace for every bot and user), which you can't clear.`,
|
||||
clearable: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import repeatToolCallKey from "./repeat-tool-call-key";
|
||||
|
||||
const call = ({ name, arguments: args }: { name: string; arguments: string }) => ({ id: "1", name, arguments: args });
|
||||
|
||||
describe("repeatToolCallKey", () => {
|
||||
test("matches the same read whatever order the arguments came in", () => {
|
||||
const first = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"a.md","offset":1}` }) });
|
||||
const second = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"offset":1,"path":"a.md"}` }) });
|
||||
|
||||
expect(first).not.toBeNull();
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
test("tells different arguments and different tools apart", () => {
|
||||
const first = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"a.md"}` }) });
|
||||
|
||||
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"b.md"}` }) })).not.toBe(first);
|
||||
expect(repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"path":"a.md"}` }) })).not.toBe(first);
|
||||
});
|
||||
|
||||
test("reads arguments left out as an empty object", () => {
|
||||
expect(repeatToolCallKey({ call: call({ name: "list_tasks", arguments: "" }) })).toBe("list_tasks:{}");
|
||||
expect(repeatToolCallKey({ call: call({ name: "list_tasks", arguments: " " }) })).toBe("list_tasks:{}");
|
||||
});
|
||||
|
||||
test("never repeats a tool that may write", () => {
|
||||
expect(repeatToolCallKey({ call: call({ name: "computer_bash", arguments: `{"command":"ls"}` }) })).toBeNull();
|
||||
expect(repeatToolCallKey({ call: call({ name: "write_file", arguments: `{"path":"a.md"}` }) })).toBeNull();
|
||||
expect(repeatToolCallKey({ call: call({ name: "computer_write_file", arguments: `{"path":"a.md"}` }) })).toBeNull();
|
||||
});
|
||||
|
||||
test("leaves arguments it can't read alone", () => {
|
||||
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: "{nope" }) })).toBeNull();
|
||||
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: `["a.md"]` }) })).toBeNull();
|
||||
});
|
||||
|
||||
test("sorts keys inside nested arguments too", () => {
|
||||
const first = repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"where":{"b":1,"a":2}}` }) });
|
||||
const second = repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"where":{"a":2,"b":1}}` }) });
|
||||
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { HarnessToolCall } from "../types";
|
||||
import isRepeatableTool from "./repeatable-tool-names";
|
||||
|
||||
/**
|
||||
* What makes two calls the same call: the tool and its arguments, whatever
|
||||
* order the model wrote their keys in (a model re-reads a file it read
|
||||
* before with the same fields in another order). Null for a tool whose
|
||||
* answer may change, and for arguments that aren't a JSON object, which
|
||||
* `runToolCall` turns down anyway.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
let args: unknown;
|
||||
|
||||
try {
|
||||
args = call.arguments.trim() ? JSON.parse(call.arguments) : {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!args || typeof args != "object" || Array.isArray(args)) return null;
|
||||
|
||||
return `${call.name}:${JSON.stringify(sortKeys({ value: args }))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The value with every object's keys sorted, so two spellings of the same
|
||||
* arguments compare equal.
|
||||
*/
|
||||
function sortKeys({ value }: { value: unknown }): unknown {
|
||||
if (Array.isArray(value)) return value.map((item) => sortKeys({ value: item }));
|
||||
|
||||
if (value && typeof value == "object") {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>)
|
||||
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
||||
.map(([key, inner]) => [key, sortKeys({ value: inner })]),
|
||||
);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { ReadKnowledgebaseDocumentToolName, SearchKnowledgebaseToolName } from "@/src/dict/knowledgebase-dict";
|
||||
|
||||
/**
|
||||
* Tools that only read. Called twice with the same arguments in one run
|
||||
* they answer the same thing, so `runTextLoop` answers the second call from
|
||||
* the first instead of running it again (`repeatToolCallKey`): a run that
|
||||
* re-reads the same file or re-lists the same folder stops paying for it
|
||||
* twice, in the call and in the transcript it resends every turn.
|
||||
*
|
||||
* Only reads belong here. A write, a command, or anything else with a side
|
||||
* effect clears everything remembered, so a read is reused only while
|
||||
* nothing has run that could have changed its answer.
|
||||
*/
|
||||
export const RepeatableToolNames: readonly string[] = [
|
||||
"read_file",
|
||||
"list_files",
|
||||
"computer_read_file",
|
||||
SearchKnowledgebaseToolName,
|
||||
ReadKnowledgebaseDocumentToolName,
|
||||
"list_tasks",
|
||||
"list_extensions",
|
||||
"list_graphics",
|
||||
"read_graphic",
|
||||
"list_hooks",
|
||||
"read_hook_call",
|
||||
"search_hook_calls",
|
||||
"list_schedules",
|
||||
"list_workspace_bots",
|
||||
"list_workspace_people",
|
||||
"find_bot",
|
||||
"find_workspace",
|
||||
"search_past_sessions",
|
||||
"read_past_session",
|
||||
"search_computers",
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether a tool call may be answered from an earlier identical one.
|
||||
*/
|
||||
export default function isRepeatableTool({ name }: { name: string }) {
|
||||
return RepeatableToolNames.includes(name);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { RunLimit } from "@/src/utils/run-limit";
|
||||
|
||||
/**
|
||||
* Who and what a model call was for. Every harness call that reports its
|
||||
* usage is written down with this (`/api/auth/crud` no: `token_usages`),
|
||||
@@ -61,6 +63,23 @@ export type HarnessCallSettings = {
|
||||
* resting after an earlier failure, in order.
|
||||
*/
|
||||
resting?: string[];
|
||||
/**
|
||||
* The bounds the run worked under: the steps it had, the prompt tokens
|
||||
* it may spend and the working context it sent per turn. Kept with the
|
||||
* call so a message read later still says which limit shaped it.
|
||||
*/
|
||||
limits?: HarnessCallLimits;
|
||||
};
|
||||
|
||||
/**
|
||||
* A run's own bounds on one call (`HarnessCallSettings.limits`). Null: the
|
||||
* run didn't say, so the number isn't known (not "unlimited");
|
||||
* `"unlimited"`: the run had no limit of that kind.
|
||||
*/
|
||||
export type HarnessCallLimits = {
|
||||
steps: RunLimit | null;
|
||||
run_tokens: RunLimit | null;
|
||||
context_tokens: RunLimit | null;
|
||||
};
|
||||
|
||||
export type HarnessUsageCall = {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { MarkdownManager } from "@tiptap/markdown";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import { Marked, marked } from "marked";
|
||||
import ComposerOrderedList from "./composer-ordered-list";
|
||||
|
||||
/**
|
||||
* The composer reads a draft or a recalled message back through the same
|
||||
* markdown manager its editor builds, extensions and all. Its own marked
|
||||
* instance, since Tiptap hands every manager the module-level one and a
|
||||
* manager built elsewhere (another test) would leave its tokenizers there.
|
||||
*/
|
||||
const manager = new MarkdownManager({
|
||||
marked: new Marked() as unknown as typeof marked,
|
||||
extensions: [StarterKit.configure({ orderedList: false }), ComposerOrderedList] as never,
|
||||
});
|
||||
|
||||
const parse = ({ markdown }: { markdown: string }) => manager.parse(markdown) as {
|
||||
type: string;
|
||||
attrs?: { start?: number };
|
||||
content?: {
|
||||
type: string;
|
||||
attrs?: { start?: number };
|
||||
text?: string;
|
||||
content?: { type: string; text?: string }[];
|
||||
}[];
|
||||
};
|
||||
|
||||
const text = ({ markdown }: { markdown: string }) => parse({ markdown }).content?.[0]?.content?.[0]?.text;
|
||||
|
||||
describe("composer ordered lists read digits only", () => {
|
||||
test("a sentence opening with a short word stays a paragraph", () => {
|
||||
const doc = parse({ markdown: "Ok. Do another pass on the browser." });
|
||||
|
||||
expect(doc.content?.map((node) => node.type)).toEqual(["paragraph"]);
|
||||
expect(text({ markdown: "Ok. Do another pass on the browser." })).toBe(
|
||||
"Ok. Do another pass on the browser.",
|
||||
);
|
||||
});
|
||||
|
||||
test("a two-letter word with a full stop stays a paragraph", () => {
|
||||
expect(parse({ markdown: "ab. xyz" }).content?.[0]?.type).toBe("paragraph");
|
||||
});
|
||||
|
||||
test("a roman numeral marker stays a paragraph", () => {
|
||||
expect(parse({ markdown: "ii. second point" }).content?.[0]?.type).toBe("paragraph");
|
||||
});
|
||||
|
||||
test("a digit marker is still an ordered list", () => {
|
||||
expect(parse({ markdown: "1. first\n2. second" }).content?.[0]?.type).toBe("orderedList");
|
||||
});
|
||||
|
||||
test("a list keeps its start number", () => {
|
||||
expect(parse({ markdown: "10. tenth" }).content?.[0]?.attrs?.start).toBe(10);
|
||||
});
|
||||
|
||||
test("a bullet list is untouched", () => {
|
||||
expect(parse({ markdown: "- one\n- two" }).content?.[0]?.type).toBe("bulletList");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { MarkdownTokenizer } from "@tiptap/core";
|
||||
import OrderedList from "@tiptap/extension-ordered-list";
|
||||
|
||||
/**
|
||||
* The one way markdown starts an ordered list here: digits, as every
|
||||
* renderer in the app reads it (react-markdown/remark). Tiptap's own
|
||||
* tokenizer also takes `a.` and `i.`, so a recalled message such as
|
||||
* "Ok. Do another pass on the browser." came back as a list item
|
||||
* numbered 401 with "Ok." swallowed as the marker.
|
||||
*/
|
||||
const DigitMarker = /^ {0,3}\d{1,9}[.)][\t ]/;
|
||||
|
||||
const TiptapTokenizer = OrderedList.config.markdownTokenizer as MarkdownTokenizer;
|
||||
|
||||
const ComposerOrderedList = OrderedList.extend({
|
||||
markdownTokenizer: {
|
||||
...TiptapTokenizer,
|
||||
tokenize: (src, tokens, lexer) => {
|
||||
if (!DigitMarker.test(src)) return undefined;
|
||||
|
||||
return TiptapTokenizer.tokenize(src, tokens, lexer);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export default ComposerOrderedList;
|
||||
@@ -9,9 +9,15 @@ import type { BotMessageWithAttachments } from "@/src/types";
|
||||
export type BotMessageActions = {
|
||||
onReply: (params: { message: BotMessageWithAttachments }) => void;
|
||||
onReact: (params: { message_id: number; emoji: BotMessageReactionEmoji }) => void;
|
||||
/**
|
||||
* A suggested next step the user clicked (`[suggestion:ID]`): put it
|
||||
* in their input, never send it.
|
||||
*/
|
||||
onUseSuggestion: (params: { text: string }) => void;
|
||||
};
|
||||
|
||||
export const BotMessageActionsContext = React.createContext<BotMessageActions>({
|
||||
onReply: () => {},
|
||||
onReact: () => {},
|
||||
onUseSuggestion: () => {},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { BotSuggestionView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
suggestion_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps already read, by id, so a thread naming them twice asks once.
|
||||
*/
|
||||
const loaded = new Map<number, Promise<BotSuggestionView | null>>();
|
||||
|
||||
function loadSuggestion({ suggestion_id }: Params) {
|
||||
const cached = loaded.get(suggestion_id);
|
||||
|
||||
if (cached) return cached;
|
||||
|
||||
const pending = fetchApi<{}, APIResponseObject<BotSuggestionView>>(
|
||||
`/api/admin/bot-suggestions/get-suggestion?suggestion_id=${suggestion_id}`,
|
||||
{ method: "GET" },
|
||||
)
|
||||
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
|
||||
.catch(() => null);
|
||||
|
||||
loaded.set(suggestion_id, pending);
|
||||
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested (`[suggestion:ID]`): read when their buttons
|
||||
* render. Only the user they were suggested to can read them; anyone else
|
||||
* gets null.
|
||||
*/
|
||||
export default function useBotSuggestion({ suggestion_id }: Params) {
|
||||
const [view, setView] = useState<BotSuggestionView | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
loadSuggestion({ suggestion_id }).then((result) => {
|
||||
if (!live) return;
|
||||
setView(result);
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [suggestion_id]);
|
||||
|
||||
return { view, loading };
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import Placeholder from "@tiptap/extension-placeholder";
|
||||
import { Markdown } from "@tiptap/markdown";
|
||||
import type { SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";
|
||||
import type { BotWithLastMessage, WorkspaceWithActivity } from "@/src/types";
|
||||
import ComposerOrderedList from "../(data)/composer-ordered-list";
|
||||
import {
|
||||
ComposerMentionKinds,
|
||||
type ComposerMentionChar,
|
||||
@@ -39,6 +40,11 @@ type Params = {
|
||||
* Files pasted or dropped in.
|
||||
*/
|
||||
onFiles: (params: { files: File[] }) => void;
|
||||
/**
|
||||
* An arrow key that may walk the user's previous messages; true when it
|
||||
* did, so the cursor stays where the recalled message left it.
|
||||
*/
|
||||
onHistory: (params: { direction: "up" | "down"; empty: boolean }) => boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -49,7 +55,9 @@ type Params = {
|
||||
* in a code block or list, where Enter is the editor's and Mod+Enter
|
||||
* sends. Enter picks from an open mention menu. Pasted text comes in
|
||||
* plain, without another site's styling; pasted or dropped files go to
|
||||
* `onFiles`.
|
||||
* `onFiles`. The Up and Down arrows walk the user's previous messages
|
||||
* through `onHistory` (an empty input recalls the newest; an open mention
|
||||
* menu keeps them for itself).
|
||||
*/
|
||||
export default function useComposerEditor({
|
||||
placeholder,
|
||||
@@ -58,9 +66,10 @@ export default function useComposerEditor({
|
||||
onChange,
|
||||
onSubmit,
|
||||
onFiles,
|
||||
onHistory,
|
||||
}: Params) {
|
||||
const latest = useRef({ bots, workspaces, onChange, onSubmit, onFiles });
|
||||
latest.current = { bots, workspaces, onChange, onSubmit, onFiles };
|
||||
const latest = useRef({ bots, workspaces, onChange, onSubmit, onFiles, onHistory });
|
||||
latest.current = { bots, workspaces, onChange, onSubmit, onFiles, onHistory };
|
||||
|
||||
const [menu, setMenu] = useState<ComposerMentionMenu | null>(null);
|
||||
const menu_ref = useRef<ComposerMentionMenu | null>(null);
|
||||
@@ -134,7 +143,10 @@ export default function useComposerEditor({
|
||||
horizontalRule: false,
|
||||
underline: false,
|
||||
link: { openOnClick: false, autolink: true },
|
||||
orderedList: false,
|
||||
}),
|
||||
/** Digits only, so text like "Ok. Do that." stays a paragraph. */
|
||||
ComposerOrderedList,
|
||||
Placeholder.configure({ placeholder }),
|
||||
Markdown,
|
||||
Mention.extend({
|
||||
@@ -155,7 +167,17 @@ export default function useComposerEditor({
|
||||
const editorOwnsEnter = () =>
|
||||
this.editor.isActive("codeBlock") || this.editor.isActive("listItem");
|
||||
|
||||
/** A selection, a composing IME or an open menu keep the arrows. */
|
||||
const walkHistory = (direction: "up" | "down") => {
|
||||
if (menu_ref.current?.items.length || this.editor.view.composing) return false;
|
||||
if (!this.editor.state.selection.empty) return false;
|
||||
|
||||
return latest.current.onHistory({ direction, empty: this.editor.isEmpty });
|
||||
};
|
||||
|
||||
return {
|
||||
ArrowUp: () => walkHistory("up"),
|
||||
ArrowDown: () => walkHistory("down"),
|
||||
Enter: () => {
|
||||
if (menu_ref.current?.items.length || this.editor.view.composing) return false;
|
||||
if (editorOwnsEnter()) return false;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useRef } from "react";
|
||||
import stepComposerHistory, {
|
||||
EmptyComposerHistory,
|
||||
type ComposerHistoryState,
|
||||
} from "../(utils)/composer-history-step";
|
||||
|
||||
/**
|
||||
* The user's previous messages, walked with the Up and Down arrows: what
|
||||
* they were typing is kept and comes back when Down passes the newest
|
||||
* message again.
|
||||
*/
|
||||
export type ComposerHistory = {
|
||||
/** A recalled message is in the input (so the arrows keep walking). */
|
||||
isActive: () => boolean;
|
||||
/**
|
||||
* One arrow press: the text the input takes, or null when the key
|
||||
* belongs to the editor (a cursor to move, nothing to recall).
|
||||
*/
|
||||
step: (params: {
|
||||
direction: "up" | "down";
|
||||
/** What's in the input now, put back on the way down. */
|
||||
draft: string;
|
||||
/** Whether the input has nothing in it. */
|
||||
empty: boolean;
|
||||
}) => { text: string } | null;
|
||||
/** Typing (or sending) takes the input back from the recalled messages. */
|
||||
reset: () => void;
|
||||
};
|
||||
|
||||
export default function useComposerHistory({
|
||||
texts,
|
||||
}: {
|
||||
/** What the user typed before, oldest first. */
|
||||
texts: string[];
|
||||
}): ComposerHistory {
|
||||
const state = useRef<ComposerHistoryState>(EmptyComposerHistory);
|
||||
const texts_ref = useRef(texts);
|
||||
|
||||
texts_ref.current = texts;
|
||||
|
||||
const reset = () => {
|
||||
state.current = EmptyComposerHistory;
|
||||
};
|
||||
|
||||
const step = ({
|
||||
direction,
|
||||
draft,
|
||||
empty,
|
||||
}: {
|
||||
direction: "up" | "down";
|
||||
draft: string;
|
||||
empty: boolean;
|
||||
}) => {
|
||||
const next = stepComposerHistory({
|
||||
state: state.current,
|
||||
texts: texts_ref.current,
|
||||
direction,
|
||||
draft,
|
||||
empty,
|
||||
});
|
||||
|
||||
if (!next) return null;
|
||||
|
||||
state.current = next.state;
|
||||
|
||||
return { text: next.text };
|
||||
};
|
||||
|
||||
return { isActive: () => state.current.index > 0, step, reset };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useContext } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { ArrowUpRight } from "lucide-react";
|
||||
import { BotMessageActionsContext } from "../(data)/message-actions-context";
|
||||
|
||||
type Props = {
|
||||
step: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* One suggested next step, a button that puts it in the user's input (it
|
||||
* never sends on its own).
|
||||
*/
|
||||
export default function BotSuggestionChip({ step }: Props) {
|
||||
const { onUseSuggestion } = useContext(BotMessageActionsContext);
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={`Put this in your input: ${step}`}
|
||||
className="inline-flex h-auto max-w-full gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0"
|
||||
onClick={() => onUseSuggestion({ text: step })}
|
||||
>
|
||||
<Span className="min-w-0">{step}</Span>
|
||||
<ArrowUpRight size={14} aria-hidden className="shrink-0" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useBotSuggestion from "../(hooks)/use-bot-suggestion";
|
||||
import BotSuggestionChip from "./bot-suggestion-chip";
|
||||
|
||||
type Props = {
|
||||
suggestion_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested (`botSuggestionRef`): its heading and a
|
||||
* button per step, inline under the answer. Clicking one puts it in the
|
||||
* user's input; nothing has to be answered. Anyone they weren't suggested
|
||||
* to sees their number only.
|
||||
*/
|
||||
export default function BotSuggestionsRef({ suggestion_id }: Props) {
|
||||
const { view, loading } = useBotSuggestion({ suggestion_id });
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `next steps ${suggestion_id}` : `next steps ${suggestion_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
if (!view.steps.length) return null;
|
||||
|
||||
return (
|
||||
<Span className="inline-flex max-w-full flex-wrap items-center gap-1.5 align-middle">
|
||||
<Span className="text-[13px] font-bold text-ink-secondary">{view.title || "Next steps"}</Span>
|
||||
{view.steps.map((step) => (
|
||||
<BotSuggestionChip key={step} step={step} />
|
||||
))}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
type Props = {
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Empties the input's text (the quote, the picked files and the draft it
|
||||
* saves stay where they are).
|
||||
*/
|
||||
export default function ComposerClearButton({ disabled, onClick }: Props) {
|
||||
return (
|
||||
<Button
|
||||
title={disabled ? "Nothing to clear" : "Clear the text"}
|
||||
aria-label="Clear the text"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className="shrink-0 p-1! -mx-1 my-1 text-ink dark:text-ink rounded-default-xs focus-visible:ring-2 focus-visible:ring-ink"
|
||||
>
|
||||
<X size={16} aria-hidden />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -23,12 +23,15 @@ import transcribeVoice from "../(functions)/transcribe-voice";
|
||||
import useComposerAttachments from "../(hooks)/use-composer-attachments";
|
||||
import useComposerDraft from "../(hooks)/use-composer-draft";
|
||||
import useComposerEditor from "../(hooks)/use-composer-editor";
|
||||
import useComposerHistory from "../(hooks)/use-composer-history";
|
||||
import useVoiceRecorder from "../(hooks)/use-voice-recorder";
|
||||
import useOnlineStatus from "@/src/hooks/use-online-status";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import messageTooLongMessage from "@/src/utils/message-too-long-message";
|
||||
import composerHistoryTexts from "../(utils)/composer-history-texts";
|
||||
import ComposerAttachButton from "./composer-attach-button";
|
||||
import ComposerAttachments from "./composer-attachments";
|
||||
import ComposerClearButton from "./composer-clear-button";
|
||||
import ComposerEditor from "./composer-editor";
|
||||
import ComposerMentionList from "./composer-mention-list";
|
||||
import ComposerReplyPreview from "./composer-reply-preview";
|
||||
@@ -44,6 +47,11 @@ export type ComposerHandle = {
|
||||
* Quotes text from the thread at the cursor.
|
||||
*/
|
||||
insertQuote: (params: { text: string }) => void;
|
||||
/**
|
||||
* Puts text at the cursor (a suggested next step), leaving the draft
|
||||
* to the user to edit and send.
|
||||
*/
|
||||
insertText: (params: { text: string }) => void;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
@@ -69,6 +77,11 @@ type Props = {
|
||||
* before anything is sent, and again by the server.
|
||||
*/
|
||||
max_chars?: number | null;
|
||||
/**
|
||||
* The user's own earlier messages in the thread, oldest first: the Up
|
||||
* and Down arrows walk them.
|
||||
*/
|
||||
previous_messages?: BotMessageWithAttachments[];
|
||||
/**
|
||||
* The message the next one quotes, if the user picked one.
|
||||
*/
|
||||
@@ -100,7 +113,9 @@ type Props = {
|
||||
* are listed under the input. The mic dictates: what's said is written
|
||||
* into the input at the cursor, to edit before sending. Sending shows the
|
||||
* message in the thread straight away and empties the input, so a slow
|
||||
* connection never holds either; a failed send puts both back.
|
||||
* connection never holds either; a failed send puts both back. Up recalls
|
||||
* the message the user sent before (Down comes forward again, back to what
|
||||
* they were typing), and the X button empties the text without sending it.
|
||||
*/
|
||||
export default function Composer({
|
||||
bot,
|
||||
@@ -109,6 +124,7 @@ export default function Composer({
|
||||
voice,
|
||||
has_browsers,
|
||||
max_chars,
|
||||
previous_messages,
|
||||
reply_to,
|
||||
onCancelReply,
|
||||
onSendStart,
|
||||
@@ -135,20 +151,54 @@ export default function Composer({
|
||||
|
||||
latest_text.current = text;
|
||||
|
||||
const history = useComposerHistory({
|
||||
texts: composerHistoryTexts({ messages: previous_messages || [] }),
|
||||
});
|
||||
/**
|
||||
* Assigned once the editor exists, since recalling a message writes
|
||||
* into it; the editor's keys read it through a ref.
|
||||
*/
|
||||
const walk_history = useRef<
|
||||
(params: { direction: "up" | "down"; empty: boolean }) => boolean
|
||||
>(() => false);
|
||||
|
||||
const input = useComposerEditor({
|
||||
placeholder: `Message ${bot.name}`,
|
||||
bots,
|
||||
workspaces,
|
||||
onChange: ({ markdown }) => setText(markdown),
|
||||
onChange: ({ markdown }) => {
|
||||
history.reset();
|
||||
setText(markdown);
|
||||
},
|
||||
onSubmit: () => send_ref.current(),
|
||||
onFiles: files.add,
|
||||
onHistory: (params) => walk_history.current(params),
|
||||
});
|
||||
const editor = input.editor;
|
||||
|
||||
walk_history.current = ({ direction, empty }) => {
|
||||
const next = history.step({
|
||||
direction,
|
||||
draft: latest_text.current,
|
||||
empty,
|
||||
});
|
||||
|
||||
if (!next) return false;
|
||||
|
||||
setText(next.text);
|
||||
input.setMarkdown({ markdown: next.text });
|
||||
editor?.commands.focus("end");
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
useImperativeHandle(
|
||||
handle_ref,
|
||||
() => ({ insertQuote: input.insertQuote }),
|
||||
[input.insertQuote],
|
||||
() => ({
|
||||
insertQuote: input.insertQuote,
|
||||
insertText: input.insertText,
|
||||
}),
|
||||
[input.insertQuote, input.insertText],
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -221,6 +271,17 @@ export default function Composer({
|
||||
files.restore({ attachments });
|
||||
};
|
||||
|
||||
/**
|
||||
* Empties the input's text, without sending it: what was typed is
|
||||
* dropped, the quote and the picked files stay.
|
||||
*/
|
||||
function clearText() {
|
||||
setText("");
|
||||
history.reset();
|
||||
input.clear();
|
||||
editor?.commands.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* The bubble and the bot's "getting your message" row show at once, and
|
||||
* the input empties, so a slow connection never holds any of it. The
|
||||
@@ -285,6 +346,7 @@ export default function Composer({
|
||||
onCancelReply?.();
|
||||
|
||||
setText("");
|
||||
history.reset();
|
||||
input.clear();
|
||||
files.clear();
|
||||
|
||||
@@ -363,6 +425,11 @@ export default function Composer({
|
||||
title={error}
|
||||
/>
|
||||
|
||||
<ComposerClearButton
|
||||
disabled={!text.trim()}
|
||||
onClick={clearText}
|
||||
/>
|
||||
|
||||
{recorder.supported ? (
|
||||
<ComposerVoiceButton
|
||||
state={recorder.state}
|
||||
|
||||
@@ -37,7 +37,9 @@ export default function MessageActions({ message }: Props) {
|
||||
message_id={message.id}
|
||||
onReact={onReact}
|
||||
/>
|
||||
{message.author == "bot" ? <MessageDetailsModal message_id={Number(message.id)} /> : null}
|
||||
{message.author == "bot" ? (
|
||||
<MessageDetailsModal message_id={Number(message.id)} tool_log={message.tool_log} />
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</Row>
|
||||
|
||||
@@ -10,17 +10,22 @@ import MessageDetailsCallRow from "./message-details-call-row";
|
||||
import MessageDetailsFailureRow from "./message-details-failure-row";
|
||||
import MessageDetailsHeading from "./message-details-heading";
|
||||
import MessageDetailsModelRow from "./message-details-model-row";
|
||||
import MessageToolsRollup from "./message-tools-rollup";
|
||||
|
||||
type Props = {
|
||||
details: MessageDetails;
|
||||
/**
|
||||
* The message's `tool_log`: what its run did, tool by tool.
|
||||
*/
|
||||
tool_log?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* How a message was generated: the provider and model that answered and
|
||||
* what it spent, then the job that ran it, every model it used, every
|
||||
* call in order and every call that failed, with why.
|
||||
* what it spent, then the job that ran it, what its tools did, every model
|
||||
* it used, every call in order and every call that failed, with why.
|
||||
*/
|
||||
export default function MessageDetailsBody({ details }: Props) {
|
||||
export default function MessageDetailsBody({ details, tool_log }: Props) {
|
||||
const { totals, models, calls, failures, failed_calls, job } = details;
|
||||
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
|
||||
|
||||
@@ -63,6 +68,8 @@ export default function MessageDetailsBody({ details }: Props) {
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<MessageToolsRollup tool_log={tool_log} />
|
||||
|
||||
{models.length ? (
|
||||
<>
|
||||
<MessageDetailsHeading>{models.length > 1 ? "Models used" : "Model used"}</MessageDetailsHeading>
|
||||
|
||||
@@ -12,14 +12,19 @@ import MessageDetailsBody from "./message-details-body";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
* Its `tool_log`: what the run behind it did, shown in the modal and
|
||||
* passed along to the copied report.
|
||||
*/
|
||||
tool_log?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The info button under a bot message, and the modal it opens: which
|
||||
* provider and model generated it, the run behind it, and every model
|
||||
* call with its tokens and cost. Loaded when it opens.
|
||||
* provider and model generated it, the run behind it, what its tools did,
|
||||
* and every model call with its tokens and cost. Loaded when it opens.
|
||||
*/
|
||||
export default function MessageDetailsModal({ message_id }: Props) {
|
||||
export default function MessageDetailsModal({ message_id, tool_log }: Props) {
|
||||
const [open, set_open] = useState(false);
|
||||
const { details, loading, error } = useMessageDetails({ message_id, enabled: open });
|
||||
|
||||
@@ -47,7 +52,7 @@ export default function MessageDetailsModal({ message_id }: Props) {
|
||||
|
||||
<Stack className="mt-4 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
{details ? (
|
||||
<MessageDetailsBody details={details} />
|
||||
<MessageDetailsBody details={details} tool_log={tool_log} />
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading || !error ? "Loading details..." : error}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { ToolRollupEntry } from "@/src/utils/tool-rollup";
|
||||
|
||||
type Props = {
|
||||
tool: ToolRollupEntry;
|
||||
};
|
||||
|
||||
/**
|
||||
* One tool in a message's rollup: its name as the run called it, what the
|
||||
* app calls that, and how many calls it made, of which how many failed.
|
||||
*/
|
||||
export default function MessageToolRow({ tool }: Props) {
|
||||
return (
|
||||
<Row className="w-full py-1.5 gap-3! flex-nowrap items-baseline border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<Span
|
||||
className="grow min-w-0 font-mono text-[12px] leading-4 text-ink truncate"
|
||||
title={`${tool.label} (${tool.name})`}
|
||||
>
|
||||
{tool.name}
|
||||
</Span>
|
||||
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary tabular-nums">{tool.label}</Span>
|
||||
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums">
|
||||
{tool.count == 1 ? "1 call" : `${tool.count} calls`}
|
||||
</Span>
|
||||
{tool.failed ? (
|
||||
<Span className="w-14 shrink-0 text-right text-[11px] leading-4 text-ink-secondary tabular-nums">
|
||||
{`${tool.failed} failed`}
|
||||
</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { ToolRollupEntry } from "@/src/utils/tool-rollup";
|
||||
import toolRollup from "@/src/utils/tool-rollup";
|
||||
import MessageDetailRow from "./message-detail-row";
|
||||
import MessageDetailsHeading from "./message-details-heading";
|
||||
import MessageToolRow from "./message-tool-row";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* The message's `tool_log` (`{ name, ok }` per call).
|
||||
*/
|
||||
tool_log?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a message's run actually did, by tool: the one reading that tells a
|
||||
* run which worked from one that spent 242 model calls and changed
|
||||
* nothing. The app's own record (`bot_messages.tool_log`), so it can't
|
||||
* claim work the run didn't make.
|
||||
*/
|
||||
export default function MessageToolsRollup({ tool_log }: Props) {
|
||||
const rollup = toolRollup({ tool_log });
|
||||
|
||||
if (!rollup || !rollup.tools.length) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<MessageDetailsHeading>Tools used</MessageDetailsHeading>
|
||||
<MessageDetailRow
|
||||
label="Tool calls"
|
||||
value={rollup.failed ? `${rollup.calls} (${rollup.failed} failed)` : String(rollup.calls)}
|
||||
/>
|
||||
{rollup.tools.map((tool: ToolRollupEntry) => (
|
||||
<MessageToolRow key={tool.name} tool={tool} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import SettingRefChip from "./setting-ref-chip";
|
||||
|
||||
describe("SettingRefChip", () => {
|
||||
test("names the group and the field, and links to the field's anchor", () => {
|
||||
const html = renderToString(<SettingRefChip section="run-limits" field="reply_steps" />);
|
||||
|
||||
expect(html).toContain("Run limits · Tool steps per chat reply");
|
||||
expect(html).toContain("/admin/settings/general/run-limits#reply_steps");
|
||||
});
|
||||
|
||||
test("a group on its own links to its page", () => {
|
||||
const html = renderToString(<SettingRefChip section="storage" />);
|
||||
|
||||
expect(html).toContain("Storage");
|
||||
expect(html).toContain("/admin/settings/general/storage");
|
||||
expect(html).not.toContain("#");
|
||||
});
|
||||
|
||||
test("a ref the app can't resolve keeps its words, without linking anywhere", () => {
|
||||
const html = renderToString(<SettingRefChip section="nope" field="thing" />);
|
||||
|
||||
expect(html).toContain("setting nope thing");
|
||||
expect(html).not.toContain("href");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Settings2 } from "lucide-react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import generalSettingsHref, { findGeneralSettingsField, findGeneralSettingsSection } from "@/src/dict/general-settings-dict";
|
||||
|
||||
type Props = {
|
||||
section: string;
|
||||
/**
|
||||
* The field within the group, when the ref names one.
|
||||
*/
|
||||
field?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A setting a bot named in a message (`settingRef`): a pill linking to that
|
||||
* group's own page under Settings > General, with the field's anchor when
|
||||
* it names one. The bot says the value in its text; the pill takes the
|
||||
* reader to the input that changes it.
|
||||
*/
|
||||
export default function SettingRefChip({ section, field }: Props) {
|
||||
const known = findGeneralSettingsSection({ key: section });
|
||||
const known_field = findGeneralSettingsField({ section, field });
|
||||
|
||||
if (!known) {
|
||||
return <Span className="font-bold">{`setting ${section}${field ? ` ${field}` : ""}`}</Span>;
|
||||
}
|
||||
|
||||
const label = known_field ? `${known.title} · ${known_field.title}` : known.title;
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={generalSettingsHref({ section: known.key, field: known_field?.key })}
|
||||
title={`Open ${label} in Settings`}
|
||||
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 whitespace-nowrap hover:opacity-80"
|
||||
>
|
||||
<Settings2 size={13} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{label}</Span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -63,7 +63,8 @@ import requestLiveCrewRefresh from "@/src/functions/frontend/request-live-crew-r
|
||||
* when the back button restores the page. Older messages load as the
|
||||
* thread scrolls up. `?session_id=` opens another session of the
|
||||
* conversation; a closed one shows, in the composer's place, a link to
|
||||
* where the conversation went on.
|
||||
* where the conversation went on. Up recalls the last message the user
|
||||
* sent, in the composer.
|
||||
*/
|
||||
export default function Conversation() {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
@@ -381,6 +382,8 @@ export default function Conversation() {
|
||||
onReply: ({ message }: { message: BotMessageWithAttachments }) =>
|
||||
setReplyTo(message),
|
||||
onReact: reactToMessage,
|
||||
onUseSuggestion: ({ text }: { text: string }) =>
|
||||
composer.current?.insertText({ text }),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
@@ -467,6 +470,7 @@ export default function Conversation() {
|
||||
voice={pageProps?.bot_voice}
|
||||
has_browsers={Boolean(pageProps?.has_browsers)}
|
||||
max_chars={pageProps?.message_max_chars}
|
||||
previous_messages={thread_messages}
|
||||
reply_to={reply_to}
|
||||
onCancelReply={() => setReplyTo(null)}
|
||||
onSendStart={({ message }) =>
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import stepComposerHistory, {
|
||||
EmptyComposerHistory,
|
||||
type ComposerHistoryState,
|
||||
} from "./composer-history-step";
|
||||
|
||||
/** Presses arrows in turn, collecting what the input took each time. */
|
||||
function walk({
|
||||
texts,
|
||||
presses,
|
||||
draft = "",
|
||||
empty = true,
|
||||
state = EmptyComposerHistory,
|
||||
}: {
|
||||
texts: string[];
|
||||
presses: ("up" | "down")[];
|
||||
draft?: string;
|
||||
empty?: boolean;
|
||||
state?: ComposerHistoryState;
|
||||
}) {
|
||||
const shown: (string | null)[] = [];
|
||||
let current = state;
|
||||
let in_input = draft;
|
||||
|
||||
for (const direction of presses) {
|
||||
const next = stepComposerHistory({
|
||||
state: current,
|
||||
texts,
|
||||
direction,
|
||||
draft: in_input,
|
||||
empty,
|
||||
});
|
||||
|
||||
shown.push(next ? next.text : null);
|
||||
|
||||
if (next) {
|
||||
current = next.state;
|
||||
in_input = next.text;
|
||||
}
|
||||
|
||||
/** Once a message is in, the input isn't empty any more. */
|
||||
empty = false;
|
||||
}
|
||||
|
||||
return { shown, state: current, in_input };
|
||||
}
|
||||
|
||||
const texts = ["first", "second", "third"];
|
||||
|
||||
describe("stepComposerHistory", () => {
|
||||
test("Up on an empty input recalls the newest message", () => {
|
||||
const { shown } = walk({ texts, presses: ["up"] });
|
||||
|
||||
expect(shown).toEqual(["third"]);
|
||||
});
|
||||
|
||||
test("Up again walks back through older messages", () => {
|
||||
const { shown } = walk({ texts, presses: ["up", "up", "up"] });
|
||||
|
||||
expect(shown).toEqual(["third", "second", "first"]);
|
||||
});
|
||||
|
||||
test("Up on the oldest message is the editor's; the input stays as it is", () => {
|
||||
const { shown, in_input } = walk({ texts, presses: ["up", "up", "up", "up"] });
|
||||
|
||||
expect(shown).toEqual(["third", "second", "first", null]);
|
||||
expect(in_input).toEqual("first");
|
||||
});
|
||||
|
||||
test("Down comes forward again and then back to what was being typed", () => {
|
||||
const { shown, in_input } = walk({
|
||||
texts,
|
||||
presses: ["up", "up", "down", "down"],
|
||||
draft: "half a thought",
|
||||
});
|
||||
|
||||
expect(shown).toEqual(["third", "second", "third", "half a thought"]);
|
||||
expect(in_input).toEqual("half a thought");
|
||||
});
|
||||
|
||||
test("the draft survives walking all the way back and forth", () => {
|
||||
const { in_input, state } = walk({
|
||||
texts,
|
||||
presses: ["up", "up", "up", "down", "down", "down"],
|
||||
draft: "an edit",
|
||||
});
|
||||
|
||||
expect(in_input).toEqual("an edit");
|
||||
expect(state).toEqual(EmptyComposerHistory);
|
||||
});
|
||||
|
||||
test("Down on the draft is the editor's", () => {
|
||||
const { shown } = walk({ texts, presses: ["down"] });
|
||||
|
||||
expect(shown).toEqual([null]);
|
||||
});
|
||||
|
||||
test("Up with text being edited moves the cursor, never replaces the text", () => {
|
||||
const { shown } = walk({
|
||||
texts,
|
||||
presses: ["up"],
|
||||
draft: "still typing",
|
||||
empty: false,
|
||||
});
|
||||
|
||||
expect(shown).toEqual([null]);
|
||||
});
|
||||
|
||||
test("Up recalls nothing in a conversation with no earlier message", () => {
|
||||
const { shown } = walk({ texts: [], presses: ["up"] });
|
||||
|
||||
expect(shown).toEqual([null]);
|
||||
});
|
||||
|
||||
test("recalling the only message and pressing Up again stops there", () => {
|
||||
const { shown } = walk({ texts: ["only"], presses: ["up", "up"] });
|
||||
|
||||
expect(shown).toEqual(["only", null]);
|
||||
});
|
||||
|
||||
test("a session that holds fewer messages never reads past the oldest", () => {
|
||||
const { shown, in_input } = walk({
|
||||
texts: ["newest"],
|
||||
presses: ["up", "down"],
|
||||
state: { index: 3, draft: "my draft" },
|
||||
});
|
||||
|
||||
expect(shown).toEqual([null, "my draft"]);
|
||||
expect(in_input).toEqual("my draft");
|
||||
});
|
||||
|
||||
test("the state it hands back is what the next press starts from", () => {
|
||||
const first = stepComposerHistory({
|
||||
state: EmptyComposerHistory,
|
||||
texts,
|
||||
direction: "up",
|
||||
draft: "draft",
|
||||
empty: true,
|
||||
});
|
||||
|
||||
expect(first?.state).toEqual({ index: 1, draft: "draft" });
|
||||
expect(first?.text).toEqual("third");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Where the Up and Down arrows stand in the user's previous messages: 0 is
|
||||
* what they were typing, 1 the newest message recalled, 2 the one before it.
|
||||
*/
|
||||
export type ComposerHistoryState = {
|
||||
index: number;
|
||||
/**
|
||||
* What was in the input when the newest message was recalled, put back
|
||||
* when the arrows come down past it again.
|
||||
*/
|
||||
draft: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The input as the user left it: what they type is theirs, not a message
|
||||
* from before.
|
||||
*/
|
||||
export const EmptyComposerHistory: ComposerHistoryState = { index: 0, draft: "" };
|
||||
|
||||
/**
|
||||
* One press of an arrow through the user's previous messages, oldest last:
|
||||
* Up recalls the newest from an empty input and older ones from there, Down
|
||||
* walks back to the draft. Null when the key is the editor's own (nothing
|
||||
* to recall, no older message, or text in the input the user is editing).
|
||||
*/
|
||||
export default function stepComposerHistory({
|
||||
state,
|
||||
texts,
|
||||
direction,
|
||||
draft,
|
||||
empty,
|
||||
}: {
|
||||
state: ComposerHistoryState;
|
||||
/** What the user typed before, oldest first. */
|
||||
texts: string[];
|
||||
direction: "up" | "down";
|
||||
/** What's in the input now. */
|
||||
draft: string;
|
||||
/** Whether the input has nothing in it. */
|
||||
empty: boolean;
|
||||
}): { state: ComposerHistoryState; text: string } | null {
|
||||
const count = texts.length;
|
||||
|
||||
if (!state.index) {
|
||||
/**
|
||||
* Text being edited keeps Up for moving the cursor: only an empty
|
||||
* input starts walking back through the messages.
|
||||
*/
|
||||
if (direction == "down" || !empty || !count) return null;
|
||||
|
||||
return { state: { index: 1, draft }, text: texts[count - 1]! };
|
||||
}
|
||||
|
||||
/**
|
||||
* A session the input followed may hold fewer messages than the one the
|
||||
* arrows started in: the oldest one left is as far back as it goes.
|
||||
*/
|
||||
const index = Math.min(state.index, count);
|
||||
|
||||
if (direction == "up") {
|
||||
if (index >= count) return null;
|
||||
|
||||
return {
|
||||
state: { ...state, index: index + 1 },
|
||||
text: texts[count - (index + 1)]!,
|
||||
};
|
||||
}
|
||||
|
||||
if (index <= 1) return { state: EmptyComposerHistory, text: state.draft };
|
||||
|
||||
return {
|
||||
state: { ...state, index: index - 1 },
|
||||
text: texts[count - (index - 1)]!,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import composerHistoryTexts from "./composer-history-texts";
|
||||
|
||||
const sent = (text: string) => ({ author: "user" as const, text });
|
||||
const answered = (text: string) => ({ author: "bot" as const, text });
|
||||
|
||||
describe("composerHistoryTexts", () => {
|
||||
test("keeps what the user typed, oldest first", () => {
|
||||
const texts = composerHistoryTexts({
|
||||
messages: [
|
||||
sent("plan the migration"),
|
||||
answered("Here's the plan"),
|
||||
sent("ship it tonight"),
|
||||
],
|
||||
});
|
||||
|
||||
expect(texts).toEqual(["plan the migration", "ship it tonight"]);
|
||||
});
|
||||
|
||||
test("leaves out the bot's answers and blank messages", () => {
|
||||
const texts = composerHistoryTexts({
|
||||
messages: [answered("Morning"), sent(" "), sent(""), sent("real text")],
|
||||
});
|
||||
|
||||
expect(texts).toEqual(["real text"]);
|
||||
});
|
||||
|
||||
test("leaves out what a chatroom or an install request wrote on the user's side", () => {
|
||||
const texts = composerHistoryTexts({
|
||||
messages: [
|
||||
sent("ask the crew"),
|
||||
{ author: "user" as const, text: "Room closed: the answer", from_chatroom_id: 12 },
|
||||
{ author: "user" as const, text: "Installed numpy", from_install_request_id: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
expect(texts).toEqual(["ask the crew"]);
|
||||
});
|
||||
|
||||
test("trims a message's text around it", () => {
|
||||
const texts = composerHistoryTexts({ messages: [sent(" keep this ")] });
|
||||
|
||||
expect(texts).toEqual(["keep this"]);
|
||||
});
|
||||
|
||||
test("is empty for a session with nothing sent yet", () => {
|
||||
expect(composerHistoryTexts({ messages: [answered("Hello")] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
|
||||
/**
|
||||
* A message the Up arrow can recall: only what the user typed here. A
|
||||
* chatroom's outcome and an install request's answer are stored on the
|
||||
* user's side, but the user wrote neither.
|
||||
*/
|
||||
export type ComposerHistoryMessage = Pick<
|
||||
BotMessageWithAttachments,
|
||||
"author" | "text" | "from_chatroom_id" | "from_install_request_id"
|
||||
>;
|
||||
|
||||
/**
|
||||
* What the user typed, oldest first, so the newest message Up recalls is
|
||||
* its last entry.
|
||||
*/
|
||||
export default function composerHistoryTexts({
|
||||
messages,
|
||||
}: {
|
||||
messages: ComposerHistoryMessage[];
|
||||
}) {
|
||||
const texts: string[] = [];
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.author != "user" || isCrewMessage({ message })) continue;
|
||||
|
||||
const text = message.text?.trim();
|
||||
|
||||
if (text) texts.push(text);
|
||||
}
|
||||
|
||||
return texts;
|
||||
}
|
||||
@@ -13,10 +13,13 @@ import {
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { parseFolderRefHref } from "@/src/utils/folder-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
import { botSuggestionRefId } from "@/src/utils/bot-suggestion-ref";
|
||||
import { graphicRefId } from "@/src/utils/graphic-ref";
|
||||
import { chatroomRefId } from "@/src/utils/chatroom-ref";
|
||||
import { taskRefId } from "@/src/utils/task-ref";
|
||||
import { generalSettingsRefId } from "@/src/utils/general-settings-ref";
|
||||
import BotQuestionRefChip from "../(partials)/bot-question-ref-chip";
|
||||
import BotSuggestionsRef from "../(partials)/bot-suggestions-ref";
|
||||
import BotRefChip from "../(partials)/bot-ref-chip";
|
||||
import ChatroomRefChip from "../(partials)/chatroom-ref-chip";
|
||||
import ComputerRefChip from "../(partials)/computer-ref-chip";
|
||||
@@ -27,6 +30,7 @@ import HookProposalRefChip from "../(partials)/hook-proposal-ref-chip";
|
||||
import ProposalRefChip from "../(partials)/proposal-ref-chip";
|
||||
import SecretRefChip from "../(partials)/secret-ref-chip";
|
||||
import SecretRequestRefChip from "../(partials)/secret-request-ref-chip";
|
||||
import SettingRefChip from "../(partials)/setting-ref-chip";
|
||||
import TakeOverChip from "../(partials)/take-over-chip";
|
||||
import TaskRefChip from "../(partials)/task-ref-chip";
|
||||
import WorkspaceRefChip from "../(partials)/workspace-ref-chip";
|
||||
@@ -37,8 +41,10 @@ import WorkspaceRefChip from "../(partials)/workspace-ref-chip";
|
||||
* computer, a bot or workspace a link to it, a file a chip that previews
|
||||
* it, a folder a chip that opens it in the files browser, a proposal a chip
|
||||
* that opens the confirm card, a secret a masked chip, a secret request or
|
||||
* questions a chip that opens their card, a graphic the graphic itself, a
|
||||
* chatroom or task a chip that opens it. Null for any other link.
|
||||
* questions a chip that opens their card, suggested next steps the
|
||||
* buttons that fill the input, a graphic the graphic itself, a
|
||||
* chatroom or task a chip that opens it, a setting a pill to that group of
|
||||
* Settings > General. Null for any other link.
|
||||
*/
|
||||
export default function refChipForHref({ href }: { href?: string }): ReactNode | null {
|
||||
if (href?.startsWith(ComputerRefHrefPrefix)) {
|
||||
@@ -105,9 +111,11 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
}
|
||||
|
||||
const question_id = botQuestionRefId({ href });
|
||||
|
||||
if (question_id) return <BotQuestionRefChip question_id={question_id} />;
|
||||
|
||||
const suggestion_id = botSuggestionRefId({ href });
|
||||
if (suggestion_id) return <BotSuggestionsRef suggestion_id={suggestion_id} />;
|
||||
|
||||
const chatroom_id = chatroomRefId({ href });
|
||||
|
||||
if (chatroom_id) return <ChatroomRefChip chatroom_id={chatroom_id} />;
|
||||
@@ -120,6 +128,10 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
|
||||
if (graphic_id) return <GraphicRefCard graphic_id={graphic_id} />;
|
||||
|
||||
const setting_ref = generalSettingsRefId({ href });
|
||||
|
||||
if (setting_ref) return <SettingRefChip section={setting_ref.section} field={setting_ref.field} />;
|
||||
|
||||
const folder_ref = parseFolderRefHref({ href });
|
||||
|
||||
if (folder_ref) return <FolderRefChip spec={folder_ref.spec} path={folder_ref.path} />;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { PagePropsType } from "@/src/types";
|
||||
import type { BunextPageModuleMetaFn } from "@moduletrace/bunext/types";
|
||||
import { SiteData } from "@/src/data/site-data";
|
||||
|
||||
/**
|
||||
* A General settings group page's title: the group, since two of them
|
||||
* would otherwise read the same.
|
||||
*/
|
||||
export default function settingsSectionPageMeta(): BunextPageModuleMetaFn {
|
||||
return async (params) => {
|
||||
const props = params.serverRes?.props as PagePropsType | undefined;
|
||||
const section = props?.general_section;
|
||||
const person = props?.person;
|
||||
const person_name = person
|
||||
? `${person.first_name + (person.last_name ? ` ${person.last_name}` : "")}`
|
||||
: "";
|
||||
const label = section?.title || "General";
|
||||
|
||||
return {
|
||||
title: `${label} Settings${person_name ? ` - ${person_name}` : ""} | ${SiteData["SiteName"]}`,
|
||||
description: `Read your ${label.toLowerCase()} settings on ${SiteData["SiteName"]}.`,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useContext, type ReactNode } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { ArrowRight } from "lucide-react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import { GeneralSettingsRoot, findGeneralSettingsSection } from "@/src/dict/general-settings-dict";
|
||||
|
||||
type Props = {
|
||||
title: string;
|
||||
@@ -16,8 +20,16 @@ type Props = {
|
||||
/**
|
||||
* One block of settings: what it is on the left, the controls on the right.
|
||||
* Stacks below 768px. Blocks are separated by hairlines, never cards.
|
||||
*
|
||||
* A group that has a page of its own (the one a bot's setting ref opens)
|
||||
* links to it, unless this is already that page.
|
||||
*/
|
||||
export default function SettingsGroup({ title, description, children, id }: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const section = findGeneralSettingsSection({ key: id });
|
||||
const href = section ? `${GeneralSettingsRoot}/${section.key}` : null;
|
||||
const on_own_page = href ? pageProps?.url?.pathname == href : false;
|
||||
|
||||
return (
|
||||
<Stack id={id} className="w-full scroll-mt-4 gap-4! md:grid md:grid-cols-[200px_1fr] md:gap-10! py-8 border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<Stack className="gap-1! min-w-0">
|
||||
@@ -29,6 +41,15 @@ export default function SettingsGroup({ title, description, children, id }: Prop
|
||||
{description}
|
||||
</Span>
|
||||
) : null}
|
||||
{href && !on_own_page ? (
|
||||
<Link
|
||||
href={href}
|
||||
className="inline-flex w-fit items-center gap-1 text-[13px] leading-[18px] font-bold text-ink-secondary hover:text-ink"
|
||||
>
|
||||
{`Open ${section?.title || title}`}
|
||||
<ArrowRight size={13} aria-hidden className="shrink-0" />
|
||||
</Link>
|
||||
) : null}
|
||||
</Stack>
|
||||
<Stack className="gap-4! min-w-0 w-full items-stretch">
|
||||
{children}
|
||||
|
||||
@@ -9,7 +9,11 @@ import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
title: string;
|
||||
description: string;
|
||||
/**
|
||||
* A line under the title. A group page leaves it out: its section
|
||||
* already says what the group is for.
|
||||
*/
|
||||
description?: string;
|
||||
/**
|
||||
* Controls at the end of the header, e.g. a settings link.
|
||||
*/
|
||||
@@ -44,14 +48,16 @@ export default function SettingsPaneHeader({
|
||||
>
|
||||
{title}
|
||||
</H1>
|
||||
<Span
|
||||
className={twMerge(
|
||||
"text-[13px] leading-[18px] text-ink-secondary truncate",
|
||||
"line-clamp-1 whitespace-nowrap w-full",
|
||||
)}
|
||||
>
|
||||
{description}
|
||||
</Span>
|
||||
{description ? (
|
||||
<Span
|
||||
className={twMerge(
|
||||
"text-[13px] leading-[18px] text-ink-secondary truncate",
|
||||
"line-clamp-1 whitespace-nowrap w-full",
|
||||
)}
|
||||
>
|
||||
{description}
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
{action ? (
|
||||
<Row className="ml-auto shrink-0 gap-1! flex-nowrap justify-end">
|
||||
|
||||
@@ -7,7 +7,7 @@ import SettingsPaneHeader from "./settings-pane-header";
|
||||
|
||||
type Props = {
|
||||
title: string;
|
||||
description: string;
|
||||
description?: string;
|
||||
children: ReactNode;
|
||||
/**
|
||||
* A wider column, for tables (activity).
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ComponentType } from "react";
|
||||
import AppearanceSection from "../(sections)/appearance-section";
|
||||
import AppNetworksSection from "../(sections)/app-networks-section";
|
||||
import ChatroomRetentionSection from "../(sections)/chatroom-retention-section";
|
||||
import ComputerWorkspacesSection from "../(sections)/computer-workspaces-section";
|
||||
import HookCallRetentionSection from "../(sections)/hook-call-retention-section";
|
||||
import InstallIconSection from "../(sections)/install-icon-section";
|
||||
import InstallNameSection from "../(sections)/install-name-section";
|
||||
import LogRetentionSection from "../(sections)/log-retention-section";
|
||||
import MessageLengthSection from "../(sections)/message-length-section";
|
||||
import NotificationsSection from "../(sections)/notifications-section";
|
||||
import PromptSection from "../(sections)/prompt-section";
|
||||
import RunLimitsSection from "../(sections)/run-limits-section";
|
||||
import SessionLengthSection from "../(sections)/session-length-section";
|
||||
import SkillLimitsSection from "../(sections)/skill-limits-section";
|
||||
import StorageSection from "../(sections)/storage-section";
|
||||
import VersionSection from "../(sections)/version-section";
|
||||
|
||||
/**
|
||||
* Each group of General settings, keyed as `GeneralSettingsSections` names
|
||||
* it, so the group's own page shows the same section the full page does
|
||||
* (and the same form, when the user may change it).
|
||||
*/
|
||||
const GeneralSettingsSectionComponents: Record<string, ComponentType> = {
|
||||
theme: AppearanceSection,
|
||||
"docker-networks": AppNetworksSection,
|
||||
chatrooms: ChatroomRetentionSection,
|
||||
"computer-workspaces": ComputerWorkspacesSection,
|
||||
"hook-calls": HookCallRetentionSection,
|
||||
"install-icon": InstallIconSection,
|
||||
"install-name": InstallNameSection,
|
||||
"activity-log": LogRetentionSection,
|
||||
messages: MessageLengthSection,
|
||||
notifications: NotificationsSection,
|
||||
"prompt-appendix": PromptSection,
|
||||
"run-limits": RunLimitsSection,
|
||||
sessions: SessionLengthSection,
|
||||
"skill-limits": SkillLimitsSection,
|
||||
storage: StorageSection,
|
||||
version: VersionSection,
|
||||
};
|
||||
|
||||
export default GeneralSettingsSectionComponents;
|
||||
@@ -87,6 +87,8 @@ export default function ChatroomRetentionForm({ retention }: Props) {
|
||||
<Input
|
||||
key={`keep-${form_key}`}
|
||||
label="Keep closed chatrooms for"
|
||||
id="keep_days"
|
||||
className="scroll-mt-24"
|
||||
type="number"
|
||||
min={0}
|
||||
max={overview?.max_days}
|
||||
@@ -105,6 +107,8 @@ export default function ChatroomRetentionForm({ retention }: Props) {
|
||||
<Input
|
||||
key={`max-${form_key}`}
|
||||
label="Most chatrooms per place"
|
||||
id="max_per_place"
|
||||
className="scroll-mt-24"
|
||||
type="number"
|
||||
min={0}
|
||||
max={overview?.max_per_place_ceiling}
|
||||
|
||||
@@ -69,6 +69,8 @@ export default function ComputerWorkspaceQuotaForm({ quota }: Props) {
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Input
|
||||
label="Megabytes per computer"
|
||||
id="quota_mb"
|
||||
className="scroll-mt-24"
|
||||
type="number"
|
||||
min={0}
|
||||
step={512}
|
||||
|
||||
@@ -83,6 +83,8 @@ export default function HookCallRetentionForm({ retention }: Props) {
|
||||
<Input
|
||||
key={`keep-${form_key}`}
|
||||
label="Keep hook calls for"
|
||||
id="keep_days"
|
||||
className="scroll-mt-24"
|
||||
type="number"
|
||||
min={0}
|
||||
max={overview?.max}
|
||||
|
||||
@@ -79,6 +79,8 @@ export default function InstallNameForm({ install_name }: Props) {
|
||||
<Input
|
||||
key={`install-name-${form_key}`}
|
||||
label="Install name"
|
||||
id="install_name"
|
||||
className="scroll-mt-24"
|
||||
placeholder={SiteData["SiteName"]}
|
||||
maxLength={PwaInstallNameMaxLength}
|
||||
defaultValue={value}
|
||||
|
||||
@@ -82,6 +82,8 @@ export default function LogRetentionForm({ retention }: Props) {
|
||||
<Input
|
||||
key={`keep-${form_key}`}
|
||||
label="Keep activity for"
|
||||
id="keep_days"
|
||||
className="scroll-mt-24"
|
||||
type="number"
|
||||
min={0}
|
||||
max={overview?.max}
|
||||
|
||||
@@ -82,6 +82,8 @@ export default function MessageLengthForm({ length }: Props) {
|
||||
<Input
|
||||
key={`chars-${form_key}`}
|
||||
label="Longest message"
|
||||
id="max_chars"
|
||||
className="scroll-mt-24"
|
||||
type="number"
|
||||
min={0}
|
||||
max={overview?.max}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { emptyRunLimitFields, startRunLimitNumber, type RunLimitFieldValue } from "./run-limit-fields";
|
||||
|
||||
const every = ({ value = "", unlimited = false }: Partial<RunLimitFieldValue>) => ({
|
||||
task_steps: { value, unlimited },
|
||||
reply_steps: { value, unlimited },
|
||||
unattended_steps: { value, unlimited },
|
||||
run_tokens: { value, unlimited },
|
||||
context_tokens: { value, unlimited },
|
||||
model_rest_seconds: { value, unlimited },
|
||||
});
|
||||
|
||||
describe("emptyRunLimitFields", () => {
|
||||
test("names every field whose switch is off with no number in it", () => {
|
||||
const values = every({ value: "" });
|
||||
|
||||
expect(emptyRunLimitFields({ values })).toEqual([
|
||||
"Tool steps per task",
|
||||
"Tool steps per chat reply",
|
||||
"Tool steps per routine or hook call",
|
||||
"Tokens per run",
|
||||
"Working context",
|
||||
"Model rest after a failure",
|
||||
]);
|
||||
});
|
||||
|
||||
test("a switch that's on needs no number, and a number needs no switch", () => {
|
||||
expect(emptyRunLimitFields({ values: every({ unlimited: true }) })).toEqual([]);
|
||||
expect(emptyRunLimitFields({ values: every({ value: "250000" }) })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a blank field with its switch off is the only thing it reports", () => {
|
||||
const values = {
|
||||
...every({ value: "100" }),
|
||||
context_tokens: { value: " ", unlimited: false },
|
||||
};
|
||||
|
||||
expect(emptyRunLimitFields({ values })).toEqual(["Working context"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("startRunLimitNumber", () => {
|
||||
test("a field with a default shows that default when its switch goes off", () => {
|
||||
expect(startRunLimitNumber({ limit: 250_000, ceiling: 100_000_000 })).toBe(250_000);
|
||||
});
|
||||
|
||||
test("a default that is itself unlimited leaves the field at the top of its range", () => {
|
||||
expect(startRunLimitNumber({ limit: "unlimited", ceiling: 10_000 })).toBe(10_000);
|
||||
expect(startRunLimitNumber({ ceiling: 3_600 })).toBe(3_600);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user