Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4209fd9647 | ||
|
|
c21bafb737 | ||
|
|
99f47ffe36 | ||
|
|
f068f7f58e | ||
|
|
b860dfe859 | ||
|
|
5ba7747e11 |
@@ -87,7 +87,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Bots, sessions, chat
|
||||
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
@@ -95,12 +95,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **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. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
|
||||
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
@@ -125,17 +126,17 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`). A plan that can't be written or read starts the run unplanned, never blocks it. **The wrap up is told what is on disk:** a task run passes `Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders (`git status --porcelain` and `git diff --stat` per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it.
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_bot` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the reply job fails instead (`review_note` -> `BotJobFatalError`), since a model that kept writing the same thing sends the claim anyway. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **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`, which shares the line shape with `appRecordLines`). Before a reply goes out, `reviewBotReply` (the loop's `review`) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_bot` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the reply job fails instead (`review_note` -> `BotJobFatalError`), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
|
||||
### Live updates
|
||||
|
||||
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, and the debug view's `server:bot-trace` (just the job and its session). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
|
||||
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, the debug view's `server:bot-trace` (just the job and its session), and a plan's card `server:bot-plan` (just its id and conversation). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
|
||||
|
||||
### Crew requests (`bot_asks`)
|
||||
|
||||
A worker reaches another bot **only through the coordinator's gate**: `ask_bot` (every worker run with a session except hook calls; never the coordinator) queues a request (`createAsk`) for the run's user and place. Who can be asked is the app's call (`askableBots`): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (`AskGateNote`); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (`runAskReview`, queued by `enqueueAskReview`, dispatched from `run-bot-job` on `params.stage == "review"`) answering bounded JSON (`AskDecisionSchema`: `approve`, `redirect` or `refuse`, the bot, and a one-sentence reason) which `applyAskDecision` carries out. A refusal ends the request (`refused`) with its reason; an approval or a redirect sends the brief to the target (`enqueueAskAnswer`) as one reply job in **a new session of the target's conversation with that user for the request's workspace** (`startBotSession` with `workspace_id`, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (`from_ask_id`, `askRequestMessage`, pushed live) and the answer as the bot's reply; the target's own chat (and any other place it is read from) shows the request's row, whose `Open` link appears only outside the request's own thread (`answer_ask.session_id != session_id`), while the session carries `AskSessionBar`, built from `previous_session_id` (recorded when the request took its session, null when the bot had no conversation there before it, an empty active session counted as the request's own, `askPreviousSessionId`: with nothing to go back to, the bar is not shown at all), back to the conversation the user was in; an outcome message carries the `[ask:ID]` pill (`askRef`, `AskRefChip`, `api/admin/bots/ask`) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (`ensureAskSession`, status `ask`, deleted when empty). Stopping the target's run ends the request too (`stopBotJobs` reads `params.ask_id`, then `stopAsk`), and the bot that asked is told why and woken for it (`stopAsk`'s `reason` into `askOutcomeMessage`); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (`finishAsk`), except when the user stopped it. **Every session query that lists or picks a conversation must exclude hook sessions** (`visibleSessionSql`); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as `failed` (`onAskJobEnded`, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (`crew/ask-<id>/`) and the refs repointed (`shareAskFiles`). Caps: `AppData.AskMaxDepth` (nested requests, `parent_ask_id`; a bot waiting up the chain can't be asked), `AskMaxOpenPerBot`, `AskBriefMaxChars`. A request's run shows on the target bot's face and in its thread (the thinking row says `SEO Expert is answering Software Engineer's request in Moduletrace LTD…` with Stop, from `grabConversationAsk`; `answer_ask` in the page props, `answering_ask` in `botBusyState`) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (`grabRunningBotJobFace` excludes hook runs only); a hook call can't ask. A bot reads its own requests with `list_asks` (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run (which sees only its brief) gets its bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (`stopAsk`, `stopAsks`). **Retention:** ended requests go after the app setting `ask_keep_days` (daily `prune-asks`) and past `ask_max_per_place` per place, oldest first (`pruneAsksSql`; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through `deleteAskRows` -> `deleteSessionRows`, which clears each session's job steps, traces, jobs, billed `token_usages` and messages first, so no child row is left behind for the next `db:schema`). Sessions from before this feature (`bot_sessions.status = 'chatroom'`) are deleted at boot by `migrateChatroomsToAsks`.
|
||||
A worker reaches another bot **only through the coordinator's gate**: `ask_bot` (every worker run with a session except hook calls; never the coordinator) queues a request (`createAsk`) for the run's user and place. Who can be asked is the app's call (`askableBots`): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (`AskGateNote`); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (`runAskReview`, queued by `enqueueAskReview`, dispatched from `run-bot-job` on `params.stage == "review"`) answering bounded JSON (`AskDecisionSchema`: `approve`, `redirect` or `refuse`, the bot, and a one-sentence reason) which `applyAskDecision` carries out. A refusal ends the request (`refused`) with its reason; an approval or a redirect sends the brief to the target (`enqueueAskAnswer`) as one reply job in **a new session of the target's conversation with that user for the request's workspace** (`startBotSession` with `workspace_id`, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (`from_ask_id`, `askRequestMessage`, pushed live) and the answer as the bot's reply; the target's own chat (and any other place it is read from) shows the request's row, whose `Open` link appears only outside the request's own thread (`answer_ask.session_id != session_id`), while the session carries `AskSessionBar`, built from `previous_session_id` (recorded when the request took its session, null when the bot had no conversation there before it, an empty active session counted as the request's own, `askPreviousSessionId`: with nothing to go back to, the bar is not shown at all), back to the conversation the user was in; an outcome message carries the `[ask:ID]` pill (`askRef`, `AskRefChip`, `api/admin/bots/ask`) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (`ensureAskSession`, status `ask`, deleted when empty). Stopping the target's run ends the request too (`stopBotJobs` reads `params.ask_id`, then `stopAsk`), and the bot that asked is told why and woken for it (`stopAsk`'s `reason` into `askOutcomeMessage`); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (`finishAsk`), except when the user stopped it. **Every session query that lists or picks a conversation must exclude hook sessions** (`visibleSessionSql`); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as `failed` (`onAskJobEnded`, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (`crew/ask-<id>/`) and the refs repointed (`shareAskFiles`). Caps: `AppData.AskMaxDepth` (nested requests, `parent_ask_id`; a bot waiting up the chain can't be asked), `AskMaxOpenPerBot`, `AskBriefMaxChars`. A request's run shows on the target bot's face and in its thread (the thinking row says `SEO Expert is answering Software Engineer's request in Moduletrace LTD…` with Stop, from `grabConversationAsk`; `answer_ask` in the page props, `answering_ask` in `botBusyState`) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (`grabRunningBotJobFace` excludes hook runs and crew-request runs both; `answeringAskFace` keeps an answer run's face while it works, since a sibling job's completion would otherwise put the bot to sleep mid-answer); a hook call can't ask. A bot reads its own requests with `list_asks` (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run (which sees only its brief) gets its bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (`stopAsk`, `stopAsks`). **Retention:** ended requests go after the app setting `ask_keep_days` (daily `prune-asks`) and past `ask_max_per_place` per place, oldest first (`pruneAsksSql`; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through `deleteAskRows` -> `deleteSessionRows`, which clears each session's job steps, traces, jobs, billed `token_usages` and messages first, so no child row is left behind for the next `db:schema`). Sessions from before this feature (`bot_sessions.status = 'chatroom'`) are deleted at boot by `migrateChatroomsToAsks`.
|
||||
|
||||
### Workspaces
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
import type { BUN_SQLITE_DatabaseSchemaType } from "@moduletrace/bun-sqlite/types";
|
||||
import { EnvParadigms, SecretRequestStatuses } from "@/src/dict/env-dict";
|
||||
import { BotQuestionStatuses } from "@/src/dict/bot-question-dict";
|
||||
import { BotPlanStates } from "@/src/dict/bot-plan-dict";
|
||||
import { McpServerStatuses, McpTransports } from "@/src/dict/mcp-dict";
|
||||
import {
|
||||
CustomToolKinds,
|
||||
@@ -615,12 +616,21 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
fieldDescription: `Set on the message that opens a session the bot moved the conversation into (\`continue_in_new_session\`): the session it carries on from, whose summary is the message's text. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "client_id",
|
||||
fieldDescription: `The composer's own id for a message it sent, so a send whose answer never arrived is recognised as the one already stored rather than posted twice`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_messages_bot_id_created_at",
|
||||
indexTableFields: ["bot_id", "created_at"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_messages_client_id",
|
||||
indexTableFields: ["client_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_messages_session_id_created_at",
|
||||
indexTableFields: ["session_id", "created_at"],
|
||||
@@ -1959,6 +1969,64 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_plans",
|
||||
tableDescription: `A plan a bot broke complex work into in a conversation (\`create_plan\`): an ordered list of steps it works one at a time, reporting each as it goes. Written as \`planned\` and approved on its card by the user, who may change the steps first; only one is open in a conversation at a time. Visible to the user it was made for`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "title",
|
||||
fieldDescription: `A short name for the work, in the bot's words`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "goal",
|
||||
fieldDescription: `What the plan is for, and what \"done\" means`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "steps",
|
||||
fieldDescription: `JSON array of { text, state (pending | done | skipped), note } in the order they're worked; the note is what a finished step produced`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "status",
|
||||
dataType: "TEXT",
|
||||
options: BotPlanStates.map((state) => state.value),
|
||||
defaultValue: "planned",
|
||||
},
|
||||
{
|
||||
fieldName: "decided_at",
|
||||
fieldDescription: `When the user approved (or stopped) it; null while it waits on them`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `The user it was made for, who alone sees it and approves it. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot that wrote it and works it. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The conversation it belongs to, which it never leaves. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_plans_session_id",
|
||||
indexTableFields: ["session_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_graphics",
|
||||
tableDescription: `A visual a bot made for a user (a chart, diagram, timeline or report) as one self-contained HTML document. Served by the app at \`/graphics/<id>\` in a sandbox with no network and an origin of its own, so it never runs with the viewer's session. Per user like the conversation it was made in; an edit replaces the HTML and bumps \`version\``,
|
||||
|
||||
+54
-1
@@ -26,6 +26,7 @@ export const BunSQLiteTables = [
|
||||
"install_requests",
|
||||
"bot_questions",
|
||||
"bot_suggestions",
|
||||
"bot_plans",
|
||||
"bot_graphics",
|
||||
"workspaces",
|
||||
"workspace_bots",
|
||||
@@ -435,6 +436,10 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
|
||||
* Set on the message that opens a session the bot moved the conversation into (`continue_in_new_session`): the session it carries on from, whose summary is the message's text. Not a foreign key
|
||||
*/
|
||||
carried_from_session_id?: number | "";
|
||||
/**
|
||||
* The composer's own id for a message it sent, so a send whose answer never arrived is recognised as the one already stored rather than posted twice
|
||||
*/
|
||||
client_id?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS = {
|
||||
@@ -1271,6 +1276,54 @@ export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_PLANS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
/**
|
||||
* A short name for the work, in the bot's words
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* What the plan is for, and what "done" means
|
||||
*/
|
||||
goal?: string;
|
||||
/**
|
||||
* JSON array of { text, state (pending | done | skipped), note } in the order they're worked; the note is what a finished step produced
|
||||
*/
|
||||
steps?: string;
|
||||
status?: "planned" | "active" | "paused" | "done" | "cancelled" | "";
|
||||
/**
|
||||
* When the user approved (or stopped) it; null while it waits on them
|
||||
*/
|
||||
decided_at?: number | "";
|
||||
/**
|
||||
* The user it was made for, who alone sees it and approves it. Not a foreign key
|
||||
*/
|
||||
user_id?: number | "";
|
||||
/**
|
||||
* The bot that wrote it and works it. Not a foreign key
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The conversation it belongs to, which it never leaves. Not a foreign key
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The session's workspace; null for the bot's own chat. Not a foreign key
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_GRAPHICS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -2933,4 +2986,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_BOT_ASKS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_BOT_JOB_TRACES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_BOT_ASKS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_BOT_JOB_TRACES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_PLANS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.21.4",
|
||||
"version": "0.23.0",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -31,6 +31,8 @@ import grabJobUserId from "@/src/functions/backend/db/bots-queue/grab-job-user-i
|
||||
import runBotJob from "./run-bot-job";
|
||||
import parseJobJson from "./parse-job-json";
|
||||
import nameBotSession from "./name-bot-session";
|
||||
import wakeBotsQueue from "./wake-bots-queue";
|
||||
import continueBotPlan from "@/src/functions/backend/db/bot-plans/continue-bot-plan";
|
||||
import pushBotSession from "./push-bot-session";
|
||||
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
|
||||
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
|
||||
@@ -85,6 +87,14 @@ export default async function processBotJob({
|
||||
const schedule_id = Number(params.schedule_id) || null;
|
||||
const hook_id = Number(params.hook_id) || null;
|
||||
|
||||
const controller = new AbortController();
|
||||
/**
|
||||
* Registered before the first read below: those queries can wait on a
|
||||
* busy database, and a Stop that arrived while they ran found nothing
|
||||
* to abort, so a stopped job went on running until its own next write.
|
||||
*/
|
||||
registerJobAbort({ job_id, abort: () => controller.abort() });
|
||||
|
||||
/**
|
||||
* Its face changes only for the user it works for.
|
||||
*/
|
||||
@@ -100,7 +110,10 @@ export default async function processBotJob({
|
||||
);
|
||||
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }).catch(() => null));
|
||||
|
||||
const controller = new AbortController();
|
||||
if (controller.signal.aborted) {
|
||||
unregisterJobAbort({ job_id });
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* The deadline is the one abort that is a failure, not a cancellation:
|
||||
* the job's error is then the timeout's, not the "Cancelled." an
|
||||
@@ -108,6 +121,10 @@ export default async function processBotJob({
|
||||
*/
|
||||
const timeout_message = `"${job.title || "The job"}" took too long and was stopped.`;
|
||||
let timed_out = false;
|
||||
/**
|
||||
* Set once the run reports a step (a tool call): its attempt is spent.
|
||||
*/
|
||||
let worked = false;
|
||||
|
||||
/**
|
||||
* A stopped job never touches the face again: `stopBotJobs` already set
|
||||
@@ -126,8 +143,6 @@ export default async function processBotJob({
|
||||
* is already failed in the queue, so an abort is a cancellation and its
|
||||
* result is dropped (`controller.signal.aborted` below).
|
||||
*/
|
||||
registerJobAbort({ job_id, abort: () => controller.abort() });
|
||||
|
||||
const update: BotJobContext["update"] = async (params) => {
|
||||
if (controller.signal.aborted) return false;
|
||||
|
||||
@@ -146,6 +161,14 @@ export default async function processBotJob({
|
||||
try {
|
||||
if (!(await update({ progress: described.text }))) return;
|
||||
|
||||
/**
|
||||
* The run has done real work: a later wait for the models to
|
||||
* come back must not give its attempt back, or a run that
|
||||
* wrote files and then met a resting model replays from turn 1
|
||||
* as many times as the outage lasts.
|
||||
*/
|
||||
worked = true;
|
||||
|
||||
const row = await insertBotJobUpdate({ job_id, bot_id, ...described });
|
||||
|
||||
await pushToSessionUser({
|
||||
@@ -299,6 +322,23 @@ export default async function processBotJob({
|
||||
|
||||
await pushBotNotice({ bot_id, ...completion });
|
||||
|
||||
/**
|
||||
* A run that worked a step of a plan hands it on: the next step is
|
||||
* queued here, once this reply is out, so each step is its own
|
||||
* message (`continueBotPlan` holds it when the user is needed or
|
||||
* the run started work of its own).
|
||||
*/
|
||||
if (outcome.plan_id) {
|
||||
await continueBotPlan({
|
||||
plan_id: outcome.plan_id,
|
||||
session_id: Number(completion.message?.session_id || job.session_id),
|
||||
needs_you: Boolean(outcome.needs_you),
|
||||
tool_names: (outcome.tool_log || []).map((use) => use.name),
|
||||
}).then((job_id) => {
|
||||
if (job_id) wakeBotsQueue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Once the first exchange is sent, the bot names the session and
|
||||
* previews it. After the reply is pushed, so it never waits on it;
|
||||
@@ -344,14 +384,15 @@ export default async function processBotJob({
|
||||
* wait for the first to come back without using an attempt.
|
||||
*/
|
||||
if (error instanceof HarnessError && error.resting) {
|
||||
await deferBotJob({
|
||||
const deferred = await deferBotJob({
|
||||
job_id,
|
||||
worker,
|
||||
until: error.retry_at || Date.now() + AppData.HarnessCooldownMs,
|
||||
refund: true,
|
||||
refund: !worked,
|
||||
});
|
||||
|
||||
await setFace({ face: "asleep", status_line: BotWaitingStatusLine });
|
||||
if (deferred) await setFace({ face: "asleep", status_line: BotWaitingStatusLine });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BotPlanChangedData } from "@/src/types";
|
||||
import pushToSessionUser from "./push-to-session-user";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
session_id: number | string;
|
||||
bot_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tells the open tabs of the user a plan belongs to that it changed
|
||||
* (written, a step done, approved, edited), so every card of it reloads
|
||||
* what it shows. A plan only ever shows in its own conversation.
|
||||
*/
|
||||
export default async function pushBotPlan({ plan_id, session_id, bot_id }: Params) {
|
||||
const data: BotPlanChangedData = {
|
||||
plan_id: Number(plan_id),
|
||||
session_id: Number(session_id),
|
||||
bot_id: Number(bot_id),
|
||||
};
|
||||
|
||||
await pushToSessionUser({
|
||||
session_id,
|
||||
data: { event: "server:bot-plan", data },
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabUnreportedFailedBotJobs from "@/src/functions/backend/db/bots-queue/grab-unreported-failed-bot-jobs";
|
||||
import notifyBotJobFailed from "@/src/functions/backend/db/bots-queue/notify-bot-job-failed";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
@@ -11,7 +12,19 @@ export default async function reportLostBotJobs() {
|
||||
const jobs = await grabUnreportedFailedBotJobs();
|
||||
|
||||
for (const job of jobs) {
|
||||
if (!job.bot_id) continue;
|
||||
if (!job.bot_id) {
|
||||
/**
|
||||
* A job whose bot was deleted has nobody to tell, but it is
|
||||
* stamped all the same: left unstamped, the same rows are read
|
||||
* on every poll and never pruned.
|
||||
*/
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bots_queue SET finished_at = ? WHERE id = ? AND finished_at IS NULL`,
|
||||
values: [Date.now(), Number(job.id)],
|
||||
}).catch(() => {});
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const notice = await notifyBotJobFailed({
|
||||
job,
|
||||
|
||||
@@ -22,11 +22,17 @@ import {
|
||||
workspaceAdminNote,
|
||||
WorkspaceLearningNote,
|
||||
openRunsNote,
|
||||
PlansNote,
|
||||
PlanWaitingNote,
|
||||
PlanStepNote,
|
||||
PlanActiveNote,
|
||||
PlanPausedNote,
|
||||
} 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 { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import { isUnlimitedLimit } from "@/src/utils/run-limit";
|
||||
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";
|
||||
@@ -40,6 +46,7 @@ import openBotBrowsers from "@/src/harness/tools/browsers/open-bot-browsers";
|
||||
import openBotExtensions from "@/src/harness/tools/extensions/open-bot-extensions";
|
||||
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
|
||||
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
|
||||
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
|
||||
import parseJobJson from "./parse-job-json";
|
||||
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
|
||||
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
|
||||
@@ -67,6 +74,10 @@ import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
import grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools";
|
||||
import grabSessionPlan from "@/src/functions/backend/db/bot-plans/grab-session-plan";
|
||||
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
|
||||
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
@@ -123,7 +134,32 @@ export default async function runBotReply({
|
||||
|
||||
const answered_id = await grabAnsweredMessageId({ session_id });
|
||||
|
||||
if (!hasUnansweredMessage({ history, answered_id })) {
|
||||
const job_params = parseJobJson({ text: job.params }) || {};
|
||||
/**
|
||||
* The plan this job was queued for (`enqueuePlanStep`): the run works
|
||||
* that plan's current step, whether or not the user wrote anything.
|
||||
*/
|
||||
const on_plan_step = Number(job_params.plan_id) > 0;
|
||||
|
||||
if (!on_plan_step && !hasUnansweredMessage({ history, answered_id })) {
|
||||
return { result: "", silent: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The conversation's plan: the one this job works, else the one open
|
||||
* here, which the run reads and reports on.
|
||||
*/
|
||||
const plan_row = on_plan_step
|
||||
? await grabBotPlan({ plan_id: Number(job_params.plan_id) }).catch(() => null)
|
||||
: await grabSessionPlan({ session_id });
|
||||
const plan = plan_row ? toBotPlanView({ row: plan_row }) : null;
|
||||
|
||||
/**
|
||||
* A step job queued before the user paused (or dropped) the plan has
|
||||
* nothing to do: it ends without a word, rather than reporting a step
|
||||
* nobody asked for any more.
|
||||
*/
|
||||
if (on_plan_step && (plan?.status != "active" || plan?.current_step == null)) {
|
||||
return { result: "", silent: true };
|
||||
}
|
||||
|
||||
@@ -137,7 +173,7 @@ export default async function runBotReply({
|
||||
/**
|
||||
* What the user wrote since the run last looked.
|
||||
*/
|
||||
const incoming = async (): Promise<HarnessMessage[]> => {
|
||||
const incoming = async ({ counted = true }: { counted?: boolean } = {}): Promise<HarnessMessage[]> => {
|
||||
const fresh = await grabBotMessages({
|
||||
session_id,
|
||||
after_id: seen_id,
|
||||
@@ -148,7 +184,13 @@ export default async function runBotReply({
|
||||
if (!fresh.length) return [];
|
||||
|
||||
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
|
||||
answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
|
||||
/**
|
||||
* A message read by the wrap up is not what the answer answers: the
|
||||
* answer was written for what came before it, and its own queued
|
||||
* reply is the one that reads this. Marking it answered here made
|
||||
* that reply finish silently, with nothing sent for it.
|
||||
*/
|
||||
if (counted) answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
|
||||
|
||||
return await messagesToTurns({ messages: fresh, user_id });
|
||||
};
|
||||
@@ -223,6 +265,11 @@ export default async function runBotReply({
|
||||
* always carries, without needing the user.
|
||||
*/
|
||||
const shown: string[] = [];
|
||||
/**
|
||||
* The plan it wrote in this reply: on its card and waiting for the user
|
||||
* to approve it, so the reply needs them.
|
||||
*/
|
||||
const plan_refs: string[] = [];
|
||||
/**
|
||||
* Files the bot wrote and asked to send with its reply.
|
||||
*/
|
||||
@@ -370,6 +417,12 @@ export default async function runBotReply({
|
||||
*/
|
||||
const open_runs = attended ? await grabOpenSessionRuns({ bot_id: bot.id, session_id }) : [];
|
||||
|
||||
/**
|
||||
* What the run may spend: a reply handed a tracker task says when it
|
||||
* used them all (`exhausted`).
|
||||
*/
|
||||
const reply_max_steps = await grabReplyMaxToolSteps();
|
||||
|
||||
try {
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
@@ -384,6 +437,14 @@ export default async function runBotReply({
|
||||
can_hand_over ? HandOverTaskNote : "",
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask: Boolean(attended) && !asked }),
|
||||
attended && !asked ? PlansNote : "",
|
||||
attended && !asked && plan?.status == "planned" ? PlanWaitingNote({ plan }) : "",
|
||||
attended && !asked && plan?.status == "paused" ? PlanPausedNote({ plan }) : "",
|
||||
attended && !asked && plan?.status == "active"
|
||||
? on_plan_step
|
||||
? PlanStepNote({ plan })
|
||||
: PlanActiveNote({ plan })
|
||||
: "",
|
||||
attended ? QuestionsNote : "",
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
@@ -433,7 +494,13 @@ export default async function runBotReply({
|
||||
session_id,
|
||||
workspace_id,
|
||||
computer_id: computers[0]?.id || null,
|
||||
onRequest: ({ ref }) => proposals.push(ref),
|
||||
/**
|
||||
* A card is answered in a conversation the user follows:
|
||||
* in a hidden session (a crew request, a hook call, a
|
||||
* room) nobody sees it, so the bot is told to ask in the
|
||||
* chat instead of leaving a request hanging.
|
||||
*/
|
||||
onRequest: attended ? ({ ref }) => proposals.push(ref) : undefined,
|
||||
onShow: ({ ref }) => shown.push(ref),
|
||||
}),
|
||||
/**
|
||||
@@ -460,6 +527,21 @@ export default async function runBotReply({
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(attended && !asked
|
||||
? grabBotPlanTools({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
on_step: on_plan_step,
|
||||
/**
|
||||
* A plan nobody approved yet needs the user, so
|
||||
* it goes with the refs that set `needs_you`: the
|
||||
* bot is waiting on them, not on itself.
|
||||
*/
|
||||
onPlan: ({ ref, waiting }) => (waiting ? plan_refs.push(ref) : shown.push(ref)),
|
||||
})
|
||||
: []),
|
||||
...(has_past_sessions
|
||||
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
|
||||
: []),
|
||||
@@ -477,7 +559,7 @@ export default async function runBotReply({
|
||||
...skills.tools,
|
||||
...knowledge.tools,
|
||||
],
|
||||
max_steps: await grabReplyMaxToolSteps(),
|
||||
max_steps: reply_max_steps,
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
bot_id: bot.id,
|
||||
@@ -499,8 +581,24 @@ export default async function runBotReply({
|
||||
* with why instead (`review_note`), and the job fails saying so. The
|
||||
* user gets an honest failure, not a claim the app knows is false.
|
||||
*/
|
||||
if (result.review_note)
|
||||
if (result.review_note) {
|
||||
await dropUnsentQuestions({ refs: proposals });
|
||||
|
||||
throw new BotJobFatalError(`The answer didn't hold up against the app's record, so it wasn't sent.`);
|
||||
}
|
||||
|
||||
const answer = stripAppRecords({ text: result.text }).trim();
|
||||
|
||||
/**
|
||||
* Nothing said is nothing to send: an empty message lands in the
|
||||
* thread as a bubble with no text, and the user has no idea what
|
||||
* happened. The job fails with why instead, which they do see.
|
||||
*/
|
||||
if (!answer && !shown.length && !attachments.length) {
|
||||
await dropUnsentQuestions({ refs: proposals });
|
||||
|
||||
throw new BotJobFatalError(`The run ended without an answer to send.`);
|
||||
}
|
||||
|
||||
if (job.id && answering_id) {
|
||||
await markReplyAnswered({ job_id: job.id, message_id: answering_id });
|
||||
@@ -508,13 +606,20 @@ export default async function runBotReply({
|
||||
|
||||
return {
|
||||
...withTakeOverRefs({
|
||||
text: stripAppRecords({ text: result.text }),
|
||||
refs: [...take_overs, ...proposals],
|
||||
text: answer,
|
||||
refs: [...take_overs, ...proposals, ...plan_refs],
|
||||
shown,
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
plan_id: on_plan_step ? plan?.id : undefined,
|
||||
/**
|
||||
* A reply handed a tracker task (`params.tracker_task_id`) that
|
||||
* used every step it had stopped short of finishing it: left
|
||||
* alone, the task looked like work still in hand.
|
||||
*/
|
||||
exhausted: !isUnlimitedLimit(reply_max_steps) && result.steps > reply_max_steps,
|
||||
};
|
||||
} finally {
|
||||
await extensions.close();
|
||||
@@ -522,6 +627,21 @@ export default async function runBotReply({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cards whose message never went out are deleted: their answer only comes
|
||||
* from the card, so a pending row left behind waits forever and counts as a
|
||||
* question still asked.
|
||||
*/
|
||||
async function dropUnsentQuestions({ refs }: { refs: string[] }) {
|
||||
for (const ref of refs) {
|
||||
const question_id = Number(/\[question:(\d+)\]/.exec(ref)?.[1] || 0);
|
||||
|
||||
if (!question_id) continue;
|
||||
|
||||
await deleteBotQuestion({ question_id }).catch(() => null);
|
||||
}
|
||||
}
|
||||
|
||||
function newestUserMessageId({ messages }: { messages: Pick<BotMessageWithAttachments, "id" | "author">[] }) {
|
||||
return Math.max(
|
||||
0,
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
botFilesNote,
|
||||
ComputerFilesNote,
|
||||
ScheduledRunNote,
|
||||
ScheduledPlanNote,
|
||||
HookRunNote,
|
||||
InstallRequestNote,
|
||||
TasksNote,
|
||||
@@ -45,6 +46,7 @@ import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/e
|
||||
import openBotSkills, { type OpenBotSkills } from "@/src/harness/tools/skills/open-bot-skills";
|
||||
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
|
||||
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
|
||||
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
@@ -56,6 +58,7 @@ import askToTakeOverTool from "@/src/harness/tools/computer/ask-to-take-over-too
|
||||
import importFileTool from "@/src/harness/tools/computer/import-file-tool";
|
||||
import searchComputersTool from "@/src/harness/tools/computer/search-computers-tool";
|
||||
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
|
||||
import grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools";
|
||||
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
|
||||
import reportRunFailedTool from "@/src/harness/tools/bot/report-run-failed-tool";
|
||||
import answerInstallRequestTool from "@/src/harness/tools/bot/answer-install-request-tool";
|
||||
@@ -184,9 +187,14 @@ export default async function runBotTask({
|
||||
const hooked = Boolean(params.hook_id);
|
||||
/**
|
||||
* Only a task the user follows in their conversation asks them
|
||||
* questions: routines and hook calls act on their own.
|
||||
* questions: routines and hook calls act on their own, and a crew
|
||||
* request's run works in a session nobody reads from this bot's chat.
|
||||
*/
|
||||
const can_ask = Boolean(session_id) && !scheduled && !hooked;
|
||||
const can_ask =
|
||||
Boolean(session_id) &&
|
||||
!scheduled &&
|
||||
!hooked &&
|
||||
!(await isHiddenSession({ session_id: Number(session_id) }));
|
||||
/**
|
||||
* The coordinator weighing a worker's install request
|
||||
* (`request_install`): it answers it with answer_install_request.
|
||||
@@ -348,6 +356,22 @@ export default async function runBotTask({
|
||||
job_id: job.id || null,
|
||||
onGraphic: ({ ref }) => shown.push(ref),
|
||||
}),
|
||||
/**
|
||||
* A routine's plan is approved at once and worked through in
|
||||
* the run, since nobody is there to approve it on a card
|
||||
* (`ScheduledPlanNote`). A hook call gets none: its thread is a
|
||||
* log of calls, not a conversation to read a plan in.
|
||||
*/
|
||||
...(scheduled && session_id
|
||||
? grabBotPlanTools({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
approve: true,
|
||||
onPlan: ({ ref }) => shown.push(ref),
|
||||
})
|
||||
: []),
|
||||
];
|
||||
|
||||
extensions = await openBotExtensions({
|
||||
@@ -437,6 +461,7 @@ export default async function runBotTask({
|
||||
TaskRunNote,
|
||||
steps_note,
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
scheduled ? ScheduledPlanNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
install_request_id ? InstallRequestNote : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
|
||||
@@ -74,6 +74,12 @@ export type BotJobOutcome = {
|
||||
* (`noteTrackerTask`).
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
/**
|
||||
* The plan this run worked a step of (`params.plan_id`): the app queues
|
||||
* its next step once the reply is out (`continueBotPlan`), unless the
|
||||
* run asked for the user or started work that runs on its own.
|
||||
*/
|
||||
plan_id?: number;
|
||||
};
|
||||
|
||||
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
|
||||
|
||||
@@ -1098,6 +1098,33 @@ export const AppData = {
|
||||
* Longest heading a bot may give its suggested next steps.
|
||||
*/
|
||||
BotSuggestionTitleMaxChars: 120,
|
||||
/**
|
||||
* Most steps one plan may hold (`create_plan`). Short enough that a
|
||||
* user reads the whole thing before approving it.
|
||||
*/
|
||||
BotPlanMaxSteps: 10,
|
||||
/**
|
||||
* Longest title a plan may have.
|
||||
*/
|
||||
BotPlanTitleMaxChars: 120,
|
||||
/**
|
||||
* Longest goal a plan may state (what "done" means).
|
||||
*/
|
||||
BotPlanGoalMaxChars: 300,
|
||||
/**
|
||||
* Longest one plan step may be.
|
||||
*/
|
||||
BotPlanStepMaxChars: 240,
|
||||
/**
|
||||
* Longest line a bot may keep on a finished step, saying what it
|
||||
* produced.
|
||||
*/
|
||||
BotPlanStepNoteMaxChars: 400,
|
||||
/**
|
||||
* Plans shown in a conversation's prompt as earlier ones, so a bot
|
||||
* remembers work it already broke down.
|
||||
*/
|
||||
BotPlanPastShown: 3,
|
||||
/**
|
||||
* Longest dictation the composer records before it stops on its own.
|
||||
*/
|
||||
|
||||
@@ -17,6 +17,12 @@ import {
|
||||
TaskWrapUpIncomingNote,
|
||||
TasksNote,
|
||||
wrapUpWorktreeNote,
|
||||
PlansNote,
|
||||
PlanStepNote,
|
||||
PlanWaitingNote,
|
||||
PlanActiveNote,
|
||||
PlanPausedNote,
|
||||
ScheduledPlanNote,
|
||||
} from "./harness-prompts";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
|
||||
@@ -245,3 +251,60 @@ describe("AskGateRequest", () => {
|
||||
expect(text).toContain("List your open tasks.");
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A plan is the answer to a bot that answers a long request with one wall of
|
||||
* text: the notes hold it to one step per reply and a report of two or three
|
||||
* sentences, and the card behind them shows the rest.
|
||||
*/
|
||||
const plan = {
|
||||
id: 4,
|
||||
title: "Audit the pricing pages",
|
||||
goal: "Know which pages price badly",
|
||||
status: "active" as const,
|
||||
steps: [
|
||||
{ text: "Collect the pages", state: "done" as const, note: "14 pages" },
|
||||
{ text: "Score them", state: "pending" as const, note: "" },
|
||||
{ text: "Write it up", state: "pending" as const, note: "" },
|
||||
],
|
||||
current_step: 1,
|
||||
};
|
||||
|
||||
describe("plan notes", () => {
|
||||
test("waits for the user's approval, and says a plan that is open stays open", () => {
|
||||
expect(PlanWaitingNote({ plan: { ...plan, status: "planned", current_step: 1 } })).toContain(
|
||||
"Plan #4 \"Audit the pricing pages\"",
|
||||
);
|
||||
expect(PlansNote).toContain("nothing of it starts until the user approves it");
|
||||
});
|
||||
|
||||
test("tells the run to work its step only, then report in two or three sentences", () => {
|
||||
const note = PlanStepNote({ plan });
|
||||
|
||||
expect(note).toContain("This reply works step 2 only: Score them");
|
||||
expect(note).toContain("One step per reply");
|
||||
expect(note).toContain("two or three sentences");
|
||||
expect(note).toContain("complete_plan_step");
|
||||
});
|
||||
|
||||
test("lists the steps with where each one stands and what it produced", () => {
|
||||
const note = PlanStepNote({ plan });
|
||||
|
||||
expect(note).toContain("1. [done] Collect the pages - 14 pages");
|
||||
expect(note).toContain("2. [now] Score them");
|
||||
expect(note).toContain("3. [pending] Write it up");
|
||||
});
|
||||
|
||||
test("an active plan elsewhere in the conversation leaves the plan where it is", () => {
|
||||
expect(PlanActiveNote({ plan })).toContain("leave the plan where it is");
|
||||
});
|
||||
|
||||
test("a paused plan is the user's to resume", () => {
|
||||
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain("paused by the user");
|
||||
});
|
||||
|
||||
test("a routine's plan is approved at once and worked through in the run", () => {
|
||||
expect(ScheduledPlanNote).toContain("approved at once");
|
||||
expect(ScheduledPlanNote).toContain("work its steps in this run");
|
||||
});
|
||||
});
|
||||
|
||||
+141
-1
@@ -1,4 +1,6 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
|
||||
import type { BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
|
||||
import botRef from "@/src/utils/bot-ref";
|
||||
import folderRef from "@/src/utils/folder-ref";
|
||||
import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
@@ -443,6 +445,28 @@ Nothing has run since that could change that answer, so calling it once more onl
|
||||
export const answerNotSentNote = `The message you wrote before these tool results was never sent: a run sends only its final message, and you went on to call a tool after writing that one. If the user still needs any of it, write it again in your last message. Don't send work in progress as an answer and then carry on.`;
|
||||
export const repeatedAnswerNote = `This is the message the app just sent back, word for word: nothing has changed since, so it will not go out either. Write it again from what the app's record shows. Take out what that record cannot support, and if the work still needs doing, call the tool that does it now rather than saying it is under way.`;
|
||||
|
||||
/**
|
||||
* Told when a turn tried to end on a card and the card's tool refused it
|
||||
* (wrong arguments, an answered card): nothing went up, so the answer must
|
||||
* not read as if it had. The run carries on, which is what gives the model
|
||||
* the turn it needs to fix the call.
|
||||
*/
|
||||
export const closingFailedNote = `The card that call was meant to put up was not created: the tool refused it, and its error is above. Your message was written as if it had gone up, and it has not. Fix the call and make it again, or answer without it, and write your message for what actually exists.`;
|
||||
|
||||
/**
|
||||
* Told once when a closing call worked but the turn said nothing beside it:
|
||||
* a card alone leaves the user with buttons and no answer, and a run that
|
||||
* carries on from there works on the thing it just asked about.
|
||||
*/
|
||||
export const closingNoTextNote = `The card you just put up has no message beside it, and a card on its own leaves the user nothing to read. Write the sentence that goes with it now, and stop there: what comes next waits on their answer.`;
|
||||
|
||||
/**
|
||||
* Put under an answer the review kept faulting once its unsupported parts
|
||||
* were taken out (`repairAnswerText`): the user is told part of it is gone
|
||||
* rather than losing the whole answer, and knows what to ask again.
|
||||
*/
|
||||
export const repairedAnswerNote = `_Part of this answer was left out: it described work no tool of this run did._`;
|
||||
|
||||
/**
|
||||
* Told once, when the prompt no longer fits the working context even after
|
||||
* everything trimmable was trimmed: what is left is what the user wrote,
|
||||
@@ -566,7 +590,7 @@ A task on your own list can go to another bot with hand_over_task: it moves to t
|
||||
- When they asked for the move but not whether to start it, ask first: put one ask_user card with every task they named ("hand over and start", "hand over to wait", "leave it") and hand over only once they've answered. Once a task has left your list you can't start it any more.
|
||||
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
|
||||
- Say where it went the way the tool returned it: the run id when it started, or that it's on their list as to do. Never say a task was handed over, or that someone picked work up, without it.
|
||||
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
|
||||
- Handing over is not asking: when you only need an answer from another bot, use ask_bot.`;
|
||||
|
||||
/**
|
||||
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
|
||||
@@ -794,3 +818,119 @@ Title: ${title}
|
||||
The request:
|
||||
|
||||
${request}`;
|
||||
|
||||
/**
|
||||
* A plan as the prompts read it (`BotPlanView` without the bot's own name):
|
||||
* its steps parsed and the one being worked.
|
||||
*/
|
||||
type PlanPrompt = {
|
||||
id: number;
|
||||
title: string;
|
||||
goal: string;
|
||||
status: BotPlanState;
|
||||
steps: BotPlanStepRecord[];
|
||||
current_step: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan's steps as a run reads them in its prompt: numbered, with what is
|
||||
* done, what it is on, and what is left.
|
||||
*/
|
||||
const planStepLines = ({ plan }: { plan: PlanPrompt }) =>
|
||||
plan.steps
|
||||
.map((step, index) => {
|
||||
const mark = index == plan.current_step ? "now" : step.state;
|
||||
|
||||
return `${index + 1}. [${mark}] ${step.text}${step.note ? ` - ${step.note}` : ""}`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
/**
|
||||
* Added to a chat reply: when to break work into a plan instead of a long
|
||||
* answer, and what to keep of a plan that will be used again.
|
||||
*/
|
||||
export const PlansNote = `# Plans, for work that comes in pieces
|
||||
|
||||
Some requests are several pieces of work that build on each other, and answering them in one long message is how a reply ends up confusing: the user can't see where it is going, and nothing of it is checked. For those, call create_plan before starting:
|
||||
|
||||
- the work has three or more pieces that depend on each other (find out, then decide, then change), or
|
||||
- the user's answer will cost real time or money and they should see the shape of it first, or
|
||||
- you would otherwise be listing everything you're about to do.
|
||||
|
||||
Don't plan a question you can answer, one change, or work you're handing to a run (start_task): that is already broken down.
|
||||
|
||||
A plan is a title, the goal that says what finished looks like, and 3 to 6 steps, one line each, in the order you'd do them, each naming what it produces in the user's words. The steps are what the user reads, so write them for them, not for you.
|
||||
|
||||
It goes up as a card in the conversation and nothing of it starts until the user approves it (they can change the steps first). Say in one sentence that you wrote the plan and that it's theirs to change; don't repeat the steps in your text, the card shows them, and don't work a step in that reply.
|
||||
|
||||
Then the app wakes you one step at a time, each step in its own reply, and the card ticks along as you go.
|
||||
|
||||
## Plans worth keeping
|
||||
|
||||
When a plan you worked through is one the same work comes back to (a new project, a new client, the same check every month), save it before the conversation moves on: put the steps in as a short checklist with update_memory, in your memory of this user when it's how they work, in your core memory when it's the install's way. Say in a line that you kept it. A job that repeats on a schedule isn't memory: that's a routine, and create_schedule makes one once the user agrees.`;
|
||||
|
||||
/**
|
||||
* A plan waiting on the user: the bot wrote it and may not start it yet,
|
||||
* whatever the user writes in the meantime.
|
||||
*/
|
||||
export const PlanWaitingNote = ({ plan }: { plan: PlanPrompt }) => `# Your plan is waiting on the user
|
||||
|
||||
Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting for the user to approve it or change its steps. Its steps are not work yet: don't start them, don't report on them, and don't write another plan. Answer what the user wrote; if they asked for changes to the plan, they make them on the card.`;
|
||||
|
||||
/**
|
||||
* Given to the run that works one step of an approved plan: that step only,
|
||||
* a short report of it, and nothing else. This is where a reply stops being
|
||||
* a wall of text.
|
||||
*/
|
||||
export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
|
||||
const index = plan.current_step ?? 0;
|
||||
const step = plan.steps[index];
|
||||
|
||||
return `# Your plan, step ${index + 1} of ${plan.steps.length}
|
||||
|
||||
Plan #${plan.id} "${plan.title}".${plan.goal ? ` Goal: ${plan.goal}` : ""}
|
||||
|
||||
${planStepLines({ plan })}
|
||||
|
||||
This reply works step ${index + 1} only: ${step?.text || ""}
|
||||
|
||||
- One step per reply. The app wakes you for the next one when this finishes, so don't start it now and don't do two.
|
||||
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
|
||||
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
|
||||
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask one question with ask_user and say the plan is holding at this step.
|
||||
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same reply, and say what changed.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Given to any other run in a conversation whose plan is approved and being
|
||||
* worked: the plan is in the prompt, and the user's own message comes first.
|
||||
*/
|
||||
export const PlanActiveNote = ({ plan }: { plan: PlanPrompt }) => {
|
||||
const index = plan.current_step;
|
||||
|
||||
return `# The plan in this conversation
|
||||
|
||||
Plan #${plan.id} "${plan.title}" is approved and in progress${index == null ? "" : `, on step ${index + 1} of ${plan.steps.length}`}.
|
||||
|
||||
${planStepLines({ plan })}
|
||||
|
||||
- If the user's message is about this plan's work, work that step and only that step, then complete_plan_step with what it produced, then a short report.
|
||||
- If they asked something else, answer that and leave the plan where it is: it carries on from there.
|
||||
- The steps are theirs to change on the card. If the work moved on from one of them, update_plan and say what changed.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* A paused plan: the user stopped it, so its steps wait until they say
|
||||
* otherwise. The bot still answers them.
|
||||
*/
|
||||
export const PlanPausedNote = ({ plan }: { plan: PlanPrompt }) => `# A paused plan
|
||||
|
||||
Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_step ?? 0) + 1} of ${plan.steps.length}. Don't work its steps and don't finish them: answer what the user asks, and leave picking it back up to them (they resume it from the card).`;
|
||||
|
||||
/**
|
||||
* Added to a routine's run: nobody is there to approve a plan, so the bot
|
||||
* writes one and works all of it in the run, reporting at the end.
|
||||
*/
|
||||
export const ScheduledPlanNote = `# A plan in a scheduled run
|
||||
|
||||
Nobody is watching this run, so a plan can't wait for approval. If this run's work is several pieces that build on each other, write it with create_plan anyway (it is approved at once here) and work its steps in this run: complete_plan_step after each one, with what it produced, so the conversation shows how far it got. Nothing interleaves with your run, so don't stop after one step. Your report at the end covers the whole plan: what each step produced and what is left.`;
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Where a plan stands. A bot writes one as `planned` and the user approves
|
||||
* it on its card, which makes it `active`: from there the bot works one
|
||||
* step at a time and reports each (`complete_plan_step`). `paused` stops it
|
||||
* where it is until the user resumes it, `done` is every step finished or
|
||||
* skipped, and `cancelled` is a plan nobody carries on.
|
||||
*/
|
||||
export const BotPlanStates = [
|
||||
{
|
||||
title: "Waiting for you",
|
||||
value: "planned",
|
||||
},
|
||||
{
|
||||
title: "In progress",
|
||||
value: "active",
|
||||
},
|
||||
{
|
||||
title: "Paused",
|
||||
value: "paused",
|
||||
},
|
||||
{
|
||||
title: "Done",
|
||||
value: "done",
|
||||
},
|
||||
{
|
||||
title: "Cancelled",
|
||||
value: "cancelled",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type BotPlanState = (typeof BotPlanStates)[number]["value"];
|
||||
|
||||
/**
|
||||
* The states a plan can still be worked in: only one of them is open in a
|
||||
* conversation at a time.
|
||||
*/
|
||||
export const BotPlanOpenStates: BotPlanState[] = ["planned", "active", "paused"];
|
||||
|
||||
/**
|
||||
* A step of a plan: it waits, it's done (with a line on what it produced),
|
||||
* or it was skipped (the work made it unnecessary).
|
||||
*/
|
||||
export const BotPlanStepStates = [
|
||||
{
|
||||
title: "Done",
|
||||
value: "done",
|
||||
},
|
||||
{
|
||||
title: "Skipped",
|
||||
value: "skipped",
|
||||
},
|
||||
{
|
||||
title: "Pending",
|
||||
value: "pending",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type BotPlanStepState = (typeof BotPlanStepStates)[number]["value"];
|
||||
|
||||
/**
|
||||
* The states the user sets from a plan's card: approve it, pause it or end
|
||||
* it. `done` is the app's own call, set when the last step is finished.
|
||||
*/
|
||||
export const BotPlanSettableStates: BotPlanState[] = ["active", "paused", "cancelled"];
|
||||
@@ -84,7 +84,7 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
|
||||
/**
|
||||
* A worker can't hand out work: it passes on a task it already has
|
||||
* (`hand_over_task`), and asks the crew for anything else through the
|
||||
* coordinator (`ask_crew`).
|
||||
* coordinator (`ask_bot`).
|
||||
*/
|
||||
worker: ["hand_over_task"],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
|
||||
import cancelAskJobs from "./cancel-ask-jobs";
|
||||
import finishAsk from "./finish-ask";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ends every request a bot is part of, before the bot row goes: the ones it
|
||||
* asked and the ones it was asked. Left open, an ask stays `working` for
|
||||
* good (nothing would ever end it), it is never pruned, and it spends the
|
||||
* asking bot's open-request allowance (`AppData.AskMaxOpenPerBot`) so that
|
||||
* bot can never ask anyone again. A request whose asked bot is gone ends
|
||||
* with a failure the asking bot is woken with; one whose asking bot is gone
|
||||
* is only closed, since there is nobody to tell.
|
||||
*/
|
||||
export default async function endAsksForBot({ bot_id }: Params) {
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
|
||||
sql: `SELECT * FROM bot_asks
|
||||
WHERE status IN ('pending', 'working')
|
||||
AND (requester_bot_id = ? OR target_bot_id = ?)`,
|
||||
values: [Number(bot_id), Number(bot_id)],
|
||||
});
|
||||
|
||||
const ended: BUN_SQLITE_COBBLE_BOT_ASKS[] = [];
|
||||
|
||||
for (const ask of res.payload || []) {
|
||||
const asked = Number(ask.target_bot_id) == Number(bot_id);
|
||||
|
||||
const finished = await finishAsk({
|
||||
ask,
|
||||
status: "failed",
|
||||
outcome: asked
|
||||
? "The bot it was passed to was deleted, so it never answered."
|
||||
: "The bot that asked was deleted.",
|
||||
wake: asked && Number(ask.requester_bot_id) != Number(bot_id),
|
||||
});
|
||||
|
||||
if (!finished) continue;
|
||||
|
||||
ended.push(finished);
|
||||
|
||||
/**
|
||||
* Whatever was still running for it goes too, and its task closes
|
||||
* with it (`cancelAskJobs`).
|
||||
*/
|
||||
await cancelAskJobs({ ask_id: Number(ask.id), reason: "The bot was deleted." });
|
||||
}
|
||||
|
||||
return ended;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
/**
|
||||
* The conversation the run is in: a plan is only worked where it was
|
||||
* written.
|
||||
*/
|
||||
session_id: number | string;
|
||||
/**
|
||||
* What the step produced, in a line or two.
|
||||
*/
|
||||
summary: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot finished the plan's current step: it's marked done with what it
|
||||
* produced, and the plan moves to the next one. The last step done ends
|
||||
* the plan.
|
||||
*
|
||||
* A step is only ever finished inside a run that did the work, one at a
|
||||
* time: a plan waiting on the user can't be worked, and neither can one
|
||||
* that's paused, ended, or has nothing left.
|
||||
*/
|
||||
export default async function completeBotPlanStep({ plan_id, session_id, summary }: Params) {
|
||||
const row = await grabBotPlan({ plan_id });
|
||||
|
||||
if (Number(row.session_id) != Number(session_id)) {
|
||||
throw new AppError(`Plan #${row.id} belongs to another conversation: work that conversation's plan.`);
|
||||
}
|
||||
|
||||
if (row.status == "planned") {
|
||||
throw new AppError(
|
||||
`Plan #${row.id} is waiting for the user to approve it on its card: don't work its steps yet. Answer them and let them decide.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (row.status != "active") {
|
||||
throw new AppError(`Plan #${row.id} is ${row.status}: there's no step to finish.`);
|
||||
}
|
||||
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
const index = currentPlanStepIndex({ steps });
|
||||
|
||||
if (index == null) {
|
||||
throw new AppError(`Every step of plan #${row.id} is already done.`);
|
||||
}
|
||||
|
||||
const note = summary.trim().slice(0, AppData.BotPlanStepNoteMaxChars);
|
||||
const working = steps[index];
|
||||
|
||||
if (!working) {
|
||||
throw new AppError(`Every step of plan #${row.id} is already done.`);
|
||||
}
|
||||
|
||||
steps[index] = { text: working.text, state: "done", note };
|
||||
|
||||
const next = currentPlanStepIndex({ steps });
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_plans SET steps = ?, status = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [JSON.stringify(steps), next == null ? "done" : "active", now, Number(row.id)],
|
||||
});
|
||||
|
||||
return {
|
||||
plan_id: Number(row.id),
|
||||
session_id: Number(row.session_id),
|
||||
bot_id: Number(row.bot_id),
|
||||
index,
|
||||
step: working.text,
|
||||
note,
|
||||
/**
|
||||
* The step to work next: null once the plan is finished.
|
||||
*/
|
||||
next_step: next,
|
||||
done: next == null,
|
||||
steps,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
import shouldContinuePlan from "@/src/utils/should-continue-plan";
|
||||
import enqueuePlanStep from "./enqueue-plan-step";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The reply asked the user something (`ask_user`), so it waits on them
|
||||
* rather than carrying on.
|
||||
*/
|
||||
needs_you?: boolean;
|
||||
/**
|
||||
* The tools the run called: one that starts work (a task, a hand-over,
|
||||
* a request to another bot) has a report still to come, so the plan
|
||||
* waits for it instead of talking over it.
|
||||
*/
|
||||
tool_names?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Carries a plan on after a run finished a step: the bot reports the step it
|
||||
* finished, and this wakes it for the next one, so the work runs through the
|
||||
* plan step by step without the user nudging it each time.
|
||||
*
|
||||
* Nothing is queued when the run is waiting on the user, when it started
|
||||
* work whose report is still to come, when the plan was paused or cancelled
|
||||
* meanwhile, or when the conversation already has a reply waiting (a message
|
||||
* the user sent mid-step, whose own run picks the plan up from there).
|
||||
*/
|
||||
export default async function continueBotPlan({ plan_id, session_id, needs_you, tool_names }: Params) {
|
||||
const row = await grabBotPlan({ plan_id });
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
|
||||
const waiting = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bots_queue
|
||||
WHERE session_id = ? AND kind = 'reply' AND status IN ('pending', 'processing')
|
||||
LIMIT 1`,
|
||||
values: [Number(session_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
const carry_on = shouldContinuePlan({
|
||||
status: row.status || "",
|
||||
needs_you,
|
||||
tool_names,
|
||||
plan_session_id: row.session_id,
|
||||
session_id,
|
||||
has_pending_step: currentPlanStepIndex({ steps }) != null,
|
||||
has_waiting_reply: Boolean(waiting),
|
||||
});
|
||||
|
||||
if (!carry_on) return null;
|
||||
|
||||
return await enqueuePlanStep({ plan_id: row.id });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_PLANS, BunSQLiteTables } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import type { BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
|
||||
import grabSessionPlan from "./grab-session-plan";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
title: string;
|
||||
goal?: string;
|
||||
/**
|
||||
* The steps in the order they're worked.
|
||||
*/
|
||||
steps: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Stores a plan a bot wrote, waiting for the user's approval (`planned`).
|
||||
* One plan is open in a conversation at a time: the bot works the one it
|
||||
* has before writing another. Returns the plan's id.
|
||||
*/
|
||||
export default async function createBotPlan({ user_id, bot_id, session_id, workspace_id, title, goal, steps }: Params) {
|
||||
const open = await grabSessionPlan({ session_id });
|
||||
|
||||
if (open) {
|
||||
throw new AppError(
|
||||
`There's already a plan open in this conversation (#${open.id}, "${open.title || "untitled"}"): work that one, or cancel it before writing another.`,
|
||||
);
|
||||
}
|
||||
|
||||
const records: BotPlanStepRecord[] = steps.map((step) => ({ text: step, state: "pending", note: "" }));
|
||||
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_PLANS, (typeof BunSQLiteTables)[number]>({
|
||||
table: "bot_plans",
|
||||
data: [
|
||||
{
|
||||
title,
|
||||
goal: goal || "",
|
||||
steps: JSON.stringify(records),
|
||||
status: "planned",
|
||||
user_id: Number(user_id),
|
||||
bot_id: Number(bot_id),
|
||||
session_id: Number(session_id),
|
||||
workspace_id: workspace_id ? Number(workspace_id) : undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const id = Number(res.singleRes?.id || res.postInsertReturn?.insertId);
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the plan: ${res.msg}`);
|
||||
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
session_ids: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes the plans of sessions that are going away, with the conversation
|
||||
* they belonged to (foreign keys are off outside the server process, so a
|
||||
* parent's children go explicitly).
|
||||
*/
|
||||
export default async function deleteBotPlanRows({ session_ids }: Params) {
|
||||
const ids = session_ids.map(Number).filter(Boolean);
|
||||
|
||||
if (!ids.length) return;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_plans WHERE session_id IN (${ids.map(() => "?").join(", ")})`,
|
||||
values: ids,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wakes the bot for its plan's current step: one reply job, which works
|
||||
* that step and reports it. Nothing is queued for a plan that isn't
|
||||
* running, or one with no step left, so approving a finished plan, a double
|
||||
* click or a stop never leaves a run with nothing to do.
|
||||
*
|
||||
* The step itself is read by the run from the conversation's plan, never
|
||||
* from here: a run that starts late still works the step that's actually
|
||||
* next.
|
||||
*/
|
||||
export default async function enqueuePlanStep({ plan_id }: Params) {
|
||||
const row = await grabBotPlan({ plan_id });
|
||||
|
||||
if (row.status != "active") return null;
|
||||
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
|
||||
if (currentPlanStepIndex({ steps }) == null) return null;
|
||||
|
||||
const user_id = Number(row.user_id);
|
||||
|
||||
const job_id = await enqueueBotJob({
|
||||
kind: "reply",
|
||||
user_id,
|
||||
bot_id: Number(row.bot_id),
|
||||
session_id: Number(row.session_id),
|
||||
title: BotReplyJobTitle,
|
||||
instructions: "Work the current step of the plan in this conversation, then report it.",
|
||||
params: { plan_id: Number(row.id) },
|
||||
});
|
||||
|
||||
return job_id;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
import toBotPlanView from "./to-bot-plan-view";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
/**
|
||||
* Only the user it was made for reads it.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan as its card shows it, for the user it was made for. Throws
|
||||
* otherwise.
|
||||
*/
|
||||
export default async function grabBotPlanView({ plan_id, user_id }: Params) {
|
||||
const row = await grabBotPlan({ plan_id, user_id });
|
||||
|
||||
return toBotPlanView({ row }) as BotPlanView;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_PLANS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
/**
|
||||
* Only the user a plan was made for reads it. Left out by a run, which
|
||||
* already works that user's conversation.
|
||||
*/
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan as the helpers read it: its id and the places it belongs to are
|
||||
* there once it's been found, which the typedef can't say on its own.
|
||||
*/
|
||||
export type BotPlanRow = BUN_SQLITE_COBBLE_BOT_PLANS & {
|
||||
id: number;
|
||||
user_id: number;
|
||||
bot_id: number;
|
||||
session_id: number;
|
||||
title: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan by its id, with the name of the bot that wrote it (a run's prompt
|
||||
* and the card both name it). Throws when it isn't there, or isn't the
|
||||
* user's.
|
||||
*/
|
||||
export default async function grabBotPlan({ plan_id, user_id }: Params) {
|
||||
const row = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_PLANS & { bot_name?: string }>({
|
||||
sql: `SELECT bp.*, b.name AS bot_name FROM bot_plans bp
|
||||
LEFT JOIN bots b ON b.id = bp.bot_id
|
||||
WHERE bp.id = ?${user_id ? " AND bp.user_id = ?" : ""} LIMIT 1`,
|
||||
values: user_id ? [Number(plan_id), Number(user_id)] : [Number(plan_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row?.id) throw new AppError(`That plan isn't yours or no longer exists.`);
|
||||
|
||||
return row as BotPlanRow;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_PLANS } from "@/db/types/db";
|
||||
import { BotPlanOpenStates } from "@/src/dict/bot-plan-dict";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The plan open in a conversation: the one the bot is waiting on the user
|
||||
* to approve, or is working. A conversation has at most one, so a run
|
||||
* always knows which plan it is on. Null when the conversation has none
|
||||
* (finished and cancelled plans are history, not work).
|
||||
*/
|
||||
export default async function grabSessionPlan({ session_id }: Params) {
|
||||
const row = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_PLANS>({
|
||||
sql: `SELECT * FROM bot_plans
|
||||
WHERE session_id = ? AND status IN (${BotPlanOpenStates.map(() => "?").join(", ")})
|
||||
ORDER BY id DESC LIMIT 1`,
|
||||
values: [Number(session_id), ...BotPlanOpenStates],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return row?.id ? row : null;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pauses the plan a failed run was working a step of: nothing would ever
|
||||
* advance it, so it would show that step in progress forever and every later
|
||||
* reply in that conversation would be told the plan is under way and may not
|
||||
* move it. Paused, the card offers the step again (Resume queues it as it
|
||||
* stands). The step itself is left for that retry. A plan the user paused or
|
||||
* ended meanwhile, or one of another conversation, is left alone.
|
||||
*/
|
||||
export default async function pauseFailedPlanStep({ job }: Params) {
|
||||
const plan_id = Number(parseJobJson({ text: job.params })?.plan_id) || 0;
|
||||
|
||||
if (!plan_id || !job.session_id) return null;
|
||||
|
||||
const row = await grabBotPlan({ plan_id }).catch(() => null);
|
||||
|
||||
if (!row?.id || row.status != "active") return null;
|
||||
|
||||
if (Number(row.session_id) != Number(job.session_id)) return null;
|
||||
|
||||
const res = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `UPDATE bot_plans SET status = 'paused', updated_at = ?
|
||||
WHERE id = ? AND status = 'active' RETURNING id`,
|
||||
values: [Date.now(), Number(row.id)],
|
||||
});
|
||||
|
||||
if (!res.payload?.length) return null;
|
||||
|
||||
return {
|
||||
plan_id: Number(row.id),
|
||||
session_id: Number(row.session_id),
|
||||
bot_id: Number(row.bot_id),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import planStepsRewriteProblem from "@/src/utils/plan-steps-rewrite-problem";
|
||||
import parseBotPlanSteps, { type BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
user_id: number | string;
|
||||
title: string;
|
||||
goal?: string;
|
||||
/**
|
||||
* The plan's steps as the user wants them, in order.
|
||||
*/
|
||||
steps: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The user changed a plan's steps on its card, before the bot starts or
|
||||
* while it's working. A step already done (or skipped) is the record of work
|
||||
* that really happened: it stays where it is and keeps its note, so it may
|
||||
* not be changed or dropped, and the steps before it are its own. Everything
|
||||
* after is theirs to rewrite, reorder, add to or cut. A plan left with
|
||||
* nothing to work is done.
|
||||
*/
|
||||
export default async function saveBotPlanSteps({ plan_id, user_id, title, goal, steps }: Params) {
|
||||
const row = await grabBotPlan({ plan_id, user_id });
|
||||
|
||||
if (row.status != "planned" && row.status != "active" && row.status != "paused") {
|
||||
throw new AppError(`This plan is ${row.status}: there's nothing left to change in it.`);
|
||||
}
|
||||
|
||||
const existing = parseBotPlanSteps({ text: row.steps });
|
||||
const finished = existing.filter((step) => step.state != "pending");
|
||||
const by_text = new Map(finished.map((step) => [step.text.toLowerCase(), step]));
|
||||
|
||||
const next: BotPlanStepRecord[] = steps.map((text) => {
|
||||
const kept = by_text.get(text.toLowerCase());
|
||||
|
||||
return kept ? { ...kept } : { text, state: "pending" as const, note: "" };
|
||||
});
|
||||
|
||||
const rewrite_problem = planStepsRewriteProblem({ finished, next });
|
||||
|
||||
if (rewrite_problem) throw new AppError(rewrite_problem);
|
||||
|
||||
const now = Date.now();
|
||||
const done = currentPlanStepIndex({ steps: next }) == null;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_plans SET title = ?, goal = ?, steps = ?, status = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [
|
||||
title,
|
||||
goal || "",
|
||||
JSON.stringify(next),
|
||||
done ? "done" : row.status,
|
||||
now,
|
||||
Number(row.id),
|
||||
],
|
||||
});
|
||||
|
||||
return await grabBotPlan({ plan_id: row.id, user_id });
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
user_id: number | string;
|
||||
status: BotPlanState;
|
||||
};
|
||||
|
||||
/**
|
||||
* The user moved a plan from its card: approved it (which starts it),
|
||||
* paused it where it is, picked it back up, or ended it. Only the moves
|
||||
* that mean something from where it stands are allowed, so a double click
|
||||
* changes nothing and a finished plan never comes back.
|
||||
*
|
||||
* Returns the row as it now stands and whether it just started, which is
|
||||
* when the bot is woken for its first step.
|
||||
*/
|
||||
export default async function setBotPlanStatus({ plan_id, user_id, status }: Params) {
|
||||
const row = await grabBotPlan({ plan_id, user_id });
|
||||
const current = row.status as BotPlanState;
|
||||
|
||||
if (current == status) return { row, started: false };
|
||||
|
||||
if (current == "done" || current == "cancelled") {
|
||||
throw new AppError(`This plan is ${current}: it can't be picked up again.`);
|
||||
}
|
||||
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
const caught_up = currentPlanStepIndex({ steps }) == null;
|
||||
|
||||
if (status == "active") {
|
||||
if (current != "planned" && current != "paused") {
|
||||
throw new AppError(`This plan is ${current}: it isn't paused.`);
|
||||
}
|
||||
|
||||
if (caught_up) {
|
||||
throw new AppError(`Every step of this plan is already done: there's nothing to start.`);
|
||||
}
|
||||
}
|
||||
|
||||
if (status == "paused" && current != "active") {
|
||||
throw new AppError(`Only a plan that's running can be paused.`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_plans SET status = ?, decided_at = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [
|
||||
status,
|
||||
status == "active" || status == "cancelled" ? now : row.decided_at || null,
|
||||
now,
|
||||
Number(row.id),
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
row: await grabBotPlan({ plan_id: row.id, user_id }),
|
||||
/**
|
||||
* Approved for the first time: the bot picks the plan up now. A
|
||||
* resume after a pause is the same move from the user's side.
|
||||
*/
|
||||
started: status == "active",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_PLANS } from "@/db/types/db";
|
||||
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
import planStepCounts from "@/src/utils/plan-step-counts";
|
||||
|
||||
type Params = {
|
||||
row: BUN_SQLITE_COBBLE_BOT_PLANS & { bot_name?: string };
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan's row as the card and a prompt read it: its steps parsed, where it
|
||||
* stands, and how much of it is behind it. One shape for both, so the card
|
||||
* never shows something the bot wasn't told.
|
||||
*/
|
||||
export default function toBotPlanView({ row }: Params): BotPlanView {
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
const counts = planStepCounts({ steps });
|
||||
|
||||
return {
|
||||
id: Number(row.id),
|
||||
title: row.title || "",
|
||||
goal: row.goal || "",
|
||||
steps,
|
||||
status: (row.status || "planned") as BotPlanState,
|
||||
current_step: currentPlanStepIndex({ steps }),
|
||||
finished_steps: counts.finished,
|
||||
total_steps: counts.total,
|
||||
decided_at: row.decided_at ? Number(row.decided_at) : null,
|
||||
created_at: Number(row.created_at) || 0,
|
||||
updated_at: Number(row.updated_at) || 0,
|
||||
user_id: Number(row.user_id),
|
||||
bot_id: Number(row.bot_id),
|
||||
bot_name: row.bot_name || "",
|
||||
session_id: Number(row.session_id),
|
||||
workspace_id: row.workspace_id ? Number(row.workspace_id) : null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
question_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes questions a bot asked whose message never went out. The card is
|
||||
* the only way to answer them, so a row left behind waits for an answer
|
||||
* nobody can give, and counts as still asked.
|
||||
*/
|
||||
export default async function deleteBotQuestion({ question_id }: Params) {
|
||||
const res = await BunSQLite.sql({
|
||||
sql: "DELETE FROM bot_questions WHERE id = ? AND status = 'pending'",
|
||||
values: [question_id],
|
||||
});
|
||||
|
||||
if (res.error) throw new Error(`Couldn't delete the question: ${res.msg || res.error}`);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -119,5 +119,16 @@ export default async function carryOverBotSession({
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything else still to come for the closed session moves with it.
|
||||
* A queued job left behind answers into a session the conversation has
|
||||
* left (`SessionMovedBar` where its reply should be), sets unread on a
|
||||
* thread nobody opens again, and pushes nothing the user is looking at.
|
||||
*/
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bots_queue SET session_id = ? WHERE session_id = ? AND status IN ('pending', 'processing')`,
|
||||
values: [next.id!, active.id],
|
||||
});
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteUnlinkedAttachmentMedia from "../media/delete-unlinked-attachment-media";
|
||||
import deleteBotPlanRows from "../bot-plans/delete-bot-plan-rows";
|
||||
|
||||
type Params = {
|
||||
session_ids: number[];
|
||||
@@ -105,6 +106,7 @@ export default async function deleteSessionRows({ session_ids }: Params) {
|
||||
sql: `DELETE FROM bot_tasks WHERE session_id IN (${session_placeholders})`,
|
||||
values: ids,
|
||||
});
|
||||
await deleteBotPlanRows({ session_ids: ids });
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_sessions WHERE id IN (${session_placeholders})`,
|
||||
values: ids,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The face a bot shows one user while it answers another bot's crew request
|
||||
* for them. That run works in a hidden session, which
|
||||
* `grabRunningBotJobFace` leaves out on purpose, so without this a job that
|
||||
* finished beside it would put the bot to sleep while the request was still
|
||||
* being answered. Null when no request is running.
|
||||
*/
|
||||
export default async function answeringAskFace({
|
||||
bot_id,
|
||||
user_id,
|
||||
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
|
||||
const running = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT q.id FROM bots_queue q
|
||||
WHERE q.bot_id = ? AND q.status = 'processing'
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ask_id IS NOT NULL)
|
||||
LIMIT 1`,
|
||||
values: [bot_id, user_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return running ? { face: "working", status_line: BotReplyJobTitle } : null;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import { BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import setBotFace from "../bots/set-bot-face";
|
||||
import answeringAskFace from "./answering-ask-face";
|
||||
import countOpenBotJobs from "./count-open-bot-jobs";
|
||||
import grabRunningBotJobFace from "./grab-running-bot-job-face";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
user_id: number | string;
|
||||
/**
|
||||
* Of the job that just ended, so a bot with nothing left shows done
|
||||
* after a task and idle after a reply.
|
||||
*/
|
||||
kind?: BUN_SQLITE_COBBLE_BOTS_QUEUE["kind"];
|
||||
};
|
||||
|
||||
/**
|
||||
* What a bot shows a user now that one of its jobs ended without asking
|
||||
* for them: its resting face when nothing else is open, else the work still
|
||||
* running, or waiting when what is left is only queued. Counted for the
|
||||
* user alone: another user's job is never on this face.
|
||||
*/
|
||||
export default async function botFaceAfterJob({ bot_id, user_id, kind }: Params) {
|
||||
/**
|
||||
* A crew request's run shows its work too, so the face left to show is
|
||||
* the one still processing. Asked first: its session is hidden, so the
|
||||
* job counts of one that's still being answered read as nothing open.
|
||||
*/
|
||||
const running = await grabRunningBotJobFace({ bot_id, user_id });
|
||||
|
||||
if (running) return await setBotFace({ bot_id, user_id, ...running });
|
||||
|
||||
const answering = await answeringAskFace({ bot_id, user_id });
|
||||
|
||||
if (answering) return await setBotFace({ bot_id, user_id, ...answering });
|
||||
|
||||
const open = await countOpenBotJobs({ bot_id, user_id, conversations_only: true });
|
||||
|
||||
if (!open) {
|
||||
return await setBotFace({ bot_id, user_id, face: kind == "task" ? "done" : "idle" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Jobs are open for this user but none is running (`deferBotJob` put
|
||||
* them back while every model rests, or they wait in the queue): the
|
||||
* bot waits, rather than showing work that isn't happening.
|
||||
*/
|
||||
return await setBotFace({
|
||||
bot_id,
|
||||
user_id,
|
||||
face: "asleep",
|
||||
status_line: BotWaitingStatusLine,
|
||||
});
|
||||
}
|
||||
@@ -2,8 +2,10 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import { BotJobCancelledError } from "@/src/dict/bot-queue-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
|
||||
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import botFaceAfterJob from "./bot-face-after-job";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -12,8 +14,11 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Cancels a pending or running job in one of the user's conversations. It's marked failed
|
||||
* with `BotJobCancelledError`; a running handler finds out on its next
|
||||
* `updateBotJob` (which returns false) and stops. Its task is closed.
|
||||
* with `BotJobCancelledError`; a running handler is aborted here and now when
|
||||
* this process is the one running it (anywhere else it finds out on its
|
||||
* next `updateBotJob`, which returns false) and stops. Its task is closed,
|
||||
* and the bot's face for that user is worked out again, so a cancelled run
|
||||
* never leaves it showing work that ended.
|
||||
*/
|
||||
export default async function cancelBotJob({ user_id, job_id }: Params) {
|
||||
const now = Date.now();
|
||||
@@ -39,6 +44,17 @@ export default async function cancelBotJob({ user_id, job_id }: Params) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* What it is waiting on is aborted now, so the run stops writing before
|
||||
* the caller goes on: a cancelled run that kept its model call going
|
||||
* still wrote its files and its steps.
|
||||
*/
|
||||
abortRunningJob({ job_id: Number(job.id) });
|
||||
|
||||
if (job.bot_id) {
|
||||
await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
|
||||
}
|
||||
|
||||
await recordHookCallResponse({ job, status: "failed", response: BotJobCancelledError, now });
|
||||
|
||||
await settleInstallRequest({ job, text: BotJobCancelledError, failed: true });
|
||||
|
||||
@@ -25,6 +25,12 @@ type Params = {
|
||||
*
|
||||
* bun-sqlite's `queue.claim` takes no filter, so the claim is its same
|
||||
* single statement (atomic: two workers never claim one job) plus `kind`.
|
||||
*
|
||||
* One job per computer: only one task can work on a computer at a time, so
|
||||
* claiming several of its tasks filled every task slot with jobs waiting on
|
||||
* that computer's lock, and a second computer sat idle while its pending
|
||||
* tasks were already claimed. A computer with a task in flight is skipped
|
||||
* here instead, so the slots go to work that can run now.
|
||||
*/
|
||||
export default async function claimBotJobs({ worker, limit = 1, kind }: Params) {
|
||||
const released = await BunSQLite.queue.release_stale<
|
||||
@@ -44,9 +50,17 @@ export default async function claimBotJobs({ worker, limit = 1, kind }: Params)
|
||||
sql: `UPDATE bots_queue SET status = 'processing', attempts = attempts + 1,
|
||||
locked_at = ?, locked_by = ?, updated_at = ?
|
||||
WHERE id IN (
|
||||
SELECT id FROM bots_queue
|
||||
SELECT MIN(id) FROM bots_queue
|
||||
WHERE status = 'pending' AND available_at <= ? AND kind = ?
|
||||
ORDER BY id LIMIT ?
|
||||
AND (
|
||||
computer_id IS NULL
|
||||
OR computer_id NOT IN (
|
||||
SELECT computer_id FROM bots_queue
|
||||
WHERE status = 'processing' AND kind = 'task' AND computer_id IS NOT NULL
|
||||
)
|
||||
)
|
||||
GROUP BY COALESCE(computer_id, -id)
|
||||
ORDER BY MIN(id) LIMIT ?
|
||||
) RETURNING *`,
|
||||
values: [now, worker, now, now, kind, Math.floor(limit)],
|
||||
});
|
||||
|
||||
@@ -2,18 +2,19 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import { BotNeedsYouStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import insertBotMessage from "../bots/insert-bot-message";
|
||||
import deleteBotMessage from "../bots/delete-bot-message";
|
||||
import setBotFace from "../bots/set-bot-face";
|
||||
import countOpenBotJobs from "./count-open-bot-jobs";
|
||||
import botFaceAfterJob from "./bot-face-after-job";
|
||||
import grabLockedBotJob from "./grab-locked-bot-job";
|
||||
import relayJobToRequester from "./relay-job-to-requester";
|
||||
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
|
||||
import noteTrackerTask from "./note-tracker-task";
|
||||
import jobSessionId from "./job-session-id";
|
||||
import grabJobUserId from "./grab-job-user-id";
|
||||
import grabRunningBotJobFace from "./grab-running-bot-job-face";
|
||||
import withMessageUsage from "../usage/with-message-usage";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
|
||||
import onAskJobEnded from "../asks/on-ask-job-ended";
|
||||
@@ -62,8 +63,8 @@ type Params = {
|
||||
* to the user in the bot's conversation. Unless it has other jobs open
|
||||
* for that user, the bot shows that user needs-you if asked, else done
|
||||
* after a task and idle after a reply; with others open, it shows the one
|
||||
* still running (a reply in another session mustn't hide a task's row).
|
||||
* Nobody else's face changes. A handed-over job's result also goes to the bot that handed
|
||||
* still running (a reply in another session mustn't hide a task's row) or
|
||||
* waits for one held back by the queue. Nobody else's face changes. A handed-over job's result also goes to the bot that handed
|
||||
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
|
||||
* its whole step budget without finishing (`noteTrackerTask`). A hook
|
||||
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job working a crew
|
||||
@@ -86,34 +87,19 @@ export default async function completeBotJob({
|
||||
throw new AppError(`This job is no longer held by ${worker}.`);
|
||||
}
|
||||
|
||||
const res = await BunSQLite.queue.complete({
|
||||
table: "bots_queue",
|
||||
id: job.id,
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new Error(`Couldn't complete the job: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
|
||||
values: [result, now, job.id],
|
||||
});
|
||||
|
||||
/**
|
||||
* A handed-over task's run is about that task, whatever its tools did.
|
||||
*/
|
||||
const message_task_ids = [jobTrackerTaskId({ job }), ...task_ids];
|
||||
|
||||
if (job.task_id) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
|
||||
values: [now, job.task_id],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The answer is written while this handler still holds the job: with
|
||||
* the job marked done first, a throw here reached `failBotJob`, which
|
||||
* found the job gone and swallowed it, so the answer was lost with no
|
||||
* notice and the bot stayed at working.
|
||||
*/
|
||||
const inserted = silent
|
||||
? null
|
||||
: await insertBotMessage({
|
||||
@@ -145,6 +131,34 @@ export default async function completeBotJob({
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
const res = await BunSQLite.queue.complete({
|
||||
table: "bots_queue",
|
||||
id: job.id,
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
/**
|
||||
* The job never ended, so its answer would sit under a run with no
|
||||
* end: it's taken back out (its files stay) and the caller fails
|
||||
* the job, which tells the user instead.
|
||||
*/
|
||||
if (inserted?.id) await deleteBotMessage({ message_id: inserted.id }).catch(() => {});
|
||||
|
||||
throw new Error(`Couldn't complete the job: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
|
||||
values: [result, now, job.id],
|
||||
});
|
||||
|
||||
if (job.task_id) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
|
||||
values: [now, job.task_id],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushed live as it is returned, so it carries its usage now: the
|
||||
* thread shows the tokens without a reload.
|
||||
@@ -161,41 +175,49 @@ export default async function completeBotJob({
|
||||
*/
|
||||
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }));
|
||||
|
||||
const bot = !user_id || in_hook
|
||||
? null
|
||||
: needs_you
|
||||
? await setBotFace({
|
||||
bot_id: job.bot_id,
|
||||
user_id,
|
||||
face: "needs-you",
|
||||
status_line: BotNeedsYouStatusLine,
|
||||
})
|
||||
: (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,
|
||||
user_id,
|
||||
face: job.kind == "reply" ? "idle" : "done",
|
||||
});
|
||||
/**
|
||||
* The job is done and its answer saved, so what is left is clearing up:
|
||||
* a throw in here is logged rather than failing a job that already
|
||||
* ended and holding the answer back from the live push.
|
||||
*/
|
||||
let bot: Awaited<ReturnType<typeof setBotFace>> | null = null;
|
||||
let relay: Awaited<ReturnType<typeof relayJobToRequester>> | null = null;
|
||||
|
||||
await noteTrackerTask({ job, exhausted });
|
||||
try {
|
||||
bot =
|
||||
!user_id || in_hook
|
||||
? null
|
||||
: needs_you
|
||||
? await setBotFace({
|
||||
bot_id: job.bot_id,
|
||||
user_id,
|
||||
face: "needs-you",
|
||||
status_line: BotNeedsYouStatusLine,
|
||||
})
|
||||
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
|
||||
|
||||
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
|
||||
await noteTrackerTask({ job, exhausted });
|
||||
|
||||
const relay = silent ? null : await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
|
||||
await recordHookCallResponse({
|
||||
job,
|
||||
status: "done",
|
||||
response: result,
|
||||
message_id: inserted?.id,
|
||||
});
|
||||
|
||||
await onAskJobEnded({ job, text: silent ? "" : result });
|
||||
relay = silent
|
||||
? null
|
||||
: await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
|
||||
|
||||
await settleInstallRequest({ job, text: result });
|
||||
await onAskJobEnded({ job, text: silent ? "" : result });
|
||||
|
||||
await settleInstallRequest({ job, text: result });
|
||||
} catch (error) {
|
||||
await logError({
|
||||
title: `Bot job #${job.id} completed, its clearing up didn't`,
|
||||
error,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
return { message, bot, relay };
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts back the face of a job still running for the user, if any.
|
||||
*/
|
||||
async function restoreRunningFace({ bot_id, user_id }: { bot_id: number; user_id: number }) {
|
||||
const running = await grabRunningBotJobFace({ bot_id, user_id });
|
||||
|
||||
return running ? await setBotFace({ bot_id, user_id, ...running }) : null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many replies are still to come in a session: its queued ones and the
|
||||
* one being written. Zero means nothing will answer there any more, which
|
||||
* is how a thread tells a reply that ended without a word (a run that found
|
||||
* every message already answered) from one still on its way.
|
||||
*/
|
||||
export default async function grabSessionOpenReplies({ session_id }: Params): Promise<number> {
|
||||
const row = (
|
||||
await BunSQLite.sql<{ count: number }>({
|
||||
sql: `SELECT COUNT(*) AS count FROM bots_queue
|
||||
WHERE session_id = ? AND kind = 'reply' AND status IN ('pending', 'processing')`,
|
||||
values: [Number(session_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return Number(row?.count) || 0;
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import onAskJobEnded from "../asks/on-ask-job-ended";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
|
||||
@@ -77,6 +79,16 @@ export default async function notifyBotJobFailed({
|
||||
|
||||
const user_id = await grabJobUserId({ job });
|
||||
|
||||
/**
|
||||
* A plan whose step this run was working is paused with it: nothing
|
||||
* would ever advance it, so its card would show that step in progress
|
||||
* forever and every later reply would be told the plan is running and
|
||||
* may not move it.
|
||||
*/
|
||||
const paused_plan = await pauseFailedPlanStep({ job }).catch(() => null);
|
||||
|
||||
if (paused_plan) await pushBotPlan(paused_plan);
|
||||
|
||||
/**
|
||||
* A hook's run is followed by nobody, so it never shows on the bot's
|
||||
* face. A crew request's does: the bot answering it is working.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
message_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes one message of a conversation, and the links it had to files:
|
||||
* the files themselves stay (they are the bot's or the user's, not the
|
||||
* message's), so this is safe for a message that shouldn't have been
|
||||
* written in the first place. Foreign keys are off outside the server, so
|
||||
* the child rows go explicitly.
|
||||
*/
|
||||
export default async function deleteBotMessage({ message_id }: Params) {
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_message_media WHERE message_id = ?`,
|
||||
values: [message_id],
|
||||
});
|
||||
|
||||
/**
|
||||
* A graphic the message showed is nobody's any more: it stays readable
|
||||
* from its own page rather than pointing at a message that is gone.
|
||||
*/
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_graphics SET message_id = NULL WHERE message_id = ?`,
|
||||
values: [message_id],
|
||||
}).catch(() => {});
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_messages WHERE id = ?`,
|
||||
values: [message_id],
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new Error(`Couldn't delete the message: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import purgeStorage, { grabStorageMediaIds } from "@/src/functions/backend/db/bo
|
||||
import { grabTaskMediaIds } from "@/src/functions/backend/db/tasks/purge-task-media";
|
||||
import passOnBotTasks from "@/src/functions/backend/db/tasks/pass-on-bot-tasks";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import endAsksForBot from "../asks/end-asks-for-bot";
|
||||
import { clearEnvCache } from "../envs/grab-all-envs";
|
||||
import grabUserBot from "./grab-user-bot";
|
||||
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
|
||||
@@ -69,6 +71,17 @@ export default async function deleteBot({ user_id, bot_id }: Params) {
|
||||
|
||||
clearEnvCache();
|
||||
|
||||
/**
|
||||
* After the row is gone, so a request it asked isn't answered into a
|
||||
* conversation that no longer exists. Left open, a request tied to this
|
||||
* bot is never pruned and spends the other bot's open-request allowance
|
||||
* for good.
|
||||
*/
|
||||
await endAsksForBot({ bot_id: bot.id! }).catch(async (error: unknown) => {
|
||||
await logError({ title: `Requests of bot #${bot.id} not ended`, error }).catch(() => {});
|
||||
return [];
|
||||
});
|
||||
|
||||
if (bot.image_media_id) {
|
||||
await deleteMedia({ id: bot.image_media_id, user_id: Number(user_id) }).catch(() => {});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | null;
|
||||
client_id: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The id of the message a send already stored under the composer's own id,
|
||||
* or null when that send never landed. Scoped to the user, the bot and the
|
||||
* place, and searched over every session of that conversation, since the
|
||||
* send that stored it may have rolled the next one onto a new session.
|
||||
*/
|
||||
export default async function grabMessageIdByClientId({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
client_id,
|
||||
}: Params): Promise<number | null> {
|
||||
const row = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT m.id FROM bot_messages m
|
||||
JOIN bot_sessions s ON s.id = m.session_id
|
||||
WHERE m.client_id = ? AND m.bot_id = ? AND m.author = 'user' AND s.user_id = ?
|
||||
AND COALESCE(m.workspace_id, 0) = COALESCE(?, 0)
|
||||
ORDER BY m.id DESC LIMIT 1`,
|
||||
values: [
|
||||
client_id,
|
||||
Number(bot_id),
|
||||
Number(user_id),
|
||||
workspace_id ? Number(workspace_id) : null,
|
||||
],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return Number(row?.id) || null;
|
||||
}
|
||||
@@ -35,6 +35,11 @@ type Params = {
|
||||
* to it, stored and shown like a crew request's outcome.
|
||||
*/
|
||||
from_install_request_id?: number;
|
||||
/**
|
||||
* The composer's own id for the send, so the same message sent twice
|
||||
* (a lost answer, a retry) is recognised rather than stored again.
|
||||
*/
|
||||
client_id?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -52,6 +57,7 @@ export default async function insertUserMessage({
|
||||
media = [],
|
||||
from_ask_id,
|
||||
from_install_request_id,
|
||||
client_id,
|
||||
}: Params): Promise<BotMessageWithAttachments> {
|
||||
const now = Date.now();
|
||||
|
||||
@@ -71,6 +77,7 @@ export default async function insertUserMessage({
|
||||
reply_to_message_id: reply_to?.id || undefined,
|
||||
from_ask_id,
|
||||
from_install_request_id,
|
||||
client_id,
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -104,6 +111,7 @@ export default async function insertUserMessage({
|
||||
reply_to_message_id: reply_to?.id || undefined,
|
||||
from_ask_id,
|
||||
from_install_request_id,
|
||||
client_id,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
attachments: media.map((file) => mediaToAttachment({ media: file })),
|
||||
|
||||
@@ -82,6 +82,14 @@ export default async function updateTask({
|
||||
return await grabTask({ user_id, task_id });
|
||||
}
|
||||
|
||||
/**
|
||||
* `tasks` list rows by `updated_at` (`grabTasks`), so a status change
|
||||
* that leaves it alone never rises; the move and hand-over helpers set
|
||||
* it themselves.
|
||||
*/
|
||||
fields.push(`updated_at = ?`);
|
||||
values.push(Date.now());
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `UPDATE tasks SET ${fields.join(", ")} WHERE id = ?`,
|
||||
values: [...values, Number(task_id)],
|
||||
|
||||
@@ -195,11 +195,29 @@ export async function grabMessageRunUsage({
|
||||
/**
|
||||
* What a job that is still open has spent so far, from its own calls and
|
||||
* its recorded steps: a reply cannot look at itself through a message,
|
||||
* since that is written when it ends.
|
||||
* since that is written when it ends. Held to the session it is read from,
|
||||
* so one run can read its own job and never another conversation's.
|
||||
*/
|
||||
export async function grabJobRunUsage({ job_id }: { job_id: number | string }) {
|
||||
export async function grabJobRunUsage({
|
||||
job_id,
|
||||
session_id,
|
||||
}: {
|
||||
job_id: number | string;
|
||||
session_id: number | string;
|
||||
}) {
|
||||
const calls = (
|
||||
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "job_id"), values: [Number(job_id) || 0] })).payload || []
|
||||
(
|
||||
await BunSQLite.sql<CallRow>({
|
||||
sql: `SELECT t.id, t.created_at, t.harness, t.provider_name, t.model_slug,
|
||||
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.settings
|
||||
FROM token_usages t
|
||||
JOIN bots_queue q ON q.id = t.job_id
|
||||
WHERE t.job_id = ? AND q.session_id = ?
|
||||
ORDER BY t.created_at ASC, t.id ASC
|
||||
LIMIT 500`,
|
||||
values: [Number(job_id) || 0, Number(session_id) || 0],
|
||||
})
|
||||
).payload || []
|
||||
).map((item) => toCall({ row: item }));
|
||||
|
||||
if (!calls.length) return null;
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import grabWorkspaceComputers from "./grab-workspace-computers";
|
||||
import grabUserWorkspace from "./grab-user-workspace";
|
||||
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -12,12 +13,18 @@ type Params = {
|
||||
/**
|
||||
* Makes one of a workspace's computers its default, where its tasks run.
|
||||
* Returns the workspace's computers, the new default first.
|
||||
*
|
||||
* Where a whole workspace's work runs is a crew decision, like linking the
|
||||
* computer in the first place: a member's bot deciding it needs another one
|
||||
* would move every bot there, for everyone, from one conversation.
|
||||
*/
|
||||
export default async function setWorkspaceComputer({
|
||||
user_id,
|
||||
workspace_id,
|
||||
computer_id,
|
||||
}: Params) {
|
||||
await assertCrewManager({ user_id });
|
||||
|
||||
const workspace = await grabUserWorkspace({ workspace_id, user_id });
|
||||
|
||||
if (!workspace?.id) {
|
||||
|
||||
@@ -72,15 +72,20 @@ describe("fitTranscriptToContext", () => {
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 12 characters of this computer_bash output");
|
||||
});
|
||||
|
||||
test("never trims the newest messages, even over budget", () => {
|
||||
test("cuts the newest results only once every older one is gone", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "tool", tool_call_id: "1", content: big },
|
||||
];
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 1000 });
|
||||
|
||||
expect(result.trimmed).toBe(0);
|
||||
expect(transcript[1]!.content).toBe(big);
|
||||
/**
|
||||
* The newest result used to be left whole however far over budget the
|
||||
* prompt was, so it went out anyway and every candidate refused it.
|
||||
*/
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[1]!.content)).toContain("[Trimmed:");
|
||||
expect(transcript[0]!.content).toBe("go");
|
||||
});
|
||||
|
||||
test("keeps to the working context even when the window is far larger", () => {
|
||||
@@ -93,9 +98,10 @@ describe("fitTranscriptToContext", () => {
|
||||
});
|
||||
|
||||
expect(result.budget).toBe(15000);
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(result.trimmed).toBe(2);
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
expect(String(transcript[4]!.content)).toContain("[Trimmed:");
|
||||
expect(transcript[6]!.content).toBe("recent");
|
||||
});
|
||||
|
||||
test("cuts in one block, down to well under the budget, then leaves it alone", () => {
|
||||
@@ -171,7 +177,29 @@ describe("fitTranscriptToContext", () => {
|
||||
expect(result.trimmed).toBeGreaterThan(0);
|
||||
expect(transcript[0]!.content).toBe(request);
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(result.over_budget).toBe(true);
|
||||
/**
|
||||
* Every result was cut, the newest included: the request is what is
|
||||
* left, and the run pays for it in full.
|
||||
*/
|
||||
expect(String(transcript[4]!.content)).toContain("[Trimmed:");
|
||||
});
|
||||
|
||||
test("a brief that fits once the results are cut is not reported as over budget", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "Look through the fixture and tell me what fails." },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "recent" },
|
||||
];
|
||||
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 131_072, budget_tokens: 12_000 });
|
||||
|
||||
expect(result.over_budget).toBe(false);
|
||||
expect(result.trimmed).toBeGreaterThan(0);
|
||||
expect(transcript[0]!.content).toBe("Look through the fixture and tell me what fails.");
|
||||
});
|
||||
|
||||
test("says a transcript it trimmed down fits", () => {
|
||||
|
||||
@@ -175,6 +175,30 @@ export default function fitTranscriptToContext({
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest results were never cut, and a run still over budget with
|
||||
* nothing older to trim sent the whole prompt anyway: one 60k-character
|
||||
* sweep plus a pasted brief went out every turn, and every candidate
|
||||
* refused it. The newest results are what the run is working from, so
|
||||
* they are cut last, and only once everything older is gone. A user's
|
||||
* own text is never touched.
|
||||
*/
|
||||
for (let index = Math.max(trimmable, 0); index < transcript.length && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
|
||||
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: trimResult({ index, content: message.content, name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, answerNotSentNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -1435,7 +1435,6 @@ describe("runTextLoop closing tools", () => {
|
||||
});
|
||||
|
||||
test("keeps going when the card comes with real work", async () => {
|
||||
asked.length = 0;
|
||||
const { generate } = scripted([
|
||||
{
|
||||
text: "Saved your preference and put the question up.",
|
||||
@@ -1458,6 +1457,72 @@ describe("runTextLoop closing tools", () => {
|
||||
expect(result.text).toBe("Noted. The question is under this message.");
|
||||
expect(result.steps).toBe(2);
|
||||
});
|
||||
|
||||
test("a card the tool refused is not the end of the run", async () => {
|
||||
asked.length = 0;
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Here are my questions:",
|
||||
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":5}` }],
|
||||
},
|
||||
{
|
||||
text: "Which date rule should the articles follow?",
|
||||
tool_calls: [{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Ask me which date rule." }],
|
||||
tools: [askUser, remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
/**
|
||||
* The card was never put up, so the answer promising one never went
|
||||
* out: the run was told and asked again.
|
||||
*/
|
||||
expect(result.text).toBe("Which date rule should the articles follow?");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(asked).toEqual(["Which date rule?"]);
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: closingFailedNote });
|
||||
});
|
||||
|
||||
test("a card with nothing said beside it is told once, then ends where it is", async () => {
|
||||
asked.length = 0;
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "",
|
||||
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
|
||||
},
|
||||
{
|
||||
text: " ",
|
||||
tool_calls: [{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Ask me which date rule." }],
|
||||
tools: [askUser, remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
/**
|
||||
* A card alone answers nothing, and going on would work on the very
|
||||
* thing it just asked about. Told once, then the run ends: an empty
|
||||
* answer fails the job with a reason the user can see, rather than
|
||||
* starting work nobody asked for.
|
||||
*/
|
||||
expect(result.text).toBe("");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(seen.length).toBe(2);
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: closingNoTextNote });
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop answer not sent", () => {
|
||||
|
||||
@@ -2,14 +2,20 @@ import { AppData } from "@/src/data/app-data";
|
||||
import {
|
||||
alreadyRanToolNote,
|
||||
answerNotSentNote,
|
||||
closingFailedNote,
|
||||
closingNoTextNote,
|
||||
commitEarlyNote,
|
||||
contextTrimmedNote,
|
||||
failedToolCallNote,
|
||||
oversizedRequestNote,
|
||||
repairedAnswerNote,
|
||||
repeatedAnswerNote,
|
||||
tokensLowNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import sanitizeAnswerText from "@/src/utils/sanitize-answer-text";
|
||||
import repairAnswerText from "@/src/utils/repair-answer-text";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import HarnessError from "../harness-error";
|
||||
import isClosingTool from "../tools/closing-tool-names";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
@@ -93,9 +99,10 @@ type Params = {
|
||||
* last call), read after each round of tools and before an answer is
|
||||
* returned. They join the transcript, so a message sent while the bot
|
||||
* works can change what it does, and an answer they arrive in time for
|
||||
* is written again with them in mind.
|
||||
* is written again with them in mind. `counted` is false at the wrap up:
|
||||
* those turns are read, not answered (`takeIncoming`).
|
||||
*/
|
||||
incoming?: () => Promise<HarnessMessage[]>;
|
||||
incoming?: (params?: { counted?: boolean }) => 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
|
||||
@@ -352,12 +359,12 @@ export default async function runTextLoop({
|
||||
const tool_uses: HarnessToolUse[] = [];
|
||||
/**
|
||||
* The reads this run already made, by the call they answer
|
||||
* (`repeatToolCallKey`) and the step it was. A read repeated word for
|
||||
* word gets this answer instead of being run again, and anything that
|
||||
* may have written forgets them: a file read once, then edited, is
|
||||
* read again.
|
||||
* (`repeatToolCallKey`), the step it was and the transcript message its
|
||||
* output went into. A read repeated word for word gets this answer
|
||||
* instead of being run again, and anything that may have written forgets
|
||||
* them: a file read once, then edited, is read again.
|
||||
*/
|
||||
const repeated_reads = new Map<string, number>();
|
||||
const repeated_reads = new Map<string, { step: number; message: HarnessMessage }>();
|
||||
/**
|
||||
* The calls that failed, by the call they answer (`toolCallKey`), with
|
||||
* the step the first of them ran on and the error it gave. An identical
|
||||
@@ -409,6 +416,11 @@ export default async function runTextLoop({
|
||||
* that the message never went out (`answerNotSentNote`).
|
||||
*/
|
||||
let told_answer_lost = false;
|
||||
/**
|
||||
* A card put up with nothing said beside it has been told, once, to write
|
||||
* the sentence that goes with it (`closingNoTextNote`).
|
||||
*/
|
||||
let told_closing_text = false;
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
@@ -482,7 +494,20 @@ export default async function runTextLoop({
|
||||
const checkAnswer = async ({ text, index }: { text: string; index: number }) => {
|
||||
if (!review) return { verdict: "passed" as const };
|
||||
|
||||
const note = await review({ text, tool_uses }).catch(() => null);
|
||||
const note = await review({ text, tool_uses }).catch(async (error) => {
|
||||
/**
|
||||
* A reviewer that throws passes the answer, which is the safe
|
||||
* thing to do with the user's reply, but it must not read like a
|
||||
* review that found nothing: a reviewer that is broken every
|
||||
* time leaves every answer unchecked, and nothing said so.
|
||||
*/
|
||||
await logError({
|
||||
title: "Reviewing a reply failed, so its answer went out unchecked",
|
||||
error,
|
||||
}).catch(() => null);
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
if (!note) return { verdict: "passed" as const };
|
||||
|
||||
@@ -524,7 +549,7 @@ export default async function runTextLoop({
|
||||
if (wrap_up && !wrap_up_announced) {
|
||||
wrap_up_announced = true;
|
||||
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index });
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index, counted: false });
|
||||
|
||||
/**
|
||||
* The machine's own account of the work, when the caller has
|
||||
@@ -632,6 +657,15 @@ export default async function runTextLoop({
|
||||
(call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name),
|
||||
);
|
||||
|
||||
/**
|
||||
* What the app would never show as its own word comes out before
|
||||
* anything reads the answer: a setting pill that leads nowhere and a
|
||||
* record line this run's tools don't support are text, and sending
|
||||
* the whole answer back for one costs a rewrite and, on the third,
|
||||
* the answer (`sanitizeAnswerText`).
|
||||
*/
|
||||
if (answer.text) answer.text = sanitizeAnswerText({ text: answer.text });
|
||||
|
||||
/**
|
||||
* A saving turn that reached for anything else is told what it has
|
||||
* left, and gets that one round again (never more, so the run
|
||||
@@ -693,6 +727,32 @@ export default async function runTextLoop({
|
||||
const check = await checkAnswer({ text: answer.text || "", index });
|
||||
|
||||
if (check.verdict === "refused") {
|
||||
/**
|
||||
* A fault the app can take out is taken out instead of the
|
||||
* whole answer: what is left is what the tools support, said
|
||||
* to be part of the answer, so three faults no longer cost a
|
||||
* user an answer that was right.
|
||||
*/
|
||||
const repaired = repairAnswerText({ text: answer.text || "" });
|
||||
|
||||
if (repaired.changed && repaired.text) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "repaired",
|
||||
text: repairedAnswerNote,
|
||||
});
|
||||
|
||||
return {
|
||||
text: `${repaired.text}\n\n${repairedAnswerNote}`,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: check.note,
|
||||
@@ -708,10 +768,14 @@ export default async function runTextLoop({
|
||||
}
|
||||
|
||||
if (!tool_calls.length) {
|
||||
/**
|
||||
* Whitespace alone is no answer: it would land as an empty bubble
|
||||
* (`run-bot-reply` treats it as none and fails with a reason).
|
||||
*/
|
||||
const said = (answer.text || "").trim();
|
||||
|
||||
return {
|
||||
text:
|
||||
answer.text ||
|
||||
(wrap_up ? `I ran out of steps before I could finish.` : ""),
|
||||
text: said || (wrap_up ? `I ran out of steps before I could finish.` : ""),
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
@@ -726,7 +790,15 @@ export default async function runTextLoop({
|
||||
|
||||
for (const call of tool_calls) {
|
||||
const repeat_key = repeatToolCallKey({ call });
|
||||
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
const remembered = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
/**
|
||||
* A read answered from a step is answered only while its output
|
||||
* is still in the prompt: trimming cut it down to its two ends
|
||||
* (`fitTranscriptToContext`), which no longer holds what the run
|
||||
* was reading. Pointing at it then made the model retry the same
|
||||
* call until the token budget ran out.
|
||||
*/
|
||||
const already_read = remembered && transcript.includes(remembered.message) ? remembered.step : undefined;
|
||||
const call_key = toolCallKey({ call });
|
||||
const failed_before = call_key ? failed_calls.get(call_key) : undefined;
|
||||
const give_up =
|
||||
@@ -781,7 +853,7 @@ export default async function runTextLoop({
|
||||
repeated_reads.clear();
|
||||
} else if (already_read === undefined) {
|
||||
if (content.startsWith("Error:")) repeated_reads.delete(repeat_key);
|
||||
else repeated_reads.set(repeat_key, index);
|
||||
else if (remembered) repeated_reads.delete(repeat_key);
|
||||
}
|
||||
|
||||
if (give_up) {
|
||||
@@ -800,18 +872,63 @@ export default async function runTextLoop({
|
||||
failed_calls.clear();
|
||||
}
|
||||
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
const tool_message: HarnessMessage = { role: "tool", tool_call_id: call.id, content };
|
||||
|
||||
transcript.push(tool_message);
|
||||
|
||||
if (repeat_key && already_read === undefined && !content.startsWith("Error:")) {
|
||||
repeated_reads.set(repeat_key, { step: index, message: tool_message });
|
||||
}
|
||||
|
||||
if (images.length) shown.push({ tool_name: call.name, images });
|
||||
}
|
||||
|
||||
/**
|
||||
* An answer that ends on a card is the whole reply: the question
|
||||
* An answer that called a card is the whole reply: the question
|
||||
* waits for the user, and what comes next was just offered. Going on
|
||||
* would send the next turn's short line in its place, since the reply
|
||||
* is only the run's last message (`ClosingToolNames`).
|
||||
* is only the run's last message (`ClosingToolNames`). A turn that
|
||||
* called nothing at all is still a whole answer (the check below).
|
||||
*/
|
||||
if (answer.text && tool_calls.every((call) => isClosingTool({ name: call.name }))) {
|
||||
const called_card = tool_calls.some((call) => isClosingTool({ name: call.name }));
|
||||
const closing = tool_calls.every((call) => isClosingTool({ name: call.name }));
|
||||
/**
|
||||
* The card has to be there: a closing call whose arguments the tool
|
||||
* refused put nothing up, and a message written as if it had is a
|
||||
* reply that points at a card no one can see.
|
||||
*/
|
||||
const closing_worked = closing && tool_uses.slice(-tool_calls.length).every((use) => use.ok);
|
||||
|
||||
if (called_card && !closing_worked) {
|
||||
pushUserTurn({ transcript, content: closingFailedNote });
|
||||
await traced({ kind: "event", index, name: "closing_failed", text: closingFailedNote });
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* A card with nothing beside it answers nothing, and the run would
|
||||
* go on to work on the very thing it just asked about. Told once,
|
||||
* and the run ends on the sentence it writes (`closingNoTextNote`).
|
||||
*/
|
||||
if (closing_worked && called_card && !(answer.text || "").trim()) {
|
||||
if (!told_closing_text) {
|
||||
told_closing_text = true;
|
||||
pushUserTurn({ transcript, content: closingNoTextNote });
|
||||
await traced({ kind: "event", index, name: "closing_no_text", text: closingNoTextNote });
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
if (closing_worked && answer.text) {
|
||||
/**
|
||||
* Checked before it goes out, as any reply is: a note comes
|
||||
* back and the answer is written again (the card stays on the
|
||||
@@ -820,6 +937,26 @@ export default async function runTextLoop({
|
||||
const check = await checkAnswer({ text: answer.text, index });
|
||||
|
||||
if (check.verdict === "refused") {
|
||||
const repaired = repairAnswerText({ text: answer.text });
|
||||
|
||||
if (repaired.changed && repaired.text) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "repaired",
|
||||
text: repairedAnswerNote,
|
||||
});
|
||||
|
||||
return {
|
||||
text: `${repaired.text}\n\n${repairedAnswerNote}`,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: check.note,
|
||||
@@ -933,10 +1070,13 @@ export default async function runTextLoop({
|
||||
|
||||
/**
|
||||
* Adds what the user wrote since the last look, after `note`. True when
|
||||
* there was anything.
|
||||
* there was anything. `counted` says whether the run will answer what it
|
||||
* read: the wrap up writes the answer it already had to, so a message
|
||||
* taken in there is left for its own reply (`run-bot-reply`), not marked
|
||||
* answered by an answer written before it arrived.
|
||||
*/
|
||||
async function takeIncoming({ note, index }: { note: string; index: number }) {
|
||||
const turns = (await incoming?.()) || [];
|
||||
async function takeIncoming({ note, index, counted = true }: { note: string; index: number; counted?: boolean }) {
|
||||
const turns = (await incoming?.({ counted })) || [];
|
||||
const user_turns = turns.filter((turn) => turn.role == "user");
|
||||
|
||||
if (!user_turns.length) return false;
|
||||
|
||||
@@ -13,6 +13,12 @@ type Params = {
|
||||
* The user's worker bots.
|
||||
*/
|
||||
workers: BUN_SQLITE_COBBLE_BOTS[];
|
||||
/**
|
||||
* Whether the run is one the user is following in a conversation. A run
|
||||
* nobody watches acts on a brief alone, and a brief can be written by
|
||||
* any bot.
|
||||
*/
|
||||
attended?: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -26,7 +32,7 @@ type Args = {
|
||||
* Irreversible, so it only runs when the user asked for that exact bot to
|
||||
* go.
|
||||
*/
|
||||
export default function deleteBotTool({ user_id, workers }: Params): HarnessTool<Args> {
|
||||
export default function deleteBotTool({ user_id, workers, attended = false }: Params): HarnessTool<Args> {
|
||||
const crew = workers.map((bot) => `${bot.id}: ${bot.name}`).join("; ");
|
||||
|
||||
return {
|
||||
@@ -36,6 +42,17 @@ export default function deleteBotTool({ user_id, workers }: Params): HarnessTool
|
||||
bot_id: z.number().int(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
/**
|
||||
* Nothing here can be undone, so it happens where the user can
|
||||
* see it and say stop: a routine, a hook call or a task another
|
||||
* bot handed over only has a brief to go on.
|
||||
*/
|
||||
if (!attended) {
|
||||
throw new Error(
|
||||
`Deleting a bot can't be undone, so it is done only in a conversation with the user, where they can confirm it. Nothing was deleted: say that it has to be asked for in the chat with them.`,
|
||||
);
|
||||
}
|
||||
|
||||
const fresh = await grabCrewWorkers();
|
||||
const worker = fresh.find((bot) => bot.id == args.bot_id);
|
||||
|
||||
|
||||
@@ -13,6 +13,12 @@ type Params = {
|
||||
* The user's live workspaces.
|
||||
*/
|
||||
workspaces: BUN_SQLITE_COBBLE_WORKSPACES[];
|
||||
/**
|
||||
* Whether the run is one the user is following in a conversation. A run
|
||||
* nobody watches acts on a brief alone, and a brief can be written by
|
||||
* any bot.
|
||||
*/
|
||||
attended?: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -28,6 +34,7 @@ type Args = {
|
||||
export default function deleteWorkspaceTool({
|
||||
user_id,
|
||||
workspaces,
|
||||
attended = false,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const list = workspaces.map((w) => `${w.id}: ${w.name}`).join("; ");
|
||||
|
||||
@@ -38,6 +45,17 @@ export default function deleteWorkspaceTool({
|
||||
workspace_id: z.number().int(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
/**
|
||||
* Nothing here can be undone, so it happens where the user can
|
||||
* see it and say stop: a routine, a hook call or a task another
|
||||
* bot handed over only has a brief to go on.
|
||||
*/
|
||||
if (!attended) {
|
||||
throw new Error(
|
||||
`Deleting a workspace can't be undone, so it is done only in a conversation with the user, where they can confirm it. Nothing was deleted: say that it has to be asked for in the chat with them.`,
|
||||
);
|
||||
}
|
||||
|
||||
const live = (await grabUserWorkspaces({ user_id })).filter((w) => !w.archived);
|
||||
const workspace = live.find((w) => w.id == args.workspace_id);
|
||||
|
||||
|
||||
@@ -258,7 +258,7 @@ export default async function grabBotChatTools({
|
||||
|
||||
tools.push(findBotTool(), findWorkspaceTool({ user_id }), listWorkspaceBotsTool({ user_id }));
|
||||
|
||||
tools.push(deleteWorkspaceTool({ user_id, workspaces }));
|
||||
tools.push(deleteWorkspaceTool({ user_id, workspaces, attended }));
|
||||
|
||||
if (!workers.length) return tools;
|
||||
|
||||
@@ -284,7 +284,7 @@ export default async function grabBotChatTools({
|
||||
}),
|
||||
);
|
||||
|
||||
tools.push(updateBotTool({ user_id, workers }), deleteBotTool({ user_id, workers }));
|
||||
tools.push(updateBotTool({ user_id, workers }), deleteBotTool({ user_id, workers, attended }));
|
||||
|
||||
if (computers.length) {
|
||||
const access = Object.fromEntries(
|
||||
|
||||
@@ -15,6 +15,7 @@ import askBotTool from "./ask-bot-tool";
|
||||
import listAsksTool from "./list-asks-tool";
|
||||
import readMessageUsageTool from "./settings/read-message-usage-tool";
|
||||
import readSettingsTool from "./settings/read-settings-tool";
|
||||
import grabCrewRole from "@/src/functions/backend/db/access/grab-crew-role";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
@@ -88,16 +89,33 @@ export default async function grabBotTools({
|
||||
onPropose,
|
||||
onTask,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
const can_manage_crew = (await grabCrewRole({ user_id })) != "member";
|
||||
|
||||
return [
|
||||
setPictureTool({ user_id, bot_id, scopes, is_coordinator }),
|
||||
readSettingsTool(),
|
||||
readMessageUsageTool({ session_id }),
|
||||
updateMemoryTool({ user_id, bot_id, workspace_id }),
|
||||
updateInstructionsTool({ user_id, bot_id, workspace_id }),
|
||||
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
|
||||
updateMemoryTool({ user_id, bot_id, workspace_id, can_manage_crew }),
|
||||
...(can_manage_crew || workspace_id
|
||||
? [updateInstructionsTool({ user_id, bot_id, workspace_id, can_manage_crew })]
|
||||
: []),
|
||||
/**
|
||||
* A hook call runs on someone else's words: its brief and payload are
|
||||
* fenced as data, so a payload that talks the model round must not be
|
||||
* able to leave a lasting mark on what the bot remembers, how it works
|
||||
* or when it runs. It reads, works and reports; those changes are made
|
||||
* in the conversation it reports into. A routine is the user's own
|
||||
* schedule, and a task run answers the user's own request, so both
|
||||
* keep them.
|
||||
*/
|
||||
...(hooked
|
||||
? []
|
||||
: [
|
||||
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
|
||||
updateScheduleTool({ user_id, bot_id }),
|
||||
deleteScheduleTool({ user_id, bot_id }),
|
||||
]),
|
||||
listSchedulesTool({ user_id, bot_id }),
|
||||
updateScheduleTool({ user_id, bot_id }),
|
||||
deleteScheduleTool({ user_id, bot_id }),
|
||||
...grabBotHookTools({ user_id, bot_id, session_id, workspace_id, computers, hooked, onPropose }),
|
||||
...(session_id ? [reactToMessageTool({ bot_id, user_id, session_id })] : []),
|
||||
/**
|
||||
|
||||
@@ -66,7 +66,7 @@ export default function handOverTaskTool({ user_id, bot, session_id, powers, wor
|
||||
|
||||
return {
|
||||
name: "hand_over_task",
|
||||
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_crew; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
|
||||
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_bot; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
|
||||
schema: z.object({
|
||||
task_id: z.number().int().describe("An open task on your own list (list_tasks)"),
|
||||
bot_id: z.number().int(),
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod";
|
||||
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
|
||||
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
plan_id: number;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The user dropped the plan (they said so, or the work it was for is gone),
|
||||
* so the bot ends it rather than leaving a card that will never move. Its
|
||||
* steps stop there: nothing more is queued for it.
|
||||
*/
|
||||
export default function cancelPlanTool({ user_id, bot_id, session_id }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "cancel_plan",
|
||||
description: `End a plan in this conversation, once the user has said the work it was for is off or they want it dropped. Never to make a plan that is going badly look finished: a plan you can't carry on with is theirs to end too, so ask them. Say in a line that it's cancelled, and why.`,
|
||||
schema: z.object({
|
||||
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
|
||||
reason: z.string().trim().min(1).max(300).describe(`Why it's off, in one line`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const row = await grabBotPlan({ plan_id: args.plan_id });
|
||||
|
||||
if (Number(row.session_id) != Number(session_id)) {
|
||||
throw new AppError(`Plan #${args.plan_id} belongs to another conversation: cancel that conversation's plan.`);
|
||||
}
|
||||
|
||||
await setBotPlanStatus({ plan_id: args.plan_id, user_id, status: "cancelled" });
|
||||
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
|
||||
|
||||
return `Plan #${args.plan_id} is cancelled (${args.reason}) and its card says so. Nothing more runs for it. Say in a line that it's off and what stands done, then answer normally.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import completeBotPlanStep from "@/src/functions/backend/db/bot-plans/complete-bot-plan-step";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The step is finished inside a run that works the whole plan itself (a
|
||||
* routine), so this isn't the reply that ends it: the run carries on
|
||||
* into the next step, and one run can finish more than one.
|
||||
*/
|
||||
in_run?: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
plan_id: number;
|
||||
summary: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The plan's current step is finished: the card checks it off with what it
|
||||
* produced, and the app wakes the bot for the next one after this reply.
|
||||
* A step is only ever finished by a run that did the work, one at a time.
|
||||
*/
|
||||
export default function completePlanStepTool({ bot_id, session_id, in_run }: Params): HarnessTool<Args> {
|
||||
let completed = false;
|
||||
|
||||
return {
|
||||
name: "complete_plan_step",
|
||||
description: in_run
|
||||
? `Finish one step of the plan, once you have actually done it, before you start the next. Give one or two lines on what it produced (the number, the path, the link). You work this plan yourself here, so call it after each step and keep going.`
|
||||
: `Finish the plan's current step, once you have actually done it. Give one or two lines on what it produced (the number, the path, the link). Call it before you write your report: the report is this reply's last message. One step per reply. Never call it for a step you didn't do, and never for one after the current step.`,
|
||||
schema: z.object({
|
||||
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
|
||||
summary: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, `Say what the step produced`)
|
||||
.max(
|
||||
AppData.BotPlanStepNoteMaxChars,
|
||||
`Keep it under ${AppData.BotPlanStepNoteMaxChars} characters`,
|
||||
)
|
||||
.describe(`What the step produced, in a line or two`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (completed && !in_run) {
|
||||
throw new Error(`You already finished a step of this plan in this reply. One step per reply.`);
|
||||
}
|
||||
|
||||
const done = await completeBotPlanStep({
|
||||
plan_id: args.plan_id,
|
||||
session_id,
|
||||
summary: args.summary,
|
||||
});
|
||||
|
||||
completed = true;
|
||||
/**
|
||||
* The card is already in the thread above, from the message that
|
||||
* wrote or changed the plan: this reply needs no copy of it, and
|
||||
* the push keeps the one that's there current.
|
||||
*/
|
||||
await pushBotPlan({ plan_id: done.plan_id, session_id, bot_id });
|
||||
|
||||
if (done.done) {
|
||||
return `Step ${done.index + 1} is done and it was the last one: the plan is finished on its card. Write your report now, two or three sentences on what the plan produced. If this plan will come back (the same work, the next project or the next month), save its steps now with update_memory as a short checklist, and say in a line that you kept them.`;
|
||||
}
|
||||
|
||||
const next = done.steps[done.next_step ?? 0];
|
||||
|
||||
if (in_run) {
|
||||
return `Step ${done.index + 1} is done: the card shows it. Carry on with step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}. Save your report for the end, when every step is done.`;
|
||||
}
|
||||
|
||||
return `Step ${done.index + 1} is done: the card shows it. The next step starts on its own after this reply (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}), so don't start it now. Write your report: two or three sentences on what this step produced.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { z } from "zod";
|
||||
import createBotPlan from "@/src/functions/backend/db/bot-plans/create-bot-plan";
|
||||
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
|
||||
import botPlanRef from "@/src/utils/bot-plan-ref";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* A scheduled run, which nobody watches: the plan is approved at once,
|
||||
* since there is no card for someone to approve it on.
|
||||
*/
|
||||
approve?: boolean;
|
||||
/**
|
||||
* Called with the plan's ref, so the message carries its card. `waiting`
|
||||
* says nobody approved it yet: the user is needed for it to go on.
|
||||
*/
|
||||
onPlan: (params: { ref: string; waiting?: boolean }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
title: string;
|
||||
goal?: string;
|
||||
steps: z.infer<typeof BotPlanStepTextsSchema>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot broke work into a plan. In a chat it waits on its card for the
|
||||
* user to approve (or change) it, and the app then wakes the bot one step at
|
||||
* a time. In a scheduled run nobody is there to approve anything, so the
|
||||
* plan starts itself and the run works through it.
|
||||
*/
|
||||
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "create_plan",
|
||||
description: approve
|
||||
? `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. Nobody is watching this run, so it's approved at once and you work it here: call complete_plan_step after each step.`
|
||||
: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
|
||||
schema: z.object({
|
||||
title: BotPlanTitleSchema.describe(`A short name for the work, e.g. "Audit the pricing pages"`),
|
||||
goal: BotPlanGoalSchema.describe(`What the plan is for and what "done" means, in one sentence`),
|
||||
steps: BotPlanStepTextsSchema.describe(`The steps in the order they're worked, each one line`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const plan_id = await createBotPlan({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
title: args.title,
|
||||
goal: args.goal,
|
||||
steps: args.steps,
|
||||
});
|
||||
|
||||
if (approve) {
|
||||
await setBotPlanStatus({ plan_id, user_id, status: "active" });
|
||||
}
|
||||
|
||||
onPlan({ ref: botPlanRef({ plan_id }), waiting: !approve });
|
||||
await pushBotPlan({ plan_id, session_id, bot_id });
|
||||
|
||||
const count = args.steps.length;
|
||||
|
||||
if (approve) {
|
||||
return `Plan #${plan_id} is written (${count} step${count == 1 ? "" : "s"}), and it's approved already because this run isn't watched. Work its steps in this run, calling complete_plan_step after each with what it produced.`;
|
||||
}
|
||||
|
||||
return `Plan #${plan_id} is on its card in the conversation (${count} step${count == 1 ? "" : "s"}) and nothing of it runs until the user approves it. Say in one sentence that you wrote it and that they can change it before it starts; don't repeat the steps and don't work any of them now. When they approve it, you'll be woken for the first step.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import grabBotPlanTools from "./grab-bot-plan-tools";
|
||||
|
||||
/**
|
||||
* A run working a plan's step may only work it: writing another plan, or
|
||||
* cancelling the one it was woken for, is the user's call on the card. A
|
||||
* scheduled run has no card to approve anything on, so its plan starts
|
||||
* itself and nothing is left for the bot to cancel.
|
||||
*/
|
||||
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
|
||||
|
||||
const build = (overrides: Parameters<typeof grabBotPlanTools>[0] | {} = {}) =>
|
||||
grabBotPlanTools({
|
||||
user_id: 1,
|
||||
bot_id: 2,
|
||||
session_id: 3,
|
||||
workspace_id: null,
|
||||
onPlan: () => {},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("grabBotPlanTools", () => {
|
||||
test("a chat reply can write a plan, change it, end it and finish its steps", () => {
|
||||
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan", "complete_plan_step"]);
|
||||
});
|
||||
|
||||
test("a run working a step can only change the plan and finish its step", () => {
|
||||
expect(names(build({ on_step: true }))).toEqual(["update_plan", "complete_plan_step"]);
|
||||
});
|
||||
|
||||
test("a scheduled run writes a plan that's already approved, and can't cancel it", () => {
|
||||
expect(names(build({ approve: true }))).toEqual(["create_plan", "update_plan", "complete_plan_step"]);
|
||||
});
|
||||
|
||||
test("a plan the app writes shows its card on the message", () => {
|
||||
const refs: string[] = [];
|
||||
|
||||
build({ onPlan: ({ ref }) => refs.push(ref) });
|
||||
|
||||
expect(refs).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { HarnessTool } from "../../../types";
|
||||
import cancelPlanTool from "./cancel-plan-tool";
|
||||
import completePlanStepTool from "./complete-plan-step-tool";
|
||||
import createPlanTool from "./create-plan-tool";
|
||||
import updatePlanTool from "./update-plan-tool";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* The run is a plan's own step: it has a plan to finish, and no reason
|
||||
* to write one or end one.
|
||||
*/
|
||||
on_step?: boolean;
|
||||
/**
|
||||
* A scheduled run, which nobody watches: a plan it writes is approved
|
||||
* at once and worked through in the run (`ScheduledPlanNote`).
|
||||
*/
|
||||
approve?: boolean;
|
||||
/**
|
||||
* Called with each plan's ref, so the message carries its card.
|
||||
*/
|
||||
onPlan: (params: { ref: string; waiting?: boolean }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools a bot plans with: `create_plan` when work is several steps,
|
||||
* `update_plan` when what it found makes the rest wrong, and
|
||||
* `complete_plan_step` to finish the step it worked. A chat reply's plan
|
||||
* waits on its card for the user; a scheduled run's is approved at once,
|
||||
* since nobody is there to approve it.
|
||||
*
|
||||
* A run that is itself working a plan gets neither `create_plan` (the
|
||||
* conversation already has one open) nor `cancel_plan` (whether the plan
|
||||
* stands is the user's call), so the only thing it can do is work it.
|
||||
*/
|
||||
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, approve, onPlan }: Params) {
|
||||
const tools: HarnessTool[] = [];
|
||||
|
||||
if (!on_step) {
|
||||
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }));
|
||||
|
||||
if (!approve) {
|
||||
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
|
||||
}
|
||||
}
|
||||
|
||||
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
|
||||
tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
|
||||
|
||||
return tools;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from "zod";
|
||||
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
|
||||
import saveBotPlanSteps from "@/src/functions/backend/db/bot-plans/save-bot-plan-steps";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import botPlanRef from "@/src/utils/bot-plan-ref";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
onPlan: (params: { ref: string }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
plan_id: number;
|
||||
steps: z.infer<typeof BotPlanStepTextsSchema>;
|
||||
title?: string;
|
||||
goal?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot changed the plan it is working, because the work showed the plan
|
||||
* was wrong. The same rules the user's edits follow hold: a step already
|
||||
* done is a record of work that happened, so it stays at the top with its
|
||||
* note, and everything after it is the bot's to rewrite.
|
||||
*/
|
||||
export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "update_plan",
|
||||
description: `Change the plan you're working when what you found makes the rest of it wrong. Send the whole list of steps, in order, the steps already done first and unchanged (their notes are what was worked). Say in your reply what changed and why, in a line. Don't use it to make the plan look finished.`,
|
||||
schema: z.object({
|
||||
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
|
||||
steps: BotPlanStepTextsSchema.describe(`The plan's steps as they should now read, done ones first and unchanged`),
|
||||
title: BotPlanTitleSchema.optional().describe(`A new title, only when the work turned out to be something else`),
|
||||
goal: BotPlanGoalSchema.describe(`A new goal, only when what "done" means has changed`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const row = await grabBotPlan({ plan_id: args.plan_id });
|
||||
|
||||
if (Number(row.session_id) != Number(session_id)) {
|
||||
throw new AppError(`Plan #${args.plan_id} belongs to another conversation: change that conversation's plan.`);
|
||||
}
|
||||
|
||||
await saveBotPlanSteps({
|
||||
plan_id: args.plan_id,
|
||||
user_id,
|
||||
title: args.title?.trim() || row.title || "",
|
||||
goal: args.goal?.trim() || row.goal || "",
|
||||
steps: args.steps,
|
||||
});
|
||||
|
||||
onPlan({ ref: botPlanRef({ plan_id: args.plan_id }) });
|
||||
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
|
||||
|
||||
return `Plan #${args.plan_id} is updated and its card shows the new steps. Say in a line what changed and why, then carry on with the step you're on.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -80,7 +80,12 @@ Long runs cost more than the work suggests because every turn resends the prompt
|
||||
|
||||
if (!job_id) return describeMessageUsageList({ messages: await grabSessionMessageUsage({ session_id: run_session_id }) });
|
||||
|
||||
const usage = await grabJobRunUsage({ job_id });
|
||||
/**
|
||||
* Read within this conversation's session: a job id is not a
|
||||
* handle to someone else's run, and the cost of a run says which
|
||||
* provider, model and limits it used.
|
||||
*/
|
||||
const usage = await grabJobRunUsage({ job_id, session_id: run_session_id });
|
||||
|
||||
if (!usage) {
|
||||
return `No model calls recorded for run #${job_id} yet.`;
|
||||
|
||||
@@ -13,6 +13,13 @@ type Params = {
|
||||
* for the workspace unless it picks `core`.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Whether the run's user manages the crew. A member's run writes the
|
||||
* bot's instructions for the workspace it is in and never its core
|
||||
* ones: those start every user's prompt, so one member's conversation
|
||||
* would rewrite them for everyone else.
|
||||
*/
|
||||
can_manage_crew?: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -20,28 +27,43 @@ type Args = {
|
||||
scope?: "workspace" | "core";
|
||||
};
|
||||
|
||||
const WorkspaceNote = `your instructions for this workspace, under "# Your instructions in ...": yours there, not the workspace's description or context. Keep everything that still applies.`;
|
||||
|
||||
/**
|
||||
* Lets a bot rewrite its own instructions as it adapts to the user: its
|
||||
* core instructions, or in a workspace (by default) its instructions for
|
||||
* that workspace.
|
||||
* that workspace. Calls itself only with the crew-manager case in reach
|
||||
* (`grabBotTools`), since core instructions are what every user's run of
|
||||
* the bot starts from.
|
||||
*/
|
||||
export default function updateInstructionsTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
can_manage_crew = false,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const instructions = z.string().trim().max(AppData.PromptMaxLength);
|
||||
const may_write_core = Boolean(can_manage_crew);
|
||||
|
||||
return {
|
||||
name: "update_instructions",
|
||||
description: workspace_id
|
||||
? `Replace your instructions with this full text (markdown). scope "workspace" (the default) is your instructions for this workspace, under "# Your instructions in ...": yours there, not the workspace's description or context; "core" is your core instructions, the start of your prompt in every workspace and your own chat. Both are shared: the workspace's with everyone working in it, your core ones with every user you work for. Change them only for how you should work for all of them, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`
|
||||
: `Replace your core instructions with this full text (markdown): the start of your prompt, before any workspace or memory, shared with every user you work for. Change them only for how you should work for every user you work for, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`,
|
||||
schema: workspace_id
|
||||
? z.object({ instructions, scope: z.enum(["workspace", "core"]).default("workspace") })
|
||||
: z.object({ instructions: instructions.min(1) }),
|
||||
description:
|
||||
!workspace_id
|
||||
? `Replace your core instructions with this full text (markdown): the start of your prompt, before any workspace or memory, shared with every user you work for. Change them only for how you should work for every user you work for, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`
|
||||
: may_write_core
|
||||
? `Replace your instructions with this full text (markdown). scope "workspace" (the default) is ${WorkspaceNote} "core" is your core instructions, the start of your prompt in every workspace and your own chat. Both are shared: the workspace's with everyone working in it, your core ones with every user you work for. Change them only for how you should work for all of them, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`
|
||||
: `Replace your instructions for this workspace with this full text (markdown). ${WorkspaceNote} They are shared with everyone working here, so change them for how you should work here, never for what one user prefers: that goes in your memory of them (update_memory, scope "user").`,
|
||||
schema:
|
||||
workspace_id && may_write_core
|
||||
? z.object({
|
||||
instructions: instructions.min(1),
|
||||
scope: z.enum(["workspace", "core"]).default("workspace"),
|
||||
})
|
||||
: z.object({ instructions: instructions.min(1) }),
|
||||
run: async ({ args }) => {
|
||||
if (workspace_id && args.scope != "core") {
|
||||
const scope = workspace_id && may_write_core ? args.scope : "workspace";
|
||||
|
||||
if (workspace_id && scope != "core") {
|
||||
await updateWorkspaceBot({
|
||||
user_id,
|
||||
workspace_id,
|
||||
@@ -57,6 +79,10 @@ export default function updateInstructionsTool({
|
||||
return `Instructions for this workspace saved and checked. They apply from your next run here. They are yours in this workspace, not its context: the workspace's own description and context did not change.`;
|
||||
}
|
||||
|
||||
if (!may_write_core) {
|
||||
return `Your core instructions are shared with every user you work for, so only an admin can change them. Nothing was saved: your instructions for this workspace are the ones you can write here (update_memory, scope "workspace", keeps what you learn about the work itself).`;
|
||||
}
|
||||
|
||||
await updateBotSystemPrompt({
|
||||
user_id,
|
||||
bot_id,
|
||||
@@ -66,4 +92,4 @@ export default function updateInstructionsTool({
|
||||
return `Core instructions saved and checked. They apply from your next run, everywhere.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,12 @@ type Params = {
|
||||
* the workspace unless it picks another scope.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Whether the run's user manages the crew: core memory is shared with
|
||||
* every user the bot works for, so a member's run writes only what is
|
||||
* theirs (`user`) or the workspace's.
|
||||
*/
|
||||
can_manage_crew?: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -41,8 +47,10 @@ export default function updateMemoryTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
can_manage_crew = false,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const memory = z.string().max(AppData.PromptMaxLength);
|
||||
const may_write_core = Boolean(can_manage_crew);
|
||||
|
||||
return {
|
||||
name: "update_memory",
|
||||
@@ -54,6 +62,14 @@ export default function updateMemoryTool({
|
||||
: z.object({ memory, scope: z.enum(["user", "core"]).default("user") }),
|
||||
run: async ({ args }) => {
|
||||
if (args.scope == "core") {
|
||||
/**
|
||||
* Core memory starts every user's run of this bot: one
|
||||
* member's conversation must not rewrite it for the rest.
|
||||
*/
|
||||
if (!may_write_core) {
|
||||
return `Your core memory is shared with every user you work for, so only an admin can change it. Nothing was saved: what holds for this user goes in your memory of them (scope "user"${workspace_id ? `, or "workspace" for what holds for the work here` : ""}).`;
|
||||
}
|
||||
|
||||
await updateBotMemory({ user_id, bot_id, memory: args.memory });
|
||||
await checkSavedText({ kind: "core_memory", bot_id, expected: args.memory });
|
||||
return `Core memory saved and checked.`;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { WrapUpHandOffToolNames, WrapUpSaveToolNames } from "@/src/harness/text/run-text-loop";
|
||||
import { WritingToolNames } from "./writing-tool-names";
|
||||
import { WorkStartingTools } from "@/src/utils/reply-claim-problems";
|
||||
|
||||
/**
|
||||
* Tool names written straight into a list go stale when a tool is renamed:
|
||||
* `ask_crew` became `ask_bot` and three lists kept the old name, one of
|
||||
* them (`WorkStartingTools`) enough that a reply which really had asked the
|
||||
* crew was faulted for claiming work it did. The lists are checked against
|
||||
* the tools the harness declares, so a rename can't leave one behind.
|
||||
*/
|
||||
async function declaredToolNames() {
|
||||
const names = new Set<string>();
|
||||
|
||||
for (const file of new Bun.Glob("**/*.ts").scanSync({ cwd: import.meta.dir, absolute: true })) {
|
||||
if (file.endsWith(".test.ts")) continue;
|
||||
|
||||
for (const matched of (await Bun.file(file).text()).matchAll(/name:\s*"([a-z][a-z0-9_]{2,})"/g)) {
|
||||
names.add(matched[1]!);
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
const Lists: Record<string, readonly string[]> = {
|
||||
WorkStartingTools,
|
||||
WritingToolNames,
|
||||
WrapUpSaveToolNames,
|
||||
WrapUpHandOffToolNames,
|
||||
};
|
||||
|
||||
describe("harness tool name lists", () => {
|
||||
test("every name in one is a tool the harness declares", async () => {
|
||||
const declared = await declaredToolNames();
|
||||
|
||||
const entries: [string, readonly string[]][] = Object.entries(Lists);
|
||||
|
||||
const stale = entries
|
||||
.map(([list, names]) => [list, names.filter((name) => !declared.has(name))] as const)
|
||||
.filter(([, names]) => names.length > 0);
|
||||
|
||||
expect(stale).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -42,7 +42,7 @@ export const WritingToolNames: readonly string[] = [
|
||||
"answer_install_request",
|
||||
"start_task",
|
||||
"delegate_task",
|
||||
"ask_crew",
|
||||
"ask_bot",
|
||||
"create_bot",
|
||||
"update_bot",
|
||||
"delete_bot",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
plan_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One plan a bot wrote (`api/admin/bot-plans/get-plan`), for its card.
|
||||
*/
|
||||
export default async function fetchBotPlan({ plan_id }: Params) {
|
||||
return await fetchApi<{}, APIResponseObject<BotPlanView>>(
|
||||
`/api/admin/bot-plans/get-plan?plan_id=${encodeURIComponent(String(plan_id))}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
plan_id: number;
|
||||
title: string;
|
||||
goal?: string;
|
||||
steps: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The user changed a plan's steps on its card, before approving it or while
|
||||
* it runs. Returns the plan as it now stands.
|
||||
*/
|
||||
export default async function saveBotPlan({ plan_id, title, goal, steps }: Params) {
|
||||
return await fetchApi<Omit<Params, "plan_id"> & { plan_id: number }, APIResponseObject<BotPlanView>>(
|
||||
`/api/admin/bot-plans/save-plan`,
|
||||
{ method: "POST", body: { plan_id, title, goal, steps } },
|
||||
);
|
||||
}
|
||||
@@ -9,12 +9,13 @@ export default async function sendBotMessage({
|
||||
text,
|
||||
media_ids,
|
||||
reply_to_message_id,
|
||||
client_id,
|
||||
}: SendBotMessageRequest) {
|
||||
return await fetchApi<
|
||||
SendBotMessageRequest,
|
||||
APIResponseObject<BotMessageWithAttachments>
|
||||
>(`/api/admin/bots/send-message`, {
|
||||
method: "POST",
|
||||
body: { bot_id, workspace_id, text, media_ids, reply_to_message_id },
|
||||
body: { bot_id, workspace_id, text, media_ids, reply_to_message_id, client_id },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
plan_id: number;
|
||||
/**
|
||||
* Approve it, pick it back up, pause it, or end it.
|
||||
*/
|
||||
status: Extract<BotPlanState, "active" | "paused" | "cancelled">;
|
||||
};
|
||||
|
||||
/**
|
||||
* Moves a plan from its card. Approving it (or picking it back up) wakes
|
||||
* the bot for the step it stands on, so the plan carries on by itself.
|
||||
*/
|
||||
export default async function setBotPlanState({ plan_id, status }: Params) {
|
||||
return await fetchApi<Params, APIResponseObject<BotPlanView>>(`/api/admin/bot-plans/set-plan-status`, {
|
||||
method: "POST",
|
||||
body: { plan_id, status },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { BotPlanChangedData, BotPlanView } from "@/src/types";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import fetchBotPlan from "../(functions)/fetch-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan as its card shows it (`[plan:ID]`). Read when the card renders,
|
||||
* then kept current from the app's pushes (`server:bot-plan`, sent while a
|
||||
* run works a step and when the user moves the plan), since the same card
|
||||
* sits in several messages and its steps change under them. A failed read
|
||||
* gives up rather than blocking the card forever; a push retries it.
|
||||
*
|
||||
* Read here rather than through `loadRefView`, whose cache never expires:
|
||||
* a plan is alive, and a card left showing yesterday's step is worse than
|
||||
* one that asks again.
|
||||
*/
|
||||
export default function useBotPlan({ plan_id }: Params) {
|
||||
const [view, setViewState] = useState<BotPlanView | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string>();
|
||||
const mounted = useRef(true);
|
||||
|
||||
const read = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchBotPlan({ plan_id });
|
||||
|
||||
if (!mounted.current) return;
|
||||
|
||||
if (res.success && res.singleRes) {
|
||||
setViewState(res.singleRes);
|
||||
setError(undefined);
|
||||
} else {
|
||||
setError(res.msg || `This plan isn't available.`);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (mounted.current) setError(e instanceof Error ? e.message : `This plan isn't available.`);
|
||||
} finally {
|
||||
if (mounted.current) setLoading(false);
|
||||
}
|
||||
}, [plan_id]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
|
||||
setLoading(true);
|
||||
void read();
|
||||
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, [read]);
|
||||
|
||||
useServerEvent({
|
||||
event: "server:bot-plan",
|
||||
onData: (data: BotPlanChangedData) => {
|
||||
if (Number(data?.plan_id) != plan_id) return;
|
||||
|
||||
void read();
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The card's own moves replace what was read, so it shows the change
|
||||
* without asking the app again.
|
||||
*/
|
||||
const setView = useCallback((next: BotPlanView) => {
|
||||
setViewState(next);
|
||||
setError(undefined);
|
||||
}, []);
|
||||
|
||||
return { view, loading, error, setView, reload: read };
|
||||
}
|
||||
@@ -18,6 +18,11 @@ type Params = {
|
||||
* The thread's last message: only newer ones are replayed.
|
||||
*/
|
||||
last_message_id?: number | null;
|
||||
/**
|
||||
* How many replies the session still has to come, as the read found it:
|
||||
* zero means the one it was waiting on ended without a message.
|
||||
*/
|
||||
on_open_jobs?: (params: { open_jobs: number }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -33,10 +38,23 @@ type Params = {
|
||||
* screen. The step is replayed as `server:bot-job-update`, so a run whose
|
||||
* steps were pushed while the page slept still shows the one it's on.
|
||||
* Reading it even when no reply is due is what lets a row stuck on a stale
|
||||
* face or task clear itself without a reload.
|
||||
* face or task clear itself without a reload. The replies the session still
|
||||
* has to come are handed back too: a run that ended without a word leaves
|
||||
* the thread's last message the user's, so the face alone can't tell it from
|
||||
* one still on its way.
|
||||
*/
|
||||
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
|
||||
export default function useReplyCatchUp({
|
||||
session_id,
|
||||
awaiting_reply,
|
||||
last_message_id,
|
||||
on_open_jobs,
|
||||
}: Params) {
|
||||
const last_message = useRef(Number(last_message_id) || 0);
|
||||
/**
|
||||
* Read through a ref, so a new callback on every render doesn't rebuild
|
||||
* the check (and the poll's timer with it).
|
||||
*/
|
||||
const report_open_jobs = useRef(on_open_jobs);
|
||||
/**
|
||||
* The open session: a read that lands after the thread moved to
|
||||
* another one is dropped instead of replaying into the wrong thread.
|
||||
@@ -45,6 +63,7 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
|
||||
|
||||
last_message.current = Number(last_message_id) || 0;
|
||||
open_session.current = session_id;
|
||||
report_open_jobs.current = on_open_jobs;
|
||||
|
||||
const check = useCallback(async () => {
|
||||
if (!session_id) return;
|
||||
@@ -80,6 +99,16 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
|
||||
* word an interim one) drops the row once its face moves on.
|
||||
*/
|
||||
if (res.bot?.id) replay({ data: { event: "server:bot-updated", data: res.bot } });
|
||||
|
||||
/**
|
||||
* A thread whose last word is the user's waits on a reply; when none
|
||||
* is left to come, the one it waited on ended without a message
|
||||
* (every message in the session had been answered already) and the
|
||||
* thinking row goes.
|
||||
*/
|
||||
if (typeof res.open_jobs == "number") {
|
||||
report_open_jobs.current?.({ open_jobs: res.open_jobs });
|
||||
}
|
||||
}, [session_id]);
|
||||
|
||||
useRefocus({ onRefocus: () => void check() });
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { ListChecks } from "lucide-react";
|
||||
import { BotPlanStates, type BotPlanState } from "@/src/dict/bot-plan-dict";
|
||||
import setBotPlanState from "../(functions)/set-bot-plan-state";
|
||||
import useBotPlan from "../(hooks)/use-bot-plan";
|
||||
import botPlanStatusLine from "../(utils)/bot-plan-status-line";
|
||||
import BotPlanEditModal from "./bot-plan-edit-modal";
|
||||
import BotPlanStepRow from "./bot-plan-step-row";
|
||||
|
||||
type Props = {
|
||||
plan_id: number;
|
||||
};
|
||||
|
||||
const stateTitle = ({ status }: { status: BotPlanState }) =>
|
||||
BotPlanStates.find((state) => state.value == status)?.title || status;
|
||||
|
||||
/**
|
||||
* A plan a bot wrote (`botPlanRef`), shown where the bot named it: what it
|
||||
* is for, its steps and where they stand, and the moves the user makes on
|
||||
* it. While it waits for them it goes nowhere; once approved the bot works
|
||||
* it one step per reply, and the card ticks along as each report comes in.
|
||||
* Anyone the plan wasn't written for sees its number only.
|
||||
*
|
||||
* Built from spans, since the ref sits inside a paragraph of the message
|
||||
* (a block element there is a nesting error React reports).
|
||||
*/
|
||||
export default function BotPlanCard({ plan_id }: Props) {
|
||||
const { view, loading, error: read_error, setView } = useBotPlan({ plan_id });
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [busy, setBusy] = useState<BotPlanState>();
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `plan ${plan_id}` : `plan ${plan_id} (not available${read_error ? `: ${read_error}` : ""})`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const move = async ({ status }: { status: BotPlanState }) => {
|
||||
if (busy) return;
|
||||
|
||||
setBusy(status);
|
||||
setError(undefined);
|
||||
|
||||
const res = await setBotPlanState({
|
||||
plan_id: view.id,
|
||||
status: status as "active" | "paused" | "cancelled",
|
||||
});
|
||||
|
||||
setBusy(undefined);
|
||||
|
||||
if (!res.success || !res.singleRes) {
|
||||
setError(res.msg || `Couldn't move the plan.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setView(res.singleRes);
|
||||
};
|
||||
|
||||
const can_change = view.status == "planned" || view.status == "active" || view.status == "paused";
|
||||
|
||||
return (
|
||||
<Span className="my-1 flex w-full flex-col overflow-hidden rounded-default border border-solid border-hairline">
|
||||
<Span className="flex w-full flex-nowrap items-center gap-2 border-0 border-b border-solid border-hairline bg-surface py-1.5 pr-2 pl-3">
|
||||
<ListChecks size={14} aria-hidden className="shrink-0 text-ink-secondary" />
|
||||
<Span className="min-w-0 grow truncate text-[13px] leading-5 font-bold text-ink">{view.title}</Span>
|
||||
<Span
|
||||
className={twMerge(
|
||||
"shrink-0 rounded-full border border-solid border-hairline px-2 py-0.5 text-[11px] leading-4 font-bold text-ink-secondary",
|
||||
view.status == "active" && "text-ink",
|
||||
)}
|
||||
>
|
||||
{stateTitle({ status: view.status })}
|
||||
</Span>
|
||||
</Span>
|
||||
|
||||
<Span className="flex w-full flex-col gap-2 py-2.5 pr-3 pl-3">
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary">{botPlanStatusLine({ view })}</Span>
|
||||
|
||||
{view.goal ? (
|
||||
<Span className="text-[13px] leading-5 text-ink-secondary">{view.goal}</Span>
|
||||
) : null}
|
||||
|
||||
<Span className="flex w-full flex-col gap-1.5 pt-0.5">
|
||||
{view.steps.map((step, index) => (
|
||||
<BotPlanStepRow
|
||||
key={`${index}-${step.text}`}
|
||||
step={step}
|
||||
current={view.status == "active" && index == view.current_step}
|
||||
/>
|
||||
))}
|
||||
</Span>
|
||||
|
||||
{can_change ? (
|
||||
<Span className="flex w-full flex-wrap items-center gap-1.5 pt-1">
|
||||
{view.status == "planned" ? (
|
||||
<Button
|
||||
title="Approve and start"
|
||||
type="button"
|
||||
size="smaller"
|
||||
loading={busy == "active"}
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => void move({ status: "active" })}
|
||||
>
|
||||
Approve and start
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{view.status == "active" ? (
|
||||
<Button
|
||||
title="Pause the plan"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
loading={busy == "paused"}
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => void move({ status: "paused" })}
|
||||
>
|
||||
Pause
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{view.status == "paused" ? (
|
||||
<Button
|
||||
title="Pick the plan back up"
|
||||
type="button"
|
||||
size="smaller"
|
||||
loading={busy == "active"}
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => void move({ status: "active" })}
|
||||
>
|
||||
Pick it back up
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
title="Change the plan's steps"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => setEditing(true)}
|
||||
>
|
||||
Change steps
|
||||
</Button>
|
||||
|
||||
{view.status == "planned" || view.status == "paused" ? (
|
||||
<Button
|
||||
title="Cancel the plan"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
loading={busy == "cancelled"}
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => void move({ status: "cancelled" })}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
) : null}
|
||||
</Span>
|
||||
) : null}
|
||||
|
||||
{error ? <Span className="text-[12px] leading-4 text-ink">{error}</Span> : null}
|
||||
</Span>
|
||||
|
||||
{editing ? (
|
||||
<BotPlanEditModal
|
||||
view={view}
|
||||
onSaved={(next) => {
|
||||
setEditing(false);
|
||||
setView(next);
|
||||
}}
|
||||
onCancel={() => setEditing(false)}
|
||||
/>
|
||||
) : null}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Textarea from "@moduletrace/twui/form/Textarea";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import saveBotPlan from "../(functions)/save-bot-plan";
|
||||
import BotPlanStepField from "./bot-plan-step-field";
|
||||
|
||||
type Props = {
|
||||
view: BotPlanView;
|
||||
onSaved: (view: BotPlanView) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
type Field = {
|
||||
/**
|
||||
* What React keys the row by, so taking one out doesn't shuffle what
|
||||
* the others show.
|
||||
*/
|
||||
key: number;
|
||||
text: string;
|
||||
/**
|
||||
* A step already worked: it reads as it was, and stays at the top.
|
||||
*/
|
||||
locked?: boolean;
|
||||
};
|
||||
|
||||
let next_key = 1;
|
||||
|
||||
/**
|
||||
* The plan before the bot starts on it, as the user wants it: its title,
|
||||
* what the plan is for, and the steps. Steps already done are the record of
|
||||
* work that happened, so they read only and stay where they are.
|
||||
*/
|
||||
export default function BotPlanEditModal({ view, onSaved, onCancel }: Props) {
|
||||
const [title, setTitle] = useState(view.title);
|
||||
const [goal, setGoal] = useState(view.goal);
|
||||
const [fields, setFields] = useState<Field[]>(() =>
|
||||
view.steps.map((step) => ({
|
||||
key: next_key++,
|
||||
text: step.text,
|
||||
locked: step.state != "pending",
|
||||
})),
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const setField = ({ key, text }: { key: number; text: string }) =>
|
||||
setFields((current) => current.map((field) => (field.key == key ? { ...field, text } : field)));
|
||||
|
||||
const removeField = ({ key }: { key: number }) =>
|
||||
setFields((current) => current.filter((field) => field.key != key));
|
||||
|
||||
const addField = () =>
|
||||
setFields((current) => [
|
||||
...current,
|
||||
{ key: next_key++, text: "" },
|
||||
]);
|
||||
|
||||
const submit = async () => {
|
||||
if (loading) return;
|
||||
|
||||
const steps = fields.map((field) => field.text.trim()).filter(Boolean);
|
||||
|
||||
if (!steps.length) {
|
||||
setError(`A plan needs at least one step.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await saveBotPlan({ plan_id: view.id, title: title.trim(), goal: goal.trim(), steps });
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!res.success || !res.singleRes) {
|
||||
setError(res.msg || `Couldn't save the plan.`);
|
||||
return;
|
||||
}
|
||||
|
||||
onSaved(res.singleRes);
|
||||
};
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => !next && onCancel()}
|
||||
title="Change the plan"
|
||||
description="The steps the bot works, one per reply. Steps already done stay as they are."
|
||||
>
|
||||
<Form className="w-full gap-4! items-stretch pt-4" onSubmit={submit}>
|
||||
<Input
|
||||
id="plan-title"
|
||||
title="Title"
|
||||
label="Title"
|
||||
showLabel
|
||||
placeholder="Audit the pricing pages"
|
||||
defaultValue={title}
|
||||
maxLength={AppData.BotPlanTitleMaxChars}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
id="plan-goal"
|
||||
title="Goal"
|
||||
label="Goal"
|
||||
showLabel
|
||||
rows={2}
|
||||
placeholder="What finished looks like, in one sentence."
|
||||
defaultValue={goal}
|
||||
info={`Up to ${AppData.BotPlanGoalMaxChars} characters.`}
|
||||
onChange={(e) => setGoal(e.target.value)}
|
||||
/>
|
||||
|
||||
<Stack className="w-full gap-2! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] font-bold text-ink">
|
||||
Steps ({fields.length} of {AppData.BotPlanMaxSteps})
|
||||
</Span>
|
||||
|
||||
{fields.map((field, index) => (
|
||||
<BotPlanStepField
|
||||
key={field.key}
|
||||
index={index}
|
||||
text={field.text}
|
||||
locked={field.locked}
|
||||
onChange={({ text }) => setField({ key: field.key, text })}
|
||||
onRemove={() => removeField({ key: field.key })}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Button
|
||||
title="Add a step"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
className="self-start"
|
||||
disabled={fields.length >= AppData.BotPlanMaxSteps}
|
||||
onClick={addField}
|
||||
>
|
||||
Add a step
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<AddFormActions submit_label="Save the plan" loading={loading} error={error} onCancel={onCancel} />
|
||||
</Form>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { X } from "lucide-react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Props = {
|
||||
index: number;
|
||||
text: string;
|
||||
/**
|
||||
* A step that's already done is what was worked: it reads, and can't be
|
||||
* changed.
|
||||
*/
|
||||
locked?: boolean;
|
||||
onChange: (params: { text: string }) => void;
|
||||
onRemove: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One step in the plan editor: its text, and a way to take it out while
|
||||
* the plan hadn't worked it yet.
|
||||
*/
|
||||
export default function BotPlanStepField({ index, text, locked, onChange, onRemove }: Props) {
|
||||
return (
|
||||
<Row className="w-full flex-nowrap items-start gap-1.5!">
|
||||
<Span className="mt-2.5 w-5 shrink-0 text-right text-[12px] leading-4 font-bold text-ink-secondary">
|
||||
{index + 1}
|
||||
</Span>
|
||||
|
||||
<Span className="min-w-0 grow">
|
||||
<Input
|
||||
id={`plan-step-${index}`}
|
||||
title={`Step ${index + 1}`}
|
||||
label={`Step ${index + 1}`}
|
||||
showLabel={false}
|
||||
placeholder="What this step does, in one line"
|
||||
defaultValue={text}
|
||||
disabled={locked}
|
||||
maxLength={AppData.BotPlanStepMaxChars}
|
||||
autoComplete="off"
|
||||
info={locked ? "Already worked: the line the bot wrote about it stays." : undefined}
|
||||
onChange={(e) => onChange({ text: e.target.value })}
|
||||
/>
|
||||
</Span>
|
||||
|
||||
{locked ? null : (
|
||||
<Button
|
||||
title={`Remove step ${index + 1}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
className="mt-1 shrink-0 p-1.5!"
|
||||
onClick={onRemove}
|
||||
>
|
||||
<X size={14} aria-hidden />
|
||||
</Button>
|
||||
)}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import BotPlanStepRow from "./bot-plan-step-row";
|
||||
|
||||
/**
|
||||
* A plan's card reads at a glance: what each step is, which one the bot is
|
||||
* on, and what a finished one produced. The note is the app's own record of
|
||||
* the work, so it shows under the step it belongs to.
|
||||
*/
|
||||
const step = (overrides: Partial<{ text: string; state: "done" | "skipped" | "pending"; note: string }> = {}) => ({
|
||||
text: "Collect the pages",
|
||||
state: "pending" as const,
|
||||
note: "",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("BotPlanStepRow", () => {
|
||||
test("a finished step carries what it produced", () => {
|
||||
const html = renderToString(<BotPlanStepRow step={step({ state: "done", note: "14 pages" })} current={false} />);
|
||||
|
||||
expect(html).toContain("Collect the pages");
|
||||
expect(html).toContain("14 pages");
|
||||
});
|
||||
|
||||
test("the step being worked says so, until it has a note", () => {
|
||||
expect(renderToString(<BotPlanStepRow step={step()} current={false} />)).not.toContain("Working on this now.");
|
||||
|
||||
expect(renderToString(<BotPlanStepRow step={step()} current />)).toContain("Working on this now.");
|
||||
});
|
||||
|
||||
test("a skipped step is behind the plan like a done one", () => {
|
||||
const html = renderToString(<BotPlanStepRow step={step({ state: "skipped" })} current={false} />);
|
||||
|
||||
expect(html).toContain("Collect the pages");
|
||||
expect(html).not.toContain("Working on this now.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Circle, CircleCheck, CircleSlash, CircleDot } from "lucide-react";
|
||||
import type { BotPlanStep } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
step: BotPlanStep;
|
||||
/**
|
||||
* The step the bot is on: only one is, and only while the plan runs.
|
||||
*/
|
||||
current: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One step of a plan on its card: whether it's done (with the line the bot
|
||||
* wrote about what it produced), the one being worked, or still to come.
|
||||
*/
|
||||
export default function BotPlanStepRow({ step, current }: Props) {
|
||||
const done = step.state == "done";
|
||||
const skipped = step.state == "skipped";
|
||||
|
||||
return (
|
||||
<Span className="flex w-full flex-nowrap items-start gap-2">
|
||||
<Span className="mt-0.5 flex shrink-0 items-center">
|
||||
{done ? (
|
||||
<CircleCheck size={14} aria-hidden className="text-ink" />
|
||||
) : skipped ? (
|
||||
<CircleSlash size={14} aria-hidden className="text-ink-disabled" />
|
||||
) : current ? (
|
||||
<CircleDot size={14} aria-hidden className="text-ink" />
|
||||
) : (
|
||||
<Circle size={14} aria-hidden className="text-ink-disabled" />
|
||||
)}
|
||||
</Span>
|
||||
|
||||
<Span className="flex min-w-0 flex-col gap-0.5">
|
||||
<Span
|
||||
className={twMerge(
|
||||
"text-[13px] leading-5",
|
||||
(done || skipped) && "text-ink-secondary",
|
||||
)}
|
||||
>
|
||||
{step.text}
|
||||
</Span>
|
||||
|
||||
{step.note ? (
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary">{step.note}</Span>
|
||||
) : current ? (
|
||||
<Span className="text-[12px] leading-4 text-ink-secondary">Working on this now.</Span>
|
||||
) : null}
|
||||
</Span>
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -313,7 +313,19 @@ export default function Composer({
|
||||
temp_id.current -= 1;
|
||||
|
||||
const client_id = temp_id.current;
|
||||
const text_sent = text;
|
||||
/**
|
||||
* The text goes as the server will store it, trimmed: a message
|
||||
* with a trailing newline was saved without it, and the bubble
|
||||
* waiting for it never matched the saved one.
|
||||
*/
|
||||
const text_sent = text.trim();
|
||||
/**
|
||||
* The server's own handle for this send, so a send whose answer
|
||||
* never arrived is recognised as the message already stored. Not
|
||||
* the thread's temp id: that restarts after a reload and would
|
||||
* match an older message of the same conversation.
|
||||
*/
|
||||
const request_id = crypto.randomUUID();
|
||||
const media_ids = files.media_ids;
|
||||
const attachments = files.pending.flatMap((item) =>
|
||||
item.status == "ready" && item.attachment ? [item.attachment] : [],
|
||||
@@ -356,6 +368,7 @@ export default function Composer({
|
||||
text: text_sent,
|
||||
media_ids,
|
||||
reply_to_message_id: reply_to?.id || null,
|
||||
client_id: request_id,
|
||||
});
|
||||
|
||||
if (!res.success || !res.singleRes) {
|
||||
|
||||
@@ -28,6 +28,23 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
|
||||
const [value, setValue] = useState("");
|
||||
const [busy, setBusy] = useState<"save" | "decline">();
|
||||
const [error, setError] = useState<string>();
|
||||
/**
|
||||
* The answer the bot never heard: the request was decided and the
|
||||
* message that tells it didn't go, so the user gets a way to send it
|
||||
* again instead of a card that closed on a promise nobody kept.
|
||||
*/
|
||||
const [unsent, setUnsent] = useState<string>();
|
||||
|
||||
const tellBot = async (params: { text: string }) => {
|
||||
const res = await sendBotMessage({
|
||||
bot_id: Number(pageProps?.bot?.id) || 0,
|
||||
workspace_id: pageProps?.workspace?.id || null,
|
||||
text: params.text,
|
||||
media_ids: [],
|
||||
}).catch(() => null);
|
||||
|
||||
return Boolean(res?.success);
|
||||
};
|
||||
|
||||
const open = view.status == "pending";
|
||||
|
||||
@@ -61,17 +78,38 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
|
||||
setValue("");
|
||||
onDecided(res.singleRes);
|
||||
|
||||
await sendBotMessage({
|
||||
bot_id: Number(pageProps?.bot?.id) || 0,
|
||||
workspace_id: pageProps?.workspace?.id || null,
|
||||
text: secretRequestMessage({ view: res.singleRes }),
|
||||
media_ids: [],
|
||||
}).catch(() => null);
|
||||
const text = secretRequestMessage({ view: res.singleRes });
|
||||
|
||||
if (!(await tellBot({ text }))) {
|
||||
/**
|
||||
* The secret is saved; what's left is telling the bot, and that
|
||||
* has to be possible from here rather than by remembering to
|
||||
* type it in the chat.
|
||||
*/
|
||||
setUnsent(text);
|
||||
setBusy(undefined);
|
||||
setError(`Saved for you, but the bot wasn't told. Send it the message again below.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(undefined);
|
||||
onDone();
|
||||
};
|
||||
|
||||
const resend = async () => {
|
||||
if (!unsent) return;
|
||||
|
||||
setError(undefined);
|
||||
|
||||
if (!(await tellBot({ text: unsent }))) {
|
||||
setError(`Couldn't tell the bot. Try again.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setUnsent(undefined);
|
||||
onDone();
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
<MessageDetailsHeading>What it is</MessageDetailsHeading>
|
||||
@@ -104,6 +142,19 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
|
||||
|
||||
{error ? <Span className="mt-2 text-[13px] leading-5 text-ink">{error}</Span> : null}
|
||||
|
||||
{!open && unsent ? (
|
||||
<Row className="mt-3 w-full gap-2! justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
size="small"
|
||||
title="Send the bot the message it never got"
|
||||
onClick={resend}
|
||||
>
|
||||
Tell the bot
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
|
||||
{open ? (
|
||||
<Row className="mt-5 w-full gap-2! justify-end">
|
||||
<Button
|
||||
|
||||
@@ -97,6 +97,13 @@ export default function Conversation() {
|
||||
* session, which the composer gives way to a link to.
|
||||
*/
|
||||
const [moved_to_session_id, setMovedToSessionId] = useState<number | null>(null);
|
||||
/**
|
||||
* How many replies the session still has to come, as the last catch-up
|
||||
* read found them, or null while that isn't known yet. A reply that ends
|
||||
* without a message leaves the last word the user's, so without this the
|
||||
* thread would wait on an answer that is never coming.
|
||||
*/
|
||||
const [open_reply_jobs, setOpenReplyJobs] = useState<number | null>(null);
|
||||
const [has_other_unread, setHasOtherUnread] = useState(false);
|
||||
/**
|
||||
* The debug logs under the thinking row, which its bug button toggles.
|
||||
@@ -212,6 +219,7 @@ export default function Conversation() {
|
||||
});
|
||||
progress.reset({ task: history.task });
|
||||
setReplyStep(history.step || null);
|
||||
setOpenReplyJobs(null);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -230,7 +238,8 @@ export default function Conversation() {
|
||||
*/
|
||||
const awaiting_reply =
|
||||
!moved_to_session_id &&
|
||||
isAwaitingReply({ last_message: last_thread_message, face: live_bot?.face });
|
||||
isAwaitingReply({ last_message: last_thread_message, face: live_bot?.face }) &&
|
||||
(open_reply_jobs == null || open_reply_jobs > 0);
|
||||
|
||||
const reply_progress = useReplyProgress({
|
||||
bot_id: bot?.id || 0,
|
||||
@@ -243,6 +252,7 @@ export default function Conversation() {
|
||||
session_id,
|
||||
awaiting_reply,
|
||||
last_message_id: last_saved_id,
|
||||
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -279,6 +289,13 @@ export default function Conversation() {
|
||||
dropSentMessage({ pending: prev, message }),
|
||||
);
|
||||
|
||||
/**
|
||||
* A message the user sent, here or in another tab, has a reply
|
||||
* queued behind it: what the last read said about open replies is
|
||||
* out of date.
|
||||
*/
|
||||
if (message.author == "user") setOpenReplyJobs(null);
|
||||
|
||||
/**
|
||||
* Before the history lands the thread has no session yet: the
|
||||
* message waits in the thread, and the history merges with it.
|
||||
@@ -493,12 +510,19 @@ export default function Conversation() {
|
||||
previous_messages={thread_messages}
|
||||
reply_to={reply_to}
|
||||
onCancelReply={() => setReplyTo(null)}
|
||||
onSendStart={({ message }) =>
|
||||
onSendStart={({ message }) => {
|
||||
/**
|
||||
* A reply is queued for it, so
|
||||
* the thread waits on one again
|
||||
* (a session that had none left
|
||||
* stopped polling).
|
||||
*/
|
||||
setOpenReplyJobs(null);
|
||||
setPendingMessages((prev) => [
|
||||
...prev,
|
||||
message,
|
||||
])
|
||||
}
|
||||
]);
|
||||
}}
|
||||
onSendFailed={({ temp_id }) =>
|
||||
setPendingMessages((prev) =>
|
||||
prev.filter(
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import botPlanStatusLine from "./bot-plan-status-line";
|
||||
|
||||
/**
|
||||
* The card's line says where the plan stands and what the user can do, so
|
||||
* every state reads differently: a waiting plan asks for approval, a working
|
||||
* one says which step, a paused one says how to go on.
|
||||
*/
|
||||
const view = (overrides: Partial<BotPlanView>): BotPlanView => ({
|
||||
id: 4,
|
||||
title: "Audit the pricing pages",
|
||||
goal: "",
|
||||
steps: [],
|
||||
status: "planned",
|
||||
current_step: 1,
|
||||
finished_steps: 1,
|
||||
total_steps: 5,
|
||||
decided_at: null,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
user_id: 1,
|
||||
bot_id: 2,
|
||||
bot_name: "Scout",
|
||||
session_id: 3,
|
||||
workspace_id: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("botPlanStatusLine", () => {
|
||||
test("a waiting plan asks the user to approve or change it", () => {
|
||||
expect(botPlanStatusLine({ view: view({ status: "planned" }) })).toBe(
|
||||
"Scout wrote this plan. Approve it to start, or change the steps first.",
|
||||
);
|
||||
});
|
||||
|
||||
test("a working plan names the step it's on, one-based", () => {
|
||||
expect(botPlanStatusLine({ view: view({ status: "active", current_step: 1 }) })).toBe(
|
||||
"Step 2 of 5: Scout works one step per reply and reports each.",
|
||||
);
|
||||
});
|
||||
|
||||
test("a paused plan points at picking it back up", () => {
|
||||
expect(botPlanStatusLine({ view: view({ status: "paused", current_step: 1 }) })).toContain(
|
||||
"Paused at step 2 of 5.",
|
||||
);
|
||||
});
|
||||
|
||||
test("a finished plan counts the steps behind it", () => {
|
||||
expect(botPlanStatusLine({ view: view({ status: "done", current_step: null, finished_steps: 5 }) })).toBe(
|
||||
"Every step is done (5 of 5).",
|
||||
);
|
||||
});
|
||||
|
||||
test("a cancelled plan says where it stopped", () => {
|
||||
expect(botPlanStatusLine({ view: view({ status: "cancelled" }) })).toContain("Cancelled at step 2 of 5.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
view: Pick<BotPlanView, "status" | "current_step" | "total_steps" | "finished_steps" | "bot_name">;
|
||||
};
|
||||
|
||||
/**
|
||||
* The line a plan's card carries under its title: where the plan stands,
|
||||
* and what the user can do about it.
|
||||
*/
|
||||
export default function botPlanStatusLine({ view }: Params) {
|
||||
const step = view.current_step == null ? view.total_steps : view.current_step + 1;
|
||||
|
||||
switch (view.status) {
|
||||
case "planned":
|
||||
return `${view.bot_name} wrote this plan. Approve it to start, or change the steps first.`;
|
||||
case "active":
|
||||
return `Step ${step} of ${view.total_steps}: ${view.bot_name} works one step per reply and reports each.`;
|
||||
case "paused":
|
||||
return `Paused at step ${step} of ${view.total_steps}. Pick it back up when you're ready.`;
|
||||
case "done":
|
||||
return `Every step is done (${view.finished_steps} of ${view.total_steps}).`;
|
||||
case "cancelled":
|
||||
return `Cancelled at step ${step} of ${view.total_steps}.`;
|
||||
default:
|
||||
return `Step ${step} of ${view.total_steps}.`;
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export default function dropSentMessage({ pending, message }: Params): BotMessag
|
||||
|
||||
const index = pending.findIndex(
|
||||
(item) =>
|
||||
item.text == message.text &&
|
||||
(item.text || "").trim() == (message.text || "").trim() &&
|
||||
(item.reply_to?.id || null) == (message.reply_to_message_id || null) &&
|
||||
(item.attachments?.length || 0) == (message.attachments?.length || 0),
|
||||
);
|
||||
|
||||
@@ -12,12 +12,14 @@ import {
|
||||
WorkspaceRefHrefPrefix,
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { parseFolderRefHref } from "@/src/utils/folder-ref";
|
||||
import { botPlanRefId } from "@/src/utils/bot-plan-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
import { botSuggestionRefId } from "@/src/utils/bot-suggestion-ref";
|
||||
import { graphicRefId } from "@/src/utils/graphic-ref";
|
||||
import { taskRefId } from "@/src/utils/task-ref";
|
||||
import { askRefId } from "@/src/utils/ask-ref";
|
||||
import { generalSettingsRefId } from "@/src/utils/general-settings-ref";
|
||||
import BotPlanCard from "../(partials)/bot-plan-card";
|
||||
import BotQuestionRefChip from "../(partials)/bot-question-ref-chip";
|
||||
import BotSuggestionsRef from "../(partials)/bot-suggestions-ref";
|
||||
import BotRefChip from "../(partials)/bot-ref-chip";
|
||||
@@ -115,6 +117,9 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
const suggestion_id = botSuggestionRefId({ href });
|
||||
if (suggestion_id) return <BotSuggestionsRef suggestion_id={suggestion_id} />;
|
||||
|
||||
const plan_id = botPlanRefId({ href });
|
||||
if (plan_id) return <BotPlanCard plan_id={plan_id} />;
|
||||
|
||||
const task_id = taskRefId({ href });
|
||||
|
||||
if (task_id) return <TaskRefChip task_id={task_id} />;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabBotPlanView from "@/src/functions/backend/db/bot-plans/grab-bot-plan-view";
|
||||
import { GetBotPlanSchema } from "@/src/schemas/bot-plan-schema";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* `GET ?plan_id=`: a plan as its card shows it, for the user it was made
|
||||
* for. Nobody else reads it.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<BotPlanView>> = async ({ req, query }) => {
|
||||
try {
|
||||
if (req.method != "GET") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
const { plan_id } = parseWithSchema({ schema: GetBotPlanSchema, data: query });
|
||||
|
||||
return { success: true, singleRes: await grabBotPlanView({ plan_id, user_id: user.id }) };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabBotPlanView from "@/src/functions/backend/db/bot-plans/grab-bot-plan-view";
|
||||
import saveBotPlanSteps from "@/src/functions/backend/db/bot-plans/save-bot-plan-steps";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import { SaveBotPlanSchema } from "@/src/schemas/bot-plan-schema";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* The user changed a plan's steps on its card, before approving it or while
|
||||
* it runs. Steps already done stay as they are: they record work that
|
||||
* happened. Answers with the plan as it now stands, and tells the open
|
||||
* conversation so every card of it shows the same steps.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<BotPlanView>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
const { plan_id, title, goal, steps } = parseWithSchema({ schema: SaveBotPlanSchema, data: body });
|
||||
|
||||
const row = await saveBotPlanSteps({ plan_id, user_id: user.id, title, goal, steps });
|
||||
const view = await grabBotPlanView({ plan_id: row.id, user_id: user.id });
|
||||
|
||||
await pushBotPlan({
|
||||
plan_id: row.id,
|
||||
session_id: row.session_id,
|
||||
bot_id: row.bot_id,
|
||||
});
|
||||
|
||||
return { success: true, singleRes: view };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabBotPlanView from "@/src/functions/backend/db/bot-plans/grab-bot-plan-view";
|
||||
import enqueuePlanStep from "@/src/functions/backend/db/bot-plans/enqueue-plan-step";
|
||||
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import { SetBotPlanStateSchema } from "@/src/schemas/bot-plan-schema";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* The user moved a plan from its card: approved it (or picked it back up),
|
||||
* paused it, or ended it. Approving and resuming wake the bot for the step
|
||||
* it stands on, so the plan carries on by itself; pausing and cancelling
|
||||
* only stop it, since the run between two steps is what queues the next.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<BotPlanView>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
const { plan_id, status } = parseWithSchema({ schema: SetBotPlanStateSchema, data: body });
|
||||
|
||||
const { row, started } = await setBotPlanStatus({
|
||||
plan_id,
|
||||
user_id: user.id,
|
||||
status: status as "active" | "paused" | "cancelled",
|
||||
});
|
||||
|
||||
const view = await grabBotPlanView({ plan_id: row.id, user_id: user.id });
|
||||
|
||||
await pushBotPlan({ plan_id: row.id, session_id: row.session_id, bot_id: row.bot_id });
|
||||
|
||||
if (started) {
|
||||
const job_id = await enqueuePlanStep({ plan_id: row.id });
|
||||
|
||||
if (job_id) wakeBotsQueue();
|
||||
}
|
||||
|
||||
return { success: true, singleRes: view };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -3,6 +3,9 @@ import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-u
|
||||
import ensureBotSession from "@/src/functions/backend/db/bot-sessions/ensure-bot-session";
|
||||
import insertUserMessage from "@/src/functions/backend/db/bots/insert-user-message";
|
||||
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
|
||||
import grabMessageIdByClientId from "@/src/functions/backend/db/bots/grab-message-id-by-client-id";
|
||||
import deleteBotMessage from "@/src/functions/backend/db/bots/delete-bot-message";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import grabAttachableMedia from "@/src/functions/backend/db/bots/grab-attachable-media";
|
||||
import storeChatAttachments from "@/src/functions/backend/db/bot-files/store-chat-attachments";
|
||||
import enqueueBotReply from "@/src/functions/backend/db/bots-queue/enqueue-bot-reply";
|
||||
@@ -51,10 +54,11 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
const { bot_id, workspace_id, text, media_ids, reply_to_message_id } = parseWithSchema({
|
||||
schema: SendBotMessageRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
const { bot_id, workspace_id, text, media_ids, reply_to_message_id, client_id } =
|
||||
parseWithSchema({
|
||||
schema: SendBotMessageRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
|
||||
const max_chars = await grabBotMessageMaxChars();
|
||||
|
||||
@@ -65,6 +69,44 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
const conversation = await grabUserConversation({ user_id: user.id, bot_id, workspace_id });
|
||||
const bot = conversation.bot;
|
||||
|
||||
/**
|
||||
* A send whose answer never arrived is sent again with the same
|
||||
* client id, and the message it stored is already there: answering
|
||||
* that one, with its reply still queued (`enqueueBotReply` reuses the
|
||||
* open job), keeps the thread from showing the message twice with
|
||||
* the bot answering both copies.
|
||||
*/
|
||||
if (client_id) {
|
||||
const stored_id = await grabMessageIdByClientId({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
client_id,
|
||||
}).catch(() => null);
|
||||
|
||||
const stored = stored_id
|
||||
? await grabUserBotMessage({ user_id: user.id, message_id: stored_id }).catch(
|
||||
() => null,
|
||||
)
|
||||
: null;
|
||||
|
||||
if (stored?.id && stored.session_id) {
|
||||
await enqueueBotReply({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(stored.session_id),
|
||||
message_id: Number(stored.id),
|
||||
});
|
||||
|
||||
wakeBotsQueue();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: stored,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const media = await grabAttachableMedia({ user_id: Number(user.id), media_ids });
|
||||
const session = await ensureBotSession({
|
||||
user_id: user.id,
|
||||
@@ -100,24 +142,44 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
text,
|
||||
reply_to,
|
||||
media,
|
||||
client_id,
|
||||
});
|
||||
|
||||
try {
|
||||
await enqueueBotReply({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
message_id: message.id || 0,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
/**
|
||||
* A message with no reply queued would sit in the thread with
|
||||
* nothing ever answering it, while the composer has already
|
||||
* taken its pending bubble down: it is taken back out, so the
|
||||
* send fails where the user can see it and send it again.
|
||||
*/
|
||||
await deleteBotMessage({ message_id: Number(message.id) }).catch(() => null);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files join the conversation's folder, so a later run can
|
||||
* search what the user sent now.
|
||||
* search what the user sent now. The message and its reply are
|
||||
* stored and queued by now: a folder that can't be written costs a
|
||||
* search hit, never the message.
|
||||
*/
|
||||
await storeChatAttachments({
|
||||
bot_id: bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
user_id: user.id,
|
||||
media,
|
||||
});
|
||||
|
||||
await enqueueBotReply({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
message_id: message.id || 0,
|
||||
}).catch(async (error: unknown) => {
|
||||
await logError({
|
||||
title: `Files of message #${message.id} not added to its conversation`,
|
||||
error,
|
||||
}).catch(() => {});
|
||||
});
|
||||
|
||||
wakeBotsQueue();
|
||||
|
||||
@@ -4,6 +4,7 @@ import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
|
||||
import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
|
||||
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
|
||||
import grabSessionReplyStep from "@/src/functions/backend/db/bots-queue/grab-session-reply-step";
|
||||
import grabSessionOpenReplies from "@/src/functions/backend/db/bots-queue/grab-session-open-replies";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
|
||||
import type { SessionMessagesResponse } from "@/src/types";
|
||||
@@ -17,7 +18,9 @@ import type { BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
* bot's face, status line and active task for that user (as
|
||||
* `server:bot-updated` carries them) plus the step its reply is on (as
|
||||
* `server:bot-job-update` does), so the open conversation can catch up on a
|
||||
* reply, a face change or a step whose live push it missed.
|
||||
* reply, a face change or a step whose live push it missed. `open_jobs` says
|
||||
* whether anything is still to answer there, so a run that ended without a
|
||||
* word can't leave the thread thinking.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({ req, body }) => {
|
||||
try {
|
||||
@@ -54,6 +57,7 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
|
||||
task: await grabActiveBotTask({ bot_id, user_id: user.id }),
|
||||
},
|
||||
step: await grabSessionReplyStep({ session_id: session.id }),
|
||||
open_jobs: await grabSessionOpenReplies({ session_id: session.id }),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotPlanSettableStates, BotPlanStepStates } from "@/src/dict/bot-plan-dict";
|
||||
|
||||
/**
|
||||
* One step a plan holds, as it's stored and read back.
|
||||
*/
|
||||
export const BotPlanStepSchema = z.object({
|
||||
text: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, `Write every step`)
|
||||
.max(AppData.BotPlanStepMaxChars, `Keep each step under ${AppData.BotPlanStepMaxChars} characters`),
|
||||
state: z.enum(BotPlanStepStates.map((state) => state.value) as [string, ...string[]]).optional(),
|
||||
note: z.string().trim().max(AppData.BotPlanStepNoteMaxChars).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* The steps a bot writes (`create_plan`, `update_plan`): one line each, in
|
||||
* the order they're worked, and distinct, since two the same read as a
|
||||
* mistake on the card.
|
||||
*/
|
||||
export const BotPlanStepTextsSchema = z
|
||||
.array(
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, `Write every step`)
|
||||
.max(AppData.BotPlanStepMaxChars, `Keep each step under ${AppData.BotPlanStepMaxChars} characters`),
|
||||
)
|
||||
.min(1, `A plan needs at least one step`)
|
||||
.max(AppData.BotPlanMaxSteps, `Keep a plan to ${AppData.BotPlanMaxSteps} steps`)
|
||||
.refine((steps) => new Set(steps.map((step) => step.toLowerCase())).size == steps.length, `Steps must differ`);
|
||||
|
||||
export const BotPlanTitleSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, `Give the plan a title`)
|
||||
.max(AppData.BotPlanTitleMaxChars, `Keep the title under ${AppData.BotPlanTitleMaxChars} characters`);
|
||||
|
||||
export const BotPlanGoalSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(AppData.BotPlanGoalMaxChars, `Keep the goal under ${AppData.BotPlanGoalMaxChars} characters`)
|
||||
.optional();
|
||||
|
||||
/**
|
||||
* What the user changing a plan's steps sends: the whole list, the steps
|
||||
* already done included (`saveBotPlanSteps` refuses to change or drop
|
||||
* those).
|
||||
*/
|
||||
export const SaveBotPlanSchema = z.object({
|
||||
plan_id: z.coerce.number().int().positive(`Pick the plan`),
|
||||
title: BotPlanTitleSchema,
|
||||
goal: BotPlanGoalSchema,
|
||||
steps: BotPlanStepTextsSchema,
|
||||
});
|
||||
|
||||
export const GetBotPlanSchema = z.object({
|
||||
plan_id: z.coerce.number().int().positive(`Pick the plan`),
|
||||
});
|
||||
|
||||
/**
|
||||
* Where the user moves a plan from its card: approve it (or pick it back
|
||||
* up), pause it, or end it.
|
||||
*/
|
||||
export const SetBotPlanStateSchema = z.object({
|
||||
plan_id: z.coerce.number().int().positive(`Pick the plan`),
|
||||
status: z.enum(BotPlanSettableStates as [string, ...string[]]),
|
||||
});
|
||||
|
||||
export type SaveBotPlanRequest = z.infer<typeof SaveBotPlanSchema>;
|
||||
export type SetBotPlanStateRequest = z.infer<typeof SetBotPlanStateSchema>;
|
||||
@@ -63,6 +63,12 @@ export const SendBotMessageRequestSchema = z.object({
|
||||
* The message this one replies to, quoted above it.
|
||||
*/
|
||||
reply_to_message_id: z.coerce.number().int().positive().nullish(),
|
||||
/**
|
||||
* The composer's own id for this send, so a send whose answer never
|
||||
* arrived is recognised as the message already stored instead of
|
||||
* being posted a second time.
|
||||
*/
|
||||
client_id: z.string().trim().max(64).optional(),
|
||||
}).refine((body) => body.text || body.media_ids.length, "Write a message or attach a file first");
|
||||
|
||||
export type SendBotMessageRequest = z.infer<typeof SendBotMessageRequestSchema>;
|
||||
|
||||
@@ -36,6 +36,7 @@ import type { HarnessKind } from "../dict/harness-dict";
|
||||
import type { HarnessProviderKind } from "../dict/harness-provider-dict";
|
||||
import type { EnvParadigm, KnownEnv, SecretRequestStatus } from "../dict/env-dict";
|
||||
import type { BotQuestionKind, BotQuestionStatus } from "../dict/bot-question-dict";
|
||||
import type { BotPlanState, BotPlanStepState } from "../dict/bot-plan-dict";
|
||||
import type { ContainerStatus } from "../dict/computer-dict";
|
||||
import type { BotFace, BotKind, BotMessageReactionEmoji } from "../dict/bot-dict";
|
||||
import type { BotTraceKind } from "../dict/bot-trace-dict";
|
||||
@@ -578,6 +579,13 @@ export type SessionMessagesResponse = APIResponseObject<BotMessageWithAttachment
|
||||
* step's push replays it and keeps its thinking row's line.
|
||||
*/
|
||||
step?: BotJobUpdateData | null;
|
||||
/**
|
||||
* How many replies the session still has to come (queued or being
|
||||
* written). Zero says nothing will answer there any more: a thread whose
|
||||
* last word is the user's stops waiting instead of thinking forever,
|
||||
* which is what a run that ended without a message looks like.
|
||||
*/
|
||||
open_jobs?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -891,6 +899,53 @@ export type BotSuggestionView = {
|
||||
bot_name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plan a bot broke complex work into (`[plan:ID]`): its steps, how far it
|
||||
* got, and what the user may do with it. The card reads it, and the run's
|
||||
* prompt carries the same shape without the bot's name.
|
||||
*/
|
||||
export type BotPlanView = {
|
||||
id: number;
|
||||
title: string;
|
||||
goal: string;
|
||||
steps: BotPlanStep[];
|
||||
status: BotPlanState;
|
||||
/**
|
||||
* The step being worked: the first one still pending, or null when
|
||||
* none is left.
|
||||
*/
|
||||
current_step: number | null;
|
||||
finished_steps: number;
|
||||
total_steps: number;
|
||||
decided_at: number | null;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
user_id: number;
|
||||
bot_id: number;
|
||||
bot_name: string;
|
||||
session_id: number;
|
||||
workspace_id: number | null;
|
||||
};
|
||||
|
||||
export type BotPlanStep = {
|
||||
text: string;
|
||||
state: BotPlanStepState;
|
||||
/**
|
||||
* What a finished step produced, in the bot's words.
|
||||
*/
|
||||
note: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pushed when a plan is written, moved on, or changed by the user, so every
|
||||
* open card of it reloads what it shows.
|
||||
*/
|
||||
export type BotPlanChangedData = {
|
||||
plan_id: number;
|
||||
session_id: number;
|
||||
bot_id: number;
|
||||
};
|
||||
|
||||
export type SecretRequestView = {
|
||||
id: number;
|
||||
key: string;
|
||||
@@ -2691,6 +2746,11 @@ export const WebSocketEvents = [
|
||||
* `BotTraceData`)
|
||||
*/
|
||||
"server:bot-trace",
|
||||
/**
|
||||
* A plan a bot wrote was created, moved on a step, or changed by the
|
||||
* user (`data`: `BotPlanChangedData`)
|
||||
*/
|
||||
"server:bot-plan",
|
||||
/**
|
||||
* A call to one of the user's hooks came in or changed (`data`:
|
||||
* `{ hook_id }`)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unsupportedAppRecordLines from "./app-record-claims";
|
||||
|
||||
const start_task = { name: "start_task", ok: true };
|
||||
|
||||
describe("unsupportedAppRecordLines", () => {
|
||||
test("faults the line that names a tool the reply never called", () => {
|
||||
const text = "I'm checking your inbox now.\n\n[App record: this message's run called start_task.]";
|
||||
|
||||
expect(unsupportedAppRecordLines({ text, tool_uses: [] }).length).toBe(1);
|
||||
});
|
||||
|
||||
test("leaves a line the reply's record supports alone: the bot quoting what it wrote before it ran anything", () => {
|
||||
const text = "That line was mine, not the app's:\n\n[App record: this message's run called start_task.]";
|
||||
|
||||
expect(unsupportedAppRecordLines({ text, tool_uses: [start_task] })).toEqual([]);
|
||||
});
|
||||
|
||||
test("the app's honest line for a run that called nothing claims nothing", () => {
|
||||
for (const line of [
|
||||
"[App record: this message's run called no tools.]",
|
||||
"[App record: this message's run called none.]",
|
||||
]) {
|
||||
expect(unsupportedAppRecordLines({ text: `Nothing ran.\n\n${line}`, tool_uses: [] })).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("counts and failure notes in the app's shape don't hide a name", () => {
|
||||
const text = "[App record: this message's run called computer_bash x2 (1 failed), start_task.]";
|
||||
|
||||
expect(unsupportedAppRecordLines({ text, tool_uses: [{ name: "computer_bash", ok: false }] }).length).toBe(1);
|
||||
expect(
|
||||
unsupportedAppRecordLines({
|
||||
text,
|
||||
tool_uses: [
|
||||
{ name: "computer_bash", ok: false },
|
||||
start_task,
|
||||
],
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("a record-shaped line in words the app never writes stays suspect", () => {
|
||||
expect(
|
||||
unsupportedAppRecordLines({
|
||||
text: "[App record: start_task was called here]",
|
||||
tool_uses: [start_task],
|
||||
}).length,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test("nothing outside a record line is a record: the phrase in a sentence, a quote or a code span", () => {
|
||||
const mentioned = [
|
||||
'I wrote a fake "[App record: ...]" line claiming a clone I never did.',
|
||||
"The app adds a line shaped `[App record: ...]`, never me.",
|
||||
"Read the note the app calls [App record: ...] below your message.",
|
||||
];
|
||||
|
||||
for (const text of mentioned) {
|
||||
expect(unsupportedAppRecordLines({ text, tool_uses: [] })).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import { AppRecordPrefix, appRecordLines } from "./strip-app-records";
|
||||
|
||||
type Params = {
|
||||
text: string;
|
||||
/**
|
||||
* Every tool call the reply made, the app's own record of the run.
|
||||
*/
|
||||
tool_uses: HarnessToolUse[];
|
||||
};
|
||||
|
||||
/**
|
||||
* How the app words its record, the one shape it ever writes: `this
|
||||
* message's run called update_memory, fetch_url x3 (1 failed).` A line in
|
||||
* another shape may still be a forged record wearing other words, so it
|
||||
* stays suspect rather than passing.
|
||||
*/
|
||||
const RecordShape = /^this message's run called\s+([^.\]]*)/i;
|
||||
|
||||
/**
|
||||
* Words that sit where a tool name does but name no work: the app's own
|
||||
* line for a run that called nothing.
|
||||
*/
|
||||
const NotToolNames = ["none", "nothing", "no tools"];
|
||||
|
||||
/**
|
||||
* The tool names a record line claims the run called, or null when the
|
||||
* line isn't in the app's shape. Counts and failure notes (`x3`,
|
||||
* `(1 failed)`) come off, and so does anything that isn't a tool name.
|
||||
*/
|
||||
function claimedToolNames({ line }: { line: string }): string[] | null {
|
||||
/**
|
||||
* The app writes one space after the prefix, so it comes off before
|
||||
* the shape is read.
|
||||
*/
|
||||
const body = line.trim().slice(AppRecordPrefix.length).trim().replace(/\]\s*$/, "");
|
||||
const shape = body.match(RecordShape);
|
||||
|
||||
if (!shape) return null;
|
||||
|
||||
const named = shape[1] ?? "";
|
||||
|
||||
return named
|
||||
.split(",")
|
||||
.map((part) => part.replace(/\([^)]*\)/g, "").replace(/\s*x\d+/gi, "").trim())
|
||||
.filter((name) => /^[a-z][a-z0-9_]*$/.test(name))
|
||||
.filter((name) => !NotToolNames.includes(name.toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The record lines in a bot's answer the app's record of the reply does not
|
||||
* support: each names a tool this reply never called. This is the only
|
||||
* forgery that hurts, since it makes the app vouch for work no tool did.
|
||||
*
|
||||
* A line the record supports is the app's truth in the app's shape: copied
|
||||
* out of the bot's own history, usually to say plainly that it wrote the
|
||||
* line before it had called the tool. Saying that is the correction the
|
||||
* user needs, so it is left alone. `run-bot-reply` strips these lines from
|
||||
* what it stores anyway, so the user never reads the copy as the app's
|
||||
* word.
|
||||
*/
|
||||
export default function unsupportedAppRecordLines({ text, tool_uses }: Params): string[] {
|
||||
const recordLines = appRecordLines({ text });
|
||||
|
||||
if (!recordLines.length) return [];
|
||||
|
||||
/**
|
||||
* A failed call was still a call: the app's own line names it, with
|
||||
* the count of what went wrong.
|
||||
*/
|
||||
const called = new Set(tool_uses.map((use) => use.name));
|
||||
|
||||
return recordLines.filter((line) => {
|
||||
const claims = claimedToolNames({ line });
|
||||
|
||||
if (!claims) return true;
|
||||
|
||||
return claims.some((name) => !called.has(name));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import botPlanRef, { botPlanRefId, BotPlanRefHrefPrefix } from "./bot-plan-ref";
|
||||
import linkComputerRefs from "./link-computer-refs";
|
||||
|
||||
/**
|
||||
* A plan reaches the chat as `[plan:4]`, which the renderer turns into a
|
||||
* link its card reads the id back from. A ref the bot wrote inside a code
|
||||
* span alone still links; one inside longer code stays as it was written.
|
||||
*/
|
||||
describe("botPlanRef", () => {
|
||||
test("writes the ref the message carries", () => {
|
||||
expect(botPlanRef({ plan_id: 4 })).toBe("[plan:4]");
|
||||
expect(botPlanRef({ plan_id: "4" })).toBe("[plan:4]");
|
||||
});
|
||||
|
||||
test("reads the id back from the card's href, and nothing from another link", () => {
|
||||
expect(botPlanRefId({ href: `${BotPlanRefHrefPrefix}12` })).toBe(12);
|
||||
expect(botPlanRefId({ href: `${BotPlanRefHrefPrefix}0` })).toBeNull();
|
||||
expect(botPlanRefId({ href: `${BotPlanRefHrefPrefix}twelve` })).toBeNull();
|
||||
expect(botPlanRefId({ href: "#suggestion-4" })).toBeNull();
|
||||
expect(botPlanRefId({ href: undefined })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a plan ref in a message", () => {
|
||||
test("turns a plan ref into a link", () => {
|
||||
expect(linkComputerRefs({ text: "Here it is, [plan:4]: approve when ready." })).toContain(
|
||||
"[plan 4](#plan-4)",
|
||||
);
|
||||
});
|
||||
|
||||
test("links a ref quoted alone in a code span", () => {
|
||||
expect(linkComputerRefs({ text: "Written: `[plan:4]`." })).toContain("[plan 4](#plan-4)");
|
||||
});
|
||||
|
||||
test("leaves a ref inside longer code as the bot wrote it", () => {
|
||||
const text = "```\n[plan:4]\n```";
|
||||
|
||||
expect(linkComputerRefs({ text })).toBe(text);
|
||||
});
|
||||
|
||||
test("leaves a ref that is already a link alone", () => {
|
||||
const text = "[plan 4](#plan-4)";
|
||||
|
||||
expect(linkComputerRefs({ text })).toBe(text);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* The inline ref a bot writes to show a plan it wrote: `/bot_plans`
|
||||
* renders it as the plan's card (its steps, and the buttons to approve or
|
||||
* change them before the bot begins).
|
||||
*/
|
||||
export default function botPlanRef({ plan_id }: { plan_id: number | string }) {
|
||||
return `[plan:${Number(plan_id)}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The href a rendered plan ref links to, so the card can read its id back
|
||||
* (`botPlanRefId`).
|
||||
*/
|
||||
export const BotPlanRefHrefPrefix = "#plan-";
|
||||
|
||||
/**
|
||||
* The plan id an href points at, or null for any other link.
|
||||
*/
|
||||
export function botPlanRefId({ href }: { href?: string | null }) {
|
||||
if (!href?.startsWith(BotPlanRefHrefPrefix)) return null;
|
||||
|
||||
const plan_id = Number(href.slice(BotPlanRefHrefPrefix.length));
|
||||
|
||||
if (!Number.isInteger(plan_id) || plan_id <= 0) return null;
|
||||
|
||||
return plan_id;
|
||||
}
|
||||
@@ -16,6 +16,18 @@ describe("claimsWorkUnderWay", () => {
|
||||
"I'll go ahead and check the tab right away.",
|
||||
"What I sent @SEO Expert: a full brief, with the scope and the ground rules.",
|
||||
"I've passed the brief on to [bot:6] SEO Expert.",
|
||||
/**
|
||||
* The reply that started nothing: it said the run was under
|
||||
* way, then wrote its own app record line to look like the
|
||||
* tools had run. Caught by the app, not by the user.
|
||||
*/
|
||||
"I'm starting the hydration work as a single-route proof rather than a shell-wide rewrite, on [computer:1] - with the production numbers as the target. I'll say why I scoped it that way once the run reports.",
|
||||
"I've started the hydration work on computer 1. I'll report when it lands.",
|
||||
"I'm starting the recon run for task #44.",
|
||||
"I've kicked off the run on computer 1.",
|
||||
"I'm spinning up the build now.",
|
||||
"I'm starting it now.",
|
||||
"Starting it now.",
|
||||
]) {
|
||||
expect(claimsWorkUnderWay({ text })).toBe(true);
|
||||
}
|
||||
@@ -33,6 +45,10 @@ describe("claimsWorkUnderWay", () => {
|
||||
"I'll use the navy palette in the next round.",
|
||||
"I sent the invoice to accounting last week.",
|
||||
"The report was sent to the team on Monday.",
|
||||
"I'll start with what changed, then the numbers.",
|
||||
"I'm starting to think the brief is wrong.",
|
||||
"I started the invoice last week.",
|
||||
"Task #48 is doing, nothing is running yet.",
|
||||
]) {
|
||||
expect(claimsWorkUnderWay({ text })).toBe(false);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ const UnderWayPatterns = [
|
||||
/\bI(?:'|’)ll\s+(?:report back|get back to you|let you know when|bring (?:you |it )?back|report (?:the|my) (?:results?|findings))/i,
|
||||
/\b(?:report|results?|details|update)\s+(?:follows|will follow|to follow|coming)\b/i,
|
||||
/\bin (?:my|the|a) (?:next|following) message\b/i,
|
||||
/\b(?:when|once) (?:it|that|the (?:run|scan|search|check))(?:'|’)?s? (?:back|done|finished|complete)\b/i,
|
||||
/\b(?:when|once) (?:it|that|the (?:run|job|task|scan|search|check|work))(?:'|’)?s?\s+(?:back|done|finished|complete|reports|lands|returns|comes in|comes back)\b/i,
|
||||
/**
|
||||
* "I'll drive the browser to ideogram.ai directly and see what's
|
||||
* there." A dot inside a word (a domain, a file name) doesn't end the
|
||||
@@ -27,6 +27,16 @@ const UnderWayPatterns = [
|
||||
* record decides whether it's true.
|
||||
*/
|
||||
/\b(?:sent|passed|forwarded|handed)\b[^.!?\n]{0,80}(?:@[a-z0-9_-]+|\[bot:\d+\])/i,
|
||||
/**
|
||||
* "I'm starting the hydration work on computer 1", "I've kicked off
|
||||
* the run": a run claimed as started, without the "now" or the
|
||||
* promised report the patterns above need. Only `start_task` starts
|
||||
* one, so the app's record decides whether it's true.
|
||||
*/
|
||||
/\bI(?:'|’)?m\s+(?:now\s+|just\s+)?(?:starting|beginning|kicking off|launching|queueing|queuing|firing off|spinning up)\b[^.!?\n]{0,120}\b(?:run|task|job|work|scan|audit|recon|build|pass)\b/i,
|
||||
/\bI(?:'|’)ve\s+(?:now\s+|just\s+)?(?:started|begun|kicked off|launched|queued|fired off|spun up)\b/i,
|
||||
/\bI(?:'|’)?m\s+(?:now\s+|just\s+)?(?:starting|beginning|kicking off)\s+(?:it|this|that)\b/i,
|
||||
/(?:^|[.!?\n]\s*)(?:starting|beginning|kicking off)\s+(?:it|that|the (?:run|job|task|work|scan|audit|build))\b/i,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotPlanStepRecord } from "./parse-bot-plan-steps";
|
||||
import currentPlanStepIndex from "./current-plan-step-index";
|
||||
import planStepCounts from "./plan-step-counts";
|
||||
|
||||
/**
|
||||
* A plan is worked in the order the bot wrote it, so the step to work is
|
||||
* always the first one still pending: the app decides it, never the run. A
|
||||
* skipped step is behind the plan as much as a done one.
|
||||
*/
|
||||
const step = ({ text, state }: { text: string; state: BotPlanStepRecord["state"] }): BotPlanStepRecord => ({
|
||||
text,
|
||||
state,
|
||||
note: "",
|
||||
});
|
||||
|
||||
describe("currentPlanStepIndex", () => {
|
||||
test("is the first step still waiting, whatever was skipped before it", () => {
|
||||
const steps = [
|
||||
step({ text: "Collect the pages", state: "done" }),
|
||||
step({ text: "Score them", state: "skipped" }),
|
||||
step({ text: "Write it up", state: "pending" }),
|
||||
step({ text: "Send it", state: "pending" }),
|
||||
];
|
||||
|
||||
expect(currentPlanStepIndex({ steps })).toBe(2);
|
||||
});
|
||||
|
||||
test("is null once nothing is left to work", () => {
|
||||
expect(
|
||||
currentPlanStepIndex({
|
||||
steps: [step({ text: "one", state: "done" }), step({ text: "two", state: "skipped" })],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("is null for a plan with no steps", () => {
|
||||
expect(currentPlanStepIndex({ steps: [] })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("planStepCounts", () => {
|
||||
test("counts the steps behind the plan, skipped ones included", () => {
|
||||
const steps = [
|
||||
step({ text: "one", state: "done" }),
|
||||
step({ text: "two", state: "skipped" }),
|
||||
step({ text: "three", state: "pending" }),
|
||||
];
|
||||
|
||||
expect(planStepCounts({ steps })).toEqual({ finished: 2, total: 3 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
|
||||
|
||||
/**
|
||||
* The step a plan is on: the first one still waiting. Null once none is
|
||||
* left, which is a plan with nothing more to run. Steps are worked in the
|
||||
* order the bot wrote them, so this is where the work is, never a step the
|
||||
* bot picks for itself.
|
||||
*/
|
||||
export default function currentPlanStepIndex({ steps }: { steps: BotPlanStepRecord[] }) {
|
||||
const index = steps.findIndex((step) => step.state == "pending");
|
||||
|
||||
return index == -1 ? null : index;
|
||||
}
|
||||
@@ -69,7 +69,8 @@ export const SecretRequestRefHrefPrefix = "#secret-request-";
|
||||
/**
|
||||
* The kinds of ref a message can carry, as written before the colon.
|
||||
*/
|
||||
const RefKinds = "computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|suggestion|graphic|room|task|setting|file|folder";
|
||||
const RefKinds =
|
||||
"computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|suggestion|plan|graphic|room|task|setting|file|folder";
|
||||
|
||||
/**
|
||||
* A code span holding nothing but one ref (`` `[file:12]` ``): bots often
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user