Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c36f8e3736 | ||
|
|
70ef0e6ae2 | ||
|
|
2a7ea3c76b | ||
|
|
7ffce997ce | ||
|
|
d80899b756 | ||
|
|
3671d9b72e | ||
|
|
78d7f66528 | ||
|
|
09b8269ced | ||
|
|
8b30480ceb | ||
|
|
7356494ff2 | ||
|
|
f08940341b | ||
|
|
915692a9ee | ||
|
|
8b1b7d9c64 | ||
|
|
45556b3b7f | ||
|
|
956a6b9772 |
+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
|
||||
@@ -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
|
||||
|
||||
@@ -87,24 +87,26 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### 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). 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`.
|
||||
- **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,7 +131,7 @@ 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`)
|
||||
|
||||
@@ -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)
|
||||
@@ -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`, `hand_over_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).
|
||||
|
||||
@@ -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.19.1",
|
||||
"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 })) {
|
||||
|
||||
@@ -101,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
|
||||
@@ -466,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>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
@@ -373,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,
|
||||
@@ -417,11 +497,12 @@ 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
|
||||
|
||||
@@ -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";
|
||||
@@ -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),
|
||||
}));
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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,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 }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import type { HarnessTrace } from "./types";
|
||||
import redactTrace from "./redact-trace";
|
||||
|
||||
const secrets = [{ key: "API_KEY", value: "sk-very-secret" }];
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
|
||||
const turn: HarnessTrace = {
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
model: "m",
|
||||
provider: "p",
|
||||
text: "Using sk-very-secret now.",
|
||||
reasoning: "The key is sk-very-secret.",
|
||||
tool_calls: [{ name: "bash", arguments: `{"cmd":"echo sk-very-secret"}` }],
|
||||
usage: null,
|
||||
finish_reason: "tool_calls",
|
||||
duration_ms: 5,
|
||||
};
|
||||
|
||||
describe("redactTrace", () => {
|
||||
test("blanks the secret out of a turn's answer, reasoning and tool calls", () => {
|
||||
const safe = redactTrace({ trace: turn, redact });
|
||||
|
||||
expect(safe).toEqual({
|
||||
...turn,
|
||||
text: "Using [API_KEY] now.",
|
||||
reasoning: "The key is [API_KEY].",
|
||||
tool_calls: [{ name: "bash", arguments: `{"cmd":"echo [API_KEY]"}` }],
|
||||
});
|
||||
});
|
||||
|
||||
test("blanks it out of a tool's arguments and answer", () => {
|
||||
const safe = redactTrace({
|
||||
trace: {
|
||||
kind: "tool",
|
||||
index: 0,
|
||||
name: "computer_bash",
|
||||
arguments: "export KEY=sk-very-secret",
|
||||
result: "sk-very-secret",
|
||||
ok: true,
|
||||
images: 0,
|
||||
duration_ms: 3,
|
||||
},
|
||||
redact,
|
||||
});
|
||||
|
||||
expect(safe).toMatchObject({
|
||||
arguments: "export KEY=[API_KEY]",
|
||||
result: "[API_KEY]",
|
||||
});
|
||||
});
|
||||
|
||||
test("blanks it out of an event's note", () => {
|
||||
expect(
|
||||
redactTrace({
|
||||
trace: { kind: "event", index: 1, name: "incoming", text: "sk-very-secret" },
|
||||
redact,
|
||||
}),
|
||||
).toMatchObject({ text: "[API_KEY]" });
|
||||
});
|
||||
|
||||
test("keeps a turn with no text as it was", () => {
|
||||
expect(
|
||||
redactTrace({
|
||||
trace: { ...turn, text: null, reasoning: null },
|
||||
redact,
|
||||
}),
|
||||
).toMatchObject({ text: null, reasoning: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { HarnessTrace } from "./types";
|
||||
|
||||
type Params = {
|
||||
trace: HarnessTrace;
|
||||
/**
|
||||
* Blanks secret values out of the text (`redactSecrets`). A task run
|
||||
* passes its computer's, which also holds what the bot captured
|
||||
* (`capture_secret`) during this run.
|
||||
*/
|
||||
redact: (text: string) => string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The same trace with every piece of text it carries redacted: a tool's
|
||||
* arguments and answer, a turn's answer and reasoning, an event's note.
|
||||
* The job's own trace is redacted with the run's envs whatever this does
|
||||
* (`insertBotJobTrace`), so this only adds the secrets the run discovered
|
||||
* as it went.
|
||||
*/
|
||||
export default function redactTrace({ trace, redact }: Params): HarnessTrace {
|
||||
if (trace.kind == "turn") {
|
||||
return {
|
||||
...trace,
|
||||
text: trace.text ? redact(trace.text) : trace.text,
|
||||
reasoning: trace.reasoning ? redact(trace.reasoning) : trace.reasoning,
|
||||
tool_calls: trace.tool_calls.map((call) => ({
|
||||
...call,
|
||||
arguments: redact(call.arguments),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (trace.kind == "tool") {
|
||||
return {
|
||||
...trace,
|
||||
arguments: redact(trace.arguments),
|
||||
result: redact(trace.result),
|
||||
};
|
||||
}
|
||||
|
||||
return { ...trace, text: trace.text ? redact(trace.text) : trace.text };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { HarnessUsage } from "../types";
|
||||
|
||||
/**
|
||||
* One model turn as the debug view keeps it: what the model answered, what
|
||||
* it reasoned, the tools it asked for, and what the turn cost.
|
||||
*/
|
||||
export type HarnessTurnTrace = {
|
||||
kind: "turn";
|
||||
index: number;
|
||||
model: string | null;
|
||||
provider: string | null;
|
||||
text: string | null;
|
||||
reasoning: string | null;
|
||||
tool_calls: { name: string; arguments: string }[];
|
||||
usage: HarnessUsage | null;
|
||||
finish_reason: string | null;
|
||||
duration_ms: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One tool call as the debug view keeps it: the arguments the model wrote
|
||||
* and what the tool answered. Both are the model's own text, so both may
|
||||
* hold a secret value: a trace is redacted before it is stored
|
||||
* (`redactTrace`).
|
||||
*/
|
||||
export type HarnessToolTrace = {
|
||||
kind: "tool";
|
||||
index: number;
|
||||
name: string;
|
||||
arguments: string;
|
||||
result: string;
|
||||
ok: boolean;
|
||||
images: number;
|
||||
duration_ms: number;
|
||||
/**
|
||||
* The step this call was answered from instead of being run: the one
|
||||
* whose identical read answered it (`alreadyRanToolNote`), or the one
|
||||
* whose identical failure did (`failedToolCallNote`).
|
||||
*/
|
||||
repeat_of?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Something the loop itself did, that no turn or tool call shows: a
|
||||
* context trim, the wrap up, what the user wrote mid-run, an answer
|
||||
* `review` sent back.
|
||||
*/
|
||||
export type HarnessEventTrace = {
|
||||
kind: "event";
|
||||
index: number;
|
||||
name: string;
|
||||
text: string | null;
|
||||
};
|
||||
|
||||
export type HarnessTrace = HarnessTurnTrace | HarnessToolTrace | HarnessEventTrace;
|
||||
|
||||
/**
|
||||
* Where a run's detailed trace goes (`bot_job_traces`, read by the
|
||||
* conversation's debug view). Best effort: the loop never fails because a
|
||||
* trace couldn't be kept.
|
||||
*/
|
||||
export type HarnessTracer = (trace: HarnessTrace) => Promise<void> | void;
|
||||
@@ -107,6 +107,12 @@ export type HarnessTool<Args = any> = {
|
||||
* definitions would otherwise ride along on every turn.
|
||||
*/
|
||||
deferred?: boolean;
|
||||
/**
|
||||
* This call's deadline, overriding `AppData.HarnessToolTimeoutMs`: a
|
||||
* bigger one for a tool with its own slow work, `null` for none at all
|
||||
* (`computer_bash`, whose command may run for hours).
|
||||
*/
|
||||
timeout_ms?: number | null;
|
||||
run: (params: { args: Args; signal: AbortSignal }) => Promise<HarnessToolOutput>;
|
||||
};
|
||||
|
||||
@@ -229,6 +235,13 @@ export type HarnessChatResult = {
|
||||
tool_calls: HarnessToolCall[];
|
||||
finish_reason?: string;
|
||||
usage?: HarnessUsage;
|
||||
/**
|
||||
* What the model reasoned before answering, when its provider hands it
|
||||
* back (`reasoning`, `reasoning_content`) or it wrote it inline in
|
||||
* `text` (`stripThinkTags`). Only the debug view shows it: never the
|
||||
* bot's answer, history or prompt.
|
||||
*/
|
||||
reasoning?: string | null;
|
||||
};
|
||||
|
||||
export type HarnessAudioInput = {
|
||||
|
||||
@@ -11,6 +11,7 @@ import relayCreatedBots from "./relay-created-bots";
|
||||
import relayCreatedWorkspaces from "./relay-created-workspaces";
|
||||
import relayNewBotMessages from "./relay-new-bot-messages";
|
||||
import relayNewJobUpdates from "./relay-new-job-updates";
|
||||
import relayNewJobTraces from "./relay-new-job-traces";
|
||||
import type { LiveRelayCursor } from "./types";
|
||||
|
||||
/**
|
||||
@@ -27,7 +28,7 @@ export default async function liveRelay() {
|
||||
* A failed read starts the relay from the beginning instead of not
|
||||
* starting it: clients drop what they already have.
|
||||
*/
|
||||
const latest = async (table: "bot_messages" | "bots_queue_updates") => {
|
||||
const latest = async (table: "bot_messages" | "bots_queue_updates" | "bot_job_traces") => {
|
||||
try {
|
||||
return (
|
||||
Number(
|
||||
@@ -50,6 +51,7 @@ export default async function liveRelay() {
|
||||
const cursor: LiveRelayCursor = {
|
||||
message_id: await latest("bot_messages"),
|
||||
update_id: await latest("bots_queue_updates"),
|
||||
trace_id: await latest("bot_job_traces"),
|
||||
bots_at: Date.now(),
|
||||
sessions_at: Date.now(),
|
||||
};
|
||||
@@ -67,6 +69,7 @@ export default async function liveRelay() {
|
||||
|
||||
cursor.message_id = await relayNewBotMessages({ after_id: cursor.message_id, users });
|
||||
cursor.update_id = await relayNewJobUpdates({ after_id: cursor.update_id, users });
|
||||
cursor.trace_id = await relayNewJobTraces({ after_id: cursor.trace_id, users });
|
||||
|
||||
/**
|
||||
* Overlap one interval, so a change written in the same
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotTraceData } from "@/src/types";
|
||||
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
|
||||
|
||||
type Params = {
|
||||
after_id: number;
|
||||
users: Set<string>;
|
||||
};
|
||||
|
||||
type Row = BotTraceData & { user_id: number; id: number };
|
||||
|
||||
/**
|
||||
* Pushes `server:bot-trace` for every session whose job kept a trace entry
|
||||
* newer than `after_id`, to the sockets on this process of the user the
|
||||
* job runs for. Only the job and its session travel: a debug view that's
|
||||
* open reads the entries it doesn't have. Returns the newest id read.
|
||||
*/
|
||||
export default async function relayNewJobTraces({ after_id, users }: Params) {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<Row>({
|
||||
sql: `SELECT MAX(t.id) AS id, t.bots_queue_id AS job_id, t.session_id, s.user_id
|
||||
FROM bot_job_traces t
|
||||
JOIN bot_sessions s ON s.id = t.session_id
|
||||
WHERE t.id > ?
|
||||
GROUP BY t.session_id
|
||||
ORDER BY id ASC
|
||||
LIMIT 500`,
|
||||
values: [after_id],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
for (const { user_id, ...trace } of rows) {
|
||||
if (!users.has(String(user_id))) continue;
|
||||
|
||||
sendToUser({
|
||||
user_id,
|
||||
data: {
|
||||
event: "server:bot-trace",
|
||||
data: {
|
||||
job_id: Number(trace.job_id),
|
||||
session_id: trace.session_id ? Number(trace.session_id) : null,
|
||||
} satisfies BotTraceData,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return Number(rows[rows.length - 1]?.id) || after_id;
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
/**
|
||||
* How far the relay has read: the newest message and job step it pushed,
|
||||
* and when it last looked for changed bots and sessions.
|
||||
* How far the relay has read: the newest message, job step and trace entry
|
||||
* it pushed, and when it last looked for changed bots and sessions.
|
||||
*/
|
||||
export type LiveRelayCursor = {
|
||||
message_id: number;
|
||||
update_id: number;
|
||||
trace_id: number;
|
||||
bots_at: number;
|
||||
sessions_at: number;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
/**
|
||||
* The room the message was posted in, when it came from a chatroom: its
|
||||
* run is read through the room's own access.
|
||||
*/
|
||||
chatroom_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the run behind one message did, in detail: the debug logs tab of
|
||||
* its Details modal. Read when that tab is opened rather than with the
|
||||
* details, since a long run's tool answers are the biggest thing the modal
|
||||
* would carry.
|
||||
*/
|
||||
export default async function fetchMessageTrace({ message_id, chatroom_id }: Params) {
|
||||
return await fetchApi<{ message_id: number; chatroom_id?: number }, APIResponseObject<BotTraceJob[]>>(
|
||||
"/api/admin/bots/message-trace",
|
||||
{ method: "POST", body: { message_id, ...(chatroom_id ? { chatroom_id } : {}) } },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import type { BotTraceData, BotTraceJob } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The session the conversation shows: its runs' traces are what the
|
||||
* debug view lists.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The view is on screen. Nothing is read, and no push is taken, while
|
||||
* it's closed.
|
||||
*/
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* How long after the first push a reload waits, so a run that keeps
|
||||
* tracing through its tools reads once rather than once per step.
|
||||
*/
|
||||
const ReloadGapMs = 500;
|
||||
|
||||
/**
|
||||
* What a conversation's runs did in detail (`bot_job_traces`): read when
|
||||
* the debug view opens and on `server:bot-trace`, which names only the job
|
||||
* and its session, so the view reads the entries it doesn't have.
|
||||
*/
|
||||
export default function useBotTrace({ session_id, open }: Params) {
|
||||
const [jobs, setJobs] = useState<BotTraceJob[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!session_id) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await fetchApi<{}, APIResponseObject<BotTraceJob[]>>(
|
||||
"/api/admin/bots/trace",
|
||||
{ method: "POST", body: { session_id } },
|
||||
).catch(() => null);
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!res?.success) {
|
||||
setError(res?.msg || `Couldn't load the trace.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setJobs(res.singleRes || []);
|
||||
}, [session_id]);
|
||||
|
||||
/**
|
||||
* One reload is enough for everything written while it was waiting.
|
||||
*/
|
||||
const schedule = useCallback(() => {
|
||||
if (timer.current) return;
|
||||
|
||||
timer.current = setTimeout(() => {
|
||||
timer.current = null;
|
||||
load().catch(() => {});
|
||||
}, ReloadGapMs);
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
setJobs([]);
|
||||
load().catch(() => {});
|
||||
}, [open, session_id]);
|
||||
|
||||
useServerEvent({
|
||||
event: "server:bot-trace",
|
||||
onData: (data: BotTraceData) => {
|
||||
if (!open || data?.session_id != session_id) return;
|
||||
|
||||
schedule();
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* A run that ends pushes its message, not a trace: the view reads once
|
||||
* more so its last entries and its status are right.
|
||||
*/
|
||||
useServerEvent({
|
||||
event: "server:bot-message",
|
||||
onData: (data: { session_id?: number } | undefined) => {
|
||||
if (!open || data?.session_id != session_id) return;
|
||||
|
||||
schedule();
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { jobs, loading, error, reload: load };
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from "react";
|
||||
import bubbleOverflows from "../(utils)/bubble-overflow";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The message's text: a different message is measured again and starts
|
||||
* closed.
|
||||
*/
|
||||
text: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a user's own message is taller than the room it shows, and
|
||||
* whether the user opened the rest of it. A pasted prompt can run for
|
||||
* pages; the bubble cuts it, so it no longer pushes the conversation it
|
||||
* belongs to off the screen, and "Read more" opens the whole of it.
|
||||
* Measured in the browser only: the server has no layout, so the first
|
||||
* render shows the text cut and no button.
|
||||
*/
|
||||
export default function useBubbleClamp({ text }: Params) {
|
||||
const content_ref = useRef<HTMLDivElement | null>(null);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [overflows, setOverflows] = useState(false);
|
||||
/** An opened message shows all of its text, so it has nothing to cut. */
|
||||
const open = useRef(false);
|
||||
|
||||
open.current = expanded;
|
||||
|
||||
const measure = useCallback(() => {
|
||||
const element = content_ref.current;
|
||||
|
||||
if (!element || open.current) return;
|
||||
|
||||
setOverflows(
|
||||
bubbleOverflows({
|
||||
scroll_height: element.scrollHeight,
|
||||
client_height: element.clientHeight,
|
||||
}),
|
||||
);
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setExpanded(false);
|
||||
setOverflows(false);
|
||||
}, [text]);
|
||||
|
||||
/**
|
||||
* Measured before the first paint, so the button never lands after the
|
||||
* thread is already on screen, and again when the window (and with it
|
||||
* the bubble's width) changes.
|
||||
*/
|
||||
useLayoutEffect(() => {
|
||||
const element = content_ref.current;
|
||||
|
||||
if (!element) return;
|
||||
|
||||
measure();
|
||||
|
||||
if (typeof ResizeObserver == "undefined") return;
|
||||
|
||||
const observer = new ResizeObserver(measure);
|
||||
|
||||
observer.observe(element);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [measure, text, expanded]);
|
||||
|
||||
return {
|
||||
content_ref: content_ref as RefObject<HTMLDivElement>,
|
||||
expanded,
|
||||
overflows,
|
||||
toggle: useCallback(() => setExpanded((value) => !value), []),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import readDebugOpen from "@/src/functions/frontend/read-debug-open";
|
||||
import rememberDebugOpen from "@/src/functions/frontend/remember-debug-open";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Whose answer it is: the view belongs to the user, not to a bot, so
|
||||
* it stays as they left it in every conversation on this device.
|
||||
*/
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the conversation's debug view is open, remembered per user on
|
||||
* this device (`readDebugOpen`). Read after the first render: the server
|
||||
* has no `localStorage`.
|
||||
*/
|
||||
export default function useDebugOpen({ user_id }: Params) {
|
||||
const [open, setOpenState] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setOpenState(readDebugOpen({ user_id }));
|
||||
}, [user_id]);
|
||||
|
||||
const setOpen = useCallback(
|
||||
(next: boolean) => {
|
||||
setOpenState(next);
|
||||
rememberDebugOpen({ user_id, open: next });
|
||||
},
|
||||
[user_id],
|
||||
);
|
||||
|
||||
return { open, setOpen };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import fetchMessageTrace from "../(functions)/fetch-message-trace";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
/**
|
||||
* Set when the message was posted in a chatroom, so its run is read
|
||||
* through the room's access.
|
||||
*/
|
||||
chatroom_id?: number;
|
||||
/**
|
||||
* Read only once the debug logs tab is open, so the modal's first tab
|
||||
* doesn't wait on a long run's trace.
|
||||
*/
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The trace behind one message (`api/admin/bots/message-trace`), for the
|
||||
* debug logs tab of its Details modal. Read when that tab opens, and kept
|
||||
* while the modal is open.
|
||||
*/
|
||||
export default function useMessageTrace({ message_id, chatroom_id, enabled = true }: Params) {
|
||||
const [jobs, setJobs] = useState<BotTraceJob[]>();
|
||||
const [loading, set_loading] = useState(false);
|
||||
const [error, set_error] = useState<string>();
|
||||
|
||||
const load = useCallback(async () => {
|
||||
set_loading(true);
|
||||
set_error(undefined);
|
||||
|
||||
const res = await fetchMessageTrace({ message_id, chatroom_id }).catch(() => null);
|
||||
|
||||
set_loading(false);
|
||||
|
||||
if (!res?.success || !res.singleRes) {
|
||||
set_error(res?.msg || `Couldn't load this message's debug logs.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setJobs(res.singleRes);
|
||||
}, [message_id, chatroom_id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled) load().catch(() => {});
|
||||
}, [enabled, load]);
|
||||
|
||||
return { jobs, loading, error, reload: load };
|
||||
}
|
||||
@@ -23,15 +23,17 @@ type Params = {
|
||||
/**
|
||||
* Keeps the thread from waiting on a push that never came: every return to
|
||||
* the page (`useRefocus`) reads the session's latest messages and the
|
||||
* bot's face, status line and active task, and while a reply is due it
|
||||
* does so every `AppData.BotReplyCatchUpMs` too. A missed message is
|
||||
* replayed as the `server:bot-message` it would have been, so the thread,
|
||||
* the rail and the unread flag all take it the usual way. The bot's face,
|
||||
* status line and active task are replayed as `server:bot-updated`, so a
|
||||
* reply that ended without a final message (its face push missed) can't
|
||||
* leave the bot thinking or a finished task on screen. Reading it even
|
||||
* when no reply is due is what lets a row stuck on a stale face or task
|
||||
* clear itself without a reload.
|
||||
* bot's face, status line, active task and the step its reply is on, and
|
||||
* while a reply is due it does so every `AppData.BotReplyCatchUpMs` too. A
|
||||
* missed message is replayed as the `server:bot-message` it would have been,
|
||||
* so the thread, the rail and the unread flag all take it the usual way. The
|
||||
* bot's face, status line and active task are replayed as
|
||||
* `server:bot-updated`, so a reply that ended without a final message (its
|
||||
* face push missed) can't leave the bot thinking or a finished task on
|
||||
* screen. The step is replayed as `server:bot-job-update`, so a run whose
|
||||
* steps were pushed while the page slept still shows the one it's on.
|
||||
* Reading it even when no reply is due is what lets a row stuck on a stale
|
||||
* face or task clear itself without a reload.
|
||||
*/
|
||||
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
|
||||
const last_message = useRef(Number(last_message_id) || 0);
|
||||
@@ -66,6 +68,13 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
|
||||
replay({ data: { event: "server:bot-message", data: message } });
|
||||
}
|
||||
|
||||
/**
|
||||
* The step the reply is on now, replayed as the push it would have
|
||||
* been: a row shows the line of the last step it heard of, and a
|
||||
* reload or a socket that dropped heard of none.
|
||||
*/
|
||||
if (res.step?.id) replay({ data: { event: "server:bot-job-update", data: res.step } });
|
||||
|
||||
/**
|
||||
* After the messages, so a reply that ended silently (its last
|
||||
* word an interim one) drops the row once its face moves on.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import isNewerStep from "../(utils)/is-newer-step";
|
||||
|
||||
type Params = {
|
||||
bot_id: number;
|
||||
@@ -14,25 +15,55 @@ type Params = {
|
||||
* it.
|
||||
*/
|
||||
last_message_id?: number | null;
|
||||
/**
|
||||
* The step the server still has for the open reply, read with the
|
||||
* history: a page that just loaded shows what the run is doing at once
|
||||
* rather than only the row's label, waiting for its next push (the
|
||||
* catch-up replays the newer ones).
|
||||
*/
|
||||
seed?: BotJobUpdateData | null;
|
||||
};
|
||||
|
||||
type Step = {
|
||||
id: number;
|
||||
text: string;
|
||||
after_message_id: number | null;
|
||||
/**
|
||||
* The session it was read in: another one's step never shows here.
|
||||
*/
|
||||
session_id: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The latest step of the reply running in the open session (a
|
||||
* `bots_queue_updates` row's text, from `server:bot-job-update` without a
|
||||
* task), so a reply that works through tools shows what it's doing. Only
|
||||
* tool steps: the closing note is the answer itself.
|
||||
* tool steps: the closing note is the answer itself. The steps the server
|
||||
* still holds (the history's, the catch-up's replay) are taken the same
|
||||
* way, and never take the row back a line.
|
||||
*/
|
||||
export default function useReplyProgress({ bot_id, session_id, last_message_id }: Params) {
|
||||
export default function useReplyProgress({
|
||||
bot_id,
|
||||
session_id,
|
||||
last_message_id,
|
||||
seed,
|
||||
}: Params) {
|
||||
const [step, setStep] = useState<Step | null>(null);
|
||||
const last_message = useRef(last_message_id || null);
|
||||
|
||||
last_message.current = last_message_id || null;
|
||||
|
||||
const adopt = useCallback((update: BotJobUpdateData) => {
|
||||
const taken: Step = {
|
||||
id: Number(update.id),
|
||||
text: update.text as string,
|
||||
after_message_id: last_message.current,
|
||||
session_id: Number(update.session_id) || null,
|
||||
};
|
||||
|
||||
setStep((shown) => (isNewerStep({ shown, step: taken }) ? taken : shown));
|
||||
}, []);
|
||||
|
||||
useServerEvent({
|
||||
event: "server:bot-job-update",
|
||||
onData: (update: BotJobUpdateData) => {
|
||||
@@ -45,9 +76,23 @@ export default function useReplyProgress({ bot_id, session_id, last_message_id }
|
||||
if (update.kind == "note") return;
|
||||
if (!session_id || update.session_id != session_id) return;
|
||||
|
||||
setStep({ text: update.text, after_message_id: last_message.current });
|
||||
adopt(update);
|
||||
},
|
||||
});
|
||||
|
||||
return step && step.after_message_id == (last_message_id || null) ? step.text : null;
|
||||
}
|
||||
/**
|
||||
* Read again with the history, so it lands once the thread shows the
|
||||
* messages it belongs after (it's keyed to the last one).
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!seed?.id || !seed.text) return;
|
||||
|
||||
adopt(seed);
|
||||
}, [seed, last_message_id, adopt]);
|
||||
|
||||
return step &&
|
||||
step.session_id == (session_id || null) &&
|
||||
step.after_message_id == (last_message_id || null)
|
||||
? step.text
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import BotThinkingRow from "./bot-thinking-row";
|
||||
|
||||
function bot(overrides: Partial<BotWithLastMessage>): BotWithLastMessage {
|
||||
return {
|
||||
id: 1,
|
||||
name: "Ember",
|
||||
color: "#c2410c",
|
||||
stone: "ember",
|
||||
face: "working",
|
||||
...overrides,
|
||||
} as BotWithLastMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The row under the thread: its label, and the step of the work it shows.
|
||||
* The reply's step is the one a reload has to bring back, or the row sits
|
||||
* on its label until the run's next push.
|
||||
*/
|
||||
describe("BotThinkingRow", () => {
|
||||
test("a reply owed here shows the step it's on", () => {
|
||||
const html = renderToString(
|
||||
<BotThinkingRow bot={bot({})} awaiting_reply reply_progress="Reading the invoice" />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Ember is thinking");
|
||||
expect(html).toContain("Reading the invoice");
|
||||
});
|
||||
|
||||
test("a task shows the step it's on", () => {
|
||||
const html = renderToString(
|
||||
<BotThinkingRow
|
||||
bot={bot({ status_line: "Working on a task" })}
|
||||
has_task
|
||||
progress="Using sandbox_execute_bash"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Ember is working");
|
||||
expect(html).toContain("Using sandbox_execute_bash");
|
||||
});
|
||||
|
||||
test("no step yet shows the label alone", () => {
|
||||
const html = renderToString(<BotThinkingRow bot={bot({})} awaiting_reply />);
|
||||
|
||||
expect(html).toContain("Ember is thinking");
|
||||
expect(html).not.toContain("Reading the invoice");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { lazy, Suspense } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Bug } from "lucide-react";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import { BotGettingMessageStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
@@ -8,6 +12,12 @@ import type { BotWithLastMessage } from "@/src/types";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
|
||||
/**
|
||||
* The debug strip is its own chunk: most conversations never open it, and
|
||||
* the page's first load is what the bundle budget is about.
|
||||
*/
|
||||
const TracePanel = lazy(() => import("./trace-panel"));
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
/**
|
||||
@@ -31,6 +41,19 @@ type Props = {
|
||||
* This session has an active task.
|
||||
*/
|
||||
has_task?: boolean;
|
||||
/**
|
||||
* The session's id: the debug logs read the run it's working on.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The debug logs are open under the row. The conversation keeps that,
|
||||
* remembered per user.
|
||||
*/
|
||||
debug_open?: boolean;
|
||||
/**
|
||||
* Shows or hides the debug logs under the row.
|
||||
*/
|
||||
on_toggle_debug?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -41,7 +64,8 @@ type Props = {
|
||||
* reply shows from the thread alone: every user message queues one, so while
|
||||
* the user has the last word a reply is due here, even while the bot works
|
||||
* elsewhere. Only the waits (for a model, for its computer) come from the
|
||||
* face. While it shows, a stop button pulls the plug on the bot's work.
|
||||
* face. While it shows, a stop button pulls the plug on the bot's work, and
|
||||
* a bug button opens the run's debug logs under it (`TracePanel`).
|
||||
*/
|
||||
export default function BotThinkingRow({
|
||||
bot,
|
||||
@@ -50,6 +74,9 @@ export default function BotThinkingRow({
|
||||
awaiting_reply,
|
||||
receiving,
|
||||
has_task,
|
||||
session_id,
|
||||
debug_open,
|
||||
on_toggle_debug,
|
||||
}: Props) {
|
||||
const name = bot.name || "The bot";
|
||||
const { waiting, getting, thinking, working, busy, stoppable } = botBusyState({
|
||||
@@ -71,24 +98,49 @@ export default function BotThinkingRow({
|
||||
const detail = working ? progress : thinking ? reply_progress : null;
|
||||
|
||||
return (
|
||||
<Row role="status" className="w-full gap-3! flex-nowrap items-center">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={waiting ? "asleep" : "working"}
|
||||
size={28}
|
||||
/>
|
||||
<Stack className="min-w-0 gap-0! items-start">
|
||||
<Span className="text-sm leading-5 text-ink-secondary animate-pulse motion-reduce:animate-none">
|
||||
{label}
|
||||
</Span>
|
||||
{detail ? (
|
||||
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
|
||||
{detail}
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
<Row role="status" className="w-full gap-3! flex-nowrap items-center">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={waiting ? "asleep" : "working"}
|
||||
size={28}
|
||||
/>
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
<Span className="text-sm leading-5 text-ink-secondary animate-pulse motion-reduce:animate-none">
|
||||
{label}
|
||||
</Span>
|
||||
{detail ? (
|
||||
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
|
||||
{detail}
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
{on_toggle_debug ? (
|
||||
<Button
|
||||
title={debug_open ? "Hide the debug logs" : "Show the debug logs"}
|
||||
aria-label={debug_open ? "Hide the debug logs" : "Show the debug logs"}
|
||||
aria-pressed={Boolean(debug_open)}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
size="smaller"
|
||||
onClick={on_toggle_debug}
|
||||
className={twMerge(
|
||||
"shrink-0 p-1! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink",
|
||||
debug_open && "bg-sunken text-ink dark:text-ink",
|
||||
)}
|
||||
>
|
||||
<Bug size={14} aria-hidden />
|
||||
</Button>
|
||||
) : null}
|
||||
</Stack>
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
{debug_open && on_toggle_debug ? (
|
||||
<Suspense fallback={null}>
|
||||
<TracePanel session_id={session_id} open={Boolean(debug_open)} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,8 @@ type Props = {
|
||||
* instructions there and making it the admin there, its
|
||||
* settings and, while it works, stopping it. A
|
||||
* row that opens a modal closes the menu first, so the modal never sits
|
||||
* behind an open menu.
|
||||
* behind an open menu. The debug view is what the session's runs did in
|
||||
* detail, beside the thread.
|
||||
*/
|
||||
export default function ConversationHeaderMenu({
|
||||
bot,
|
||||
|
||||
@@ -42,10 +42,10 @@ type Props = {
|
||||
|
||||
/**
|
||||
* 64px header. Under the name, what the bot runs on: its model and the
|
||||
* computer it's on. On the right, one menu holding everything the header
|
||||
* used to show as icons: sessions, a new session, the computer, the models
|
||||
* and the bot's settings. Kept here so a save or a switch shows under the
|
||||
* name at once.
|
||||
* computer it's on. On the right, one menu
|
||||
* holding everything the header used to show as icons: sessions, a new
|
||||
* session, the computer, the models and the bot's settings. Kept here so a
|
||||
* save or a switch shows under the name at once.
|
||||
*/
|
||||
export default function ConversationHeader({
|
||||
bot,
|
||||
@@ -145,7 +145,7 @@ export default function ConversationHeader({
|
||||
</Row>
|
||||
</Stack>
|
||||
|
||||
<Row className="ml-auto shrink-0 flex-nowrap justify-end">
|
||||
<Row className="ml-auto shrink-0 flex-nowrap items-center justify-end gap-1!">
|
||||
<Dropdown
|
||||
position="bottom-right"
|
||||
externalOpen={open_menu}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Check, ClipboardCopy } from "lucide-react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import copyPendingText from "@/src/utils/copy-pending-text";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import messageDebugLogsMarkdown from "../(utils)/message-debug-logs-markdown";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
* The runs behind the message, as the tab already read them.
|
||||
*/
|
||||
jobs: BotTraceJob[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The debug logs tab's "Copy debug logs": puts the message's whole trace on
|
||||
* the clipboard as one markdown document (`messageDebugLogsMarkdown`),
|
||||
* every step it kept included. The row shows a check for a moment, then
|
||||
* goes back.
|
||||
*/
|
||||
export default function CopyDebugLogsButton({ message_id, jobs }: Props) {
|
||||
const [copied, set_copied] = useState(false);
|
||||
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeout.current) clearTimeout(timeout.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const copy = async () => {
|
||||
const text = Promise.resolve(messageDebugLogsMarkdown({ message_id, jobs, now: Date.now() }));
|
||||
|
||||
try {
|
||||
const worked = await copyPendingText({ text });
|
||||
|
||||
if (!worked) {
|
||||
window.alert("Couldn't copy the debug logs to the clipboard.");
|
||||
return;
|
||||
}
|
||||
|
||||
set_copied(true);
|
||||
timeout.current = setTimeout(() => set_copied(false), AppData.CopyConfirmationMs);
|
||||
} catch {
|
||||
window.alert("Couldn't copy the debug logs.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={copied ? "Copied" : "Copy this message's debug logs as markdown"}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={copied ? <Check size={14} aria-hidden /> : <ClipboardCopy size={14} aria-hidden />}
|
||||
disabled={copied}
|
||||
onClick={() => {
|
||||
if (!copied) void copy();
|
||||
}}
|
||||
className="shrink-0 px-2! text-[12px]"
|
||||
>
|
||||
{copied ? "Copied" : "Copy debug logs"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isValidElement, type ReactNode } from "react";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import SunkenCodeBlock from "@/src/components/general/sunken-code-block";
|
||||
|
||||
/**
|
||||
* A fenced code block in a bot message, on the sunken surface with
|
||||
@@ -10,17 +10,5 @@ export default function MarkdownCodeBlock({ children }: { children?: ReactNode }
|
||||
? (children.props as { children?: ReactNode }).children
|
||||
: children;
|
||||
|
||||
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",
|
||||
}}
|
||||
className="font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10"
|
||||
>
|
||||
{code}
|
||||
</CodeBlock>
|
||||
);
|
||||
}
|
||||
return <SunkenCodeBlock>{code}</SunkenCodeBlock>;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import useMessageTrace from "../(hooks)/use-message-trace";
|
||||
import CopyDebugLogsButton from "./copy-debug-logs-button";
|
||||
import TraceJobCard from "./trace-job-card";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
* Set when the message was posted in a chatroom, so its run is read
|
||||
* through the room's access.
|
||||
*/
|
||||
chatroom_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The debug logs tab of a message's Details modal: what the run behind it
|
||||
* did, turn by turn and tool by tool, with the arguments it wrote and the
|
||||
* answers it read. Empty once the trace has been pruned (the app setting
|
||||
* `bot_trace_keep_days`), and for the messages the app writes itself (a
|
||||
* stop, a failure notice), which no run generated.
|
||||
*/
|
||||
export default function MessageDebugLogs({ message_id, chatroom_id }: Props) {
|
||||
const { jobs, loading, error, reload } = useMessageTrace({ message_id, chatroom_id });
|
||||
|
||||
if (error)
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-start">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{error}</Span>
|
||||
<Button
|
||||
title="Read the debug logs again"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
onClick={() => {
|
||||
void reload();
|
||||
}}
|
||||
>
|
||||
Try again
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
if (!jobs)
|
||||
return (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading ? "Reading the run..." : "No debug logs were kept for this message."}
|
||||
</Span>
|
||||
);
|
||||
|
||||
if (!jobs.length)
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
No debug logs were kept for this message. The app writes some messages itself (a stop,
|
||||
a failed run's notice), and a run's logs are deleted after {AppData.BotTraceKeepDays}{" "}
|
||||
days.
|
||||
</Span>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-4! items-stretch">
|
||||
<Row className="w-full flex-nowrap items-center justify-end">
|
||||
<CopyDebugLogsButton message_id={message_id} jobs={jobs} />
|
||||
</Row>
|
||||
<Stack className="w-full gap-6! items-stretch">
|
||||
{jobs.map((job) => (
|
||||
<TraceJobCard key={job.id} job={job} />
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,23 @@
|
||||
import { useState } from "react";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Spacer from "@moduletrace/twui/layout/Spacer";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Info } from "lucide-react";
|
||||
import useMessageDetails from "../(hooks)/use-message-details";
|
||||
import CopyMessageDetailsButton from "./copy-message-details-button";
|
||||
import MessageActionButton from "./message-action-button";
|
||||
import MessageDetailsBody from "./message-details-body";
|
||||
import MessageDetailsTabButton from "./message-details-tab-button";
|
||||
|
||||
/**
|
||||
* Only the modal's second tab needs the logs, and only once it's opened, so
|
||||
* it loads as its own chunk rather than with the conversation.
|
||||
*/
|
||||
const MessageDebugLogs = lazy(() => import("./message-debug-logs"));
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
@@ -28,10 +37,13 @@ type Props = {
|
||||
* The info button under a bot message (in a conversation or a chatroom),
|
||||
* and the modal it opens: which provider and model generated it, the run
|
||||
* behind it, what its tools did, and every model call with its tokens and
|
||||
* cost. Loaded when it opens.
|
||||
* cost - then, under "Debug logs", what the run did step by step (its
|
||||
* turns and what it reasoned, every tool call with its arguments and
|
||||
* answer), which is read only when that tab is opened.
|
||||
*/
|
||||
export default function MessageDetailsModal({ message_id, tool_log, chatroom_id }: Props) {
|
||||
const [open, set_open] = useState(false);
|
||||
const [tab, set_tab] = useState<"details" | "debug">("details");
|
||||
const { details, loading, error } = useMessageDetails({ message_id, enabled: open, chatroom_id });
|
||||
|
||||
return (
|
||||
@@ -44,27 +56,54 @@ export default function MessageDetailsModal({ message_id, tool_log, chatroom_id
|
||||
targetWrapperProps={{ className: "shrink-0" }}
|
||||
open={open}
|
||||
setOpen={set_open}
|
||||
className="max-w-xl bg-paper p-6"
|
||||
className="max-w-2xl bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
|
||||
<CopyMessageDetailsButton message_id={message_id} chatroom_id={chatroom_id} />
|
||||
</Row>
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
How this answer was generated: the provider and model behind it, the settings they were called with, and what it spent.
|
||||
How this answer was generated: the provider and model behind it, the settings they were called with,
|
||||
what it spent, and what its run did step by step.
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
<Stack className="mt-4 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
{details ? (
|
||||
<MessageDetailsBody details={details} tool_log={tool_log} />
|
||||
<Row className="mt-4 w-full gap-2! flex-nowrap items-center">
|
||||
<Row className="gap-0.5! p-0.5 flex-nowrap items-center rounded-default border border-solid border-hairline">
|
||||
<MessageDetailsTabButton
|
||||
label="Details"
|
||||
selected={tab == "details"}
|
||||
onSelect={() => set_tab("details")}
|
||||
/>
|
||||
<MessageDetailsTabButton
|
||||
label="Debug logs"
|
||||
selected={tab == "debug"}
|
||||
onSelect={() => set_tab("debug")}
|
||||
/>
|
||||
</Row>
|
||||
<Spacer />
|
||||
</Row>
|
||||
|
||||
<Divider className="mt-3 w-full border-hairline dark:border-hairline" />
|
||||
|
||||
<Stack className="mt-3 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
{tab == "details" ? (
|
||||
<Stack className="w-full gap-3! items-stretch">
|
||||
<Row className="w-full flex-nowrap items-center justify-end">
|
||||
<CopyMessageDetailsButton message_id={message_id} chatroom_id={chatroom_id} />
|
||||
</Row>
|
||||
{details ? (
|
||||
<MessageDetailsBody details={details} tool_log={tool_log} />
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading || !error ? "Loading details..." : error}
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading || !error ? "Loading details..." : error}
|
||||
</Span>
|
||||
<Suspense fallback={null}>
|
||||
<MessageDebugLogs message_id={message_id} chatroom_id={chatroom_id} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import MessageDetailsTabButton from "./message-details-tab-button";
|
||||
|
||||
/**
|
||||
* The Details modal's tabs: the one showing is filled in ink with on-ink
|
||||
* text (readable in both themes), the other stays quiet.
|
||||
*/
|
||||
describe("MessageDetailsTabButton", () => {
|
||||
test("the selected tab is pressed and filled", () => {
|
||||
const html = renderToString(
|
||||
<MessageDetailsTabButton label="Debug logs" selected onSelect={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Debug logs");
|
||||
expect(html).toContain("bg-ink");
|
||||
expect(html).toContain("text-on-ink");
|
||||
expect(html).toContain('aria-pressed="true"');
|
||||
});
|
||||
|
||||
test("the other tab is quiet until picked", () => {
|
||||
const html = renderToString(
|
||||
<MessageDetailsTabButton label="Details" selected={false} onSelect={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Details");
|
||||
expect(html).not.toContain("text-on-ink");
|
||||
expect(html).toContain('aria-pressed="false"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
selected: boolean;
|
||||
onSelect: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One tab of a message's Details modal: ink-filled while it is the one
|
||||
* showing, quiet otherwise (the way the usage page's range buttons read as
|
||||
* pressed), so the active tab is readable in both themes.
|
||||
*/
|
||||
export default function MessageDetailsTabButton({ label, selected, onSelect }: Props) {
|
||||
return (
|
||||
<Button
|
||||
title={label}
|
||||
type="button"
|
||||
size="small"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
aria-pressed={selected}
|
||||
onClick={() => {
|
||||
if (!selected) onSelect();
|
||||
}}
|
||||
className={twMerge(
|
||||
"px-2.5! py-1! text-[12px]! rounded-default-xs",
|
||||
selected
|
||||
? "bg-ink dark:bg-ink hover:bg-ink dark:hover:bg-ink text-on-ink dark:text-on-ink cursor-default"
|
||||
: "text-ink-secondary dark:text-ink-secondary hover:bg-ink/5 dark:hover:bg-ink/5 hover:text-ink dark:hover:text-ink",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,19 @@ type Props = {
|
||||
* that doesn't wake the bot.
|
||||
*/
|
||||
no_reply_due?: boolean;
|
||||
/**
|
||||
* The session shown: the debug logs read the run it's working on.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The debug logs under the thinking row, streaming what the run does.
|
||||
* The conversation keeps it, remembered per user.
|
||||
*/
|
||||
debug_open?: boolean;
|
||||
/**
|
||||
* Shows or hides the debug logs under the thinking row.
|
||||
*/
|
||||
on_toggle_debug?: () => void;
|
||||
/**
|
||||
* Shown after the messages, or in the middle of an empty thread, e.g.
|
||||
* that the bot has no model to answer with.
|
||||
@@ -98,6 +111,9 @@ export default function MessageThread({
|
||||
progress,
|
||||
reply_progress,
|
||||
receiving,
|
||||
session_id,
|
||||
debug_open,
|
||||
on_toggle_debug,
|
||||
has_task,
|
||||
moved_on,
|
||||
no_reply_due,
|
||||
@@ -171,6 +187,9 @@ export default function MessageThread({
|
||||
}
|
||||
receiving={receiving}
|
||||
has_task={has_task}
|
||||
session_id={session_id}
|
||||
debug_open={debug_open}
|
||||
on_toggle_debug={on_toggle_debug}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useContext } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { CircleStop } from "lucide-react";
|
||||
import { BotStopButtonLabel } from "@/src/dict/bot-queue-dict";
|
||||
import { StopBotContext } from "../(data)/stop-bot-context";
|
||||
@@ -56,6 +57,11 @@ export default function StopBotButton({ bot_name, menu, disabled }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* In the thinking row it's an icon beside the debug logs toggle, so the
|
||||
* row keeps its width for the line the bot is on; the menu still names
|
||||
* it.
|
||||
*/
|
||||
return (
|
||||
<Button
|
||||
title={title}
|
||||
@@ -67,13 +73,15 @@ export default function StopBotButton({ bot_name, menu, disabled }: Props) {
|
||||
disabled={off}
|
||||
loading={stopping}
|
||||
loadingIconSize="small"
|
||||
beforeIcon={<CircleStop size={14} aria-hidden />}
|
||||
onClick={() => {
|
||||
void stop();
|
||||
}}
|
||||
className="shrink-0 text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
|
||||
className={twMerge(
|
||||
"shrink-0 p-1! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink",
|
||||
off && "opacity-40 cursor-not-allowed",
|
||||
)}
|
||||
>
|
||||
{BotStopButtonLabel}
|
||||
<CircleStop size={14} aria-hidden />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { TracePreviewChars } from "../(utils)/trace-entry-view";
|
||||
import TraceBlock from "./trace-block";
|
||||
|
||||
/**
|
||||
* A trace block is read inside the Details modal and the debug strip, on
|
||||
* whichever theme the user has. Code used to come out of twui's own dark
|
||||
* block (a fixed `#28272b`), which left dark-on-dark text in light mode and
|
||||
* set the block larger than the log around it.
|
||||
*/
|
||||
describe("TraceBlock", () => {
|
||||
test("code sits on the theme's sunken surface, never twui's dark block", () => {
|
||||
const html = renderToString(<TraceBlock label="What it was sent" kind="code" text={'{"command":"ls"}'} />);
|
||||
|
||||
expect(html).toContain("var(--color-sunken)");
|
||||
expect(html).not.toContain("#28272b");
|
||||
expect(html).toContain("text-ink");
|
||||
});
|
||||
|
||||
test("code and prose share the log's size", () => {
|
||||
const code = renderToString(<TraceBlock kind="code" text={"ls -la"} />);
|
||||
const prose = renderToString(<TraceBlock text="Two tabs are open." />);
|
||||
|
||||
expect(code).toContain("text-[13px]");
|
||||
expect(code).toContain("leading-5");
|
||||
expect(prose).toContain("text-[13px]");
|
||||
expect(prose).toContain("leading-5");
|
||||
});
|
||||
|
||||
test("a long text is cut until it is opened", () => {
|
||||
const text = `start ${"x".repeat(TracePreviewChars)}end`;
|
||||
|
||||
const cut = renderToString(<TraceBlock kind="code" text={text} />);
|
||||
const whole = renderToString(<TraceBlock kind="code" text="short" />);
|
||||
|
||||
expect(cut).toContain("start");
|
||||
expect(cut).not.toContain("end");
|
||||
expect(cut).toContain(`Show all ${text.length.toLocaleString()} characters`);
|
||||
expect(whole).not.toContain("Show all");
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user