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 |
+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`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `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,28 +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.
|
||||
- **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).
|
||||
- **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`.
|
||||
- **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`.
|
||||
@@ -120,7 +122,7 @@ 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 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`).
|
||||
@@ -129,11 +131,11 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
|
||||
### 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
|
||||
|
||||
@@ -150,7 +152,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
|
||||
- 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)
|
||||
@@ -165,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, 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.
|
||||
`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
|
||||
|
||||
@@ -218,10 +220,10 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **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, `read_settings`, `read_message_usage`, `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).
|
||||
@@ -241,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
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
+102
@@ -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`,
|
||||
|
||||
+61
-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",
|
||||
@@ -763,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.
|
||||
@@ -2866,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_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
|
||||
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
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.18.10",
|
||||
"version": "0.20.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -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 })) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
CoordinatorSoloNote,
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
HandOverTaskNote,
|
||||
workspaceAdminNote,
|
||||
WorkspaceLearningNote,
|
||||
openRunsNote,
|
||||
@@ -100,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
|
||||
@@ -331,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
|
||||
@@ -357,9 +365,10 @@ 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 }),
|
||||
@@ -410,20 +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),
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => shown.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)]
|
||||
: []),
|
||||
@@ -448,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
|
||||
|
||||
@@ -36,6 +36,7 @@ import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-comp
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
import runTextLoop from "@/src/harness/text/run-text-loop";
|
||||
import 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";
|
||||
@@ -108,6 +109,7 @@ export default async function runBotTask({
|
||||
computer_shared,
|
||||
signal,
|
||||
report,
|
||||
trace,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
const workspace_id = job.workspace_id || null;
|
||||
/**
|
||||
@@ -525,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,
|
||||
|
||||
@@ -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)`;
|
||||
}
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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,6 +3,7 @@ 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";
|
||||
@@ -51,6 +52,12 @@ export default function cron() {
|
||||
task: pruneBotHookEvents,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-bot-traces",
|
||||
schedule: "@daily",
|
||||
task: pruneBotTraces,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-chatrooms",
|
||||
schedule: "@daily",
|
||||
|
||||
@@ -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],
|
||||
});
|
||||
}
|
||||
+75
-15
@@ -51,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`,
|
||||
@@ -111,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.1",
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.2",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -305,11 +311,14 @@ 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: 2 * 60 * 60 * 1000,
|
||||
/**
|
||||
@@ -464,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,
|
||||
/**
|
||||
@@ -518,8 +527,36 @@ export const AppData = {
|
||||
* 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: 40_000_000,
|
||||
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
|
||||
@@ -640,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
|
||||
@@ -725,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`).
|
||||
@@ -842,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.
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
+110
-8
@@ -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,
|
||||
@@ -229,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.`;
|
||||
|
||||
/**
|
||||
@@ -258,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,
|
||||
@@ -279,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,
|
||||
@@ -368,6 +375,84 @@ ${plan.steps.map((step, index) => `${index + 1}. ${step}`).join("\n")}${plan.don
|
||||
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,
|
||||
@@ -412,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):
|
||||
@@ -536,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: {},
|
||||
|
||||
@@ -181,6 +181,15 @@ export const GeneralSettingsSections: GeneralSettingsSection[] = [
|
||||
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",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ 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";
|
||||
@@ -28,11 +29,12 @@ type RawValues = Record<string, number | string | null>;
|
||||
* started shows its new number).
|
||||
*/
|
||||
export default async function grabGeneralSettingsValues(): Promise<GeneralSettingsSectionValues[]> {
|
||||
const [run_limits, skill_limits, hook_calls, logs, chatrooms, sessions, messages, storage, computer_workspace, appendix, install_name] =
|
||||
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),
|
||||
@@ -59,6 +61,7 @@ export default async function grabGeneralSettingsValues(): Promise<GeneralSettin
|
||||
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,
|
||||
|
||||
@@ -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,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";
|
||||
@@ -129,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.
|
||||
*/
|
||||
|
||||
@@ -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() };
|
||||
}
|
||||
@@ -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),
|
||||
}));
|
||||
}
|
||||
@@ -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 } });
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
@@ -28,12 +28,50 @@ describe("fitTranscriptToContext", () => {
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 26000 });
|
||||
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters of earlier computer_bash output");
|
||||
expect(String(transcript[2]!.content)).toContain("characters of the middle of this computer_bash output");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
expect(transcript[6]!.content).toBe("recent");
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
});
|
||||
|
||||
test("keeps both ends of what it trimmed, so the run need not call it again", () => {
|
||||
const content = `HEAD${'x'.repeat(30000)}TAIL`;
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "second" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 8000 });
|
||||
|
||||
const trimmed = String(transcript[2]!.content);
|
||||
|
||||
expect(trimmed).toStartWith("HEAD");
|
||||
expect(trimmed).toEndWith("TAIL");
|
||||
expect(trimmed).toContain("than repeating it");
|
||||
expect(trimmed.length).toBeLessThan(content.length);
|
||||
});
|
||||
|
||||
test("says nothing about ends it did not keep, for a short result", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: "short answer" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "second" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 50 });
|
||||
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 12 characters of this computer_bash output");
|
||||
});
|
||||
|
||||
test("never trims the newest messages, even over budget", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
@@ -56,7 +94,7 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
expect(result.budget).toBe(15000);
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed:");
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
});
|
||||
|
||||
@@ -109,4 +147,53 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
expect(JSON.parse(call.arguments).trimmed).toContain(`${long.length} characters`);
|
||||
});
|
||||
|
||||
test("never trims the user's own request, however long it is", () => {
|
||||
const request = "Explain this.".repeat(2500);
|
||||
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: request },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "recent" },
|
||||
];
|
||||
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript,
|
||||
context_length: 131_072,
|
||||
budget_tokens: 12_000,
|
||||
});
|
||||
|
||||
expect(result.trimmed).toBeGreaterThan(0);
|
||||
expect(transcript[0]!.content).toBe(request);
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(result.over_budget).toBe(true);
|
||||
});
|
||||
|
||||
test("says a transcript it trimmed down fits", () => {
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript: run(),
|
||||
context_length: 200_000,
|
||||
budget_tokens: 12_000,
|
||||
});
|
||||
|
||||
expect(result.over_budget).toBe(false);
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
});
|
||||
|
||||
test("says a request nothing can be cut from does not fit", () => {
|
||||
const request = "x".repeat(30_000);
|
||||
const transcript: HarnessMessage[] = [{ role: "user", content: request }];
|
||||
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 131_072, budget_tokens: 4_000 });
|
||||
|
||||
expect(result.trimmed).toBe(0);
|
||||
expect(result.over_budget).toBe(true);
|
||||
expect(transcript[0]!.content).toBe(request);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -46,6 +46,14 @@ const CharsPerToken = 3;
|
||||
* What an image or audio part is counted as, in tokens.
|
||||
*/
|
||||
const MediaTokens = 1500;
|
||||
/**
|
||||
* Characters of a trimmed tool result that are kept at each end. A trimmed
|
||||
* result used to be replaced whole, with a note telling the model to call
|
||||
* the tool again if it still needed it, so it did: the same `SELECT`, the
|
||||
* same `cat`, re-run and resent. Keeping the start and the end (the command
|
||||
* and its totals, as `truncate` does) is usually all the run still needs.
|
||||
*/
|
||||
const TrimmedKeepChars = 500;
|
||||
/**
|
||||
* Tool call arguments longer than this (a file written whole) are cut on
|
||||
* the second pass, after the tool results.
|
||||
@@ -58,7 +66,9 @@ const ArgumentsKeepChars = 1500;
|
||||
* working context, or 70% of the window when that is smaller), the
|
||||
* oldest tool results, then long tool call arguments, then the oldest
|
||||
* assistant texts are replaced with a note of what was cut, down to 60%
|
||||
* of the budget. Returns how many messages were trimmed.
|
||||
* of the budget. Returns how many messages were trimmed, and whether the
|
||||
* prompt still doesn't fit (nothing trimmable was left: the conversation
|
||||
* is the user's own text, which is never cut).
|
||||
*/
|
||||
export default function fitTranscriptToContext({
|
||||
system,
|
||||
@@ -76,7 +86,7 @@ export default function fitTranscriptToContext({
|
||||
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
let trimmed = 0;
|
||||
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget };
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget, over_budget: false };
|
||||
|
||||
const target = Math.floor(budget * TrimToShare);
|
||||
const trimmable = transcript.length - keep_last;
|
||||
@@ -90,6 +100,24 @@ export default function fitTranscriptToContext({
|
||||
trimmed++;
|
||||
};
|
||||
|
||||
/**
|
||||
* A tool result cut down to its two ends and a note: the run works from
|
||||
* what it kept, rather than paying for the call again.
|
||||
*/
|
||||
const trimResult = ({ index, content, name }: { index: number; content: string; name: string | undefined }) => {
|
||||
const kept = content.length > TrimmedKeepChars * 4;
|
||||
const head = kept ? content.slice(0, TrimmedKeepChars) : "";
|
||||
const tail = kept ? content.slice(-TrimmedKeepChars) : "";
|
||||
const cut = content.length - head.length - tail.length;
|
||||
const label = name ? `${name} output` : "tool output";
|
||||
|
||||
if (!kept) return `[Trimmed: ${cut} characters of this ${label} to fit the working context.]`;
|
||||
|
||||
const note = `[Trimmed: ${cut} characters of the middle of this ${label} to fit the working context. Its start and end are kept here: work from them, and narrow the call (a smaller range, a filter, one row) rather than repeating it.]`;
|
||||
|
||||
return `${head}\n\n${note}\n\n${tail}`;
|
||||
};
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
@@ -101,7 +129,7 @@ export default function fitTranscriptToContext({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier ${name ? `${name} output` : "tool output"} to fit the working context. Call it again if you still need it.]`,
|
||||
content: trimResult({ index, content: message.content, name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -147,7 +175,7 @@ export default function fitTranscriptToContext({
|
||||
});
|
||||
}
|
||||
|
||||
return { trimmed, estimated_tokens: total, budget };
|
||||
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -140,9 +140,11 @@ export default async function generateText({
|
||||
signal,
|
||||
});
|
||||
|
||||
const text = answer.text ? stripThinkTags({ text: answer.text }) : "";
|
||||
const stripped = answer.text
|
||||
? stripThinkTags({ text: answer.text })
|
||||
: { text: "", reasoning: null };
|
||||
|
||||
if (!text && !answer.tool_calls.length) {
|
||||
if (!stripped.text && !answer.tool_calls.length) {
|
||||
throw new HarnessError({
|
||||
message: `The model returned an empty answer.`,
|
||||
retryable: true,
|
||||
@@ -150,7 +152,14 @@ export default async function generateText({
|
||||
});
|
||||
}
|
||||
|
||||
return { ...answer, text: text || null, sent_params };
|
||||
/**
|
||||
* Reasoning is kept only for the debug view: what the model
|
||||
* wrote inline wins over a provider's own field, since models
|
||||
* that write tags rarely send both.
|
||||
*/
|
||||
const reasoning = stripped.reasoning || answer.reasoning || null;
|
||||
|
||||
return { ...answer, text: stripped.text || null, reasoning, sent_params };
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,24 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
|
||||
import {
|
||||
alreadyRanToolNote,
|
||||
answerNotSentNote,
|
||||
commitEarlyNote,
|
||||
failedToolCallNote,
|
||||
oversizedRequestNote,
|
||||
tokensLowNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import HarnessError from "../harness-error";
|
||||
import isClosingTool from "../tools/closing-tool-names";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey from "../tools/repeat-tool-call-key";
|
||||
import repeatToolCallKey, { toolCallKey } from "../tools/repeat-tool-call-key";
|
||||
import isRepeatableTool from "../tools/repeatable-tool-names";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import type { ToolCallResult } from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import isWritingTool from "../tools/writing-tool-names";
|
||||
import type { HarnessTrace, HarnessTracer } from "../trace/types";
|
||||
import type {
|
||||
HarnessCandidate,
|
||||
HarnessMessage,
|
||||
@@ -66,6 +78,14 @@ type Params = {
|
||||
* progress and checkpoints.
|
||||
*/
|
||||
onStep?: (step: TextLoopStep) => Promise<void> | void;
|
||||
/**
|
||||
* Where the run's detailed trace goes (`bot_job_traces`, the
|
||||
* conversation's debug view): every turn with what the model reasoned,
|
||||
* every tool call with its arguments and answer, and what the loop
|
||||
* itself did. Best effort: a trace that can't be kept never fails the
|
||||
* run.
|
||||
*/
|
||||
trace?: HarnessTracer;
|
||||
/**
|
||||
* The user's turns that arrived since the run started (and since the
|
||||
* last call), read after each round of tools and before an answer is
|
||||
@@ -261,6 +281,7 @@ export default async function runTextLoop({
|
||||
context_budget,
|
||||
signal = new AbortController().signal,
|
||||
onStep,
|
||||
trace,
|
||||
incoming,
|
||||
incoming_notes,
|
||||
review,
|
||||
@@ -316,6 +337,16 @@ export default async function runTextLoop({
|
||||
* read again.
|
||||
*/
|
||||
const repeated_reads = new Map<string, number>();
|
||||
/**
|
||||
* The calls that failed, by the call they answer (`toolCallKey`), with
|
||||
* the step the first of them ran on and the error it gave. An identical
|
||||
* call past `AppData.HarnessSameFailureRetries` is answered from here
|
||||
* instead of being run: it fails the same way, and each repeat resends
|
||||
* the whole transcript (one run paid five times for the same
|
||||
* `FileNotFoundError`). Anything that could change the outcome clears
|
||||
* them, so a call retried after the missing piece was put in place runs.
|
||||
*/
|
||||
const failed_calls = new Map<string, { step: number; attempts: number; error: string }>();
|
||||
/**
|
||||
* The tools a wrap up may still call: what saves the work, and
|
||||
* `start_task` for the work it can't finish. A run that spent every
|
||||
@@ -347,7 +378,39 @@ export default async function runTextLoop({
|
||||
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
/**
|
||||
* A run that wrote a message and then called a tool has been told, once,
|
||||
* that the message never went out (`answerNotSentNote`).
|
||||
*/
|
||||
let told_answer_lost = false;
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
*/
|
||||
let told_over_budget = false;
|
||||
let warned_steps = isUnlimitedLimit(max_steps) || max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
/**
|
||||
* The prompt tokens past which the run is told to land the work
|
||||
* (`AppData.HarnessRunTokensWarnShare` of its budget), and whether it has
|
||||
* been told. A run with no token budget has none to be near the end of.
|
||||
*/
|
||||
const tokens_warn_at =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0
|
||||
? Math.floor(max_prompt_tokens * AppData.HarnessRunTokensWarnShare)
|
||||
: Infinity;
|
||||
let warned_tokens = tokens_warn_at == Infinity;
|
||||
/**
|
||||
* A quarter of the budget with nothing produced yet: research is not
|
||||
* progress, and a run that spends the whole budget reading lands its
|
||||
* report but none of the work (one task run did exactly that: 195
|
||||
* turns, 30M tokens, zero rows written, Nov 2026). Said once, while
|
||||
* there is still budget to land the rest.
|
||||
*/
|
||||
const commits_at =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0
|
||||
? Math.floor(max_prompt_tokens * AppData.HarnessRunTokensCommitShare)
|
||||
: Infinity;
|
||||
let told_to_commit = commits_at == Infinity;
|
||||
/**
|
||||
* The wrap up is announced once, and may save until it has: a run told
|
||||
* to stop with its report unwritten gets a turn to write it (at most
|
||||
@@ -361,6 +424,20 @@ export default async function runTextLoop({
|
||||
*/
|
||||
let used_wrap_turn = false;
|
||||
|
||||
/**
|
||||
* One trace entry, kept only when the run has somewhere to put it. A
|
||||
* trace is for reading afterwards, never a reason to fail the work.
|
||||
*/
|
||||
const traced = async (entry: HarnessTrace) => {
|
||||
if (!trace) return;
|
||||
|
||||
try {
|
||||
await trace(entry);
|
||||
} catch {
|
||||
/* the debug view is never worth a failed run */
|
||||
}
|
||||
};
|
||||
|
||||
for (let index = 0; index <= step_ceiling + 1 + WrapUpSavingTurns; index++) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
@@ -384,7 +461,7 @@ export default async function runTextLoop({
|
||||
if (wrap_up && !wrap_up_announced) {
|
||||
wrap_up_announced = true;
|
||||
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up });
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index });
|
||||
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
@@ -395,6 +472,13 @@ export default async function runTextLoop({
|
||||
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
|
||||
}),
|
||||
});
|
||||
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "wrap_up",
|
||||
text: `${out_of_steps ? "Out of steps" : "Out of tokens"}. ${wrap_tools.length ? `It has one turn left with ${wrap_tools.map((tool) => tool.name).join(", ")}.` : "It has no tool left and must answer now."}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (wrap_up_saving) saving_turns++;
|
||||
@@ -407,7 +491,7 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
|
||||
|
||||
fitTranscriptToContext({
|
||||
const fit = fitTranscriptToContext({
|
||||
system: run_system,
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessUnknownContextWindow,
|
||||
@@ -415,6 +499,23 @@ export default async function runTextLoop({
|
||||
tools_chars: JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
/**
|
||||
* Everything trimmable was trimmed and it still doesn't fit: what is
|
||||
* over is what the user wrote, which is never cut. Told once, so it
|
||||
* works in pieces and says what it could not reach instead of
|
||||
* inventing the rest (`oversizedRequestNote`).
|
||||
*/
|
||||
if (fit.over_budget && !told_over_budget) {
|
||||
told_over_budget = true;
|
||||
|
||||
const note = oversizedRequestNote({ budget: fit.budget });
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: "over_budget", text: note });
|
||||
}
|
||||
|
||||
const turn_started_at = Date.now();
|
||||
|
||||
const answer = await generate({
|
||||
messages: [{ role: "system", content: run_system }, ...transcript],
|
||||
tools: definitions.length ? definitions : undefined,
|
||||
@@ -466,11 +567,34 @@ export default async function runTextLoop({
|
||||
candidate: answer.candidate,
|
||||
});
|
||||
|
||||
await traced({
|
||||
kind: "turn",
|
||||
index,
|
||||
model: answer.candidate.model.name || answer.candidate.model.slug,
|
||||
provider: answer.candidate.provider.name || null,
|
||||
text: answer.text,
|
||||
reasoning: answer.reasoning ?? null,
|
||||
tool_calls: tool_calls.map((call) => ({ name: call.name, arguments: call.arguments })),
|
||||
usage: answer.usage ?? null,
|
||||
finish_reason: answer.finish_reason ?? null,
|
||||
duration_ms: Date.now() - turn_started_at,
|
||||
});
|
||||
|
||||
/**
|
||||
* An answer the user wrote past is drafted again. Not on the wrap
|
||||
* up: the run is out of steps, and a later reply picks them up.
|
||||
*/
|
||||
if (!tool_calls.length && !wrap_up && (await takeIncoming({ note: incoming_notes?.redraft || RedraftNote }))) {
|
||||
if (
|
||||
!tool_calls.length &&
|
||||
!wrap_up &&
|
||||
(await takeIncoming({ note: incoming_notes?.redraft || RedraftNote, index }))
|
||||
) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "redraft",
|
||||
text: "The user wrote again before this answer went out, so it was written again with that in mind.",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -480,6 +604,7 @@ export default async function runTextLoop({
|
||||
const note = await review({ text: answer.text || "", tool_uses }).catch(() => null);
|
||||
|
||||
if (note) {
|
||||
await traced({ kind: "event", index, name: "review", text: note });
|
||||
pushUserTurn({ transcript, content: note });
|
||||
continue;
|
||||
}
|
||||
@@ -505,11 +630,33 @@ export default async function runTextLoop({
|
||||
for (const call of tool_calls) {
|
||||
const repeat_key = repeatToolCallKey({ call });
|
||||
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
const call_key = toolCallKey({ call });
|
||||
const failed_before = call_key ? failed_calls.get(call_key) : undefined;
|
||||
const give_up =
|
||||
failed_before !== undefined && failed_before.attempts > AppData.HarnessSameFailureRetries;
|
||||
|
||||
const { text: content, images } =
|
||||
const result: ToolCallResult =
|
||||
already_read !== undefined
|
||||
? { text: alreadyRanToolNote({ name: call.name, step: already_read }), images: [] }
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
? {
|
||||
text: alreadyRanToolNote({ name: call.name, step: already_read }),
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: give_up
|
||||
? {
|
||||
text: failedToolCallNote({
|
||||
name: call.name,
|
||||
step: failed_before.step,
|
||||
attempts: failed_before.attempts,
|
||||
error: failed_before.error,
|
||||
}),
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
const { text: content, images } = result;
|
||||
const ok = !give_up && !content.startsWith("Error:");
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
@@ -519,7 +666,19 @@ export default async function runTextLoop({
|
||||
loaded.push(call.name);
|
||||
}
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
tool_uses.push({ name: call.name, ok });
|
||||
|
||||
await traced({
|
||||
kind: "tool",
|
||||
index,
|
||||
name: call.name,
|
||||
arguments: call.arguments,
|
||||
result: content,
|
||||
ok,
|
||||
images: images.length,
|
||||
duration_ms: result.duration_ms,
|
||||
repeat_of: (give_up ? failed_before.step : already_read) ?? null,
|
||||
});
|
||||
|
||||
if (!repeat_key) {
|
||||
repeated_reads.clear();
|
||||
@@ -528,11 +687,61 @@ export default async function runTextLoop({
|
||||
else repeated_reads.set(repeat_key, index);
|
||||
}
|
||||
|
||||
if (give_up) {
|
||||
failed_calls.set(call_key!, { ...failed_before, attempts: failed_before.attempts + 1 });
|
||||
} else if (content.startsWith("Error:")) {
|
||||
if (call_key) {
|
||||
const earlier = failed_calls.get(call_key);
|
||||
|
||||
failed_calls.set(call_key, {
|
||||
step: earlier?.step ?? index,
|
||||
attempts: (earlier?.attempts ?? 0) + 1,
|
||||
error: earlier?.error ?? clipFailure({ text: content }),
|
||||
});
|
||||
}
|
||||
} else if (!call_key || !isRepeatableTool({ name: call.name })) {
|
||||
failed_calls.clear();
|
||||
}
|
||||
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
|
||||
if (images.length) shown.push({ tool_name: call.name, images });
|
||||
}
|
||||
|
||||
/**
|
||||
* An answer that ends on a card is the whole reply: the question
|
||||
* waits for the user, and what comes next was just offered. Going on
|
||||
* would send the next turn's short line in its place, since the reply
|
||||
* is only the run's last message (`ClosingToolNames`).
|
||||
*/
|
||||
if (answer.text && tool_calls.every((call) => isClosingTool({ name: call.name }))) {
|
||||
/**
|
||||
* Checked before it goes out, as any reply is: a note comes
|
||||
* back and the answer is written again (the card stays on the
|
||||
* reply, its ref is already recorded).
|
||||
*/
|
||||
if (review && !reviewed) {
|
||||
reviewed = true;
|
||||
|
||||
const note = await review({ text: answer.text, tool_uses }).catch(() => null);
|
||||
|
||||
if (note) {
|
||||
await traced({ kind: "event", index, name: "review", text: note });
|
||||
pushUserTurn({ transcript, content: note });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: answer.text,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Screenshots and other tool images follow the results in a user
|
||||
* turn. A model that sees gets them as they are when the text
|
||||
@@ -550,7 +759,45 @@ export default async function runTextLoop({
|
||||
});
|
||||
}
|
||||
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote });
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote, index });
|
||||
|
||||
/**
|
||||
* The run wrote for the user and then carried on: that message never
|
||||
* goes out, and a run that doesn't know it ends with the tail of an
|
||||
* answer it already wrote. Told once, with the message still in the
|
||||
* transcript to write again.
|
||||
*/
|
||||
if (!told_answer_lost && answer.text) {
|
||||
told_answer_lost = true;
|
||||
|
||||
pushUserTurn({ transcript, content: answerNotSentNote });
|
||||
await traced({ kind: "event", index, name: "answer_not_sent", text: answerNotSentNote });
|
||||
}
|
||||
|
||||
/**
|
||||
* What this turn spent: past the budget, the wrap up says it better
|
||||
* (`wrapUpPrompt`) than either note below.
|
||||
*/
|
||||
const spent_out =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens;
|
||||
|
||||
/**
|
||||
* Something produced, or a quarter of the budget gone without it:
|
||||
* said before the steps are nearly out, so a run still has room to
|
||||
* land the work rather than reporting on it. A run that has written
|
||||
* anything at all is left alone; one that landed its work through a
|
||||
* shell says so (`commitEarlyNote`).
|
||||
*/
|
||||
if (tool_uses.some((used) => used.ok && isWritingTool({ name: used.name }))) told_to_commit = true;
|
||||
|
||||
if (!told_to_commit && !spent_out && usage.prompt_tokens >= commits_at) {
|
||||
told_to_commit = true;
|
||||
|
||||
const note = commitEarlyNote({ spent: usage.prompt_tokens, of: max_prompt_tokens as number });
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: "commit_early", text: note });
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps left before the wrap up, once the next turn is taken.
|
||||
@@ -562,6 +809,22 @@ export default async function runTextLoop({
|
||||
if (!warned_steps && !isUnlimitedLimit(max_steps) && left <= warn_at) {
|
||||
warned_steps = true;
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
await traced({ kind: "event", index, name: "steps_low", text: stepsLowNote({ left }) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Half the token budget gone, once: every further turn resends this
|
||||
* whole conversation, so what the run does next is paid for out of
|
||||
* the answer. Skipped when the turn just spent the budget out: the
|
||||
* wrap up says it better (`wrapUpPrompt`).
|
||||
*/
|
||||
if (!warned_tokens && !spent_out && usage.prompt_tokens >= tokens_warn_at) {
|
||||
warned_tokens = true;
|
||||
|
||||
const tokens_left = (max_prompt_tokens as number) - usage.prompt_tokens;
|
||||
|
||||
pushUserTurn({ transcript, content: tokensLowNote({ left: tokens_left }) });
|
||||
await traced({ kind: "event", index, name: "tokens_low", text: tokensLowNote({ left: tokens_left }) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -571,7 +834,7 @@ export default async function runTextLoop({
|
||||
* Adds what the user wrote since the last look, after `note`. True when
|
||||
* there was anything.
|
||||
*/
|
||||
async function takeIncoming({ note }: { note: string }) {
|
||||
async function takeIncoming({ note, index }: { note: string; index: number }) {
|
||||
const turns = (await incoming?.()) || [];
|
||||
const user_turns = turns.filter((turn) => turn.role == "user");
|
||||
|
||||
@@ -583,6 +846,29 @@ export default async function runTextLoop({
|
||||
pushUserTurn({ transcript, content: turn.content });
|
||||
}
|
||||
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "incoming",
|
||||
text: user_turns
|
||||
.map((turn) => (typeof turn.content == "string" ? turn.content : ""))
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Characters of a failure a repeated call's note keeps: a failing command
|
||||
* can print a whole traceback, and the note is resent with every turn
|
||||
* after it.
|
||||
*/
|
||||
const FailureNoteChars = 400;
|
||||
|
||||
/**
|
||||
* The error a repeated call's note reuses, cut to `FailureNoteChars`.
|
||||
*/
|
||||
const clipFailure = ({ text }: { text: string }) =>
|
||||
text.length <= FailureNoteChars ? text : `${text.slice(0, FailureNoteChars)}...`;
|
||||
|
||||
@@ -3,19 +3,26 @@ import stripThinkTags from "./strip-think-tags";
|
||||
|
||||
describe("stripThinkTags", () => {
|
||||
test("removes reasoning blocks", () => {
|
||||
expect(
|
||||
stripThinkTags({ text: "<think>plan\nmore</think>\n\nDone." }),
|
||||
).toBe("Done.");
|
||||
expect(
|
||||
stripThinkTags({ text: "A <THINK>x</THINK>B <think>y</think>C" }),
|
||||
).toBe("A B C");
|
||||
expect(stripThinkTags({ text: "\u003cthink\u003eplan\nmore\u003c/think\u003e\n\nDone." }).text).toBe("Done.");
|
||||
expect(stripThinkTags({ text: "A \u003cTHINK\u003ex\u003c/THINK\u003eB" }).text).toBe("A B");
|
||||
});
|
||||
|
||||
test("drops an unclosed block at the start", () => {
|
||||
expect(stripThinkTags({ text: "<think>never ends" })).toBe("");
|
||||
test("keeps what was reasoned, in order", () => {
|
||||
expect(
|
||||
stripThinkTags({ text: "\u003cthink\u003efirst\u003c/think\u003ea \u003cthink\u003esecond\u003c/think\u003eb" }).reasoning,
|
||||
).toBe("first\n\nsecond");
|
||||
expect(stripThinkTags({ text: "\u003cTHINK\u003ex\u003c/THINK\u003eB" }).reasoning).toBe("x");
|
||||
expect(stripThinkTags({ text: "no reasoning here" }).reasoning).toBe(null);
|
||||
});
|
||||
|
||||
test("drops an unclosed block at the start, keeping it as reasoning", () => {
|
||||
expect(stripThinkTags({ text: " \u003cthink\u003enever ends" })).toEqual({
|
||||
text: "",
|
||||
reasoning: "never ends",
|
||||
});
|
||||
});
|
||||
|
||||
test("leaves plain text alone", () => {
|
||||
expect(stripThinkTags({ text: " Hello " })).toBe("Hello");
|
||||
expect(stripThinkTags({ text: " Hello " })).toEqual({ text: "Hello", reasoning: null });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,12 +3,30 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes the `<think>...</think>` reasoning some models write into their
|
||||
* answer, including an unclosed one at the start.
|
||||
* Splits a model's answer from the ` thinking...` reasoning some
|
||||
* models write into it, including an unclosed one at the start. The answer
|
||||
* is what the bot says; the reasoning goes only to the debug view.
|
||||
*/
|
||||
export default function stripThinkTags({ text }: Params) {
|
||||
return text
|
||||
.replace(/<think>[\s\S]*?<\/think>/gi, "")
|
||||
.replace(/^\s*<think>[\s\S]*$/i, "")
|
||||
export default function stripThinkTags({ text }: Params): { text: string; reasoning: string | null } {
|
||||
const thoughts: string[] = [];
|
||||
|
||||
let answer = text.replace(/<think[^>]*>([\s\S]*?)<\/think>/gi, (_block: string, reason: string) => {
|
||||
thoughts.push(reason);
|
||||
return "";
|
||||
});
|
||||
|
||||
const unclosed = /^\s*<think[^>]*>([\s\S]*)$/i.exec(answer);
|
||||
|
||||
if (unclosed) {
|
||||
thoughts.push(unclosed[1] || "");
|
||||
answer = answer.slice(0, unclosed.index);
|
||||
}
|
||||
|
||||
const reasoning = thoughts
|
||||
.map((thought) => thought.trim())
|
||||
.filter(Boolean)
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return { text: answer.trim(), reasoning: reasoning || null };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
|
||||
/**
|
||||
* The task being handed over, and what `handOverTask` answered with it:
|
||||
* what a hand-over passes on is the whole point of these tests, so the
|
||||
* helper is mocked and its arguments recorded.
|
||||
*/
|
||||
let task = {
|
||||
id: 27,
|
||||
title: "Rewrite the pricing page",
|
||||
bot_id: 4,
|
||||
workspace_id: 3,
|
||||
status: "todo",
|
||||
} as BUN_SQLITE_COBBLE_TASKS;
|
||||
let handedArgs: Record<string, unknown> | null = null;
|
||||
let handed: Record<string, unknown> = {};
|
||||
|
||||
mock.module("@/src/functions/backend/db/tasks/grab-run-task", () => ({
|
||||
default: async () => task,
|
||||
}));
|
||||
|
||||
mock.module("@/src/functions/backend/db/tasks/hand-over-task", () => ({
|
||||
default: async (args: Record<string, unknown>) => {
|
||||
handedArgs = args;
|
||||
return handed;
|
||||
},
|
||||
}));
|
||||
|
||||
const delegateTaskTool = (await import("./delegate-task-tool")).default;
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const worker = { id: 5, name: "Researcher", role: "research", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
function tool() {
|
||||
return delegateTaskTool({
|
||||
user_id: 1,
|
||||
requester_id: 1,
|
||||
session_id: 10,
|
||||
requester_name: "Coordinator",
|
||||
workers: [worker],
|
||||
workspaces: [],
|
||||
grabTargets: async () => [worker],
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
task = {
|
||||
id: 27,
|
||||
title: "Rewrite the pricing page",
|
||||
bot_id: 4,
|
||||
workspace_id: 3,
|
||||
status: "todo",
|
||||
} as BUN_SQLITE_COBBLE_TASKS;
|
||||
handedArgs = null;
|
||||
handed = { task, job_id: null, bot_name: "Researcher", workspace_id: 3, joined: "" };
|
||||
});
|
||||
|
||||
describe("delegateTaskTool, handing over a task on a list", () => {
|
||||
test("moves it as to do by default: no run is queued", async () => {
|
||||
const answer = await tool().run({ args: { bot_id: 5, task_id: 27 }, signal });
|
||||
|
||||
expect(handedArgs?.start).toBe(false);
|
||||
expect(handedArgs?.task_id).toBe(27);
|
||||
expect(String(answer)).toContain("as to do");
|
||||
expect(String(answer)).toContain("Nothing is running");
|
||||
});
|
||||
|
||||
test("starts it only with start: true, when the user asked for that", async () => {
|
||||
handed = { task, job_id: 318, bot_name: "Researcher", workspace_id: 3, joined: "" };
|
||||
|
||||
const answer = await tool().run({ args: { bot_id: 5, task_id: 27, start: true }, signal });
|
||||
|
||||
expect(handedArgs?.start).toBe(true);
|
||||
expect(String(answer)).toContain("is with Researcher now (job #318)");
|
||||
expect(String(answer)).toContain("marked doing");
|
||||
});
|
||||
|
||||
test("says a hand-over starts nothing, and to ask before it moves", () => {
|
||||
expect(tool().description).toContain("Handing a task over never starts it");
|
||||
expect(tool().description).toContain("ask first with ask_user");
|
||||
});
|
||||
});
|
||||
@@ -96,11 +96,11 @@ describe("delegateTaskTool", () => {
|
||||
expect(tool.description).toContain("task_id");
|
||||
});
|
||||
|
||||
test("can hand a task over without starting it", () => {
|
||||
test("hands a task over as to do unless told to start it", () => {
|
||||
const tool = coordinatorTool();
|
||||
|
||||
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: false }).success).toBe(true);
|
||||
expect(tool.description).toContain("start: false");
|
||||
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: true }).success).toBe(true);
|
||||
expect(tool.description).toContain("start: true");
|
||||
});
|
||||
|
||||
test("without a task_id, still needs a title and instructions", async () => {
|
||||
|
||||
@@ -69,7 +69,8 @@ type Args = {
|
||||
*/
|
||||
task_id?: number;
|
||||
/**
|
||||
* With `task_id`: false to only move the task, nothing started.
|
||||
* The user asked for that task's work to begin now (with `task_id`):
|
||||
* left out it only moves, to do, and no run is spent.
|
||||
*/
|
||||
start?: boolean;
|
||||
title?: string;
|
||||
@@ -114,7 +115,7 @@ export default function delegateTaskTool({
|
||||
|
||||
return {
|
||||
name: "delegate_task",
|
||||
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there), goes to doing, and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. When the user hasn't asked for that task's work to begin yet (they want it moved, or to decide first), add start: false: it only moves to their list as to do, and no run is spent on reporting that they're waiting. Crew: ${crew}.${
|
||||
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there) and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. Handing a task over never starts it: it lands there as to do, and only start: true (when the user asked for the work to begin now) marks it doing and queues the run. When the user asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it) and hand over only once they've answered. A new brief with no task_id always runs at once. Crew: ${crew}.${
|
||||
workspace_id
|
||||
? ` You are working in a workspace, so the task runs there: in this workspace's context.`
|
||||
: ` Leave workspace_id out to run it in the crew member's own chat: only its own memory, files and directly assigned computers apply there, and the user finds the result by talking to it on its own. Add workspace_id to run it in one of the user's workspaces instead: the workspace's shared context, the member's instructions and memory there, its files and its computers (the workspace's own and the member's) all apply, and the result lands in its conversation in that workspace, beside the project it belongs to. Pick a workspace when the work belongs to that project; the member is added to it when it isn't in it yet. Workspaces: ${places || "none"}.`
|
||||
@@ -125,7 +126,7 @@ export default function delegateTaskTool({
|
||||
start: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("With task_id: false to only move the task (to do, nothing runs) until the user says to start"),
|
||||
.describe("With task_id: true to start the work at once, only when the user asked for it; left out it only moves (to do, nothing runs)"),
|
||||
title: z.string().min(1).max(80).optional(),
|
||||
instructions: z.string().min(1).max(8000).optional(),
|
||||
workspace_id: z
|
||||
@@ -198,7 +199,7 @@ export default function delegateTaskTool({
|
||||
handed_by: requester_name,
|
||||
requested_by_bot_id: requester_id,
|
||||
requested_by_session_id: session_id,
|
||||
start: args.start !== false,
|
||||
start: args.start === true,
|
||||
});
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
|
||||
@@ -37,6 +37,9 @@ mock.module("@/src/functions/backend/db/workspaces/grab-user-workspaces", () =>
|
||||
mock.module("@/src/functions/backend/db/bots/grab-crew-workers", () => ({
|
||||
default: async () => workers,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/chatrooms/chatroom-askable-bots", () => ({
|
||||
default: async () => workers,
|
||||
}));
|
||||
|
||||
const grabBotChatTools = (await import("./grab-bot-chat-tools")).default;
|
||||
|
||||
@@ -66,6 +69,32 @@ async function names({ workspace_id }: { workspace_id: number | null }) {
|
||||
return tools.map((tool) => tool.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same list for a plain worker: no work to hand out, only its own task to
|
||||
* pass on, to a bot it could ask (`chatroomAskableBots`).
|
||||
*/
|
||||
async function workerNames({ workspace_id, allowed = ["hand_over_task"] }: { workspace_id: number | null; allowed?: string[] }) {
|
||||
const worker = {
|
||||
bot_types: [],
|
||||
is_coordinator: false,
|
||||
admin_workspace_ids: [],
|
||||
is_workspace_admin: false,
|
||||
can: (permission: string) => allowed.includes(permission),
|
||||
};
|
||||
|
||||
const tools = await grabBotChatTools({
|
||||
bot: { id: 5, kind: "worker", name: "SEO Expert" },
|
||||
powers: worker,
|
||||
user_id: 1,
|
||||
computers: [],
|
||||
session_id: 43,
|
||||
workspace_id,
|
||||
onPropose: () => {},
|
||||
});
|
||||
|
||||
return tools.map((tool) => tool.name);
|
||||
}
|
||||
|
||||
describe("grabBotChatTools", () => {
|
||||
test("the coordinator in a workspace reaches the install's skills, servers and tools", async () => {
|
||||
workers = [{ id: 5, name: "A worker", kind: "worker" }];
|
||||
@@ -93,4 +122,23 @@ describe("grabBotChatTools", () => {
|
||||
expect(list).toContain("list_extensions");
|
||||
expect(list).toContain("propose_skill");
|
||||
});
|
||||
|
||||
test("a worker gets no work to hand out, only its own task to pass on", async () => {
|
||||
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
|
||||
|
||||
const list = await workerNames({ workspace_id: 11 });
|
||||
|
||||
expect(list).toContain("hand_over_task");
|
||||
expect(list).not.toContain("delegate_task");
|
||||
expect(list).not.toContain("manage_workspace_tasks");
|
||||
});
|
||||
|
||||
test("a worker whose types don't allow it gets neither", async () => {
|
||||
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
|
||||
|
||||
const list = await workerNames({ workspace_id: 11, allowed: [] });
|
||||
|
||||
expect(list).not.toContain("hand_over_task");
|
||||
expect(list).not.toContain("delegate_task");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,6 +24,8 @@ import updateWorkspaceTool from "./update-workspace-tool";
|
||||
import listWorkspacePeopleTool from "./list-workspace-people-tool";
|
||||
import setUserWorkspaceRoleTool from "./set-user-workspace-role-tool";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
import chatroomAskableBots from "@/src/functions/backend/db/chatrooms/chatroom-askable-bots";
|
||||
import handOverTaskTool from "./hand-over-task-tool";
|
||||
import setWorkspaceInstructionsTool from "./set-workspace-instructions-tool";
|
||||
import startTaskTool from "./start-task-tool";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
@@ -111,9 +113,10 @@ type Params = {
|
||||
* workspace's crew (a bot's core prompt is asked for from wherever the
|
||||
* user is), plus set_bot_type to make a worker a workspace's admin. A
|
||||
* workspace admin, in the workspace it leads, gets
|
||||
* `grabWorkspaceAdminTools`. Every gate reads the bot's types (`powers`),
|
||||
* never `bots.kind`. Anything else on a computer goes through a task,
|
||||
* never mid-reply.
|
||||
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
|
||||
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
|
||||
* a computer goes through a task, never mid-reply.
|
||||
*/
|
||||
export default async function grabBotChatTools({
|
||||
bot,
|
||||
@@ -169,12 +172,34 @@ export default async function grabBotChatTools({
|
||||
];
|
||||
|
||||
if (!powers.is_coordinator) {
|
||||
if (!workspace_id || !powers.is_workspace_admin) return tools;
|
||||
if (workspace_id && powers.is_workspace_admin) {
|
||||
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
|
||||
|
||||
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
|
||||
onWorkspaceAdmin?.(admin);
|
||||
tools.push(...admin.tools);
|
||||
|
||||
onWorkspaceAdmin?.(admin);
|
||||
tools.push(...admin.tools);
|
||||
return tools;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only what it already has goes: the bots it may hand to are the
|
||||
* ones it could ask for this user, read again when it does.
|
||||
*/
|
||||
if (session_id && powers.can("hand_over_task")) {
|
||||
const workers = await chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id });
|
||||
|
||||
tools.push(
|
||||
handOverTaskTool({
|
||||
user_id,
|
||||
bot,
|
||||
session_id,
|
||||
powers,
|
||||
workers,
|
||||
grabTargets: () => chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id }),
|
||||
onTask,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return tools;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
|
||||
/**
|
||||
* What `grabRunTask` answers: the task it would act on.
|
||||
*/
|
||||
let task: BUN_SQLITE_COBBLE_TASKS = {
|
||||
id: 43,
|
||||
title: "Cut the LCP on the homepage",
|
||||
bot_id: 2,
|
||||
workspace_id: 2,
|
||||
status: "todo",
|
||||
} as BUN_SQLITE_COBBLE_TASKS;
|
||||
|
||||
/**
|
||||
* What `handOverTask` answers, and with which arguments it was called: a
|
||||
* worker's hand-over has to carry the bot that had the task and the session
|
||||
* the result is reported back to.
|
||||
*/
|
||||
let handed: Record<string, unknown> = {};
|
||||
let handedArgs: Record<string, unknown> | null = null;
|
||||
|
||||
mock.module("@/src/functions/backend/db/tasks/grab-run-task", () => ({
|
||||
default: async () => task,
|
||||
}));
|
||||
|
||||
mock.module("@/src/functions/backend/db/tasks/hand-over-task", () => ({
|
||||
default: async (args: Record<string, unknown>) => {
|
||||
handedArgs = args;
|
||||
return handed;
|
||||
},
|
||||
}));
|
||||
|
||||
const handOverTaskTool = (await import("./hand-over-task-tool")).default;
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const bot = { id: 2, name: "SEO Expert", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
|
||||
const engineer = { id: 6, name: "Software Engineer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
|
||||
const designer = { id: 3, name: "Graphic Designer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
|
||||
|
||||
const powers = {
|
||||
bot_types: [],
|
||||
is_coordinator: false,
|
||||
admin_workspace_ids: [],
|
||||
is_workspace_admin: false,
|
||||
can: (permission: string) => permission == "hand_over_task",
|
||||
} as unknown as BotRunPowers;
|
||||
|
||||
beforeEach(() => {
|
||||
task = { id: 43, title: "Cut the LCP on the homepage", bot_id: 2, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
|
||||
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
|
||||
handedArgs = null;
|
||||
});
|
||||
|
||||
function build({ targets = [engineer, designer], onTask }: { targets?: BUN_SQLITE_COBBLE_BOTS[]; onTask?: (params: { task_id: number }) => void } = {}) {
|
||||
return handOverTaskTool({
|
||||
user_id: 1,
|
||||
bot,
|
||||
session_id: 43,
|
||||
powers,
|
||||
workers: targets,
|
||||
grabTargets: async () => targets,
|
||||
onTask,
|
||||
});
|
||||
}
|
||||
|
||||
describe("handOverTaskTool", () => {
|
||||
test("takes a task of its own and one of the bots it can ask", () => {
|
||||
const tool = build();
|
||||
|
||||
expect(tool.name).toBe("hand_over_task");
|
||||
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6 }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6, start: false }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6, start: true }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ bot_id: 6 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("names the crew it can hand to", () => {
|
||||
const tool = build();
|
||||
|
||||
expect(tool.description).toContain("6: Software Engineer; 3: Graphic Designer");
|
||||
});
|
||||
|
||||
test("tells the bot to ask before the task leaves its list, and that a hand-over starts nothing", () => {
|
||||
const tool = build();
|
||||
|
||||
expect(tool.description).toContain("Handing it over never starts it");
|
||||
expect(tool.description).toContain("ask first with ask_user");
|
||||
});
|
||||
|
||||
test("hands the task over with the bot and session to report back to", async () => {
|
||||
const answer = await build().run({ args: { task_id: 43, bot_id: 6, start: true }, signal: new AbortController().signal });
|
||||
|
||||
expect(handedArgs?.task_id).toBe(43);
|
||||
expect(handedArgs?.to_bot_id).toBe(6);
|
||||
expect(handedArgs?.user_id).toBe(1);
|
||||
expect(handedArgs?.handed_by).toBe("SEO Expert");
|
||||
expect(handedArgs?.requested_by_bot_id).toBe(2);
|
||||
expect(handedArgs?.requested_by_session_id).toBe(43);
|
||||
expect(handedArgs?.start).toBe(true);
|
||||
expect(String(answer)).toContain("is with Software Engineer now (job #312)");
|
||||
expect(String(answer)).toContain("it's off your list");
|
||||
expect(String(answer)).toContain("their result is reported back here");
|
||||
});
|
||||
|
||||
test("the same task, not a copy: it reports the new bot's joined note", async () => {
|
||||
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "It joined the workspace." };
|
||||
|
||||
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
|
||||
|
||||
expect(String(answer)).toContain("It joined the workspace.");
|
||||
});
|
||||
|
||||
test("moves it as to do unless the user asked to start it", async () => {
|
||||
handed = { task, job_id: null, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
|
||||
|
||||
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
|
||||
|
||||
expect(handedArgs?.start).toBe(false);
|
||||
expect(String(answer)).toContain("as to do");
|
||||
expect(String(answer)).toContain("Nothing is running");
|
||||
});
|
||||
|
||||
test("an explicit start: false asks for the same move", async () => {
|
||||
handed = { task, job_id: null, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
|
||||
|
||||
const answer = await build().run({ args: { task_id: 43, bot_id: 6, start: false }, signal: new AbortController().signal });
|
||||
|
||||
expect(handedArgs?.start).toBe(false);
|
||||
expect(String(answer)).toContain("as to do");
|
||||
expect(String(answer)).toContain("Nothing is running");
|
||||
});
|
||||
|
||||
test("reports the task it touched, so the message links it", async () => {
|
||||
const touched: number[] = [];
|
||||
|
||||
await build({ onTask: ({ task_id }) => touched.push(task_id) }).run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
|
||||
|
||||
expect(touched).toEqual([43]);
|
||||
});
|
||||
|
||||
test("refuses a task that isn't its own", async () => {
|
||||
task = { id: 44, title: "Someone else's", bot_id: 9, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
|
||||
|
||||
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
|
||||
"isn't on your own list (it's another bot's), so it isn't yours to hand over",
|
||||
);
|
||||
|
||||
expect(handedArgs).toBeNull();
|
||||
});
|
||||
|
||||
test("refuses a workspace-wide task", async () => {
|
||||
task = { id: 44, title: "Everyone's", bot_id: null, workspace_id: 2, status: "todo" } as unknown as BUN_SQLITE_COBBLE_TASKS;
|
||||
|
||||
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow("(it's workspace-wide)");
|
||||
});
|
||||
|
||||
test("refuses a bot it can't ask, and lists the ones it can", async () => {
|
||||
await expect(build().run({ args: { task_id: 43, bot_id: 99 }, signal: new AbortController().signal })).rejects.toThrow(
|
||||
"No bot has id 99 among the ones you can hand to. Bot: 6: Software Engineer; 3: Graphic Designer.",
|
||||
);
|
||||
|
||||
expect(handedArgs).toBeNull();
|
||||
});
|
||||
|
||||
test("with no crew says so", async () => {
|
||||
const tool = build({ targets: [] });
|
||||
|
||||
expect(tool.description).toContain("Crew you can hand to: none.");
|
||||
|
||||
await expect(tool.run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
|
||||
"No bot has id 6 among the ones you can hand to. Bot: none.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { z } from "zod";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
|
||||
import handOverTask from "@/src/functions/backend/db/tasks/hand-over-task";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
/**
|
||||
* The bot passing its own task on: the worker that has it, or a
|
||||
* workspace's admin.
|
||||
*/
|
||||
bot: BUN_SQLITE_COBBLE_BOTS;
|
||||
/**
|
||||
* The session it hands over from: the new bot's result is reported
|
||||
* back there (`relayJobToRequester`).
|
||||
*/
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The run's reach over the task tracker (`grabBotRunPowers`), beside the
|
||||
* check that the task is this bot's own.
|
||||
*/
|
||||
powers: BotRunPowers;
|
||||
/**
|
||||
* The bots it may hand to, for the description (`chatroomAskableBots`).
|
||||
*/
|
||||
workers: BUN_SQLITE_COBBLE_BOTS[];
|
||||
/**
|
||||
* Reads the bots it may hand to when it does, so a bot added mid-run is
|
||||
* there: the ones it could ask (`chatroomAskableBots`).
|
||||
*/
|
||||
grabTargets: () => Promise<BUN_SQLITE_COBBLE_BOTS[]>;
|
||||
/**
|
||||
* Called with the task it hands over, so the message the run posts links
|
||||
* to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
task_id: number;
|
||||
bot_id: number;
|
||||
/**
|
||||
* True only when the user asked for the work to begin now. Left out the
|
||||
* task only moves: it goes to the other bot's list as to do and no job
|
||||
* is queued.
|
||||
*/
|
||||
start?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lets a bot give a task on its own list to another bot (`handOverTask`):
|
||||
* the narrow hand-over of `delegate_task`, for the runs that have no right
|
||||
* to hand out work. It only ever moves a task the run already has, only an
|
||||
* open one, and only to a bot it could ask for the same user, so it can't
|
||||
* create a task for someone else or widen a run's reach. The task keeps its
|
||||
* place (a workspace's stays there) and moves as to do: it never starts the
|
||||
* work unless the user asked for that (`start`), and when they only asked
|
||||
* for the move the bot asks first. The other bot works that same task, and
|
||||
* the result is reported back in this session.
|
||||
*/
|
||||
export default function handOverTaskTool({ user_id, bot, session_id, powers, workers, grabTargets, onTask }: Params): HarnessTool<Args> {
|
||||
const bot_id = bot.id || 0;
|
||||
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
|
||||
|
||||
return {
|
||||
name: "hand_over_task",
|
||||
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_crew; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
|
||||
schema: z.object({
|
||||
task_id: z.number().int().describe("An open task on your own list (list_tasks)"),
|
||||
bot_id: z.number().int(),
|
||||
start: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("true to start the work at once, only when the user asked for it; left out it only moves (to do, nothing runs)"),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const task = await grabRunTask({
|
||||
task_id: args.task_id,
|
||||
bot_id,
|
||||
is_coordinator: powers.is_coordinator,
|
||||
admin_workspace_ids: powers.admin_workspace_ids,
|
||||
});
|
||||
|
||||
/**
|
||||
* A workspace-wide task is nobody's: handing it to one bot would
|
||||
* take it away from the rest of the crew.
|
||||
*/
|
||||
if (Number(task.bot_id || 0) != bot_id) {
|
||||
throw new Error(
|
||||
`Task #${task.id} isn't on your own list (it's ${
|
||||
task.workspace_id && !task.bot_id ? "workspace-wide" : "another bot's"
|
||||
}), so it isn't yours to hand over.`,
|
||||
);
|
||||
}
|
||||
|
||||
const fresh = await grabTargets();
|
||||
|
||||
if (!fresh.some((target) => target.id == args.bot_id)) {
|
||||
throw new Error(
|
||||
`No bot has id ${args.bot_id} among the ones you can hand to. Bot: ${
|
||||
fresh.map((target) => `${target.id}: ${target.name}`).join("; ") || "none"
|
||||
}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const handed = await handOverTask({
|
||||
user_id,
|
||||
task_id: Number(task.id),
|
||||
to_bot_id: args.bot_id,
|
||||
instructions: undefined,
|
||||
handed_by: bot.name || "The bot that had it",
|
||||
requested_by_bot_id: bot_id,
|
||||
requested_by_session_id: session_id,
|
||||
start: args.start === true,
|
||||
});
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
|
||||
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in its own chat";
|
||||
|
||||
if (!handed.job_id) {
|
||||
return `Task #${task.id} "${task.title}" is on ${handed.bot_name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.${handed.joined ? ` ${handed.joined}` : ""}`;
|
||||
}
|
||||
|
||||
return `Task #${task.id} "${task.title}" is with ${handed.bot_name} now (job #${handed.job_id})${where}, marked doing, and it's off your list.${handed.joined} They work that same task; their result is reported back here.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -35,7 +35,14 @@ type Args = {
|
||||
* the answers come back as the user's next message. Once per run, so every
|
||||
* question goes on one card.
|
||||
*/
|
||||
export default function askUserTool({ user_id, bot_id, session_id, workspace_id, in_task, onAsk }: Params): HarnessTool<Args> {
|
||||
export default function askUserTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
in_task,
|
||||
onAsk,
|
||||
}: Params): HarnessTool<Args> {
|
||||
let asked = false;
|
||||
|
||||
return {
|
||||
@@ -46,12 +53,23 @@ export default function askUserTool({ user_id, bot_id, session_id, workspace_id,
|
||||
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
}`,
|
||||
schema: z.object({
|
||||
title: z.string().trim().max(120).optional().describe("A short heading for the card, e.g. \"Before I deploy\""),
|
||||
questions: BotQuestionItemsSchema.describe("The questions, in the order to answer them"),
|
||||
title: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(120)
|
||||
.optional()
|
||||
.describe(
|
||||
'A short heading for the card, e.g. "Before I deploy"',
|
||||
),
|
||||
questions: BotQuestionItemsSchema.describe(
|
||||
"The questions, in the order to answer them",
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (asked) {
|
||||
throw new Error(`You already asked the user in this run. Put every question in one ask_user call, then wait for their answers.`);
|
||||
throw new Error(
|
||||
`You already asked the user in this run. Put every question in one ask_user call, then wait for their answers.`,
|
||||
);
|
||||
}
|
||||
|
||||
const id = await createBotQuestion({
|
||||
|
||||
@@ -28,15 +28,16 @@ type Args = {
|
||||
/**
|
||||
* Offers the user concrete next steps as buttons under the bot's answer.
|
||||
* Clicking one puts it in their input; nothing waits on it, unlike
|
||||
* `ask_user`, so the reply goes on as usual. Once per run, so every
|
||||
* suggestion lands in one row.
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It ends
|
||||
* the reply (`ClosingToolNames`): the buttons belong under the answer, and
|
||||
* a run that kept going would replace that answer with a later line.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
name: "suggest_next_steps",
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and carry on as if they may ignore it. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and put it up in the same turn as the answer it belongs under. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
|
||||
/**
|
||||
* Jobs still running in the room. Closing cancels them, so the tool has to
|
||||
* refuse over one: a coordinator once answered while the Software Engineer
|
||||
* ran the work it had been asked for, the run died with "The chatroom
|
||||
* closed", and the answer said the tasks were picked up.
|
||||
*/
|
||||
let open: { id: number; bot_id: number | null; bot_name: string | null; status: string }[] = [];
|
||||
let closedArgs: Record<string, unknown> | null = null;
|
||||
let closed = true;
|
||||
|
||||
mock.module("@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs", () => ({
|
||||
default: async () => open,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/chatrooms/share-room-files", () => ({
|
||||
default: async ({ answer }: { answer: string }) => answer,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/chatrooms/close-chatroom", () => ({
|
||||
default: async (args: Record<string, unknown>) => {
|
||||
closedArgs = args;
|
||||
|
||||
return closed;
|
||||
},
|
||||
}));
|
||||
|
||||
const answerRequesterTool = (await import("./answer-requester-tool")).default;
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const room = { id: 3, status: "open", requester_bot_id: 2 } as BUN_SQLITE_COBBLE_CHATROOMS;
|
||||
|
||||
beforeEach(() => {
|
||||
open = [];
|
||||
closedArgs = null;
|
||||
closed = true;
|
||||
});
|
||||
|
||||
function build(onClosed?: () => void) {
|
||||
return answerRequesterTool({ chatroom: room, job_id: 300, onClosed });
|
||||
}
|
||||
|
||||
describe("answerRequesterTool", () => {
|
||||
test("answers and closes the room when nothing else runs", async () => {
|
||||
const acted: string[] = [];
|
||||
const answer = await build(() => acted.push("closed")).run({ args: { answer: "The plan." }, signal: new AbortController().signal });
|
||||
|
||||
expect(String(answer)).toContain("The room is closed");
|
||||
expect(closedArgs?.status).toBe("answered");
|
||||
expect(closedArgs?.outcome).toBe("The plan.");
|
||||
expect(closedArgs?.job_id).toBe(300);
|
||||
expect(acted).toEqual(["closed"]);
|
||||
});
|
||||
|
||||
test("refuses while a member job still runs, naming it", async () => {
|
||||
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
|
||||
|
||||
await expect(build().run({ args: { answer: "Done." }, signal: new AbortController().signal })).rejects.toThrow(
|
||||
"Still working here: Software Engineer (run #295, processing). Answering closes the room and cancels that run",
|
||||
);
|
||||
|
||||
expect(closedArgs).toBeNull();
|
||||
});
|
||||
|
||||
test("close_anyway answers over it", async () => {
|
||||
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
|
||||
|
||||
await build().run({ args: { answer: "Not needed after all.", close_anyway: true }, signal: new AbortController().signal });
|
||||
|
||||
expect(closedArgs?.status).toBe("answered");
|
||||
});
|
||||
|
||||
test("a room already closed is reported, not acted on", async () => {
|
||||
closed = false;
|
||||
|
||||
const acted: string[] = [];
|
||||
|
||||
await expect(build(() => acted.push("closed")).run({ args: { answer: "Late." }, signal: new AbortController().signal })).rejects.toThrow(
|
||||
"This room is already closed.",
|
||||
);
|
||||
|
||||
expect(acted).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
|
||||
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
|
||||
import shareRoomFiles from "@/src/functions/backend/db/chatrooms/share-room-files";
|
||||
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
type Params = {
|
||||
@@ -18,22 +20,38 @@ type Params = {
|
||||
|
||||
type Args = {
|
||||
answer: string;
|
||||
/**
|
||||
* Closes over a job still running in the room, cancelling it.
|
||||
*/
|
||||
close_anyway?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The coordinator sends the answer back to the bot that asked, closing the
|
||||
* room as answered (`closeChatroom`). Files it names that the asker can't
|
||||
* read are copied to it first and their refs pointed at the copies
|
||||
* (`shareRoomFiles`).
|
||||
* (`shareRoomFiles`). While a member's job still runs it refuses, unless
|
||||
* `close_anyway` says the answer doesn't depend on it: closing cancels that
|
||||
* job and the work with it.
|
||||
*/
|
||||
export default function answerRequesterTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "answer_requester",
|
||||
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown.`,
|
||||
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown. Closing cancels whatever still runs in the room, so while a bot is working this refuses: read where it stands first, or pass close_anyway when the answer doesn't depend on its work.`,
|
||||
schema: z.object({
|
||||
answer: z.string().trim().min(1).max(12000),
|
||||
close_anyway: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("Close over a run still working here, cancelling it: only when the answer doesn't depend on it"),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
|
||||
|
||||
if (open.length && !args.close_anyway) {
|
||||
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Answering" }));
|
||||
}
|
||||
|
||||
const outcome = await shareRoomFiles({ chatroom, answer: args.answer });
|
||||
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "answered", outcome, job_id });
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
|
||||
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
|
||||
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
type Params = {
|
||||
@@ -17,20 +19,35 @@ type Params = {
|
||||
|
||||
type Args = {
|
||||
reason: string;
|
||||
/**
|
||||
* Closes over a job still running in the room, cancelling it.
|
||||
*/
|
||||
close_anyway?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The coordinator turns the request down, telling the bot that asked why,
|
||||
* and closes the room as refused (`closeChatroom`).
|
||||
* and closes the room as refused (`closeChatroom`). While a member's job
|
||||
* still runs it refuses, unless `close_anyway` (closing cancels it).
|
||||
*/
|
||||
export default function refuseRequestTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "refuse_request",
|
||||
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it.`,
|
||||
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it. Closing cancels whatever still runs in the room, so while a bot is working this refuses: pass close_anyway when the refusal doesn't depend on its work.`,
|
||||
schema: z.object({
|
||||
reason: z.string().trim().min(1).max(4000),
|
||||
close_anyway: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("Close over a run still working here, cancelling it: only when the refusal doesn't depend on it"),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
|
||||
|
||||
if (open.length && !args.close_anyway) {
|
||||
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Turning it down" }));
|
||||
}
|
||||
|
||||
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "refused", outcome: args.reason, job_id });
|
||||
|
||||
if (!closed) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Tools a run ends on: they put a card under the answer and expect nothing
|
||||
* after them. `ask_user` waits for the user's answer, and
|
||||
* `suggest_next_steps` is offered when the work is done, so a turn that
|
||||
* writes the reply and asks, or offers what comes next, has said everything
|
||||
* it has to say.
|
||||
*
|
||||
* `runTextLoop` reads this to end the run on that turn, because the reply is
|
||||
* only the run's last message. A run that went on after answering sent
|
||||
* whatever it wrote last instead: a bot wrote out the PR links the user
|
||||
* asked for, then called `list_tasks` (which `TaskReminderNote` told it to
|
||||
* do after answering), and the user got the short "still open" line with no
|
||||
* links in it (Nov 2026).
|
||||
*/
|
||||
export const ClosingToolNames: readonly string[] = ["ask_user", "suggest_next_steps"];
|
||||
|
||||
/**
|
||||
* Whether a call to this tool ends the run when it carries the answer.
|
||||
*/
|
||||
export default function isClosingTool({ name }: { name: string }) {
|
||||
return ClosingToolNames.includes(name);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import commandTimeoutSeconds from "./command-timeout";
|
||||
|
||||
describe("commandTimeoutSeconds", () => {
|
||||
test("has no limit when nothing is asked and the install sets none", () => {
|
||||
expect(commandTimeoutSeconds({ max: 0 })).toBeNull();
|
||||
});
|
||||
|
||||
test("a bot's own timeout still applies with no install limit", () => {
|
||||
expect(commandTimeoutSeconds({ asked: 3600, max: 0 })).toBe(3600);
|
||||
});
|
||||
|
||||
test("rounds a bot's timeout up to whole seconds, at least one", () => {
|
||||
expect(commandTimeoutSeconds({ asked: 0.2, max: 0 })).toBe(1);
|
||||
expect(commandTimeoutSeconds({ asked: 12.1, max: 0 })).toBe(13);
|
||||
});
|
||||
|
||||
test("an install limit applies when the bot names none", () => {
|
||||
expect(commandTimeoutSeconds({ max: 270 })).toBe(270);
|
||||
});
|
||||
|
||||
test("an install limit caps what the bot asks for", () => {
|
||||
expect(commandTimeoutSeconds({ asked: 600, max: 270 })).toBe(270);
|
||||
expect(commandTimeoutSeconds({ asked: 60, max: 270 })).toBe(60);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* How long a `computer_bash` call may run: the bot's own `timeout` when it
|
||||
* names one, else the install's limit (`AppData.ComputerCommandMaxSeconds`,
|
||||
* 0 for none). `null` means the command runs until it ends, the run is
|
||||
* stopped or its job ends.
|
||||
*/
|
||||
export default function commandTimeoutSeconds({ asked, max }: { asked?: number; max: number }): number | null {
|
||||
const asked_seconds = asked ? Math.max(1, Math.ceil(asked)) : null;
|
||||
|
||||
if (max <= 0) return asked_seconds;
|
||||
|
||||
return asked_seconds == null ? max : Math.min(max, asked_seconds);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import shellQuote from "@/src/utils/shell-quote";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
import capToolOutput from "./cap-tool-output";
|
||||
import commandTimeoutSeconds from "./command-timeout";
|
||||
import computerDirsShell from "./computer-dirs-shell";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
|
||||
@@ -19,13 +20,18 @@ type Args = {
|
||||
/**
|
||||
* A bash command on the run's computer, from the run's folder (its
|
||||
* `HOME`), with the computer's envs loaded, as the worker's own account
|
||||
* (no sudo) or, for the coordinator, the computer's user (with sudo). Each call is its own shell,
|
||||
* stopped on the computer at its timeout (at most
|
||||
* `AppData.ComputerCommandMaxSeconds`) or when the run is stopped, so a
|
||||
* command that never ends can't block the computer.
|
||||
* (no sudo) or, for the coordinator, the computer's user (with sudo).
|
||||
* Each call is its own shell with no time limit of its own: it runs until
|
||||
* the command ends, the run is stopped, or it reaches the `timeout` the
|
||||
* bot named (`commandTimeoutSeconds`, capped by
|
||||
* `AppData.ComputerCommandMaxSeconds` when that is set), so a long script
|
||||
* is never cut short and nothing is left blocking the computer.
|
||||
*/
|
||||
export default function computerBashTool({ computer, dirs, shell_path, redact }: ComputerToolContext): HarnessTool<Args> {
|
||||
const max = AppData.ComputerCommandMaxSeconds;
|
||||
const timeout_note = max > 0
|
||||
? `Seconds before it is stopped, at most ${max} (${max} when left out).`
|
||||
: "Seconds before it is stopped. Left out, it has no time limit.";
|
||||
|
||||
return {
|
||||
name: "computer_bash",
|
||||
@@ -33,15 +39,20 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
dirs.run_as
|
||||
? `as your own account ${computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).name}, without sudo: other bots' folders and the computer's own services are closed to you. Install Python and Node packages into your folder yourself (pip install --user ..., npm install -g ...: both land in ~/.local, on your PATH); for a system package (apt) or anything else that needs root, ask with request_install`
|
||||
: `as the user gem, with passwordless sudo: install what you need with sudo apt-get update && sudo apt-get install -y ..., or pip install. Worker bots' folders belong to their own accounts, so read or change them with sudo`
|
||||
}). It starts in your folder (${dirs.cwd}, also ~ and $HOME) with your envs set. Every call is a fresh shell (cd and export don't carry over), reads no input (anything waiting for a prompt fails at once: pass -y, a password through its env, and so on) and is stopped after timeout seconds (at most ${max}, ${max} when not given). Start longer work in the background (nohup ... > log 2>&1 &) and check its log in later calls. Output past ${Math.round(AppData.ComputerCommandMaxOutputChars / 1000)}k characters is cut in the middle, so filter it.`,
|
||||
}). It starts in your folder (${dirs.cwd}, also ~ and $HOME) with your envs set. Every call is a fresh shell (cd and export don't carry over), reads no input (anything waiting for a prompt fails at once: pass -y, a password through its env, and so on) and has no time limit${max > 0 ? ` unless you pass timeout seconds (at most ${max})` : ""}: it runs until the command ends, you stop it, or the run ends. Work that must outlive the run goes in the background (nohup ... > log 2>&1 &), checked in later calls. Output past ${Math.round(AppData.ComputerCommandMaxOutputChars / 1000)}k characters is cut in the middle, so filter it.`,
|
||||
/**
|
||||
* The command's own limit is what ends it: the harness's per-tool
|
||||
* deadline would cut a long script at 10 minutes.
|
||||
*/
|
||||
timeout_ms: null,
|
||||
schema: z.object({
|
||||
command: z.string().min(1).max(100_000),
|
||||
cwd: z.string().max(AppData.BotFilePathMaxChars).optional().describe("Where to start, inside your folders"),
|
||||
timeout: z.number().positive().optional().describe(`Seconds, at most ${max}`),
|
||||
timeout: z.number().positive().optional().describe(timeout_note),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const cwd = args.cwd ? resolveComputerPath({ path: args.cwd, dirs }) : null;
|
||||
const seconds = Math.min(max, Math.max(1, Math.ceil(args.timeout || max)));
|
||||
const seconds = commandTimeoutSeconds({ asked: args.timeout, max });
|
||||
|
||||
const result = await runComputerCommand({
|
||||
computer,
|
||||
@@ -51,7 +62,7 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
cwd ? `cd ${shellQuote({ text: cwd })} && ` : "",
|
||||
args.command,
|
||||
].join(""),
|
||||
timeout_ms: seconds * 1000,
|
||||
timeout_ms: seconds == null ? null : seconds * 1000,
|
||||
run_as: dirs.run_as,
|
||||
signal,
|
||||
});
|
||||
@@ -68,7 +79,7 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
return [
|
||||
`Exit code: ${result.exit_code ?? "unknown"}`,
|
||||
output || "(no output)",
|
||||
result.timed_out ? `[Stopped after ${seconds}s: the command timed out. Run long work in the background and check its log.]` : "",
|
||||
result.timed_out ? `[Stopped after ${seconds ?? 0}s: the command timed out. Run long work in the background and check its log.]` : "",
|
||||
result.truncated ? `[The computer kept only the first part of a very long output.]` : "",
|
||||
full || "",
|
||||
]
|
||||
|
||||
@@ -4,13 +4,14 @@ import isRepeatableTool from "./repeatable-tool-names";
|
||||
/**
|
||||
* What makes two calls the same call: the tool and its arguments, whatever
|
||||
* order the model wrote their keys in (a model re-reads a file it read
|
||||
* before with the same fields in another order). Null for a tool whose
|
||||
* answer may change, and for arguments that aren't a JSON object, which
|
||||
* `runToolCall` turns down anyway.
|
||||
* before with the same fields in another order). Null for arguments that
|
||||
* aren't a JSON object, which `runToolCall` turns down anyway.
|
||||
*
|
||||
* Every tool has one, not only the reads: a failing call repeated word for
|
||||
* word is answered from its failure (`runTextLoop`), since it fails the
|
||||
* same way rather than by luck.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
export function toolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
let args: unknown;
|
||||
|
||||
try {
|
||||
@@ -24,6 +25,16 @@ export default function repeatToolCallKey({ call }: { call: HarnessToolCall }):
|
||||
return `${call.name}:${JSON.stringify(sortKeys({ value: args }))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes two reads the same read: null for a tool whose answer may
|
||||
* change (anything with a side effect), which is answered by running it.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
return toolCallKey({ call });
|
||||
}
|
||||
|
||||
/**
|
||||
* The value with every object's keys sorted, so two spellings of the same
|
||||
* arguments compare equal.
|
||||
|
||||
@@ -6,6 +6,7 @@ import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "../harness-error";
|
||||
import unknownToolArgs from "./unknown-tool-args";
|
||||
import unknownToolMessage from "./unknown-tool-message";
|
||||
import toolTimeoutMs from "./tool-timeout-ms";
|
||||
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
|
||||
|
||||
/**
|
||||
@@ -29,6 +30,10 @@ export type ToolCallResult = {
|
||||
* marked `from_tool`, for the turn after the tool results.
|
||||
*/
|
||||
images: HarnessToolImage[];
|
||||
/**
|
||||
* How long the call took, for the debug view's trace.
|
||||
*/
|
||||
duration_ms: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -37,15 +42,18 @@ export type ToolCallResult = {
|
||||
* can correct itself; only cancellation is thrown.
|
||||
*/
|
||||
export default async function runToolCall({ call, tools, signal }: Params): Promise<ToolCallResult> {
|
||||
const started_at = Date.now();
|
||||
const text = await runTool({ call, tools, signal });
|
||||
const duration_ms = Date.now() - started_at;
|
||||
|
||||
if (typeof text == "string") return { text, images: [] };
|
||||
if (typeof text == "string") return { text, images: [], duration_ms };
|
||||
|
||||
return {
|
||||
text: truncate({ text: text.text, name: call.name }),
|
||||
images: text.images
|
||||
.slice(0, AppData.HarnessToolMaxImages)
|
||||
.map((image) => ({ ...image, from_tool: true })),
|
||||
duration_ms,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -81,16 +89,22 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}
|
||||
|
||||
try {
|
||||
const output = await withTimeout({
|
||||
timeout_ms: AppData.HarnessToolTimeoutMs,
|
||||
signal,
|
||||
message: `${call.name} took too long and was stopped.`,
|
||||
task: (tool_signal) =>
|
||||
tool.run({
|
||||
args: parsed ? parsed.data : raw,
|
||||
signal: tool_signal,
|
||||
}),
|
||||
});
|
||||
const args = parsed ? parsed.data : raw;
|
||||
const timeout_ms = toolTimeoutMs({ tool });
|
||||
|
||||
/**
|
||||
* A tool with no deadline (`computer_bash`) runs until it ends, the
|
||||
* run is stopped or its job ends: the caller's signal alone cancels
|
||||
* it, so a long command isn't cut at a tool's own limit.
|
||||
*/
|
||||
const output = timeout_ms == null
|
||||
? await tool.run({ args, signal })
|
||||
: await withTimeout({
|
||||
timeout_ms,
|
||||
signal,
|
||||
message: `${call.name} took too long and was stopped.`,
|
||||
task: (tool_signal) => tool.run({ args, signal: tool_signal }),
|
||||
});
|
||||
|
||||
return typeof output == "string" ? truncate({ text: output, name: call.name }) : output;
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import toolTimeoutMs from "./tool-timeout-ms";
|
||||
import type { HarnessTool } from "../types";
|
||||
|
||||
function tool({ timeout_ms }: { timeout_ms?: number | null }): HarnessTool {
|
||||
return {
|
||||
name: "computer_bash",
|
||||
description: "test",
|
||||
...(timeout_ms === undefined ? {} : { timeout_ms }),
|
||||
run: async () => "done",
|
||||
};
|
||||
}
|
||||
|
||||
describe("toolTimeoutMs", () => {
|
||||
test("a tool with no opinion gets the install's cap", () => {
|
||||
expect(toolTimeoutMs({ tool: tool({}) })).toBe(AppData.HarnessToolTimeoutMs);
|
||||
});
|
||||
|
||||
test("a tool may ask for a larger deadline of its own", () => {
|
||||
expect(toolTimeoutMs({ tool: tool({ timeout_ms: 3_600_000 }) })).toBe(3_600_000);
|
||||
});
|
||||
|
||||
test("a tool may ask for no deadline at all", () => {
|
||||
expect(toolTimeoutMs({ tool: tool({ timeout_ms: null }) })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTool } from "../types";
|
||||
|
||||
/**
|
||||
* One tool call's deadline: the tool's own (`HarnessTool.timeout_ms`) when
|
||||
* it names one, `null` meaning none at all (`computer_bash`: a script may
|
||||
* run for hours), else the install's cap for every tool
|
||||
* (`AppData.HarnessToolTimeoutMs`). Only the run's own cancellation, the
|
||||
* job's deadline or Stop end a call with no deadline.
|
||||
*/
|
||||
export default function toolTimeoutMs({ tool }: { tool: HarnessTool<any> }): number | null {
|
||||
if (tool.timeout_ms === undefined) return AppData.HarnessToolTimeoutMs;
|
||||
|
||||
return tool.timeout_ms;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import isWritingTool, { WritingToolNames } from "./writing-tool-names";
|
||||
|
||||
test("counts the tools that leave something behind", () => {
|
||||
for (const name of ["write_file", "import_file", "computer_edit_file", "update_task", "start_task", "set_picture"]) {
|
||||
expect(isWritingTool({ name })).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("counts none of the tools that only read", () => {
|
||||
for (const name of ["read_file", "list_files", "computer_read_file", "list_tasks", "search_computers", "load_tools"]) {
|
||||
expect(isWritingTool({ name })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves computer_bash out, so a shell-driven run can still be told to land the work", () => {
|
||||
expect(isWritingTool({ name: "computer_bash" })).toBe(false);
|
||||
expect(WritingToolNames.includes("computer_bash")).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Tools that leave something behind: a file written, a record changed, a
|
||||
* graphic or a picture made, work handed on. `runTextLoop` reads this to
|
||||
* tell a run that has produced something from one that has only been
|
||||
* reading, so a run measuring its way through a whole budget is told to
|
||||
* land a piece of the work while there is still room (`commitEarlyNote`).
|
||||
*
|
||||
* `computer_bash` is deliberately not here: it is the one tool that both
|
||||
* reads and writes (a `SELECT` and an `UPDATE` look the same to the
|
||||
* harness), so counting it would let a shell-driven run research its way to
|
||||
* the ceiling and never be told. A run that has already landed work that
|
||||
* way says so in its answer, and the note asks it to.
|
||||
*/
|
||||
export const WritingToolNames: readonly string[] = [
|
||||
"write_file",
|
||||
"import_file",
|
||||
"copy_file",
|
||||
"move_file",
|
||||
"delete_file",
|
||||
"computer_write_file",
|
||||
"computer_edit_file",
|
||||
"make_pdf",
|
||||
"create_graphic",
|
||||
"update_graphic",
|
||||
"set_picture",
|
||||
"transform_image",
|
||||
"generate_image",
|
||||
"generate_video",
|
||||
"create_task",
|
||||
"update_task",
|
||||
"delete_task",
|
||||
"create_schedule",
|
||||
"update_schedule",
|
||||
"delete_schedule",
|
||||
"hand_over_schedule",
|
||||
"hand_over_task",
|
||||
"update_memory",
|
||||
"update_instructions",
|
||||
"set_bot_workspace_instructions",
|
||||
"capture_secret",
|
||||
"request_install",
|
||||
"answer_install_request",
|
||||
"start_task",
|
||||
"delegate_task",
|
||||
"ask_crew",
|
||||
"create_bot",
|
||||
"update_bot",
|
||||
"delete_bot",
|
||||
"create_workspace",
|
||||
"update_workspace",
|
||||
"delete_workspace",
|
||||
"add_bot_to_workspace",
|
||||
"remove_bot_from_workspace",
|
||||
"assign_computer",
|
||||
"set_workspace_computer",
|
||||
"set_bot_type",
|
||||
"set_extension_access",
|
||||
"set_user_workspace_role",
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether a successful call to this tool produced something.
|
||||
*/
|
||||
export default function isWritingTool({ name }: { name: string }) {
|
||||
return WritingToolNames.includes(name);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import capTraceText from "./cap-trace-text";
|
||||
|
||||
describe("capTraceText", () => {
|
||||
test("keeps a text that fits whole", () => {
|
||||
expect(capTraceText({ text: "Saved.", max: 20 })).toBe("Saved.");
|
||||
});
|
||||
|
||||
test("is null when there's nothing to keep", () => {
|
||||
expect(capTraceText({ text: null, max: 20 })).toBeNull();
|
||||
expect(capTraceText({ text: "", max: 20 })).toBeNull();
|
||||
expect(capTraceText({ text: undefined, max: 20 })).toBeNull();
|
||||
});
|
||||
|
||||
test("keeps the start and says how much was cut", () => {
|
||||
const text = "a".repeat(120);
|
||||
|
||||
expect(capTraceText({ text, max: 100 })).toBe(
|
||||
`${"a".repeat(100)}\n[cut: 20 more characters not kept]`,
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps exactly `max` characters without cutting", () => {
|
||||
const text = "b".repeat(40);
|
||||
|
||||
expect(capTraceText({ text, max: 40 })).toBe(text);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
type Params = {
|
||||
text: string | null | undefined;
|
||||
/**
|
||||
* How much of it is kept (`AppData.BotTrace*MaxChars`). A trace is
|
||||
* read, not replayed, so the start is enough.
|
||||
*/
|
||||
max: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One field of a trace, cut to what the debug view keeps of it. Null when
|
||||
* there's nothing to keep.
|
||||
*/
|
||||
export default function capTraceText({ text, max }: Params): string | null {
|
||||
if (!text) return null;
|
||||
|
||||
if (text.length <= max) return text;
|
||||
|
||||
return `${text.slice(0, max)}\n[cut: ${text.length - max} more characters not kept]`;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTrace } from "./types";
|
||||
import prepareTrace from "./prepare-trace";
|
||||
|
||||
describe("prepareTrace", () => {
|
||||
test("keeps a turn's numbers and tool names in its metadata", () => {
|
||||
const metadata = JSON.parse(
|
||||
prepareTrace({
|
||||
trace: {
|
||||
kind: "turn",
|
||||
index: 2,
|
||||
model: "openai/gpt-x",
|
||||
provider: "OpenRouter",
|
||||
text: "On it.",
|
||||
reasoning: "They asked for a report.",
|
||||
tool_calls: [
|
||||
{ name: "write_file", arguments: "{}" },
|
||||
{ name: "list_files", arguments: "{}" },
|
||||
],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 4, cost: 0 },
|
||||
finish_reason: "tool_calls",
|
||||
duration_ms: 1200,
|
||||
},
|
||||
}).metadata || "{}",
|
||||
);
|
||||
|
||||
expect(metadata).toEqual({
|
||||
index: 2,
|
||||
model: "openai/gpt-x",
|
||||
provider: "OpenRouter",
|
||||
finish_reason: "tool_calls",
|
||||
duration_ms: 1200,
|
||||
tools: ["write_file", "list_files"],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 4, cost: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps a turn's answer and reasoning, and no arguments", () => {
|
||||
const prepared = prepareTrace({
|
||||
trace: {
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
model: null,
|
||||
provider: null,
|
||||
text: "Done.",
|
||||
reasoning: "Simple.",
|
||||
tool_calls: [],
|
||||
usage: null,
|
||||
finish_reason: "stop",
|
||||
duration_ms: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(prepared).toMatchObject({
|
||||
kind: "turn",
|
||||
name: null,
|
||||
text: "Done.",
|
||||
reasoning: "Simple.",
|
||||
arguments: null,
|
||||
result: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps whether a tool call failed, and cuts its answer", () => {
|
||||
const long_answer = "x".repeat(AppData.BotTraceResultMaxChars + 10);
|
||||
|
||||
const prepared = prepareTrace({
|
||||
trace: {
|
||||
kind: "tool",
|
||||
index: 1,
|
||||
name: "computer_bash",
|
||||
arguments: `{"command":"ls"}`,
|
||||
result: long_answer,
|
||||
ok: false,
|
||||
images: 0,
|
||||
duration_ms: 40,
|
||||
},
|
||||
});
|
||||
|
||||
expect(JSON.parse(prepared.metadata || "{}")).toEqual({
|
||||
index: 1,
|
||||
ok: false,
|
||||
images: 0,
|
||||
duration_ms: 40,
|
||||
repeat_of: null,
|
||||
});
|
||||
expect(prepared.name).toBe("computer_bash");
|
||||
expect(prepared.result).toContain("[cut: 10 more characters not kept]");
|
||||
expect(prepared.text).toBeNull();
|
||||
expect(prepared.reasoning).toBeNull();
|
||||
});
|
||||
|
||||
test("keeps an event's name and note", () => {
|
||||
const prepared = prepareTrace({
|
||||
trace: { kind: "event", index: 4, name: "steps_low", text: "5 steps left." },
|
||||
});
|
||||
|
||||
expect(prepared).toMatchObject({
|
||||
kind: "event",
|
||||
name: "steps_low",
|
||||
text: "5 steps left.",
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
});
|
||||
expect(JSON.parse(prepared.metadata || "{}")).toEqual({ index: 4 });
|
||||
});
|
||||
|
||||
test("a call the loop skipped says which step answered it", () => {
|
||||
const prepared = prepareTrace({
|
||||
trace: {
|
||||
kind: "tool",
|
||||
index: 3,
|
||||
name: "read_file",
|
||||
arguments: "{}",
|
||||
result: "Already read.",
|
||||
ok: true,
|
||||
images: 0,
|
||||
duration_ms: 0,
|
||||
repeat_of: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(JSON.parse(prepared.metadata || "{}").repeat_of).toBe(1);
|
||||
});
|
||||
|
||||
test("every trace kind carries a fragment of the same shape", () => {
|
||||
const traces: HarnessTrace[] = [
|
||||
{
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
model: null,
|
||||
provider: null,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
tool_calls: [],
|
||||
usage: null,
|
||||
finish_reason: null,
|
||||
duration_ms: 0,
|
||||
},
|
||||
{
|
||||
kind: "tool",
|
||||
index: 0,
|
||||
name: "x",
|
||||
arguments: "",
|
||||
result: "",
|
||||
ok: true,
|
||||
images: 0,
|
||||
duration_ms: 0,
|
||||
},
|
||||
{ kind: "event", index: 0, name: "e", text: null },
|
||||
];
|
||||
|
||||
for (const trace of traces) {
|
||||
const prepared = prepareTrace({ trace });
|
||||
|
||||
expect(Object.keys(prepared).sort()).toEqual([
|
||||
"arguments",
|
||||
"kind",
|
||||
"metadata",
|
||||
"name",
|
||||
"reasoning",
|
||||
"result",
|
||||
"text",
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import capTraceText from "./cap-trace-text";
|
||||
import type { HarnessTrace } from "./types";
|
||||
|
||||
/**
|
||||
* A trace as `bot_job_traces` stores it: whole fields the debug view reads
|
||||
* straight, with only the numbers and names it shows beside them in
|
||||
* `metadata`.
|
||||
*/
|
||||
export type PreparedTrace = {
|
||||
kind: HarnessTrace["kind"];
|
||||
name: string | null;
|
||||
text: string | null;
|
||||
reasoning: string | null;
|
||||
arguments: string | null;
|
||||
result: string | null;
|
||||
metadata: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* One trace, its text cut to the caps the debug view keeps
|
||||
* (`AppData.BotTraceTextMaxChars`, `BotTraceArgumentsMaxChars`,
|
||||
* `BotTraceResultMaxChars`). A turn's tool calls keep their names only:
|
||||
* the tool rows of the same step carry the arguments.
|
||||
*/
|
||||
export default function prepareTrace({ trace }: { trace: HarnessTrace }): PreparedTrace {
|
||||
if (trace.kind == "turn") {
|
||||
return {
|
||||
kind: "turn",
|
||||
name: null,
|
||||
text: capTraceText({ text: trace.text, max: AppData.BotTraceTextMaxChars }),
|
||||
reasoning: capTraceText({ text: trace.reasoning, max: AppData.BotTraceTextMaxChars }),
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: JSON.stringify({
|
||||
index: trace.index,
|
||||
model: trace.model,
|
||||
provider: trace.provider,
|
||||
finish_reason: trace.finish_reason,
|
||||
duration_ms: trace.duration_ms,
|
||||
tools: trace.tool_calls.map((call) => call.name),
|
||||
usage: trace.usage || null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
if (trace.kind == "tool") {
|
||||
return {
|
||||
kind: "tool",
|
||||
name: trace.name,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
arguments: capTraceText({ text: trace.arguments, max: AppData.BotTraceArgumentsMaxChars }),
|
||||
result: capTraceText({ text: trace.result, max: AppData.BotTraceResultMaxChars }),
|
||||
metadata: JSON.stringify({
|
||||
index: trace.index,
|
||||
ok: trace.ok,
|
||||
images: trace.images,
|
||||
duration_ms: trace.duration_ms,
|
||||
repeat_of: trace.repeat_of ?? null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "event",
|
||||
name: trace.name,
|
||||
text: capTraceText({ text: trace.text, max: AppData.BotTraceTextMaxChars }),
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: JSON.stringify({ index: trace.index }),
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user