Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bd749428e | ||
|
|
cd6702de55 | ||
|
|
1a6ae71286 | ||
|
|
7cc881f1da | ||
|
|
b717220bc3 | ||
|
|
6e153d311e | ||
|
|
6532abc715 | ||
|
|
be4eb13a7c | ||
|
|
86d171729f |
@@ -90,7 +90,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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.
|
||||
- **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 (cookie `cobble_last_visited_bot_id`, never a workspace conversation) 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. `/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.
|
||||
- **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). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
|
||||
@@ -99,6 +99,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. 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.
|
||||
@@ -115,11 +116,11 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last.
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
|
||||
### Live updates
|
||||
|
||||
@@ -127,7 +128,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
|
||||
|
||||
### Chatrooms (`chatrooms`)
|
||||
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions; their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
|
||||
### Workspaces
|
||||
|
||||
@@ -158,7 +159,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
|
||||
|
||||
### Tasks (the to-do tracker)
|
||||
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
|
||||
### Envs
|
||||
|
||||
@@ -210,9 +211,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`.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`), trims old tool output to fit context. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`; a long run is told once, `AppData.HarnessStepsLowWarning` steps before the wrap up, to save its report, since the wrap up has no tools) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **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). 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).
|
||||
|
||||
@@ -4289,6 +4289,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
fieldName: "cached_tokens",
|
||||
fieldDescription: `Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it`,
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
fieldName: "completion_tokens",
|
||||
fieldDescription: `Tokens written back: the answer, its tool calls and its reasoning`,
|
||||
|
||||
@@ -2638,6 +2638,10 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
|
||||
* Tokens sent: the prompt, the system instructions and the tool results
|
||||
*/
|
||||
prompt_tokens?: number | "";
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it
|
||||
*/
|
||||
cached_tokens?: number | "";
|
||||
/**
|
||||
* Tokens written back: the answer, its tool calls and its reasoning
|
||||
*/
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.15.3",
|
||||
"version": "0.16.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import botMessagesToHarness from "./bot-messages-to-harness";
|
||||
import loadAttachmentParts from "./load-attachment-parts";
|
||||
|
||||
type Params = {
|
||||
messages: BotMessageWithAttachments[];
|
||||
/**
|
||||
* Whose conversation it is: the refs in the user's messages are named
|
||||
* as that user sees them.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A conversation's messages as a run reads them: with the files of each
|
||||
* (`loadAttachmentParts`) and the names of the bots, workspaces and other
|
||||
* refs the user's messages point at. Replies and task runs read the same
|
||||
* way.
|
||||
*/
|
||||
export default async function messagesToTurns({ messages, user_id }: Params): Promise<HarnessMessage[]> {
|
||||
return botMessagesToHarness({
|
||||
messages,
|
||||
parts: await loadAttachmentParts({ messages }),
|
||||
refs: await grabMessageRefNames({
|
||||
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
|
||||
user_id,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -168,7 +168,7 @@ export default async function processBotJob({
|
||||
* The face changes once the job really starts, after any wait for
|
||||
* its computer.
|
||||
*/
|
||||
const run = async () => {
|
||||
const run = async ({ computer_shared }: { computer_shared?: boolean } = {}) => {
|
||||
await setFace({
|
||||
face: "working",
|
||||
status_line:
|
||||
@@ -194,6 +194,7 @@ export default async function processBotJob({
|
||||
job,
|
||||
params,
|
||||
checkpoint: parseJobJson({ text: job.checkpoint }),
|
||||
computer_shared,
|
||||
signal: run_signal,
|
||||
update,
|
||||
report,
|
||||
@@ -203,19 +204,25 @@ export default async function processBotJob({
|
||||
|
||||
/**
|
||||
* A task whose computer is busy says so while it waits, so the
|
||||
* user doesn't see silence.
|
||||
* user doesn't see silence. A chatroom job doesn't wait: the bot
|
||||
* that asked is often the one holding the computer, with a run of
|
||||
* up to an hour, and the room would sit silent until it ends. It
|
||||
* works beside it with the shell and files only (`computer_shared`),
|
||||
* which is all most answers need.
|
||||
*/
|
||||
const runOnComputer = async (computer_id: number) => {
|
||||
if (computer_lock.busy({ key: computer_id })) {
|
||||
if (params.chatroom_id) return await run({ computer_shared: true });
|
||||
|
||||
await setFace({ face: "asleep", status_line: BotComputerBusyStatusLine });
|
||||
}
|
||||
|
||||
return await computer_lock.run({ key: computer_id, task: run });
|
||||
return await computer_lock.run({ key: computer_id, task: () => run() });
|
||||
};
|
||||
|
||||
const outcome =
|
||||
job.kind == "reply"
|
||||
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: run })
|
||||
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: () => run() })
|
||||
: job.computer_id
|
||||
? await runOnComputer(job.computer_id)
|
||||
: await run();
|
||||
|
||||
@@ -17,11 +17,12 @@ import {
|
||||
TaskReminderNote,
|
||||
workspaceAdminNote,
|
||||
WorkspaceLearningNote,
|
||||
openRunsNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
import workspaceAdminsNote from "./workspace-admins-note";
|
||||
import type { WorkspaceAdminTools } from "@/src/harness/tools/bot/grab-workspace-admin-tools";
|
||||
import { grabReplyMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
|
||||
@@ -36,7 +37,8 @@ import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-s
|
||||
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
|
||||
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
|
||||
import grabKnowledgebaseContext from "@/src/harness/tools/knowledgebases/grab-knowledgebase-context";
|
||||
import botMessagesToHarness from "./bot-messages-to-harness";
|
||||
import messagesToTurns from "./messages-to-turns";
|
||||
import grabOpenSessionRuns from "@/src/functions/backend/db/bots-queue/grab-open-session-runs";
|
||||
import composeBrowsersNote from "./compose-browsers-note";
|
||||
import composeComputersNote from "./compose-computers-note";
|
||||
import composeEnvsNote from "./compose-envs-note";
|
||||
@@ -48,8 +50,6 @@ import readPastSessionTool from "@/src/harness/tools/bot/sessions/read-past-sess
|
||||
import { grabBotSessionMaxMessages } from "@/src/functions/backend/db/app-settings/grab-bot-session-max-messages";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import jobSessionId from "@/src/functions/backend/db/bots-queue/job-session-id";
|
||||
import loadAttachmentParts from "./load-attachment-parts";
|
||||
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
|
||||
import withTakeOverRefs from "./with-take-over-refs";
|
||||
import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import hasUnansweredMessage from "./has-unanswered-message";
|
||||
@@ -84,8 +84,9 @@ type Params = BotJobContext & {
|
||||
* Messages the user sends while it works join the run (`incoming`): one
|
||||
* that changes the work changes the answer before it goes out, and one
|
||||
* that's separate can be acknowledged at once (`send_message`) and done
|
||||
* after the current work. The job records the newest
|
||||
* one it read (`markReplyAnswered`). Finishes silently when an earlier
|
||||
* after the current work. Runs open in the session take in what the user
|
||||
* writes too (`openRunsNote`), so a correction to one starts no other.
|
||||
* The job records the newest one it read (`markReplyAnswered`). Finishes silently when an earlier
|
||||
* reply already read everything (`hasUnansweredMessage`). An answer naming
|
||||
* files or tasks that don't exist, or saying work is under way when none
|
||||
* is, is written again once (`reviewBotReply`).
|
||||
@@ -124,16 +125,6 @@ export default async function runBotReply({
|
||||
let seen_id = Math.max(0, ...history.map((message) => Number(message.id)));
|
||||
let answering_id = newestUserMessageId({ messages: history });
|
||||
|
||||
const toTurns = async ({ messages }: { messages: BotMessageWithAttachments[] }) =>
|
||||
botMessagesToHarness({
|
||||
messages,
|
||||
parts: await loadAttachmentParts({ messages }),
|
||||
refs: await grabMessageRefNames({
|
||||
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
|
||||
user_id,
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* What the user wrote since the run last looked.
|
||||
*/
|
||||
@@ -150,7 +141,7 @@ export default async function runBotReply({
|
||||
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
|
||||
answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
|
||||
|
||||
return await toTurns({ messages: fresh });
|
||||
return await messagesToTurns({ messages: fresh, user_id });
|
||||
};
|
||||
|
||||
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
|
||||
@@ -340,6 +331,12 @@ export default async function runBotReply({
|
||||
? workspaceAdminNote({ workspace_name: lead.workspace.name || "this workspace", members: lead.members })
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id });
|
||||
|
||||
/**
|
||||
* The bot's runs open here hear what the user writes: a correction to
|
||||
* one reaches it, so the reply doesn't start another.
|
||||
*/
|
||||
const open_runs = attended ? await grabOpenSessionRuns({ bot_id: bot.id, session_id }) : [];
|
||||
|
||||
try {
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
@@ -369,6 +366,7 @@ export default async function runBotReply({
|
||||
run_kind: browser_run_kind,
|
||||
}),
|
||||
crew_note,
|
||||
openRunsNote({ runs: open_runs }),
|
||||
powers.is_coordinator ? "" : AskCrewNote,
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
@@ -378,7 +376,7 @@ export default async function runBotReply({
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
messages: await toTurns({ messages: history }),
|
||||
messages: await messagesToTurns({ messages: history, user_id }),
|
||||
tools: [
|
||||
...tools,
|
||||
sendMessageTool({ bot_id: bot.id, session_id: Number(session_id), workspace_id }),
|
||||
@@ -426,6 +424,8 @@ export default async function runBotReply({
|
||||
...knowledge.tools,
|
||||
],
|
||||
max_steps: await grabReplyMaxToolSteps(),
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
bot_id: bot.id,
|
||||
workspace_id,
|
||||
signal,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import grabCrewRequests from "@/src/functions/backend/db/chatrooms/grab-crew-requests";
|
||||
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings/grab-skill-limits";
|
||||
import grabWorkspaceAdminTools from "@/src/harness/tools/bot/grab-workspace-admin-tools";
|
||||
@@ -16,9 +17,18 @@ import {
|
||||
TasksNote,
|
||||
TaskRunNote,
|
||||
AskCrewNote,
|
||||
crewRequestsNote,
|
||||
WorkspaceLearningNote,
|
||||
TaskIncomingNote,
|
||||
TaskRedraftNote,
|
||||
TaskWrapUpIncomingNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { grabHarnessMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import {
|
||||
grabContextBudgetTokens,
|
||||
grabHarnessMaxToolSteps,
|
||||
grabRunMaxPromptTokens,
|
||||
grabUnattendedMaxToolSteps,
|
||||
} from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
@@ -52,6 +62,9 @@ import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import ScheduledRunFailedError from "./scheduled-run-failed-error";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
import taskIncoming from "./task-incoming";
|
||||
import pushUserTurn from "@/src/harness/text/push-user-turn";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
|
||||
type Params = BotJobContext & {
|
||||
bot: Pick<BUN_SQLITE_COBBLE_BOTS, "kind"> & { id: number };
|
||||
@@ -72,6 +85,10 @@ type Params = BotJobContext & {
|
||||
* A scheduled run acts on its own (`ScheduledRunNote`), as does a hook
|
||||
* call (`HookRunNote`, its payload only data); one that reports it failed
|
||||
* (`report_run_failed`) throws, so the queue retries it.
|
||||
* A task the user follows takes in what they write in its conversation
|
||||
* from when it was queued (`taskIncoming`): already there at the start,
|
||||
* between steps, past a report not yet out, and by the wrap up. A
|
||||
* correction changes the work; anything else is left to the chat.
|
||||
* Every model turn is reported as a step (`report`).
|
||||
*/
|
||||
export default async function runBotTask({
|
||||
@@ -79,6 +96,7 @@ export default async function runBotTask({
|
||||
user_id,
|
||||
job,
|
||||
params,
|
||||
computer_shared,
|
||||
signal,
|
||||
report,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
@@ -97,6 +115,7 @@ export default async function runBotTask({
|
||||
const computer = job.computer_id
|
||||
? await openComputerTools({
|
||||
computer_id: job.computer_id,
|
||||
browser: !computer_shared,
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
workspace_id,
|
||||
@@ -324,19 +343,50 @@ export default async function runBotTask({
|
||||
|
||||
/**
|
||||
* The install's limit, or less when the brief's writer set a
|
||||
* budget (`start_task` `max_steps`).
|
||||
* budget (`start_task` `max_steps`). A routine run or a hook call,
|
||||
* which nobody watches, gets the smaller unattended limit (never
|
||||
* more than a task's).
|
||||
*/
|
||||
const install_steps = await grabHarnessMaxToolSteps();
|
||||
const task_steps = await grabHarnessMaxToolSteps();
|
||||
const install_steps =
|
||||
scheduled || hooked ? Math.min(task_steps, await grabUnattendedMaxToolSteps()) : task_steps;
|
||||
const budget = Math.floor(Number(params.max_steps) || 0);
|
||||
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
|
||||
|
||||
/**
|
||||
* What the user wrote since the run was queued, for a run they
|
||||
* follow: what's there now goes after the brief.
|
||||
*/
|
||||
const incoming =
|
||||
can_ask && session_id
|
||||
? await taskIncoming({ session_id, queued_at: Number(job.created_at) || Date.now(), user_id })
|
||||
: null;
|
||||
const arrived = (await incoming?.take()) || [];
|
||||
const brief: HarnessMessage = {
|
||||
role: "user",
|
||||
content: composeJobBrief({
|
||||
title: job.title,
|
||||
instructions: job.instructions,
|
||||
params,
|
||||
}),
|
||||
};
|
||||
const opening: HarnessMessage[] = [brief];
|
||||
|
||||
if (arrived.length) {
|
||||
pushUserTurn({ transcript: opening, content: TaskIncomingNote });
|
||||
|
||||
for (const turn of arrived) {
|
||||
if (turn.role == "user") pushUserTurn({ transcript: opening, content: turn.content });
|
||||
}
|
||||
}
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
budget > 0
|
||||
? `This run has at most ${max_steps} steps (model turns), set when it was queued. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
budget > 0 || scheduled || hooked
|
||||
? `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
: "",
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
@@ -358,7 +408,12 @@ export default async function runBotTask({
|
||||
? ""
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
|
||||
powers.is_coordinator || hooked ? "" : AskCrewNote,
|
||||
computer
|
||||
powers.is_coordinator || hooked || params.chatroom_id
|
||||
? ""
|
||||
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
|
||||
computer && computer_shared
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
|
||||
: computer
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
|
||||
: workspace_id
|
||||
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
|
||||
@@ -382,23 +437,26 @@ export default async function runBotTask({
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: composeJobBrief({
|
||||
title: job.title,
|
||||
instructions: job.instructions,
|
||||
params,
|
||||
}),
|
||||
},
|
||||
],
|
||||
messages: opening,
|
||||
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
|
||||
max_steps,
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
bot_id: bot.id,
|
||||
workspace_id,
|
||||
signal,
|
||||
onStep: (step) =>
|
||||
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
|
||||
...(incoming
|
||||
? {
|
||||
incoming: incoming.take,
|
||||
incoming_notes: {
|
||||
working: TaskIncomingNote,
|
||||
redraft: TaskRedraftNote,
|
||||
wrap_up: TaskWrapUpIncomingNote,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
if (failure) {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
|
||||
|
||||
/**
|
||||
* A task run reads what the user wrote in its session after it was
|
||||
* queued. Run against real SQLite.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT, created_at INTEGER)`);
|
||||
db.run(`INSERT INTO bot_messages VALUES
|
||||
(1, 1, 'user', 100),
|
||||
(2, 1, 'bot', 200),
|
||||
(3, 2, 'user', 250),
|
||||
(4, 1, 'user', 300),
|
||||
(5, 1, 'bot', 400)`);
|
||||
|
||||
function baseline({ session_id, queued_at }: { session_id: number; queued_at: number }) {
|
||||
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
|
||||
|
||||
return (db.query(sql).get(...values) as { id: number }).id;
|
||||
}
|
||||
|
||||
describe("taskIncomingBaselineSql", () => {
|
||||
test("is the session's newest message when the run was queued", () => {
|
||||
expect(baseline({ session_id: 1, queued_at: 250 })).toBe(2);
|
||||
expect(baseline({ session_id: 1, queued_at: 300 })).toBe(4);
|
||||
});
|
||||
|
||||
test("ignores other sessions", () => {
|
||||
expect(baseline({ session_id: 2, queued_at: 260 })).toBe(3);
|
||||
expect(baseline({ session_id: 1, queued_at: 260 })).toBe(2);
|
||||
});
|
||||
|
||||
test("is 0 when the session had nothing yet", () => {
|
||||
expect(baseline({ session_id: 1, queued_at: 50 })).toBe(0);
|
||||
expect(baseline({ session_id: 9, queued_at: 500 })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
/**
|
||||
* When the run was queued (`bots_queue.created_at`, ms).
|
||||
*/
|
||||
queued_at: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SQL for the newest message a session had when a run was queued:
|
||||
* what the user writes after it is new to the run, however long it waited
|
||||
* for its computer or how often it was tried. Selects one `id` column, 0
|
||||
* for an empty session.
|
||||
*/
|
||||
export default function taskIncomingBaselineSql({ session_id, queued_at }: Params): SqlCondition {
|
||||
return {
|
||||
sql: `SELECT COALESCE(MAX(id), 0) AS id FROM bot_messages WHERE session_id = ? AND created_at <= ?`,
|
||||
values: [Number(session_id), Number(queued_at)],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
import messagesToTurns from "./messages-to-turns";
|
||||
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
/**
|
||||
* When the run was queued (`bots_queue.created_at`, ms).
|
||||
*/
|
||||
queued_at: number;
|
||||
/**
|
||||
* Whose conversation it is.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the user writes in a task run's conversation, for the run to take
|
||||
* in (`runTextLoop`'s `incoming`): each `take` returns the messages since
|
||||
* the last, starting from when the run was queued. A crew message (a
|
||||
* room's outcome, an install answer) is left to the reply it wakes.
|
||||
*/
|
||||
export default async function taskIncoming({ session_id, queued_at, user_id }: Params) {
|
||||
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
|
||||
const res = await BunSQLite.sql<{ id: number }>({ sql, values });
|
||||
|
||||
let seen_id = Number(res.payload?.[0]?.id) || 0;
|
||||
|
||||
const take = async (): Promise<HarnessMessage[]> => {
|
||||
const fresh = await grabBotMessages({
|
||||
session_id,
|
||||
after_id: seen_id,
|
||||
author: "user",
|
||||
limit: AppData.BotReplyHistoryMessages,
|
||||
});
|
||||
|
||||
if (!fresh.length) return [];
|
||||
|
||||
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
|
||||
|
||||
const from_user = fresh.filter((message) => !isCrewMessage({ message }));
|
||||
|
||||
return from_user.length ? await messagesToTurns({ messages: from_user, user_id }) : [];
|
||||
};
|
||||
|
||||
return { take };
|
||||
}
|
||||
@@ -9,6 +9,12 @@ export type BotJobContext = {
|
||||
* Saved by an earlier attempt, if the job was picked up again.
|
||||
*/
|
||||
checkpoint: Record<string, unknown> | null;
|
||||
/**
|
||||
* The job runs on its computer beside another job that holds it (a
|
||||
* chatroom job, which never waits for a busy computer): it gets the
|
||||
* computer's shell and files, never its browser.
|
||||
*/
|
||||
computer_shared?: boolean;
|
||||
/**
|
||||
* Aborted when the job is cancelled or lost to another handler. Stop
|
||||
* work and return; the result is discarded.
|
||||
|
||||
+92
-3
@@ -302,6 +302,17 @@ export const AppData = {
|
||||
ChatroomMaxCoordinatorTurns: 6,
|
||||
ChatroomMaxDepth: 2,
|
||||
ChatroomMaxOpenPerBot: 3,
|
||||
/**
|
||||
* How far back a run is shown the requests its bot made to the crew
|
||||
* from the same place (`grabCrewRequests`), and how many at most.
|
||||
*/
|
||||
CrewRequestsRecentMs: 6 * 60 * 60 * 1000,
|
||||
CrewRequestsListed: 8,
|
||||
/**
|
||||
* Files a room's answer may have copied over to the bot that asked
|
||||
* (`shareRoomFiles`); refs past it are left as written.
|
||||
*/
|
||||
ChatroomSharedFilesMax: 30,
|
||||
ChatroomCoordinatorMaxToolSteps: 6,
|
||||
ChatroomRailLimit: 8,
|
||||
/**
|
||||
@@ -376,10 +387,10 @@ export const AppData = {
|
||||
HarnessAutoMinScore: 12,
|
||||
HarnessAutoMinSizeB: 20,
|
||||
/**
|
||||
* Models tried per harness call before giving up (pinned plus
|
||||
* automatic fallbacks).
|
||||
* Models tried per harness call before giving up (the pick, its
|
||||
* fallback models, then automatic picks).
|
||||
*/
|
||||
HarnessMaxCandidates: 5,
|
||||
HarnessMaxCandidates: 6,
|
||||
HarnessRequestTimeoutMs: 3 * 60 * 1000,
|
||||
/**
|
||||
* One tool call gives up after this long, whatever the tool is (bot
|
||||
@@ -394,6 +405,22 @@ export const AppData = {
|
||||
*/
|
||||
HarnessCooldownMs: 60 * 1000,
|
||||
HarnessMaxCooldownMs: 24 * 60 * 60 * 1000,
|
||||
/**
|
||||
* How long a model (or a provider, for a bad key or no credits) that
|
||||
* failed is passed over before it is tried again, provider's
|
||||
* `Retry-After` included. The install may save its own
|
||||
* (`harness_model_rest_seconds`, Settings > General), read through
|
||||
* `grabModelRestMs`. One failure once benched the pinned model for an
|
||||
* hour and every reply ran on a weak free model meanwhile.
|
||||
*/
|
||||
HarnessModelRestMs: 2 * 60 * 1000,
|
||||
HarnessModelRestMinSeconds: 10,
|
||||
HarnessModelRestMaxSeconds: 60 * 60,
|
||||
/**
|
||||
* Models the text harness tries, in order, after its pick and before
|
||||
* the automatic free picks (`fallback_model_ids` in its options).
|
||||
*/
|
||||
HarnessTextFallbackModelsMax: 3,
|
||||
/**
|
||||
* Model turns in one text run before it must stop and report. The
|
||||
* install may save its own limit (the `harness_max_tool_steps` setting,
|
||||
@@ -401,10 +428,63 @@ export const AppData = {
|
||||
* through `grabHarnessMaxToolSteps`.
|
||||
*/
|
||||
HarnessMaxToolSteps: 200,
|
||||
/**
|
||||
* Model turns a routine run or a hook call may take: nobody watches
|
||||
* them, and one routine run once spent 39M tokens checking a site. The
|
||||
* install may save its own (`unattended_max_tool_steps`), read through
|
||||
* `grabUnattendedMaxToolSteps`; a brief's own `max_steps` can only
|
||||
* lower it.
|
||||
*/
|
||||
UnattendedMaxToolSteps: 40,
|
||||
/**
|
||||
* Prompt tokens one run may spend in all (every turn resends the
|
||||
* prompt): past it the next turn is the wrap up. A safety net under the
|
||||
* step limit, for runs whose turns are large. The install may save its
|
||||
* own (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
|
||||
*/
|
||||
RunMaxPromptTokens: 4_000_000,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
* output is trimmed, whatever the model's window. Every turn resends
|
||||
* all of it, so a run that only trims at a 1M window pays for its whole
|
||||
* history on every step. The install may save its own
|
||||
* (`harness_context_budget_tokens`), read through
|
||||
* `grabContextBudgetTokens`.
|
||||
*/
|
||||
HarnessContextBudgetTokens: 80_000,
|
||||
/**
|
||||
* The least a saved working context may be: below it a run would trim
|
||||
* the output it is reading right now.
|
||||
*/
|
||||
HarnessContextBudgetMinTokens: 20_000,
|
||||
HarnessContextBudgetMaxTokens: 1_000_000,
|
||||
/**
|
||||
* Run token budgets the settings page accepts.
|
||||
*/
|
||||
RunMaxPromptTokensMin: 100_000,
|
||||
RunMaxPromptTokensMax: 100_000_000,
|
||||
/**
|
||||
* Longest tool result handed back to the model.
|
||||
*/
|
||||
HarnessToolResultMaxChars: 20000,
|
||||
/**
|
||||
* Longest result of a browser tool (`browser_*`, the computer's or a
|
||||
* user's own browser): page snapshots and `browser_evaluate` output
|
||||
* were the heaviest results a run kept resending.
|
||||
*/
|
||||
HarnessBrowserResultMaxChars: 12000,
|
||||
/**
|
||||
* Extension tools (MCP servers, a user's browsers) are listed by name
|
||||
* and loaded with `load_tools` only when their definitions together
|
||||
* pass this many characters; below it they're simply all given.
|
||||
*/
|
||||
HarnessDeferToolsMinChars: 6000,
|
||||
/**
|
||||
* How much of a deferred tool's description its line in the list
|
||||
* shows.
|
||||
*/
|
||||
HarnessDeferredToolLineChars: 140,
|
||||
/**
|
||||
* Images one tool call may hand back (the rest are dropped), and how
|
||||
* many of the newest tool images stay in a run's transcript: every
|
||||
@@ -413,6 +493,15 @@ export const AppData = {
|
||||
*/
|
||||
HarnessToolMaxImages: 4,
|
||||
HarnessToolImagesKept: 3,
|
||||
/**
|
||||
* Steps left when a run is told, once, that it's nearly out, so it
|
||||
* saves its report before the wrap up ends it (two runs in a row once
|
||||
* ran out with the report unwritten). Only in runs of at least
|
||||
* `HarnessStepsLowMinSteps` steps, where the warning still leaves room
|
||||
* to act on it.
|
||||
*/
|
||||
HarnessStepsLowWarning: 5,
|
||||
HarnessStepsLowMinSteps: 15,
|
||||
/**
|
||||
* Upload cap for audio sent to transcription.
|
||||
*/
|
||||
|
||||
@@ -4,6 +4,11 @@ import {
|
||||
chatReplyNote,
|
||||
ComputerFilesNote,
|
||||
coordinatorReplyNote,
|
||||
crewRequestsNote,
|
||||
openRunsNote,
|
||||
TaskIncomingNote,
|
||||
TaskRedraftNote,
|
||||
TaskWrapUpIncomingNote,
|
||||
TasksNote,
|
||||
} from "./harness-prompts";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
@@ -78,3 +83,55 @@ describe("harness prompts", () => {
|
||||
expect(TasksNote).not.toContain("[bot:");
|
||||
});
|
||||
});
|
||||
|
||||
describe("openRunsNote", () => {
|
||||
test("names each open run and whether it's queued or under way", () => {
|
||||
const note = openRunsNote({
|
||||
runs: [
|
||||
{ id: 12, title: "Art directions", status: "processing" },
|
||||
{ id: 13, title: null, status: "pending" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(note).toContain(`Run #12 "Art directions": under way`);
|
||||
expect(note).toContain(`Run #13 "Task": queued`);
|
||||
expect(note).toContain("don't start another run");
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
|
||||
test("is empty with no open runs", () => {
|
||||
expect(openRunsNote({ runs: [] })).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("task incoming notes", () => {
|
||||
test("leave separate requests to the chat and never offer send_message", () => {
|
||||
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
|
||||
expect(note).not.toContain("send_message");
|
||||
expect(note).not.toContain("\u2014");
|
||||
}
|
||||
|
||||
expect(TaskIncomingNote).toContain("leave it to the chat");
|
||||
expect(TaskRedraftNote).toContain("leave it to the chat");
|
||||
});
|
||||
});
|
||||
|
||||
describe("crewRequestsNote", () => {
|
||||
test("lists open and answered requests, and where an answer's files are", () => {
|
||||
const note = crewRequestsNote({
|
||||
requests: [
|
||||
{ id: 5, title: "Cite sheet", status: "open" },
|
||||
{ id: 4, title: "Research files", status: "answered" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(note).toContain(`[room:5] "Cite sheet": still open`);
|
||||
expect(note).toContain(`[room:4] "Research files": answered`);
|
||||
expect(note).toContain("crew/room-4/");
|
||||
expect(note).toContain("Don't ask for these again");
|
||||
});
|
||||
|
||||
test("is empty with no requests", () => {
|
||||
expect(crewRequestsNote({ requests: [] })).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,6 +33,12 @@ export const ToolImagesNote = `The images the tool calls above returned (screens
|
||||
*/
|
||||
export const DroppedToolImageNote = `[An earlier image from a tool, no longer shown to save space. Take it again if you still need it.]`;
|
||||
|
||||
/**
|
||||
* Stands in for a page snapshot a newer snapshot of the same browser
|
||||
* replaced (`supersedeToolOutputs`): the page it showed is gone.
|
||||
*/
|
||||
export const SupersededSnapshotNote = `[An older page snapshot, replaced by the newer one further down. Take another if you need the page again.]`;
|
||||
|
||||
/**
|
||||
* The folder-ref example a note shows, always over the running bot's own
|
||||
* folder: a literal owner id in the prompt teaches the bot to name another
|
||||
@@ -58,6 +64,8 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
|
||||
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
|
||||
- Never claim you did something you didn't do.
|
||||
- When the user overrules how you read a rule or a brief, go with their reading: say once what you'd watch for if it matters, then work their way. Don't restate the objection in later replies.
|
||||
- An answer from the crew, a finished run or any other app message is information, not the user's go-ahead. If you told the user you'd wait for their choice, say in a line or two what arrived and keep waiting. If it adds nothing new for them, keep your answer to a line. And never read the user's silence as an answer: they may simply not have seen your question yet.
|
||||
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with start_task (with separate when another run of yours is open on that computer) and say it's queued.
|
||||
- The user can mention a bot as [bot:ID] and a workspace as [workspace:ID]; a [Mentions: ...] line after their message says who and what those are. Write the same refs when you name them back.
|
||||
- Documents, images and reports you make are files: save them with write_file, make_pdf or generate_image, and send one to the user with it ("attach"). When you name a file, write its [file:ID] ref, e.g. [file:12], so the user can open it. When you name a folder, write a folder ref instead, e.g. ${ownFolderRef({ bot_id })}: that opens the folder in Files and downloads nothing.
|
||||
@@ -242,7 +250,54 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
|
||||
*/
|
||||
export const TaskRunNote = `# Working on a task
|
||||
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
|
||||
/**
|
||||
* Told to a task run with what the user wrote in its conversation since
|
||||
* it was queued (`taskIncoming`). The chat replies answer the user there;
|
||||
* the run only decides whether it changes the work. A task has no
|
||||
* send_message.
|
||||
*/
|
||||
export const TaskIncomingNote = `The user wrote in this conversation while you were working on this task (below). Your chat replies answer them there; here, only decide whether it changes this task, from what it means, not how it's worded:
|
||||
- If it changes, corrects or adds to this task, work from it from here on. Redo what it overrules instead of reporting a result it overruled, and say in your report what you changed because of it.
|
||||
- If it's about something else, leave it to the chat and carry on with this task.`;
|
||||
|
||||
/**
|
||||
* Told to a task run when the user wrote past a report that hadn't gone
|
||||
* out yet.
|
||||
*/
|
||||
export const TaskRedraftNote = `Your report above was not sent: the user wrote in this conversation before it went out (below).
|
||||
- If it changes, corrects or adds to this task, do the work it calls for (don't repeat tool calls you have already made), then write the report again.
|
||||
- If it's about something else, leave it to the chat and send the report as it was.`;
|
||||
|
||||
/**
|
||||
* Told to a task run with what the user wrote by its wrap up, when it has
|
||||
* no steps left to act on it.
|
||||
*/
|
||||
export const TaskWrapUpIncomingNote = `The user wrote in this conversation before you finished (below), and this run has no steps left to act on it. If it changes, corrects or adds to this task, say in your report what it changes and what is still to redo because of it; never report a result it overruled as it stands.`;
|
||||
|
||||
/**
|
||||
* 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,
|
||||
* so the reply never starts another run for it. Empty with none.
|
||||
*/
|
||||
export const openRunsNote = ({
|
||||
runs,
|
||||
}: {
|
||||
runs: { id: number; title?: string | null; status: string }[];
|
||||
}) => {
|
||||
if (!runs.length) return "";
|
||||
|
||||
const lines = runs.map(
|
||||
(run) => `- Run #${run.id} "${run.title || "Task"}": ${run.status == "pending" ? "queued" : "under way"}`,
|
||||
);
|
||||
|
||||
return `# Your runs open in this conversation
|
||||
|
||||
${lines.join("\n")}
|
||||
|
||||
Until it reports, a run is shown what the user writes here, between its steps. When the user corrects, changes or adds to the work of one of these runs, it takes that in: tell them so in a line, and don't start another run for it or redo that work in this reply (start_task with separate is only for different work). If they want a run to start over from scratch, they can Stop it and ask again.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Added to every run: the shared to-do list, and how a bot keeps it
|
||||
@@ -390,11 +445,41 @@ Each turn, decide and act with one of your tools:
|
||||
? askable.map((bot) => `${bot.id}: ${bot.name || "A bot"}${bot.role ? ` (${bot.role})` : ""}`).join("; ")
|
||||
: "none"
|
||||
}. Their work comes back to you in the room, and you get another turn.
|
||||
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made.
|
||||
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out.
|
||||
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why.
|
||||
|
||||
Ask one bot at a time and only ask again when the answer falls short. You have ${turns_left} turn${turns_left == 1 ? "" : "s"} left in this room; on the last one, answer with what you have or refuse. Your own words in the room are short notes on what you're doing.`;
|
||||
|
||||
/**
|
||||
* Lists a task run's open and recent requests to the crew (`grabCrewRequests`):
|
||||
* the run sees only its brief, so it otherwise asks again for what's on
|
||||
* its way or already came back. Empty with none.
|
||||
*/
|
||||
export const crewRequestsNote = ({
|
||||
requests,
|
||||
}: {
|
||||
requests: { id?: number | ""; title?: string | null; status?: string | null }[];
|
||||
}) => {
|
||||
if (!requests.length) return "";
|
||||
|
||||
const lines = requests.map(
|
||||
(room) =>
|
||||
`- [room:${room.id}] "${room.title || "Request"}": ${
|
||||
room.status == "open"
|
||||
? "still open; the answer comes to the conversation, not to this run"
|
||||
: room.status == "answered"
|
||||
? `answered; files it sent are in your files under crew/room-${room.id}/, or in the workspace's`
|
||||
: room.status
|
||||
}`,
|
||||
);
|
||||
|
||||
return `# Your recent requests to the crew
|
||||
|
||||
${lines.join("\n")}
|
||||
|
||||
Don't ask for these again. For what an answered one sent, look in your files and the workspace's (list_files) before asking.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Added to a worker's prompt while it can ask the crew through the
|
||||
* coordinator (`ask_crew`).
|
||||
|
||||
@@ -121,6 +121,7 @@ export const JobStepToolLabels: Record<string, string> = {
|
||||
update_memory: "Updating memory",
|
||||
update_instructions: "Updating instructions",
|
||||
load_skill: "Reading a skill",
|
||||
load_tools: "Loading tools",
|
||||
send_message: "Sending a message",
|
||||
create_graphic: "Drawing a graphic",
|
||||
update_graphic: "Redrawing a graphic",
|
||||
|
||||
@@ -107,6 +107,30 @@ export function harnessFallbackTitle({ harness }: { harness: HarnessKind }) {
|
||||
*/
|
||||
export const HarnessMaxToolStepsSettingKey = "harness_max_tool_steps";
|
||||
|
||||
/**
|
||||
* The `app_settings` key holding the install's limit on model turns in a
|
||||
* routine run or a hook call. Unset means `AppData.UnattendedMaxToolSteps`.
|
||||
*/
|
||||
export const UnattendedMaxToolStepsSettingKey = "unattended_max_tool_steps";
|
||||
|
||||
/**
|
||||
* The `app_settings` key holding the prompt tokens one run may spend.
|
||||
* Unset means `AppData.RunMaxPromptTokens`.
|
||||
*/
|
||||
export const RunMaxPromptTokensSettingKey = "run_max_prompt_tokens";
|
||||
|
||||
/**
|
||||
* The `app_settings` key holding the working context a run keeps, in
|
||||
* tokens. Unset means `AppData.HarnessContextBudgetTokens`.
|
||||
*/
|
||||
export const HarnessContextBudgetSettingKey = "harness_context_budget_tokens";
|
||||
|
||||
/**
|
||||
* The `app_settings` key holding how long a failed model rests, in
|
||||
* seconds. Unset means `AppData.HarnessModelRestMs`.
|
||||
*/
|
||||
export const HarnessModelRestSettingKey = "harness_model_rest_seconds";
|
||||
|
||||
/**
|
||||
* Vendors preferred for automatic picks, best first. Free models from any
|
||||
* other vendor come after these, and only if they look competent.
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
|
||||
import { HarnessMaxToolStepsSettingKey } from "@/src/dict/harness-dict";
|
||||
import {
|
||||
HarnessContextBudgetSettingKey,
|
||||
HarnessMaxToolStepsSettingKey,
|
||||
HarnessModelRestSettingKey,
|
||||
RunMaxPromptTokensSettingKey,
|
||||
UnattendedMaxToolStepsSettingKey,
|
||||
} from "@/src/dict/harness-dict";
|
||||
import type { RunLimitsOverview } from "@/src/types";
|
||||
import readStepLimit from "@/src/utils/read-step-limit";
|
||||
import grabAppSetting from "./grab-app-setting";
|
||||
|
||||
export type { RunLimitsOverview };
|
||||
|
||||
/**
|
||||
* Model turns a task run may take: the install's own limit
|
||||
* (`harness_max_tool_steps`, Settings > General), else
|
||||
@@ -32,44 +41,93 @@ export async function grabReplyMaxToolSteps() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Both limits with their defaults, for the settings page.
|
||||
* Model turns a routine run or a hook call may take, which nobody
|
||||
* watches: the install's own limit (`unattended_max_tool_steps`), else
|
||||
* `AppData.UnattendedMaxToolSteps`.
|
||||
*/
|
||||
export async function grabUnattendedMaxToolSteps() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: UnattendedMaxToolStepsSettingKey }),
|
||||
fallback: AppData.UnattendedMaxToolSteps,
|
||||
max: AppData.BotStepLimitMax,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt tokens one run may spend before it must wrap up: the install's
|
||||
* own budget (`run_max_prompt_tokens`), else `AppData.RunMaxPromptTokens`.
|
||||
*/
|
||||
export async function grabRunMaxPromptTokens() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: RunMaxPromptTokensSettingKey }),
|
||||
fallback: AppData.RunMaxPromptTokens,
|
||||
min: AppData.RunMaxPromptTokensMin,
|
||||
max: AppData.RunMaxPromptTokensMax,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The working context a run keeps per turn, in estimated tokens: the
|
||||
* install's own (`harness_context_budget_tokens`), else
|
||||
* `AppData.HarnessContextBudgetTokens`.
|
||||
*/
|
||||
export async function grabContextBudgetTokens() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: HarnessContextBudgetSettingKey }),
|
||||
fallback: AppData.HarnessContextBudgetTokens,
|
||||
min: AppData.HarnessContextBudgetMinTokens,
|
||||
max: AppData.HarnessContextBudgetMaxTokens,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a model that failed is passed over, in seconds: the install's
|
||||
* own (`harness_model_rest_seconds`), else `AppData.HarnessModelRestMs`.
|
||||
*/
|
||||
export async function grabModelRestSeconds() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: HarnessModelRestSettingKey }),
|
||||
fallback: AppData.HarnessModelRestMs / 1000,
|
||||
min: AppData.HarnessModelRestMinSeconds,
|
||||
max: AppData.HarnessModelRestMaxSeconds,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Every run limit with its default, for the settings page.
|
||||
*/
|
||||
export default async function grabRunLimitsOverview() {
|
||||
const [task_steps, reply_steps] = await Promise.all([
|
||||
grabHarnessMaxToolSteps(),
|
||||
grabReplyMaxToolSteps(),
|
||||
]);
|
||||
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds] =
|
||||
await Promise.all([
|
||||
grabHarnessMaxToolSteps(),
|
||||
grabReplyMaxToolSteps(),
|
||||
grabUnattendedMaxToolSteps(),
|
||||
grabRunMaxPromptTokens(),
|
||||
grabContextBudgetTokens(),
|
||||
grabModelRestSeconds(),
|
||||
]);
|
||||
|
||||
const overview: RunLimitsOverview = {
|
||||
task_steps,
|
||||
reply_steps,
|
||||
unattended_steps,
|
||||
run_tokens,
|
||||
context_tokens,
|
||||
model_rest_seconds,
|
||||
task_default: AppData.HarnessMaxToolSteps,
|
||||
reply_default: AppData.BotReplyMaxToolSteps,
|
||||
unattended_default: AppData.UnattendedMaxToolSteps,
|
||||
run_tokens_default: AppData.RunMaxPromptTokens,
|
||||
context_tokens_default: AppData.HarnessContextBudgetTokens,
|
||||
max: AppData.BotStepLimitMax,
|
||||
run_tokens_min: AppData.RunMaxPromptTokensMin,
|
||||
run_tokens_max: AppData.RunMaxPromptTokensMax,
|
||||
context_tokens_min: AppData.HarnessContextBudgetMinTokens,
|
||||
context_tokens_max: AppData.HarnessContextBudgetMaxTokens,
|
||||
model_rest_default: AppData.HarnessModelRestMs / 1000,
|
||||
model_rest_min: AppData.HarnessModelRestMinSeconds,
|
||||
model_rest_max: AppData.HarnessModelRestMaxSeconds,
|
||||
};
|
||||
|
||||
return overview;
|
||||
}
|
||||
|
||||
export type RunLimitsOverview = {
|
||||
/**
|
||||
* The limit a task run uses right now.
|
||||
*/
|
||||
task_steps: number;
|
||||
/**
|
||||
* The limit a chat reply uses right now.
|
||||
*/
|
||||
reply_steps: number;
|
||||
/**
|
||||
* What a task run uses when the install saved no limit.
|
||||
*/
|
||||
task_default: number;
|
||||
/**
|
||||
* What a chat reply uses when the install saved no limit.
|
||||
*/
|
||||
reply_default: number;
|
||||
/**
|
||||
* The most the settings page accepts.
|
||||
*/
|
||||
max: number;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { LastConversation } from "@/src/types";
|
||||
import conversationHref from "@/src/utils/conversation-href";
|
||||
import readLastVisitedBot from "@/src/utils/read-last-visited-bot";
|
||||
import grabUserConversation, { type UserConversation } from "./grab-user-conversation";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
req: Request;
|
||||
};
|
||||
|
||||
/**
|
||||
* The conversation the last-visited cookie names, for the rail's way back
|
||||
* on settings and the rail pages, only while the user still reaches it
|
||||
* (`grabUserConversation`, the conversation pages' own check). A workspace
|
||||
* conversation the user lost falls back to the bot's own chat; with
|
||||
* neither, null and the rail shows no way back.
|
||||
*/
|
||||
export default async function grabLastConversation({
|
||||
user_id,
|
||||
req,
|
||||
}: Params): Promise<LastConversation | null> {
|
||||
const visited = readLastVisitedBot({ req });
|
||||
|
||||
if (!visited) return null;
|
||||
|
||||
const reach = ({ workspace_id }: { workspace_id: number | null }) =>
|
||||
grabUserConversation({ user_id, bot_id: visited.bot_id, workspace_id }).catch(
|
||||
() => null,
|
||||
);
|
||||
|
||||
const conversation: UserConversation | null =
|
||||
(visited.workspace_id ? await reach({ workspace_id: visited.workspace_id }) : null) ||
|
||||
(await reach({ workspace_id: null }));
|
||||
|
||||
if (!conversation) return null;
|
||||
|
||||
const { bot, workspace } = conversation;
|
||||
|
||||
return {
|
||||
href: conversationHref({ bot_id: bot.id, workspace_id: workspace?.id }),
|
||||
bot: {
|
||||
id: bot.id,
|
||||
name: bot.name || `Bot ${bot.id}`,
|
||||
kind: bot.kind || null,
|
||||
color: bot.color || null,
|
||||
stone: bot.stone || null,
|
||||
hue: bot.hue || null,
|
||||
image_media_id: bot.image_media_id || null,
|
||||
},
|
||||
workspace: workspace?.id
|
||||
? { id: workspace.id, name: workspace.name || `Workspace ${workspace.id}` }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -152,7 +152,7 @@ export default async function completeBotJob({
|
||||
face: "needs-you",
|
||||
status_line: BotNeedsYouStatusLine,
|
||||
})
|
||||
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id }))
|
||||
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id, conversations_only: true }))
|
||||
? await restoreRunningFace({ bot_id: job.bot_id, user_id })
|
||||
: await setBotFace({
|
||||
bot_id: job.bot_id,
|
||||
|
||||
@@ -6,15 +6,21 @@ type Params = {
|
||||
* Only jobs in this user's conversations.
|
||||
*/
|
||||
user_id: number | string;
|
||||
/**
|
||||
* Leave out jobs in chatrooms, which never show on the bot's face.
|
||||
*/
|
||||
conversations_only?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many of a bot's jobs for one user are still pending or processing.
|
||||
*/
|
||||
export default async function countOpenBotJobs({ bot_id, user_id }: Params) {
|
||||
export default async function countOpenBotJobs({ bot_id, user_id, conversations_only }: Params) {
|
||||
const res = await BunSQLite.sql<{ open: number }>({
|
||||
sql: `SELECT COUNT(*) AS open FROM bots_queue WHERE bot_id = ? AND status IN ('pending', 'processing')
|
||||
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL)`,
|
||||
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL${
|
||||
conversations_only ? " AND chatroom_id IS NULL" : ""
|
||||
})`,
|
||||
values: [bot_id, user_id],
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import openSessionRunsSql from "./open-session-runs-sql";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
export type OpenSessionRun = {
|
||||
id: number;
|
||||
title: string | null;
|
||||
status: "pending" | "processing";
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot's runs in this session that are still to report and take in
|
||||
* what the user writes here (`openSessionRunsSql`), for the reply to know
|
||||
* a correction reaches them.
|
||||
*/
|
||||
export default async function grabOpenSessionRuns({ bot_id, session_id }: Params): Promise<OpenSessionRun[]> {
|
||||
const { sql, values } = openSessionRunsSql({ bot_id, session_id });
|
||||
const res = await BunSQLite.sql<OpenSessionRun>({ sql, values });
|
||||
|
||||
return res.payload || [];
|
||||
}
|
||||
@@ -15,7 +15,8 @@ type Params = {
|
||||
* The face a bot should show one user while other jobs for them are
|
||||
* still running: thinking while a reply runs (it's short, and its chat
|
||||
* needs the row), else working on a task (in its workspace, if it runs in
|
||||
* one). Null when none is running.
|
||||
* one). Null when none is running. Work in a chatroom or a hook's thread
|
||||
* never counts: it shows there, never on the face.
|
||||
*/
|
||||
export default async function grabRunningBotJobFace({
|
||||
bot_id,
|
||||
@@ -26,7 +27,7 @@ export default async function grabRunningBotJobFace({
|
||||
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
|
||||
LEFT JOIN workspaces w ON w.id = q.workspace_id
|
||||
WHERE q.bot_id = ? AND q.status = 'processing'
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL)
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL AND chatroom_id IS NULL)
|
||||
ORDER BY q.id`,
|
||||
values: [bot_id, user_id],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import openSessionRunsSql from "./open-session-runs-sql";
|
||||
|
||||
/**
|
||||
* The runs a reply is told hear the user: the bot's open task runs in the
|
||||
* session, never a routine's or a hook call's. Run against real SQLite.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, kind TEXT, status TEXT, title TEXT, params TEXT)`);
|
||||
db.run(`INSERT INTO bots_queue VALUES
|
||||
(1, 10, 1, 'task', 'processing', 'Art directions', NULL),
|
||||
(2, 10, 1, 'task', 'pending', 'Logo', '{"max_steps":20}'),
|
||||
(3, 10, 1, 'reply', 'processing', NULL, NULL),
|
||||
(4, 10, 1, 'task', 'completed', 'Old run', NULL),
|
||||
(5, 10, 1, 'task', 'processing', 'Routine', '{"schedule_id":3}'),
|
||||
(6, 10, 1, 'task', 'pending', 'Hook call', '{"hook_id":4}'),
|
||||
(7, 11, 1, 'task', 'processing', 'Another bot', NULL),
|
||||
(8, 10, 2, 'task', 'processing', 'Another session', NULL)`);
|
||||
|
||||
function runs() {
|
||||
const { sql, values } = openSessionRunsSql({ bot_id: 10, session_id: 1 });
|
||||
|
||||
return db.query(sql).all(...values) as { id: number; title: string; status: string }[];
|
||||
}
|
||||
|
||||
describe("openSessionRunsSql", () => {
|
||||
test("lists the bot's open task runs in the session, oldest first", () => {
|
||||
expect(runs()).toEqual([
|
||||
{ id: 1, title: "Art directions", status: "processing" },
|
||||
{ id: 2, title: "Logo", status: "pending" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SQL for the bot's runs in a session that are queued or working and
|
||||
* take in what the user writes there: routine runs and hook calls act on
|
||||
* their own, so they're left out. Oldest first; selects `id`, `title` and
|
||||
* `status`.
|
||||
*/
|
||||
export default function openSessionRunsSql({ bot_id, session_id }: Params): SqlCondition {
|
||||
return {
|
||||
sql: `SELECT id, title, status FROM bots_queue
|
||||
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
|
||||
AND status IN ('pending', 'processing')
|
||||
AND json_extract(COALESCE(params, '{}'), '$.schedule_id') IS NULL
|
||||
AND json_extract(COALESCE(params, '{}'), '$.hook_id') IS NULL
|
||||
ORDER BY id ASC`,
|
||||
values: [Number(bot_id), Number(session_id)],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
/**
|
||||
* The bot that asked.
|
||||
*/
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* The place it asked from: rooms are kept per place, like
|
||||
* conversations.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Rooms closed before this aren't listed (open ones always are).
|
||||
* Defaults to `AppData.CrewRequestsRecentMs` ago.
|
||||
*/
|
||||
since?: number;
|
||||
};
|
||||
|
||||
export type CrewRequest = Pick<BUN_SQLITE_COBBLE_CHATROOMS, "id" | "title" | "status" | "closed_at">;
|
||||
|
||||
/**
|
||||
* A bot's requests to the crew from one place, for one user: every open
|
||||
* room and the ones closed lately, newest first. A task run gets only its
|
||||
* brief, so without these it didn't know a request was already open or
|
||||
* answered, and asked the crew for the same files three times.
|
||||
*/
|
||||
export default async function grabCrewRequests({ user_id, bot_id, workspace_id, since }: Params): Promise<CrewRequest[]> {
|
||||
const res = await BunSQLite.sql<CrewRequest>({
|
||||
sql: `SELECT id, title, status, closed_at FROM chatrooms
|
||||
WHERE user_id = ? AND requester_bot_id = ? AND workspace_id IS ?
|
||||
AND (status = 'open' OR closed_at >= ?)
|
||||
ORDER BY id DESC
|
||||
LIMIT ?`,
|
||||
values: [
|
||||
Number(user_id),
|
||||
Number(bot_id),
|
||||
workspace_id ? Number(workspace_id) : null,
|
||||
since ?? Date.now() - AppData.CrewRequestsRecentMs,
|
||||
AppData.CrewRequestsListed,
|
||||
],
|
||||
});
|
||||
|
||||
return res.payload || [];
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS, BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import fileRefIds from "@/src/utils/file-ref-ids";
|
||||
import rewriteFileRefs from "@/src/utils/rewrite-file-refs";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import copyBotFile from "../bot-files/copy-bot-file";
|
||||
import grabBotFile from "../bot-files/grab-bot-file";
|
||||
import grabRunScopes from "../bot-files/grab-run-scopes";
|
||||
import grabBotById from "../bots/grab-bot-by-id";
|
||||
|
||||
type Params = {
|
||||
chatroom: Pick<BUN_SQLITE_COBBLE_CHATROOMS, "id" | "user_id" | "workspace_id" | "requester_bot_id">;
|
||||
/**
|
||||
* The coordinator's answer, as it would be sent.
|
||||
*/
|
||||
answer: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes the files a room's answer names readable by the bot that asked.
|
||||
* A bot asked in a room saves to its own folder, which the asker can't
|
||||
* read, so an answer citing `[file:330]` sent the asker back to the crew
|
||||
* for the same files twice more. Each cited file the asker doesn't reach
|
||||
* but a bot in the room does is copied into the asker's own folder under
|
||||
* `crew/room-<id>/` (the bytes, so the member's folder stays its own), and
|
||||
* the ref is pointed at the copy. Files the asker already reaches, and
|
||||
* files no bot in the room reaches, are left as they are. A copy that
|
||||
* fails keeps the original ref, and the answer still goes out.
|
||||
*/
|
||||
export default async function shareRoomFiles({ chatroom, answer }: Params) {
|
||||
const ids = fileRefIds({ text: answer }).slice(0, AppData.ChatroomSharedFilesMax);
|
||||
const requester = chatroom.requester_bot_id ? await grabBotById({ bot_id: chatroom.requester_bot_id }) : null;
|
||||
|
||||
if (!ids.length || !requester?.id || !chatroom.user_id) return answer;
|
||||
|
||||
const place = { user_id: chatroom.user_id, workspace_id: chatroom.workspace_id || null };
|
||||
const requester_scopes = await grabRunScopes({ bot: requester, ...place });
|
||||
const own: StorageScope = { scope: "bot", owner_id: Number(requester.id) };
|
||||
const member_scopes = await grabMemberScopes({ chatroom, requester_id: Number(requester.id), place });
|
||||
const copies = new Map<number, number>();
|
||||
|
||||
for (const file_id of ids) {
|
||||
if (await grabBotFile({ scopes: requester_scopes, file_id })) continue;
|
||||
|
||||
const source = await findReachingScopes({ member_scopes, file_id });
|
||||
|
||||
if (!source) continue;
|
||||
|
||||
try {
|
||||
const copy = await copyBotFile({
|
||||
scopes: [...source.scopes, own],
|
||||
file_id,
|
||||
bot_id: requester.id,
|
||||
scope: own,
|
||||
path: `crew/room-${chatroom.id}/${source.name}`,
|
||||
user_id: chatroom.user_id,
|
||||
});
|
||||
|
||||
if (copy?.id) copies.set(file_id, Number(copy.id));
|
||||
} catch (error: unknown) {
|
||||
await logError({
|
||||
title: `Couldn't copy a crew answer's file for the bot that asked`,
|
||||
error,
|
||||
user_id: Number(chatroom.user_id),
|
||||
metadata: { chatroom_id: chatroom.id, file_id, bot_id: requester.id },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return rewriteFileRefs({ text: answer, ids: copies });
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders each bot asked in the room reaches there, for its user and
|
||||
* place (never the coordinator's or the asker's own).
|
||||
*/
|
||||
async function grabMemberScopes({
|
||||
chatroom,
|
||||
requester_id,
|
||||
place,
|
||||
}: {
|
||||
chatroom: Params["chatroom"];
|
||||
requester_id: number;
|
||||
place: { user_id: number | string; workspace_id: number | string | null };
|
||||
}) {
|
||||
const sessions = (
|
||||
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_BOT_SESSIONS, "bot_id">>({
|
||||
sql: `SELECT DISTINCT bot_id FROM bot_sessions WHERE chatroom_id = ? AND bot_id != ?`,
|
||||
values: [Number(chatroom.id), requester_id],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
const scopes: StorageScope[][] = [];
|
||||
|
||||
for (const session of sessions) {
|
||||
const bot = await grabBotById({ bot_id: session.bot_id! });
|
||||
|
||||
if (!bot?.id || bot.kind == "coordinator") continue;
|
||||
|
||||
scopes.push(await grabRunScopes({ bot, ...place }));
|
||||
}
|
||||
|
||||
return scopes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first member's folders that reach a file, with the file's name for
|
||||
* its copy.
|
||||
*/
|
||||
async function findReachingScopes({ member_scopes, file_id }: { member_scopes: StorageScope[][]; file_id: number }) {
|
||||
for (const scopes of member_scopes) {
|
||||
const file = await grabBotFile({ scopes, file_id });
|
||||
|
||||
if (file?.id) {
|
||||
return { scopes, name: (file.path || file.name || `file-${file_id}`).split("/").pop() || `file-${file_id}` };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessKind } from "@/src/dict/harness-dict";
|
||||
import { withHarnessParameters } from "@/src/dict/harness-parameter-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import assertHarnessModel from "./assert-harness-model";
|
||||
|
||||
type Params = {
|
||||
harness: HarnessKind;
|
||||
/**
|
||||
* The options the setting row holds now (`{}` for a new row).
|
||||
*/
|
||||
existing: Record<string, unknown>;
|
||||
/**
|
||||
* The picked model, never also a fallback.
|
||||
*/
|
||||
model_id: number | null;
|
||||
voice?: string;
|
||||
sees_images?: boolean;
|
||||
fallback_model_ids?: number[];
|
||||
params?: Record<string, number | string>;
|
||||
};
|
||||
|
||||
/**
|
||||
* A harness setting's options as the settings forms save them: what the
|
||||
* row held beyond the form's own fields, then the voice (speech), whether
|
||||
* the text model reads images itself, the text harness's fallback models
|
||||
* (each checked like a pick, on any provider) and the generation settings.
|
||||
*/
|
||||
export default async function buildHarnessSettingOptions({
|
||||
harness,
|
||||
existing,
|
||||
model_id,
|
||||
voice,
|
||||
sees_images,
|
||||
fallback_model_ids = [],
|
||||
params = {},
|
||||
}: Params) {
|
||||
const { voice: _voice, sees_images: _sees, fallback_model_ids: _fallbacks, ...options } = existing;
|
||||
const fallbacks =
|
||||
harness == "text" ? [...new Set(fallback_model_ids)].filter((id) => id != model_id) : [];
|
||||
|
||||
if (fallbacks.length > AppData.HarnessTextFallbackModelsMax) {
|
||||
throw new AppError(`Pick at most ${AppData.HarnessTextFallbackModelsMax} fallback models.`);
|
||||
}
|
||||
|
||||
for (const id of fallbacks) {
|
||||
await assertHarnessModel({ harness, model_id: id });
|
||||
}
|
||||
|
||||
return withHarnessParameters({
|
||||
options: {
|
||||
...options,
|
||||
...(voice ? { voice } : {}),
|
||||
...(harness == "text" && sees_images ? { sees_images: true } : {}),
|
||||
...(fallbacks.length ? { fallback_model_ids: fallbacks } : {}),
|
||||
},
|
||||
params,
|
||||
});
|
||||
}
|
||||
@@ -113,7 +113,7 @@ export default async function attachTaskFile({
|
||||
const count = (await grabTaskMedia({ task_id: task.id! })).length;
|
||||
|
||||
if (count >= AppData.TaskMediaMaxPerTask) {
|
||||
throw new AppError(`Task #${task.id} already carries ${AppData.TaskMediaMaxPerTask} files. Unlink one first.`);
|
||||
throw new AppError(`Task #${task.id} already carries ${AppData.TaskMediaMaxPerTask} files. Unlink one first (update_task with unlink_file_ids, or on the task in the app).`);
|
||||
}
|
||||
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_TASK_MEDIA, (typeof BunSQLiteTables)[number]>({
|
||||
|
||||
@@ -46,11 +46,21 @@ type Params = {
|
||||
*/
|
||||
requested_by_bot_id?: number | string | null;
|
||||
requested_by_session_id?: number | string | null;
|
||||
/**
|
||||
* False to only move it: the task goes to the new bot's list as to do
|
||||
* and no job is queued, for when the user hasn't asked for the work to
|
||||
* begin. Handing three tasks over "to wait for the go-ahead" once ran
|
||||
* three jobs that each only reported they were waiting.
|
||||
*/
|
||||
start?: boolean;
|
||||
};
|
||||
|
||||
export type HandedOverTask = {
|
||||
task: BUN_SQLITE_COBBLE_TASKS;
|
||||
job_id: number | string;
|
||||
/**
|
||||
* The job doing the work; null when it wasn't started.
|
||||
*/
|
||||
job_id: number | string | null;
|
||||
bot_name: string;
|
||||
workspace_id: number | null;
|
||||
/**
|
||||
@@ -65,7 +75,8 @@ export type HandedOverTask = {
|
||||
* that workspace), one on a bot's own list moves to the new bot's. The task goes to doing, its log
|
||||
* says who handed it over, and a job is queued in the new bot's
|
||||
* conversation with the task's brief and `params.tracker_task_id`, so the
|
||||
* bot moves this same task along and the job's end is noted on it.
|
||||
* bot moves this same task along and the job's end is noted on it. With
|
||||
* `start` false it only moves: to do, no job, the notice says so.
|
||||
*/
|
||||
export default async function handOverTask({
|
||||
user_id,
|
||||
@@ -76,6 +87,7 @@ export default async function handOverTask({
|
||||
handed_by,
|
||||
requested_by_bot_id,
|
||||
requested_by_session_id,
|
||||
start = true,
|
||||
}: Params): Promise<HandedOverTask> {
|
||||
const task = await grabTaskRow({ task_id });
|
||||
|
||||
@@ -107,7 +119,7 @@ export default async function handOverTask({
|
||||
const conversation = await grabUserConversation({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
|
||||
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
|
||||
const title = (task.title || "Task").slice(0, 80);
|
||||
const open = await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title });
|
||||
const open = start ? await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title }) : null;
|
||||
|
||||
if (open) {
|
||||
throw new AppError(
|
||||
@@ -130,28 +142,31 @@ export default async function handOverTask({
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
const job_id = await enqueueBotJob({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
title,
|
||||
instructions: brief,
|
||||
params: { tracker_task_id: Number(task.id) },
|
||||
computer_id: computers[0]?.id || undefined,
|
||||
requested_by_bot_id: requested_by_bot_id || undefined,
|
||||
requested_by_session_id: requested_by_session_id || undefined,
|
||||
});
|
||||
const job_id = start
|
||||
? await enqueueBotJob({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
title,
|
||||
instructions: brief,
|
||||
params: { tracker_task_id: Number(task.id) },
|
||||
computer_id: computers[0]?.id || undefined,
|
||||
requested_by_bot_id: requested_by_bot_id || undefined,
|
||||
requested_by_session_id: requested_by_session_id || undefined,
|
||||
})
|
||||
: null;
|
||||
const status = start ? "doing" : "todo";
|
||||
|
||||
await updateTask({
|
||||
user_id,
|
||||
task_id: task.id!,
|
||||
status: "doing",
|
||||
status,
|
||||
updated_by_bot_id: requested_by_bot_id || null,
|
||||
});
|
||||
|
||||
await addTaskNote({
|
||||
task_id: task.id!,
|
||||
text: `${handed_by} handed this over to ${bot.name}.`,
|
||||
text: `${handed_by} handed this over to ${bot.name}${start ? "" : ", to start when the user says so"}.`,
|
||||
author: requested_by_bot_id ? "bot" : "user",
|
||||
bot_id: requested_by_bot_id || null,
|
||||
});
|
||||
@@ -162,12 +177,12 @@ export default async function handOverTask({
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
workspace_id: run_workspace_id,
|
||||
text: `${handed_by} handed me task #${task.id}: **${title}**`,
|
||||
text: `${handed_by} handed me task #${task.id}: **${title}**${start ? "" : ". It's on my list; I'll start when you say."}`,
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
task: { ...moved, status: "doing" },
|
||||
task: { ...moved, status },
|
||||
job_id,
|
||||
bot_name: conversation.bot.name || bot.name || "The bot",
|
||||
workspace_id: run_workspace_id,
|
||||
|
||||
@@ -23,6 +23,7 @@ type CallRow = {
|
||||
model_slug: string | null;
|
||||
model_name: string | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
settings: string | null;
|
||||
@@ -53,7 +54,7 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
|
||||
await BunSQLite.sql<CallRow>({
|
||||
sql: `SELECT t.id, t.created_at, t.harness, t.provider_id, t.provider_name,
|
||||
p.kind AS provider_kind, t.model_slug, m.name AS model_name,
|
||||
t.prompt_tokens, t.completion_tokens, t.cost, t.settings, t.job_id
|
||||
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.cost, t.settings, t.job_id
|
||||
FROM token_usages t
|
||||
LEFT JOIN harness_providers p ON p.id = t.provider_id
|
||||
LEFT JOIN harness_models m ON m.id = t.model_id
|
||||
@@ -73,6 +74,7 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
|
||||
model_slug: row.model_slug || null,
|
||||
model_name: row.model_name || null,
|
||||
prompt_tokens: Number(row.prompt_tokens) || 0,
|
||||
cached_tokens: Number(row.cached_tokens) || 0,
|
||||
completion_tokens: Number(row.completion_tokens) || 0,
|
||||
cost: Number.isFinite(Number(row.cost)) && row.cost !== null ? Number(row.cost) : null,
|
||||
settings: parseCallSettings({ json: row.settings }),
|
||||
|
||||
@@ -9,10 +9,19 @@ type Params = {
|
||||
message_ids: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A text call that a model answered in place of one ahead of it: one
|
||||
* failed during the call, or was passed over while resting.
|
||||
*/
|
||||
const FellBackSql = `(harness = 'text' AND (
|
||||
COALESCE(json_array_length(json_extract(settings, '$.fell_back_from')), 0) > 0
|
||||
OR COALESCE(json_array_length(json_extract(settings, '$.resting')), 0) > 0))`;
|
||||
|
||||
/**
|
||||
* What each of these messages cost, summed over every model call it took
|
||||
* (chat turns, media readings, image generations). This is what a
|
||||
* message's token line shows.
|
||||
* (chat turns, media readings, image generations), and the fallback model
|
||||
* that answered for it, if one did. This is what a message's token line
|
||||
* shows.
|
||||
*/
|
||||
export default async function grabMessageUsage({ message_ids }: Params) {
|
||||
const totals = new Map<number, TokenUsageSummary>();
|
||||
@@ -26,12 +35,16 @@ export default async function grabMessageUsage({ message_ids }: Params) {
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
calls: number;
|
||||
fallback_model: string | null;
|
||||
fallback_calls: number | null;
|
||||
}>({
|
||||
sql: `SELECT message_id,
|
||||
SUM(prompt_tokens) AS prompt_tokens,
|
||||
SUM(completion_tokens) AS completion_tokens,
|
||||
SUM(cost) AS cost,
|
||||
COUNT(*) AS calls
|
||||
COUNT(*) AS calls,
|
||||
MAX(CASE WHEN ${FellBackSql} THEN model_slug END) AS fallback_model,
|
||||
SUM(CASE WHEN ${FellBackSql} THEN 1 ELSE 0 END) AS fallback_calls
|
||||
FROM token_usages
|
||||
WHERE message_id IN (${ids.map(() => "?").join(", ")})
|
||||
GROUP BY message_id`,
|
||||
@@ -49,6 +62,9 @@ export default async function grabMessageUsage({ message_ids }: Params) {
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(Number.isFinite(cost) && cost > 0 ? { cost } : {}),
|
||||
calls: Number(row.calls) || 0,
|
||||
...(row.fallback_model
|
||||
? { fallback_model: row.fallback_model, fallback_calls: Number(row.fallback_calls) || 1 }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ export default async function grabUsageModels({ start, end, limit }: Params): Pr
|
||||
harness: string | null;
|
||||
calls: number | null;
|
||||
prompt_tokens: number | null;
|
||||
cached_tokens: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
}>({
|
||||
@@ -52,6 +53,7 @@ export default async function grabUsageModels({ start, end, limit }: Params): Pr
|
||||
u.harness,
|
||||
COUNT(*) AS calls,
|
||||
SUM(u.prompt_tokens) AS prompt_tokens,
|
||||
SUM(u.cached_tokens) AS cached_tokens,
|
||||
SUM(u.completion_tokens) AS completion_tokens,
|
||||
SUM(u.cost) AS cost
|
||||
FROM token_usages u
|
||||
|
||||
@@ -12,6 +12,10 @@ type Params = {
|
||||
type UsageRow = {
|
||||
calls: number | null;
|
||||
prompt_tokens: number | null;
|
||||
/**
|
||||
* Left out by the queries that don't sum it.
|
||||
*/
|
||||
cached_tokens?: number | null;
|
||||
completion_tokens: number | null;
|
||||
cost: number | null;
|
||||
};
|
||||
@@ -34,6 +38,7 @@ export default async function grabUsageTotals({ start, end }: Params): Promise<U
|
||||
sql: `SELECT harness,
|
||||
COUNT(*) AS calls,
|
||||
SUM(prompt_tokens) AS prompt_tokens,
|
||||
SUM(cached_tokens) AS cached_tokens,
|
||||
SUM(completion_tokens) AS completion_tokens,
|
||||
SUM(cost) AS cost
|
||||
FROM token_usages
|
||||
@@ -59,12 +64,14 @@ export default async function grabUsageTotals({ start, end }: Params): Promise<U
|
||||
*/
|
||||
export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): TokenUsageSummary {
|
||||
let prompt_tokens = 0;
|
||||
let cached_tokens = 0;
|
||||
let completion_tokens = 0;
|
||||
let cost = 0;
|
||||
let calls = 0;
|
||||
|
||||
for (const summary of summaries) {
|
||||
prompt_tokens += summary.prompt_tokens;
|
||||
cached_tokens += summary.cached_tokens || 0;
|
||||
completion_tokens += summary.completion_tokens;
|
||||
cost += summary.cost || 0;
|
||||
calls += summary.calls;
|
||||
@@ -72,6 +79,7 @@ export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): T
|
||||
|
||||
return {
|
||||
prompt_tokens,
|
||||
...(cached_tokens > 0 ? { cached_tokens } : {}),
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(cost > 0 ? { cost } : {}),
|
||||
@@ -84,11 +92,13 @@ export function sumSummary({ summaries }: { summaries: TokenUsageSummary[] }): T
|
||||
*/
|
||||
export function toSummary({ row }: { row: UsageRow }): TokenUsageSummary {
|
||||
const prompt_tokens = Number(row.prompt_tokens) || 0;
|
||||
const cached_tokens = Number(row.cached_tokens) || 0;
|
||||
const completion_tokens = Number(row.completion_tokens) || 0;
|
||||
const cost = Number(row.cost);
|
||||
|
||||
return {
|
||||
prompt_tokens,
|
||||
...(cached_tokens > 0 ? { cached_tokens } : {}),
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
...(Number.isFinite(cost) && cost > 0 ? { cost } : {}),
|
||||
|
||||
@@ -6,20 +6,26 @@ type Params = {
|
||||
req: Request;
|
||||
res: Response;
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* The workspace the conversation is in; none for the bot's own chat.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The page's response with the last-visited cookie set, so `/admin/bots`
|
||||
* opens this bot's own chat again next time. Called from the conversation
|
||||
* opens this bot's own chat again next time and the rail on settings and
|
||||
* the rail pages leads back to this conversation. Called from the conversation
|
||||
* pages' `res_transform`, which is why it takes and returns the response.
|
||||
*/
|
||||
export default function withLastVisitedBotCookies({ req, res, bot_id }: Params): Response {
|
||||
export default function withLastVisitedBotCookies({ req, res, bot_id, workspace_id }: Params): Response {
|
||||
const new_res = res.clone();
|
||||
|
||||
setCookies(
|
||||
new_res,
|
||||
lastVisitedBotCookies({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
secure: isSecureRequest({ req }),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -55,13 +55,14 @@ export default async function speakText({
|
||||
* completion count to read: the call is recorded as it is, with
|
||||
* the text's length standing in for what was spoken.
|
||||
*/
|
||||
on_success: async ({ candidate, failed }) =>
|
||||
on_success: async ({ candidate, failed, resting }) =>
|
||||
await recordHarnessUsage({
|
||||
call: buildUsageCall({
|
||||
harness: "speech",
|
||||
candidate,
|
||||
usage: { prompt_tokens: text.length, completion_tokens: 0 },
|
||||
failed,
|
||||
resting,
|
||||
settings: {
|
||||
settings_source: setting.source,
|
||||
voice: voiceFor(candidate),
|
||||
|
||||
@@ -51,12 +51,13 @@ export default async function transcribeAudio({
|
||||
const { result } = await withCandidates<{ text: string; usage?: HarnessUsage }>({
|
||||
harness: "transcription",
|
||||
candidates,
|
||||
on_success: async ({ candidate, result: transcript, failed }): Promise<void> =>
|
||||
on_success: async ({ candidate, result: transcript, failed, resting }): Promise<void> =>
|
||||
await recordHarnessUsage({
|
||||
call: buildUsageCall({
|
||||
harness: "transcription",
|
||||
candidate,
|
||||
failed,
|
||||
resting,
|
||||
usage: transcript.usage,
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -63,12 +63,13 @@ export default async function embedText({
|
||||
const { result, candidate: answered } = await withCandidates<HarnessEmbedResult>({
|
||||
harness: "embedding",
|
||||
candidates,
|
||||
on_success: async ({ candidate, result: embedded, failed }): Promise<void> =>
|
||||
on_success: async ({ candidate, result: embedded, failed, resting }): Promise<void> =>
|
||||
await recordHarnessUsage({
|
||||
call: buildUsageCall({
|
||||
harness: "embedding",
|
||||
candidate,
|
||||
failed,
|
||||
resting,
|
||||
usage: embedded.usage,
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -67,12 +67,13 @@ export default async function generateImage({
|
||||
const { result } = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
|
||||
harness: edit?.picked ? "image_edit" : "image",
|
||||
candidates: ordered.map(({ candidate }) => candidate),
|
||||
on_success: async ({ candidate, result: made, failed }): Promise<void> =>
|
||||
on_success: async ({ candidate, result: made, failed, resting }): Promise<void> =>
|
||||
await recordHarnessUsage({
|
||||
call: buildUsageCall({
|
||||
harness: harness_of.get(candidate.key) || "image",
|
||||
candidate,
|
||||
failed,
|
||||
resting,
|
||||
usage: made.usage,
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -53,13 +53,14 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
|
||||
}>({
|
||||
harness: "vision",
|
||||
candidates,
|
||||
on_success: async ({ candidate, result: answer, failed }): Promise<void> =>
|
||||
on_success: async ({ candidate, result: answer, failed, resting }): Promise<void> =>
|
||||
await recordHarnessUsage({
|
||||
call: buildUsageCall({
|
||||
harness: "vision",
|
||||
candidate,
|
||||
usage: answer.usage,
|
||||
failed,
|
||||
resting,
|
||||
settings: {
|
||||
settings_source: saved_params.source,
|
||||
params: flattenSentParams({ params: answer.sent_params }),
|
||||
|
||||
@@ -51,6 +51,15 @@ describe("readChatResponse", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("reads the cached prompt tokens, in either spelling", () => {
|
||||
const answer = (usage: Record<string, unknown>) =>
|
||||
read({ choices: [{ message: { content: "Hi." } }], usage: { prompt_tokens: 100, completion_tokens: 2, ...usage } }).usage;
|
||||
|
||||
expect(answer({ prompt_tokens_details: { cached_tokens: 80 } })?.cached_tokens).toBe(80);
|
||||
expect(answer({ prompt_cache_hit_tokens: 60 })?.cached_tokens).toBe(60);
|
||||
expect(answer({})?.cached_tokens).toBe(undefined);
|
||||
});
|
||||
|
||||
test("joins content parts and treats empty text as none", () => {
|
||||
expect(
|
||||
read({
|
||||
|
||||
@@ -77,6 +77,13 @@ export default function readChatResponse({
|
||||
usage: json.usage
|
||||
? {
|
||||
prompt_tokens: json.usage.prompt_tokens,
|
||||
/**
|
||||
* OpenAI's and OpenRouter's spelling; some providers
|
||||
* (DeepSeek's own API) say `prompt_cache_hit_tokens`.
|
||||
*/
|
||||
cached_tokens:
|
||||
Number(json.usage.prompt_tokens_details?.cached_tokens ?? json.usage.prompt_cache_hit_tokens) ||
|
||||
undefined,
|
||||
completion_tokens: json.usage.completion_tokens,
|
||||
cost: json.usage.cost,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { grabModelRestSeconds } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
|
||||
/**
|
||||
* How long a failed model rests, in ms (`grabModelRestSeconds`). Falls
|
||||
* back to `AppData.HarnessModelRestMs` when the setting can't be read, so
|
||||
* a harness call never fails over it.
|
||||
*/
|
||||
export default async function grabModelRestMs() {
|
||||
try {
|
||||
return (await grabModelRestSeconds()) * 1000;
|
||||
} catch {
|
||||
return AppData.HarnessModelRestMs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import type HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate } from "../types";
|
||||
|
||||
type Params = {
|
||||
harness: string;
|
||||
candidate: HarnessCandidate;
|
||||
error: HarnessError;
|
||||
/**
|
||||
* Unix ms it may be tried again, if it rests.
|
||||
*/
|
||||
rests_until?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a model's failure to the activity log: which model, what the
|
||||
* provider said and how long it rests, so a switch to a fallback can be
|
||||
* explained afterwards. Once per failure, and a resting model isn't tried,
|
||||
* so an outage logs at most once per rest per model. Never throws.
|
||||
*/
|
||||
export default async function logCandidateFailure({ harness, candidate, error, rests_until }: Params) {
|
||||
const provider = candidate.provider.name || candidate.provider.kind;
|
||||
const rest = rests_until
|
||||
? ` It rests for ${Math.max(1, Math.round((rests_until - Date.now()) / 1000))} seconds.`
|
||||
: " It isn't benched; the next model takes this call.";
|
||||
|
||||
try {
|
||||
await logEvent({
|
||||
title: "Model failed",
|
||||
category: "system",
|
||||
plain_text: `${candidate.model.slug} on ${provider} failed a ${harness} call (${candidate.source} pick): ${error.message}.${rest}`,
|
||||
details: [
|
||||
{ label: "Model", value: candidate.model.slug },
|
||||
{ label: "Provider", value: provider },
|
||||
{ label: "Pick", value: candidate.source },
|
||||
{ label: "Status", value: error.status ?? "none" },
|
||||
],
|
||||
metadata: {
|
||||
harness,
|
||||
candidate_key: candidate.key,
|
||||
source: candidate.source,
|
||||
status: error.status,
|
||||
retryable: error.retryable,
|
||||
provider_wide: error.provider_wide,
|
||||
rests_until,
|
||||
},
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import harnessModelRowToCatalog from "@/src/functions/backend/db/harness/harness
|
||||
import resolveProviderConfig from "@/src/functions/backend/db/harness/resolve-provider-config";
|
||||
import modelServesHarness from "../catalog/model-serves-harness";
|
||||
import rankAutoModels from "../catalog/rank-auto-models";
|
||||
import harnessFallbackModelIds from "@/src/utils/harness-fallback-model-ids";
|
||||
import HarnessError from "../harness-error";
|
||||
import type {
|
||||
HarnessCandidate,
|
||||
@@ -35,12 +36,14 @@ type CatalogEntry = HarnessCatalogModel & {
|
||||
};
|
||||
|
||||
/**
|
||||
* The models a harness call tries, in order: the pick (the bot's own, else
|
||||
* the super admin's), then
|
||||
* (if it has fallback on, or there is no pick) the automatic free picks.
|
||||
* Only enabled providers with a usable key count, and only the setting's
|
||||
* provider when it has one. Empty when nothing is
|
||||
* set up; throws `unavailable` when the harness is turned off.
|
||||
* The models a harness call tries, in order: the pick (the workspace's,
|
||||
* the bot's own, else the super admin's), then the setting's fallback
|
||||
* models in their order (`fallback_model_ids`, each on its own provider),
|
||||
* then (if it has fallback on, or there is no pick) the automatic free
|
||||
* picks. Only enabled providers with a usable key count, and only the
|
||||
* setting's provider for the pick and automatic picks when it has one.
|
||||
* Empty when nothing is set up; throws `unavailable` when the harness is
|
||||
* turned off.
|
||||
*/
|
||||
export default async function resolveHarnessCandidates({
|
||||
harness,
|
||||
@@ -65,25 +68,32 @@ export default async function resolveHarnessCandidates({
|
||||
|
||||
if (!providers.size) return [];
|
||||
|
||||
const fallback_ids = harnessFallbackModelIds({ options: setting.options }).filter(
|
||||
(id) => id != setting.model_id,
|
||||
);
|
||||
const picked_ids = [setting.model_id ?? 0, ...fallback_ids];
|
||||
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HARNESS_MODELS>({
|
||||
sql: `SELECT * FROM harness_models
|
||||
WHERE available = 1 AND (free = 1 OR id = ?)`,
|
||||
values: [setting.model_id ?? 0],
|
||||
WHERE available = 1 AND (free = 1 OR id IN (${picked_ids.map(() => "?").join(", ")}))`,
|
||||
values: picked_ids,
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
const entries: CatalogEntry[] = rows.flatMap((row) => {
|
||||
const toEntry = ({ row, any_provider }: { row: BUN_SQLITE_COBBLE_HARNESS_MODELS; any_provider: boolean }) => {
|
||||
const provider =
|
||||
row.provider_id && (!setting.provider_id || row.provider_id == setting.provider_id)
|
||||
row.provider_id && (any_provider || !setting.provider_id || row.provider_id == setting.provider_id)
|
||||
? providers.get(row.provider_id)
|
||||
: undefined;
|
||||
|
||||
return provider && row.id
|
||||
? [{ ...harnessModelRowToCatalog({ row }), row_id: row.id, provider }]
|
||||
: [];
|
||||
});
|
||||
};
|
||||
|
||||
const entries: CatalogEntry[] = rows.flatMap((row) => toEntry({ row, any_provider: false }));
|
||||
|
||||
const pinned = entries.find(
|
||||
(entry) =>
|
||||
@@ -91,8 +101,21 @@ export default async function resolveHarnessCandidates({
|
||||
modelServesHarness({ model: entry, harness }),
|
||||
);
|
||||
|
||||
/**
|
||||
* Each fallback model names its own provider, so the setting's
|
||||
* provider limit doesn't apply to them.
|
||||
*/
|
||||
const fallbacks: CatalogEntry[] = fallback_ids.flatMap((id) => {
|
||||
const row = rows.find((r) => r.id == id);
|
||||
|
||||
return row
|
||||
? toEntry({ row, any_provider: true }).filter((entry) => modelServesHarness({ model: entry, harness }))
|
||||
: [];
|
||||
});
|
||||
|
||||
const ordered = [
|
||||
...(pinned ? [{ entry: pinned, source: "pinned" as const }] : []),
|
||||
...fallbacks.map((entry) => ({ entry, source: "fallback" as const })),
|
||||
...(!pinned || setting.fallback
|
||||
? rankAutoModels({ models: entries, harness }).map((entry) => ({
|
||||
entry,
|
||||
|
||||
@@ -4,7 +4,11 @@ import type { HarnessCandidate } from "../types";
|
||||
import createCooldowns from "./create-cooldowns";
|
||||
import withCandidates from "./with-candidates";
|
||||
|
||||
function candidate(slug: string, provider_id = 1): HarnessCandidate {
|
||||
function candidate(
|
||||
slug: string,
|
||||
provider_id = 1,
|
||||
source: HarnessCandidate["source"] = "auto",
|
||||
): HarnessCandidate {
|
||||
return {
|
||||
key: `${provider_id}:${slug}`,
|
||||
provider: {
|
||||
@@ -18,7 +22,7 @@ function candidate(slug: string, provider_id = 1): HarnessCandidate {
|
||||
output_modalities: ["text"],
|
||||
supports_tools: true,
|
||||
},
|
||||
source: "auto",
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -173,4 +177,111 @@ describe("withCandidates", () => {
|
||||
|
||||
expect(await run(bug)).toBe(bug);
|
||||
});
|
||||
|
||||
test("a failed model rests no longer than the model rest, whatever it was", async () => {
|
||||
const now = 1_000_000;
|
||||
const rest_ms = 120_000;
|
||||
|
||||
for (const error of [
|
||||
new HarnessError({ message: "gone", status: 404 }),
|
||||
new HarnessError({ message: "refused", status: 403 }),
|
||||
rateLimited("1:a", now + 60 * 60 * 1000),
|
||||
new HarnessError({ message: "down", status: 503, retryable: true }),
|
||||
]) {
|
||||
const cooldowns = createCooldowns();
|
||||
const a = candidate("a", 1, "pinned");
|
||||
|
||||
await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [a, candidate("b")],
|
||||
cooldowns,
|
||||
rest_ms,
|
||||
now: () => now,
|
||||
run: async (c) => {
|
||||
if (c == a) throw error;
|
||||
},
|
||||
});
|
||||
|
||||
expect(cooldowns.get({ key: a.key, now })).toBe(now + rest_ms);
|
||||
}
|
||||
});
|
||||
|
||||
test("a provider that says to come back sooner rests only that long", async () => {
|
||||
const now = 1_000_000;
|
||||
const cooldowns = createCooldowns();
|
||||
const a = candidate("a");
|
||||
|
||||
await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [a, candidate("b")],
|
||||
cooldowns,
|
||||
rest_ms: 120_000,
|
||||
now: () => now,
|
||||
run: async (c) => {
|
||||
if (c == a) throw rateLimited(a.key, now + 5_000);
|
||||
},
|
||||
});
|
||||
|
||||
expect(cooldowns.get({ key: a.key, now })).toBe(now + 5_000);
|
||||
});
|
||||
|
||||
test("a refused request benches nothing", async () => {
|
||||
const cooldowns = createCooldowns();
|
||||
const a = candidate("a");
|
||||
|
||||
await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [a, candidate("b")],
|
||||
cooldowns,
|
||||
rest_ms: 120_000,
|
||||
run: async (c) => {
|
||||
if (c == a) throw new HarnessError({ message: "bad request", status: 400 });
|
||||
},
|
||||
});
|
||||
|
||||
expect(cooldowns.get({ key: a.key })).toBeUndefined();
|
||||
});
|
||||
|
||||
test("tells the answer which models failed and which were resting", async () => {
|
||||
const cooldowns = createCooldowns();
|
||||
const pinned = candidate("pinned", 1, "pinned");
|
||||
const first = candidate("first", 2, "fallback");
|
||||
const second = candidate("second", 3, "fallback");
|
||||
let seen: { failed: string[]; resting: string[] } | undefined;
|
||||
|
||||
cooldowns.set({ key: pinned.key, at: Date.now() + 60_000 });
|
||||
|
||||
await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [pinned, first, second],
|
||||
cooldowns,
|
||||
rest_ms: 120_000,
|
||||
run: async (c) => {
|
||||
if (c == first) throw rateLimited(first.key);
|
||||
},
|
||||
on_success: ({ failed, resting }) => {
|
||||
seen = { failed: [...failed], resting: [...resting] };
|
||||
},
|
||||
});
|
||||
|
||||
expect(seen).toEqual({ failed: [first.key], resting: [pinned.key] });
|
||||
});
|
||||
|
||||
test("a run on an automatic pick goes back to the pick and its fallbacks once they rested", async () => {
|
||||
const tried: string[] = [];
|
||||
|
||||
await withCandidates({
|
||||
harness: "text",
|
||||
candidates: [candidate("pinned", 1, "pinned"), candidate("fallback", 2, "fallback"), candidate("free-a"), candidate("free-b")],
|
||||
prefer_key: "1:free-b",
|
||||
cooldowns: createCooldowns(),
|
||||
rest_ms: 120_000,
|
||||
run: async (c) => {
|
||||
tried.push(c.model.slug);
|
||||
if (c.source != "auto") throw rateLimited(c.key);
|
||||
},
|
||||
});
|
||||
|
||||
expect(tried).toEqual(["pinned", "fallback", "free-b"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,15 +3,19 @@ import { Harnesses, type HarnessKind } from "@/src/dict/harness-dict";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate } from "../types";
|
||||
import type { HarnessCooldowns } from "./create-cooldowns";
|
||||
import grabModelRestMs from "./grab-model-rest-ms";
|
||||
import DefaultCooldowns from "./harness-cooldowns";
|
||||
import logCandidateFailure from "./log-candidate-failure";
|
||||
|
||||
type Params<T> = {
|
||||
harness: HarnessKind;
|
||||
candidates: HarnessCandidate[];
|
||||
run: (candidate: HarnessCandidate) => Promise<T>;
|
||||
/**
|
||||
* Tried first when it's a candidate: the model a multi-step run already
|
||||
* uses, so it doesn't switch models mid-task without a reason.
|
||||
* The model a multi-step run already uses, so it doesn't switch models
|
||||
* mid-task without a reason. It goes before the other automatic picks,
|
||||
* never before the pick or its fallback models: a run that fell back
|
||||
* goes back to them once they've rested.
|
||||
*/
|
||||
prefer_key?: string;
|
||||
/**
|
||||
@@ -26,26 +30,32 @@ type Params<T> = {
|
||||
* The candidates that failed before this one answered, by key.
|
||||
*/
|
||||
failed: string[];
|
||||
/**
|
||||
* The candidates ahead of this one that were passed over because
|
||||
* they were resting after an earlier failure, by key.
|
||||
*/
|
||||
resting: string[];
|
||||
}) => Promise<void> | void;
|
||||
cooldowns?: HarnessCooldowns;
|
||||
/**
|
||||
* How long a failed candidate rests. Read from the install's setting
|
||||
* (`grabModelRestMs`) when not given.
|
||||
*/
|
||||
rest_ms?: number;
|
||||
/**
|
||||
* Writes each failure to the activity log (`logCandidateFailure`). On
|
||||
* by default for the process-wide cooldowns, i.e. real calls.
|
||||
*/
|
||||
log_failures?: boolean;
|
||||
now?: () => number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Bad keys and missing credits keep a provider out this long.
|
||||
*/
|
||||
const ProviderCooldownMs = 10 * 60 * 1000;
|
||||
/**
|
||||
* A model the provider no longer has (404) or won't serve to us (403)
|
||||
* stays out this long.
|
||||
*/
|
||||
const GoneCooldownMs = 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Runs a harness call on the first candidate that works, in order (the
|
||||
* preferred one first), up to `AppData.HarnessMaxCandidates` tries.
|
||||
* Runs a harness call on the first candidate that works, in order
|
||||
* (`orderCandidates`), up to `AppData.HarnessMaxCandidates` tries.
|
||||
* Candidates (and providers) on cooldown are skipped; a failure puts its
|
||||
* candidate, or its whole provider for a key problem, on cooldown.
|
||||
* candidate, or its whole provider for a key problem, on cooldown for the
|
||||
* install's model rest (`coolDown`) and is logged.
|
||||
*
|
||||
* Throws a `HarnessError`: `unavailable` when there is nothing to try,
|
||||
* otherwise the last failure, `retryable` if any failure was.
|
||||
@@ -57,6 +67,8 @@ export default async function withCandidates<T>({
|
||||
prefer_key,
|
||||
on_success,
|
||||
cooldowns = DefaultCooldowns,
|
||||
rest_ms,
|
||||
log_failures = cooldowns === DefaultCooldowns,
|
||||
now = Date.now,
|
||||
}: Params<T>): Promise<{ result: T; candidate: HarnessCandidate }> {
|
||||
const title = Harnesses.find((h) => h.value == harness)?.title || harness;
|
||||
@@ -68,10 +80,7 @@ export default async function withCandidates<T>({
|
||||
});
|
||||
}
|
||||
|
||||
const ordered = [
|
||||
...candidates.filter((c) => c.key == prefer_key),
|
||||
...candidates.filter((c) => c.key != prefer_key),
|
||||
];
|
||||
const ordered = orderCandidates({ candidates, prefer_key });
|
||||
|
||||
const isReady = (candidate: HarnessCandidate) =>
|
||||
!cooldowns.get({ key: candidate.key, now: now() }) &&
|
||||
@@ -97,6 +106,9 @@ export default async function withCandidates<T>({
|
||||
}
|
||||
|
||||
const errors: HarnessError[] = [];
|
||||
const failed: string[] = [];
|
||||
const resting: string[] = [];
|
||||
const rest = rest_ms ?? (await grabModelRestMs());
|
||||
|
||||
for (const candidate of ordered) {
|
||||
if (errors.length >= AppData.HarnessMaxCandidates) break;
|
||||
@@ -104,16 +116,15 @@ export default async function withCandidates<T>({
|
||||
/**
|
||||
* Checked each time: a failure can bench the rest of its provider.
|
||||
*/
|
||||
if (!isReady(candidate)) continue;
|
||||
if (!isReady(candidate)) {
|
||||
resting.push(candidate.key);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await run(candidate);
|
||||
|
||||
await on_success?.({
|
||||
candidate,
|
||||
result,
|
||||
failed: errors.flatMap((e) => (e.candidate_key ? [e.candidate_key] : [])),
|
||||
});
|
||||
await on_success?.({ candidate, result, failed, resting });
|
||||
|
||||
return { result, candidate };
|
||||
} catch (error: unknown) {
|
||||
@@ -121,7 +132,13 @@ export default async function withCandidates<T>({
|
||||
if (error.code == "aborted") throw error;
|
||||
|
||||
errors.push(error);
|
||||
coolDown({ candidate, error, cooldowns, now: now() });
|
||||
failed.push(candidate.key);
|
||||
|
||||
const rests_until = coolDown({ candidate, error, cooldowns, now: now(), rest_ms: rest });
|
||||
|
||||
if (log_failures) {
|
||||
await logCandidateFailure({ harness, candidate, error, rests_until });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,33 +172,66 @@ function providerKey(candidate: HarnessCandidate) {
|
||||
return `provider:${candidate.provider.id ?? candidate.provider.base_url}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The order candidates are tried in: as resolved (the pick, its fallback
|
||||
* models, then the automatic picks), with the model a run already uses
|
||||
* moved ahead of the other automatic picks.
|
||||
*/
|
||||
function orderCandidates({
|
||||
candidates,
|
||||
prefer_key,
|
||||
}: {
|
||||
candidates: HarnessCandidate[];
|
||||
prefer_key?: string;
|
||||
}) {
|
||||
const preferred = candidates.find((c) => c.key == prefer_key);
|
||||
|
||||
if (!preferred || preferred.source != "auto") return candidates;
|
||||
|
||||
return [
|
||||
...candidates.filter((c) => c.source != "auto"),
|
||||
preferred,
|
||||
...candidates.filter((c) => c.source == "auto" && c != preferred),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Benches a failed candidate (or its whole provider, for a bad key or no
|
||||
* credits) for `rest_ms`, or until the provider says to come back when
|
||||
* that's sooner. A request the model refused (400, 422) benches nothing:
|
||||
* it's about that request. Returns when it may be tried again, if benched.
|
||||
*/
|
||||
function coolDown({
|
||||
candidate,
|
||||
error,
|
||||
cooldowns,
|
||||
now,
|
||||
rest_ms,
|
||||
}: {
|
||||
candidate: HarnessCandidate;
|
||||
error: HarnessError;
|
||||
cooldowns: HarnessCooldowns;
|
||||
now: number;
|
||||
rest_ms: number;
|
||||
}) {
|
||||
const until = now + rest_ms;
|
||||
|
||||
if (error.provider_wide) {
|
||||
cooldowns.set({ key: providerKey(candidate), at: now + ProviderCooldownMs });
|
||||
return;
|
||||
cooldowns.set({ key: providerKey(candidate), at: until });
|
||||
return until;
|
||||
}
|
||||
|
||||
if (error.retryable) {
|
||||
const at = error.retry_at || now + AppData.HarnessCooldownMs;
|
||||
const at = Math.min(Math.max(error.retry_at || until, now), until);
|
||||
|
||||
cooldowns.set({
|
||||
key: candidate.key,
|
||||
at: Math.min(at, now + AppData.HarnessMaxCooldownMs),
|
||||
});
|
||||
return;
|
||||
cooldowns.set({ key: candidate.key, at });
|
||||
return at;
|
||||
}
|
||||
|
||||
if (error.status == 403 || error.status == 404) {
|
||||
cooldowns.set({ key: candidate.key, at: now + GoneCooldownMs });
|
||||
cooldowns.set({ key: candidate.key, at: until });
|
||||
return until;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTool } from "../types";
|
||||
import { LoadToolsToolName } from "../tools/load-tools-tool";
|
||||
|
||||
/**
|
||||
* The system prompt's list of the tools a run may load (`load_tools`):
|
||||
* each by name with the start of its description, so the model knows
|
||||
* what is there without every definition riding along on each turn.
|
||||
*/
|
||||
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
|
||||
const lines = tools.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`);
|
||||
|
||||
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with the names you need (one call can load several), then call them. Don't load what you won't use.\n${lines.join("\n")}`;
|
||||
}
|
||||
|
||||
function shortDescription({ text }: { text: string }) {
|
||||
const line = text.trim().split("\n")[0]!.trim();
|
||||
const max = AppData.HarnessDeferredToolLineChars;
|
||||
|
||||
return line.length > max ? `${line.slice(0, max - 3).trimEnd()}...` : line;
|
||||
}
|
||||
@@ -25,10 +25,10 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
test("trims the oldest tool output first, keeping the newest", () => {
|
||||
const transcript = run();
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 20000 });
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 26000 });
|
||||
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters");
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters of earlier computer_bash output");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
expect(transcript[6]!.content).toBe("recent");
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
@@ -44,4 +44,69 @@ describe("fitTranscriptToContext", () => {
|
||||
expect(result.trimmed).toBe(0);
|
||||
expect(transcript[1]!.content).toBe(big);
|
||||
});
|
||||
|
||||
test("keeps to the working context even when the window is far larger", () => {
|
||||
const transcript = run();
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript,
|
||||
context_length: 1_000_000,
|
||||
budget_tokens: 15000,
|
||||
});
|
||||
|
||||
expect(result.budget).toBe(15000);
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed:");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
});
|
||||
|
||||
test("cuts in one block, down to well under the budget, then leaves it alone", () => {
|
||||
const transcript = run();
|
||||
const first = fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 18000 });
|
||||
|
||||
expect(first.trimmed).toBe(1);
|
||||
|
||||
transcript.push(
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "4", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "4", content: "x".repeat(9000) },
|
||||
);
|
||||
|
||||
const second = fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 18000 });
|
||||
|
||||
expect(second.trimmed).toBe(0);
|
||||
});
|
||||
|
||||
test("counts the tool definitions against the budget", () => {
|
||||
const transcript = run();
|
||||
const without = fitTranscriptToContext({ system: "s", transcript: run(), context_length: 1_000_000, budget_tokens: 25000 });
|
||||
const with_tools = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript,
|
||||
context_length: 1_000_000,
|
||||
budget_tokens: 25000,
|
||||
tools_chars: 30000,
|
||||
});
|
||||
|
||||
expect(without.trimmed).toBe(0);
|
||||
expect(with_tools.trimmed).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("cuts long tool call arguments once the results are gone", () => {
|
||||
const long = JSON.stringify({ path: "a.html", content: "y".repeat(30000) });
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "Write the page." },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_write_file", arguments: long }] },
|
||||
{ role: "tool", tool_call_id: "1", content: "Written." },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "ok" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 5000 });
|
||||
|
||||
const call = (transcript[1] as { tool_calls: { arguments: string }[] }).tool_calls[0]!;
|
||||
|
||||
expect(JSON.parse(call.arguments).trimmed).toContain(`${long.length} characters`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,17 @@ type Params = {
|
||||
* The model's context window, in tokens.
|
||||
*/
|
||||
context_length: number;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most the prompt
|
||||
* may be per turn, whatever the window. Left out, only the window
|
||||
* limits it.
|
||||
*/
|
||||
budget_tokens?: number;
|
||||
/**
|
||||
* Characters of the tool definitions sent with every turn: they count
|
||||
* against the budget like the prompt.
|
||||
*/
|
||||
tools_chars?: number;
|
||||
/**
|
||||
* The newest messages, never trimmed: the model needs them to go on.
|
||||
*/
|
||||
@@ -21,6 +32,12 @@ type Params = {
|
||||
* Share of the window the prompt may fill; the rest is for the answer.
|
||||
*/
|
||||
const PromptShare = 0.7;
|
||||
/**
|
||||
* Once over budget, trimming goes on down to this share of it. Cutting in
|
||||
* one block, rather than one message each turn, keeps the start of the
|
||||
* prompt the same for many turns, which is what providers cache.
|
||||
*/
|
||||
const TrimToShare = 0.6;
|
||||
/**
|
||||
* Rough characters per token, on the low side so the estimate errs high.
|
||||
*/
|
||||
@@ -29,44 +46,129 @@ const CharsPerToken = 3;
|
||||
* What an image or audio part is counted as, in tokens.
|
||||
*/
|
||||
const MediaTokens = 1500;
|
||||
/**
|
||||
* Tool call arguments longer than this (a file written whole) are cut on
|
||||
* the second pass, after the tool results.
|
||||
*/
|
||||
const ArgumentsKeepChars = 1500;
|
||||
|
||||
/**
|
||||
* Keeps a long tool run inside the model's context window: while the
|
||||
* estimated prompt is over budget, the oldest tool results (then the
|
||||
* oldest assistant texts) are replaced with a note of what was cut.
|
||||
* Returns how many messages were trimmed.
|
||||
* Keeps a long tool run inside its working context: once the estimated
|
||||
* prompt (system, tool definitions, transcript) passes the budget (the
|
||||
* working context, or 70% of the window when that is smaller), the
|
||||
* oldest tool results, then long tool call arguments, then the oldest
|
||||
* assistant texts are replaced with a note of what was cut, down to 60%
|
||||
* of the budget. Returns how many messages were trimmed.
|
||||
*/
|
||||
export default function fitTranscriptToContext({
|
||||
system,
|
||||
transcript,
|
||||
context_length,
|
||||
budget_tokens,
|
||||
tools_chars = 0,
|
||||
keep_last = 4,
|
||||
}: Params) {
|
||||
const budget = Math.floor(context_length * PromptShare);
|
||||
let total = estimateTokens({ text: system }) + transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
const window_budget = Math.floor(context_length * PromptShare);
|
||||
const budget = budget_tokens && budget_tokens > 0 ? Math.min(window_budget, budget_tokens) : window_budget;
|
||||
let total =
|
||||
estimateTokens({ text: system }) +
|
||||
Math.ceil(tools_chars / CharsPerToken) +
|
||||
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
let trimmed = 0;
|
||||
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget };
|
||||
|
||||
const target = Math.floor(budget * TrimToShare);
|
||||
const trimmable = transcript.length - keep_last;
|
||||
const names = toolNames({ transcript });
|
||||
|
||||
for (const role of ["tool", "assistant"] as const) {
|
||||
for (let index = 0; index < trimmable && total > budget; index++) {
|
||||
const message = transcript[index]!;
|
||||
const replace = ({ index, message }: { index: number; message: HarnessMessage }) => {
|
||||
const before = messageTokens({ message: transcript[index]! });
|
||||
|
||||
if (message.role != role || typeof message.content != "string") continue;
|
||||
if (message.content.startsWith("[Trimmed:")) continue;
|
||||
transcript[index] = message;
|
||||
total += messageTokens({ message }) - before;
|
||||
trimmed++;
|
||||
};
|
||||
|
||||
const before = messageTokens({ message });
|
||||
const note = `[Trimmed: ${message.content.length} characters of earlier ${role == "tool" ? "tool output" : "notes"} to fit the context.]`;
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
transcript[index] = { ...message, content: note } as HarnessMessage;
|
||||
total += messageTokens({ message: transcript[index]! }) - before;
|
||||
trimmed++;
|
||||
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
|
||||
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier ${name ? `${name} output` : "tool output"} to fit the working context. Call it again if you still need it.]`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "assistant" || !message.tool_calls?.some((call) => call.arguments.length > ArgumentsKeepChars)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
tool_calls: message.tool_calls.map((call) =>
|
||||
call.arguments.length > ArgumentsKeepChars
|
||||
? {
|
||||
...call,
|
||||
arguments: JSON.stringify({
|
||||
trimmed: `${call.arguments.length} characters of arguments cut to fit the working context`,
|
||||
}),
|
||||
}
|
||||
: call,
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "assistant" || typeof message.content != "string" || isTrimmed({ text: message.content })) {
|
||||
continue;
|
||||
}
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier notes to fit the working context.]`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { trimmed, estimated_tokens: total, budget };
|
||||
}
|
||||
|
||||
/**
|
||||
* The tool each call id went to, for the note that replaces its result.
|
||||
*/
|
||||
function toolNames({ transcript }: { transcript: HarnessMessage[] }) {
|
||||
const names = new Map<string, string>();
|
||||
|
||||
for (const message of transcript) {
|
||||
if (message.role != "assistant") continue;
|
||||
|
||||
for (const call of message.tool_calls || []) names.set(call.id, call.name);
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
function isTrimmed({ text }: { text: string }) {
|
||||
return text.startsWith("[Trimmed:");
|
||||
}
|
||||
|
||||
function messageTokens({ message }: { message: HarnessMessage }) {
|
||||
let tokens = 4;
|
||||
|
||||
|
||||
@@ -96,13 +96,14 @@ export default async function generateText({
|
||||
harness: "text",
|
||||
candidates: resolved,
|
||||
prefer_key,
|
||||
on_success: async ({ candidate: answered, result: answer, failed }): Promise<void> =>
|
||||
on_success: async ({ candidate: answered, result: answer, failed, resting }): Promise<void> =>
|
||||
await recordHarnessUsage({
|
||||
call: buildUsageCall({
|
||||
harness: "text",
|
||||
candidate: answered,
|
||||
usage: answer.usage,
|
||||
failed,
|
||||
resting,
|
||||
settings: {
|
||||
...(saved_params ? { settings_source: saved_params.source } : {}),
|
||||
params: flattenSentParams({ params: answer.sent_params }),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { DroppedToolImageNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
|
||||
import runTextLoop, { IncomingMessagesNote, RedraftNote } from "./run-text-loop";
|
||||
import runTextLoop, { IncomingMessagesNote, RedraftNote, stepsLowNote } from "./run-text-loop";
|
||||
|
||||
const candidate: HarnessCandidate = {
|
||||
key: "1:m",
|
||||
@@ -201,6 +201,50 @@ describe("runTextLoop", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
|
||||
const max_steps = AppData.HarnessStepsLowMinSteps;
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted(Array.from({ length: max_steps + 1 }, () => loop_call));
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_steps,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const warned_at = max_steps - AppData.HarnessStepsLowWarning;
|
||||
const note = stepsLowNote({ left: AppData.HarnessStepsLowWarning });
|
||||
const warnings = seen.map((call) => call.messages.filter((m) => m.role == "user" && String(m.content).includes(note)).length);
|
||||
|
||||
expect(warnings[warned_at - 1]).toBe(0);
|
||||
expect(warnings[warned_at]).toBe(1);
|
||||
expect(seen[warned_at]!.messages.at(-1)).toEqual({ role: "user", content: note });
|
||||
expect(warnings.at(-1)).toBe(1);
|
||||
});
|
||||
|
||||
test("doesn't warn a short run", async () => {
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted([loop_call, loop_call, { text: "Done." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_steps: 2,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(JSON.stringify(seen)).not.toContain("left in this run");
|
||||
});
|
||||
|
||||
test("records failed tool calls, and tells the wrap up so", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "c", name: "missing_tool", arguments: "{}" }] },
|
||||
@@ -374,6 +418,59 @@ describe("runTextLoop", () => {
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain("You've used every step");
|
||||
});
|
||||
|
||||
test("tells the run its own notes with what came in", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"x"}` }] },
|
||||
{ text: "Report." },
|
||||
{ text: "Report, corrected." },
|
||||
]);
|
||||
const arrivals = [
|
||||
[{ role: "user" as const, content: "Use photos too." }],
|
||||
[{ role: "user" as const, content: "And keep it short." }],
|
||||
];
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Brief." }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
incoming: async () => arrivals.shift() || [],
|
||||
incoming_notes: { working: "Working note.", redraft: "Redraft note." },
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Report, corrected.");
|
||||
expect(seen[1]!.messages.at(-1)).toEqual({ role: "user", content: "Working note.\n\nUse photos too." });
|
||||
expect(seen[2]!.messages.at(-1)).toEqual({ role: "user", content: "Redraft note.\n\nAnd keep it short." });
|
||||
});
|
||||
|
||||
test("with a wrap up note, takes in what came in by the wrap up before it", async () => {
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted([loop_call, { text: "Out of steps." }]);
|
||||
let looks = 0;
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
incoming: async () => {
|
||||
looks++;
|
||||
return looks == 2 ? [{ role: "user", content: "Late correction." }] : [];
|
||||
},
|
||||
incoming_notes: { wrap_up: "Too late to act." },
|
||||
});
|
||||
|
||||
expect(looks).toBe(2);
|
||||
const last = seen[1]!.messages.at(-1)!.content as string;
|
||||
expect(last).toContain("Too late to act.\n\nLate correction.");
|
||||
expect(last.indexOf("Late correction.")).toBeLessThan(last.indexOf("You've used every step"));
|
||||
});
|
||||
|
||||
test("writes an answer the review faults again, once, with its note and the tool calls", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
|
||||
@@ -443,4 +540,105 @@ describe("runTextLoop", () => {
|
||||
expect(result.text).toBe("Out of steps.");
|
||||
expect(reviews).toBe(0);
|
||||
});
|
||||
|
||||
test("wraps up once the run has spent its token budget", async () => {
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
usage: { prompt_tokens: 600, completion_tokens: 1 },
|
||||
};
|
||||
const { generate, seen } = scripted([loop_call, loop_call, { text: "Stopping here.", ...loop_call }]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen[2]!.tools).toBe(undefined);
|
||||
expect(seen[2]!.messages.at(-1)!.content).toContain("This run has used all the tokens it may spend.");
|
||||
expect(result.text).toBe("Stopping here.");
|
||||
});
|
||||
|
||||
test("keeps only the newest page snapshot in the transcript", async () => {
|
||||
let page = 0;
|
||||
const snapshot: HarnessTool = {
|
||||
name: "browser_snapshot",
|
||||
description: "Reads the page.",
|
||||
schema: z.object({}),
|
||||
run: async () => `page ${++page}`,
|
||||
};
|
||||
const snap = (id: string) => ({ tool_calls: [{ id, name: "browser_snapshot", arguments: "{}" }] });
|
||||
const { generate, seen } = scripted([snap("a"), snap("b")]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Look." }],
|
||||
tools: [snapshot],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const tool_turns = seen[2]!.messages.filter((message) => message.role == "tool");
|
||||
|
||||
expect(tool_turns.map((message) => message.content)).toEqual([SupersededSnapshotNote, "page 2"]);
|
||||
});
|
||||
|
||||
test("lists deferred tools by name and gives their definitions once loaded", async () => {
|
||||
const big = "Does a thing. ".repeat(Math.ceil(AppData.HarnessDeferToolsMinChars / 14));
|
||||
const used: string[] = [];
|
||||
const extension = (name: string): HarnessTool => ({
|
||||
name,
|
||||
description: big,
|
||||
parameters: { type: "object", properties: {} },
|
||||
deferred: true,
|
||||
run: async () => {
|
||||
used.push(name);
|
||||
return "done";
|
||||
},
|
||||
});
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "1", name: "load_tools", arguments: `{"names":["srv__a"]}` }] },
|
||||
{ tool_calls: [{ id: "2", name: "srv__a", arguments: "{}" }] },
|
||||
{ tool_calls: [{ id: "3", name: "srv__b", arguments: "{}" }] },
|
||||
{ text: "Done." },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, extension("srv__a"), extension("srv__b")],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const names = (index: number) => seen[index]!.tools!.map((tool) => tool.name);
|
||||
|
||||
expect(names(0)).toEqual(["remember", "load_tools"]);
|
||||
expect(String(seen[0]!.messages[0]!.content)).toContain("Tools you can load");
|
||||
expect(String(seen[0]!.messages[0]!.content)).toContain("- srv__a: Does a thing.");
|
||||
expect(names(1)).toEqual(["remember", "load_tools", "srv__a"]);
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain("Loaded: srv__a.");
|
||||
expect(names(3)).toEqual(["remember", "load_tools", "srv__a", "srv__b"]);
|
||||
expect(used).toEqual(["srv__a", "srv__b"]);
|
||||
});
|
||||
|
||||
test("gives small deferred tools straight away", async () => {
|
||||
const small: HarnessTool = { ...remember, name: "srv__small", deferred: true };
|
||||
const { generate, seen } = scripted([{ text: "Hi." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, small],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "srv__small"]);
|
||||
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../harness-error";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import type {
|
||||
@@ -12,11 +13,13 @@ import type {
|
||||
HarnessToolUse,
|
||||
HarnessUsage,
|
||||
} from "../types";
|
||||
import deferredToolsNote from "./deferred-tools-note";
|
||||
import describeToolUses from "./describe-tool-uses";
|
||||
import dropOldToolImages from "./drop-old-tool-images";
|
||||
import fitTranscriptToContext from "./fit-transcript-to-context";
|
||||
import generateText from "./generate-text";
|
||||
import pushUserTurn from "./push-user-turn";
|
||||
import supersedeToolOutputs from "./supersede-tool-outputs";
|
||||
import toolImagesTurn from "./tool-images-turn";
|
||||
|
||||
export type TextLoopStep = {
|
||||
@@ -35,8 +38,25 @@ type Params = {
|
||||
* The conversation so far, ending with what to do now.
|
||||
*/
|
||||
messages: HarnessMessage[];
|
||||
/**
|
||||
* The run's tools. Deferred ones (`HarnessTool.deferred`) are listed
|
||||
* by name and loaded with `load_tools`, when together they're large
|
||||
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
|
||||
*/
|
||||
tools?: HarnessTool[];
|
||||
max_steps?: number;
|
||||
/**
|
||||
* Prompt tokens the run may spend in all (`grabRunMaxPromptTokens`):
|
||||
* once its turns have sent this many, the next one is the wrap up.
|
||||
* Left out, only `max_steps` ends it.
|
||||
*/
|
||||
max_prompt_tokens?: number;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most each turn
|
||||
* sends before old tool output is trimmed, whatever the model's
|
||||
* window. Left out, the window decides.
|
||||
*/
|
||||
context_budget?: number;
|
||||
signal?: AbortSignal;
|
||||
/**
|
||||
* Called after each model turn, before its tools run. Use it for
|
||||
@@ -51,6 +71,14 @@ type Params = {
|
||||
* is written again with them in mind.
|
||||
*/
|
||||
incoming?: () => Promise<HarnessMessage[]>;
|
||||
/**
|
||||
* What the run is told with what came in: `working` after a round of
|
||||
* tools, `redraft` past an answer that hadn't gone out (defaults
|
||||
* `IncomingMessagesNote`, `RedraftNote`). With `wrap_up`, what came in
|
||||
* by the wrap up is added before it too, for a run nothing picks up
|
||||
* after (a task); without it a later reply does.
|
||||
*/
|
||||
incoming_notes?: { working?: string; redraft?: string; wrap_up?: string };
|
||||
/**
|
||||
* Checks an answer before it's returned, with the tool calls the run
|
||||
* made. A note sends the answer back to be written again with it, once
|
||||
@@ -91,13 +119,22 @@ export type TextLoopResult = {
|
||||
/**
|
||||
* Told on the last step, with the app's record of the tools the run
|
||||
* called (`describeToolUses`): out of steps, a model tends to report the
|
||||
* work it planned as done.
|
||||
* work it planned as done. `tokens` when the run's token budget ended it
|
||||
* rather than its steps.
|
||||
*/
|
||||
export const wrapUpPrompt = ({ uses }: { uses: HarnessToolUse[] }) =>
|
||||
`You've used every step this run allows. Don't call any more tools. Report what you did, what is left, and anything you need from the user.
|
||||
export const wrapUpPrompt = ({ uses, reason = "steps" }: { uses: HarnessToolUse[]; reason?: "steps" | "tokens" }) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} Don't call any more tools. Report what you did, what is left, and anything you need from the user.
|
||||
|
||||
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
|
||||
|
||||
/**
|
||||
* Told once, `AppData.HarnessStepsLowWarning` steps before the wrap up,
|
||||
* while the run can still save what it has: the wrap up has no tools, so a
|
||||
* report not written by then is lost.
|
||||
*/
|
||||
export const stepsLowNote = ({ left }: { left: number }) =>
|
||||
`You have ${left} step${left == 1 ? "" : "s"} left in this run. Save what the user will want now (the report or deliverable, with write_file or import_file) before anything else, then finish. What isn't saved when the steps run out is lost.`;
|
||||
|
||||
/**
|
||||
* Told with what the user wrote while the run worked. Whether a message
|
||||
* belongs to the work is the model's call, from what it says: a correction
|
||||
@@ -121,17 +158,27 @@ Don't repeat tool calls you have already made.`;
|
||||
* The text harness at work: the model answers or calls tools, tool results
|
||||
* go back to it, and so on until it answers without calling a tool. Tools
|
||||
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
|
||||
* `max_steps` turns the model is asked to wrap up without tools. An answer
|
||||
* `review` finds fault with is written again once.
|
||||
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
|
||||
* model is asked to wrap up without tools. An answer `review` finds fault
|
||||
* with is written again once.
|
||||
*
|
||||
* Every turn resends everything, so the run keeps it small: only the
|
||||
* newest page snapshot of each browser stays (`supersedeToolOutputs`),
|
||||
* old tool output is trimmed to the working context
|
||||
* (`fitTranscriptToContext`), and deferred tools are listed by name until
|
||||
* loaded.
|
||||
*/
|
||||
export default async function runTextLoop({
|
||||
system,
|
||||
messages,
|
||||
tools = [],
|
||||
max_steps = AppData.HarnessMaxToolSteps,
|
||||
max_prompt_tokens,
|
||||
context_budget,
|
||||
signal = new AbortController().signal,
|
||||
onStep,
|
||||
incoming,
|
||||
incoming_notes,
|
||||
review,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
@@ -139,10 +186,39 @@ export default async function runTextLoop({
|
||||
resolveCandidates = () => resolveHarnessCandidates({ harness: "text", bot_id, workspace_id }),
|
||||
}: Params): Promise<TextLoopResult> {
|
||||
const candidates = await resolveCandidates();
|
||||
const definitions = tools.map((tool) => toolDefinition({ tool }));
|
||||
/**
|
||||
* Deferred tools wait to be loaded only when their definitions
|
||||
* together are worth keeping out of every turn.
|
||||
*/
|
||||
const deferrable = tools.filter((tool) => tool.deferred);
|
||||
const defer =
|
||||
deferrable.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0) >=
|
||||
AppData.HarnessDeferToolsMinChars;
|
||||
/**
|
||||
* Loaded deferred tools, in the order they were loaded: their
|
||||
* definitions go after the others, so the start of the list (and of
|
||||
* the prompt, which providers cache) stays the same.
|
||||
*/
|
||||
const loaded: string[] = [];
|
||||
const run_tools: HarnessTool[] = defer
|
||||
? [
|
||||
...tools,
|
||||
loadToolsTool({
|
||||
deferred: deferrable,
|
||||
isLoaded: (name) => loaded.includes(name),
|
||||
onLoad: (names) => loaded.push(...names),
|
||||
}),
|
||||
]
|
||||
: tools;
|
||||
const all_definitions = new Map(run_tools.map((tool) => [tool.name, toolDefinition({ tool })]));
|
||||
const definitionsNow = () => [
|
||||
...run_tools.filter((tool) => !defer || !tool.deferred).map((tool) => all_definitions.get(tool.name)!),
|
||||
...loaded.map((name) => all_definitions.get(name)!),
|
||||
];
|
||||
const run_system = defer ? `${system}\n\n${deferredToolsNote({ tools: deferrable })}` : system;
|
||||
const media_cache = new Map<string, string>();
|
||||
const transcript: HarnessMessage[] = [...messages];
|
||||
const usage: Required<HarnessUsage> = {
|
||||
const usage: Required<Omit<HarnessUsage, "cached_tokens">> = {
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
cost: 0,
|
||||
@@ -150,18 +226,27 @@ export default async function runTextLoop({
|
||||
const tool_uses: HarnessToolUse[] = [];
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
let warned_steps = max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
|
||||
for (let index = 0; index <= max_steps; index++) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
}
|
||||
|
||||
const wrap_up = index == max_steps;
|
||||
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens);
|
||||
const wrap_up = index == max_steps || out_of_tokens;
|
||||
|
||||
if (wrap_up) {
|
||||
pushUserTurn({ transcript, content: wrapUpPrompt({ uses: tool_uses }) });
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up });
|
||||
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
content: wrapUpPrompt({ uses: tool_uses, reason: index == max_steps ? "steps" : "tokens" }),
|
||||
});
|
||||
}
|
||||
|
||||
const definitions = definitionsNow();
|
||||
|
||||
/**
|
||||
* Sized for the model the run is on (or will start on). A fallback
|
||||
* with a smaller window gets a 400 and the next model is tried.
|
||||
@@ -169,13 +254,15 @@ export default async function runTextLoop({
|
||||
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
|
||||
|
||||
fitTranscriptToContext({
|
||||
system,
|
||||
system: run_system,
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessAutoMinContext,
|
||||
budget_tokens: context_budget,
|
||||
tools_chars: wrap_up ? 0 : JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
const answer = await generate({
|
||||
messages: [{ role: "system", content: system }, ...transcript],
|
||||
messages: [{ role: "system", content: run_system }, ...transcript],
|
||||
tools: wrap_up || !definitions.length ? undefined : definitions,
|
||||
candidates,
|
||||
prefer_key,
|
||||
@@ -209,7 +296,7 @@ export default async function runTextLoop({
|
||||
* 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: RedraftNote }))) {
|
||||
if (!tool_calls.length && !wrap_up && (await takeIncoming({ note: incoming_notes?.redraft || RedraftNote }))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -240,7 +327,15 @@ export default async function runTextLoop({
|
||||
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
|
||||
|
||||
for (const call of tool_calls) {
|
||||
const { text: content, images } = await runToolCall({ call, tools, signal });
|
||||
const { text: content, images } = await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
* it stays loaded from here on.
|
||||
*/
|
||||
if (defer && deferrable.some((tool) => tool.name == call.name) && !loaded.includes(call.name)) {
|
||||
loaded.push(call.name);
|
||||
}
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
@@ -254,6 +349,8 @@ export default async function runTextLoop({
|
||||
* setting allows it (`textSeesImages`); otherwise `generateText`
|
||||
* has them read first.
|
||||
*/
|
||||
supersedeToolOutputs({ transcript });
|
||||
|
||||
if (shown.length) {
|
||||
pushUserTurn({ transcript, content: toolImagesTurn({ shown }) });
|
||||
dropOldToolImages({
|
||||
@@ -263,7 +360,17 @@ export default async function runTextLoop({
|
||||
});
|
||||
}
|
||||
|
||||
await takeIncoming({ note: IncomingMessagesNote });
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote });
|
||||
|
||||
/**
|
||||
* Steps left before the wrap up, once the next turn is taken.
|
||||
*/
|
||||
const left = max_steps - (index + 1);
|
||||
|
||||
if (!warned_steps && left <= AppData.HarnessStepsLowWarning) {
|
||||
warned_steps = true;
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unreachable: the text loop ended without an answer.`);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { SupersededSnapshotNote } from "@/src/data/harness-prompts";
|
||||
import type { HarnessMessage } from "../types";
|
||||
import supersedeToolOutputs from "./supersede-tool-outputs";
|
||||
|
||||
const call = (id: string, name: string): HarnessMessage => ({
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [{ id, name, arguments: "{}" }],
|
||||
});
|
||||
|
||||
const result = (id: string, content: string): HarnessMessage => ({ role: "tool", tool_call_id: id, content });
|
||||
|
||||
describe("supersedeToolOutputs", () => {
|
||||
test("keeps only the newest snapshot of each browser", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "Check the site." },
|
||||
call("1", "browser_snapshot"),
|
||||
result("1", "page one"),
|
||||
call("2", "browser_click"),
|
||||
result("2", "clicked"),
|
||||
call("3", "pc__browser_snapshot"),
|
||||
result("3", "my page"),
|
||||
call("4", "browser_snapshot"),
|
||||
result("4", "page two"),
|
||||
];
|
||||
|
||||
expect(supersedeToolOutputs({ transcript })).toBe(1);
|
||||
expect(transcript[2]!.content).toBe(SupersededSnapshotNote);
|
||||
expect(transcript[4]!.content).toBe("clicked");
|
||||
expect(transcript[6]!.content).toBe("my page");
|
||||
expect(transcript[8]!.content).toBe("page two");
|
||||
expect(supersedeToolOutputs({ transcript })).toBe(0);
|
||||
});
|
||||
|
||||
test("a failed snapshot replaces nothing", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
call("1", "browser_snapshot"),
|
||||
result("1", "page one"),
|
||||
call("2", "browser_snapshot"),
|
||||
result("2", "Error: the browser is closed."),
|
||||
];
|
||||
|
||||
expect(supersedeToolOutputs({ transcript })).toBe(0);
|
||||
expect(transcript[1]!.content).toBe("page one");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { SupersededSnapshotNote } from "@/src/data/harness-prompts";
|
||||
import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
import type { HarnessMessage } from "../types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Changed in place, so the run keeps the savings.
|
||||
*/
|
||||
transcript: HarnessMessage[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Keeps only the newest page snapshot of each browser in a run's
|
||||
* transcript: a snapshot shows the page as it was, and the next one
|
||||
* replaces it, so resending the old ones on every turn only costs tokens.
|
||||
* Older ones become a note. A failed snapshot replaces nothing. Returns
|
||||
* how many were replaced.
|
||||
*/
|
||||
export default function supersedeToolOutputs({ transcript }: Params) {
|
||||
const names = new Map<string, string>();
|
||||
|
||||
for (const message of transcript) {
|
||||
if (message.role != "assistant") continue;
|
||||
|
||||
for (const call of message.tool_calls || []) names.set(call.id, call.name);
|
||||
}
|
||||
|
||||
const newest = new Map<string, number>();
|
||||
|
||||
transcript.forEach((message, index) => {
|
||||
if (message.role != "tool" || !isSnapshot({ message, names })) return;
|
||||
|
||||
newest.set(names.get(message.tool_call_id)!, index);
|
||||
});
|
||||
|
||||
let replaced = 0;
|
||||
|
||||
transcript.forEach((message, index) => {
|
||||
if (message.role != "tool" || !isSnapshot({ message, names })) return;
|
||||
if (newest.get(names.get(message.tool_call_id)!) == index) return;
|
||||
|
||||
transcript[index] = { ...message, content: SupersededSnapshotNote };
|
||||
replaced++;
|
||||
});
|
||||
|
||||
return replaced;
|
||||
}
|
||||
|
||||
/**
|
||||
* A successful snapshot that is still shown in full.
|
||||
*/
|
||||
function isSnapshot({ message, names }: { message: HarnessMessage & { role: "tool" }; names: Map<string, string> }) {
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
return (
|
||||
Boolean(name) &&
|
||||
isBrowserTool({ name: name!, action: "browser_snapshot" }) &&
|
||||
!message.content.startsWith("Error:") &&
|
||||
message.content != SupersededSnapshotNote
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
import grabBotById from "@/src/functions/backend/db/bots/grab-bot-by-id";
|
||||
import chatroomAskableBots from "@/src/functions/backend/db/chatrooms/chatroom-askable-bots";
|
||||
import createChatroom from "@/src/functions/backend/db/chatrooms/create-chatroom";
|
||||
import grabCrewRequests from "@/src/functions/backend/db/chatrooms/grab-crew-requests";
|
||||
import chatroomRef from "@/src/utils/chatroom-ref";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
@@ -29,6 +30,7 @@ type Args = {
|
||||
title: string;
|
||||
request: string;
|
||||
bot_id?: number;
|
||||
separate?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -37,18 +39,25 @@ type Args = {
|
||||
* coordinator works out who should answer, asks them, and sends the answer
|
||||
* back to this conversation, which wakes the bot to act on it. Who can be
|
||||
* asked is decided by the app, never the model: in a workspace its
|
||||
* members, otherwise every worker the user reaches.
|
||||
* members, otherwise every worker the user reaches. While one of its
|
||||
* requests from the same place is open, another is refused unless it says
|
||||
* it's `separate`: a task run that couldn't see the open one asked bot 20
|
||||
* for the same two files a third time.
|
||||
*/
|
||||
export default function askCrewTool({ user_id, bot_id, session_id, workspace_id, onChatroom }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "ask_crew",
|
||||
description: `Ask another bot for something you need (what it knows, a file it has, work in its line) through the coordinator. The coordinator reads your request, asks the bot best placed to answer and sends the answer back here as a message, which wakes you to act on it: don't wait or check on it. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
|
||||
description: `Ask another bot for something you need (what it knows, a file it has, work in its line) through the coordinator. The coordinator reads your request, asks the bot best placed to answer and sends the answer back here as a message, which wakes you to act on it: don't wait or check on it. If a task you'd start needs the answer, don't start it in the same reply: it would run without it, so start it once the answer wakes you. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
|
||||
workspace_id ? "You're in a workspace, so only its members can be asked." : "Any bot the user works with can be asked."
|
||||
} The request and everything said about it is kept in a chatroom the user can read.`,
|
||||
} The request and everything said about it is kept in a chatroom the user can read. While a request of yours from here is open, a new one is refused unless it asks for something else (separate: true).`,
|
||||
schema: z.object({
|
||||
title: z.string().trim().min(1).max(80).describe("A short label for the request"),
|
||||
request: z.string().trim().min(1).max(8000).describe("The brief, in markdown"),
|
||||
bot_id: z.number().int().optional().describe("The bot you think can help, if you know"),
|
||||
separate: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("true when this asks for something different from a request of yours that's still open"),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const bot = await grabBotById({ bot_id });
|
||||
@@ -71,6 +80,18 @@ export default function askCrewTool({ user_id, bot_id, session_id, workspace_id,
|
||||
);
|
||||
}
|
||||
|
||||
if (!args.separate) {
|
||||
const open = (await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id })).filter(
|
||||
(room) => room.status == "open",
|
||||
);
|
||||
|
||||
if (open.length) {
|
||||
return `Not asked: you already have ${open
|
||||
.map((room) => `${chatroomRef({ id: room.id! })} "${room.title}"`)
|
||||
.join(", ")} open. Its answer comes back here as a message and wakes you, so don't ask again for the same thing. If this asks for something different, call ask_crew again with separate: true.`;
|
||||
}
|
||||
}
|
||||
|
||||
const named = args.bot_id ? askable.find((other) => other.id == args.bot_id) : null;
|
||||
|
||||
if (args.bot_id && !named) {
|
||||
|
||||
@@ -96,6 +96,13 @@ describe("delegateTaskTool", () => {
|
||||
expect(tool.description).toContain("task_id");
|
||||
});
|
||||
|
||||
test("can hand a task over without starting it", () => {
|
||||
const tool = coordinatorTool();
|
||||
|
||||
expect(tool.schema?.safeParse({ bot_id: 5, task_id: 27, start: false }).success).toBe(true);
|
||||
expect(tool.description).toContain("start: false");
|
||||
});
|
||||
|
||||
test("without a task_id, still needs a title and instructions", async () => {
|
||||
const tool = delegateTaskTool({
|
||||
user_id: 1,
|
||||
|
||||
@@ -63,6 +63,10 @@ type Args = {
|
||||
* and the worker works that same task.
|
||||
*/
|
||||
task_id?: number;
|
||||
/**
|
||||
* With `task_id`: false to only move the task, nothing started.
|
||||
*/
|
||||
start?: boolean;
|
||||
title?: string;
|
||||
instructions?: string;
|
||||
/**
|
||||
@@ -104,7 +108,7 @@ export default function delegateTaskTool({
|
||||
|
||||
return {
|
||||
name: "delegate_task",
|
||||
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there), goes to doing, and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. Crew: ${crew}.${
|
||||
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there), goes to doing, and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. When the user hasn't asked for that task's work to begin yet (they want it moved, or to decide first), add start: false: it only moves to their list as to do, and no run is spent on reporting that they're waiting. Crew: ${crew}.${
|
||||
workspace_id
|
||||
? ` You are working in a workspace, so the task runs there: in this workspace's context.`
|
||||
: ` Leave workspace_id out to run it in the crew member's own chat: only its own memory, files and directly assigned computers apply there, and the user finds the result by talking to it on its own. Add workspace_id to run it in one of the user's workspaces instead: the workspace's shared context, the member's instructions and memory there, its files and its computers (the workspace's own and the member's) all apply, and the result lands in its conversation in that workspace, beside the project it belongs to. Pick a workspace when the work belongs to that project; the member is added to it when it isn't in it yet. Workspaces: ${places || "none"}.`
|
||||
@@ -112,6 +116,10 @@ export default function delegateTaskTool({
|
||||
schema: z.object({
|
||||
bot_id: z.number().int(),
|
||||
task_id: z.number().int().optional().describe("An open task (list_tasks) to hand over as it is"),
|
||||
start: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("With task_id: false to only move the task (to do, nothing runs) until the user says to start"),
|
||||
title: z.string().min(1).max(80).optional(),
|
||||
instructions: z.string().min(1).max(8000).optional(),
|
||||
workspace_id: z
|
||||
@@ -184,11 +192,16 @@ export default function delegateTaskTool({
|
||||
handed_by: requester_name,
|
||||
requested_by_bot_id: requester_id,
|
||||
requested_by_session_id: session_id,
|
||||
start: args.start !== false,
|
||||
});
|
||||
|
||||
return `Task #${task.id} "${task.title}" is with ${worker.name} now (job #${handed.job_id})${
|
||||
handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in their own chat"
|
||||
}, marked doing.${handed.joined} They work that same task; the result is reported back here.`;
|
||||
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in their own chat";
|
||||
|
||||
if (!handed.job_id) {
|
||||
return `Task #${task.id} "${task.title}" is on ${worker.name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.${handed.joined}`;
|
||||
}
|
||||
|
||||
return `Task #${task.id} "${task.title}" is with ${worker.name} now (job #${handed.job_id})${where}, marked doing.${handed.joined} They work that same task; the result is reported back here.`;
|
||||
}
|
||||
|
||||
if (!args.title?.trim() || !args.instructions?.trim()) {
|
||||
|
||||
@@ -97,7 +97,7 @@ export default function startTaskTool({
|
||||
|
||||
if (open) {
|
||||
throw new Error(
|
||||
`Run #${open.id} "${open.title || "Task"}" is still ${open.status == "pending" ? "queued" : "under way"} here on that computer. If this is the same work, don't start it again: its result will be posted here (the user can Stop it to start over). If it's different work, call start_task again now with separate: true; it's queued and starts as soon as run #${open.id} ends. Nothing starts it later but you, now, so never tell the user you'll start it once run #${open.id} is done.`,
|
||||
`Run #${open.id} "${open.title || "Task"}" is still ${open.status == "pending" ? "queued" : "under way"} here on that computer. If this is the same work, don't start it again: its result will be posted here (the user can Stop it to start over). It's shown what the user writes here between its steps, so a correction or addition to that work reaches it and never calls for another run. If it's different work, call start_task again now with separate: true; it's queued and starts as soon as run #${open.id} ends. Nothing starts it later but you, now, so never tell the user you'll start it once run #${open.id} is done.`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import type { TaskFile } from "@/src/types";
|
||||
import describeTaskLog from "./describe-task-log";
|
||||
|
||||
const task = { id: 27, status: "doing", title: "Aspen Dental", bot_id: 21, workspace_id: 3 } as BUN_SQLITE_COBBLE_TASKS;
|
||||
|
||||
describe("describeTaskLog", () => {
|
||||
test("lists what's filed, bot files by their ref", () => {
|
||||
const files = [
|
||||
{ id: 1, task_id: 27, media_id: 9, bot_file_id: 303, kind: "deliverable", name: "v1.png" },
|
||||
{ id: 2, task_id: 27, media_id: 10, kind: "reference", name: "brief.pdf" },
|
||||
] as TaskFile[];
|
||||
|
||||
const text = describeTaskLog({ task, notes: [], files, bot_id: 21 });
|
||||
|
||||
expect(text).toContain("Files (2):");
|
||||
expect(text).toContain("- deliverable: [file:303] v1.png");
|
||||
expect(text).toContain("- reference: the user's upload brief.pdf");
|
||||
});
|
||||
|
||||
test("leaves the files out when there are none", () => {
|
||||
expect(describeTaskLog({ task, notes: [], bot_id: 21 })).not.toContain("Files");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import type { TaskNote } from "@/src/types";
|
||||
import type { TaskFile, TaskNote } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
task: BUN_SQLITE_COBBLE_TASKS;
|
||||
notes: TaskNote[];
|
||||
/**
|
||||
* What's filed on it (`grabTaskMedia`), so a bot can name, check and
|
||||
* unlink them.
|
||||
*/
|
||||
files?: TaskFile[];
|
||||
/**
|
||||
* The run's own bot, named "you" in the log.
|
||||
*/
|
||||
@@ -13,9 +18,10 @@ type Params = {
|
||||
/**
|
||||
* One task for a bot's run: where it is, its brief and its whole log, each
|
||||
* note with who wrote it (bot name and id, or the user) and when, so a bot
|
||||
* on a workspace-wide task sees what the others already did.
|
||||
* on a workspace-wide task sees what the others already did, and its files
|
||||
* (a bot file by its `[file:ID]` ref, a user's upload by name).
|
||||
*/
|
||||
export default function describeTaskLog({ task, notes, bot_id }: Params) {
|
||||
export default function describeTaskLog({ task, notes, files = [], bot_id }: Params) {
|
||||
const who = task.bot_id
|
||||
? task.bot_id == Number(bot_id)
|
||||
? "yours"
|
||||
@@ -38,10 +44,20 @@ export default function describeTaskLog({ task, notes, bot_id }: Params) {
|
||||
.join("\n")
|
||||
: "- Nothing logged yet.";
|
||||
|
||||
const filed = files.length
|
||||
? files
|
||||
.map(
|
||||
(file) =>
|
||||
`- ${file.kind}: ${file.bot_file_id ? `[file:${file.bot_file_id}] ` : "the user's upload "}${file.name}${file.missing ? " (its bytes are gone)" : ""}`,
|
||||
)
|
||||
.join("\n")
|
||||
: "";
|
||||
|
||||
return [
|
||||
`#${task.id} [${task.status}] ${task.title} (${task.workspace_id ? `in workspace ${task.workspace_id}, ` : ""}${who})`,
|
||||
task.status == "blocked" && task.blocked_reason ? `Blocked: ${task.blocked_reason}` : "",
|
||||
`Brief:\n${task.description?.trim() || "(none)"}`,
|
||||
filed ? `Files (${files.length}):\n${filed}` : "",
|
||||
`Log, oldest first:\n${log}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { type TaskStatus, TaskStatusValues } from "@/src/dict/task-dict";
|
||||
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
|
||||
import grabTaskNotes from "@/src/functions/backend/db/tasks/grab-task-notes";
|
||||
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
|
||||
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
|
||||
import describeTaskLog from "./describe-task-log";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
@@ -61,7 +62,12 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
|
||||
if (args.task_id) {
|
||||
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
|
||||
|
||||
return describeTaskLog({ task, notes: await grabTaskNotes({ task_id: task.id! }), bot_id });
|
||||
return describeTaskLog({
|
||||
task,
|
||||
notes: await grabTaskNotes({ task_id: task.id! }),
|
||||
files: await grabTaskMedia({ task_id: task.id! }),
|
||||
bot_id,
|
||||
});
|
||||
}
|
||||
|
||||
const scope = args.scope || "all";
|
||||
|
||||
@@ -22,6 +22,12 @@ describe("updateTaskTool", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("takes files to unlink, and says how to make room", () => {
|
||||
expect(tool.schema?.safeParse({ task_id: 20, unlink_file_ids: [303, 304] }).success).toBe(true);
|
||||
expect(tool.description).toContain("unlink_file_ids");
|
||||
expect(tool.description).toContain(`holds ${AppData.TaskMediaMaxPerTask} files`);
|
||||
});
|
||||
|
||||
test("tells the bot to rename rather than add a second task", () => {
|
||||
expect(tool.description).toContain("Rename it with title");
|
||||
expect(tool.description).toContain("never create a second task");
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import { type TaskStatus, TaskStatusValues } from "@/src/dict/task-dict";
|
||||
import addTaskNote from "@/src/functions/backend/db/tasks/add-task-note";
|
||||
import attachTaskFile from "@/src/functions/backend/db/tasks/attach-task-file";
|
||||
import detachTaskFile from "@/src/functions/backend/db/tasks/detach-task-file";
|
||||
import findDuplicateTask from "@/src/functions/backend/db/tasks/find-duplicate-task";
|
||||
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
|
||||
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
|
||||
@@ -36,6 +37,7 @@ type Args = {
|
||||
note?: string;
|
||||
deliverable_file_ids?: number[];
|
||||
reference_file_ids?: number[];
|
||||
unlink_file_ids?: number[];
|
||||
workspace_wide?: boolean;
|
||||
};
|
||||
|
||||
@@ -58,7 +60,7 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
|
||||
return {
|
||||
name: "update_task",
|
||||
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
|
||||
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
|
||||
schema: z.object({
|
||||
task_id: z.number().int(),
|
||||
title: z
|
||||
@@ -92,6 +94,10 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
.array(z.number().int())
|
||||
.optional()
|
||||
.describe(`The [file:ID] refs of files it works from`),
|
||||
unlink_file_ids: z
|
||||
.array(z.number().int())
|
||||
.optional()
|
||||
.describe(`The [file:ID] refs of files filed on the task to take off it (they stay in their folder). The user's own uploads can't be unlinked this way.`),
|
||||
workspace_wide: z
|
||||
.boolean()
|
||||
.optional()
|
||||
@@ -189,6 +195,29 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
}
|
||||
}
|
||||
|
||||
if (args.unlink_file_ids?.length) {
|
||||
const filed = await grabTaskMedia({ task_id: task.id! });
|
||||
|
||||
for (const file_id of args.unlink_file_ids) {
|
||||
const link = filed.find((file) => Number(file.bot_file_id || 0) == Number(file_id));
|
||||
|
||||
if (!link?.id) {
|
||||
said.push(`file ${file_id} isn't filed on it`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await detachTaskFile({ task_id: task.id!, task_media_id: link.id, user_id });
|
||||
said.push(`unlinked "${link.name}"`);
|
||||
done.push(`Unlinked "${link.name}".`);
|
||||
} catch (error: unknown) {
|
||||
said.push(
|
||||
`couldn't unlink file ${file_id}: ${error instanceof Error ? error.message : "unknown error"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [kind, ids] of [
|
||||
["deliverable", args.deliverable_file_ids],
|
||||
["reference", args.reference_file_ids],
|
||||
|
||||
@@ -114,15 +114,21 @@ export default async function openBotBrowsers({
|
||||
if (names.has(name)) continue;
|
||||
|
||||
names.add(name);
|
||||
tools.push(
|
||||
mcpHarnessTool({
|
||||
/**
|
||||
* Deferred: listed by name until the run loads them
|
||||
* (`load_tools`), so a turn that doesn't browse doesn't carry
|
||||
* every browser tool's definition.
|
||||
*/
|
||||
tools.push({
|
||||
...mcpHarnessTool({
|
||||
name,
|
||||
tool: { ...tool, description: `${browser.name}: ${tool.description}` },
|
||||
client,
|
||||
redact,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
}),
|
||||
);
|
||||
deferred: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
|
||||
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
|
||||
import shareRoomFiles from "@/src/functions/backend/db/chatrooms/share-room-files";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
type Params = {
|
||||
@@ -21,7 +22,9 @@ type Args = {
|
||||
|
||||
/**
|
||||
* The coordinator sends the answer back to the bot that asked, closing the
|
||||
* room as answered (`closeChatroom`).
|
||||
* room as answered (`closeChatroom`). Files it names that the asker can't
|
||||
* read are copied to it first and their refs pointed at the copies
|
||||
* (`shareRoomFiles`).
|
||||
*/
|
||||
export default function answerRequesterTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
@@ -31,7 +34,8 @@ export default function answerRequesterTool({ chatroom, job_id, onClosed }: Para
|
||||
answer: z.string().trim().min(1).max(12000),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "answered", outcome: args.answer, job_id });
|
||||
const outcome = await shareRoomFiles({ chatroom, answer: args.answer });
|
||||
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "answered", outcome, job_id });
|
||||
|
||||
if (!closed) {
|
||||
throw new Error(`This room is already closed.`);
|
||||
|
||||
@@ -47,6 +47,13 @@ type Params = {
|
||||
* Without it, or without a user, the bot can't capture secrets.
|
||||
*/
|
||||
onSecretRef?: (params: { ref: string }) => void;
|
||||
/**
|
||||
* False for a run sharing the computer with the one that holds it
|
||||
* (`processBotJob`): only its shell and files, since the browser is
|
||||
* one Chrome and two runs driving it would take each other's tabs.
|
||||
* Defaults to true.
|
||||
*/
|
||||
browser?: boolean;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
@@ -83,6 +90,7 @@ export default async function openComputerTools({
|
||||
workspace_id,
|
||||
dirs,
|
||||
onSecretRef,
|
||||
browser = true,
|
||||
signal,
|
||||
}: Params): Promise<OpenComputer> {
|
||||
const target = await grabComputerMcpUrl({ computer_id });
|
||||
@@ -117,16 +125,20 @@ export default async function openComputerTools({
|
||||
const secrets: { key: string; value: string }[] = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
|
||||
const client = await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal });
|
||||
const client = browser
|
||||
? await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal })
|
||||
: null;
|
||||
const context: ComputerToolContext = { computer: target, dirs, shell_path: paths.shell_path, redact };
|
||||
|
||||
try {
|
||||
const browser_tools = await grabMcpTools({
|
||||
client,
|
||||
exclude: ComputerMcpExcludedTools,
|
||||
redact,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
});
|
||||
const browser_tools = client
|
||||
? await grabMcpTools({
|
||||
client,
|
||||
exclude: ComputerMcpExcludedTools,
|
||||
redact,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
})
|
||||
: [];
|
||||
|
||||
return {
|
||||
name: target.name,
|
||||
@@ -160,10 +172,12 @@ export default async function openComputerTools({
|
||||
],
|
||||
envs: envs.map((env) => ({ key: env.key, description: env.description })),
|
||||
redact,
|
||||
close: () => client.close().catch(() => {}),
|
||||
close: async () => {
|
||||
await client?.close().catch(() => {});
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await client.close().catch(() => {});
|
||||
await client?.close().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,8 @@ export type OpenBotExtensions = {
|
||||
/**
|
||||
* The MCP servers' and custom tools' tools a bot gets on one run
|
||||
* (`grabBotExtensions`), as harness tools. MCP tools are built from each
|
||||
* server's last listing (`<slug>__<tool>`) and connect on their first call,
|
||||
* server's last listing (`<slug>__<tool>`), deferred until the run loads
|
||||
* them (`HarnessTool.deferred`), and connect on their first call,
|
||||
* so a run that doesn't use them never waits on them. Secret env values are
|
||||
* blanked out of every result. Call `close` when the run ends.
|
||||
*/
|
||||
@@ -106,15 +107,21 @@ export default async function openBotExtensions({
|
||||
const open = openMcpServer({ server, envs, signal });
|
||||
opened.push(open);
|
||||
|
||||
/**
|
||||
* Deferred: listed by name until the run loads them (`load_tools`).
|
||||
* One server's definitions alone ran to 30,000 characters, sent
|
||||
* with every turn of every run.
|
||||
*/
|
||||
for (const tool of listed) {
|
||||
add(
|
||||
mcpHarnessTool({
|
||||
add({
|
||||
...mcpHarnessTool({
|
||||
name: mcpToolName({ slug: server.slug, name: tool.name }),
|
||||
tool: { ...tool, description: `${server.name}: ${tool.description}` },
|
||||
client: open.client,
|
||||
redact,
|
||||
}),
|
||||
);
|
||||
deferred: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { z } from "zod";
|
||||
import type { HarnessTool } from "../types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The run's deferred tools (`HarnessTool.deferred`).
|
||||
*/
|
||||
deferred: HarnessTool[];
|
||||
/**
|
||||
* Whether a tool is already loaded.
|
||||
*/
|
||||
isLoaded: (name: string) => boolean;
|
||||
/**
|
||||
* Loads them: their definitions go with every turn from the next one.
|
||||
*/
|
||||
onLoad: (names: string[]) => void;
|
||||
};
|
||||
|
||||
export const LoadToolsToolName = "load_tools";
|
||||
|
||||
/**
|
||||
* Brings deferred tools into the run (`runTextLoop`): the model sees them
|
||||
* listed by name in its prompt and loads the ones it needs, rather than
|
||||
* every turn carrying every extension's definitions. A name ending in `*`
|
||||
* loads every deferred tool it starts.
|
||||
*/
|
||||
export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): HarnessTool<{ names: string[] }> {
|
||||
return {
|
||||
name: LoadToolsToolName,
|
||||
description: `Loads tools from the "Tools you can load" list in your instructions, so you can call them from your next step. Give their exact names; "<prefix>*" loads every listed tool starting with the prefix (e.g. one server's). Load only what you're about to use.`,
|
||||
schema: z.object({
|
||||
names: z.array(z.string().trim().min(1).max(200)).min(1).max(40),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const found = new Set<string>();
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const name of args.names) {
|
||||
const matches = name.endsWith("*")
|
||||
? deferred.filter((tool) => tool.name.startsWith(name.slice(0, -1)))
|
||||
: deferred.filter((tool) => tool.name == name);
|
||||
|
||||
if (!matches.length) missing.push(name);
|
||||
|
||||
for (const tool of matches) found.add(tool.name);
|
||||
}
|
||||
|
||||
const fresh = [...found].filter((name) => !isLoaded(name));
|
||||
const already = [...found].filter((name) => isLoaded(name));
|
||||
|
||||
if (fresh.length) onLoad(fresh);
|
||||
|
||||
return [
|
||||
fresh.length ? `Loaded: ${fresh.join(", ")}. Call them from your next step.` : "",
|
||||
already.length ? `Already loaded: ${already.join(", ")}.` : "",
|
||||
missing.length ? `Not in the list: ${missing.join(", ")}. Use the exact names under "Tools you can load".` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -65,6 +65,19 @@ describe("runToolCall", () => {
|
||||
expect(result).toEndWith("[Cut: 5 more characters.]");
|
||||
});
|
||||
|
||||
test("cuts a browser tool's result sooner, saying how to see the rest", async () => {
|
||||
const browser: HarnessTool<{ text: string }> = { ...echo, name: "pc__browser_evaluate" };
|
||||
const long = "x".repeat(AppData.HarnessBrowserResultMaxChars + 7);
|
||||
const { text } = await runToolCall({
|
||||
call: { id: "1", name: browser.name, arguments: JSON.stringify({ text: long }) },
|
||||
tools: [browser],
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(text).toStartWith("x".repeat(AppData.HarnessBrowserResultMaxChars) + "\n[Cut: 7 more characters.");
|
||||
expect(text).toContain("Narrow the call");
|
||||
});
|
||||
|
||||
test("passes images on, capped and marked as a tool's", async () => {
|
||||
const result = await run("shot", "{}");
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import isBrowserTool from "@/src/utils/browser-tool-name";
|
||||
import TaskTimeoutError from "@/src/utils/task-timeout-error";
|
||||
import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "../harness-error";
|
||||
import unknownToolArgs from "./unknown-tool-args";
|
||||
import unknownToolMessage from "./unknown-tool-message";
|
||||
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
|
||||
|
||||
type Params = {
|
||||
@@ -35,7 +37,7 @@ export default async function runToolCall({ call, tools, signal }: Params): Prom
|
||||
if (typeof text == "string") return { text, images: [] };
|
||||
|
||||
return {
|
||||
text: truncate({ text: text.text }),
|
||||
text: truncate({ text: text.text, name: call.name }),
|
||||
images: text.images
|
||||
.slice(0, AppData.HarnessToolMaxImages)
|
||||
.map((image) => ({ ...image, from_tool: true })),
|
||||
@@ -46,7 +48,7 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
const tool = tools.find((t) => t.name == call.name);
|
||||
|
||||
if (!tool) {
|
||||
return `Error: There is no tool called "${call.name}". Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
|
||||
return unknownToolMessage({ name: call.name, tools });
|
||||
}
|
||||
|
||||
let raw: unknown;
|
||||
@@ -85,7 +87,7 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}),
|
||||
});
|
||||
|
||||
return typeof output == "string" ? truncate({ text: output }) : output;
|
||||
return typeof output == "string" ? truncate({ text: output, name: call.name }) : output;
|
||||
} catch (error: unknown) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
@@ -99,10 +101,16 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}
|
||||
}
|
||||
|
||||
function truncate({ text }: { text: string }) {
|
||||
const max = AppData.HarnessToolResultMaxChars;
|
||||
/**
|
||||
* A result past its tool's cap is cut there. Browser tools get the
|
||||
* smaller cap: a page snapshot or an evaluate over a whole page was the
|
||||
* heaviest thing a run kept resending.
|
||||
*/
|
||||
function truncate({ text, name }: { text: string; name: string }) {
|
||||
const browser = isBrowserTool({ name });
|
||||
const max = browser ? AppData.HarnessBrowserResultMaxChars : AppData.HarnessToolResultMaxChars;
|
||||
|
||||
if (text.length <= max) return text;
|
||||
|
||||
return `${text.slice(0, max)}\n[Cut: ${text.length - max} more characters.]`;
|
||||
return `${text.slice(0, max)}\n[Cut: ${text.length - max} more characters.${browser ? " Narrow the call (a selector, an element ref, a smaller evaluate) to see the rest." : ""}]`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unknownToolMessage from "./unknown-tool-message";
|
||||
|
||||
describe("unknownToolMessage", () => {
|
||||
test("lists the tools for an unknown tool", () => {
|
||||
expect(unknownToolMessage({ name: "nope", tools: [{ name: "a" }, { name: "b" }] })).toBe(
|
||||
`Error: There is no tool called "nope". Available: a, b.`,
|
||||
);
|
||||
});
|
||||
|
||||
test("points a reply's browser call to start_task", () => {
|
||||
const text = unknownToolMessage({ name: "browser_navigate", tools: [{ name: "start_task" }] });
|
||||
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
expect(text).toContain("call start_task");
|
||||
});
|
||||
|
||||
test("says where computer tools live without offering start_task when there is none", () => {
|
||||
const text = unknownToolMessage({ name: "computer_bash", tools: [{ name: "list_files" }] });
|
||||
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
expect(text).not.toContain("start_task");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { HarnessTool } from "@/src/harness/types";
|
||||
|
||||
type Params = {
|
||||
name: string;
|
||||
tools: Pick<HarnessTool, "name">[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Computer tools: the app's own shell and file tools and Playwright MCP's
|
||||
* browser tools, which only a task run on a computer has.
|
||||
*/
|
||||
const ComputerToolPattern = /^(?:computer_|browser_)/;
|
||||
|
||||
/**
|
||||
* What a call to a tool the run doesn't have gets back. A computer or
|
||||
* browser tool called from a run without one (a chat reply, seeing them in
|
||||
* its history's app records) is told to start a task: a weak model called
|
||||
* `browser_navigate` from a reply three times, then told the user it had
|
||||
* no browser.
|
||||
*/
|
||||
export default function unknownToolMessage({ name, tools }: Params) {
|
||||
const available = `Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
|
||||
|
||||
if (!ComputerToolPattern.test(name)) {
|
||||
return `Error: There is no tool called "${name}". ${available}`;
|
||||
}
|
||||
|
||||
const can_start = tools.some((t) => t.name == "start_task");
|
||||
|
||||
return `Error: There is no tool called "${name}" here: computer and browser tools only exist in a task on a computer.${
|
||||
can_start
|
||||
? " To use the computer or its browser (an open tab, a site the user is logged in to), call start_task with a clear brief, then tell the user what you're doing. You can use the computer that way; never say you can't."
|
||||
: ""
|
||||
} ${available}`;
|
||||
}
|
||||
+15
-2
@@ -101,6 +101,12 @@ export type HarnessTool<Args = any> = {
|
||||
description: string;
|
||||
schema?: z.ZodType<Args>;
|
||||
parameters?: Record<string, unknown>;
|
||||
/**
|
||||
* Listed by name only until the model loads it with `load_tools`
|
||||
* (`runTextLoop`): an extension's or a user browser's tools, whose
|
||||
* definitions would otherwise ride along on every turn.
|
||||
*/
|
||||
deferred?: boolean;
|
||||
run: (params: { args: Args; signal: AbortSignal }) => Promise<HarnessToolOutput>;
|
||||
};
|
||||
|
||||
@@ -169,13 +175,20 @@ export type HarnessCandidate = {
|
||||
provider: HarnessProviderConfig;
|
||||
model: HarnessModelInfo;
|
||||
/**
|
||||
* `pinned`: the super admin's pick. `auto`: an automatic free pick.
|
||||
* `pinned`: the setting's pick. `fallback`: one of the setting's
|
||||
* fallback models, tried in order after it. `auto`: an automatic free
|
||||
* pick.
|
||||
*/
|
||||
source: "pinned" | "auto";
|
||||
source: "pinned" | "fallback" | "auto";
|
||||
};
|
||||
|
||||
export type HarnessUsage = {
|
||||
prompt_tokens?: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its cache
|
||||
* (billed lower), when it says.
|
||||
*/
|
||||
cached_tokens?: number;
|
||||
completion_tokens?: number;
|
||||
/**
|
||||
* In the provider's currency (USD for OpenRouter), when reported.
|
||||
|
||||
@@ -42,12 +42,23 @@ describe("buildUsageCall", () => {
|
||||
model_id: 41,
|
||||
model_slug: "deepseek/deepseek-chat",
|
||||
prompt_tokens: 1200,
|
||||
cached_tokens: 0,
|
||||
completion_tokens: 340,
|
||||
cost: 0.0042,
|
||||
settings: { model_source: "auto" },
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps how much of the prompt the provider served from its cache", () => {
|
||||
const call = buildUsageCall({
|
||||
harness: "text",
|
||||
candidate: candidate(),
|
||||
usage: { prompt_tokens: 1200, cached_tokens: 900, completion_tokens: 340 },
|
||||
});
|
||||
|
||||
expect(call.cached_tokens).toBe(900);
|
||||
});
|
||||
|
||||
test("keeps the settings sent and the models that failed first", () => {
|
||||
const call = buildUsageCall({
|
||||
harness: "text",
|
||||
|
||||
@@ -10,11 +10,15 @@ type Params = {
|
||||
* whose they were. The model's source and the fallback are filled in
|
||||
* here.
|
||||
*/
|
||||
settings?: Omit<HarnessCallSettings, "model_source" | "fell_back_from">;
|
||||
settings?: Omit<HarnessCallSettings, "model_source" | "fell_back_from" | "resting">;
|
||||
/**
|
||||
* The candidates that failed before this one (`withCandidates`).
|
||||
*/
|
||||
failed?: string[];
|
||||
/**
|
||||
* The candidates ahead of it passed over while resting.
|
||||
*/
|
||||
resting?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -23,7 +27,7 @@ type Params = {
|
||||
* still get a row (no tokens), so a call is never invisible. Its settings
|
||||
* say how it was made, for a message's details.
|
||||
*/
|
||||
export default function buildUsageCall({ harness, candidate, usage, settings, failed }: Params): HarnessUsageCall {
|
||||
export default function buildUsageCall({ harness, candidate, usage, settings, failed, resting }: Params): HarnessUsageCall {
|
||||
return {
|
||||
harness,
|
||||
provider_id: candidate.provider.id,
|
||||
@@ -31,12 +35,14 @@ export default function buildUsageCall({ harness, candidate, usage, settings, fa
|
||||
model_id: modelIdOf(candidate),
|
||||
model_slug: candidate.model.slug,
|
||||
prompt_tokens: Number(usage?.prompt_tokens) || 0,
|
||||
cached_tokens: Number(usage?.cached_tokens) || 0,
|
||||
completion_tokens: Number(usage?.completion_tokens) || 0,
|
||||
cost: typeof usage?.cost == "number" && Number.isFinite(usage.cost) ? usage.cost : undefined,
|
||||
settings: {
|
||||
model_source: candidate.source,
|
||||
...settings,
|
||||
...(failed?.length ? { fell_back_from: failed } : {}),
|
||||
...(resting?.length ? { resting } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ export default async function recordHarnessUsage({ scope, call }: Params) {
|
||||
model_id: call.model_id,
|
||||
model_slug: call.model_slug,
|
||||
prompt_tokens: Math.max(0, Math.round(call.prompt_tokens || 0)),
|
||||
cached_tokens: Math.max(0, Math.round(call.cached_tokens || 0)),
|
||||
completion_tokens: Math.max(0, Math.round(call.completion_tokens || 0)),
|
||||
cost: typeof call.cost == "number" && Number.isFinite(call.cost) ? call.cost : undefined,
|
||||
settings: call.settings ? JSON.stringify(call.settings) : undefined,
|
||||
|
||||
@@ -32,9 +32,10 @@ export type HarnessUsageScope = {
|
||||
*/
|
||||
export type HarnessCallSettings = {
|
||||
/**
|
||||
* `pinned`: the model picked in the setting. `auto`: an automatic pick.
|
||||
* `pinned`: the model picked in the setting. `fallback`: one of its
|
||||
* fallback models. `auto`: an automatic pick.
|
||||
*/
|
||||
model_source: "pinned" | "auto";
|
||||
model_source: "pinned" | "fallback" | "auto";
|
||||
/**
|
||||
* Whose setting the call used: the workspace's, the bot's own or the
|
||||
* install's default. Left out when the call overrode it.
|
||||
@@ -55,6 +56,11 @@ export type HarnessCallSettings = {
|
||||
* answered, in the order they were tried.
|
||||
*/
|
||||
fell_back_from?: string[];
|
||||
/**
|
||||
* The candidates ahead of this one passed over because they were
|
||||
* resting after an earlier failure, in order.
|
||||
*/
|
||||
resting?: string[];
|
||||
};
|
||||
|
||||
export type HarnessUsageCall = {
|
||||
@@ -64,6 +70,10 @@ export type HarnessUsageCall = {
|
||||
model_id?: number;
|
||||
model_slug?: string;
|
||||
prompt_tokens: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its cache.
|
||||
*/
|
||||
cached_tokens?: number;
|
||||
completion_tokens: number;
|
||||
cost?: number;
|
||||
settings?: HarnessCallSettings;
|
||||
@@ -75,6 +85,11 @@ export type HarnessUsageCall = {
|
||||
*/
|
||||
export type TokenUsageSummary = {
|
||||
prompt_tokens: number;
|
||||
/**
|
||||
* Of the prompt tokens, how many the providers served from their
|
||||
* cache. Left out when none were (or none said).
|
||||
*/
|
||||
cached_tokens?: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
/**
|
||||
@@ -85,4 +100,11 @@ export type TokenUsageSummary = {
|
||||
* How many model calls it took.
|
||||
*/
|
||||
calls: number;
|
||||
/**
|
||||
* Messages only: a model that answered text calls in place of the one
|
||||
* ahead of it (it failed or was resting), and how many calls it
|
||||
* answered so. Left out when every text call ran on the first choice.
|
||||
*/
|
||||
fallback_model?: string;
|
||||
fallback_calls?: number;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import type { LastConversation } from "@/src/types";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
|
||||
type Props = {
|
||||
conversation: LastConversation;
|
||||
};
|
||||
|
||||
/**
|
||||
* Above the rail's list on settings and the rail pages: back to the
|
||||
* conversation this browser was last in, the bot's own chat or a
|
||||
* workspace's (named under the bot). The logo still goes to `/admin/bots`.
|
||||
* Avatar only when the rail collapses. The stone stays idle: this row
|
||||
* isn't live, so it never shows a status it can't keep current.
|
||||
*/
|
||||
export default function RailLastConversation({ conversation }: Props) {
|
||||
const { bot, workspace, href } = conversation;
|
||||
const title = workspace
|
||||
? `Back to ${bot.name} in ${workspace.name}`
|
||||
: `Back to ${bot.name}`;
|
||||
|
||||
return (
|
||||
<Stack className="shrink-0 gap-0! items-stretch px-2 @rail:px-3 pb-3">
|
||||
<Link
|
||||
href={href}
|
||||
title={title}
|
||||
aria-label={title}
|
||||
className={twMerge(
|
||||
"flex shrink-0 h-14 items-center gap-3 rounded-default px-1 @rail:px-3 leading-normal text-ink",
|
||||
"border-0 @rail:border @rail:border-solid @rail:border-hairline",
|
||||
"hover:opacity-100 hover:bg-sunken transition-colors duration-[var(--m-fast)]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper",
|
||||
)}
|
||||
>
|
||||
<Span className="hidden @rail:flex shrink-0 items-center justify-center text-ink-secondary">
|
||||
<ArrowLeft size={16} aria-hidden />
|
||||
</Span>
|
||||
<Span className="shrink-0 flex items-center justify-center mx-auto @rail:mx-0">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
/>
|
||||
</Span>
|
||||
<Stack className="hidden @rail:flex grow min-w-0 gap-0!">
|
||||
<Span className="w-full text-sm font-bold leading-5 text-ink truncate">
|
||||
{bot.name}
|
||||
</Span>
|
||||
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
|
||||
{workspace ? `In ${workspace.name}` : "Back to the conversation"}
|
||||
</Span>
|
||||
</Stack>
|
||||
</Link>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import useLiveWorkspaces from "../(hooks)/use-live-workspaces";
|
||||
import { RailPages } from "@/src/dict/rail-pages-dict";
|
||||
import { RailDrawerContext } from "../(data)/rail-drawer-context";
|
||||
import RailHeader from "../(partials)/rail-header";
|
||||
import RailLastConversation from "../(partials)/rail-last-conversation";
|
||||
import RailPagesList from "../(partials)/rail-pages-list";
|
||||
import RailCrewList from "../(partials)/rail-crew-list";
|
||||
import RailSettingsAside from "../(partials)/rail-settings-aside";
|
||||
@@ -17,9 +18,10 @@ import RailWorkspaceList from "../(partials)/rail-workspace-list";
|
||||
/**
|
||||
* Left rail: wordmark and Add, then the crew (pinned coordinator first,
|
||||
* the latest bots, the workspaces). Inside a workspace it lists that
|
||||
* workspace's crew instead; on `/admin/settings/*` a back link and the
|
||||
* settings sub pages, and on routines, activity and help a back link and
|
||||
* those pages (`RailPages`). Below `md` it is a slide-over drawer from the
|
||||
* workspace's crew instead; on `/admin/settings/*` the settings sub pages,
|
||||
* and on routines, files, usage, activity and help those pages
|
||||
* (`RailPages`), both under a way back to the last conversation
|
||||
* (`last_conversation`, the bot's own chat or a workspace's). Below `md` it is a slide-over drawer from the
|
||||
* pane header's menu button; from `md` it is a 64px icon rail, and from
|
||||
* `lg` the full 260px rail. Its own width, not the viewport's, decides
|
||||
* whether it shows names (a container query), so the drawer opens full.
|
||||
@@ -77,6 +79,9 @@ export default function BotsRail() {
|
||||
}
|
||||
>
|
||||
<RailHeader show_add={!is_settings_page && !is_rail_page} />
|
||||
{(is_settings_page || is_rail_page) && pageProps?.last_conversation ? (
|
||||
<RailLastConversation conversation={pageProps.last_conversation} />
|
||||
) : null}
|
||||
<Stack className="grow min-h-0 overflow-y-auto gap-0! items-stretch px-2 @rail:px-3 pt-1 pb-3">
|
||||
{is_settings_page ? (
|
||||
<RailSettingsAside pathname={pathname} />
|
||||
|
||||
@@ -8,6 +8,8 @@ import isUnknownSettingsPath from "../utils/is-unknown-settings-path";
|
||||
import { SettingsDefaultPath } from "../dict/settings-pages-dict";
|
||||
import grabInstallName from "../functions/backend/db/app-settings/grab-install-name";
|
||||
import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-icon";
|
||||
import grabLastConversation from "../functions/backend/db/bot-sessions/grab-last-conversation";
|
||||
import isPagesRailPath from "../utils/is-pages-rail-path";
|
||||
|
||||
/**
|
||||
* Routing for a local install. There are no public pages:
|
||||
@@ -17,6 +19,9 @@ import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-i
|
||||
* - an unknown `/admin/settings/*` page: `/admin/settings/general`
|
||||
* - `/admin/*` logged out: `/auth/login`
|
||||
* - `/auth/*` logged in (except logout): `/admin/bots`
|
||||
*
|
||||
* Settings and the rail pages also get the conversation this browser was
|
||||
* last in (`last_conversation`), for their rail's way back.
|
||||
*/
|
||||
const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
@@ -84,6 +89,12 @@ const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
|
||||
user_types,
|
||||
install_name: await grabInstallName().catch(() => ""),
|
||||
install_icon: await grabInstallIcon().catch(() => null),
|
||||
last_conversation:
|
||||
user?.id && isPagesRailPath({ pathname: url.pathname })
|
||||
? await grabLastConversation({ user_id: user.id, req }).catch(
|
||||
() => null,
|
||||
)
|
||||
: null,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -6,6 +6,10 @@ import { useEffect, useState, type RefObject } from "react";
|
||||
export type MessageSelection = {
|
||||
text: string;
|
||||
rect: DOMRect;
|
||||
/**
|
||||
* A copy of the selected range, for the quote's text (`quotableText`).
|
||||
*/
|
||||
range: Range;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -45,7 +49,7 @@ export default function useMessageSelection({ ref }: Params) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSelection({ text, rect: range.getBoundingClientRect() });
|
||||
setSelection({ text, rect: range.getBoundingClientRect(), range: range.cloneRange() });
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,135 +1,25 @@
|
||||
import type { ComponentProps } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import { ComputerViewModes, type ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import {
|
||||
BotRefHrefPrefix,
|
||||
ComputerRefHrefPrefix,
|
||||
FileRefHrefPrefix,
|
||||
HookProposalRefHrefPrefix,
|
||||
ProposalRefHrefPrefix,
|
||||
SecretRefHrefPrefix,
|
||||
SecretRequestRefHrefPrefix,
|
||||
TakeOverRefHrefPrefix,
|
||||
WorkspaceRefHrefPrefix,
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { parseFolderRefHref } from "@/src/utils/folder-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
import { graphicRefId } from "@/src/utils/graphic-ref";
|
||||
import { chatroomRefId } from "@/src/utils/chatroom-ref";
|
||||
import { taskRefId } from "@/src/utils/task-ref";
|
||||
import BotQuestionRefChip from "./bot-question-ref-chip";
|
||||
import BotRefChip from "./bot-ref-chip";
|
||||
import ChatroomRefChip from "./chatroom-ref-chip";
|
||||
import ComputerRefChip from "./computer-ref-chip";
|
||||
import FileRefChip from "./file-ref-chip";
|
||||
import FolderRefChip from "./folder-ref-chip";
|
||||
import GraphicRefCard from "./graphic-ref-card";
|
||||
import HookProposalRefChip from "./hook-proposal-ref-chip";
|
||||
import ProposalRefChip from "./proposal-ref-chip";
|
||||
import SecretRefChip from "./secret-ref-chip";
|
||||
import SecretRequestRefChip from "./secret-request-ref-chip";
|
||||
import TakeOverChip from "./take-over-chip";
|
||||
import TaskRefChip from "./task-ref-chip";
|
||||
import WorkspaceRefChip from "./workspace-ref-chip";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { QuoteInlineAttribute } from "../(utils)/quotable-text";
|
||||
import refChipForHref from "../(utils)/ref-chip-for-href";
|
||||
|
||||
/**
|
||||
* A link in a bot message. A computer the bot named (`linkComputerRefs`)
|
||||
* becomes its switch button, a take-over request a button that opens the
|
||||
* computer, a bot it named a link to that bot's conversation, a workspace
|
||||
* a link to that workspace, a file it saved a chip that previews it, a
|
||||
* folder it named a chip that opens it in the files browser, an MCP server,
|
||||
* tool, skill or hook it proposed a chip that opens the confirm card, a
|
||||
* secret it showed a masked chip, a secret it asked for a chip that opens
|
||||
* the card it's typed into, questions it asked a chip that opens the card
|
||||
* they're answered in, a graphic it made the graphic itself, a
|
||||
* chatroom a chip that opens it, a task on the tracker a chip that opens
|
||||
* the task;
|
||||
* anything else opens in a new tab.
|
||||
* A link in a bot message. A ref the bot wrote becomes its chip
|
||||
* (`refChipForHref`), marked so a quote reads it as one inline label
|
||||
* (`quotableText`); anything else opens in a new tab.
|
||||
*/
|
||||
export default function MarkdownLink({ href, children }: ComponentProps<"a">) {
|
||||
if (href?.startsWith(ComputerRefHrefPrefix)) {
|
||||
const computer_id = Number(href.slice(ComputerRefHrefPrefix.length));
|
||||
const chip = refChipForHref({ href });
|
||||
|
||||
if (computer_id) return <ComputerRefChip computer_id={computer_id} />;
|
||||
if (chip) {
|
||||
return (
|
||||
<Span {...{ [QuoteInlineAttribute]: "" }}>
|
||||
{chip}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
if (href?.startsWith(TakeOverRefHrefPrefix)) {
|
||||
const [id, mode] = href.slice(TakeOverRefHrefPrefix.length).split("-");
|
||||
const computer_id = Number(id);
|
||||
const known = ComputerViewModes.some((m) => m.value == mode);
|
||||
|
||||
if (computer_id) {
|
||||
return (
|
||||
<TakeOverChip
|
||||
computer_id={computer_id}
|
||||
mode={(known ? mode : ComputerViewModes[0].value) as ComputerViewMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (href?.startsWith(BotRefHrefPrefix)) {
|
||||
const bot_id = Number(href.slice(BotRefHrefPrefix.length));
|
||||
|
||||
if (bot_id) return <BotRefChip bot_id={bot_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(WorkspaceRefHrefPrefix)) {
|
||||
const workspace_id = Number(href.slice(WorkspaceRefHrefPrefix.length));
|
||||
|
||||
if (workspace_id) return <WorkspaceRefChip workspace_id={workspace_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(FileRefHrefPrefix)) {
|
||||
const file_id = Number(href.slice(FileRefHrefPrefix.length));
|
||||
|
||||
if (file_id) return <FileRefChip file_id={file_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(ProposalRefHrefPrefix)) {
|
||||
const proposal_id = Number(href.slice(ProposalRefHrefPrefix.length));
|
||||
|
||||
if (proposal_id) return <ProposalRefChip proposal_id={proposal_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(HookProposalRefHrefPrefix)) {
|
||||
const proposal_id = Number(href.slice(HookProposalRefHrefPrefix.length));
|
||||
|
||||
if (proposal_id) return <HookProposalRefChip proposal_id={proposal_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(SecretRefHrefPrefix)) {
|
||||
const env_id = Number(href.slice(SecretRefHrefPrefix.length));
|
||||
|
||||
if (env_id) return <SecretRefChip env_id={env_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(SecretRequestRefHrefPrefix)) {
|
||||
const request_id = Number(href.slice(SecretRequestRefHrefPrefix.length));
|
||||
|
||||
if (request_id) return <SecretRequestRefChip request_id={request_id} />;
|
||||
}
|
||||
|
||||
const question_id = botQuestionRefId({ href });
|
||||
|
||||
if (question_id) return <BotQuestionRefChip question_id={question_id} />;
|
||||
|
||||
const chatroom_id = chatroomRefId({ href });
|
||||
|
||||
if (chatroom_id) return <ChatroomRefChip chatroom_id={chatroom_id} />;
|
||||
|
||||
const task_id = taskRefId({ href });
|
||||
|
||||
if (task_id) return <TaskRefChip task_id={task_id} />;
|
||||
|
||||
const graphic_id = graphicRefId({ href });
|
||||
|
||||
if (graphic_id) return <GraphicRefCard graphic_id={graphic_id} />;
|
||||
|
||||
const folder_ref = parseFolderRefHref({ href });
|
||||
|
||||
if (folder_ref) return <FolderRefChip spec={folder_ref.spec} path={folder_ref.path} />;
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
|
||||
@@ -49,7 +49,7 @@ export default function MessageDetailsCallRow({ call, index, first_at }: Props)
|
||||
</Span>
|
||||
<Span
|
||||
className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums"
|
||||
title={`${call.prompt_tokens.toLocaleString()} in, ${call.completion_tokens.toLocaleString()} out · ${costLabel({ cost: call.cost })}`}
|
||||
title={`${call.prompt_tokens.toLocaleString()} in${call.cached_tokens ? ` (${call.cached_tokens.toLocaleString()} cached)` : ""}, ${call.completion_tokens.toLocaleString()} out · ${costLabel({ cost: call.cost })}`}
|
||||
>
|
||||
{`${formatTokens({ tokens: call.prompt_tokens })} / ${formatTokens({ tokens: call.completion_tokens })}`}
|
||||
</Span>
|
||||
|
||||
@@ -15,6 +15,7 @@ import MessageGroupBlock from "./message-group-block";
|
||||
import OlderMessagesLoader from "./older-messages-loader";
|
||||
import QuoteSelectionButton from "./quote-selection-button";
|
||||
import ScrollToBottomButton from "./scroll-to-bottom-button";
|
||||
import quotableText from "../(utils)/quotable-text";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -165,7 +166,7 @@ export default function MessageThread({
|
||||
<QuoteSelectionButton
|
||||
selection={selection}
|
||||
onQuote={() => {
|
||||
onQuote({ text: selection.text });
|
||||
onQuote({ text: quotableText({ range: selection.range }) });
|
||||
clear();
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -9,17 +9,21 @@ type Props = {
|
||||
/**
|
||||
* What one answer cost, in the row under it beside its timestamp: the
|
||||
* tokens every model call behind it spent (a chat turn, reading an image,
|
||||
* making one), and the price when the provider reported it. The hover
|
||||
* title breaks it down.
|
||||
* making one), the price when the provider reported it, and the fallback
|
||||
* model when one answered in place of the pick. The hover title breaks it
|
||||
* down.
|
||||
*/
|
||||
export default function MessageUsageChip({ usage }: Props) {
|
||||
if (!usage || usage.total_tokens <= 0) return null;
|
||||
|
||||
const { prompt_tokens, completion_tokens, total_tokens, cost, calls } = usage;
|
||||
const { prompt_tokens, completion_tokens, total_tokens, cost, calls, fallback_model, fallback_calls } = usage;
|
||||
const title = [
|
||||
`${formatTokens({ tokens: prompt_tokens })} in, ${formatTokens({ tokens: completion_tokens })} out`,
|
||||
`${calls} model ${calls == 1 ? "call" : "calls"}`,
|
||||
typeof cost == "number" && cost > 0 ? `$${cost.toFixed(4)}` : "",
|
||||
fallback_model
|
||||
? `${fallback_calls ?? 1} answered by the fallback ${fallback_model}: the model ahead of it failed or was resting`
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
@@ -30,6 +34,7 @@ export default function MessageUsageChip({ usage }: Props) {
|
||||
className="text-[11px] leading-4 text-ink-secondary tabular-nums whitespace-nowrap cursor-help"
|
||||
>
|
||||
{formatTokens({ tokens: total_tokens })} tokens
|
||||
{fallback_model ? ` · fallback: ${fallback_model.slice(fallback_model.indexOf("/") + 1)}` : ""}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Marks an element a quote reads as one inline label: a ref chip
|
||||
* (`MarkdownLink`). Chips are inline-flex buttons and links with block
|
||||
* wrappers inside, so the selection's own text put a line break before and
|
||||
* after each one, and a quoted sentence came out one paragraph per chip.
|
||||
*/
|
||||
export const QuoteInlineAttribute = "data-quote-inline";
|
||||
|
||||
type Params = {
|
||||
range: Range;
|
||||
};
|
||||
|
||||
/**
|
||||
* The text of a selection in a message as it reads on screen, for a
|
||||
* quote: paragraphs, list items and code keep their line breaks, and each
|
||||
* chip is its label, inline. Laid out once in a hidden holder (line breaks
|
||||
* come from layout), only when the quote is made, never per selection
|
||||
* change. Falls back to the selection's own text.
|
||||
*/
|
||||
export default function quotableText({ range }: Params) {
|
||||
const fallback = range.toString().trim();
|
||||
|
||||
try {
|
||||
const fragment = range.cloneContents();
|
||||
|
||||
for (const chip of Array.from(fragment.querySelectorAll(`[${QuoteInlineAttribute}]`))) {
|
||||
chip.replaceWith(document.createTextNode((chip.textContent || "").replace(/\s+/g, " ").trim()));
|
||||
}
|
||||
|
||||
const holder = document.createElement("div");
|
||||
|
||||
holder.setAttribute("aria-hidden", "true");
|
||||
holder.className = "sr-only";
|
||||
holder.append(fragment);
|
||||
document.body.append(holder);
|
||||
|
||||
const text = holder.innerText.replace(/\n{3,}/g, "\n\n").trim();
|
||||
|
||||
holder.remove();
|
||||
|
||||
return text || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { ComputerViewModes, type ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import {
|
||||
BotRefHrefPrefix,
|
||||
ComputerRefHrefPrefix,
|
||||
FileRefHrefPrefix,
|
||||
HookProposalRefHrefPrefix,
|
||||
ProposalRefHrefPrefix,
|
||||
SecretRefHrefPrefix,
|
||||
SecretRequestRefHrefPrefix,
|
||||
TakeOverRefHrefPrefix,
|
||||
WorkspaceRefHrefPrefix,
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { parseFolderRefHref } from "@/src/utils/folder-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
import { graphicRefId } from "@/src/utils/graphic-ref";
|
||||
import { chatroomRefId } from "@/src/utils/chatroom-ref";
|
||||
import { taskRefId } from "@/src/utils/task-ref";
|
||||
import BotQuestionRefChip from "../(partials)/bot-question-ref-chip";
|
||||
import BotRefChip from "../(partials)/bot-ref-chip";
|
||||
import ChatroomRefChip from "../(partials)/chatroom-ref-chip";
|
||||
import ComputerRefChip from "../(partials)/computer-ref-chip";
|
||||
import FileRefChip from "../(partials)/file-ref-chip";
|
||||
import FolderRefChip from "../(partials)/folder-ref-chip";
|
||||
import GraphicRefCard from "../(partials)/graphic-ref-card";
|
||||
import HookProposalRefChip from "../(partials)/hook-proposal-ref-chip";
|
||||
import ProposalRefChip from "../(partials)/proposal-ref-chip";
|
||||
import SecretRefChip from "../(partials)/secret-ref-chip";
|
||||
import SecretRequestRefChip from "../(partials)/secret-request-ref-chip";
|
||||
import TakeOverChip from "../(partials)/take-over-chip";
|
||||
import TaskRefChip from "../(partials)/task-ref-chip";
|
||||
import WorkspaceRefChip from "../(partials)/workspace-ref-chip";
|
||||
|
||||
/**
|
||||
* The chip a ref link in a bot message stands for (`linkComputerRefs`): a
|
||||
* computer its switch button, a take-over request a button that opens the
|
||||
* computer, a bot or workspace a link to it, a file a chip that previews
|
||||
* it, a folder a chip that opens it in the files browser, a proposal a chip
|
||||
* that opens the confirm card, a secret a masked chip, a secret request or
|
||||
* questions a chip that opens their card, a graphic the graphic itself, a
|
||||
* chatroom or task a chip that opens it. Null for any other link.
|
||||
*/
|
||||
export default function refChipForHref({ href }: { href?: string }): ReactNode | null {
|
||||
if (href?.startsWith(ComputerRefHrefPrefix)) {
|
||||
const computer_id = Number(href.slice(ComputerRefHrefPrefix.length));
|
||||
|
||||
if (computer_id) return <ComputerRefChip computer_id={computer_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(TakeOverRefHrefPrefix)) {
|
||||
const [id, mode] = href.slice(TakeOverRefHrefPrefix.length).split("-");
|
||||
const computer_id = Number(id);
|
||||
const known = ComputerViewModes.some((m) => m.value == mode);
|
||||
|
||||
if (computer_id) {
|
||||
return (
|
||||
<TakeOverChip
|
||||
computer_id={computer_id}
|
||||
mode={(known ? mode : ComputerViewModes[0].value) as ComputerViewMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (href?.startsWith(BotRefHrefPrefix)) {
|
||||
const bot_id = Number(href.slice(BotRefHrefPrefix.length));
|
||||
|
||||
if (bot_id) return <BotRefChip bot_id={bot_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(WorkspaceRefHrefPrefix)) {
|
||||
const workspace_id = Number(href.slice(WorkspaceRefHrefPrefix.length));
|
||||
|
||||
if (workspace_id) return <WorkspaceRefChip workspace_id={workspace_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(FileRefHrefPrefix)) {
|
||||
const file_id = Number(href.slice(FileRefHrefPrefix.length));
|
||||
|
||||
if (file_id) return <FileRefChip file_id={file_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(ProposalRefHrefPrefix)) {
|
||||
const proposal_id = Number(href.slice(ProposalRefHrefPrefix.length));
|
||||
|
||||
if (proposal_id) return <ProposalRefChip proposal_id={proposal_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(HookProposalRefHrefPrefix)) {
|
||||
const proposal_id = Number(href.slice(HookProposalRefHrefPrefix.length));
|
||||
|
||||
if (proposal_id) return <HookProposalRefChip proposal_id={proposal_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(SecretRefHrefPrefix)) {
|
||||
const env_id = Number(href.slice(SecretRefHrefPrefix.length));
|
||||
|
||||
if (env_id) return <SecretRefChip env_id={env_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(SecretRequestRefHrefPrefix)) {
|
||||
const request_id = Number(href.slice(SecretRequestRefHrefPrefix.length));
|
||||
|
||||
if (request_id) return <SecretRequestRefChip request_id={request_id} />;
|
||||
}
|
||||
|
||||
const question_id = botQuestionRefId({ href });
|
||||
|
||||
if (question_id) return <BotQuestionRefChip question_id={question_id} />;
|
||||
|
||||
const chatroom_id = chatroomRefId({ href });
|
||||
|
||||
if (chatroom_id) return <ChatroomRefChip chatroom_id={chatroom_id} />;
|
||||
|
||||
const task_id = taskRefId({ href });
|
||||
|
||||
if (task_id) return <TaskRefChip task_id={task_id} />;
|
||||
|
||||
const graphic_id = graphicRefId({ href });
|
||||
|
||||
if (graphic_id) return <GraphicRefCard graphic_id={graphic_id} />;
|
||||
|
||||
const folder_ref = parseFolderRefHref({ href });
|
||||
|
||||
if (folder_ref) return <FolderRefChip spec={folder_ref.spec} path={folder_ref.path} />;
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
value: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
suffix: string;
|
||||
info: string;
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One number of the run limits form. It only reads `value` when it
|
||||
* mounts: the form remounts it (its `key`) after a save or a discard.
|
||||
*/
|
||||
export default function RunLimitInput({ label, value, min = 0, max, suffix, info, onChange }: Props) {
|
||||
return (
|
||||
<Input
|
||||
label={label}
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={1}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
suffix={suffix}
|
||||
info={info}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -2,24 +2,45 @@ import { useState } from "react";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { RunLimitsOverview } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import SettingsSaveBar from "../../(partials)/settings-save-bar";
|
||||
import RunLimitInput from "./run-limit-input";
|
||||
|
||||
type Props = {
|
||||
limits?: RunLimitsOverview | null;
|
||||
};
|
||||
|
||||
type Values = {
|
||||
task_steps: string;
|
||||
reply_steps: string;
|
||||
unattended_steps: string;
|
||||
run_tokens: string;
|
||||
context_tokens: string;
|
||||
model_rest_seconds: string;
|
||||
};
|
||||
|
||||
const valuesOf = (limits?: RunLimitsOverview | null): Values => ({
|
||||
task_steps: String(limits?.task_steps ?? ""),
|
||||
reply_steps: String(limits?.reply_steps ?? ""),
|
||||
unattended_steps: String(limits?.unattended_steps ?? ""),
|
||||
run_tokens: String(limits?.run_tokens ?? ""),
|
||||
context_tokens: String(limits?.context_tokens ?? ""),
|
||||
model_rest_seconds: String(limits?.model_rest_seconds ?? ""),
|
||||
});
|
||||
|
||||
const count = (value?: number) => (value ?? 0).toLocaleString("en-US");
|
||||
|
||||
/**
|
||||
* How many model turns a task run and a chat reply may take, saved on its
|
||||
* own without a reload. Zero puts the code's default back for that one.
|
||||
* How long a bot may work on one run (model turns per task, reply and
|
||||
* routine or hook call, the prompt tokens one run may spend) and how much
|
||||
* of its work it resends per turn, and how long a failed model rests, saved on its own without a reload. Zero
|
||||
* puts the code's default back for that one.
|
||||
*/
|
||||
export default function RunLimitsForm({ limits }: Props) {
|
||||
const [overview, setOverview] = useState(limits || undefined);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [task_steps, setTaskSteps] = useState(String(limits?.task_steps ?? ""));
|
||||
const [reply_steps, setReplySteps] = useState(String(limits?.reply_steps ?? ""));
|
||||
const [values, setValues] = useState<Values>(valuesOf(limits));
|
||||
/**
|
||||
* The inputs only read `defaultValue` when they mount, so discarding or
|
||||
* saving remounts them with the saved numbers.
|
||||
@@ -32,7 +53,16 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
success?: boolean;
|
||||
}>();
|
||||
|
||||
const change = (key: keyof Values) => (value: string) => {
|
||||
setValues((current) => ({ ...current, [key]: value }));
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (loading) return;
|
||||
if (!window.confirm("Save these run limits? They apply to every bot's next run.")) return;
|
||||
|
||||
setLoading(true);
|
||||
setStatus(undefined);
|
||||
|
||||
@@ -41,8 +71,12 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
{
|
||||
method: "POST",
|
||||
body: {
|
||||
task_steps: Number(task_steps) || 0,
|
||||
reply_steps: Number(reply_steps) || 0,
|
||||
task_steps: Number(values.task_steps) || 0,
|
||||
reply_steps: Number(values.reply_steps) || 0,
|
||||
unattended_steps: Number(values.unattended_steps) || 0,
|
||||
run_tokens: Number(values.run_tokens) || 0,
|
||||
context_tokens: Number(values.context_tokens) || 0,
|
||||
model_rest_seconds: Number(values.model_rest_seconds) || 0,
|
||||
},
|
||||
},
|
||||
).catch(() => null);
|
||||
@@ -58,19 +92,17 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
}
|
||||
|
||||
setOverview(res.singleRes);
|
||||
setTaskSteps(String(res.singleRes.task_steps));
|
||||
setReplySteps(String(res.singleRes.reply_steps));
|
||||
setValues(valuesOf(res.singleRes));
|
||||
setFormKey((key) => key + 1);
|
||||
setDirty(false);
|
||||
setStatus({
|
||||
success: true,
|
||||
msg: `Saved: ${res.singleRes.task_steps} steps per task, ${res.singleRes.reply_steps} per reply.`,
|
||||
msg: `Saved: ${res.singleRes.task_steps} steps per task, ${res.singleRes.reply_steps} per reply, ${res.singleRes.unattended_steps} per routine or hook call.`,
|
||||
});
|
||||
};
|
||||
|
||||
const discard = () => {
|
||||
setTaskSteps(String(overview?.task_steps ?? ""));
|
||||
setReplySteps(String(overview?.reply_steps ?? ""));
|
||||
setValues(valuesOf(overview));
|
||||
setFormKey((key) => key + 1);
|
||||
setDirty(false);
|
||||
setStatus(undefined);
|
||||
@@ -84,43 +116,55 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
}}
|
||||
className="w-full gap-3! items-stretch"
|
||||
>
|
||||
<Stack className="w-full gap-3! items-stretch">
|
||||
<Input
|
||||
key={`task-${form_key}`}
|
||||
<Stack key={form_key} className="w-full gap-3! items-stretch">
|
||||
<RunLimitInput
|
||||
label="Tool steps per task"
|
||||
type="number"
|
||||
min={0}
|
||||
value={values.task_steps}
|
||||
max={overview?.max}
|
||||
step={1}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={task_steps}
|
||||
onChange={(event) => {
|
||||
setTaskSteps(event.target.value);
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
suffix={`steps`}
|
||||
suffix="steps"
|
||||
onChange={change("task_steps")}
|
||||
info={`How many turns the model may take before it must stop and report, when it works on a task. 0 uses the default (${overview?.task_default ?? ""}).`}
|
||||
/>
|
||||
<Input
|
||||
key={`reply-${form_key}`}
|
||||
<RunLimitInput
|
||||
label="Tool steps per chat reply"
|
||||
type="number"
|
||||
min={0}
|
||||
value={values.reply_steps}
|
||||
max={overview?.max}
|
||||
step={1}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={reply_steps}
|
||||
onChange={(event) => {
|
||||
setReplySteps(event.target.value);
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
suffix={`steps`}
|
||||
suffix="steps"
|
||||
onChange={change("reply_steps")}
|
||||
info={`How many turns a chat reply may take before it answers. Long work belongs in a task. 0 uses the default (${overview?.reply_default ?? ""}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Tool steps per routine or hook call"
|
||||
value={values.unattended_steps}
|
||||
max={overview?.max}
|
||||
suffix="steps"
|
||||
onChange={change("unattended_steps")}
|
||||
info={`Routine runs and hook calls work with nobody watching, so they stop sooner. Never more than the task limit. 0 uses the default (${overview?.unattended_default ?? ""}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Tokens per run"
|
||||
value={values.run_tokens}
|
||||
max={overview?.run_tokens_max}
|
||||
suffix="tokens"
|
||||
onChange={change("run_tokens")}
|
||||
info={`Every turn sends the prompt again, so a run's prompt tokens add up fast. Once a task or reply has sent this many, its next turn is its last and it reports. Between ${count(overview?.run_tokens_min)} and ${count(overview?.run_tokens_max)}; 0 uses the default (${count(overview?.run_tokens_default)}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Working context"
|
||||
value={values.context_tokens}
|
||||
max={overview?.context_tokens_max}
|
||||
suffix="tokens"
|
||||
onChange={change("context_tokens")}
|
||||
info={`How much a run sends per turn (its prompt, its tools and what it has done so far) before the oldest tool output is cut, whatever the model's window. Smaller costs less per turn; larger lets a bot keep more of what it read. Between ${count(overview?.context_tokens_min)} and ${count(overview?.context_tokens_max)}; 0 uses the default (${count(overview?.context_tokens_default)}).`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
label="Model rest after a failure"
|
||||
value={values.model_rest_seconds}
|
||||
max={overview?.model_rest_max}
|
||||
suffix="seconds"
|
||||
onChange={change("model_rest_seconds")}
|
||||
info={`When a model errors or is rate limited, it is passed over for this long and the next model in line answers (its fallback models, then the free picks). Shorter goes back to your pick sooner. Between ${overview?.model_rest_min ?? ""} and ${count(overview?.model_rest_max)}; 0 uses the default (${overview?.model_rest_default ?? ""}).`}
|
||||
/>
|
||||
</Stack>
|
||||
<SettingsSaveBar
|
||||
dirty={dirty}
|
||||
|
||||
@@ -16,7 +16,7 @@ export default function RunLimitsSection() {
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Run limits"
|
||||
description="How many turns a bot may take with its tools before it must stop and report. A task may take far more than a chat reply, since it does the long work."
|
||||
description="How long a bot may work on one run before it must stop and report, and how much of its work it sends the model each turn. A task may take far more than a chat reply, since it does the long work."
|
||||
id="run-limits"
|
||||
>
|
||||
<RunLimitsForm limits={pageProps?.run_limits} />
|
||||
|
||||
@@ -17,7 +17,11 @@ export default function HarnessCurrentModel({ harness }: Props) {
|
||||
: "Turned off."
|
||||
: harness.current
|
||||
? `Now using ${harness.current.name} on ${harness.current.provider_name}${
|
||||
harness.current.source == "auto" ? ", picked automatically" : ""
|
||||
harness.current.source == "auto"
|
||||
? ", picked automatically"
|
||||
: harness.current.source == "fallback"
|
||||
? ", a fallback model (the pick isn't available)"
|
||||
: ""
|
||||
}.${
|
||||
harness.candidate_count > 1
|
||||
? ` ${harness.candidate_count - 1} more to fall back on.`
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
import harnessFallbackModelOptions, { NoFallbackValue } from "../(utils)/harness-fallback-model-options";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
/**
|
||||
* 0-based place in the fallback order.
|
||||
*/
|
||||
index: number;
|
||||
models: HarnessModelOption[];
|
||||
model_id?: number;
|
||||
taken: number[];
|
||||
onChange: (params: { index: number; model_id: number | null }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One fallback model slot: a searchable pick from every provider, or none.
|
||||
*/
|
||||
export default function HarnessFallbackModelSelect({ id, index, models, model_id, taken, onChange }: Props) {
|
||||
return (
|
||||
<SearchSelect
|
||||
id={`${id}-${index}`}
|
||||
title={`Fallback model ${index + 1}`}
|
||||
label={`Fallback model ${index + 1}`}
|
||||
showLabel
|
||||
placeholder="Search models"
|
||||
options={harnessFallbackModelOptions({ models, model_id, taken })}
|
||||
defaultValues={[model_id ? String(model_id) : NoFallbackValue]}
|
||||
changeHandler={(value) => {
|
||||
const picked = Array.isArray(value) ? value[0] : value;
|
||||
|
||||
onChange({ index, model_id: !picked || picked == NoFallbackValue ? null : Number(picked) });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
import HarnessFallbackModelSelect from "./harness-fallback-model-select";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
/**
|
||||
* Every model that can do the job, on any provider.
|
||||
*/
|
||||
models: HarnessModelOption[];
|
||||
/**
|
||||
* The pick, which can't also be a fallback.
|
||||
*/
|
||||
model_id: number;
|
||||
fallback_model_ids: number[];
|
||||
onChange: (fallback_model_ids: number[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The models tried, in order, when the pick fails or rests, before the
|
||||
* automatic free picks: the filled slots plus one empty one, up to
|
||||
* `AppData.HarnessTextFallbackModelsMax`. Clearing a slot closes the gap.
|
||||
*/
|
||||
export default function HarnessFallbackModels({ id, models, model_id, fallback_model_ids, onChange }: Props) {
|
||||
const ids = fallback_model_ids.filter((fallback_id) => fallback_id != model_id);
|
||||
const slots: (number | undefined)[] =
|
||||
ids.length < AppData.HarnessTextFallbackModelsMax ? [...ids, undefined] : ids;
|
||||
|
||||
const change = ({ index, model_id: picked }: { index: number; model_id: number | null }) => {
|
||||
const next: (number | null)[] = [...ids];
|
||||
|
||||
next[index] = picked;
|
||||
onChange(next.filter((value): value is number => Boolean(value)));
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`When the model above fails or is resting, these are tried in order before the free automatic picks. Pick up to ${AppData.HarnessTextFallbackModelsMax}, from any provider.`}
|
||||
</Span>
|
||||
{slots.map((slot, index) => (
|
||||
<HarnessFallbackModelSelect
|
||||
key={`${index}-${slot ?? "none"}-${ids.join(",")}`}
|
||||
id={`${id}-fallback`}
|
||||
index={index}
|
||||
models={models}
|
||||
model_id={slot}
|
||||
taken={[model_id, ...ids.filter((_, other) => other != index)]}
|
||||
onChange={change}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { HarnessParameterHarnesses } from "@/src/dict/harness-parameter-dict";
|
||||
import type { HarnessFormValue, HarnessOverview } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import HarnessCurrentModel from "./harness-current-model";
|
||||
import HarnessFallbackModels from "./harness-fallback-models";
|
||||
import HarnessModelSelect from "./harness-model-select";
|
||||
import HarnessParameterModal from "./harness-parameter-modal";
|
||||
import HarnessProviderSelect from "./harness-provider-select";
|
||||
@@ -18,7 +19,7 @@ type Props = {
|
||||
|
||||
/**
|
||||
* One harness: its provider, then its model (narrowed to that provider),
|
||||
* whether it falls back to the automatic picks (for a harness that has
|
||||
* the text harness's fallback models (any provider), whether it falls back to the automatic picks (for a harness that has
|
||||
* them), whether it's on, and its voice for speech, with a sample to hear
|
||||
* it before saving. On a bot's page the provider select can also use the
|
||||
* default, which hides the rest.
|
||||
@@ -82,6 +83,15 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
onChange={(model_id) => onChange({ ...value, model_id, voice: undefined })}
|
||||
/>
|
||||
)}
|
||||
{!value.inherit && value.model_id && harness.harness == "text" ? (
|
||||
<HarnessFallbackModels
|
||||
id={id}
|
||||
models={harness.models}
|
||||
model_id={value.model_id}
|
||||
fallback_model_ids={value.fallback_model_ids || []}
|
||||
onChange={(fallback_model_ids) => onChange({ ...value, fallback_model_ids })}
|
||||
/>
|
||||
) : null}
|
||||
{value.inherit && harness.default ? (
|
||||
<HarnessCurrentModel harness={{ ...harness, ...harness.default }} />
|
||||
) : (
|
||||
@@ -89,8 +99,8 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
)}
|
||||
{!value.inherit && value.model_id && harness.automatic ? (
|
||||
<Checkbox
|
||||
title="Fall back to the automatic picks if this model fails"
|
||||
label={`Fall back to the automatic picks${provider ? ` on ${provider.name}` : ""} if this model fails`}
|
||||
title="Fall back to the free automatic picks if this model fails"
|
||||
label={`${harness.harness == "text" ? "Then fall back" : "Fall back"} to the free automatic picks${provider ? ` on ${provider.name}` : ""} if this model fails`}
|
||||
checked={value.fallback}
|
||||
changeHandler={(fallback) => onChange({ ...value, fallback })}
|
||||
/>
|
||||
|
||||
@@ -62,4 +62,15 @@ describe("changedHarnessSettings", () => {
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
test("lists a change to the fallback models, in order", () => {
|
||||
const with_fallbacks = { ...saved, text: { ...saved.text, model_id: 9, fallback_model_ids: [3, 5] } };
|
||||
|
||||
expect(changedHarnessSettings({ form: structuredClone(with_fallbacks), saved: with_fallbacks })).toEqual([]);
|
||||
expect(
|
||||
changedHarnessSettings({
|
||||
form: { ...with_fallbacks, text: { ...with_fallbacks.text, fallback_model_ids: [5, 3] } },
|
||||
saved: with_fallbacks,
|
||||
}).map((setting) => setting.harness),
|
||||
).toEqual(["text"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,6 +32,7 @@ function isSame({ a, b }: { a: HarnessFormValue; b?: HarnessFormValue }) {
|
||||
a.enabled == b!.enabled &&
|
||||
(a.voice || "") == (b!.voice || "") &&
|
||||
Boolean(a.sees_images) == Boolean(b!.sees_images) &&
|
||||
(a.fallback_model_ids || []).join(",") == (b!.fallback_model_ids || []).join(",") &&
|
||||
paramsKey({ params: a.params }) == paramsKey({ params: b!.params })
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { TWUISelectOptionObject } from "@moduletrace/twui/form/Select";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
|
||||
export const NoFallbackValue = "none";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Every model that can do the job, on any provider.
|
||||
*/
|
||||
models: HarnessModelOption[];
|
||||
/**
|
||||
* This slot's model, if any.
|
||||
*/
|
||||
model_id?: number;
|
||||
/**
|
||||
* The pick and the other slots' models, left out here.
|
||||
*/
|
||||
taken: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* One fallback slot's options: none, then every model that can do the
|
||||
* job on any provider (named with its provider), except the ones already
|
||||
* picked elsewhere.
|
||||
*/
|
||||
export default function harnessFallbackModelOptions({ models, model_id, taken }: Params): TWUISelectOptionObject[] {
|
||||
return [
|
||||
{ value: NoFallbackValue, title: "None", default: !model_id },
|
||||
...models
|
||||
.filter((model) => model.id == model_id || !taken.includes(model.id))
|
||||
.map((model) => ({
|
||||
value: String(model.id),
|
||||
title: `${model.name} · ${model.provider_name}${model.free && !/free/i.test(model.name) ? " · free" : ""}`,
|
||||
default: model.id == model_id,
|
||||
})),
|
||||
];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { harnessParametersFromOptions } from "@/src/dict/harness-parameter-dict";
|
||||
import harnessFallbackModelIds from "@/src/utils/harness-fallback-model-ids";
|
||||
import textSeesImages from "@/src/utils/text-sees-images";
|
||||
import type {
|
||||
HarnessOverview,
|
||||
@@ -29,6 +30,7 @@ export default function toHarnessForm({
|
||||
? harness.options.voice
|
||||
: undefined,
|
||||
sees_images: textSeesImages({ options: harness.options }),
|
||||
fallback_model_ids: harnessFallbackModelIds({ options: harness.options }),
|
||||
params: harnessParametersFromOptions({
|
||||
options: harness.options,
|
||||
}),
|
||||
|
||||
@@ -39,7 +39,10 @@ export default function UsageModelRow({ row }: Props) {
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate">
|
||||
{formatTokens({ tokens: row.calls })}
|
||||
</Span>
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate">
|
||||
<Span
|
||||
className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate"
|
||||
title={row.cached_tokens ? `${row.cached_tokens.toLocaleString()} of them from the provider's cache` : undefined}
|
||||
>
|
||||
{formatTokens({ tokens: row.prompt_tokens })}
|
||||
</Span>
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary tabular-nums text-right truncate">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user