Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c36f8e3736 | ||
|
|
70ef0e6ae2 | ||
|
|
2a7ea3c76b | ||
|
|
7ffce997ce | ||
|
|
d80899b756 | ||
|
|
3671d9b72e | ||
|
|
78d7f66528 | ||
|
|
09b8269ced | ||
|
|
8b30480ceb | ||
|
|
7356494ff2 | ||
|
|
f08940341b | ||
|
|
915692a9ee | ||
|
|
8b1b7d9c64 | ||
|
|
45556b3b7f | ||
|
|
956a6b9772 | ||
|
|
3209828723 | ||
|
|
0d38268fef | ||
|
|
41be1b6fb1 | ||
|
|
37bd3335ff | ||
|
|
0a6d7d7410 | ||
|
|
7a0e16a6b5 | ||
|
|
0885e12a8b | ||
|
|
7da9003e7b | ||
|
|
b609d72888 | ||
|
|
8e1084263c | ||
|
|
e4e19ade1b | ||
|
|
5b09e7a8db | ||
|
|
1a2e7a25bb | ||
|
|
c892cda0eb | ||
|
|
b8fd60608d |
+2
-1
@@ -53,4 +53,5 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
/public/sitemap.xml
|
||||
/public/robots.txt
|
||||
/public/sitemap-chunks/
|
||||
/.tmp
|
||||
/.tmp
|
||||
/.playwright-mcp
|
||||
@@ -36,7 +36,7 @@ For the current UI read `src/layouts/bots/` (rail, workspace rail, user popover)
|
||||
| DB schema sync / admin UI / backup | `bun run db:schema` / `db:admin` / `db:backup` |
|
||||
| Seed super admin / sample crew | `bun run seed` (needs `SEED_SUPER_ADMIN_PASSWORD`) / `bun run seed:bots [email]` (idempotent) |
|
||||
| Query DB (read-only, JSON envelope) | `bun llm-code-assistant/query-db.ts "<sql>"` |
|
||||
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards |
|
||||
| Publish a release | `bun run publish:github` / `publish:gitea`; `bun run mirror:gitea` afterwards (`gh run watch` in between until the image build ends) |
|
||||
|
||||
No linter or formatter. `bun run typecheck` and `bun run test` are the verification steps. Use `query-db.ts` to see what is actually in the database instead of reading ORM code.
|
||||
|
||||
@@ -68,7 +68,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Cron
|
||||
|
||||
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `prune-logs`.
|
||||
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-bot-traces` (the debug view's runs, app setting `bot_trace_keep_days`), `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
|
||||
|
||||
### Admin CRUD API
|
||||
|
||||
@@ -83,27 +83,30 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Bot types
|
||||
|
||||
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
|
||||
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). A plain worker gets no work to hand out, but may pass on an open task of its own to a bot it could ask (`hand_over_task`, `hand-over-task-tool.ts`): its one permission, its own list only, and `BotTypeTargetMatrix` is left alone so it still directs no one, the targets coming from `chatroomAskableBots`. Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
|
||||
|
||||
### Bots, sessions, chat
|
||||
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). 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.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
|
||||
- **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).
|
||||
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Debug view:** what a run did in order: each turn with what the model reasoned (`stripThinkTags`'s `reasoning`, or the provider's `reasoning`/`reasoning_content`) and answered, each tool call with the arguments it was sent and the answer it got (and its duration), and the loop's own events (`wrap_up`, `redraft`, `review`, `incoming`, `steps_low`). `runTextLoop` emits them through `Params.trace` into `bot_job_traces` (never `bots_queue_updates`, which the `clear-job-steps` cron deletes a minute after a job ends). While a run works, the thinking row's bug button, beside Stop (`BotThinkingRow`), toggles a 250px strip under it (`(partials)/trace-panel.tsx`, `(partials)/trace-log-line.tsx`: one line per step, following its newest line while scrolled to the bottom), read live through `(hooks)/use-bot-trace.ts` and `api/admin/bots/trace`; that toggle stays as the user left it in every conversation (on this device, per user: `useDebugOpen` over `readDebugOpen`/`rememberDebugOpen`, `AppData.DebugViewStorageKey`). When the run ends its logs are tied to the message it answered (`attachJobTracesToMessage`, from the job helpers) and read in that message's Details modal, under a **Debug logs** tab beside Details (`(partials)/message-debug-logs.tsx`, `(hooks)/use-message-trace.ts`, `api/admin/bots/message-trace`), which copies itself as one markdown document (`CopyDebugLogsButton` over `messageDebugLogsMarkdown`), which checks the message's session for the user, a super admin, or the room for a chatroom message). Every entry is redacted before storage (`insertBotJobTrace` with the run's reachable envs, plus the task run's computer redaction for what the bot captured), cut to `AppData.BotTraceTextMaxChars`/`BotTraceArgumentsMaxChars`/`BotTraceResultMaxChars`, at most `BotTraceRowsPerJob` entries per run and `BotTraceJobsPerSession` runs shown, kept for the app setting `bot_trace_keep_days` (default `AppData.BotTraceKeepDays`, daily `prune-bot-traces`). Pushes carry only `BotTraceData` (`job_id`, `session_id`): an open view reads the entries it doesn't have.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
|
||||
- **Colour:** only `src/utils/bot-color.ts` resolves/validates colours and stones (`resolveBotColor`, `resolveBotStone`, `botColorNeedsPaperFace`); new bots get `pick-free-color.ts`.
|
||||
@@ -119,19 +122,20 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), 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.
|
||||
|
||||
### Live updates
|
||||
|
||||
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`. Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
|
||||
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, and the debug view's `server:bot-trace` (just the job and its session). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
|
||||
|
||||
### Chatrooms (`chatrooms`)
|
||||
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). Closing is what cancels a room's jobs, so `answer_requester` and `refuse_request` refuse while a member job still runs (`grabChatroomOpenJobs`, `chatroomOpenJobsWarning`) unless given `close_anyway`: a coordinator that answered over a live run once killed the very work it was asked for, then reported it picked up. A coordinator's turn creates no task and moves none (`chatroomCoordinatorNote`): a task is handed over by the bot that has it or by the user. A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. A room shows what it cost the way a conversation's messages do: each message carries its `MessageUsageChip` and the Details modal (read through the room's own `api/admin/chatrooms/message-details`, which checks the room's user), and above the thread `ChatroomUsageSummary` totals the room (`usage` on its summary, from `grabChatroomUsage`: every model call counted by its run's `bot_sessions.chatroom_id`, a turn still running included, with the room's failed calls and the same split by bot). **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
|
||||
### Workspaces
|
||||
|
||||
@@ -143,12 +147,12 @@ 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.
|
||||
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
|
||||
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
|
||||
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, and has no time limit of its own: `computer_bash` asks for none unless the bot names `timeout` (an install can cap what a bot names with `AppData.ComputerCommandMaxSeconds`, 0 = no cap), so a long script runs for hours, and the command is killed with its children only when the call is aborted (Stop), so nothing blocks the computer; the agent keeps that answer's connection alive with a space every `CommandHeartbeatMs` while it runs, since the app's `fetch` drops a connection that stays silent for about six minutes. Background work (`nohup ... &`) doesn't hold the call.
|
||||
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
|
||||
|
||||
### Schedules (routines in the UI)
|
||||
@@ -163,7 +167,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
|
||||
|
||||
### Tasks (the to-do tracker)
|
||||
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
|
||||
### Envs
|
||||
|
||||
@@ -215,21 +219,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.
|
||||
- **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`).
|
||||
- **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`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, 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. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **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, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget`; 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 at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, `hand_over_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
|
||||
|
||||
### Token usage
|
||||
|
||||
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`).
|
||||
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`, including `limits`: the steps, run tokens and context the run was held to, so a bot can explain a cost against them with `read_message_usage`).
|
||||
- Attribution through an `AsyncLocalStorage` scope (`src/harness/usage/harness-usage-scope.ts`) entered once in `run-bot-job.ts`; merged, not replaced; `null` clears a field. `withUsageScope` / `runWithFallbackScope` for calls outside a run. No owner, no row.
|
||||
- Every failed model call also writes a `harness_call_failures` row (`recordHarnessFailure`, beside the log in `withCandidates`: model, pick, HTTP status, the provider's reason, rest), same attribution, no foreign keys, pruned with the logs' retention by `prune-logs`.
|
||||
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons).
|
||||
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons, and the run's calls counted by tool from `bot_messages.tool_log` in `MessageToolsRollup`: 242 model calls read differently once it says `computer_bash` 210, `start_task` 0).
|
||||
- `/admin/usage` (crew managers). **Days are local, not UTC:** group with `date(created_at / 1000, 'unixepoch', 'localtime')`; never name a local day with `toISOString().slice(0, 10)` (`bucket-usage-days.test.ts` pins this). Bars use static `h-*` classes from `(data)/usage-bar-heights.ts`.
|
||||
|
||||
### Installer and release
|
||||
@@ -239,6 +243,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **App networks:** extra docker networks for the app's own container (never computers) are the app setting `app_extra_networks` (Settings > General, super admin, picked from the networks docker lists, `listJoinableNetworks`), joined by the app itself over the docker socket (`syncAppNetworks`) at boot, on save and every 5 minutes, so they outlast `install.sh` recreating the container; the installer's `--extra-network` still works beside it.
|
||||
- Plain HTTP only; TLS is the proxy's job. Container: `--network cobble`, `.env` read-only at `/app/.env`, docker socket, `MAIN_SERVER=1`, `--init`, `--cpus 1 --memory 2048m` by default.
|
||||
- Publishing: `scripts/publish-github.sh` / `publish-gitea.sh` sharing `scripts/lib/publish-*.sh` (tested by `scripts/publish-tools.test.ts`). A GitHub release triggers `.github/workflows/release.yml` (amd64 + arm64 to `ghcr.io/moduletrace/cobble`); `mirror-gitea.sh` copies to `git.tben.me/moduletrace/cobble` (CI can't reach the VPN). **Bump `package.json`'s `version` with a release.** CI (`ci.yml`) runs typecheck and tests. Dockerfile pins Bun 1.4.3.
|
||||
- **A release is done when every artifact exists, not when the tag is pushed.** Publishing (`publish`/`release`/`ship`, any of them) means the whole chain, run by you and watched to the end: `publish:github`, `publish:gitea`, then `gh run watch` until the image build succeeds, then `mirror:gitea` (it has nothing to copy until that build finishes). Report each artifact with its link, and say plainly (with the reason) if one fails or is still building: never hand back a tag and leave the rest as a note for the user.
|
||||
|
||||
## Admin routes
|
||||
|
||||
@@ -246,7 +251,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": {
|
||||
|
||||
@@ -124,14 +124,19 @@ export const AgentConfig = {
|
||||
*/
|
||||
NoVncDir: env.COBBLE_NOVNC_DIR || "/opt/novnc",
|
||||
/**
|
||||
* A command's timeout when it names none, and the most it may ask for.
|
||||
*/
|
||||
CommandDefaultSeconds: 270,
|
||||
CommandMaxSeconds: 3600,
|
||||
/**
|
||||
* Output past this is dropped (and the response says so).
|
||||
* A command has no time limit of its own: its caller asks for one (a
|
||||
* bot's `computer_bash` leaves it out for long scripts) and the
|
||||
* caller going away still kills it (`handle-exec`). Output past this is
|
||||
* dropped, and the response says so.
|
||||
*/
|
||||
CommandMaxOutputBytes: 4 * 1024 * 1024,
|
||||
/**
|
||||
* A command sends nothing while it runs, and the app's HTTP client gives
|
||||
* up on a connection that stays silent for minutes (Bun's own fetch cuts
|
||||
* one after about six minutes), so the answer keeps it alive with a space
|
||||
* this often. `JSON.parse` ignores the whitespace around the document.
|
||||
*/
|
||||
CommandHeartbeatMs: 15_000,
|
||||
/**
|
||||
* How long children get to exit on a stop before they're killed.
|
||||
*/
|
||||
|
||||
@@ -11,9 +11,11 @@ import workerEnv from "./worker-env";
|
||||
* `POST /api/exec` `{ command, timeout_seconds?, cwd?, run_as? }`: runs
|
||||
* one bash command as the computer's user (`runCommand`), or with
|
||||
* `run_as: { bot_id, workspace_id? }` as that worker bot's own account
|
||||
* (`requestRunUser`), from its home unless `cwd` is given. The command is
|
||||
* killed if the caller goes away. Answers `{ output, exit_code,
|
||||
* timed_out, truncated }`.
|
||||
* (`requestRunUser`), from its home unless `cwd` is given. It runs until
|
||||
* it ends unless the caller gives `timeout_seconds`, and is killed if the
|
||||
* caller goes away. Answers `{ output, exit_code, timed_out, truncated }`
|
||||
* after a space every `CommandHeartbeatMs` while it runs, so a client that
|
||||
* drops a silent connection keeps it.
|
||||
*/
|
||||
export default async function handleExec({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
const body = await readJsonBody({ req, max_bytes: 1024 * 1024 });
|
||||
@@ -27,18 +29,42 @@ export default async function handleExec({ req, res }: { req: IncomingMessage; r
|
||||
if (run_user === undefined) return;
|
||||
|
||||
const asked = Number(body.timeout_seconds);
|
||||
const timeout_seconds = Number.isFinite(asked) && asked > 0
|
||||
? Math.min(Math.ceil(asked), AgentConfig.CommandMaxSeconds)
|
||||
: AgentConfig.CommandDefaultSeconds;
|
||||
/**
|
||||
* A command has no time limit unless the caller asks for one: nothing,
|
||||
* or 0, means it runs until it ends, the caller goes away (this
|
||||
* response closes) or the container stops. A positive value is that
|
||||
* many seconds, however long, so a bot's script is never cut short.
|
||||
*/
|
||||
const timeout_seconds = Number.isFinite(asked) && asked > 0 ? Math.ceil(asked) : null;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
res.on("close", () => {
|
||||
if (!res.writableFinished) controller.abort();
|
||||
});
|
||||
/**
|
||||
* A heartbeat into a socket the caller closed must not take the agent
|
||||
* down, and there's nothing left to send it: stop the command.
|
||||
*/
|
||||
res.on("error", () => controller.abort());
|
||||
|
||||
const home = run_user ? run_user.home : AgentConfig.Home;
|
||||
|
||||
if (res.destroyed) return;
|
||||
|
||||
/**
|
||||
* The result goes out as one JSON body once the command ends, which may
|
||||
* be hours away, so the answer is opened now and kept alive with a space
|
||||
* until then: a client that drops a silent connection (`fetch` does, at
|
||||
* about six minutes) would otherwise lose the command's output and think
|
||||
* it failed. A space before the document is still JSON.
|
||||
*/
|
||||
res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
||||
|
||||
const heartbeat = setInterval(() => {
|
||||
if (!res.destroyed) res.write(" ");
|
||||
}, AgentConfig.CommandHeartbeatMs);
|
||||
|
||||
const result = await runCommand({
|
||||
command: body.command,
|
||||
cwd: typeof body.cwd == "string" && body.cwd.startsWith("/") ? body.cwd : home,
|
||||
@@ -49,5 +75,7 @@ export default async function handleExec({ req, res }: { req: IncomingMessage; r
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!res.destroyed) sendJson({ res, body: result });
|
||||
clearInterval(heartbeat);
|
||||
|
||||
if (!res.destroyed) res.end(JSON.stringify(result));
|
||||
}
|
||||
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -47,6 +47,14 @@ describe("runCommand", () => {
|
||||
expect(result.truncated).toBe(true);
|
||||
});
|
||||
|
||||
test("runs to the end with no time limit", async () => {
|
||||
const result = await runCommand({ ...base, timeout_seconds: null, command: "sleep 1; echo done" });
|
||||
|
||||
expect(result.output).toBe("done\n");
|
||||
expect(result.exit_code).toBe(0);
|
||||
expect(result.timed_out).toBe(false);
|
||||
});
|
||||
|
||||
test("is killed when aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ type Params = {
|
||||
* and `gid` are then left out.
|
||||
*/
|
||||
as?: { uid: number; gid: number };
|
||||
timeout_seconds: number;
|
||||
/**
|
||||
* Stop it after this many seconds, `null` for no time limit at all.
|
||||
*/
|
||||
timeout_seconds: number | null;
|
||||
max_output_bytes: number;
|
||||
/**
|
||||
* Aborting (the caller went away, the run was stopped) kills it.
|
||||
@@ -32,9 +35,10 @@ export type CommandResult = {
|
||||
* Runs one command in its own `bash -c`, in its own process group, with
|
||||
* no input (a prompt fails at once instead of waiting). stdout and stderr
|
||||
* come back together, in order, cut at `max_output_bytes`. Past its
|
||||
* timeout, or when aborted, the whole group gets TERM, then KILL 5s later.
|
||||
* It resolves when bash exits, not when every pipe closes, so work left in
|
||||
* the background (`nohup ... &`) keeps running without holding the call.
|
||||
* timeout (when it has one), or when aborted, the whole group gets TERM,
|
||||
* then KILL 5s later. It resolves when bash exits, not when every pipe
|
||||
* closes, so work left in the background (`nohup ... &`) keeps running
|
||||
* without holding the call.
|
||||
*/
|
||||
export default function runCommand({
|
||||
command,
|
||||
@@ -91,10 +95,12 @@ export default function runCommand({
|
||||
kill_timer = setTimeout(() => child.pid && killGroup({ pid: child.pid, signal: "SIGKILL" }), 5000);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
timed_out = true;
|
||||
stop();
|
||||
}, timeout_seconds * 1000);
|
||||
const timer = timeout_seconds == null
|
||||
? undefined
|
||||
: setTimeout(() => {
|
||||
timed_out = true;
|
||||
stop();
|
||||
}, timeout_seconds * 1000);
|
||||
|
||||
const onAbort = () => stop();
|
||||
|
||||
@@ -104,7 +110,7 @@ export default function runCommand({
|
||||
if (settled) return;
|
||||
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (timer) clearTimeout(timer);
|
||||
clearTimeout(kill_timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
+149
@@ -20,6 +20,7 @@ import {
|
||||
import { Harnesses } from "@/src/dict/harness-dict";
|
||||
import { HarnessProviderKinds } from "@/src/dict/harness-provider-dict";
|
||||
import { BotJobKinds, BotJobUpdateKinds } from "@/src/dict/bot-queue-dict";
|
||||
import { BotTraceKinds } from "@/src/dict/bot-trace-dict";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import {
|
||||
BotHookEventStatuses,
|
||||
@@ -1188,6 +1189,107 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_job_traces",
|
||||
tableDescription: `What a job did, in detail, for the conversation's debug view: one row per model turn (what it answered and reasoned), per tool call (the arguments it wrote and the answer it read), and per loop event (the wrap up, a redraft, what the user wrote mid-run). Written by \`process-bot-job\` as the run goes, tied to the message it ends in, and pruned after the app setting \`bot_trace_keep_days\``,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "bots_queue_id",
|
||||
fieldDescription: `The job (bots_queue) the trace belongs to`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bots_queue",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_job_traces_job_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot the job ran for`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bots",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_job_traces_bot_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The session the job answers in: who may read the trace`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bot_sessions",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_job_traces_session_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "message_id",
|
||||
fieldDescription: `The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "kind",
|
||||
fieldDescription: `turn, tool or event`,
|
||||
dataType: "TEXT",
|
||||
options: BotTraceKinds.map((k) => k.value),
|
||||
},
|
||||
{
|
||||
fieldName: "name",
|
||||
fieldDescription: `The tool or event's name; null on a model turn`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "text",
|
||||
fieldDescription: `What the model answered, or what the event says`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "reasoning",
|
||||
fieldDescription: `What the model reasoned before answering, when the provider hands it back`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "arguments",
|
||||
fieldDescription: `The arguments a tool call was made with, as the model wrote them`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "result",
|
||||
fieldDescription: `What the tool answered (cut to AppData.BotTraceResultMaxChars)`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "metadata",
|
||||
fieldDescription: `JSON details: the step index, model, tokens, duration, and whether the call went through`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_job_traces_job_created_at",
|
||||
indexTableFields: ["bots_queue_id", "created_at"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_job_traces_session_created_at",
|
||||
indexTableFields: ["session_id", "created_at"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_job_traces_message",
|
||||
indexTableFields: ["message_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_job_traces_created_at",
|
||||
indexTableFields: ["created_at"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "cron_jobs",
|
||||
tableDescription: `A bot's schedules (routines in the UI): a brief queued as a task on a cron schedule, in UTC. The \`run-cron-jobs\` cron queues the due ones every minute`,
|
||||
@@ -1797,6 +1899,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 +2790,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`,
|
||||
|
||||
+105
-1
@@ -17,6 +17,7 @@ export const BunSQLiteTables = [
|
||||
"task_notes",
|
||||
"bots_queue",
|
||||
"bots_queue_updates",
|
||||
"bot_job_traces",
|
||||
"cron_jobs",
|
||||
"bot_hooks",
|
||||
"bot_hook_events",
|
||||
@@ -24,6 +25,7 @@ export const BunSQLiteTables = [
|
||||
"secret_requests",
|
||||
"install_requests",
|
||||
"bot_questions",
|
||||
"bot_suggestions",
|
||||
"bot_graphics",
|
||||
"workspaces",
|
||||
"workspace_bots",
|
||||
@@ -762,6 +764,65 @@ export type BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES = {
|
||||
metadata?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_JOB_TRACES = {
|
||||
/**
|
||||
* 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 | "";
|
||||
/**
|
||||
* The job (bots_queue) the trace belongs to
|
||||
*/
|
||||
bots_queue_id?: number | "";
|
||||
/**
|
||||
* The bot the job ran for
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The session the job answers in: who may read the trace
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade
|
||||
*/
|
||||
message_id?: number | "";
|
||||
/**
|
||||
* turn, tool or event
|
||||
*/
|
||||
kind?: "turn" | "tool" | "event" | "";
|
||||
/**
|
||||
* The tool or event's name; null on a model turn
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* What the model answered, or what the event says
|
||||
*/
|
||||
text?: string;
|
||||
/**
|
||||
* What the model reasoned before answering, when the provider hands it back
|
||||
*/
|
||||
reasoning?: string;
|
||||
/**
|
||||
* The arguments a tool call was made with, as the model wrote them
|
||||
*/
|
||||
arguments?: string;
|
||||
/**
|
||||
* What the tool answered (cut to AppData.BotTraceResultMaxChars)
|
||||
*/
|
||||
result?: string;
|
||||
/**
|
||||
* JSON details: the step index, model, tokens, duration, and whether the call went through
|
||||
*/
|
||||
metadata?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_CRON_JOBS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -1164,6 +1225,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 +1725,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 +2926,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_BOT_JOB_TRACES & 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.20.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
@@ -35,6 +35,7 @@
|
||||
"@types/sanitize-html": "^2.16.2",
|
||||
"@types/turndown": "^5.0.6",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"marked": "17.0.6",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import completeBotJob from "@/src/functions/backend/db/bots-queue/complete-bot-j
|
||||
import failBotJob from "@/src/functions/backend/db/bots-queue/fail-bot-job";
|
||||
import updateBotJob from "@/src/functions/backend/db/bots-queue/update-bot-job";
|
||||
import insertBotJobUpdate from "@/src/functions/backend/db/bots-queue/insert-bot-job-update";
|
||||
import insertBotJobTrace from "@/src/functions/backend/db/bots-queue/insert-bot-job-trace";
|
||||
import grabReachableEnvs from "@/src/functions/backend/db/envs/grab-reachable-envs";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import createKeyLock from "@/src/utils/create-key-lock";
|
||||
import withTimeout from "@/src/utils/with-timeout";
|
||||
@@ -32,6 +34,7 @@ import nameBotSession from "./name-bot-session";
|
||||
import pushBotSession from "./push-bot-session";
|
||||
import grabSessionChatroomId from "@/src/functions/backend/db/chatrooms/grab-session-chatroom-id";
|
||||
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
|
||||
import type { BotTraceData } from "@/src/types";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import type { BotJobContext, BotJobRunner } from "./types";
|
||||
|
||||
@@ -159,10 +162,64 @@ export default async function processBotJob({
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Every secret the run reaches, blanked out of the trace it keeps: a
|
||||
* tool's arguments and answer carry whatever it handled, and the trace
|
||||
* is read by the user long after the run.
|
||||
*/
|
||||
let trace_secrets: { key: string; value: string }[] | undefined;
|
||||
/**
|
||||
* Rows this process wrote for the job, against
|
||||
* `AppData.BotTraceRowsPerJob`: a run that goes on for hours mustn't
|
||||
* fill the database with its details.
|
||||
*/
|
||||
let traced_rows = 0;
|
||||
|
||||
const trace: BotJobContext["trace"] = async (entry) => {
|
||||
if (!job.session_id || traced_rows >= AppData.BotTraceRowsPerJob) return;
|
||||
|
||||
try {
|
||||
trace_secrets ??= user_id
|
||||
? await grabReachableEnvs({
|
||||
bot_id,
|
||||
user_id,
|
||||
workspace_id: job.workspace_id,
|
||||
computer_id: job.computer_id,
|
||||
}).then((envs) =>
|
||||
[...envs.on_computer, ...envs.tools_only].map(({ key, value }) => ({ key, value })),
|
||||
)
|
||||
: [];
|
||||
|
||||
const row = await insertBotJobTrace({
|
||||
job_id,
|
||||
bot_id,
|
||||
session_id: Number(job.session_id) || null,
|
||||
trace: entry,
|
||||
secrets: trace_secrets,
|
||||
});
|
||||
|
||||
traced_rows++;
|
||||
|
||||
/**
|
||||
* The entry itself stays out of the push: the open drawer
|
||||
* reads it from the API, so a long tool result never crosses
|
||||
* a socket to a phone that isn't looking.
|
||||
*/
|
||||
await pushToSessionUser({
|
||||
session_id: job.session_id,
|
||||
data: {
|
||||
event: "server:bot-trace",
|
||||
data: { job_id, session_id: row.session_id ? Number(row.session_id) : null } satisfies BotTraceData,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
await logError({ title: `Bot job #${job_id} trace not saved`, error }).catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
const heartbeat = setInterval(() => {
|
||||
update({}).catch(() => {});
|
||||
}, HEARTBEAT_MS);
|
||||
|
||||
try {
|
||||
/**
|
||||
* The face changes once the job really starts, after any wait for
|
||||
@@ -178,12 +235,15 @@ export default async function processBotJob({
|
||||
});
|
||||
|
||||
/**
|
||||
* A deadline per attempt: the heartbeat keeps the lock alive
|
||||
* for as long as this run takes, so without one a call that
|
||||
* never answers would hold the slot forever.
|
||||
* A deadline per attempt for a reply: the heartbeat keeps the
|
||||
* lock alive for as long as this run takes, so without one a
|
||||
* chat answer that never comes would hold the conversation's
|
||||
* slot forever. A task run has none: a command or a build may
|
||||
* legitimately hold its computer for hours (`computer_bash` has
|
||||
* no time limit either), and Stop still ends it here and now.
|
||||
*/
|
||||
return await withTimeout({
|
||||
timeout_ms: AppData.BotJobAttemptTimeoutMs,
|
||||
timeout_ms: job.kind == "task" ? null : AppData.BotJobAttemptTimeoutMs,
|
||||
signal: controller.signal,
|
||||
message: timeout_message,
|
||||
on_timeout: () => {
|
||||
@@ -198,6 +258,7 @@ export default async function processBotJob({
|
||||
signal: run_signal,
|
||||
update,
|
||||
report,
|
||||
trace,
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -205,10 +266,10 @@ export default async function processBotJob({
|
||||
/**
|
||||
* A task whose computer is busy says so while it waits, so the
|
||||
* user doesn't see silence. A chatroom job doesn't wait: the bot
|
||||
* that asked is often the one holding the computer, with a run of
|
||||
* up to an hour, and the room would sit silent until it ends. It
|
||||
* works beside it with the shell and files only (`computer_shared`),
|
||||
* which is all most answers need.
|
||||
* that asked is often the one holding the computer, with a task run
|
||||
* that may hold it for hours, and the room would sit silent until it
|
||||
* ends. It works beside it with the shell and files only
|
||||
* (`computer_shared`), which is all most answers need.
|
||||
*/
|
||||
const runOnComputer = async (computer_id: number) => {
|
||||
if (computer_lock.busy({ key: computer_id })) {
|
||||
@@ -238,6 +299,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,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
CoordinatorSoloNote,
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
HandOverTaskNote,
|
||||
workspaceAdminNote,
|
||||
WorkspaceLearningNote,
|
||||
openRunsNote,
|
||||
@@ -60,6 +62,7 @@ import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
@@ -98,6 +101,7 @@ export default async function runBotReply({
|
||||
job,
|
||||
signal,
|
||||
report,
|
||||
trace,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
/**
|
||||
* Moves when the bot carries the conversation into a new session
|
||||
@@ -210,8 +214,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[] = [];
|
||||
/**
|
||||
@@ -328,6 +333,12 @@ export default async function runBotReply({
|
||||
* admin is told who leads it.
|
||||
*/
|
||||
const can_delegate = tools.some((tool) => tool.name == "delegate_task");
|
||||
/**
|
||||
* A worker passes on a task of its own (`hand_over_task`): the reply says
|
||||
* where it went and that it needs the run id, so no one claims a hand-over
|
||||
* that didn't happen.
|
||||
*/
|
||||
const can_hand_over = tools.some((tool) => tool.name == "hand_over_task");
|
||||
const lead = led as WorkspaceAdminTools | null;
|
||||
const crew_note = powers.is_coordinator
|
||||
? can_delegate
|
||||
@@ -354,10 +365,12 @@ export default async function runBotReply({
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
can_hand_over ? HandOverTaskNote : "",
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask: true }),
|
||||
QuestionsNote,
|
||||
RequestScopeNote({ can_ask: Boolean(attended) }),
|
||||
attended ? QuestionsNote : "",
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
|
||||
GraphicsNote,
|
||||
workspace_id ? WorkspaceLearningNote : "",
|
||||
@@ -406,13 +419,30 @@ export default async function runBotReply({
|
||||
onRequest: ({ ref }) => proposals.push(ref),
|
||||
onShow: ({ ref }) => shown.push(ref),
|
||||
}),
|
||||
askUserTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onAsk: ({ ref }) => proposals.push(ref),
|
||||
}),
|
||||
/**
|
||||
* Only where the user follows the conversation: a chatroom's
|
||||
* hidden session has no card they could answer, and a
|
||||
* question there was once shown to the coordinator as a bare
|
||||
* ref, its answer never reaching the bot.
|
||||
*/
|
||||
...(attended
|
||||
? [
|
||||
askUserTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onAsk: ({ ref }) => proposals.push(ref),
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => shown.push(ref),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(has_past_sessions
|
||||
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
|
||||
: []),
|
||||
@@ -437,6 +467,7 @@ export default async function runBotReply({
|
||||
workspace_id,
|
||||
signal,
|
||||
onStep: report,
|
||||
trace,
|
||||
incoming,
|
||||
/**
|
||||
* Files, tasks and work the answer names are checked against
|
||||
|
||||
+129
-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,8 @@ 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 redactTrace from "@/src/harness/trace/redact-trace";
|
||||
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 +46,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 +71,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";
|
||||
|
||||
@@ -102,6 +109,7 @@ export default async function runBotTask({
|
||||
computer_shared,
|
||||
signal,
|
||||
report,
|
||||
trace,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
const workspace_id = job.workspace_id || null;
|
||||
/**
|
||||
@@ -158,6 +166,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 +293,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 +390,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 +431,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,
|
||||
@@ -467,6 +527,12 @@ export default async function runBotTask({
|
||||
signal,
|
||||
onStep: (step) =>
|
||||
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
|
||||
/**
|
||||
* The trace also holds a computer's own secrets: what the bot
|
||||
* captured mid-run (`capture_secret`) never reaches the
|
||||
* stored trace, whatever the job's envs are.
|
||||
*/
|
||||
trace: (entry) => trace(computer ? redactTrace({ trace: entry, redact: computer.redact }) : entry),
|
||||
...(incoming
|
||||
? {
|
||||
incoming: incoming.take,
|
||||
@@ -489,11 +555,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();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import sessionNameTranscript from "./session-name-transcript";
|
||||
|
||||
describe("sessionNameTranscript", () => {
|
||||
@@ -24,4 +25,25 @@ describe("sessionNameTranscript", () => {
|
||||
expect(transcript).toStartWith("(Summary of the earlier session this one carries on from)\n- Crew set up");
|
||||
expect(transcript).not.toContain("You: - Crew set up");
|
||||
});
|
||||
|
||||
test("names a session once as the opening pasted whole", () => {
|
||||
const brief = "a".repeat(AppData.BotSessionNameMessageChars);
|
||||
|
||||
expect(sessionNameTranscript({ messages: [{ id: 1, author: "user", text: brief }] })).toBe(`User: ${brief}`);
|
||||
});
|
||||
|
||||
test("cuts a pasted brief to its opening, and says it goes on", () => {
|
||||
const brief = "x".repeat(30_000);
|
||||
|
||||
const transcript = sessionNameTranscript({ messages: [{ id: 1, author: "user", text: brief }] });
|
||||
|
||||
expect(transcript).toStartWith(`User: ${brief.slice(0, AppData.BotSessionNameMessageChars)}...`);
|
||||
expect(transcript).toContain("the opening continues");
|
||||
expect(transcript).toContain("30,000 characters in all");
|
||||
expect(transcript.length).toBeLessThan(AppData.BotSessionNameMessageChars + 200);
|
||||
});
|
||||
|
||||
test("says a message carried only files", () => {
|
||||
expect(sessionNameTranscript({ messages: [{ id: 1, author: "user", text: "" }] })).toBe("User: (files only)");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { SessionOpeningMessage } from "@/src/functions/backend/db/bot-sessions/grab-session-opening";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
messages: SessionOpeningMessage[];
|
||||
@@ -9,13 +10,31 @@ type Params = {
|
||||
* a session the bot moved the conversation into is marked as the earlier
|
||||
* session's, so the title says what this one carries on with rather than
|
||||
* echoing everything the summary recaps.
|
||||
*
|
||||
* Each message is cut to `AppData.BotSessionNameMessageChars`: a pasted
|
||||
* brief of tens of thousands of characters names a session no better than
|
||||
* its first couple of paragraphs, and this is a model call like any other.
|
||||
*/
|
||||
export default function sessionNameTranscript({ messages }: Params) {
|
||||
return messages
|
||||
.map((message) =>
|
||||
message.carried_from_session_id
|
||||
? `(Summary of the earlier session this one carries on from)\n${message.text || ""}`
|
||||
: `${message.author == "user" ? "User" : "You"}: ${message.text || "(files only)"}`,
|
||||
? `(Summary of the earlier session this one carries on from)\n${openingText({ text: message.text })}`
|
||||
: `${message.author == "user" ? "User" : "You"}: ${openingText({ text: message.text })}`,
|
||||
)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* What the naming turn reads of one message, cut at the limit with a note
|
||||
* so the model knows the opening goes on.
|
||||
*/
|
||||
function openingText({ text }: { text: string | null | undefined }) {
|
||||
const whole = text || "";
|
||||
|
||||
if (whole.length <= AppData.BotSessionNameMessageChars) return whole || "(files only)";
|
||||
|
||||
const cut = whole.slice(0, AppData.BotSessionNameMessageChars);
|
||||
|
||||
return `${cut}... (the opening continues, ${whole.length.toLocaleString("en-US")} characters in all)`;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import type { TextLoopStep } from "@/src/harness/text/run-text-loop";
|
||||
import type { HarnessTracer } from "@/src/harness/trace/types";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
|
||||
export type BotJobContext = {
|
||||
@@ -35,6 +36,14 @@ export type BotJobContext = {
|
||||
* `onStep`. Best effort: a failed write never stops the job.
|
||||
*/
|
||||
report: (step: TextLoopStep) => Promise<void>;
|
||||
/**
|
||||
* Keeps what the run did in detail (`bot_job_traces`): every turn with
|
||||
* its reasoning, every tool call with its arguments and answer, and
|
||||
* what the loop itself did. The conversation's debug view reads it.
|
||||
* Pass it as the text loop's `trace`. Best effort, redacted before it
|
||||
* is stored, and a failed write never stops the job.
|
||||
*/
|
||||
trace: HarnessTracer;
|
||||
};
|
||||
|
||||
export type BotJobOutcome = {
|
||||
@@ -62,6 +71,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));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import SunkenCodeBlock from "./sunken-code-block";
|
||||
|
||||
type Props = {
|
||||
text: string;
|
||||
@@ -12,17 +12,7 @@ type Props = {
|
||||
export default function FilePreviewCode({ text }: Props) {
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full overflow-auto p-4 items-stretch">
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary",
|
||||
}}
|
||||
className="font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10 whitespace-pre-wrap wrap-anywhere"
|
||||
>
|
||||
{text}
|
||||
</CodeBlock>
|
||||
<SunkenCodeBlock wrapAnywhere>{text}</SunkenCodeBlock>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Select from "@moduletrace/twui/form/Select";
|
||||
import Textarea from "@moduletrace/twui/form/Textarea";
|
||||
@@ -24,6 +25,12 @@ type Props<T> = {
|
||||
* Offer a note added to the brief (a task's hand-over).
|
||||
*/
|
||||
with_note?: boolean;
|
||||
/**
|
||||
* Offer to start the work now (a task's hand-over). Off by default:
|
||||
* handing a task over only moves it, it never starts the work unless
|
||||
* the user asks for that here.
|
||||
*/
|
||||
with_start?: boolean;
|
||||
onHandedOver: (params: { saved: T; msg: string }) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
@@ -39,12 +46,14 @@ export default function HandOverForm<T extends { [k: string]: any }>({
|
||||
submit_path,
|
||||
body,
|
||||
with_note,
|
||||
with_start,
|
||||
onHandedOver,
|
||||
onCancel,
|
||||
}: Props<T>) {
|
||||
const [targets, setTargets] = useState<HandOverTarget[]>();
|
||||
const [bot_id, setBotId] = useState<number>();
|
||||
const [note, setNote] = useState("");
|
||||
const [start, setStart] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
@@ -73,14 +82,19 @@ export default function HandOverForm<T extends { [k: string]: any }>({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window.confirm(`Hand ${what} over to ${target.name}?`)) return;
|
||||
if (!window.confirm(`Hand ${what} over to ${target.name}${with_start && start ? " and start it now" : ""}?`)) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await postAdminApi<T>({
|
||||
path: submit_path,
|
||||
body: { ...body, bot_id: target.id, instructions: with_note && note.trim() ? note : undefined },
|
||||
body: {
|
||||
...body,
|
||||
bot_id: target.id,
|
||||
instructions: with_note && note.trim() ? note : undefined,
|
||||
...(with_start ? { start } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
setLoading(false);
|
||||
@@ -121,6 +135,16 @@ export default function HandOverForm<T extends { [k: string]: any }>({
|
||||
disabled={loading}
|
||||
/>
|
||||
) : null}
|
||||
{with_start && targets?.length ? (
|
||||
<Checkbox
|
||||
title="Start it now"
|
||||
label="Start it now"
|
||||
info="Left off, the task only moves: it lands on their list as to do, and nothing runs until they're told to start."
|
||||
checked={start}
|
||||
clickDispatchHandler={setStart}
|
||||
wrap
|
||||
/>
|
||||
) : null}
|
||||
<AddFormActions submit_label="Hand over" loading={loading} error={error} onCancel={onCancel} />
|
||||
</Stack>
|
||||
</Form>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import SunkenCodeBlock from "./sunken-code-block";
|
||||
|
||||
/**
|
||||
* twui's CodeBlock is a fixed dark block with a white copy icon. Everywhere
|
||||
* the app shows code it wants the theme's sunken surface instead, so this
|
||||
* wrapper is the one place that decides that: a light-mode Details modal
|
||||
* once showed dark-on-dark text because the block stayed `#28272b`.
|
||||
*/
|
||||
describe("SunkenCodeBlock", () => {
|
||||
test("rides the theme's sunken surface", () => {
|
||||
const html = renderToString(<SunkenCodeBlock>ls -la</SunkenCodeBlock>);
|
||||
|
||||
expect(html).toContain("var(--color-sunken)");
|
||||
expect(html).not.toContain("#28272b");
|
||||
expect(html).toContain("outline-hairline");
|
||||
});
|
||||
|
||||
test("draws the copy icon and its label in ink", () => {
|
||||
const html = renderToString(<SunkenCodeBlock>ls</SunkenCodeBlock>);
|
||||
|
||||
expect(html).toContain("stroke-ink-secondary");
|
||||
expect(html).toContain("twui-code-block-copied-text]:text-ink");
|
||||
});
|
||||
|
||||
test("sets code at 13px, and only breaks anywhere when asked", () => {
|
||||
const closing = renderToString(<SunkenCodeBlock>{"a".repeat(40)}</SunkenCodeBlock>);
|
||||
const wrapping = renderToString(<SunkenCodeBlock wrapAnywhere>{"a".repeat(40)}</SunkenCodeBlock>);
|
||||
|
||||
expect(closing).toContain("text-[13px]");
|
||||
expect(closing).not.toContain("wrap-anywhere");
|
||||
expect(wrapping).toContain("wrap-anywhere");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ReactNode } from "react";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
children?: ReactNode;
|
||||
/**
|
||||
* Break long words as well as lines, so one unbroken token (a JSON
|
||||
* argument, a long path) never pushes the block wider than its panel.
|
||||
*/
|
||||
wrapAnywhere?: boolean;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A block of code on the theme's sunken surface rather than twui's own dark
|
||||
* block (it defaults to `#28272b`): the surface follows light and dark, so
|
||||
* the text stays legible in both. twui draws the copy icon and its "Copied!"
|
||||
* label white, so both are recoloured to the ink scale, and the block is set
|
||||
* at 13px, the size the dense views around it use.
|
||||
*/
|
||||
export default function SunkenCodeBlock({ children, wrapAnywhere, className }: Props) {
|
||||
return (
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary [&_.twui-code-block-copied-text]:text-ink",
|
||||
}}
|
||||
className={twMerge(
|
||||
"font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10",
|
||||
wrapAnywhere && "whitespace-pre-wrap wrap-anywhere",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</CodeBlock>
|
||||
);
|
||||
}
|
||||
@@ -131,6 +131,7 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
submit_path="tasks/hand-over-task"
|
||||
body={{ task_id: Number(task.id) }}
|
||||
with_note
|
||||
with_start
|
||||
onCancel={() => setHandingOver(false)}
|
||||
onHandedOver={({ saved, msg }) => {
|
||||
setHandingOver(false);
|
||||
|
||||
@@ -3,9 +3,11 @@ import cronHeartbeat from "./heartbeat";
|
||||
import pruneBotsQueue from "./prune-bots-queue";
|
||||
import cronClearJobSteps from "./clear-job-steps";
|
||||
import pruneBotHookEvents from "./prune-bot-hook-events";
|
||||
import pruneBotTraces from "./prune-bot-traces";
|
||||
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";
|
||||
@@ -50,6 +52,12 @@ export default function cron() {
|
||||
task: pruneBotHookEvents,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-bot-traces",
|
||||
schedule: "@daily",
|
||||
task: pruneBotTraces,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-chatrooms",
|
||||
schedule: "@daily",
|
||||
@@ -80,6 +88,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,17 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { grabBotTraceKeepDays } from "@/src/functions/backend/db/app-settings/grab-bot-trace-keep-days";
|
||||
|
||||
/**
|
||||
* Deletes run traces (`bot_job_traces`, the conversation's debug view)
|
||||
* older than the install's retention (`grabBotTraceKeepDays`). Deleting a
|
||||
* job takes its traces with it (foreign keys), so this only takes what no
|
||||
* daily job prune would.
|
||||
*/
|
||||
export default async function pruneBotTraces() {
|
||||
const cutoff = Date.now() - (await grabBotTraceKeepDays()) * 24 * 60 * 60 * 1000;
|
||||
|
||||
return await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_job_traces WHERE created_at < ? RETURNING id`,
|
||||
values: [cutoff],
|
||||
});
|
||||
}
|
||||
@@ -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) };
|
||||
}
|
||||
+168
-44
@@ -1,3 +1,4 @@
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { SiteData } from "./site-data";
|
||||
|
||||
export const AppData = {
|
||||
@@ -50,6 +51,12 @@ export const AppData = {
|
||||
* next open starts there.
|
||||
*/
|
||||
ComputerViewModeStorageKey: `${SiteData["SiteSlug"]}_computer_view_modes`,
|
||||
/**
|
||||
* Whether each user left the conversation's debug view open, on this
|
||||
* device (`readDebugOpen`/`rememberDebugOpen`): the view is theirs, so
|
||||
* it stays as they left it in every conversation.
|
||||
*/
|
||||
DebugViewStorageKey: `${SiteData["SiteSlug"]}_debug_view_open`,
|
||||
ServerHealthMessage: "Server Running Well",
|
||||
AuthKeyCookieName: `${SiteData["SiteSlug"]}_auth_key`,
|
||||
AuthCSRFCookieName: `${SiteData["SiteSlug"]}_auth_csrf`,
|
||||
@@ -110,7 +117,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.2",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -167,6 +174,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,
|
||||
@@ -297,13 +311,16 @@ export const AppData = {
|
||||
BotQueueLockTimeoutMs: 10 * 60 * 1000,
|
||||
BotQueueBackoffMs: 30 * 1000,
|
||||
/**
|
||||
* One attempt of a job (one model run or task, tools included) gives up
|
||||
* after this long and counts as a failed try, so a call that hangs
|
||||
* without ever answering can't hold the job, its computer or the
|
||||
* conversation forever. The lock is outlived by the heartbeat, so this
|
||||
* is the only thing that stops a live but stuck run.
|
||||
* A reply's deadline: one attempt (its model run and tools included)
|
||||
* gives up after this long and counts as a failed try, so a chat answer
|
||||
* that hangs without ever answering can't hold the conversation
|
||||
* forever. The lock is outlived by the heartbeat, so this is the only
|
||||
* thing that stops a live but stuck reply. A task run has none (a
|
||||
* command or a build may hold it for hours): only Stop, a lost lock or
|
||||
* the process ending stops its work, and a command on its computer is
|
||||
* stopped when the call is aborted.
|
||||
*/
|
||||
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 +422,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 +441,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,
|
||||
/**
|
||||
@@ -433,10 +473,10 @@ export const AppData = {
|
||||
HarnessMaxCandidates: 6,
|
||||
HarnessRequestTimeoutMs: 3 * 60 * 1000,
|
||||
/**
|
||||
* One tool call gives up after this long, whatever the tool is (bot
|
||||
* tools, MCP servers, computers, custom tools), so a tool that ignores
|
||||
* its own limits can't stall the run. Its result comes back as an error
|
||||
* the model can work around.
|
||||
* One tool call gives up after this long unless the tool names its own
|
||||
* deadline (`HarnessTool.timeout_ms`, `null` for none), so a tool that
|
||||
* ignores its own limits can't stall the run. Its result comes back as
|
||||
* an error the model can work around.
|
||||
*/
|
||||
HarnessToolTimeoutMs: 10 * 60 * 1000,
|
||||
/**
|
||||
@@ -462,27 +502,61 @@ 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`.
|
||||
*
|
||||
* 4M, not 40M: at 40M a run could spend 195 turns re-reading its own
|
||||
* notes and still be under the ceiling, which is what one task run did
|
||||
* (30M tokens, zero rows written, Nov 2026). A run that needs more than
|
||||
* 4M is a run to split, and an install can raise it to
|
||||
* `RunMaxPromptTokensMax`.
|
||||
*/
|
||||
RunMaxPromptTokens: 4_000_000,
|
||||
/**
|
||||
* Share of its token budget a run is told about, once: past half of
|
||||
* it, every further turn costs what the answer costs, so it lands the
|
||||
* work rather than going on gathering (`tokensLowNote`).
|
||||
*/
|
||||
HarnessRunTokensWarnShare: 0.5,
|
||||
/**
|
||||
* Share of its token budget a run may spend before it is told, once,
|
||||
* that nothing has been produced yet: a quarter in, it still has room
|
||||
* to land the work, and a run that spends the whole budget measuring
|
||||
* ends with a report of what it found and none of what it was asked for
|
||||
* (`commitEarlyNote`). 0 turns it off.
|
||||
*/
|
||||
HarnessRunTokensCommitShare: 0.25,
|
||||
/**
|
||||
* How many times an identical call may fail before the run is answered
|
||||
* from that failure instead of paying for it again: one retry (a
|
||||
* transient error is worth retrying), then the note that the call
|
||||
* itself is wrong. A failing command was once repeated five times in a
|
||||
* row, each repeat resending the whole transcript.
|
||||
*/
|
||||
HarnessSameFailureRetries: 1,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
@@ -492,12 +566,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 +580,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
|
||||
@@ -600,10 +677,12 @@ export const AppData = {
|
||||
McpToolTimeoutMs: 5 * 60 * 1000,
|
||||
/**
|
||||
* A bash command on a computer (`computer_bash`) is killed there, with
|
||||
* everything it started, after at most this long, below
|
||||
* `HarnessToolTimeoutMs`.
|
||||
* everything it started, after at most this long: 0 leaves it no time
|
||||
* limit at all, so a script may run for hours. The bot may name its own
|
||||
* `timeout`, which a limit here still caps. Long work holds the
|
||||
* computer (one task run per computer), and Stop ends it.
|
||||
*/
|
||||
ComputerCommandMaxSeconds: 270,
|
||||
ComputerCommandMaxSeconds: 0,
|
||||
/**
|
||||
* What a computer's command hands the bot back (its start and end), and
|
||||
* what `computer_read_file` reads: lines at a time, each line cut
|
||||
@@ -614,7 +693,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,
|
||||
@@ -685,6 +764,23 @@ export const AppData = {
|
||||
* to have pushed the last ones (`LiveRelayPollMs`).
|
||||
*/
|
||||
BotJobStepsKeepMs: 60 * 1000,
|
||||
/**
|
||||
* The debug view's detailed trace of a job (`bot_job_traces`, read and
|
||||
* written only by `process-bot-job`): how many rows one job keeps, how
|
||||
* much of any one text, and how long the rows stay before the daily
|
||||
* `prune-bot-traces` deletes them (the install may set its own, the app
|
||||
* setting `bot_trace_keep_days`, up to `BotTraceKeepDaysMax`).
|
||||
*/
|
||||
BotTraceRowsPerJob: 400,
|
||||
BotTraceTextMaxChars: 4000,
|
||||
BotTraceArgumentsMaxChars: 2000,
|
||||
BotTraceResultMaxChars: 8000,
|
||||
BotTraceKeepDays: 7,
|
||||
BotTraceKeepDaysMax: 365,
|
||||
/**
|
||||
* How many of a session's jobs the debug view offers, newest first.
|
||||
*/
|
||||
BotTraceJobsPerSession: 5,
|
||||
/**
|
||||
* How often each server process reads new bot messages, job steps and
|
||||
* bot changes from the database for its own sockets (`liveRelay`).
|
||||
@@ -802,9 +898,13 @@ export const AppData = {
|
||||
BotSessionSummaryMaxChars: 4000,
|
||||
/**
|
||||
* The first messages of a session the bot reads to name and summarize
|
||||
* it once the first reply is in, and how long its title may be.
|
||||
* it once the first reply is in, how much of each message it reads (a
|
||||
* pasted brief can run to tens of thousands of characters, and the
|
||||
* naming turn is a model call like any other), and how long its title
|
||||
* may be.
|
||||
*/
|
||||
BotSessionNameMessages: 4,
|
||||
BotSessionNameMessageChars: 2000,
|
||||
BotSessionTitleMaxChars: 80,
|
||||
/**
|
||||
* Sessions listed per page in a conversation's sessions modal.
|
||||
@@ -847,11 +947,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 +970,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 +1037,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 +1083,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,
|
||||
|
||||
@@ -34,7 +34,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
|
||||
- Delegating into a workspace the worker isn't in adds it to that workspace as a side effect. Say that in your reply when it happens; don't add members silently for a one-off.
|
||||
- Give a full brief: objective, inputs, deliverable, acceptance criteria, constraints.
|
||||
- Check \`list_tasks\` first. Never give two bots the same job, and don't restart work an open task already covers.
|
||||
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there), goes to doing, and the worker moves that same task along. Never copy it into a new one.
|
||||
- When the work is already a task on a list, hand that task over: \`delegate_task\` with its \`task_id\`. It moves to the worker (a workspace's task stays on that workspace's list and is worked there) and the worker moves that same task along. Never copy it into a new one. A hand-over lands on their list as to do and starts nothing: pass \`start: true\` only when the user asked for the work to begin now, and when they asked for the move but not whether to start it, ask first (one \`ask_user\` card with every task they named) and hand over once they've answered.
|
||||
- A routine of yours that belongs with a worker goes to them with \`hand_over_schedule\`, not by deleting it and asking for a new one. A routine in a workspace keeps running there.
|
||||
- Track what comes back, judge it against the request, and integrate it. Don't pass a worker's unchecked claim on as fact.
|
||||
- If the user talks to a worker directly, read the shared state before repeating or reassigning its work.
|
||||
|
||||
@@ -113,6 +113,7 @@ describe("RequestScopeNote", () => {
|
||||
expect(note).toContain("a standing preference is not a standing instruction");
|
||||
expect(note).toContain("the same ask_user card");
|
||||
expect(note).toContain("delegating a task");
|
||||
expect(note).toContain("ask before it leaves: one ask_user card with every task they named");
|
||||
expect(note).toContain("don't offer it again in this conversation");
|
||||
expect(note).not.toContain("the brief is what you may do");
|
||||
expect(note).not.toContain("\u2014");
|
||||
@@ -123,6 +124,7 @@ describe("RequestScopeNote", () => {
|
||||
|
||||
expect(note).toContain("the brief is what you may do");
|
||||
expect(note).toContain("Say in your report what you would propose");
|
||||
expect(note).toContain("move it as to do and say in your report that it waits for the user to start it");
|
||||
expect(note).not.toContain("ask_user");
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
|
||||
+171
-9
@@ -72,7 +72,9 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
|
||||
## Keep the work moving
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.`;
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
|
||||
Your answer and that card go out together: ask_user and suggest_next_steps end the reply. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: where its files live,
|
||||
@@ -195,6 +197,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
|
||||
@@ -214,6 +231,11 @@ The user's request sets the scope. Do what they asked, in the scope they gave, a
|
||||
: `the brief is what you may do. Say in your report what you would propose, and why.`
|
||||
}
|
||||
- When you can't tell whether something was asked for, it wasn't: ask. Once the user has chosen, do exactly that, nothing bundled with it.
|
||||
- Handing a task over moves it; starting the work is a separate thing the user asks for. When they asked for the move but not for it to start, ${
|
||||
can_ask
|
||||
? `ask before it leaves: one ask_user card with every task they named.`
|
||||
: `move it as to do and say in your report that it waits for the user to start it.`
|
||||
}
|
||||
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
|
||||
|
||||
/**
|
||||
@@ -243,7 +265,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
|
||||
* `bot_id` is the coordinator itself, so the ref example it copies is its
|
||||
* own rather than a worker's.
|
||||
*/
|
||||
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
|
||||
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
|
||||
|
||||
/**
|
||||
* Added to the coordinator's chat prompt instead while it has no workers,
|
||||
@@ -264,7 +286,7 @@ export const workspaceAdminNote = ({
|
||||
members: { id?: number | "" }[];
|
||||
}) => `# Leading ${workspace_name}
|
||||
|
||||
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
|
||||
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
|
||||
|
||||
/**
|
||||
* Added to a workspace member's prompt while the workspace has an admin,
|
||||
@@ -280,7 +302,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 +330,129 @@ 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.`;
|
||||
|
||||
/**
|
||||
* What a run gets back instead of paying for the same failure again: an
|
||||
* identical call (same tool, same arguments) that failed, retried once
|
||||
* (`AppData.HarnessSameFailureRetries`), fails the same way, and the error
|
||||
* is almost never about luck: it is the call itself. Nothing that could
|
||||
* have changed the outcome has run since, or the memory would have been
|
||||
* dropped.
|
||||
*/
|
||||
export const failedToolCallNote = ({
|
||||
name,
|
||||
step,
|
||||
attempts,
|
||||
error,
|
||||
}: {
|
||||
name: string;
|
||||
step: number;
|
||||
attempts: number;
|
||||
error: string;
|
||||
}) =>
|
||||
`You called ${name} with these exact arguments ${attempts} times since step ${step + 1} of this run, and it failed the same way each time: ${error}
|
||||
|
||||
Nothing has run since that could change that answer, so calling it once more only buys the same error (and resends this whole conversation). Fix the call itself: change the arguments, do the step it is missing first, or report it as blocked.`;
|
||||
|
||||
/**
|
||||
* Told once to a run that wrote a message for the user and then called a
|
||||
* tool: only the run's last message goes out, so that one never arrived.
|
||||
* Said while the turn carrying the tool's answer is still in the transcript,
|
||||
* so writing it again costs nothing but the tokens. A bot answered "here are
|
||||
* the links", went on to list its tasks, and the user was sent the list
|
||||
* alone (Nov 2026).
|
||||
*/
|
||||
export const answerNotSentNote = `The message you wrote before these tool results was never sent: a run sends only its final message, and you went on to call a tool after writing that one. If the user still needs any of it, write it again in your last message. Don't send work in progress as an answer and then carry on.`;
|
||||
|
||||
/**
|
||||
* Told once, when the prompt no longer fits the working context even after
|
||||
* everything trimmable was trimmed: what is left is what the user wrote,
|
||||
* which the app never cuts. A run that keeps reading whole files into the
|
||||
* conversation only makes the next turn larger, and its answer is paid for
|
||||
* out of whatever room is left. Told rather than trimming the request: the
|
||||
* model has to know it may not be seeing all of a pasted brief, so it says
|
||||
* what it could not reach instead of inventing the rest.
|
||||
*/
|
||||
export const oversizedRequestNote = ({ budget }: { budget: number }) =>
|
||||
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and none of what is over is yours to trim: the app cuts tool output, never what the user wrote. Every turn resends all of it, so reading more makes the next one worse.
|
||||
|
||||
From here: stop pulling whole files, whole pages or entire command outputs into the conversation. Work from what you already have, read only the piece you need (a line range, a filter, grep), write what must be kept to a file rather than into a message, and answer on this turn.
|
||||
|
||||
If what you need sits in a part of the request you cannot reach in one piece, say plainly what you could and could not read, and ask the user to attach it as a file, put it in a knowledgebase, or point you at a path. A guess presented as a reading of it is worse than saying it was too long.`;
|
||||
|
||||
/**
|
||||
* Told once, when a run has spent `AppData.HarnessRunTokensWarnShare` of
|
||||
* the prompt tokens it may send: every further turn resends everything, so
|
||||
* what it does from here is paid for out of the answer's budget.
|
||||
*/
|
||||
export const tokensLowNote = ({ left }: { left: number }) =>
|
||||
`You have about ${Math.max(0, Math.round(left)).toLocaleString("en-US")} prompt tokens left in this run, and every further turn resends this whole conversation, so each one costs more than the last. Land the work now: write what you have to a file and finish the rest of the answer from it, or hand the rest on with start_task. Another round of gathering is not worth what is left.`;
|
||||
|
||||
/**
|
||||
* Sent once, a quarter of the way into a run's token budget, when nothing
|
||||
* has been produced yet: no file written, no record changed, nothing handed
|
||||
* on. One task run spent 195 turns and 30M tokens reading its own notes and
|
||||
* writing a single row to the database, because nothing ever asked it when
|
||||
* the work would start; the budget was far too large to arrive as a
|
||||
* deadline (`commitEarlyNote` says it while there is still room).
|
||||
*
|
||||
* It says a run already delivered through a shell reports that instead: the
|
||||
* harness can't tell an `UPDATE` from a `SELECT` (`isWritingTool`).
|
||||
*/
|
||||
export const commitEarlyNote = ({ spent, of }: { spent: number; of: number }) => {
|
||||
const share = Math.round((spent / Math.max(1, of)) * 100);
|
||||
|
||||
return `About ${share}% of this run's prompt-token budget is gone and nothing has been produced yet: no file written, nothing changed, nothing handed on. Reading is not the work.
|
||||
|
||||
Land one piece of what was asked for now, all the way through, before you open anything else: the first row, the first file, the first item of the list. Then the next. A run that finishes with everything understood and nothing delivered has failed at the job, however good the notes are.
|
||||
|
||||
If part of it has already landed some other way (a command that wrote it, a message that sent it), say plainly what landed and carry on from there.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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,
|
||||
@@ -352,11 +497,28 @@ Tasks are the crew's to-do list. A task belongs to one bot, on its own list or i
|
||||
*/
|
||||
export const TaskReminderNote = `# Mentioning pending tasks
|
||||
|
||||
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or after you've answered and propose what's next, call list_tasks and look at what's open.
|
||||
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or when the work you're answering is done and you're about to offer what comes next, call list_tasks before you write your answer and put the reminder in the answer itself.
|
||||
|
||||
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} tasks: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
|
||||
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
|
||||
- Never invent a task: name only what list_tasks returned.`;
|
||||
- Never invent a task: name only what list_tasks returned.
|
||||
- Never send the answer and then call list_tasks: only your last message goes out, so the answer you wrote first would never reach the user. Look first, then answer once.`;
|
||||
|
||||
/**
|
||||
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
|
||||
* already has to another bot, instead of asking the coordinator to reassign
|
||||
* it (which no tool of its own can do, and a room once answered as if it
|
||||
* had been done).
|
||||
*/
|
||||
export const HandOverTaskNote = `# Passing a task on
|
||||
|
||||
A task on your own list can go to another bot with hand_over_task: it moves to their list, and their result comes back to this conversation. Do it only when the user asked for that task to go to that bot; the list is theirs.
|
||||
|
||||
- A hand-over moves the task as to do; it never starts the work. Pass start: true only when the user asked for the work to begin now.
|
||||
- When they asked for the move but not whether to start it, ask first: put one ask_user card with every task they named ("hand over and start", "hand over to wait", "leave it") and hand over only once they've answered. Once a task has left your list you can't start it any more.
|
||||
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
|
||||
- Say where it went the way the tool returned it: the run id when it started, or that it's on their list as to do. Never say a task was handed over, or that someone picked work up, without it.
|
||||
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
|
||||
|
||||
/**
|
||||
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
|
||||
@@ -476,9 +638,9 @@ Each turn, decide and act with one of your tools:
|
||||
askable.length
|
||||
? askable.map((bot) => `${bot.id}: ${bot.name || "A bot"}${bot.role ? ` (${bot.role})` : ""}`).join("; ")
|
||||
: "none"
|
||||
}. Their work comes back to you in the room, and you get another turn.
|
||||
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out.
|
||||
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why.
|
||||
}. Their work comes back to you in the room, and you get another turn. A message from one of them while it works is where it has got to, not its answer: it may still be running a task for many minutes, and only its answer, its failure, or its finished report speaks for it.
|
||||
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out. Answering closes the room and cancels anything still running in it, so while a bot is working the tool refuses unless you pass close_anyway: pass it only when the answer doesn't depend on what that bot is doing.
|
||||
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why, concretely: what the blocker is, who can clear it and how. Same close_anyway rule. Never turn a request into a claim that it was carried out: you can't create, edit, move or reassign a task, add a bot to a workspace, or start a run for anyone, and nothing you say makes one happen. A task is moved by the bot that has it (its hand_over_task) or by the user (Hand over in the UI); when that's what was asked for, say so and name that bot.
|
||||
|
||||
Ask one bot at a time and only ask again when the answer falls short. You have ${turns_left} turn${turns_left == 1 ? "" : "s"} left in this room; on the last one, answer with what you have or refuse. Your own words in the room are short notes on what you're doing.`;
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* A `bot_job_traces` row: what a run did in detail, behind the debug view.
|
||||
* One row per turn, tool call and loop event, kept beside the one-line
|
||||
* steps the conversation's working row reads (`bots_queue_updates`).
|
||||
*/
|
||||
export const BotTraceKinds = [
|
||||
{ title: "Turn", value: "turn" },
|
||||
{ title: "Tool call", value: "tool" },
|
||||
{ title: "Event", value: "event" },
|
||||
] as const;
|
||||
|
||||
export type BotTraceKind = (typeof BotTraceKinds)[number]["value"];
|
||||
|
||||
/**
|
||||
* The app setting (Settings > General) for how many days a run's trace is
|
||||
* kept, else `AppData.BotTraceKeepDays`.
|
||||
*/
|
||||
export const BotTraceKeepDaysSettingKey = "bot_trace_keep_days";
|
||||
@@ -27,6 +27,10 @@ export const BotPermissions = [
|
||||
value: "delegate_task",
|
||||
title: "Hand tasks to other bots",
|
||||
},
|
||||
{
|
||||
value: "hand_over_task",
|
||||
title: "Hand a task on its own list to another bot",
|
||||
},
|
||||
{
|
||||
value: "set_member_instructions",
|
||||
title: "Set other bots' workspace instructions",
|
||||
@@ -72,18 +76,27 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
|
||||
coordinator: BotPermissions.map((bp) => bp.value),
|
||||
workspace_admin: [
|
||||
"delegate_task",
|
||||
"hand_over_task",
|
||||
"set_member_instructions",
|
||||
"manage_workspace_tasks",
|
||||
"edit_workspace",
|
||||
],
|
||||
worker: [],
|
||||
/**
|
||||
* A worker can't hand out work: it passes on a task it already has
|
||||
* (`hand_over_task`), and asks the crew for anything else through the
|
||||
* coordinator (`ask_crew`).
|
||||
*/
|
||||
worker: ["hand_over_task"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Which bots a bot may act on (hand a task to, set instructions for), keyed
|
||||
* by the target's role. Same shape as `UserTypeAssignmentMatrix`: the
|
||||
* coordinator passes through. A workspace admin directs workers only, so
|
||||
* two admins never hand work back and forth.
|
||||
* two admins never hand work back and forth. A worker directs no one
|
||||
* either: `hand_over_task` takes a task it already has to a bot it could
|
||||
* ask, which its own tool decides (`chatroomAskableBots`), not this
|
||||
* matrix.
|
||||
*/
|
||||
export const BotTypeTargetMatrix: TypeAssignmentMatrixType<BotRole> = {
|
||||
coordinator: {},
|
||||
|
||||
@@ -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,293 @@
|
||||
/**
|
||||
* 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: "run-traces",
|
||||
title: "Run traces",
|
||||
description: "How long the debug view keeps what a run did in detail: its turns, reasoning, tool calls and results.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [{ key: "keep_days", title: "Keep run traces 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}` : ""}`;
|
||||
}
|
||||
@@ -14,7 +14,11 @@ type Params = {
|
||||
*/
|
||||
path: string;
|
||||
init?: RequestInit;
|
||||
timeout_ms: number;
|
||||
/**
|
||||
* Give up after this long; `null` or 0 waits for the caller's own
|
||||
* signal alone.
|
||||
*/
|
||||
timeout_ms: number | null;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
@@ -24,12 +28,16 @@ type Params = {
|
||||
*/
|
||||
export default function computerFetch({ computer, path, init = {}, timeout_ms, signal }: Params) {
|
||||
const headers = new Headers(init.headers);
|
||||
const signals = [
|
||||
...(signal ? [signal] : []),
|
||||
...(timeout_ms != null && timeout_ms > 0 ? [AbortSignal.timeout(timeout_ms)] : []),
|
||||
];
|
||||
|
||||
headers.set("authorization", `Bearer ${computer.token}`);
|
||||
|
||||
return fetch(`${computer.base_url}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
signal: AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(timeout_ms)]),
|
||||
...(signals.length ? { signal: AbortSignal.any(signals) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import computerJson from "./computer-json";
|
||||
|
||||
/**
|
||||
* The agent answers `/api/exec` with a space every 15 seconds while the
|
||||
* command runs (a client that drops a silent connection would otherwise
|
||||
* lose it), then the JSON. Leading whitespace is still a JSON document,
|
||||
* and this pins that the app reads such an answer.
|
||||
*/
|
||||
describe("computerJson", () => {
|
||||
test("reads an answer kept alive with heartbeat spaces", async () => {
|
||||
const encoder = new TextEncoder();
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode(" "));
|
||||
controller.enqueue(encoder.encode(" "));
|
||||
controller.enqueue(encoder.encode(JSON.stringify({ output: "done\n", exit_code: 0, timed_out: false })));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ headers: { "content-type": "application/json" } },
|
||||
),
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await computerJson<{ output: string; exit_code: number }>({
|
||||
computer: { base_url: `http://127.0.0.1:${server.port}`, token: "computer-token" },
|
||||
path: "/api/exec",
|
||||
timeout_ms: 5_000,
|
||||
});
|
||||
|
||||
expect(result.output).toBe("done\n");
|
||||
expect(result.exit_code).toBe(0);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("sends the computer's token and its body", async () => {
|
||||
let received: { token: string | null; body: unknown } = { token: null, body: null };
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (req) => {
|
||||
received = { token: req.headers.get("authorization"), body: await req.json() };
|
||||
return Response.json({ ok: true });
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await computerJson<{ ok: boolean }>({
|
||||
computer: { base_url: `http://127.0.0.1:${server.port}`, token: "computer-token" },
|
||||
path: "/api/exec",
|
||||
body: { command: "ls" },
|
||||
timeout_ms: 5_000,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(received.token).toBe("Bearer computer-token");
|
||||
expect(received.body).toEqual({ command: "ls" });
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("says what the computer refused", async () => {
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => Response.json({ error: "Give the command." }, { status: 400 }),
|
||||
});
|
||||
|
||||
try {
|
||||
const error = await computerJson({
|
||||
computer: { base_url: `http://127.0.0.1:${server.port}`, token: "computer-token" },
|
||||
path: "/api/exec",
|
||||
timeout_ms: 5_000,
|
||||
}).catch((caught: Error) => caught);
|
||||
|
||||
expect(String(error)).toContain("Give the command.");
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -7,9 +7,10 @@ type Params = {
|
||||
command: string;
|
||||
/**
|
||||
* The command is stopped on the computer after this (whole seconds,
|
||||
* rounded up), with its whole process group.
|
||||
* rounded up), with its whole process group; `null` leaves it no time
|
||||
* limit, so it runs until it ends or the call is aborted.
|
||||
*/
|
||||
timeout_ms: number;
|
||||
timeout_ms: number | null;
|
||||
/**
|
||||
* A worker's own account to run it as (`ComputerRunDirs.run_as`);
|
||||
* without it, the computer's user (gem, with sudo).
|
||||
@@ -25,6 +26,17 @@ export type ComputerCommandResult = {
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The client's own ceiling for a call with no deadline: `AbortSignal.timeout`
|
||||
* needs a number, and twenty days is past any command a run would wait on
|
||||
* while staying under its maximum. The command's own limit, the run's Stop
|
||||
* and the computer's connection are what really end it; the agent keeps the
|
||||
* answer alive with a heartbeat while it runs, so a client that drops a
|
||||
* silent connection (Bun's fetch does, after about six minutes) never cuts
|
||||
* a long command.
|
||||
*/
|
||||
const NoDeadlineFetchMs = 20 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Runs one bash command on a computer as its user, or as a worker's own
|
||||
* account (`run_as`) (the agent's `/api/exec`): a fresh `bash -c` from its home, no input, stdout and
|
||||
@@ -36,11 +48,15 @@ export default async function runComputerCommand({ computer, command, timeout_ms
|
||||
const result = await computerJson<Partial<ComputerCommandResult>>({
|
||||
computer,
|
||||
path: "/api/exec",
|
||||
body: { command, timeout_seconds: Math.max(1, Math.ceil(timeout_ms / 1000)), ...(run_as ? { run_as } : {}) },
|
||||
body: {
|
||||
command,
|
||||
...(timeout_ms == null ? {} : { timeout_seconds: Math.max(1, Math.ceil(timeout_ms / 1000)) }),
|
||||
...(run_as ? { run_as } : {}),
|
||||
},
|
||||
/**
|
||||
* Room for the agent to stop it and answer.
|
||||
*/
|
||||
timeout_ms: timeout_ms + 15_000,
|
||||
timeout_ms: timeout_ms == null ? NoDeadlineFetchMs : timeout_ms + 15_000,
|
||||
signal,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotTraceKeepDaysSettingKey } from "@/src/dict/bot-trace-dict";
|
||||
import type { BotTraceRetentionOverview } from "@/src/types";
|
||||
import readStepLimit from "@/src/utils/read-step-limit";
|
||||
import grabAppSetting from "./grab-app-setting";
|
||||
|
||||
/**
|
||||
* How many days a run's detailed trace is kept (the debug view): the
|
||||
* install's own number (`bot_trace_keep_days`, Settings > General), else
|
||||
* `AppData.BotTraceKeepDays`.
|
||||
*/
|
||||
export async function grabBotTraceKeepDays() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: BotTraceKeepDaysSettingKey }),
|
||||
fallback: AppData.BotTraceKeepDays,
|
||||
max: AppData.BotTraceKeepDaysMax,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The number with its default and ceiling, for the settings page.
|
||||
*/
|
||||
export default async function grabBotTraceRetentionOverview() {
|
||||
const overview: BotTraceRetentionOverview = {
|
||||
keep_days: await grabBotTraceKeepDays(),
|
||||
default_days: AppData.BotTraceKeepDays,
|
||||
max: AppData.BotTraceKeepDaysMax,
|
||||
};
|
||||
|
||||
return overview;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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 grabBotTraceRetentionOverview from "./grab-bot-trace-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, run_traces, logs, chatrooms, sessions, messages, storage, computer_workspace, appendix, install_name] =
|
||||
await Promise.all([
|
||||
grabRunLimitsOverview().catch(() => null),
|
||||
grabSkillLimitsOverview().catch(() => null),
|
||||
grabHookCallRetentionOverview().catch(() => null),
|
||||
grabBotTraceRetentionOverview().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 },
|
||||
"run-traces": { keep_days: run_traces?.keep_days ?? null },
|
||||
chatrooms: {
|
||||
keep_days: chatrooms?.keep_days ?? null,
|
||||
max_per_place: chatrooms?.max_per_place ?? null,
|
||||
},
|
||||
"activity-log": { keep_days: logs?.keep_days ?? null },
|
||||
storage: { quota_mb: storage?.quota_mb ?? null },
|
||||
"computer-workspaces": { quota_mb: computer_workspace?.quota_mb ?? null },
|
||||
"prompt-appendix": { appendix: appendix ? appendix.length : null },
|
||||
"install-name": { install_name: install_name || null },
|
||||
};
|
||||
|
||||
return GeneralSettingsSections.filter((section) => section.fields.length > 0).map((section) => {
|
||||
const values = raw[section.key] || {};
|
||||
|
||||
return {
|
||||
key: section.key,
|
||||
title: section.title,
|
||||
href: generalSettingsHref({ section: section.key }),
|
||||
editor: GeneralSettingsAudiences[section.editable_by],
|
||||
editable_by: section.editable_by,
|
||||
values: section.fields.map((field) => ({
|
||||
key: field.key,
|
||||
title: field.title,
|
||||
label: settingValueLabel({
|
||||
kind: field.kind as GeneralSettingsFieldKind,
|
||||
value: values[field.key] ?? null,
|
||||
}),
|
||||
})),
|
||||
} satisfies GeneralSettingsSectionValues;
|
||||
});
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
UnattendedMaxToolStepsSettingKey,
|
||||
} from "@/src/dict/harness-dict";
|
||||
import type { RunLimitsOverview } from "@/src/types";
|
||||
import readStepLimit from "@/src/utils/read-step-limit";
|
||||
import readRunLimit from "@/src/utils/read-run-limit";
|
||||
import grabAppSetting from "./grab-app-setting";
|
||||
|
||||
export type { RunLimitsOverview };
|
||||
@@ -16,11 +16,11 @@ export type { RunLimitsOverview };
|
||||
/**
|
||||
* Model turns a task run may take: the install's own limit
|
||||
* (`harness_max_tool_steps`, Settings > General), else
|
||||
* `AppData.HarnessMaxToolSteps`. `runTextLoop`'s default is the code's one,
|
||||
* so a task run passes this in.
|
||||
* `AppData.HarnessMaxToolSteps` (unlimited). `runTextLoop`'s default is the
|
||||
* code's one, so a task run passes this in.
|
||||
*/
|
||||
export async function grabHarnessMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: HarnessMaxToolStepsSettingKey }),
|
||||
fallback: AppData.HarnessMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
@@ -30,10 +30,10 @@ export async function grabHarnessMaxToolSteps() {
|
||||
/**
|
||||
* Model turns a chat reply may take: the install's own limit
|
||||
* (`bot_reply_max_tool_steps`, Settings > General), else
|
||||
* `AppData.BotReplyMaxToolSteps`.
|
||||
* `AppData.BotReplyMaxToolSteps` (unlimited).
|
||||
*/
|
||||
export async function grabReplyMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: BotReplyMaxToolStepsSettingKey }),
|
||||
fallback: AppData.BotReplyMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
@@ -43,10 +43,10 @@ export async function grabReplyMaxToolSteps() {
|
||||
/**
|
||||
* Model turns a routine run or a hook call may take, which nobody
|
||||
* watches: the install's own limit (`unattended_max_tool_steps`), else
|
||||
* `AppData.UnattendedMaxToolSteps`.
|
||||
* `AppData.UnattendedMaxToolSteps` (unlimited).
|
||||
*/
|
||||
export async function grabUnattendedMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: UnattendedMaxToolStepsSettingKey }),
|
||||
fallback: AppData.UnattendedMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
@@ -56,9 +56,10 @@ export async function grabUnattendedMaxToolSteps() {
|
||||
/**
|
||||
* Prompt tokens one run may spend before it must wrap up: the install's
|
||||
* own budget (`run_max_prompt_tokens`), else `AppData.RunMaxPromptTokens`.
|
||||
* Unlimited when the install chose none.
|
||||
*/
|
||||
export async function grabRunMaxPromptTokens() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: RunMaxPromptTokensSettingKey }),
|
||||
fallback: AppData.RunMaxPromptTokens,
|
||||
min: AppData.RunMaxPromptTokensMin,
|
||||
@@ -69,10 +70,11 @@ export async function grabRunMaxPromptTokens() {
|
||||
/**
|
||||
* The working context a run keeps per turn, in estimated tokens: the
|
||||
* install's own (`harness_context_budget_tokens`), else
|
||||
* `AppData.HarnessContextBudgetTokens`.
|
||||
* `AppData.HarnessContextBudgetTokens`. Unlimited keeps the model's whole
|
||||
* window.
|
||||
*/
|
||||
export async function grabContextBudgetTokens() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: HarnessContextBudgetSettingKey }),
|
||||
fallback: AppData.HarnessContextBudgetTokens,
|
||||
min: AppData.HarnessContextBudgetMinTokens,
|
||||
@@ -83,9 +85,10 @@ export async function grabContextBudgetTokens() {
|
||||
/**
|
||||
* How long a model that failed is passed over, in seconds: the install's
|
||||
* own (`harness_model_rest_seconds`), else `AppData.HarnessModelRestMs`.
|
||||
* Unlimited rests it until the setting changes (or the app restarts).
|
||||
*/
|
||||
export async function grabModelRestSeconds() {
|
||||
return readStepLimit({
|
||||
return readRunLimit({
|
||||
saved: await grabAppSetting({ key: HarnessModelRestSettingKey }),
|
||||
fallback: AppData.HarnessModelRestMs / 1000,
|
||||
min: AppData.HarnessModelRestMinSeconds,
|
||||
@@ -94,7 +97,8 @@ export async function grabModelRestSeconds() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every run limit with its default, for the settings page.
|
||||
* Every run limit with its default, for the settings page. A limit is a
|
||||
* number or `"unlimited"`.
|
||||
*/
|
||||
export default async function grabRunLimitsOverview() {
|
||||
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds] =
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import type { ConversationHistory } from "@/src/types";
|
||||
import grabActiveBotTask from "../bots/grab-active-bot-task";
|
||||
import grabBotMessages from "../bots/grab-bot-messages";
|
||||
import grabSessionReplyStep from "../bots-queue/grab-session-reply-step";
|
||||
import ensureBotSession from "./ensure-bot-session";
|
||||
import grabCarriedToSessionId from "./grab-carried-to-session-id";
|
||||
import reopenBotSession from "./reopen-bot-session";
|
||||
@@ -31,8 +32,9 @@ type Params = {
|
||||
* one is reopened, unless it was carried over, which only shows, with
|
||||
* where the conversation went on), its latest
|
||||
* `AppData.ConversationFirstMessages` messages (the thread loads older
|
||||
* ones as it scrolls) and the bot's active task in it. Everything else on
|
||||
* the page comes with it from the server (`grabConversationProps`).
|
||||
* ones as it scrolls), the bot's active task in it and the step its
|
||||
* running reply is on. Everything else on the page comes with it from the
|
||||
* server (`grabConversationProps`).
|
||||
* Null when the user can't chat with the bot there.
|
||||
*/
|
||||
export default async function grabConversationHistory({
|
||||
@@ -87,13 +89,14 @@ export default async function grabConversationHistory({
|
||||
session.unread = 0;
|
||||
}
|
||||
|
||||
const [messages, task] = await Promise.all([
|
||||
const [messages, task, step] = await Promise.all([
|
||||
grabBotMessages({
|
||||
session_id: session.id!,
|
||||
user_id,
|
||||
limit: AppData.ConversationFirstMessages + 1,
|
||||
}),
|
||||
grabActiveBotTask({ bot_id: open_bot_id, session_id: session.id }),
|
||||
grabSessionReplyStep({ session_id: session.id! }),
|
||||
]);
|
||||
|
||||
const has_more = messages.length > AppData.ConversationFirstMessages;
|
||||
@@ -103,6 +106,7 @@ export default async function grabConversationHistory({
|
||||
messages: has_more ? messages.slice(1) : messages,
|
||||
has_more,
|
||||
task,
|
||||
step,
|
||||
moved_to_session_id: carried_to,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
|
||||
import isPassThroughUser from "@/src/utils/rbac/is-pass-through-user";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
user_id: number;
|
||||
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A bot message whose run's trace the caller may read: one in a session
|
||||
* that's theirs, or any of them for a super admin. Null when it isn't.
|
||||
*/
|
||||
export default async function grabTraceMessage({
|
||||
message_id,
|
||||
user_id,
|
||||
user_types,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES | null> {
|
||||
const message = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_MESSAGES & { session_user_id: number | null }>({
|
||||
sql: `SELECT m.*, s.user_id AS session_user_id
|
||||
FROM bot_messages m
|
||||
JOIN bot_sessions s ON s.id = m.session_id
|
||||
WHERE m.id = ? AND m.author = 'bot'`,
|
||||
values: [message_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!message?.id) return null;
|
||||
|
||||
if (Number(message.session_user_id) == Number(user_id)) return message;
|
||||
|
||||
if (isPassThroughUser({ user_types })) return message;
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS, BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import isPassThroughUser from "@/src/utils/rbac/is-pass-through-user";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
user_id: number | string;
|
||||
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A session whose run trace may be read: the session user's own, or any
|
||||
* session for a super admin (who reaches every bot and workspace).
|
||||
*/
|
||||
export default async function grabTraceSession({
|
||||
session_id,
|
||||
user_id,
|
||||
user_types,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS | null> {
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT s.* FROM bot_sessions s WHERE s.id = ? LIMIT 1`,
|
||||
values: [session_id],
|
||||
});
|
||||
|
||||
const session = res.payload?.[0] || null;
|
||||
|
||||
if (!session?.id) return null;
|
||||
|
||||
if (Number(session.user_id) == Number(user_id)) return session;
|
||||
|
||||
return isPassThroughUser({ user_types }) ? session : null;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
job_id: number;
|
||||
message_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ties a run's trace to the message it ended in, so its Details modal can
|
||||
* show what the run did under its debug logs tab. Best effort: a run that
|
||||
* kept no trace, or one whose entries the prune already took, has nothing
|
||||
* to update and isn't an error.
|
||||
*/
|
||||
export default async function attachJobTracesToMessage({ job_id, message_id }: Params) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_job_traces SET message_id = ? WHERE bots_queue_id = ? AND message_id IS NULL`,
|
||||
values: [message_id, job_id],
|
||||
}).catch(() => {});
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import grabJobUserId from "./grab-job-user-id";
|
||||
import grabRunningBotJobFace from "./grab-running-bot-job-face";
|
||||
import withMessageUsage from "../usage/with-message-usage";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
|
||||
import onChatroomJobEnded from "../chatrooms/on-chatroom-job-ended";
|
||||
@@ -48,6 +49,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 +64,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 +78,7 @@ export default async function completeBotJob({
|
||||
attachments,
|
||||
tool_log,
|
||||
task_ids = [],
|
||||
exhausted,
|
||||
}: Params) {
|
||||
const job = await grabLockedBotJob({ job_id, worker });
|
||||
|
||||
@@ -121,6 +130,12 @@ export default async function completeBotJob({
|
||||
if (job.id && inserted?.id) {
|
||||
await attachJobCallsToMessage({ job_id: job.id, message_id: inserted.id });
|
||||
|
||||
/**
|
||||
* What the run did goes with the message it ended in, for its
|
||||
* Details modal's debug logs tab.
|
||||
*/
|
||||
await attachJobTracesToMessage({ job_id: job.id, message_id: inserted.id });
|
||||
|
||||
/**
|
||||
* Graphics the run made belong to the message it posted.
|
||||
*/
|
||||
@@ -165,7 +180,7 @@ export default async function completeBotJob({
|
||||
face: job.kind == "reply" ? "idle" : "done",
|
||||
});
|
||||
|
||||
await noteTrackerTask({ job });
|
||||
await noteTrackerTask({ job, exhausted });
|
||||
|
||||
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import traceJobsFromRows from "./trace-jobs-from-rows";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* A message the caller already checked the user reaches.
|
||||
*/
|
||||
message_id: number;
|
||||
};
|
||||
|
||||
type JobRow = {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The traces behind one bot message: what its run did, turn by turn, for
|
||||
* the debug logs tab of its Details modal. Usually one job (a reply or the
|
||||
* task run that reported back); a retried job that posted the same message
|
||||
* would list both.
|
||||
*/
|
||||
export default async function grabMessageTraces({ message_id }: Params): Promise<BotTraceJob[]> {
|
||||
const res = await BunSQLite.sql<JobRow>({
|
||||
sql: `SELECT q.id, q.kind, q.title, q.status, q.created_at
|
||||
FROM bot_job_traces t
|
||||
JOIN bots_queue q ON q.id = t.bots_queue_id
|
||||
WHERE t.message_id = ?
|
||||
GROUP BY q.id
|
||||
ORDER BY q.created_at DESC`,
|
||||
values: [message_id],
|
||||
});
|
||||
|
||||
return traceJobsFromRows({ jobs: res.payload || [] });
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import openSessionReplyStepSql from "./open-session-reply-step-sql";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The step the reply running in a session is on, as `server:bot-job-update`
|
||||
* carries it, or null when no reply runs there. Read with a conversation's
|
||||
* history and by its catch-up, so a reload (or a push missed while the page
|
||||
* stayed open) shows what the reply is doing instead of only its label.
|
||||
*/
|
||||
export default async function grabSessionReplyStep({
|
||||
session_id,
|
||||
}: Params): Promise<BotJobUpdateData | null> {
|
||||
const { sql, values } = openSessionReplyStepSql({ session_id });
|
||||
const res = await BunSQLite.sql<BotJobUpdateData>({ sql, values });
|
||||
const step = (res.payload || [])[0];
|
||||
|
||||
return step ? { ...step, id: Number(step.id), task_id: null } : null;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import traceJobsFromRows from "./trace-jobs-from-rows";
|
||||
|
||||
type Params = {
|
||||
session_id: number;
|
||||
};
|
||||
|
||||
type JobRow = {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A session's traced jobs, newest first, each with everything it did in
|
||||
* detail: what the conversation's debug view streams while a run works and
|
||||
* what it lists when it's done. Read-only, and never more than
|
||||
* `AppData.BotTraceJobsPerSession` jobs.
|
||||
*
|
||||
* A job that's still open is listed even before its first step is kept, so
|
||||
* the live strip can say it's waiting on the bot rather than nothing being
|
||||
* there at all.
|
||||
*/
|
||||
export default async function grabSessionTraces({ session_id }: Params): Promise<BotTraceJob[]> {
|
||||
const res = await BunSQLite.sql<JobRow>({
|
||||
sql: `SELECT q.id, q.kind, q.title, q.status, q.created_at
|
||||
FROM bots_queue q
|
||||
WHERE q.id IN (
|
||||
SELECT bots_queue_id FROM bot_job_traces WHERE session_id = ?
|
||||
UNION
|
||||
SELECT id FROM bots_queue WHERE session_id = ? AND status IN ('pending', 'processing')
|
||||
)
|
||||
ORDER BY q.created_at DESC
|
||||
LIMIT ?`,
|
||||
values: [session_id, session_id, AppData.BotTraceJobsPerSession],
|
||||
});
|
||||
|
||||
return traceJobsFromRows({ jobs: res.payload || [] });
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_JOB_TRACES, BunSQLiteTables } from "@/db/types/db";
|
||||
import prepareTrace from "@/src/harness/trace/prepare-trace";
|
||||
import redactTrace from "@/src/harness/trace/redact-trace";
|
||||
import type { HarnessTrace } from "@/src/harness/trace/types";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
|
||||
type Params = {
|
||||
job_id: number;
|
||||
bot_id: number;
|
||||
session_id: number | null;
|
||||
trace: HarnessTrace;
|
||||
/**
|
||||
* Every secret the run reaches (`grabReachableEnvs`): a bot's tool
|
||||
* arguments and results carry whatever it handled, and a trace is read
|
||||
* by the user (and super admins) long after.
|
||||
*/
|
||||
secrets?: { key: string; value: string }[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Records one trace entry of a running job (`bot_job_traces`) and returns
|
||||
* the row. Text is redacted and cut before it is written, never after.
|
||||
*/
|
||||
export default async function insertBotJobTrace({
|
||||
job_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
trace,
|
||||
secrets = [],
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_JOB_TRACES> {
|
||||
const prepared = prepareTrace({
|
||||
trace: redactTrace({
|
||||
trace,
|
||||
redact: (text) => redactSecrets({ text, secrets }),
|
||||
}),
|
||||
});
|
||||
|
||||
const row: BUN_SQLITE_COBBLE_BOT_JOB_TRACES = {
|
||||
bots_queue_id: job_id,
|
||||
bot_id,
|
||||
session_id: session_id ?? undefined,
|
||||
kind: prepared.kind,
|
||||
name: prepared.name ?? undefined,
|
||||
text: prepared.text ?? undefined,
|
||||
reasoning: prepared.reasoning ?? undefined,
|
||||
arguments: prepared.arguments ?? undefined,
|
||||
result: prepared.result ?? undefined,
|
||||
metadata: prepared.metadata ?? undefined,
|
||||
};
|
||||
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_JOB_TRACES, (typeof BunSQLiteTables)[number]>({
|
||||
table: "bot_job_traces",
|
||||
data: [row],
|
||||
});
|
||||
|
||||
const id = res.postInsertReturn?.insertId;
|
||||
|
||||
if (!res.success || !id) {
|
||||
throw new Error(`Failed to save the job trace: ${res.msg}`);
|
||||
}
|
||||
|
||||
return { ...row, id, created_at: Date.now() };
|
||||
}
|
||||
@@ -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}`,
|
||||
|
||||
@@ -14,6 +14,7 @@ import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
@@ -71,6 +72,7 @@ export default async function notifyBotJobFailed({
|
||||
*/
|
||||
if (message?.id) {
|
||||
await attachJobCallsToMessage({ job_id: job.id, message_id: Number(message.id) });
|
||||
await attachJobTracesToMessage({ job_id: job.id, message_id: Number(message.id) });
|
||||
}
|
||||
|
||||
const user_id = await grabJobUserId({ job });
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import openSessionReplyStepSql from "./open-session-reply-step-sql";
|
||||
|
||||
/**
|
||||
* A conversation that reloads mid-reply reads the step the run is on from
|
||||
* the server. It must be the open reply job's newest tool step, never a
|
||||
* task's (a task brings its own), never a finished job's, never a closing
|
||||
* note (its text is the answer) and never another session's.
|
||||
*/
|
||||
function setup() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(
|
||||
`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, kind TEXT, status TEXT, session_id INTEGER, task_id INTEGER)`,
|
||||
);
|
||||
db.run(
|
||||
`CREATE TABLE bots_queue_updates (id INTEGER PRIMARY KEY, bots_queue_id INTEGER, bot_id INTEGER, kind TEXT, text TEXT, metadata TEXT, created_at INTEGER)`,
|
||||
);
|
||||
|
||||
db.run(`INSERT INTO bots_queue (id, kind, status, session_id, task_id) VALUES
|
||||
(10, 'reply', 'processing', 1, NULL),
|
||||
(11, 'task', 'processing', 1, 50),
|
||||
(12, 'reply', 'completed', 1, NULL),
|
||||
(13, 'reply', 'processing', 2, NULL)`);
|
||||
|
||||
db.run(`INSERT INTO bots_queue_updates (id, bots_queue_id, bot_id, kind, text, metadata, created_at) VALUES
|
||||
(100, 10, 7, 'tool', 'Reading the invoice', NULL, 1000),
|
||||
(101, 10, 7, 'note', 'Here is the invoice', NULL, 1001),
|
||||
(102, 11, 7, 'tool', 'Using sandbox_execute_bash', NULL, 1002),
|
||||
(103, 12, 7, 'tool', 'Read the finished job', NULL, 1003),
|
||||
(104, 13, 7, 'tool', 'Reading another session', NULL, 1004)`);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
describe("openSessionReplyStepSql", () => {
|
||||
test("reads the open reply's newest tool step, with its job's task and session", () => {
|
||||
const db = setup();
|
||||
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
|
||||
const step = db.query(sql).get(...values) as {
|
||||
id: number;
|
||||
bots_queue_id: number;
|
||||
bot_id: number;
|
||||
kind: string;
|
||||
text: string;
|
||||
task_id: number | null;
|
||||
session_id: number;
|
||||
} | null;
|
||||
|
||||
expect(step?.id).toBe(100);
|
||||
expect(step?.text).toBe("Reading the invoice");
|
||||
expect(step?.bot_id).toBe(7);
|
||||
expect(step?.task_id).toBeNull();
|
||||
expect(step?.session_id).toBe(1);
|
||||
});
|
||||
|
||||
test("a session with no reply running has no step", () => {
|
||||
const db = setup();
|
||||
db.run(`UPDATE bots_queue SET status = 'completed' WHERE id = 10`);
|
||||
|
||||
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
|
||||
|
||||
expect(db.query(sql).get(...values)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The newest step of the reply job a session still runs, with the job's
|
||||
* task and session beside it, so a conversation that reloaded (or missed
|
||||
* the step's push) shows what the reply is doing instead of waiting for its
|
||||
* next step. A reply's steps are never stored with the task they belong to
|
||||
* the way a task's are (`grabBotJobUpdates`), so they are read here.
|
||||
*
|
||||
* Only an open job's, only a reply's, and only a tool step: a closing note's
|
||||
* text is the answer, about to land as the message.
|
||||
*/
|
||||
export default function openSessionReplyStepSql({ session_id }: Params) {
|
||||
return {
|
||||
sql: `SELECT u.*, q.task_id AS task_id, q.session_id AS session_id
|
||||
FROM bots_queue_updates u
|
||||
JOIN bots_queue q ON q.id = u.bots_queue_id
|
||||
WHERE q.session_id = ? AND q.kind = 'reply' AND q.status IN ('pending', 'processing')
|
||||
AND u.kind = 'tool' AND u.text IS NOT NULL
|
||||
ORDER BY u.id DESC
|
||||
LIMIT 1`,
|
||||
values: [Number(session_id)],
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
|
||||
import closeChatroom from "../chatrooms/close-chatroom";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -150,7 +151,15 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
|
||||
text: stoppedJobReport({ job }),
|
||||
}).catch(() => null);
|
||||
|
||||
if (message?.id) messages.push(message);
|
||||
if (message?.id) {
|
||||
messages.push(message);
|
||||
|
||||
/**
|
||||
* The run's debug logs go with the answer that took its place,
|
||||
* the way a finished run's go with its own.
|
||||
*/
|
||||
await attachJobTracesToMessage({ job_id: Number(job.id), message_id: Number(message.id) });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotTraceJob, BotTraceRow } from "@/src/types";
|
||||
|
||||
type JobRow = {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The jobs whose trace rows are wanted, in the order they're shown.
|
||||
*/
|
||||
jobs: JobRow[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Each job with every entry it kept, oldest entry first (the order the run
|
||||
* did them in). One read for all of them, so a session's handful of jobs
|
||||
* costs two queries rather than one per job.
|
||||
*/
|
||||
export default async function traceJobsFromRows({ jobs }: Params): Promise<BotTraceJob[]> {
|
||||
if (!jobs.length) return [];
|
||||
|
||||
const traces =
|
||||
(
|
||||
await BunSQLite.sql<BotTraceRow>({
|
||||
sql: `SELECT id, created_at, bots_queue_id AS job_id, bot_id, kind, name, text, reasoning, arguments, result, metadata
|
||||
FROM bot_job_traces
|
||||
WHERE bots_queue_id IN (${jobs.map(() => "?").join(",")})
|
||||
ORDER BY id ASC`,
|
||||
values: jobs.map((job) => job.id),
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
return jobs.map((job) => ({
|
||||
...job,
|
||||
traces: traces.filter((row) => row.job_id == job.id),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import trackerTaskEnding from "./tracker-task-ending";
|
||||
|
||||
describe("trackerTaskEnding", () => {
|
||||
test("says a finished run left the task where it was", () => {
|
||||
expect(trackerTaskEnding({ name: "Writer", status: "doing" })).toEqual({
|
||||
blocked_reason: null,
|
||||
note: "Writer's run finished; the task is still doing.",
|
||||
});
|
||||
});
|
||||
|
||||
test("blocks the task with why the run failed", () => {
|
||||
expect(trackerTaskEnding({ name: "Writer", status: "doing", failure: "Model refused." })).toEqual({
|
||||
blocked_reason: "Writer couldn't finish it. Model refused.",
|
||||
note: "Writer couldn't finish it. Model refused.",
|
||||
});
|
||||
});
|
||||
|
||||
test("blocks the task when the run used every step it had", () => {
|
||||
const ending = trackerTaskEnding({ name: "Writer", status: "doing", exhausted: true });
|
||||
|
||||
expect(ending.blocked_reason || "").toContain("used every step its run allowed and stopped before finishing it");
|
||||
expect(ending.note).toBe(String(ending.blocked_reason));
|
||||
});
|
||||
|
||||
test("a failure's reason wins over a spent budget", () => {
|
||||
expect(
|
||||
trackerTaskEnding({ name: "Writer", status: "doing", failure: "No room.", exhausted: true })
|
||||
.blocked_reason,
|
||||
).toBe("Writer couldn't finish it. No room.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The bot's name, as the task's own readers see it.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The task's status now.
|
||||
*/
|
||||
status?: string | null;
|
||||
/**
|
||||
* Why the run failed, when it did.
|
||||
*/
|
||||
failure?: string | undefined;
|
||||
/**
|
||||
* The run used every step it was allowed. A handed-over task's run that
|
||||
* spends its whole budget and still leaves the task open did not do the
|
||||
* work: it ended `completed` with a report saying so, which the tracker
|
||||
* never heard of, so the task read as under way forever (a retrofit run
|
||||
* spent 242 steps re-reading the branch it had to change, converted
|
||||
* nothing, and its task stayed `doing`).
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
};
|
||||
|
||||
export type TrackerTaskEnding = {
|
||||
/**
|
||||
* Why the task is blocked, or null to leave its status alone.
|
||||
*/
|
||||
blocked_reason: string | null;
|
||||
/**
|
||||
* The note left on the task, which says the same thing.
|
||||
*/
|
||||
note: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What finishing (or failing) a job says on the task it was handed over
|
||||
* with, while that task is still open. The bot moves the task along itself
|
||||
* as it works; this only keeps the task honest when it didn't, and a run
|
||||
* that says it did nothing blocks the task rather than leaving it looking
|
||||
* like work in hand.
|
||||
*/
|
||||
export default function trackerTaskEnding({ name, status, failure, exhausted }: Params): TrackerTaskEnding {
|
||||
if (failure !== undefined) {
|
||||
const note = `${name} couldn't finish it. ${failure}`.trim();
|
||||
|
||||
return { blocked_reason: note, note };
|
||||
}
|
||||
|
||||
if (exhausted) {
|
||||
const note = `${name} used every step its run allowed and stopped before finishing it. Its report says where it got to, so the rest needs a run of its own.`;
|
||||
|
||||
return { blocked_reason: note, note };
|
||||
}
|
||||
|
||||
return { blocked_reason: null, note: `${name}'s run finished; the task is still ${status || "open"}.` };
|
||||
}
|
||||
@@ -1,17 +1,24 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
import type { ChatroomBot, ChatroomJob, ChatroomSummary } from "@/src/types";
|
||||
import grabChatroomUsage from "../usage/grab-chatroom-usage";
|
||||
|
||||
type Params = {
|
||||
chatrooms: BUN_SQLITE_COBBLE_CHATROOMS[];
|
||||
/**
|
||||
* Sum what each room's bots spent there, for the room's own header. A
|
||||
* list doesn't need it, and it costs a query per call.
|
||||
*/
|
||||
with_usage?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Rooms with the bots in them, asking bot first, then the coordinator,
|
||||
* then the bots it asked in the order they joined, the jobs still open in
|
||||
* the room, and the workspace it's in by name.
|
||||
* the room, the workspace it's in by name, and (when asked for) what its
|
||||
* bots spent working there.
|
||||
*/
|
||||
export default async function chatroomSummaries({ chatrooms }: Params): Promise<ChatroomSummary[]> {
|
||||
export default async function chatroomSummaries({ chatrooms, with_usage }: Params): Promise<ChatroomSummary[]> {
|
||||
if (!chatrooms.length) return [];
|
||||
|
||||
const ids = chatrooms.map((room) => Number(room.id));
|
||||
@@ -40,6 +47,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
|
||||
).payload || [];
|
||||
|
||||
const workspace_ids = [...new Set(chatrooms.map((room) => Number(room.workspace_id)).filter(Boolean))];
|
||||
const usage = with_usage ? await grabChatroomUsage({ chatroom_ids: ids }) : null;
|
||||
const workspace_names = new Map(
|
||||
(workspace_ids.length
|
||||
? (
|
||||
@@ -72,6 +80,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
|
||||
session_id: Number(job.session_id),
|
||||
})),
|
||||
workspace_name: room.workspace_id ? workspace_names.get(Number(room.workspace_id)) || null : null,
|
||||
...(usage ? { usage: usage.get(Number(room.id)) } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
message_id: number | string;
|
||||
/**
|
||||
* Only a message posted in one of the user's own rooms.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
type ChatroomMessageRef = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
chatroom_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A message posted in a chatroom of the user's, with the room it's in, or
|
||||
* null. The access check for what the message's details may show.
|
||||
*/
|
||||
export default async function grabChatroomMessage({
|
||||
message_id,
|
||||
user_id,
|
||||
}: Params): Promise<ChatroomMessageRef | null> {
|
||||
const row = (
|
||||
await BunSQLite.sql<ChatroomMessageRef>({
|
||||
sql: `SELECT m.id, m.created_at, s.chatroom_id FROM bot_messages m
|
||||
JOIN bot_sessions s ON s.id = m.session_id
|
||||
JOIN chatrooms c ON c.id = s.chatroom_id
|
||||
WHERE m.id = ? AND c.user_id = ? AND s.chatroom_id IS NOT NULL
|
||||
LIMIT 1`,
|
||||
values: [message_id, user_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row?.id) return null;
|
||||
|
||||
return {
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || 0,
|
||||
chatroom_id: Number(row.chatroom_id),
|
||||
};
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import grabMessageUsage from "../usage/grab-message-usage";
|
||||
|
||||
type Params = {
|
||||
chatroom_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every message in a chatroom, from every bot in it, oldest first. Rooms
|
||||
* are short (the coordinator's turns are capped), so they're read whole.
|
||||
* Every message in a chatroom, from every bot in it, oldest first, each
|
||||
* with what it cost. Rooms are short (the coordinator's turns are capped),
|
||||
* so they're read whole.
|
||||
*/
|
||||
export default async function grabChatroomMessages({ chatroom_id }: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES[]> {
|
||||
return (
|
||||
export default async function grabChatroomMessages({
|
||||
chatroom_id,
|
||||
}: Params): Promise<BotMessageWithAttachments[]> {
|
||||
const messages =
|
||||
(
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_MESSAGES>({
|
||||
sql: `SELECT m.* FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id
|
||||
@@ -18,6 +23,15 @@ export default async function grabChatroomMessages({ chatroom_id }: Params): Pro
|
||||
ORDER BY m.created_at ASC, m.id ASC`,
|
||||
values: [chatroom_id],
|
||||
})
|
||||
).payload || []
|
||||
);
|
||||
}
|
||||
).payload || [];
|
||||
|
||||
if (!messages.length) return messages;
|
||||
|
||||
const usage = await grabMessageUsage({ message_ids: messages.map((message) => Number(message.id)) });
|
||||
|
||||
return messages.map((message): BotMessageWithAttachments => {
|
||||
const spent = usage.get(Number(message.id));
|
||||
|
||||
return spent ? { ...message, usage: spent } : message;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
chatroom_id: number | string;
|
||||
/**
|
||||
* The job asking (the coordinator's own turn), which is still running as
|
||||
* it reads: never counted.
|
||||
*/
|
||||
except_job_id?: number | string | null;
|
||||
};
|
||||
|
||||
export type ChatroomOpenJob = {
|
||||
id: number;
|
||||
bot_id: number | null;
|
||||
bot_name: string | null;
|
||||
status: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The jobs a room still runs (pending or processing), with the bot each
|
||||
* works for: closing a room cancels them (`cancelChatroomJobs`), so the
|
||||
* tools that close one ask first whether anyone is still at work.
|
||||
*/
|
||||
export default async function grabChatroomOpenJobs({ chatroom_id, except_job_id }: Params): Promise<ChatroomOpenJob[]> {
|
||||
const res = await BunSQLite.sql<ChatroomOpenJob>({
|
||||
sql: `SELECT q.id, q.bot_id, b.name AS bot_name, q.status
|
||||
FROM bots_queue q
|
||||
JOIN bot_sessions s ON s.id = q.session_id
|
||||
LEFT JOIN bots b ON b.id = q.bot_id
|
||||
WHERE s.chatroom_id = ? AND q.status IN ('pending', 'processing') AND q.id != ?
|
||||
ORDER BY q.id`,
|
||||
values: [Number(chatroom_id), Number(except_job_id) || 0],
|
||||
});
|
||||
|
||||
return (res.payload || []).map((job) => ({
|
||||
id: Number(job.id),
|
||||
bot_id: job.bot_id ? Number(job.bot_id) : null,
|
||||
bot_name: job.bot_name || null,
|
||||
status: job.status,
|
||||
}));
|
||||
}
|
||||
@@ -8,12 +8,13 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One of the user's own chatrooms with the bots in it, or null.
|
||||
* One of the user's own chatrooms with the bots in it and what they spent
|
||||
* working there, or null.
|
||||
*/
|
||||
export default async function grabUserChatroom({ chatroom_id, user_id }: Params): Promise<ChatroomSummary | null> {
|
||||
const room = await grabChatroom({ chatroom_id, user_id });
|
||||
|
||||
if (!room?.id) return null;
|
||||
|
||||
return (await chatroomSummaries({ chatrooms: [room] }))[0] || null;
|
||||
return (await chatroomSummaries({ chatrooms: [room], with_usage: true }))[0] || null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
|
||||
import withMessageUsage from "../usage/with-message-usage";
|
||||
import grabChatroom from "./grab-chatroom";
|
||||
import pushChatroomUpdated from "./push-chatroom-updated";
|
||||
|
||||
@@ -9,18 +10,20 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Pushes a message posted in a room (`server:chatroom-message`) and the
|
||||
* room as it is now to the room's user.
|
||||
* Pushes a message posted in a room (`server:chatroom-message`), with what
|
||||
* it cost, and the room as it is now to the room's user.
|
||||
*/
|
||||
export default async function pushChatroomMessage({ chatroom_id, message }: Params) {
|
||||
const room = await grabChatroom({ chatroom_id });
|
||||
|
||||
if (!room?.id || !room.user_id) return;
|
||||
|
||||
const [pushed] = await withMessageUsage({ messages: [message] });
|
||||
|
||||
sendToUser({
|
||||
user_id: room.user_id,
|
||||
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message } },
|
||||
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message: pushed } },
|
||||
});
|
||||
|
||||
await pushChatroomUpdated({ chatroom_id: room.id });
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Pushes a room as it is now (`server:chatroom-updated`) to its user's
|
||||
* open tabs, for the rail and the room's header. Best effort.
|
||||
* open tabs, for the rail and the room's header, what its bots spent
|
||||
* included, for the totals at its top. Best effort.
|
||||
*/
|
||||
export default async function pushChatroomUpdated({ chatroom_id }: Params) {
|
||||
try {
|
||||
@@ -17,7 +18,7 @@ export default async function pushChatroomUpdated({ chatroom_id }: Params) {
|
||||
|
||||
if (!room?.id || !room.user_id) return;
|
||||
|
||||
const [summary] = await chatroomSummaries({ chatrooms: [room] });
|
||||
const [summary] = await chatroomSummaries({ chatrooms: [room], with_usage: true });
|
||||
|
||||
if (summary) {
|
||||
sendToUser({ user_id: room.user_id, data: { event: "server:chatroom-updated", data: summary } });
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
|
||||
import grabComputerWorkspaceQuotaBytes from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-bytes";
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import grabComputerMcpUrl from "./grab-computer-mcp-url";
|
||||
|
||||
export type FullComputerWorkspace = {
|
||||
computer_id: number;
|
||||
name: string;
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
/**
|
||||
* The biggest folder in it, from the agent's own listing.
|
||||
*/
|
||||
folder: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The share of the quota past which a computer is reported, so the
|
||||
* install hears about it while writes still fit. `AppData.ComputerWorkspaceWarnShare`
|
||||
* when left out.
|
||||
*/
|
||||
share?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Logs every computer whose workspace is nearly full, with what holds most
|
||||
* of it, and returns them. The workspace is the one folder on a computer
|
||||
* mounted from the data volume, so it is what can fill the host; nothing
|
||||
* prunes a bot's own files there (only caches, `prune-computer-caches`), so
|
||||
* without this the first sign is a bot refused its write (`21.3 GB of
|
||||
* 10.0 GB` on a real computer, nobody told until a run failed).
|
||||
*
|
||||
* Reported, never deleted: whose files to remove is the user's call.
|
||||
*/
|
||||
export default async function warnFullComputerWorkspaces({ share }: Params = {}): Promise<
|
||||
FullComputerWorkspace[]
|
||||
> {
|
||||
const quota_bytes = await grabComputerWorkspaceQuotaBytes();
|
||||
|
||||
if (quota_bytes <= 0) return [];
|
||||
|
||||
const threshold = quota_bytes * (share ?? AppData.ComputerWorkspaceWarnShare);
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<{ id: number; name: string | null }>({
|
||||
sql: `SELECT id, name FROM computers`,
|
||||
})
|
||||
).payload || [];
|
||||
const full: FullComputerWorkspace[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const address = await grabComputerMcpUrl({ computer_id: row.id }).catch(() => null);
|
||||
|
||||
if (!address?.ready) continue;
|
||||
|
||||
const usage = await grabComputerUsage({
|
||||
computer: { base_url: address.base_url, token: address.token },
|
||||
}).catch(() => null);
|
||||
|
||||
if (!usage || usage.used_bytes < threshold) continue;
|
||||
|
||||
const entry: FullComputerWorkspace = {
|
||||
computer_id: Number(row.id),
|
||||
name: row.name || `#${row.id}`,
|
||||
used_bytes: usage.used_bytes,
|
||||
quota_bytes,
|
||||
folder: usage.folders?.[0]?.path || null,
|
||||
};
|
||||
|
||||
full.push(entry);
|
||||
|
||||
await logEvent({
|
||||
title: `Computer ${entry.name} is nearly full`,
|
||||
category: "system",
|
||||
plain_text: `Computer ${entry.name} (#${entry.computer_id}) holds ${formatBytes({ bytes: entry.used_bytes })} of its ${formatBytes({ bytes: quota_bytes })} workspace limit${entry.folder ? `, most of it in ${entry.folder}` : ""}. Writes are refused once it passes the limit; clear the folder in Files, or raise the limit in Settings > General.`,
|
||||
metadata: {
|
||||
computer_id: entry.computer_id,
|
||||
used_bytes: entry.used_bytes,
|
||||
quota_bytes,
|
||||
folder: entry.folder,
|
||||
},
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
return full;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import modelContextLength from "./model-context-length";
|
||||
|
||||
describe("modelContextLength", () => {
|
||||
test("keeps what the provider's own list said", () => {
|
||||
expect(
|
||||
modelContextLength({ model: { context_length: 1_000_000 }, provider_context_length: 32_768 }),
|
||||
).toBe(1_000_000);
|
||||
});
|
||||
|
||||
test("gives a listed model the window its provider declares", () => {
|
||||
expect(modelContextLength({ model: {}, provider_context_length: 1_000_000 })).toBe(
|
||||
1_000_000,
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves a model unknown when neither said", () => {
|
||||
expect(modelContextLength({ model: {} })).toBeNull();
|
||||
expect(modelContextLength({ model: {}, provider_context_length: 0 })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { HarnessCatalogModel } from "@/src/harness/types";
|
||||
|
||||
type Params = {
|
||||
model: Pick<HarnessCatalogModel, "context_length">;
|
||||
/**
|
||||
* The window the provider's own row declares, for the models it lists
|
||||
* without one.
|
||||
*/
|
||||
provider_context_length?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The window a `harness_models` row keeps, in tokens: what the provider's
|
||||
* own list said, else the window the super admin declared for that provider
|
||||
* (a custom provider lists ids only), else nothing, and the run assumes
|
||||
* `AppData.HarnessUnknownContextWindow`.
|
||||
*/
|
||||
export default function modelContextLength({
|
||||
model,
|
||||
provider_context_length,
|
||||
}: Params) {
|
||||
return model.context_length || provider_context_length || null;
|
||||
}
|
||||
@@ -22,6 +22,11 @@ type Params = {
|
||||
*/
|
||||
api_key?: string;
|
||||
clear_key?: boolean;
|
||||
/**
|
||||
* The window its models are given when it lists none of its own. Zero
|
||||
* leaves them unknown.
|
||||
*/
|
||||
context_length?: number;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
@@ -36,6 +41,7 @@ export default async function saveHarnessProvider({
|
||||
base_url,
|
||||
api_key,
|
||||
clear_key,
|
||||
context_length,
|
||||
enabled,
|
||||
}: Params) {
|
||||
const preset = grabProviderPreset({ kind });
|
||||
@@ -64,6 +70,11 @@ export default async function saveHarnessProvider({
|
||||
name: name?.trim() || preset.title,
|
||||
base_url: final_base_url,
|
||||
enabled: enabled ? 1 : 0,
|
||||
/**
|
||||
* The row type spells an empty INTEGER as `""`, but a window is
|
||||
* cleared with null (the plugin binds it as NULL).
|
||||
*/
|
||||
context_length: (context_length && context_length > 0 ? context_length : null) as number,
|
||||
...key_update,
|
||||
};
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
|
||||
const count = await upsertHarnessModels({
|
||||
provider_id: provider.id,
|
||||
models,
|
||||
provider_context_length: provider.context_length || null,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
|
||||
@@ -25,6 +25,7 @@ export default function toPublicHarnessProvider({
|
||||
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
|
||||
needs_key: preset.needs_key,
|
||||
key_env: preset.key_env || undefined,
|
||||
context_length: provider.context_length || undefined,
|
||||
last_synced_at: provider.last_synced_at || undefined,
|
||||
sync_error: provider.sync_error || undefined,
|
||||
};
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HarnessCatalogModel } from "@/src/harness/types";
|
||||
import modelContextLength from "./model-context-length";
|
||||
|
||||
type Params = {
|
||||
provider_id: number;
|
||||
models: HarnessCatalogModel[];
|
||||
/**
|
||||
* The window its provider declares, for the models it lists without one
|
||||
* of their own (a custom provider lists ids only).
|
||||
*/
|
||||
provider_context_length?: number | null;
|
||||
now?: number;
|
||||
};
|
||||
|
||||
@@ -42,6 +48,7 @@ const ChunkSize = 50;
|
||||
export default async function upsertHarnessModels({
|
||||
provider_id,
|
||||
models,
|
||||
provider_context_length,
|
||||
now = Date.now(),
|
||||
}: Params) {
|
||||
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
|
||||
@@ -67,7 +74,7 @@ export default async function upsertHarnessModels({
|
||||
JSON.stringify(model.input_modalities),
|
||||
JSON.stringify(model.output_modalities),
|
||||
model.supports_tools ? 1 : 0,
|
||||
model.context_length ?? null,
|
||||
modelContextLength({ model, provider_context_length }),
|
||||
model.max_output_tokens ?? null,
|
||||
model.voices ? JSON.stringify(model.voices) : null,
|
||||
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
|
||||
|
||||
@@ -47,10 +47,12 @@ type Params = {
|
||||
requested_by_bot_id?: number | string | null;
|
||||
requested_by_session_id?: number | string | null;
|
||||
/**
|
||||
* False to only move it: the task goes to the new bot's list as to do
|
||||
* and no job is queued, for when the user hasn't asked for the work to
|
||||
* begin. Handing three tasks over "to wait for the go-ahead" once ran
|
||||
* three jobs that each only reported they were waiting.
|
||||
* True only when the user asked for the work to begin now: the task
|
||||
* goes to doing and a job is queued. Left out (the default) it only
|
||||
* moves: the task goes to the new bot's list as to do and no job is
|
||||
* queued, since handing a task over is not asking for it to be worked.
|
||||
* Handing three tasks over "to wait for the go-ahead" once ran three
|
||||
* jobs that each only reported they were waiting.
|
||||
*/
|
||||
start?: boolean;
|
||||
};
|
||||
@@ -70,13 +72,15 @@ export type HandedOverTask = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Hands an open task to another bot and starts the work: a task in a
|
||||
* workspace stays there and becomes the new bot's there (the work runs in
|
||||
* that workspace), one on a bot's own list moves to the new bot's. The task goes to doing, its log
|
||||
* says who handed it over, and a job is queued in the new bot's
|
||||
* conversation with the task's brief and `params.tracker_task_id`, so the
|
||||
* bot moves this same task along and the job's end is noted on it. With
|
||||
* `start` false it only moves: to do, no job, the notice says so.
|
||||
* Hands an open task to another bot: a task in a workspace stays there and
|
||||
* becomes the new bot's there (the work runs in that workspace), one on a
|
||||
* bot's own list moves to the new bot's. Handing it over is not asking for
|
||||
* it to be worked, so by default it only moves: the task goes to the new
|
||||
* bot's list as to do, no job is queued and the notice says so. With
|
||||
* `start` true (the user asked for the work to begin now) the task goes to
|
||||
* doing, its log says who handed it over, and a job is queued in the new
|
||||
* bot's conversation with the task's brief and `params.tracker_task_id`, so
|
||||
* the bot moves this same task along and the job's end is noted on it.
|
||||
*/
|
||||
export default async function handOverTask({
|
||||
user_id,
|
||||
@@ -87,7 +91,7 @@ export default async function handOverTask({
|
||||
handed_by,
|
||||
requested_by_bot_id,
|
||||
requested_by_session_id,
|
||||
start = true,
|
||||
start = false,
|
||||
}: Params): Promise<HandedOverTask> {
|
||||
const task = await grabTaskRow({ task_id });
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
|
||||
|
||||
type Call = {
|
||||
session_id: number | null;
|
||||
job_id: number | null;
|
||||
prompt_tokens: number;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number;
|
||||
cost: number | null;
|
||||
};
|
||||
|
||||
function seed() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, bot_id INTEGER, chatroom_id INTEGER, hook_id INTEGER)`);
|
||||
db.run(`CREATE TABLE token_usages (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER,
|
||||
prompt_tokens INTEGER, cached_tokens INTEGER, completion_tokens INTEGER, cost REAL)`);
|
||||
db.run(`CREATE TABLE harness_call_failures (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER)`);
|
||||
|
||||
/**
|
||||
* Room 1 has one hidden session per bot; 300 belongs to another room,
|
||||
* 400 to a bot's own conversation (no room), 500 to a hook's own.
|
||||
*/
|
||||
db.run(`INSERT INTO bot_sessions VALUES
|
||||
(100, 10, 1, NULL), (200, 20, 1, NULL), (300, 10, 2, NULL), (400, 10, NULL, NULL), (500, 20, NULL, 3)`);
|
||||
|
||||
let calls = 0;
|
||||
|
||||
const addCall = ({ bot_id, call }: { bot_id: number; call: Call }) =>
|
||||
db.run(`INSERT INTO token_usages (id, bot_id, session_id, job_id, prompt_tokens, cached_tokens, completion_tokens, cost)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
|
||||
++calls,
|
||||
bot_id,
|
||||
call.session_id,
|
||||
call.job_id,
|
||||
call.prompt_tokens,
|
||||
call.cached_tokens,
|
||||
call.completion_tokens,
|
||||
call.cost,
|
||||
]);
|
||||
|
||||
let failures = 0;
|
||||
|
||||
const addFailure = ({ bot_id, session_id }: { bot_id: number; session_id: number | null }) =>
|
||||
db.run(`INSERT INTO harness_call_failures (id, bot_id, session_id, job_id) VALUES (?, ?, ?, NULL)`, [
|
||||
++failures,
|
||||
bot_id,
|
||||
session_id,
|
||||
]);
|
||||
|
||||
return { db, addCall, addFailure };
|
||||
}
|
||||
|
||||
function callsByRoom({ db }: { db: Database }) {
|
||||
const { sql, values } = chatroomUsageCallsSql({ chatroom_ids: [1] });
|
||||
const rows = db.query(sql).all(...values) as {
|
||||
chatroom_id: number;
|
||||
bot_id: number;
|
||||
calls: number;
|
||||
prompt_tokens: number;
|
||||
cached_tokens: number;
|
||||
completion_tokens: number;
|
||||
cost: number;
|
||||
}[];
|
||||
|
||||
return rows
|
||||
.map((row) => ({
|
||||
chatroom_id: Number(row.chatroom_id),
|
||||
bot_id: Number(row.bot_id),
|
||||
calls: Number(row.calls),
|
||||
prompt_tokens: Number(row.prompt_tokens),
|
||||
cached_tokens: Number(row.cached_tokens),
|
||||
completion_tokens: Number(row.completion_tokens),
|
||||
cost: Number(row.cost),
|
||||
}))
|
||||
.sort((a, b) => a.bot_id - b.bot_id);
|
||||
}
|
||||
|
||||
function failuresByRoom({ db }: { db: Database }) {
|
||||
const { sql, values } = chatroomUsageFailuresSql({ chatroom_ids: [1] });
|
||||
const rows = db.query(sql).all(...values) as { chatroom_id: number; failed_calls: number }[];
|
||||
|
||||
return rows.map((row) => ({ chatroom_id: Number(row.chatroom_id), failed_calls: Number(row.failed_calls) }));
|
||||
}
|
||||
|
||||
describe("chatroomUsageCallsSql", () => {
|
||||
test("sums a room's calls by bot", () => {
|
||||
const { db, addCall } = seed();
|
||||
|
||||
addCall({
|
||||
bot_id: 10,
|
||||
call: { session_id: 100, job_id: null, prompt_tokens: 100, cached_tokens: 40, completion_tokens: 20, cost: 0.5 },
|
||||
});
|
||||
addCall({
|
||||
bot_id: 10,
|
||||
call: { session_id: 100, job_id: null, prompt_tokens: 50, cached_tokens: null, completion_tokens: 10, cost: null },
|
||||
});
|
||||
addCall({
|
||||
bot_id: 20,
|
||||
call: { session_id: 200, job_id: 50, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
|
||||
});
|
||||
|
||||
expect(callsByRoom({ db })).toEqual([
|
||||
{ chatroom_id: 1, bot_id: 10, calls: 2, prompt_tokens: 150, cached_tokens: 40, completion_tokens: 30, cost: 0.5 },
|
||||
{ chatroom_id: 1, bot_id: 20, calls: 1, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("another room's, a bot's own conversation's and a hook's calls stay out", () => {
|
||||
const { db, addCall } = seed();
|
||||
|
||||
const call = { job_id: null, prompt_tokens: 10, cached_tokens: null, completion_tokens: 5, cost: null };
|
||||
|
||||
addCall({ bot_id: 10, call: { ...call, session_id: 100 } });
|
||||
addCall({ bot_id: 10, call: { ...call, session_id: 300 } });
|
||||
addCall({ bot_id: 10, call: { ...call, session_id: 400 } });
|
||||
addCall({ bot_id: 20, call: { ...call, session_id: 500 } });
|
||||
addCall({ bot_id: 10, call: { ...call, session_id: null } });
|
||||
|
||||
expect(callsByRoom({ db })).toEqual([
|
||||
{ chatroom_id: 1, bot_id: 10, calls: 1, prompt_tokens: 10, cached_tokens: 0, completion_tokens: 5, cost: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("rooms with no calls have no rows", () => {
|
||||
const { db } = seed();
|
||||
|
||||
expect(callsByRoom({ db })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chatroomUsageFailuresSql", () => {
|
||||
test("counts a room's failed calls, still-running turns included", () => {
|
||||
const { db, addFailure } = seed();
|
||||
|
||||
addFailure({ bot_id: 10, session_id: 100 });
|
||||
addFailure({ bot_id: 20, session_id: 200 });
|
||||
addFailure({ bot_id: 10, session_id: 300 });
|
||||
addFailure({ bot_id: 10, session_id: null });
|
||||
|
||||
expect(failuresByRoom({ db })).toEqual([{ chatroom_id: 1, failed_calls: 2 }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The rooms whose calls are read.
|
||||
*/
|
||||
chatroom_ids: number[];
|
||||
};
|
||||
|
||||
const marks = ({ chatroom_ids }: Params) => chatroom_ids.map(() => "?").join(", ");
|
||||
|
||||
/**
|
||||
* Every model call a room's bots made, by room and by bot, summed (read by
|
||||
* `grabChatroomUsage`). A call is counted by the session it ran for (each
|
||||
* bot in a room has its own hidden one, `bot_sessions.chatroom_id`), which
|
||||
* is the run's own attribution: a turn still running counts too, before
|
||||
* any message is written, so a room's total moves while it works.
|
||||
*/
|
||||
export function chatroomUsageCallsSql({ chatroom_ids }: Params) {
|
||||
return {
|
||||
sql: `SELECT s.chatroom_id AS chatroom_id, t.bot_id AS bot_id,
|
||||
COUNT(*) AS calls,
|
||||
SUM(t.prompt_tokens) AS prompt_tokens,
|
||||
SUM(t.cached_tokens) AS cached_tokens,
|
||||
SUM(t.completion_tokens) AS completion_tokens,
|
||||
SUM(t.cost) AS cost
|
||||
FROM token_usages t
|
||||
JOIN bot_sessions s ON s.id = t.session_id
|
||||
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
|
||||
GROUP BY 1, 2`,
|
||||
values: [...chatroom_ids],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The rooms' model calls that failed, by room, for the count beside the
|
||||
* totals. Read the same way, by the session they ran for.
|
||||
*/
|
||||
export function chatroomUsageFailuresSql({ chatroom_ids }: Params) {
|
||||
return {
|
||||
sql: `SELECT s.chatroom_id AS chatroom_id, COUNT(*) AS failed_calls
|
||||
FROM harness_call_failures t
|
||||
JOIN bot_sessions s ON s.id = t.session_id
|
||||
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
|
||||
GROUP BY 1`,
|
||||
values: [...chatroom_ids],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { ChatroomUsage, ChatroomUsageBot } from "@/src/types";
|
||||
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
|
||||
import { sumSummary, toSummary } from "./grab-usage-totals";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The rooms whose usage is summed. A room no call touched is absent.
|
||||
*/
|
||||
chatroom_ids: (number | string)[];
|
||||
};
|
||||
|
||||
type CallRow = {
|
||||
chatroom_id: number;
|
||||
bot_id: number | null;
|
||||
calls: number | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
};
|
||||
|
||||
type FailureRow = {
|
||||
chatroom_id: number;
|
||||
failed_calls: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* What each room's bots spent working in it: every model call they made
|
||||
* there summed with the calls that failed, in total and per bot. A call
|
||||
* belongs to the room through its run's own session, so a coordinator
|
||||
* turn still running is counted before its answer is written, and a room's
|
||||
* totals never wait for a message to land.
|
||||
*/
|
||||
export default async function grabChatroomUsage({ chatroom_ids }: Params): Promise<Map<number, ChatroomUsage>> {
|
||||
const usage = new Map<number, ChatroomUsage>();
|
||||
const ids = [...new Set(chatroom_ids.map(Number).filter((id) => id > 0))];
|
||||
|
||||
if (!ids.length) return usage;
|
||||
|
||||
const [call_res, failure_res] = await Promise.all([
|
||||
BunSQLite.sql<CallRow>(chatroomUsageCallsSql({ chatroom_ids: ids })),
|
||||
BunSQLite.sql<FailureRow>(chatroomUsageFailuresSql({ chatroom_ids: ids })),
|
||||
]);
|
||||
|
||||
const calls = call_res.payload || [];
|
||||
const failures = new Map(
|
||||
(failure_res.payload || []).map((row) => [Number(row.chatroom_id), Number(row.failed_calls) || 0]),
|
||||
);
|
||||
const bot_ids = [...new Set(calls.map((row) => Number(row.bot_id)).filter((id) => id > 0))];
|
||||
const names = new Map(
|
||||
(
|
||||
bot_ids.length
|
||||
? (
|
||||
await BunSQLite.sql<{ id: number; name: string }>({
|
||||
sql: `SELECT id, name FROM bots WHERE id IN (${bot_ids.map(() => "?").join(", ")})`,
|
||||
values: bot_ids,
|
||||
})
|
||||
).payload || []
|
||||
: []
|
||||
).map((row) => [Number(row.id), row.name || null]),
|
||||
);
|
||||
|
||||
for (const id of ids) {
|
||||
const by_bot: ChatroomUsageBot[] = calls
|
||||
.filter((row) => Number(row.chatroom_id) == id)
|
||||
.map((row) => ({
|
||||
bot_id: Number(row.bot_id) || 0,
|
||||
name: names.get(Number(row.bot_id)) || null,
|
||||
...toSummary({ row }),
|
||||
}))
|
||||
.sort((a, b) => b.total_tokens - a.total_tokens || b.calls - a.calls);
|
||||
|
||||
usage.set(id, {
|
||||
totals: sumSummary({ summaries: by_bot }),
|
||||
failed_calls: failures.get(id) || 0,
|
||||
by_bot,
|
||||
});
|
||||
}
|
||||
|
||||
return usage;
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HarnessCallSettings, TokenUsageSummary } from "@/src/harness/usage/types";
|
||||
import parseCallSettings from "@/src/utils/parse-call-settings";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import toolRollup, { type ToolRollup } from "@/src/utils/tool-rollup";
|
||||
import grabMessageUsage from "./grab-message-usage";
|
||||
|
||||
/**
|
||||
* The bounds a run worked under, as it reported them with each call
|
||||
* (`HarnessCallSettings.limits`): the steps it had, the prompt tokens it
|
||||
* may spend and the working context it sent per turn.
|
||||
*/
|
||||
export type RunUsageLimits = {
|
||||
steps: RunLimit | null;
|
||||
run_tokens: RunLimit | null;
|
||||
context_tokens: RunLimit | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Today's General settings' run limits, for comparing a run with what the
|
||||
* install allows now.
|
||||
*/
|
||||
export type CurrentRunLimits = {
|
||||
task_steps: RunLimit;
|
||||
reply_steps: RunLimit;
|
||||
unattended_steps: RunLimit;
|
||||
run_tokens: RunLimit;
|
||||
context_tokens: RunLimit;
|
||||
};
|
||||
|
||||
export type RunUsageCall = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
harness: string;
|
||||
/**
|
||||
* The provider and model that answered, by the names they were called
|
||||
* with.
|
||||
*/
|
||||
provider_name: string | null;
|
||||
model_slug: string | null;
|
||||
prompt_tokens: number;
|
||||
cached_tokens: number;
|
||||
completion_tokens: number;
|
||||
settings: HarnessCallSettings | null;
|
||||
};
|
||||
|
||||
export type RunUsageMessage = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
author: string;
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
calls: number;
|
||||
};
|
||||
|
||||
export type RunUsage = {
|
||||
/**
|
||||
* What was looked at: the open job (its message not written yet) or a
|
||||
* message already in the session.
|
||||
*/
|
||||
target: {
|
||||
kind: "job" | "message";
|
||||
id: number;
|
||||
created_at: number | null;
|
||||
author: string | null;
|
||||
text: string | null;
|
||||
} | null;
|
||||
totals: TokenUsageSummary | null;
|
||||
calls: RunUsageCall[];
|
||||
/**
|
||||
* The tool calls the run made, counted by tool; null when it recorded
|
||||
* none.
|
||||
*/
|
||||
tools: ToolRollup | null;
|
||||
/**
|
||||
* What bounded the run, from its own calls; null on a call recorded
|
||||
* before limits were.
|
||||
*/
|
||||
limits: RunUsageLimits | null;
|
||||
current_limits: CurrentRunLimits;
|
||||
};
|
||||
|
||||
type CallRow = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
harness: string | null;
|
||||
provider_name: string | null;
|
||||
model_slug: string | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
settings: string | null;
|
||||
};
|
||||
|
||||
type MessageRow = {
|
||||
id: number;
|
||||
created_at: number;
|
||||
author: string | null;
|
||||
text: string | null;
|
||||
tool_log: string | null;
|
||||
};
|
||||
|
||||
const CallsSql = `SELECT t.id, t.created_at, t.harness, t.provider_name, t.model_slug,
|
||||
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.settings
|
||||
FROM token_usages t
|
||||
WHERE t.%COLUMN% = ?
|
||||
ORDER BY t.created_at ASC, t.id ASC
|
||||
LIMIT 500`;
|
||||
|
||||
const toCall = ({ row }: { row: CallRow }): RunUsageCall => ({
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || 0,
|
||||
harness: row.harness || "text",
|
||||
provider_name: row.provider_name || null,
|
||||
model_slug: row.model_slug || null,
|
||||
prompt_tokens: Number(row.prompt_tokens) || 0,
|
||||
cached_tokens: Number(row.cached_tokens) || 0,
|
||||
completion_tokens: Number(row.completion_tokens) || 0,
|
||||
settings: parseCallSettings({ json: row.settings }),
|
||||
});
|
||||
|
||||
/**
|
||||
* The limits a run worked under, from the calls themselves: each call kept
|
||||
* what the loop let it spend, so a message read months later still says
|
||||
* which limit it ran into.
|
||||
*/
|
||||
const limitsOf = ({ calls }: { calls: RunUsageCall[] }): RunUsageLimits | null => {
|
||||
const limits = calls.find((call) => call.settings?.limits)?.settings?.limits;
|
||||
|
||||
if (!limits) return null;
|
||||
|
||||
const kept = (value: RunLimit | null | undefined): RunLimit | null =>
|
||||
typeof value == "number" ? value : isUnlimitedLimit(value) ? UnlimitedLimit : null;
|
||||
|
||||
return {
|
||||
steps: kept(limits.steps),
|
||||
run_tokens: kept(limits.run_tokens),
|
||||
context_tokens: kept(limits.context_tokens),
|
||||
};
|
||||
};
|
||||
|
||||
const totalsOf = ({ prompt_tokens, completion_tokens, cost, calls }: { prompt_tokens: number; completion_tokens: number; cost?: number; calls: number }): TokenUsageSummary => ({
|
||||
prompt_tokens,
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(cost && Number.isFinite(cost) ? { cost } : {}),
|
||||
calls,
|
||||
});
|
||||
|
||||
/**
|
||||
* What one message (already checked to be in the run's own session) cost:
|
||||
* every model call it took with the settings each was made with, its tool
|
||||
* calls counted by tool, and the limits the run worked under. This is what
|
||||
* a bot reads to answer "why did that answer cost so much" before it
|
||||
* points the user at a setting (`read_message_usage`).
|
||||
*/
|
||||
export async function grabMessageRunUsage({
|
||||
message_id,
|
||||
session_id,
|
||||
}: {
|
||||
message_id: number;
|
||||
session_id: number | string;
|
||||
}) {
|
||||
const row = (
|
||||
await BunSQLite.sql<MessageRow>({
|
||||
sql: `SELECT id, created_at, author, text, tool_log FROM bot_messages WHERE id = ? AND session_id = ?`,
|
||||
values: [message_id, Number(session_id) || 0],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
const calls = (
|
||||
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "message_id"), values: [message_id] })).payload || []
|
||||
).map((item) => toCall({ row: item }));
|
||||
const prompt_tokens = calls.reduce((total, call) => total + call.prompt_tokens, 0);
|
||||
const completion_tokens = calls.reduce((total, call) => total + call.completion_tokens, 0);
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "message" as const,
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || null,
|
||||
author: row.author || null,
|
||||
text: row.text || null,
|
||||
},
|
||||
totals: totalsOf({ prompt_tokens, completion_tokens, calls: calls.length }),
|
||||
calls,
|
||||
tools: toolRollup({ tool_log: row.tool_log }),
|
||||
limits: limitsOf({ calls }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a job that is still open has spent so far, from its own calls and
|
||||
* its recorded steps: a reply cannot look at itself through a message,
|
||||
* since that is written when it ends.
|
||||
*/
|
||||
export async function grabJobRunUsage({ job_id }: { job_id: number | string }) {
|
||||
const calls = (
|
||||
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "job_id"), values: [Number(job_id) || 0] })).payload || []
|
||||
).map((item) => toCall({ row: item }));
|
||||
|
||||
if (!calls.length) return null;
|
||||
|
||||
const prompt_tokens = calls.reduce((total, call) => total + call.prompt_tokens, 0);
|
||||
const completion_tokens = calls.reduce((total, call) => total + call.completion_tokens, 0);
|
||||
|
||||
return {
|
||||
target: { kind: "job" as const, id: Number(job_id) || 0, created_at: null, author: null, text: null },
|
||||
totals: totalsOf({ prompt_tokens, completion_tokens, calls: calls.length }),
|
||||
calls,
|
||||
tools: null,
|
||||
limits: limitsOf({ calls }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's latest messages with what each cost, newest first, so a bot
|
||||
* can find the answer a user is asking about and then dig into it by id.
|
||||
*/
|
||||
export async function grabSessionMessageUsage({
|
||||
session_id,
|
||||
limit = 12,
|
||||
}: {
|
||||
session_id: number | string;
|
||||
limit?: number;
|
||||
}) {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<MessageRow>({
|
||||
sql: `SELECT id, created_at, author, text, tool_log FROM bot_messages
|
||||
WHERE session_id = ? ORDER BY id DESC LIMIT ?`,
|
||||
values: [Number(session_id) || 0, Math.max(1, Math.min(40, limit))],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
if (!rows.length) return [];
|
||||
|
||||
const totals = await grabMessageUsage({ message_ids: rows.map((row) => Number(row.id)) });
|
||||
|
||||
return rows.map((row) => {
|
||||
const usage = totals.get(Number(row.id));
|
||||
|
||||
return {
|
||||
id: Number(row.id),
|
||||
created_at: Number(row.created_at) || 0,
|
||||
author: row.author || "assistant",
|
||||
prompt_tokens: usage?.prompt_tokens || 0,
|
||||
completion_tokens: usage?.completion_tokens || 0,
|
||||
total_tokens: usage?.total_tokens || 0,
|
||||
calls: usage?.calls || 0,
|
||||
} satisfies RunUsageMessage;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import readDebugOpen from "./read-debug-open";
|
||||
import rememberDebugOpen from "./remember-debug-open";
|
||||
|
||||
class MemoryStorage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length() {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
key(index: number) {
|
||||
return [...this.store.keys()][index] ?? null;
|
||||
}
|
||||
|
||||
getItem(key: string) {
|
||||
return this.store.get(key) ?? null;
|
||||
}
|
||||
|
||||
setItem(key: string, value: string) {
|
||||
this.store.set(key, value);
|
||||
}
|
||||
|
||||
removeItem(key: string) {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.store.clear();
|
||||
}
|
||||
}
|
||||
|
||||
let storage: MemoryStorage;
|
||||
|
||||
beforeEach(() => {
|
||||
storage = new MemoryStorage();
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
value: storage as unknown as Storage,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
describe("the debug view's remembered state", () => {
|
||||
test("starts closed", () => {
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps its state per user, across conversations", () => {
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(true);
|
||||
expect(readDebugOpen({ user_id: 2 })).toBe(false);
|
||||
});
|
||||
|
||||
test("remembers closing it again", () => {
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
rememberDebugOpen({ user_id: 1, open: false });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps the other users' answers when one changes", () => {
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
rememberDebugOpen({ user_id: 2, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(true);
|
||||
expect(readDebugOpen({ user_id: 2 })).toBe(true);
|
||||
});
|
||||
|
||||
test("a broken stored value reads as closed, and is written over", () => {
|
||||
storage.setItem("cobble_debug_view_open", "not json");
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(false);
|
||||
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps working without a user id", () => {
|
||||
rememberDebugOpen({ user_id: null, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: null })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether this user left the conversation's debug view open on this device
|
||||
* (`rememberDebugOpen`). The view belongs to them, not to a bot, so one
|
||||
* answer covers every conversation.
|
||||
*/
|
||||
export default function readDebugOpen({ user_id }: Params): boolean {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(AppData["DebugViewStorageKey"]) || "{}");
|
||||
|
||||
return Boolean(stored?.[String(user_id ?? "user")]);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
user_id?: number | string | null;
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
type States = Record<string, boolean>;
|
||||
|
||||
/**
|
||||
* The answers stored so far. A value written by an older version (or
|
||||
* anything else in its place) reads as none, so the next save replaces it
|
||||
* rather than failing.
|
||||
*/
|
||||
function readStates(key: string): States {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(key) || "{}");
|
||||
|
||||
return stored && typeof stored == "object" && !Array.isArray(stored) ? stored : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records whether this user keeps the conversation's debug view open on
|
||||
* this device, so the next conversation and the next visit start where
|
||||
* they left off (`readDebugOpen`). Best effort.
|
||||
*/
|
||||
export default function rememberDebugOpen({ user_id, open }: Params) {
|
||||
try {
|
||||
const key = AppData["DebugViewStorageKey"];
|
||||
const states = readStates(key);
|
||||
const id = String(user_id ?? "user");
|
||||
|
||||
if (Boolean(states[id]) == open) return;
|
||||
|
||||
states[id] = open;
|
||||
localStorage.setItem(key, JSON.stringify(states));
|
||||
} catch {}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ describe("readChatResponse", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
text: "Checking.",
|
||||
reasoning: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "a1",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessChatResult, HarnessToolCall } from "../../types";
|
||||
import readReasoning from "./read-reasoning";
|
||||
|
||||
type WireToolCall = {
|
||||
id?: string;
|
||||
@@ -74,6 +75,13 @@ export default function readChatResponse({
|
||||
text: text || null,
|
||||
tool_calls,
|
||||
finish_reason: choice.finish_reason || undefined,
|
||||
/**
|
||||
* A reasoning model's own text, when the provider hands it back:
|
||||
* `reasoning` (OpenRouter), `reasoning_content` (DeepSeek and
|
||||
* others). Only the debug view shows it (`stripThinkTags` picks up
|
||||
* what a model writes inline instead).
|
||||
*/
|
||||
reasoning: readReasoning({ message: choice.message }),
|
||||
usage: json.usage
|
||||
? {
|
||||
prompt_tokens: json.usage.prompt_tokens,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import readReasoning from "./read-reasoning";
|
||||
|
||||
describe("readReasoning", () => {
|
||||
test("reads the reason OpenRouter hands back", () => {
|
||||
expect(readReasoning({ message: { reasoning: "They want a report." } })).toBe(
|
||||
"They want a report.",
|
||||
);
|
||||
});
|
||||
|
||||
test("reads DeepSeek's spelling too", () => {
|
||||
expect(readReasoning({ message: { reasoning_content: " Two plus two. " } })).toBe(
|
||||
"Two plus two.",
|
||||
);
|
||||
});
|
||||
|
||||
test("joins a reason given as parts", () => {
|
||||
expect(
|
||||
readReasoning({
|
||||
message: { reasoning: [{ text: "First. " }, { text: "Then the answer." }] },
|
||||
}),
|
||||
).toBe("First. Then the answer.");
|
||||
});
|
||||
|
||||
test("falls back to the readable details", () => {
|
||||
expect(
|
||||
readReasoning({
|
||||
message: {
|
||||
reasoning_details: [
|
||||
{ type: "reasoning.encrypted", data: "gibberish" },
|
||||
{ type: "reasoning.summary", summary: "Checked the numbers." },
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toBe("Checked the numbers.");
|
||||
});
|
||||
|
||||
test("is null when there's nothing readable", () => {
|
||||
expect(readReasoning({ message: {} })).toBeNull();
|
||||
expect(readReasoning({ message: { reasoning: " " } })).toBeNull();
|
||||
expect(readReasoning({ message: { reasoning_details: [{ data: "x" }] } })).toBeNull();
|
||||
expect(readReasoning({ message: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
type Params = {
|
||||
/**
|
||||
* A chat completion's `message`.
|
||||
*/
|
||||
message: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a reasoning model thought before it answered, when its provider
|
||||
* hands it back. The spellings in the wild: `reasoning` (OpenRouter, as a
|
||||
* string or a list of parts), `reasoning_content` (DeepSeek and the
|
||||
* providers that copied it), and `reasoning_details` (OpenRouter's list of
|
||||
* encrypted or summarised details, whose `text` or `summary` is readable).
|
||||
* Null when there's nothing readable.
|
||||
*/
|
||||
export default function readReasoning({ message }: Params): string | null {
|
||||
const candidates: unknown[] = [message?.reasoning, message?.reasoning_content];
|
||||
|
||||
if (Array.isArray(message?.reasoning_details)) {
|
||||
for (const detail of message.reasoning_details) candidates.push(detail?.text, detail?.summary);
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const text =
|
||||
typeof candidate == "string"
|
||||
? candidate
|
||||
: Array.isArray(candidate)
|
||||
? candidate
|
||||
.map((part: any) =>
|
||||
typeof part == "string" ? part : typeof part?.text == "string" ? part.text : "",
|
||||
)
|
||||
.join("")
|
||||
: "";
|
||||
|
||||
if (text.trim()) return text.trim();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user