Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0151ca6e55 | ||
|
|
baeb9a80d3 | ||
|
|
984ad702d6 | ||
|
|
09039bee22 | ||
|
|
d22b1ff1d2 | ||
|
|
275353ac1e | ||
|
|
52eab84f9a | ||
|
|
6dc2859292 |
@@ -100,8 +100,8 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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`, `delete_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 conversation's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next (side arrows at the far middle left/right, the header's stepper, 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` (`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.
|
||||
- **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 (a second call returns the card already up instead of throwing: a refused re-ask read as a failed closing turn and the whole answer was thrown away) -> `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 (a second call returns the steps already attached instead of throwing) -> `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.
|
||||
@@ -126,16 +126,16 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, 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: `queueBotTask` (a reply's `send_reply` work, or `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).
|
||||
- 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 job queued by a tool (`enqueueBotJob`, the `queueBotTask` path) wakes the queue and pushes `server:bot-updated` itself, so a run queued behind another on the same computer shows and starts at once instead of waiting for the poll; a failed run closes its own `bot_tasks` row (`notifyBotJobFailed`), since a row left `active` kept a conversation's progress on a run that had failed months before (a queued run creates it `active`; only complete, cancel and stop closed it before).
|
||||
- **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. **The files the brief names are checked once, before the run starts** (`namedFilesNote`, over `namedFiles`): a path that isn't on the computer but is still in the bot's files is handed over as its `[file:ID]` with `export_file`, and one with no copy anywhere says plainly not to go looking through the machine or the user's accounts. It is the app's answer, not the run's guess: a source a rebuild took off the computer once cost a run thirty turns probing the container and then the user's own accounts for a copy the app was holding the whole time.
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees, though a message written in the turn just before is taken as the one beside `send_reply` when it carries none (models that think the text travels with the call wrote the answer there), and a run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **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 or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. 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 job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), 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`, `AppCardRefToolNames`, `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`).
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?, message?})` with the message beside it or in its `message`/`text` argument (`replyTextFromCall`: a model that wrote the message into the call instead of the turn lost six production answers to "doesn't take text"), and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A message written in the turn that put a card up (`ask_user`/`suggest_next_steps` with no `send_reply`) is kept as `card_text` and goes out with the call that closes it: that sentence is what the card belongs under, and asking for it again left the model with nothing to say (session 146). A review send-back clears `draft_text` and `card_text` and the reminder flag, so a refused answer is never carried again (the same faulted text went out on every bare `send_reply` and used up the rewrite budget). A draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **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 or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"; `stripCardRefs` keeps them out of the answer and out of the model's own history, since the stored text carries the ref the app appended under it, which is how one began writing `[question:24]` at a card it never made), a `[proposal:]`/`[hook-proposal:]` ref no row backs (the model guessed `[proposal:19]` 85 s before that row existed, and the user was told three times a proposal had gone out when none had), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. 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 job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), 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`, `AppCardRefToolNames`, `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`).
|
||||
- **A reply's `send_reply` work and `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). `queueBotTask` 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 (`send_reply`'s work, `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; a retry (`params.retry_of`) always runs. **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`, 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.
|
||||
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. A push's `task` is a list of every active task that user has on the bot (`grabActiveBotTasks`), and the conversation picks its own session's (`ownTask`), since sending only the newest one blanked the row whenever another conversation of the same bot had a run open; a page also keeps polling (`use-reply-catch-up` `running`) while its session has open jobs or an active task, not only until a reply lands, since a run queued behind another on the same computer starts much later (`queueBotTask` refuses a second one there, and the face then says which wait it is: `botWaitsOnComputer` picks `BotComputerBusyStatusLine` over `BotWaitingStatusLine`).
|
||||
|
||||
### Crew requests (`bot_asks`)
|
||||
|
||||
@@ -212,7 +212,7 @@ A user's own running browser, reached over a browser MCP server they run beside
|
||||
|
||||
### Knowledgebases
|
||||
|
||||
A fourth extension kind (`ExtensionTables.knowledgebase`): `knowledgebases` given per bot (`bot_knowledgebases`), per workspace (`workspace_knowledgebases`) or every bot (`all_bots`), through the same add/remove/access/default paths as skills (`list_extensions` and `delete_extension` leave them out, and so do the proposal cards). Documents (`knowledgebase_documents`: an upload in private `media`, paradigm `knowledgebase-document`, or written `content`) are chunked into `knowledgebase_chunks` and embedded into the `knowledgebase_vectors` vec0 table by the file-ingest worker (`file_ingest_queue.document_id`, `ingestKnowledgebaseDocument`), always with the install's embedding model; old passages stay until the new ones are in, `embedding_model` records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls `reindexAfterEmbeddingChange`, and Re-index reads a knowledgebase again by hand. Word search runs on `knowledgebase_chunks_fts`, an FTS5 table (`unicode61 remove_diacritics 2`) made by `ensureKnowledgebaseFts` (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by `syncKnowledgebaseFts`, ranked by BM25 with a scored `LIKE` fallback for unspaced scripts (`knowledgebaseWordQuery`); every write and delete of `knowledgebase_chunks` updates it. Ingest jobs (`settleFailedIngestJob`) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get `search_knowledgebase`/`read_knowledgebase_document` (`openBotKnowledgebases`, limited to the run's ones) and replies start with passages found for the unanswered messages (`grabKnowledgebaseContext`); passages are fenced (`knowledgebasePassageBlock`) and `KnowledgebasesNote` says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (`ComposerToolsModal` with `composerKnowledgebasesCopy`). Deleting one deletes its documents' vectors, chunks, media and links explicitly. **The coordinator manages them when the super admin asks for it in the chat:** `grabCoordinatorKnowledgebaseTools` (`src/harness/tools/bot/knowledgebases/`, pushed beside `grabCoordinatorExtensionTools` in `grab-bot-chat-tools.ts` and in the coordinator branch of `run-bot-task.ts`) gives `list_knowledgebases` in any of its runs, and `save_knowledgebase` (name, description, on/off, who gets it through `set_extension_access`), `add_knowledgebase_document` (`file_id` a saved file, `media_id` the user's own upload, `path` on a computer, or `text`), `delete_knowledgebase_document`, `delete_knowledgebase` and `reindex_knowledgebase` only in a reply or a task the user follows (`attended`: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private `media` first (`recordKnowledgebaseFile`, shared with `upload-document.ts`, and the same refusal in `knowledgebaseFileProblem`), so it stays after the computer or the file is gone; a task's own computer is the default for `path`. `AccessExtensionKindSchema` adds `knowledgebase` for access only: `ExtensionKindSchema` stays three kinds, since `delete_extension`'s last branch deletes a custom tool.
|
||||
A fourth extension kind (`ExtensionTables.knowledgebase`): `knowledgebases` given per bot (`bot_knowledgebases`), per workspace (`workspace_knowledgebases`) or every bot (`all_bots`), through the same add/remove/access/default paths as skills (`list_extensions` and `delete_extension` leave them out, and so do the proposal cards). Documents (`knowledgebase_documents`: an upload in private `media`, paradigm `knowledgebase-document`, or written `content`) are chunked into `knowledgebase_chunks` and embedded into the `knowledgebase_vectors` vec0 table by the file-ingest worker (`file_ingest_queue.document_id`, `ingestKnowledgebaseDocument`), always with the install's embedding model; old passages stay until the new ones are in, `embedding_model` records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls `reindexAfterEmbeddingChange`, and Re-index reads a knowledgebase again by hand. Retry failed (`retryFailedDocuments`, the row menu's Retry failed and `retry_failed_documents`) queues only the documents with `ingest_error`, clearing it so the ten-minute sweep can pick them up too. Word search runs on `knowledgebase_chunks_fts`, an FTS5 table (`unicode61 remove_diacritics 2`) made by `ensureKnowledgebaseFts` (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by `syncKnowledgebaseFts`, ranked by BM25 with a scored `LIKE` fallback for unspaced scripts (`knowledgebaseWordQuery`); every write and delete of `knowledgebase_chunks` updates it. Ingest jobs (`settleFailedIngestJob`) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get `search_knowledgebase`/`read_knowledgebase_document` (`openBotKnowledgebases`, limited to the run's ones) and replies start with passages found for the unanswered messages (`grabKnowledgebaseContext`); passages are fenced (`knowledgebasePassageBlock`) and `KnowledgebasesNote` says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (`ComposerToolsModal` with `composerKnowledgebasesCopy`). Deleting one deletes its documents' vectors, chunks, media and links explicitly. **The coordinator manages them when the super admin asks for it in the chat:** `grabCoordinatorKnowledgebaseTools` (`src/harness/tools/bot/knowledgebases/`, pushed beside `grabCoordinatorExtensionTools` in `grab-bot-chat-tools.ts` and in the coordinator branch of `run-bot-task.ts`) gives `list_knowledgebases` in any of its runs, and `save_knowledgebase` (name, description, on/off, who gets it through `set_extension_access`), `add_knowledgebase_document` (`file_id` a saved file, `media_id` the user's own upload, `path` on a computer, or `text`), `delete_knowledgebase_document`, `delete_knowledgebase`, `retry_failed_documents` and `reindex_knowledgebase` only in a reply or a task the user follows (`attended`: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private `media` first (`recordKnowledgebaseFile`, shared with `upload-document.ts`, and the same refusal in `knowledgebaseFileProblem`), so it stays after the computer or the file is gone; a task's own computer is the default for `path`. `AccessExtensionKindSchema` adds `knowledgebase` for access only: `ExtensionKindSchema` stays three kinds, since `delete_extension`'s last branch deletes a custom tool.
|
||||
|
||||
sqlite-vec limits: metadata columns are NOT NULL; side-car columns can't be filtered with `MATCH` (filter in code). **Never pass `--vector` to `bunx bun-sqlite schema` in `entrypoint.sh`** (wipes vectors on boot). Changing `AppData.EmbeddingDimensions` needs a manual `--vector` run and a re-index.
|
||||
|
||||
@@ -230,11 +230,11 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; the newest messages are never trimmed; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget`; only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process.
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (`replacePendingExtensionProposals`: a skill by `data.slug`, else the extension id, else the normalised name; `replacePendingHookProposals` by `hook_id`, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
|
||||
|
||||
### Token usage
|
||||
|
||||
@@ -10,13 +10,24 @@ const base = {
|
||||
|
||||
describe("runCommand", () => {
|
||||
test("returns output in order and the exit code", async () => {
|
||||
const result = await runCommand({ ...base, command: "echo one; echo two >&2; exit 3" });
|
||||
const result = await runCommand({ ...base, command: "echo one; echo two; exit 3" });
|
||||
|
||||
expect(result.output).toBe("one\ntwo\n");
|
||||
expect(result.exit_code).toBe(3);
|
||||
expect(result.timed_out).toBe(false);
|
||||
});
|
||||
|
||||
/**
|
||||
* stdout and stderr are two pipes read as they arrive, so which of
|
||||
* them a line from each lands first is the scheduler's call: both come
|
||||
* back, each in its own order.
|
||||
*/
|
||||
test("brings stderr back together with stdout", async () => {
|
||||
const result = await runCommand({ ...base, command: "echo out; echo err >&2" });
|
||||
|
||||
expect(result.output.split("\n").filter(Boolean).sort()).toEqual(["err", "out"]);
|
||||
});
|
||||
|
||||
test("reads no input", async () => {
|
||||
const result = await runCommand({ ...base, command: "read -r line; echo \"got:$line:$?\"" });
|
||||
|
||||
|
||||
@@ -34,7 +34,9 @@ export type CommandResult = {
|
||||
/**
|
||||
* Runs one command in its own `bash -c`, in its own process group, with
|
||||
* no input (a prompt fails at once instead of waiting). stdout and stderr
|
||||
* come back together, in order, cut at `max_output_bytes`. Past its
|
||||
* come back together, each in its own order (they are two pipes, read as
|
||||
* they arrive, so neither is held back for the other), cut at
|
||||
* `max_output_bytes`. Past its
|
||||
* timeout (when it has one), or when aborted, the whole group gets TERM,
|
||||
* then KILL 5s later. It resolves when bash exits, not when every pipe
|
||||
* closes, so work left in the background (`nohup ... &`) keeps running
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.24.7",
|
||||
"version": "0.25.0",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/h
|
||||
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
|
||||
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
|
||||
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
|
||||
import stripCardRefs from "@/src/utils/strip-card-refs";
|
||||
import describeAttachment from "./describe-attachment";
|
||||
import crewMessageBlock from "@/src/utils/crew-message-block";
|
||||
|
||||
@@ -106,8 +107,16 @@ function messageParts({
|
||||
}
|
||||
|
||||
const own = message.text?.trim() || "";
|
||||
/**
|
||||
* The refs of the app's own cards (`[question:]`, `[suggestion:]`,
|
||||
* `[plan:]`) are added to a stored message after the model wrote it, so
|
||||
* replaying them as the bot's own words is what taught it to write
|
||||
* `[question:24]` itself (session 146, job 785). They come out of the
|
||||
* bot's history here; the message the user reads keeps them.
|
||||
*/
|
||||
const said = role == "assistant" && own ? stripCardRefs({ text: own }) : own;
|
||||
const mentions = role == "user" && refs && own ? describeMessageRefs({ text: own, names: refs }) : "";
|
||||
const text = replyContext({ message, text: mentions ? `${own}\n\n${mentions}` : own });
|
||||
const text = replyContext({ message, text: mentions ? `${said}\n\n${mentions}` : said });
|
||||
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
|
||||
|
||||
if (role == "assistant") {
|
||||
|
||||
@@ -2,7 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
import grabBotAudience from "@/src/functions/backend/db/access/grab-bot-audience";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
|
||||
import grabActiveBotTasks from "@/src/functions/backend/db/bots/grab-active-bot-tasks";
|
||||
import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
|
||||
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
|
||||
|
||||
@@ -89,6 +89,12 @@ async function push({
|
||||
for (const viewer_id of audience) {
|
||||
if (users && !users.has(String(viewer_id))) continue;
|
||||
|
||||
/**
|
||||
* Read per viewer, and every one of them: the push can't know which
|
||||
* conversation is open, so the page picks its own task out.
|
||||
*/
|
||||
const tasks = await grabActiveBotTasks({ bot_id, user_id: viewer_id });
|
||||
|
||||
sendToUser({
|
||||
user_id: viewer_id,
|
||||
data: {
|
||||
@@ -102,7 +108,8 @@ async function push({
|
||||
admin_workspace_ids,
|
||||
...(computer_id !== undefined ? { computer_id: computer_id || null } : {}),
|
||||
...(workspace_ids !== undefined ? { workspace_ids } : {}),
|
||||
task: await grabActiveBotTask({ bot_id, user_id: viewer_id }),
|
||||
task: tasks[0] || null,
|
||||
tasks,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-
|
||||
import { taskRowSql } from "@/src/functions/backend/db/tasks/run-task-sql";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotGraphic from "@/src/functions/backend/db/bot-graphics/grab-bot-graphic";
|
||||
import grabExtensionProposal from "@/src/functions/backend/db/extension-proposals/grab-extension-proposal";
|
||||
import grabHookProposal from "@/src/functions/backend/db/hook-proposals/grab-hook-proposal";
|
||||
import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
@@ -83,6 +85,28 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
if (!(await grabBotGraphic({ graphic_id, user_id }))) missing_graphic_ids.push(graphic_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* A proposal ref names the card it makes, so it only exists once that
|
||||
* card does: a number the model guessed describes a proposal the user
|
||||
* never got. A row made to someone else doesn't open for this user
|
||||
* either, so the lookup is by user, like the file check.
|
||||
*/
|
||||
const missing_proposal_ids: number[] = [];
|
||||
|
||||
for (const proposal_id of replyRefIds({ text, kind: "proposal" })) {
|
||||
const row = await grabExtensionProposal({ proposal_id, user_id }).catch(() => null);
|
||||
|
||||
if (!row) missing_proposal_ids.push(proposal_id);
|
||||
}
|
||||
|
||||
const missing_hook_proposal_ids: number[] = [];
|
||||
|
||||
for (const proposal_id of replyRefIds({ text, kind: "hook-proposal" })) {
|
||||
const row = await grabHookProposal({ proposal_id, user_id }).catch(() => null);
|
||||
|
||||
if (!row) missing_hook_proposal_ids.push(proposal_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The cards the app adds under the message itself: any ref of theirs in
|
||||
* the answer was written by the model, since the app's own refs are
|
||||
@@ -100,6 +124,8 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
missing_mentioned_task_ids,
|
||||
unresolved_setting_refs: unresolvedSettingRefs({ text }),
|
||||
missing_graphic_ids,
|
||||
missing_proposal_ids,
|
||||
missing_hook_proposal_ids,
|
||||
written_card_refs,
|
||||
has_open_work: await hasOpenWork({ bot_id, session_id, exclude_job_id: job_id }),
|
||||
status,
|
||||
|
||||
@@ -68,7 +68,8 @@ export const chatReplyNote = ({ bot_id }: { bot_id: number | string }) => `# Rep
|
||||
|
||||
You are chatting with the user. Answer their latest messages directly and briefly, in markdown.
|
||||
|
||||
- Every reply ends with send_reply. The text beside it is the message the user reads; a turn that writes text without it is a draft and is never sent.
|
||||
- Every reply ends with send_reply. Write the message beside it, or pass it as its message argument; a turn that writes text without it is a draft and is never sent.
|
||||
- A card's ref ([question:], [suggestion:], [plan:], [proposal:]) is written by the app from the tool that made the card, never by you. A ref you type names no card, and the user reads "not available": call ask_user, suggest_next_steps, create_plan or the propose_ tool and say in words what you mean. A proposal exists only once that tool returned one.
|
||||
- send_reply({status:"done"}) for a quick answer or a small change that needs nothing after it.
|
||||
- send_reply({status:"working", work:{title, instructions, computer_id?}}) for work that takes more than a moment, or anything on a computer (running commands, editing files, browsing). The app queues the run before your message goes out; a task you start is your own work, so never say you handed it to anyone else. Its result is posted here when it's done.
|
||||
- send_reply({status:"blocked"}) when the work can't go on; say why in the message.
|
||||
@@ -88,7 +89,7 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just queued a run (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
|
||||
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. If the card was put up in the turn that wrote the message, that message is kept, so send_reply needs no text beside it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
|
||||
## Ending the reply
|
||||
|
||||
@@ -507,27 +508,27 @@ export const closingNoTextNote = `The card you just put up has no message beside
|
||||
* never queued. Bounded by `AppData.HarnessReplyDraftsMax`, then the run
|
||||
* fails honestly rather than sending it.
|
||||
*/
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write it again beside send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. The text beside the call is what the user reads.`;
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply, beside it or as its message argument: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` worked but the turn said nothing beside it: the
|
||||
* user would get an empty line, and the status alone is not a message.
|
||||
*/
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so the user would get an empty line. Write the message beside send_reply now and call it again: status "done", "working" (with work, or after a run you started) or "blocked".`;
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. Nothing written in an earlier turn is sent in its place: write the whole message again beside send_reply, or pass it as its message argument, and call it again with status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
|
||||
|
||||
/**
|
||||
* Told when a turn tried to end without `send_reply` at all: a card alone or
|
||||
* a closing tool that isn't `send_reply` doesn't say whether work is
|
||||
* running, and its text is a draft.
|
||||
*/
|
||||
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running.`;
|
||||
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running. A message you wrote in that same turn as the card is kept, so send_reply alone sends it.`;
|
||||
|
||||
/**
|
||||
* Told when a turn called `send_reply` beside other tools: only its own turn
|
||||
* can send the message, since the other calls' results go into the
|
||||
* conversation after it.
|
||||
*/
|
||||
export const replyClosingMixedNote = `send_reply has to be the only call in its turn: this turn also did other work, so the message was not sent. Call send_reply on its own with the message beside it, after the tools you still need have run.`;
|
||||
export const replyClosingMixedNote = `send_reply's turn can also call suggest_next_steps or ask_user, and nothing else: this turn did other work, so the message was not sent. Finish that work first, then call send_reply with the whole message beside it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` itself refused the turn (status "working" with
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import { BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import { BotComputerBusyStatusLine, BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import setBotFace from "../bots/set-bot-face";
|
||||
import answeringAskFace from "./answering-ask-face";
|
||||
import botWaitsOnComputer from "./bot-waits-on-computer";
|
||||
import countOpenBotJobs from "./count-open-bot-jobs";
|
||||
import grabRunningBotJobFace from "./grab-running-bot-job-face";
|
||||
|
||||
@@ -42,14 +43,16 @@ export default async function botFaceAfterJob({ bot_id, user_id, kind }: Params)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Jobs are open for this user but none is running: they wait in the
|
||||
* queue, behind another run on the same computer or while every model
|
||||
* rests (`deferBotJob`). The line says which, since "waiting for a free
|
||||
* model" over a run that is only second in line on a computer sends the
|
||||
* user looking at the wrong thing.
|
||||
*/
|
||||
return await setBotFace({
|
||||
bot_id,
|
||||
user_id,
|
||||
face: "asleep",
|
||||
status_line: BotWaitingStatusLine,
|
||||
status_line: (await botWaitsOnComputer({ bot_id, user_id })) ? BotComputerBusyStatusLine : BotWaitingStatusLine,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import { botWaitsOnComputerSql } from "./bot-waits-on-computer";
|
||||
|
||||
/**
|
||||
* Real SQLite: the face says "Waiting for its computer" only while a run
|
||||
* of this bot's user's is queued behind another task on that same
|
||||
* computer. Anything looser reads every queued run as a computer wait.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
beforeEach(() => {
|
||||
db.run(`DROP TABLE IF EXISTS bots_queue`);
|
||||
db.run(`DROP TABLE IF EXISTS bot_sessions`);
|
||||
db.run(`DROP TABLE IF EXISTS bot_hooks`);
|
||||
db.run(`CREATE TABLE bots_queue (
|
||||
id INTEGER PRIMARY KEY,
|
||||
kind TEXT,
|
||||
status TEXT,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
computer_id INTEGER
|
||||
)`);
|
||||
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, user_id INTEGER, ask_id INTEGER, hook_id INTEGER)`);
|
||||
db.run(`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`);
|
||||
});
|
||||
|
||||
function job(row: { id: number; kind: string; status: string; session_id: number; computer_id?: number | null }) {
|
||||
db.run(`INSERT INTO bots_queue (id, kind, status, bot_id, session_id, computer_id) VALUES (?, ?, ?, 1, ?, ?)`, [
|
||||
row.id,
|
||||
row.kind,
|
||||
row.status,
|
||||
row.session_id,
|
||||
row.computer_id ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
const waits = () => {
|
||||
const { sql, values } = botWaitsOnComputerSql({ bot_id: 1, user_id: 1 });
|
||||
|
||||
return db.query(sql).all(...values).length > 0;
|
||||
};
|
||||
|
||||
describe("botWaitsOnComputerSql", () => {
|
||||
test("a queued run behind a task on the same computer is waiting on it", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 4 });
|
||||
|
||||
expect(waits()).toBe(true);
|
||||
});
|
||||
|
||||
test("a queued run on another computer is not", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 5 });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
|
||||
test("no reason yet is not a computer wait", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "reply", status: "pending", session_id: 10, computer_id: null });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
|
||||
test("another user's queue does not show on this face", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 2, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 4 });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
|
||||
test("a queued run in a crew request or a silent hook's thread is not the user's wait", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
db.run(`INSERT INTO bot_sessions VALUES (11, 1, 3, NULL)`);
|
||||
db.run(`INSERT INTO bot_hooks VALUES (2, 1)`);
|
||||
db.run(`INSERT INTO bot_sessions VALUES (12, 1, NULL, 2)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 11, computer_id: 4 });
|
||||
job({ id: 3, kind: "task", status: "pending", session_id: 12, computer_id: 4 });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* Only jobs in this user's conversations.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a run of the bot's is queued behind another on the same computer.
|
||||
* `claimBotJobs` takes one task run per computer at a time, so a second one
|
||||
* waits for the first to end, however long that takes: with no job
|
||||
* processing, the bot's face said "waiting for a free model" when what it
|
||||
* waits on is the computer. Only jobs the user follows count, since a crew
|
||||
* request's or a silent hook's run never shows on the face.
|
||||
*/
|
||||
export default async function botWaitsOnComputer({ bot_id, user_id }: Params): Promise<boolean> {
|
||||
const res = await BunSQLite.sql<{ waiting: number }>(botWaitsOnComputerSql({ bot_id, user_id }));
|
||||
|
||||
return Boolean(res.payload?.[0]?.waiting);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement itself, checked against real SQLite
|
||||
* (`bot-waits-on-computer.test.ts`).
|
||||
*/
|
||||
export function botWaitsOnComputerSql({ bot_id, user_id }: Params) {
|
||||
return {
|
||||
sql: `SELECT 1 AS waiting FROM bots_queue AS queued
|
||||
WHERE queued.bot_id = ? AND queued.status = 'pending'
|
||||
AND queued.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM bots_queue AS running
|
||||
WHERE running.status = 'processing' AND running.kind = 'task'
|
||||
AND running.computer_id = queued.computer_id
|
||||
)
|
||||
LIMIT 1`,
|
||||
values: [bot_id, user_id],
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import AppError from "@/src/utils/app-error";
|
||||
import grabUserBot from "../bots/grab-user-bot";
|
||||
import grabBotComputers from "../computers/grab-bot-computers";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import pushBotUpdated from "@/src/bots-queue/push-bot-updated";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -160,6 +162,18 @@ export default async function enqueueBotJob({
|
||||
throw new Error(`Couldn't queue the job: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The queue starts on this job now instead of at its next tick, and the
|
||||
* user is told about the run straight away: the bot's face and every
|
||||
* active task are pushed, so a queued run shows as one instead of
|
||||
* appearing when the queue happens to claim it (a run waiting behind
|
||||
* another on the same computer waits for that one to end). Best effort:
|
||||
* the push logs its own failure, and a queue not running in this process
|
||||
* picks the job up on its next poll.
|
||||
*/
|
||||
wakeBotsQueue();
|
||||
await pushBotUpdated({ bot_id: Number(bot.id), user_id: Number(user_id) });
|
||||
|
||||
return job_id;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,9 +25,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Wraps up a job that is out of attempts: stamps `finished_at` (so it's
|
||||
* reported once), tells the user in the bot's conversation and sets the
|
||||
* bot to needs-you for that user. Its task stays active, since the work isn't done. A
|
||||
* handed-over job's failure also goes to the bot that handed it over, and
|
||||
* reported once), closes its own `bot_tasks` row, tells the user in the
|
||||
* bot's conversation and sets the bot to needs-you for that user. A handed-over job's failure also goes to the bot that handed it over, and
|
||||
* blocks the handed-over task it worked on (`noteTrackerTask`). A hook run's
|
||||
* calls keep why it failed (`recordHookCallResponse`). A job working a crew request ends it
|
||||
* (`onAskJobEnded`) and leaves the bot's face alone.
|
||||
@@ -45,6 +44,20 @@ export default async function notifyBotJobFailed({
|
||||
values: [Date.now(), job.id],
|
||||
});
|
||||
|
||||
/**
|
||||
* The run's own row is over too: left active it is the task every read
|
||||
* of `grabActiveBotTask` returns for that user, so the conversation
|
||||
* keeps showing a run that ended (one failed task in October was still
|
||||
* the active task of its conversation months later), and no later run's
|
||||
* progress could show in its place.
|
||||
*/
|
||||
if (job.task_id) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
|
||||
values: [Date.now(), job.task_id],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A handed-over task's failed run links to that task.
|
||||
*/
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_BOT_TASK_STEPS,
|
||||
BUN_SQLITE_COBBLE_BOT_TASKS,
|
||||
} from "@/db/types/db";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
|
||||
import type { BotTaskWithSteps } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotJobUpdates from "../bots-queue/grab-bot-job-updates";
|
||||
import withBotTaskSteps from "./with-bot-task-steps";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -21,7 +18,9 @@ type Params = {
|
||||
/**
|
||||
* The bot's most recent active task (in one session or one user's
|
||||
* conversations, when given), its
|
||||
* steps and what its job has done so far, for the working-on panel.
|
||||
* steps and what its job has done so far, for the working-on panel. A push
|
||||
* sends every active task instead (`grabActiveBotTasks`), since this one
|
||||
* may belong to a conversation the viewer isn't reading.
|
||||
*/
|
||||
export default async function grabActiveBotTask({
|
||||
bot_id,
|
||||
@@ -42,14 +41,5 @@ export default async function grabActiveBotTask({
|
||||
return null;
|
||||
}
|
||||
|
||||
const steps_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASK_STEPS>({
|
||||
sql: `SELECT * FROM bot_task_steps WHERE task_id = ? ORDER BY position ASC, id ASC`,
|
||||
values: [task.id],
|
||||
});
|
||||
|
||||
return {
|
||||
...task,
|
||||
steps: steps_res.payload || [],
|
||||
updates: await grabBotJobUpdates({ task_id: task.id }),
|
||||
};
|
||||
}
|
||||
return withBotTaskSteps({ task });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
|
||||
import type { BotTaskWithSteps } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import withBotTaskSteps from "./with-bot-task-steps";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* Only tasks in this user's conversations.
|
||||
*/
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many active tasks a push carries. A bot has at most one run per
|
||||
* computer and one reply per session, so a handful of conversations are
|
||||
* ever running at once; the newest few are enough for a viewer to find its
|
||||
* own, and a list that grows with the whole crew's history is not.
|
||||
*/
|
||||
const BotActiveTasksShown = 10;
|
||||
|
||||
/**
|
||||
* Every active task the user has with the bot, newest first. A push can't
|
||||
* know which conversation the viewer is looking at, and sending only the
|
||||
* newest left the one they were reading with no task at all whenever
|
||||
* another run was open elsewhere (`use-task-progress` drops a task from
|
||||
* another session), so the page is sent them all and picks its own.
|
||||
*/
|
||||
export default async function grabActiveBotTasks({ bot_id, user_id }: Params): Promise<BotTaskWithSteps[]> {
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASKS>({
|
||||
sql: `SELECT * FROM bot_tasks WHERE bot_id = ? AND status = 'active'
|
||||
${user_id ? `AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ?)` : ""}
|
||||
ORDER BY created_at DESC, id DESC LIMIT ${BotActiveTasksShown}`,
|
||||
values: [bot_id, ...(user_id ? [user_id] : [])],
|
||||
});
|
||||
|
||||
const tasks = res.payload || [];
|
||||
|
||||
return await Promise.all(tasks.map((task) => withBotTaskSteps({ task })));
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_TASK_STEPS, BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
|
||||
import type { BotTaskWithSteps } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotJobUpdates from "../bots-queue/grab-bot-job-updates";
|
||||
|
||||
type Params = {
|
||||
task: BUN_SQLITE_COBBLE_BOT_TASKS;
|
||||
};
|
||||
|
||||
/**
|
||||
* A `bot_tasks` row with its steps and what its job has done so far, for
|
||||
* the working-on panel: what one active task is read as, whether it's the
|
||||
* newest of its bot or one of several in different conversations.
|
||||
*/
|
||||
export default async function withBotTaskSteps({ task }: Params): Promise<BotTaskWithSteps> {
|
||||
const steps_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASK_STEPS>({
|
||||
sql: `SELECT * FROM bot_task_steps WHERE task_id = ? ORDER BY position ASC, id ASC`,
|
||||
values: [Number(task.id)],
|
||||
});
|
||||
|
||||
return {
|
||||
...task,
|
||||
steps: steps_res.payload || [],
|
||||
updates: await grabBotJobUpdates({ task_id: Number(task.id) }),
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import checkProposalData from "./check-proposal-data";
|
||||
import claimExtensionProposal from "./claim-extension-proposal";
|
||||
import grabExtensionProposal from "./grab-extension-proposal";
|
||||
import grabProposalEnvs from "./grab-proposal-envs";
|
||||
import replacePendingExtensionProposals from "./replace-pending-extension-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -34,6 +35,24 @@ export default async function confirmExtensionProposal({ user_id, proposal_id }:
|
||||
|
||||
await claimExtensionProposal({ proposal, status: "confirmed" });
|
||||
|
||||
/**
|
||||
* Every other pending card for the same thing is replaced now that one
|
||||
* was confirmed: a card left pending can still be pressed, and its
|
||||
* outcome is already written (proposal #41 dangled a day after #42
|
||||
* made the same skill).
|
||||
*/
|
||||
await replacePendingExtensionProposals({
|
||||
proposal_id: proposal.id,
|
||||
user_id: proposal.user_id,
|
||||
bot_id: proposal.bot_id,
|
||||
workspace_id: proposal.workspace_id,
|
||||
kind: proposal.kind,
|
||||
slug: proposal.kind == "skill" ? proposal.data.slug : null,
|
||||
extension_id: proposal.extension_id,
|
||||
name: proposal.data.name,
|
||||
reason: `Replaced by proposal #${proposal.id}, which was confirmed.`,
|
||||
});
|
||||
|
||||
try {
|
||||
if (proposal.kind == "skill") {
|
||||
const current = proposal.extension_id ? await grabSkill({ skill_id: proposal.extension_id }) : null;
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS, BunSQLiteTables } from "@/d
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { SaveCustomToolRequest, SaveMcpServerRequest, SaveSkillRequest } from "@/src/schemas/extension-schema";
|
||||
import checkProposalData from "./check-proposal-data";
|
||||
import replacePendingExtensionProposals from "./replace-pending-extension-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -21,9 +22,9 @@ type Params = {
|
||||
* Stores what a bot proposes adding or changing (an MCP server, a tool or
|
||||
* a skill), pending until the user
|
||||
* confirms it from the chat. Nothing is saved, connected or run here. A
|
||||
* proposal it makes again for the same server or tool in the same
|
||||
* conversation replaces the one before, so only the latest card can be
|
||||
* confirmed. Returns its id.
|
||||
* proposal it makes again for the same thing in the same conversation
|
||||
* replaces the one before, so only the latest card can be confirmed.
|
||||
* Returns its id.
|
||||
*/
|
||||
export default async function createExtensionProposal(params: Params) {
|
||||
if (params.kind != "skill") checkProposalData(params);
|
||||
@@ -61,19 +62,15 @@ export default async function createExtensionProposal(params: Params) {
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the proposal: ${res.msg}`);
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE extension_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE session_id = ? AND kind = ? AND status = 'pending' AND id != ?
|
||||
AND (${extension_id ? "extension_id = ?" : "extension_id IS NULL AND name = ? COLLATE NOCASE"})`,
|
||||
values: [
|
||||
`Replaced by proposal #${id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(params.session_id),
|
||||
params.kind,
|
||||
id,
|
||||
extension_id || params.data.name,
|
||||
],
|
||||
await replacePendingExtensionProposals({
|
||||
proposal_id: id,
|
||||
user_id: params.user_id,
|
||||
bot_id: params.bot_id,
|
||||
workspace_id: params.workspace_id,
|
||||
kind: params.kind,
|
||||
slug: params.kind == "skill" ? params.data.slug : null,
|
||||
extension_id,
|
||||
name: params.data.name,
|
||||
});
|
||||
|
||||
return id;
|
||||
|
||||
@@ -28,6 +28,7 @@ export type ExtensionProposalRecord = {
|
||||
user_id: number;
|
||||
bot_id: number;
|
||||
session_id: number;
|
||||
workspace_id: number | null;
|
||||
} & (
|
||||
| { kind: "mcp"; data: SaveMcpServerRequest }
|
||||
| { kind: "tool"; data: SaveCustomToolRequest }
|
||||
@@ -54,6 +55,7 @@ export default function parseProposalRow({ row }: Params): ExtensionProposalReco
|
||||
user_id: Number(row.user_id),
|
||||
bot_id: Number(row.bot_id),
|
||||
session_id: Number(row.session_id),
|
||||
workspace_id: row.workspace_id ? Number(row.workspace_id) : null,
|
||||
};
|
||||
|
||||
if (kind == "mcp") return { ...base, kind, data: parseWithSchema({ schema: SaveMcpServerRequestSchema, data: raw }) };
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
import { Database, type SQLQueryBindings } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { replacePendingExtensionProposalsSql } from "./replace-pending-extension-proposals";
|
||||
|
||||
/**
|
||||
* Run against real SQLite: the point of the statement is which rows it
|
||||
* leaves alone. Production kept proposal #41 (Co-Marketing, session 145)
|
||||
* pending for ever while #42 made the same skill in session 146, and
|
||||
* RevOps was proposed four times under two names, all slug `revops`.
|
||||
*/
|
||||
function fresh() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE extension_proposals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT,
|
||||
data TEXT,
|
||||
extension_id INTEGER,
|
||||
kind TEXT,
|
||||
status TEXT,
|
||||
outcome TEXT,
|
||||
decided_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
user_id INTEGER,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
workspace_id INTEGER
|
||||
)`);
|
||||
|
||||
const insert = db.prepare(`INSERT INTO extension_proposals
|
||||
(id, name, data, extension_id, kind, status, user_id, bot_id, session_id, workspace_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
|
||||
insert.run(41, "Co-Marketing", `{"slug":"co-marketing"}`, null, "skill", "pending", 1, 1, 145, null);
|
||||
insert.run(42, "Co-Marketing", `{"slug":"co-marketing"}`, null, "skill", "confirmed", 1, 1, 146, null);
|
||||
insert.run(43, "Referrals & Affiliates", `{"slug":"referrals"}`, null, "skill", "confirmed", 1, 1, 145, null);
|
||||
insert.run(44, "Referrals", `{"slug":"referrals"}`, null, "skill", "failed", 1, 1, 146, null);
|
||||
insert.run(62, "RevOps", `{"slug":"revops"}`, null, "skill", "pending", 1, 1, 146, null);
|
||||
insert.run(63, "Revenue Operations (RevOps)", `{"slug":"revops"}`, null, "skill", "confirmed", 1, 1, 146, null);
|
||||
insert.run(70, "Lead Magnets", `{"slug":"lead-magnets"}`, null, "skill", "pending", 1, 1, 146, null);
|
||||
insert.run(71, "Link Building", `{"slug":"link-building"}`, 12, "skill", "pending", 1, 1, 146, null);
|
||||
insert.run(72, "Some Server", `{}`, null, "mcp", "pending", 1, 1, 146, null);
|
||||
insert.run(73, "Some Server", `{}`, null, "mcp", "pending", 2, 1, 146, null);
|
||||
insert.run(74, "Some Server", `{}`, null, "mcp", "pending", 1, 1, 146, 3);
|
||||
insert.run(75, "Fetch Tool", `{}`, null, "tool", "pending", 1, 1, 146, null);
|
||||
insert.run(76, "Changed Tool", `{}`, 9, "tool", "pending", 1, 1, 146, null);
|
||||
insert.run(77, "Another Tool", `{}`, 10, "tool", "pending", 1, 1, 146, null);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
function replace(
|
||||
db: Database,
|
||||
params: Parameters<typeof replacePendingExtensionProposalsSql>[0],
|
||||
) {
|
||||
const { sql, values } = replacePendingExtensionProposalsSql(params);
|
||||
|
||||
db.run(sql, values as SQLQueryBindings[]);
|
||||
}
|
||||
|
||||
const statuses = (db: Database) =>
|
||||
Object.fromEntries(
|
||||
(db.query(`SELECT id, status FROM extension_proposals`).all() as { id: number; status: string }[]).map((row) => [
|
||||
row.id,
|
||||
row.status,
|
||||
]),
|
||||
);
|
||||
|
||||
describe("replacePendingExtensionProposalsSql", () => {
|
||||
test("replaces a skill proposed again in a later session of the same conversation", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 63,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "skill",
|
||||
slug: "revops",
|
||||
name: "Revenue Operations (RevOps)",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[62]).toBe("replaced");
|
||||
expect(status[63]).toBe("confirmed");
|
||||
expect(status[70]).toBe("pending");
|
||||
expect(status[41]).toBe("pending");
|
||||
});
|
||||
|
||||
test("does not mark a skill's proposal replaced by another skill's", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 70,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "skill",
|
||||
slug: "lead-magnets",
|
||||
name: "Lead Magnets",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[62]).toBe("pending");
|
||||
expect(status[71]).toBe("pending");
|
||||
expect(Object.values(status).filter((value) => value == "replaced")).toEqual([]);
|
||||
});
|
||||
|
||||
test("a server compares the name when the proposal changes nothing yet", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 78,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "mcp",
|
||||
name: "Some Server",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[72]).toBe("replaced");
|
||||
expect(status[73]).toBe("pending");
|
||||
expect(status[74]).toBe("pending");
|
||||
});
|
||||
|
||||
test("a tool compares the extension it changes", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 78,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "tool",
|
||||
extension_id: 9,
|
||||
name: "Changed Tool",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[76]).toBe("replaced");
|
||||
expect(status[75]).toBe("pending");
|
||||
expect(status[77]).toBe("pending");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/** The proposal just stored, or just confirmed. */
|
||||
proposal_id: number | string;
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
kind: "mcp" | "tool" | "skill";
|
||||
/**
|
||||
* A skill's slug: it names the one skill a proposal is about, including
|
||||
* one that doesn't exist yet, and is what makes two of them the same.
|
||||
*/
|
||||
slug?: string | null;
|
||||
/**
|
||||
* The extension a proposal changes; a new one has none.
|
||||
*/
|
||||
extension_id?: number | string | null;
|
||||
name: string;
|
||||
/**
|
||||
* What the replaced card says, when it wasn't a newer proposal that
|
||||
* took its place.
|
||||
*/
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks every pending proposal for the same thing replaced, in the same
|
||||
* conversation: only the latest card can be confirmed, and an older one
|
||||
* left pending is a card the user can still press whose outcome is already
|
||||
* written. Scoped by user, bot and workspace rather than by session, since
|
||||
* a conversation that carries on into a new session keeps proposing into
|
||||
* it: proposal #41 (Co-Marketing, session 145) was made again 36 seconds
|
||||
* later in session 146 and confirmed there, and #41 stayed pending for
|
||||
* ever. For a skill the slug decides it (RevOps was proposed four times
|
||||
* under two names, all slug `revops`); for a server or tool it is the
|
||||
* extension itself, else the name.
|
||||
*/
|
||||
export default async function replacePendingExtensionProposals({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
kind,
|
||||
slug,
|
||||
extension_id,
|
||||
name,
|
||||
reason,
|
||||
}: Params) {
|
||||
const { sql, values } = replacePendingExtensionProposalsSql({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
kind,
|
||||
slug,
|
||||
extension_id,
|
||||
name,
|
||||
reason,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql, values });
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement itself, so the conditions are checked against real SQLite
|
||||
* (`replace-pending-extension-proposals.test.ts`): a wrong one either
|
||||
* leaves a card the user can still press or replaces a different skill's.
|
||||
*/
|
||||
export function replacePendingExtensionProposalsSql({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
kind,
|
||||
slug,
|
||||
extension_id,
|
||||
name,
|
||||
reason,
|
||||
}: Params) {
|
||||
const now = Date.now();
|
||||
const target = targetSql({ slug, extension_id, name });
|
||||
|
||||
return {
|
||||
sql: `UPDATE extension_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE user_id = ? AND bot_id = ? AND COALESCE(workspace_id, 0) = ? AND kind = ?
|
||||
AND status = 'pending' AND id != ?
|
||||
AND ${target.sql}`,
|
||||
values: [
|
||||
reason || `Replaced by proposal #${proposal_id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(user_id),
|
||||
Number(bot_id),
|
||||
Number(workspace_id) || 0,
|
||||
kind,
|
||||
Number(proposal_id),
|
||||
target.value,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes two proposals about the same thing: a skill's slug, the
|
||||
* extension being changed, or a new one's name compared with spaces,
|
||||
* hyphens and underscores taken out ("Rev Ops" and "rev-ops" are one name).
|
||||
*/
|
||||
function targetSql({ slug, extension_id, name }: { slug?: string | null; extension_id?: number | string | null; name: string }) {
|
||||
const skill_slug = slug?.trim().toLowerCase() || "";
|
||||
|
||||
if (skill_slug) return { sql: "lower(json_extract(data, '$.slug')) = ?", value: skill_slug };
|
||||
|
||||
if (extension_id) return { sql: "extension_id = ?", value: Number(extension_id) };
|
||||
|
||||
return {
|
||||
sql: "extension_id IS NULL AND lower(replace(replace(replace(trim(name), ' ', ''), '-', ''), '_', '')) = ?",
|
||||
value: name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[ _-]+/g, ""),
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import updateBotHook from "../bot-hooks/update-bot-hook";
|
||||
import checkHookProposal from "./check-hook-proposal";
|
||||
import claimHookProposal from "./claim-hook-proposal";
|
||||
import grabHookProposal from "./grab-hook-proposal";
|
||||
import replacePendingHookProposals from "./replace-pending-hook-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -27,6 +28,16 @@ export default async function confirmHookProposal({ user_id, proposal_id }: Para
|
||||
|
||||
await claimHookProposal({ proposal, status: "confirmed" });
|
||||
|
||||
await replacePendingHookProposals({
|
||||
proposal_id: proposal.id,
|
||||
user_id: proposal.user_id,
|
||||
bot_id: proposal.bot_id,
|
||||
workspace_id: proposal.workspace_id,
|
||||
hook_id: proposal.hook_id,
|
||||
title: proposal.title,
|
||||
reason: `Replaced by proposal #${proposal.id}, which was confirmed.`,
|
||||
});
|
||||
|
||||
let token: string | undefined;
|
||||
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_HOOK_PROPOSALS, BunSQLiteTables } from "@/db/typ
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HookProposalData } from "@/src/schemas/bot-hook-schema";
|
||||
import checkHookProposal from "./check-hook-proposal";
|
||||
import replacePendingHookProposals from "./replace-pending-hook-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -60,18 +61,13 @@ export default async function createHookProposal({
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the proposal: ${res.msg}`);
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE hook_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE session_id = ? AND status = 'pending' AND id != ?
|
||||
AND (${checked.current?.id ? "hook_id = ?" : "hook_id IS NULL AND title = ? COLLATE NOCASE"})`,
|
||||
values: [
|
||||
`Replaced by proposal #${id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(session_id),
|
||||
id,
|
||||
checked.current?.id || checked.title,
|
||||
],
|
||||
await replacePendingHookProposals({
|
||||
proposal_id: id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
hook_id: checked.current?.id,
|
||||
title: checked.title,
|
||||
});
|
||||
|
||||
return id;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Database, type SQLQueryBindings } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { replacePendingHookProposalsSql } from "./replace-pending-hook-proposals";
|
||||
|
||||
/**
|
||||
* A conversation carried into a new session keeps proposing into it, so a
|
||||
* pending card for the same hook (or the same new name) is marked replaced
|
||||
* across sessions, never left for the user to press after its outcome was
|
||||
* written.
|
||||
*/
|
||||
function fresh() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE hook_proposals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
hook_id INTEGER,
|
||||
title TEXT,
|
||||
status TEXT,
|
||||
outcome TEXT,
|
||||
decided_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
user_id INTEGER,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
workspace_id INTEGER
|
||||
)`);
|
||||
|
||||
const insert = db.prepare(`INSERT INTO hook_proposals
|
||||
(id, hook_id, title, status, user_id, bot_id, session_id, workspace_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
|
||||
insert.run(1, null, "Inbox Digest", "pending", 1, 1, 145, null);
|
||||
insert.run(2, null, "inbox digest", "pending", 1, 1, 146, null);
|
||||
insert.run(3, null, "Inbox Digest", "confirmed", 1, 1, 146, null);
|
||||
insert.run(4, 7, "Nightly Build", "pending", 1, 1, 146, null);
|
||||
insert.run(5, 8, "Nightly Build", "pending", 1, 1, 146, null);
|
||||
insert.run(6, null, "Inbox Digest", "pending", 2, 1, 146, null);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
function replace(db: Database, params: Parameters<typeof replacePendingHookProposalsSql>[0]) {
|
||||
const { sql, values } = replacePendingHookProposalsSql(params);
|
||||
|
||||
db.run(sql, values as SQLQueryBindings[]);
|
||||
}
|
||||
|
||||
const statuses = (db: Database) =>
|
||||
Object.fromEntries(
|
||||
(db.query(`SELECT id, status FROM hook_proposals`).all() as { id: number; status: string }[]).map((row) => [
|
||||
row.id,
|
||||
row.status,
|
||||
]),
|
||||
);
|
||||
|
||||
describe("replacePendingHookProposalsSql", () => {
|
||||
test("replaces a new hook proposed again under the same name in a later session", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, { proposal_id: 2, user_id: 1, bot_id: 1, title: "inbox digest" });
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[1]).toBe("replaced");
|
||||
expect(status[3]).toBe("confirmed");
|
||||
expect(status[6]).toBe("pending");
|
||||
expect(status[4]).toBe("pending");
|
||||
});
|
||||
|
||||
test("a hook that exists is compared by the hook, not by its title", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, { proposal_id: 9, user_id: 1, bot_id: 1, hook_id: 7, title: "Nightly Build" });
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[4]).toBe("replaced");
|
||||
expect(status[5]).toBe("pending");
|
||||
expect(status[1]).toBe("pending");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/** The proposal just stored, or just confirmed. */
|
||||
proposal_id: number | string;
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* The hook it changes; none for a new one.
|
||||
*/
|
||||
hook_id?: number | string | null;
|
||||
title: string;
|
||||
/**
|
||||
* What the replaced card says, when it wasn't a newer proposal that
|
||||
* took its place.
|
||||
*/
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks every pending hook proposal for the same hook, or the same new
|
||||
* name, replaced: only the latest card can be confirmed. Scoped by user,
|
||||
* bot and workspace rather than by session, the same way an extension
|
||||
* proposal is (`replacePendingExtensionProposals`), since a conversation
|
||||
* carried into a new session keeps proposing into it.
|
||||
*/
|
||||
export default async function replacePendingHookProposals({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
hook_id,
|
||||
title,
|
||||
reason,
|
||||
}: Params) {
|
||||
await BunSQLite.sql(
|
||||
replacePendingHookProposalsSql({ proposal_id, user_id, bot_id, workspace_id, hook_id, title, reason }),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement itself, checked against real SQLite
|
||||
* (`replace-pending-hook-proposals.test.ts`).
|
||||
*/
|
||||
export function replacePendingHookProposalsSql({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
hook_id,
|
||||
title,
|
||||
reason,
|
||||
}: Params) {
|
||||
const now = Date.now();
|
||||
const changed = Boolean(Number(hook_id));
|
||||
|
||||
return {
|
||||
sql: `UPDATE hook_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE user_id = ? AND bot_id = ? AND COALESCE(workspace_id, 0) = ?
|
||||
AND status = 'pending' AND id != ?
|
||||
AND (${changed ? "hook_id = ?" : "hook_id IS NULL AND lower(replace(replace(replace(trim(title), ' ', ''), '-', ''), '_', '')) = ?"})`,
|
||||
values: [
|
||||
reason || `Replaced by proposal #${proposal_id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(user_id),
|
||||
Number(bot_id),
|
||||
Number(workspace_id) || 0,
|
||||
Number(proposal_id),
|
||||
changed
|
||||
? Number(hook_id)
|
||||
: title
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[ _-]+/g, ""),
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,7 @@ type ComputerLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & {
|
||||
|
||||
type WorkspaceLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
|
||||
workspace_name?: string | null;
|
||||
image_media_id?: number | null;
|
||||
};
|
||||
|
||||
type CheckRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS;
|
||||
@@ -61,7 +62,8 @@ export default async function grabHostDirectories({
|
||||
values: filtered ? [host_directory_id] : [],
|
||||
}),
|
||||
BunSQLite.sql<WorkspaceLinkRow>({
|
||||
sql: `SELECT hdw.*, w.name AS workspace_name FROM host_directory_workspaces hdw
|
||||
sql: `SELECT hdw.*, w.name AS workspace_name, w.image_media_id AS image_media_id
|
||||
FROM host_directory_workspaces hdw
|
||||
LEFT JOIN workspaces w ON w.id = hdw.workspace_id
|
||||
${filtered ? "WHERE hdw.host_directory_id = ?" : ""}
|
||||
ORDER BY hdw.id ASC`,
|
||||
|
||||
@@ -8,8 +8,9 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Reads every document of a knowledgebase again (after the install's
|
||||
* embedding model changed, or one failed). Each keeps its old passages
|
||||
* until its new ones are in. Returns how many were queued.
|
||||
* embedding model changed). Each keeps its old passages until its new
|
||||
* ones are in. Documents whose last read failed, and only those, are
|
||||
* `retryFailedDocuments`. Returns how many were queued.
|
||||
*/
|
||||
export default async function reindexKnowledgebase({ knowledgebase_id }: Params) {
|
||||
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import enqueueDocumentIngest from "@/src/file-ingest/enqueue-document-ingest";
|
||||
import grabKnowledgebase from "./grab-knowledgebase";
|
||||
|
||||
type Params = {
|
||||
knowledgebase_id: number | string;
|
||||
/**
|
||||
* One document. Left out, every document of the knowledgebase whose
|
||||
* last read failed.
|
||||
*/
|
||||
document_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Queues the documents whose last read failed, and leaves the ones that
|
||||
* already succeeded. Clearing `ingest_error` lets `ingest-pending-files`
|
||||
* pick up one that was never read, if the queue write doesn't land.
|
||||
* Returns how many were queued.
|
||||
*/
|
||||
export default async function retryFailedDocuments({ knowledgebase_id, document_id }: Params) {
|
||||
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
|
||||
|
||||
const documents = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM knowledgebase_documents
|
||||
WHERE knowledgebase_id = ? AND ingest_error IS NOT NULL AND (? IS NULL OR id = ?)`,
|
||||
values: [knowledgebase.id, document_id ?? null, document_id ?? null],
|
||||
});
|
||||
|
||||
const ids = (documents.payload || []).map((document) => document.id).filter(Boolean);
|
||||
|
||||
if (!ids.length) return 0;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE knowledgebase_documents SET ingest_error = NULL, updated_at = ?
|
||||
WHERE knowledgebase_id = ? AND id IN (${ids.map(() => "?").join(", ")})`,
|
||||
values: [Date.now(), knowledgebase.id, ...ids],
|
||||
});
|
||||
|
||||
for (const id of ids) {
|
||||
await enqueueDocumentIngest({ document_id: id });
|
||||
}
|
||||
|
||||
return ids.length;
|
||||
}
|
||||
@@ -177,4 +177,67 @@ describe("embed asks for input_type when the model needs it", () => {
|
||||
).rejects.toThrow("model not found");
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("embed fits a provider's own batch cap", () => {
|
||||
/**
|
||||
* Alibaba's Model Studio compatible API: more than 20 texts in one batch
|
||||
* is refused whole, with the limit in the message.
|
||||
*/
|
||||
const alibaba: HarnessCandidate = {
|
||||
key: "20:qwen-embed",
|
||||
provider: {
|
||||
kind: "custom",
|
||||
base_url: "https://ws-test.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
|
||||
name: "Alibaba Cloud",
|
||||
},
|
||||
model: {
|
||||
slug: "qwen3.7-embedding",
|
||||
input_modalities: ["text"],
|
||||
output_modalities: ["text"],
|
||||
supports_tools: false,
|
||||
},
|
||||
source: "pinned",
|
||||
};
|
||||
|
||||
const capAtTwenty = (body: any) => {
|
||||
if (body.input.length > 20)
|
||||
throw new HarnessError({
|
||||
message:
|
||||
"Alibaba Cloud: <400> InternalError.Algo.InvalidParameter: Value error, batch size is invalid, it should not be larger than 20.: input.contents",
|
||||
status: 400,
|
||||
});
|
||||
|
||||
return {
|
||||
data: body.input.map((_: string, index: number) => ({ index, embedding: [1, index] })),
|
||||
};
|
||||
};
|
||||
|
||||
test("the refused batch is retried at the size named, and that size is kept", async () => {
|
||||
answer = capAtTwenty;
|
||||
|
||||
const many = Array.from({ length: 45 }, (_, i) => `chunk ${i}`);
|
||||
const first = await embed({ candidate: alibaba, input: many, purpose: "passage", signal });
|
||||
|
||||
expect(first.vectors).toHaveLength(45);
|
||||
expect(sent.map((body) => body.input.length)).toEqual([32, 20, 20, 5]);
|
||||
expect(first.vectors[44]).toEqual([1, 4]);
|
||||
|
||||
await embed({ candidate: alibaba, input: ["a", "b", "c"], purpose: "passage", signal });
|
||||
expect(sent.map((body) => body.input.length)).toEqual([32, 20, 20, 5, 3]);
|
||||
});
|
||||
|
||||
test("one text refused for its size is a failure, not a retry loop", async () => {
|
||||
answer = () => {
|
||||
throw new HarnessError({
|
||||
message: "Alibaba Cloud: Value error, batch size is invalid, it should not be larger than 0.",
|
||||
status: 400,
|
||||
});
|
||||
};
|
||||
|
||||
await expect(
|
||||
embed({ candidate: alibaba, input: ["a document's text"], purpose: "passage", signal }),
|
||||
).rejects.toThrow("batch size is invalid");
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@ import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessAdapter, HarnessCandidate } from "../../types";
|
||||
import grabProviderPreset from "../grab-provider-preset";
|
||||
import providerRequest from "./provider-request";
|
||||
import sendEmbeddingsBatch from "./send-embeddings-batch";
|
||||
import smallerBatchLimit from "./smaller-batch-limit";
|
||||
|
||||
/**
|
||||
* Providers that want `input_type` on every batch, by provider and model:
|
||||
@@ -13,6 +14,14 @@ import providerRequest from "./provider-request";
|
||||
*/
|
||||
const wantsInputType = new Set<string>();
|
||||
|
||||
/**
|
||||
* The largest batch a provider and model already refused a bigger one over.
|
||||
* Alibaba's Model Studio caps a batch at 20 and refuses the whole request, so
|
||||
* the size it named is remembered for the process: every later document goes
|
||||
* straight to a batch that fits instead of paying for the refusal again.
|
||||
*/
|
||||
const batchLimits = new Map<string, number>();
|
||||
|
||||
const inputTypeKey = ({ provider, model }: HarnessCandidate) =>
|
||||
`${provider.base_url}|${model.slug}`;
|
||||
|
||||
@@ -22,7 +31,7 @@ const inputTypeKey = ({ provider, model }: HarnessCandidate) =>
|
||||
* request the provider may refuse.
|
||||
*/
|
||||
const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signal }) => {
|
||||
const { provider, model } = candidate;
|
||||
const { provider } = candidate;
|
||||
const preset = grabProviderPreset({ kind: provider.kind });
|
||||
const key = inputTypeKey(candidate);
|
||||
const vectors: number[][] = [];
|
||||
@@ -33,49 +42,46 @@ const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signa
|
||||
let prompt_tokens = 0;
|
||||
|
||||
/**
|
||||
* Every OpenAI-compatible API puts embeddings at `/embeddings`.
|
||||
* The batch size in use: the install's, or the smaller one this provider
|
||||
* and model already made clear it wants.
|
||||
*/
|
||||
const path = "/embeddings";
|
||||
let limit = batchLimits.get(key) || AppData.EmbeddingBatchSize;
|
||||
|
||||
for (let start = 0; start < input.length; start += AppData.EmbeddingBatchSize) {
|
||||
for (let start = 0; start < input.length; ) {
|
||||
const batch = input
|
||||
.slice(start, start + AppData.EmbeddingBatchSize)
|
||||
.slice(start, start + limit)
|
||||
.map((text) => text.slice(0, AppData.EmbeddingMaxInputChars));
|
||||
|
||||
const body = { model: model.slug, input: batch };
|
||||
let res: Response;
|
||||
|
||||
try {
|
||||
res = await providerRequest({
|
||||
provider,
|
||||
path,
|
||||
json: wantsInputType.has(key) ? { ...body, input_type: purpose } : body,
|
||||
const sent = await sendEmbeddingsBatch({
|
||||
candidate,
|
||||
batch,
|
||||
purpose,
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
with_input_type: wantsInputType.has(key),
|
||||
});
|
||||
|
||||
if (sent.asked_input_type) wantsInputType.add(key);
|
||||
|
||||
res = sent.res;
|
||||
} catch (error) {
|
||||
/**
|
||||
* The provider says the model embeds a passage and a query
|
||||
* differently and wants to be told which. Ask again with it,
|
||||
* then remember: only the first batch per provider and model
|
||||
* pays for finding out. Any other refusal is the caller's to
|
||||
* classify.
|
||||
* A provider may cap a batch below the install's size (Alibaba's
|
||||
* Model Studio: "batch size is invalid, it should not be larger
|
||||
* than 20"). Nothing of this batch was stored, so retry it whole
|
||||
* at the smaller size, and keep that size for the rest of the
|
||||
* run. Only a size refusal is retried; anything else is the
|
||||
* caller's to classify.
|
||||
*/
|
||||
if (
|
||||
!(error instanceof HarnessError) ||
|
||||
error.status !== 400 ||
|
||||
!/input_type/i.test(error.message)
|
||||
)
|
||||
throw error;
|
||||
const smaller = smallerBatchLimit({ error, size: batch.length });
|
||||
|
||||
res = await providerRequest({
|
||||
provider,
|
||||
path,
|
||||
json: { ...body, input_type: purpose },
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
wantsInputType.add(key);
|
||||
if (smaller === null) throw error;
|
||||
|
||||
limit = smaller;
|
||||
batchLimits.set(key, smaller);
|
||||
continue;
|
||||
}
|
||||
|
||||
const json = await res.json().catch(() => null);
|
||||
@@ -142,6 +148,8 @@ const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signa
|
||||
}
|
||||
vectors.push(vector);
|
||||
}
|
||||
|
||||
start += batch.length;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -29,10 +29,6 @@ mock.module("./provider-request", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
mock.module("../grab-provider-preset", () => ({
|
||||
default: () => ({ title: "TestProvider", video_path: "/videos" }),
|
||||
}));
|
||||
|
||||
const { default: generateVideo } = await import("./generate-video");
|
||||
|
||||
afterAll(() => mock.restore());
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
type Params = {
|
||||
candidate: HarnessCandidate;
|
||||
batch: string[];
|
||||
purpose: "query" | "passage";
|
||||
signal: AbortSignal;
|
||||
/**
|
||||
* Ask with `input_type` from the first try (this provider already said
|
||||
* its model needs it).
|
||||
*/
|
||||
with_input_type: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One `/embeddings` request for a batch. A provider that says its model
|
||||
* embeds a passage and a query differently (NVIDIA's asymmetric ones) is
|
||||
* asked again with `input_type`, and the answer says it was, so the caller
|
||||
* can remember and skip the probe next time.
|
||||
*/
|
||||
export default async function sendEmbeddingsBatch({
|
||||
candidate,
|
||||
batch,
|
||||
purpose,
|
||||
signal,
|
||||
with_input_type,
|
||||
}: Params): Promise<{ res: Response; asked_input_type: boolean }> {
|
||||
const { provider, model } = candidate;
|
||||
const body = { model: model.slug, input: batch };
|
||||
const send = async (json: unknown) =>
|
||||
await providerRequest({
|
||||
provider,
|
||||
path: "/embeddings",
|
||||
json,
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
if (with_input_type) {
|
||||
return { res: await send({ ...body, input_type: purpose }), asked_input_type: true };
|
||||
}
|
||||
|
||||
try {
|
||||
return { res: await send(body), asked_input_type: false };
|
||||
} catch (error) {
|
||||
/**
|
||||
* Any other refusal is the caller's to classify.
|
||||
*/
|
||||
if (
|
||||
!(error instanceof HarnessError) ||
|
||||
error.status !== 400 ||
|
||||
!/input_type/i.test(error.message)
|
||||
)
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { res: await send({ ...body, input_type: purpose }), asked_input_type: true };
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import HarnessError from "../../harness-error";
|
||||
import smallerBatchLimit from "./smaller-batch-limit";
|
||||
|
||||
const refusal = ({ message, status = 400 }: { message: string; status?: number }) =>
|
||||
new HarnessError({ message, status });
|
||||
|
||||
describe("smallerBatchLimit", () => {
|
||||
test("takes the limit the provider stated", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({
|
||||
message:
|
||||
"Alibaba Cloud: <400> InternalError.Algo.InvalidParameter: Value error, batch size is invalid, it should not be larger than 20.: input.contents",
|
||||
}),
|
||||
size: 32,
|
||||
}),
|
||||
).toBe(20);
|
||||
});
|
||||
|
||||
test("halves the batch when no number is named", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "batch size is invalid" }), size: 32 }),
|
||||
).toBe(16);
|
||||
});
|
||||
|
||||
test("understands the other wordings providers use", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "too many inputs in the batch" }), size: 10 }),
|
||||
).toBe(5);
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "the batch size is at most 4" }), size: 10 }),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
test("one text alone is never shrunk", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid, it should not be larger than 0" }),
|
||||
size: 1,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("a stated limit that doesn't shrink the batch still halves it", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid, it should not be larger than 32" }),
|
||||
size: 32,
|
||||
}),
|
||||
).toBe(16);
|
||||
});
|
||||
|
||||
test("any other refusal is somebody else's to classify", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "model not found" }), size: 32 }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid", status: 500 }),
|
||||
size: 32,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(smallerBatchLimit({ error: new Error("batch size is invalid"), size: 32 })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
|
||||
type Params = {
|
||||
error: unknown;
|
||||
/**
|
||||
* How many texts the refused request carried.
|
||||
*/
|
||||
size: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The batch size to try when a provider refused a batch for being too large.
|
||||
*
|
||||
* Alibaba's Model Studio compatible API answers "Value error, batch size is
|
||||
* invalid, it should not be larger than 20.: input.contents" and refuses the
|
||||
* whole request, so nothing is embedded until the batch fits. Returns the
|
||||
* limit the provider stated, else half the refused batch; null when the
|
||||
* refusal is something else, or when one text alone was still refused (that
|
||||
* is a real failure, not a size one).
|
||||
*/
|
||||
export default function smallerBatchLimit({ error, size }: Params): number | null {
|
||||
if (!(error instanceof HarnessError) || error.status !== 400) return null;
|
||||
|
||||
if (!/batch size/i.test(error.message) && !/too many inputs/i.test(error.message)) return null;
|
||||
|
||||
const stated = /(?:larger than|at most|maximum of|limit of)\s*(\d+)/i.exec(error.message);
|
||||
const stated_limit = stated ? Number(stated[1]) : 0;
|
||||
const next = stated_limit > 0 && stated_limit < size ? stated_limit : Math.floor(size / 2);
|
||||
|
||||
return next >= 1 && next < size ? next : null;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, 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, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -1786,12 +1786,14 @@ describe("runTextLoop closing tools", () => {
|
||||
});
|
||||
|
||||
describe("runTextLoop required send_reply", () => {
|
||||
const sendReply: HarnessTool<{ status: "done" | "working" | "blocked"; work?: unknown }> = {
|
||||
const sendReply: HarnessTool<{ status?: "done" | "working" | "blocked"; work?: unknown; message?: string; text?: string }> = {
|
||||
name: "send_reply",
|
||||
description: "Sends the message.",
|
||||
schema: z.object({
|
||||
status: z.enum(["done", "working", "blocked"]),
|
||||
status: z.enum(["done", "working", "blocked"]).optional(),
|
||||
work: z.unknown().optional(),
|
||||
message: z.string().optional(),
|
||||
text: z.string().optional(),
|
||||
}),
|
||||
run: async () => "Sent.",
|
||||
};
|
||||
@@ -1933,14 +1935,38 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a message written in the turn before goes out with send_reply", async () => {
|
||||
test("send_reply with no text does not ship the previous draft on the first pass", async () => {
|
||||
/**
|
||||
* A model that writes the answer, then calls send_reply with
|
||||
* nothing beside it, means the sentence it just wrote. Asked to
|
||||
* write it again it wrote nothing, and the run failed with the
|
||||
* answer sitting in the transcript.
|
||||
* The model spent its stop on the draft. The next turn only stamped
|
||||
* send_reply on it, and that draft went out mid-table with no turn
|
||||
* left for a follow-up. The first bare call is told to write the
|
||||
* message again.
|
||||
*/
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
text: "No, I didn't add it anywhere.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Did you add a bot?" }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(3);
|
||||
expect(seen[2]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a finished draft goes out only after the one reminder still gets no text", async () => {
|
||||
const { generate } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
@@ -1956,12 +1982,11 @@ describe("runTextLoop required send_reply", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(seen[1]!.messages.some((message) => message.content === replyNoTextNote)).toBe(false);
|
||||
expect(result.steps).toBe(3);
|
||||
});
|
||||
|
||||
test("the message still goes out when a tool turn comes between it and send_reply", async () => {
|
||||
const { generate } = scripted([
|
||||
test("a tool turn between the draft and send_reply still gets the one reminder", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"checked"}` }] },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
@@ -1978,23 +2003,129 @@ describe("runTextLoop required send_reply", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(3);
|
||||
expect(result.steps).toBe(4);
|
||||
expect(seen[3]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a card is never paired with a message written earlier", async () => {
|
||||
asked.length = 0;
|
||||
test("send_reply and suggest_next_steps in one turn end the run and keep both", async () => {
|
||||
suggested.length = 0;
|
||||
const { generate } = scripted([
|
||||
{ text: "Which date rule?" },
|
||||
{
|
||||
text: "Both repos are scanned. Nothing was pulled in.",
|
||||
tool_calls: [
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "g1", name: "suggest_next_steps", arguments: `{"steps":["Pull email_frameworks.md in full"]}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [suggestNextSteps, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Both repos are scanned. Nothing was pulled in.");
|
||||
expect(result.steps).toBe(1);
|
||||
expect(suggested).toEqual(["Pull email_frameworks.md in full"]);
|
||||
expect(result.tool_uses.map((use) => use.name)).toEqual(["suggest_next_steps", "send_reply"]);
|
||||
});
|
||||
|
||||
test("send_reply beside a research tool is still mixed and unsent", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Scanned.",
|
||||
tool_calls: [
|
||||
{ id: "c1", name: "remember", arguments: `{"note":"scanned"}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Scanned both repos.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [remember, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Scanned both repos.");
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingMixedNote });
|
||||
});
|
||||
|
||||
test("a table that stops mid-row is sent back once, then goes out finished", async () => {
|
||||
const cut = ["| Skill | Focus |", "| **revops** | Lead routing"].join("\n");
|
||||
const whole = ["| Skill | Focus |", "| **revops** | Lead routing |"].join("\n");
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: cut,
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
{
|
||||
text: whole,
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe(whole);
|
||||
expect(result.steps).toBe(2);
|
||||
expect(String(seen[1]!.messages.at(-1)!.content)).toContain("table row");
|
||||
});
|
||||
|
||||
test("a cut-off draft is never carried, even after the reminder", async () => {
|
||||
const cut = ["| Skill | Focus |", "| **revops** | Lead routing"].join("\n");
|
||||
const { generate } = scripted([
|
||||
{ text: cut },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyNoTextNote);
|
||||
});
|
||||
|
||||
test("a card is never paired with a message written earlier", async () => {
|
||||
/**
|
||||
* The first bare send_reply is told to write the message again.
|
||||
* Writing nothing the second time must not fill the card's turn
|
||||
* with the earlier sentence: the card asked something else, and
|
||||
* that sentence is not its answer.
|
||||
*/
|
||||
asked.length = 0;
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "I checked the date rules." },
|
||||
{ tool_calls: [{ id: "s0", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
tool_calls: [
|
||||
{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
@@ -2010,6 +2141,8 @@ describe("runTextLoop required send_reply", () => {
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyNoTextNote);
|
||||
expect(asked).toEqual(["Which date rule?"]);
|
||||
expect(seen[2]!.messages.some((message) => message.content === replyNoTextNote)).toBe(true);
|
||||
});
|
||||
|
||||
test("the wrap up still offers send_reply", async () => {
|
||||
@@ -2034,6 +2167,125 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["send_reply"]);
|
||||
expect(result.text).toBe("Report.");
|
||||
});
|
||||
|
||||
test("send_reply with text in tool arguments sends the message directly", async () => {
|
||||
const { generate } = scripted([
|
||||
{
|
||||
tool_calls: [
|
||||
{
|
||||
id: "s1",
|
||||
name: "send_reply",
|
||||
arguments: JSON.stringify({ status: "done", text: "Here is your skill." }),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Install skill." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Here is your skill.");
|
||||
expect(result.steps).toBe(1);
|
||||
});
|
||||
|
||||
test("send_reply with message in tool arguments and no status defaults to done and sends the message", async () => {
|
||||
const { generate } = scripted([
|
||||
{
|
||||
tool_calls: [
|
||||
{
|
||||
id: "s1",
|
||||
name: "send_reply",
|
||||
arguments: JSON.stringify({ message: "Link-building next, as you picked." }),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "What next?" }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Link-building next, as you picked.");
|
||||
expect(result.steps).toBe(1);
|
||||
});
|
||||
|
||||
test("a message written beside a card goes out when send_reply follows alone", async () => {
|
||||
/**
|
||||
* Session 146, job 795: the model wrote the whole answer in the
|
||||
* turn that put the question up, the loop asked for `send_reply`,
|
||||
* and the next turn had nothing left to say. The sentence beside
|
||||
* the card is that card's sentence, so it is kept.
|
||||
*/
|
||||
asked.length = 0;
|
||||
const { generate } = scripted([
|
||||
{
|
||||
text: "RevOps is proposed. Which skill should I take next?",
|
||||
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Which skill next?"}` }],
|
||||
},
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Propose RevOps, then ask me." }],
|
||||
tools: [askUser, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("RevOps is proposed. Which skill should I take next?");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(asked).toEqual(["Which skill next?"]);
|
||||
});
|
||||
|
||||
test("an answer the review sends back is never carried a second time", async () => {
|
||||
/**
|
||||
* Session 146, job 785: the refused draft stayed held, so every
|
||||
* later bare `send_reply` re-sent the same faulted text and used up
|
||||
* the whole rewrite budget. It is dropped with the refusal.
|
||||
*/
|
||||
const reviewed: string[] = [];
|
||||
const notes = ["You named [proposal:999], which was never made."];
|
||||
const { generate } = scripted([
|
||||
{ text: "Proposed [proposal:999] for you." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
text: "The proposal is up for you.",
|
||||
tool_calls: [{ id: "s3", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Propose it." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
review: async ({ text }) => {
|
||||
reviewed.push(text);
|
||||
|
||||
return notes.shift() || null;
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.text).toBe("The proposal is up for you.");
|
||||
expect(result.steps).toBe(4);
|
||||
expect(reviewed).toEqual(["Proposed [proposal:999] for you.", "The proposal is up for you."]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop answer not sent", () => {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
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 unfinishedAnswerText from "@/src/utils/unfinished-answer-text";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
|
||||
@@ -300,15 +301,35 @@ const wrapUpToolsPrompt = ({
|
||||
};
|
||||
|
||||
/**
|
||||
* The status a `send_reply` call declared, for the review: a call whose
|
||||
* arguments don't parse or name an unknown status is left undefined, and
|
||||
* the tool's own schema refuses it before this matters.
|
||||
* The status a `send_reply` call declared, for the review: defaults to "working"
|
||||
* when work is passed, otherwise "done". A call whose arguments don't parse or name an
|
||||
* unknown status is left undefined.
|
||||
*/
|
||||
const replyStatusFromCall = ({ call }: { call: HarnessToolCall }): ReplyStatus | undefined => {
|
||||
try {
|
||||
const args = JSON.parse(call.arguments || "{}");
|
||||
const status = args?.status || (args?.work ? "working" : "done");
|
||||
|
||||
return ReplyStatuses.includes(args?.status) ? (args.status as ReplyStatus) : undefined;
|
||||
return ReplyStatuses.includes(status) ? (status as ReplyStatus) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Message or text passed in send_reply's arguments, when the model placed the
|
||||
* reply content in the tool call rather than assistant prose.
|
||||
*/
|
||||
const replyTextFromCall = ({ call }: { call: HarnessToolCall }): string | undefined => {
|
||||
try {
|
||||
const args = JSON.parse(call.arguments || "{}");
|
||||
if (typeof args?.message === "string" && args.message.trim()) {
|
||||
return args.message.trim();
|
||||
}
|
||||
if (typeof args?.text === "string" && args.text.trim()) {
|
||||
return args.text.trim();
|
||||
}
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -505,6 +526,12 @@ export default async function runTextLoop({
|
||||
* the sentence that goes with it (`closingNoTextNote`).
|
||||
*/
|
||||
let told_closing_text = false;
|
||||
/**
|
||||
* A message that stopped inside a table, a fence or a bare marker has
|
||||
* been sent back once (`unfinishedAnswerText`). Past that the run
|
||||
* fails rather than shipping the cut-off text.
|
||||
*/
|
||||
let told_unfinished = false;
|
||||
/**
|
||||
* How many turns the run has spent retrying a closing card: a closing
|
||||
* call that failed, or a card put up beside other work. Bounded
|
||||
@@ -519,14 +546,23 @@ export default async function runTextLoop({
|
||||
*/
|
||||
let reply_drafts = 0;
|
||||
/**
|
||||
* The last message a turn wrote with nothing beside it, held for the
|
||||
* run: a model that writes the answer and then calls `send_reply` with
|
||||
* nothing beside it means the sentence it wrote, and dropping it made
|
||||
* the app ask again until the run failed with the answer sitting in the
|
||||
* transcript. Kept across turns, since the call came after another turn
|
||||
* often enough; a card's message is never taken from here.
|
||||
* The last message a turn wrote with nothing beside it. Held so the
|
||||
* note that asks for it again can point at it. It is not the reply:
|
||||
* `send_reply` with no text beside it used to ship this unchanged, and
|
||||
* a scan that stopped mid-table went out as the answer, with no turn
|
||||
* left for the follow-up (session 130, message 874).
|
||||
*/
|
||||
let draft_text = "";
|
||||
/**
|
||||
* The message a turn wrote beside a card but without `send_reply`
|
||||
* (`closing_required`). That prose is the sentence the card belongs
|
||||
* under, not a draft about something else, so a later bare `send_reply`
|
||||
* carries it instead of making the model write the whole answer again.
|
||||
* Session 146 lost six answers this way: the text went out with
|
||||
* `ask_user`, the loop asked for `send_reply`, and the next turn had
|
||||
* nothing left to say.
|
||||
*/
|
||||
let card_text = "";
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
@@ -794,6 +830,11 @@ export default async function runTextLoop({
|
||||
const tool_calls = offered.filter((call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name));
|
||||
const reply_call = tool_calls.filter((call) => call.name === SendReplyToolName).at(-1);
|
||||
const reply_status = reply_call ? replyStatusFromCall({ call: reply_call }) : undefined;
|
||||
const call_text = reply_call ? replyTextFromCall({ call: reply_call }) : undefined;
|
||||
|
||||
if (!answer.text && call_text) {
|
||||
answer.text = call_text;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the app would never show as its own word comes out before
|
||||
@@ -907,6 +948,7 @@ export default async function runTextLoop({
|
||||
if (!(wrap_up && !wrap_up_saving) && reply_drafts < AppData.HarnessReplyDraftsMax) {
|
||||
reply_drafts += 1;
|
||||
draft_text = answer.text || "";
|
||||
card_text = "";
|
||||
pushUserTurn({ transcript, content: replyDraftNote });
|
||||
await traced({ kind: "event", index, name: "reply_draft", text: replyDraftNote });
|
||||
continue;
|
||||
@@ -976,7 +1018,20 @@ export default async function runTextLoop({
|
||||
};
|
||||
}
|
||||
|
||||
if (check.verdict === "sent_back") continue;
|
||||
if (check.verdict === "sent_back") {
|
||||
/**
|
||||
* The answer is being written again, so nothing held from
|
||||
* the refused one may go out in its place: a draft or a
|
||||
* card's sentence re-sent unchanged is a fault again, and
|
||||
* three of those cost the user the answer (session 146).
|
||||
* The reminder flag goes with it, so the rewrite can be
|
||||
* told to write beside the call once more.
|
||||
*/
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
told_closing_text = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrap-up rewrite the review let through is the answer. The
|
||||
@@ -1124,6 +1179,13 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const called_card = tool_calls.some((call) => isClosingTool({ name: call.name }));
|
||||
const called_send_reply = tool_calls.some((call) => call.name === SendReplyToolName);
|
||||
/**
|
||||
* A closing turn is `send_reply` plus the cards that belong under
|
||||
* that answer, and nothing else. `ask_user` and `suggest_next_steps`
|
||||
* are closing tools, so they share the turn. A research tool beside
|
||||
* `send_reply` is still mixed: its result arrives after the message,
|
||||
* and the message would describe work the turn had not finished.
|
||||
*/
|
||||
const closing = tool_calls.every((call) => isClosingTool({ name: call.name }));
|
||||
/**
|
||||
* A required closing answer needs `send_reply` itself, not just any
|
||||
@@ -1143,21 +1205,45 @@ export default async function runTextLoop({
|
||||
const closing_failed = closing_uses.some((use) => !use.ok);
|
||||
const closing_worked = closing && !closing_failed && closing_required;
|
||||
/**
|
||||
* The message this turn carries: its own, or the last one a turn
|
||||
* wrote with nothing beside it (`draft_text`). A model that writes
|
||||
* the answer and then calls `send_reply` with no text means that
|
||||
* sentence; asking for it again ended runs whose answer was already
|
||||
* in the transcript. A card is never paired with an older sentence:
|
||||
* "which date rule?" beside a message about something else is worse
|
||||
* than the note that asks for one.
|
||||
* The message this turn wrote beside the call. An earlier draft is
|
||||
* not filled in: the model spent its stop on that draft, and the
|
||||
* next turn only stamped `send_reply` on it, so a cut-off scan went
|
||||
* out with no follow-up. The draft is offered once, after the model
|
||||
* has been told to write it again and still sent nothing, and only
|
||||
* when that draft is a finished message.
|
||||
*/
|
||||
const written_text = (answer.text || call_text || "").trim();
|
||||
/**
|
||||
* A card is never paired with an older sentence: the card asked
|
||||
* something, and the draft was about something else. Filling it in
|
||||
* would put "I checked the date rules." under "Which date rule?".
|
||||
*/
|
||||
const written_text = (answer.text || "").trim();
|
||||
const asked_something = tool_calls.some(
|
||||
(call) => call.name !== SendReplyToolName && isClosingTool({ name: call.name }),
|
||||
);
|
||||
const message_text = written_text ? answer.text || "" : asked_something ? "" : draft_text;
|
||||
/**
|
||||
* The sentence a card turn wrote is the one that card belongs under,
|
||||
* so it is held for the `send_reply` that closes it, whether that
|
||||
* turn is the next one or shares the card. No second reminder is
|
||||
* needed: the loop already asked for the call, not the message. An
|
||||
* earlier draft is not held that way: it was about something else,
|
||||
* and pairing it with "Which date rule?" put "I checked the date
|
||||
* rules." under it.
|
||||
*/
|
||||
const carry_card = Boolean(card_text.trim()) && !unfinishedAnswerText({ text: card_text });
|
||||
const carry_draft =
|
||||
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
|
||||
const message_text = written_text || (carry_card ? card_text : carry_draft ? draft_text : "");
|
||||
|
||||
if (called_card && (closing_failed || !closing || !closing_required)) {
|
||||
/**
|
||||
* A turn that put a card up and wrote the message beside it, but
|
||||
* ended without `send_reply`, has written the reply: the next
|
||||
* turn is asked for the call, not the whole message again.
|
||||
*/
|
||||
if (closing && !closing_failed && !called_send_reply && written_text) {
|
||||
card_text = written_text;
|
||||
}
|
||||
/**
|
||||
* Bounded: past the retries a card-only turn ends on the answer
|
||||
* it wrote, reviewed like any reply, rather than looping on a
|
||||
@@ -1242,19 +1328,44 @@ export default async function runTextLoop({
|
||||
/**
|
||||
* Checked before it goes out, as any reply is: a note comes
|
||||
* back and the answer is written again (the card stays on the
|
||||
* reply, its ref is already recorded). A message held from the
|
||||
* turn before went out with this call, which is what the model
|
||||
* meant by writing it there.
|
||||
* reply, its ref is already recorded). A draft carried after
|
||||
* the one reminder is said so, so the debug view shows why an
|
||||
* earlier turn's text went out.
|
||||
*/
|
||||
if (!written_text && message_text) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "draft_carried",
|
||||
text: "The message was written in an earlier turn, so it went out with this send_reply.",
|
||||
text: carry_card
|
||||
? "The message was written beside a card in an earlier turn. send_reply had no text beside it after one reminder, so that message went out with the card under it."
|
||||
: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
|
||||
});
|
||||
}
|
||||
|
||||
const unfinished = unfinishedAnswerText({ text: message_text });
|
||||
|
||||
if (unfinished) {
|
||||
if (!told_unfinished && !(wrap_up && !wrap_up_saving)) {
|
||||
told_unfinished = true;
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
pushUserTurn({ transcript, content: unfinished });
|
||||
await traced({ kind: "event", index, name: "unfinished", text: unfinished });
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: unfinished,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
const final_turn = wrap_up && !wrap_up_saving;
|
||||
const check = await checkAnswer({ text: message_text, index, status: reply_status, final: final_turn });
|
||||
|
||||
@@ -1297,7 +1408,17 @@ export default async function runTextLoop({
|
||||
};
|
||||
}
|
||||
|
||||
if (check.verdict === "sent_back") continue;
|
||||
if (check.verdict === "sent_back") {
|
||||
/**
|
||||
* Nothing held from the refused message may go out in its
|
||||
* place, and the reminder flag goes with it so the rewrite
|
||||
* can be asked for the text beside the call once more.
|
||||
*/
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
told_closing_text = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: message_text,
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("describeKnowledgebase", () => {
|
||||
expect(text).toContain("Handbook");
|
||||
expect(text).toContain("[bot:7]");
|
||||
expect(text).toContain("1 not read yet");
|
||||
expect(text).not.toContain("retry_failed_documents");
|
||||
expect(text).toContain("re-indexing fixes it");
|
||||
});
|
||||
|
||||
@@ -48,6 +49,12 @@ describe("describeKnowledgebase", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("names the retry for ones that failed", () => {
|
||||
const text = describeKnowledgebase({ knowledgebase: { ...knowledgebase, error_count: 2 } });
|
||||
|
||||
expect(text).toContain("2 failed (retry_failed_documents reads those again)");
|
||||
});
|
||||
|
||||
test("lists documents and says one failed", () => {
|
||||
const text = describeKnowledgebase({
|
||||
knowledgebase,
|
||||
|
||||
@@ -27,7 +27,9 @@ export default function describeKnowledgebase({ knowledgebase, documents }: Para
|
||||
lines.push(
|
||||
`Documents: ${knowledgebase.document_count}` +
|
||||
(knowledgebase.pending_count ? `, ${knowledgebase.pending_count} not read yet` : "") +
|
||||
(knowledgebase.error_count ? `, ${knowledgebase.error_count} failed` : "") +
|
||||
(knowledgebase.error_count
|
||||
? `, ${knowledgebase.error_count} failed (retry_failed_documents reads those again)`
|
||||
: "") +
|
||||
(knowledgebase.warning_count ? `, ${knowledgebase.warning_count} with a warning` : "") +
|
||||
(knowledgebase.stale_count
|
||||
? `, ${knowledgebase.stale_count} searchable by words only or read by another embedding model (re-indexing fixes it)`
|
||||
|
||||
@@ -13,6 +13,7 @@ describe("grabCoordinatorKnowledgebaseTools", () => {
|
||||
"add_knowledgebase_document",
|
||||
"delete_knowledgebase_document",
|
||||
"delete_knowledgebase",
|
||||
"retry_failed_documents",
|
||||
"reindex_knowledgebase",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import deleteKnowledgebaseDocumentTool from "./delete-knowledgebase-document-too
|
||||
import deleteKnowledgebaseTool from "./delete-knowledgebase-tool";
|
||||
import listKnowledgebasesTool from "./list-knowledgebases-tool";
|
||||
import reindexKnowledgebaseTool from "./reindex-knowledgebase-tool";
|
||||
import retryFailedDocumentsTool from "./retry-failed-documents-tool";
|
||||
import saveKnowledgebaseTool from "./save-knowledgebase-tool";
|
||||
|
||||
type Params = {
|
||||
@@ -23,9 +24,9 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The coordinator's knowledgebase tools: list, fill, re-index, delete and
|
||||
* share out. Every one but the listing is only in an attended run, and each
|
||||
* checks the super admin itself.
|
||||
* The coordinator's knowledgebase tools: list, fill, retry the ones that
|
||||
* failed, re-index, delete and share out. Every one but the listing is only
|
||||
* in an attended run, and each checks the super admin itself.
|
||||
*/
|
||||
export default function grabCoordinatorKnowledgebaseTools({
|
||||
user_id,
|
||||
@@ -44,6 +45,7 @@ export default function grabCoordinatorKnowledgebaseTools({
|
||||
addKnowledgebaseDocumentTool({ user_id, bot_id, workspace_id, computer_id, attended }) as HarnessTool<unknown>,
|
||||
deleteKnowledgebaseDocumentTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
deleteKnowledgebaseTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
retryFailedDocumentsTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
reindexKnowledgebaseTool({ user_id, attended }) as HarnessTool<unknown>,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { z } from "zod";
|
||||
import grabKnowledgebase from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase";
|
||||
import retryFailedDocuments from "@/src/functions/backend/db/knowledgebases/retry-failed-documents";
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
import assertSuperAdminRun from "../extensions/assert-super-admin-run";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
attended: boolean;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
knowledgebase_id: number;
|
||||
document_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads again the documents whose last read failed. The ones that already
|
||||
* succeeded are left as they are; reading every document again is
|
||||
* `reindex_knowledgebase`.
|
||||
*/
|
||||
export default function retryFailedDocumentsTool({ user_id, attended }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "retry_failed_documents",
|
||||
description: `Read again the documents of a knowledgebase whose last read failed (list_knowledgebases marks them failed). Documents that already succeeded are left as they are. With document_id, only that one, and only when it failed. Reading every document again, including the ones that succeeded, is reindex_knowledgebase.`,
|
||||
schema: z.object({
|
||||
knowledgebase_id: z.number().int().positive(),
|
||||
document_id: z.number().int().positive().optional(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
await assertSuperAdminRun({ user_id });
|
||||
|
||||
if (!attended) throw new Error(`Knowledgebases are only changed in a reply or a task the user follows.`);
|
||||
|
||||
const knowledgebase = await grabKnowledgebase({ knowledgebase_id: args.knowledgebase_id });
|
||||
const count = await retryFailedDocuments({
|
||||
knowledgebase_id: knowledgebase.id,
|
||||
document_id: args.document_id,
|
||||
});
|
||||
|
||||
await logEvent({
|
||||
title: "Knowledgebase failed documents retried",
|
||||
category: "system",
|
||||
user_id: Number(user_id),
|
||||
plain_text: `Queued ${count} failed documents of knowledgebase #${knowledgebase.id} (${knowledgebase.name}) to be read again.`,
|
||||
metadata: { knowledgebase_id: knowledgebase.id, document_id: args.document_id, documents: count },
|
||||
});
|
||||
|
||||
if (!count) {
|
||||
return args.document_id
|
||||
? `#${args.document_id} didn't fail, so it wasn't read again.`
|
||||
: `#${knowledgebase.id} ${knowledgebase.name} has no failed documents.`;
|
||||
}
|
||||
|
||||
return `Queued ${count} failed ${count == 1 ? "document" : "documents"} of #${knowledgebase.id} ${knowledgebase.name} to be read again. The ones that already succeeded were left as they are.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import askUserTool from "./ask-user-tool";
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
|
||||
let created = 0;
|
||||
let next_id = 41;
|
||||
|
||||
mock.module("@/src/functions/backend/db/bot-questions/create-bot-question", () => ({
|
||||
default: async () => {
|
||||
created++;
|
||||
return next_id++;
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: askUserTool } = await import("./ask-user-tool");
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const tool = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: () => {} });
|
||||
|
||||
const question = { question: "Which environment?", kind: "single", options: ["Staging", "Production"] };
|
||||
const question = { question: "Which environment?", kind: "single" as const, options: ["Staging", "Production"] };
|
||||
|
||||
describe("askUserTool", () => {
|
||||
test("takes a set of questions", () => {
|
||||
@@ -23,4 +38,26 @@ describe("askUserTool", () => {
|
||||
test("caps how many questions one card holds", () => {
|
||||
expect(tool.schema?.safeParse({ questions: Array.from({ length: 7 }, () => question) }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test("asks once per run, so a second call points at the card already up", async () => {
|
||||
/**
|
||||
* A model that re-asked while the loop asked it for `send_reply`
|
||||
* was refused by a thrown error, which the loop read as a failed
|
||||
* closing call: session 146 lost its whole answer to it. The card
|
||||
* is up either way, so the second call just says so.
|
||||
*/
|
||||
created = 0;
|
||||
const refs: string[] = [];
|
||||
const once = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: ({ ref }) => refs.push(ref) });
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
const first = await once.run({ args: { questions: [question] }, signal });
|
||||
const second = await once.run({ args: { questions: [question] }, signal });
|
||||
|
||||
expect(created).toBe(1);
|
||||
expect(refs).toHaveLength(1);
|
||||
expect(String(first)).toContain("Asked the user 1 question");
|
||||
expect(String(second)).toContain("already asked");
|
||||
expect(String(second)).toContain("send_reply");
|
||||
});
|
||||
});
|
||||
@@ -47,7 +47,7 @@ export default function askUserTool({
|
||||
|
||||
return {
|
||||
name: "ask_user",
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Call it in the same turn as send_reply, with the message beside that call: a later turn cannot add the card, because that turn would replace the answer. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
in_task
|
||||
? `. In a task, ask, then stop working on what you asked about and finish your report; the card goes out with it.`
|
||||
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
@@ -67,9 +67,7 @@ export default function askUserTool({
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (asked) {
|
||||
throw new Error(
|
||||
`You already asked the user in this run. Put every question in one ask_user call, then wait for their answers.`,
|
||||
);
|
||||
return `The questions are already asked and will go out with your message. Finish your reply with send_reply.`;
|
||||
}
|
||||
|
||||
const id = await createBotQuestion({
|
||||
@@ -94,7 +92,7 @@ export default function askUserTool({
|
||||
return `Asked the user ${count} question${count == 1 ? "" : "s"}: the card is on your message. ${
|
||||
in_task
|
||||
? `Stop working on what you asked about and finish with your report (if you asked to settle something before going on, say you're waiting for their answers).`
|
||||
: `End your reply now with a short line saying what you need settled; their answers arrive as their next message.`
|
||||
: `End your reply now: write the short line saying what you need settled beside send_reply; their answers arrive as their next message.`
|
||||
} Don't repeat the questions or options in your text.`;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -142,4 +142,21 @@ describe("sendReplyTool", () => {
|
||||
expect(result).toContain("what stopped the work");
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("accepts text and message in arguments and defaults status to done", async () => {
|
||||
const result = await tool().run({ args: { message: "Here is your skill." }, signal });
|
||||
|
||||
expect(result).toContain("marked done");
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("infers status working when work is passed without status", async () => {
|
||||
const result = await tool().run({
|
||||
args: { work: { title: "Look up files", instructions: "Inspect them." } },
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(result).toContain("Run #100 queued");
|
||||
expect(queued).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -27,13 +27,15 @@ type Params = {
|
||||
};
|
||||
|
||||
type Args = {
|
||||
status: (typeof ReplyStatuses)[number];
|
||||
status?: (typeof ReplyStatuses)[number];
|
||||
work?: BotTaskWork;
|
||||
message?: string;
|
||||
text?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The one way a reply or a task report ends. The text written beside this
|
||||
* call is the message the user gets; the call declares what happens after
|
||||
* call or passed in message/text is the message the user gets; the call declares what happens after
|
||||
* it, so the app never has to guess intent from prose.
|
||||
*
|
||||
* `done` says nothing runs once the message is out. `working` says a run
|
||||
@@ -60,13 +62,16 @@ export default function sendReplyTool({
|
||||
|
||||
return {
|
||||
name: "send_reply",
|
||||
description: `End every reply with this call. The message you wrote in this turn is what the user gets; this call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. A message sent without this call is a draft and never reaches the user. ${
|
||||
description: `End every reply with this call, in the same turn as the message. The text you write beside it, or in message/text, is what the user gets; a call with neither sends nothing. A message written beside a card in an earlier turn is kept for the send_reply that closes it; anything else written earlier is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
|
||||
computers.length
|
||||
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
|
||||
: `You have no computer, so work that needs one can't run.`
|
||||
}`,
|
||||
schema: z.object({
|
||||
status: z.enum(ReplyStatuses).describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
|
||||
status: z
|
||||
.enum(ReplyStatuses)
|
||||
.default("done")
|
||||
.describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
|
||||
work: z
|
||||
.object({
|
||||
title: z.string().min(1).max(80).describe("A short label, e.g. \"Check the backup logs\""),
|
||||
@@ -88,13 +93,23 @@ export default function sendReplyTool({
|
||||
})
|
||||
.optional()
|
||||
.describe("The run to start with this message. Required when status is working and no run of yours is open here."),
|
||||
message: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("The message to send the user with this reply, when not written directly in the assistant turn."),
|
||||
text: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Alias for message: the message to send the user with this reply."),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (args.status !== "working" && args.work) {
|
||||
const status = args.status ?? (args.work ? "working" : "done");
|
||||
|
||||
if (status !== "working" && args.work) {
|
||||
throw new Error(`work can only be passed with status "working": it queues a run, so the message must say that work is under way. Nothing was sent.`);
|
||||
}
|
||||
|
||||
if (args.status === "working") {
|
||||
if (status === "working") {
|
||||
if (args.work) {
|
||||
if (!queued) {
|
||||
queued = await queueBotTask({
|
||||
@@ -129,7 +144,7 @@ export default function sendReplyTool({
|
||||
return `A run of yours is still open here, so status "working" holds. Your message beside this call goes out with it: say what it's doing, in one sentence, and that its result will be posted here.`;
|
||||
}
|
||||
|
||||
if (args.status === "blocked") {
|
||||
if (status === "blocked") {
|
||||
return `Your message beside this call goes out, marked blocked. Say plainly what stopped the work and what you need from the user to go on.`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import suggestNextStepsTool from "./suggest-next-steps-tool";
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
|
||||
let created = 0;
|
||||
let next_id = 7;
|
||||
|
||||
mock.module("@/src/functions/backend/db/bot-suggestions/create-bot-suggestion", () => ({
|
||||
default: async () => {
|
||||
created++;
|
||||
return next_id++;
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: suggestNextStepsTool } = await import("./suggest-next-steps-tool");
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const refs: string[] = [];
|
||||
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
|
||||
@@ -20,4 +35,20 @@ describe("suggestNextStepsTool", () => {
|
||||
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("suggests once per run, so a second call points at the buttons already up", async () => {
|
||||
created = 0;
|
||||
const seen: string[] = [];
|
||||
const once = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => seen.push(ref) });
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
const first = await once.run({ args: { steps: ["Write the report"] }, signal });
|
||||
const second = await once.run({ args: { steps: ["Write the report"] }, signal });
|
||||
|
||||
expect(created).toBe(1);
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(String(first)).toContain("Suggested 1 next step");
|
||||
expect(String(second)).toContain("already attached");
|
||||
expect(String(second)).toContain("send_reply");
|
||||
});
|
||||
});
|
||||
@@ -28,16 +28,16 @@ type Args = {
|
||||
/**
|
||||
* Offers the user concrete next steps as buttons under the bot's answer.
|
||||
* Clicking one puts it in their input; nothing waits on it, unlike
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It ends
|
||||
* the reply (`ClosingToolNames`): the buttons belong under the answer, and
|
||||
* a run that kept going would replace that answer with a later line.
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It shares
|
||||
* the closing turn with `send_reply` (`ClosingToolNames`): the buttons
|
||||
* belong under that answer, and a later turn would replace it.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
name: "suggest_next_steps",
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and put it up in the same turn as the answer it belongs under. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Call it in the same turn as send_reply, once the work is done, so the buttons belong to the message that turn sends (your best suggestion first). A later turn cannot add them: that turn would replace the answer. This never waits for a response: don't ask the user to pick one, don't put the answers on hold. When their answer decides what you do next, use ask_user in that same turn instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
@@ -49,7 +49,7 @@ export default function suggestNextStepsTool({ user_id, bot_id, session_id, work
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (suggested) {
|
||||
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
|
||||
return `The suggested steps are already attached to your message. Finish your reply with send_reply.`;
|
||||
}
|
||||
|
||||
const id = await createBotSuggestion({
|
||||
|
||||
@@ -14,6 +14,12 @@ type Params = {
|
||||
* The thread's last message is the user's, so a reply is due.
|
||||
*/
|
||||
awaiting_reply: boolean;
|
||||
/**
|
||||
* Something of this session's is still to show its work here (a queued
|
||||
* run, or one working on a computer): a reply that already landed says
|
||||
* nothing about it, so the poll keeps reading until it's done.
|
||||
*/
|
||||
running?: boolean;
|
||||
/**
|
||||
* The thread's last message: only newer ones are replayed.
|
||||
*/
|
||||
@@ -46,6 +52,7 @@ type Params = {
|
||||
export default function useReplyCatchUp({
|
||||
session_id,
|
||||
awaiting_reply,
|
||||
running,
|
||||
last_message_id,
|
||||
on_open_jobs,
|
||||
}: Params) {
|
||||
@@ -114,16 +121,19 @@ export default function useReplyCatchUp({
|
||||
useRefocus({ onRefocus: () => void check() });
|
||||
|
||||
/**
|
||||
* While a reply is due, a poll covers a reply whose push was missed
|
||||
* while the page stayed in front (a socket that dropped silently).
|
||||
* While a reply is due, or something of this session's is still running,
|
||||
* a poll covers a push that was missed while the page stayed in front (a
|
||||
* socket that dropped silently). A run queued behind another on the same
|
||||
* computer shows nothing at all without it: its reply already landed, so
|
||||
* no reply is due, and nothing else would read the session again.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!awaiting_reply || !session_id) return;
|
||||
if ((!awaiting_reply && !running) || !session_id) return;
|
||||
|
||||
const timer = setInterval(() => void check(), AppData.BotReplyCatchUpMs);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [awaiting_reply, session_id, check]);
|
||||
}, [awaiting_reply, running, session_id, check]);
|
||||
|
||||
/**
|
||||
* The socket was down while the page stayed open: going back online or
|
||||
|
||||
@@ -26,6 +26,25 @@ function fromTask({ task }: { task: BotTaskWithSteps | null }): Progress {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The task of the session on screen, out of every task the push carries:
|
||||
* the newest of them all is often a run in another conversation, and taking
|
||||
* that one left this thread with nothing (`task` alone, when the push has no
|
||||
* list).
|
||||
*/
|
||||
function ownTask({
|
||||
data,
|
||||
session_id,
|
||||
}: {
|
||||
data: Pick<BotUpdatedData, "task" | "tasks">;
|
||||
session_id?: number | null;
|
||||
}): BotTaskWithSteps | null {
|
||||
const tasks = data.tasks || (data.task ? [data.task] : []);
|
||||
const mine = session_id ? tasks.find((task) => task.session_id == session_id) : tasks[0];
|
||||
|
||||
return mine || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The open session's active task and its latest step (a
|
||||
* `bots_queue_updates` row's text), kept current from
|
||||
@@ -54,7 +73,7 @@ export default function useTaskProgress({ bot_id, session_id, task }: Params) {
|
||||
* The user's active task with the bot may be in another of
|
||||
* their conversations with it.
|
||||
*/
|
||||
const task = data.task && (!session_id || data.task.session_id == session_id) ? data.task : null;
|
||||
const task = ownTask({ data, session_id });
|
||||
|
||||
setProgress((prev) => ((task?.id || null) == prev.task_id ? prev : fromTask({ task })));
|
||||
},
|
||||
|
||||
@@ -271,6 +271,12 @@ export default function Conversation() {
|
||||
useReplyCatchUp({
|
||||
session_id,
|
||||
awaiting_reply,
|
||||
/**
|
||||
* A queued or running task of this session keeps the poll going after
|
||||
* the reply that queued it landed: nothing else reads it again, so a
|
||||
* run waiting behind another on its computer would never show.
|
||||
*/
|
||||
running: Boolean(progress.task_id) || Boolean(open_reply_jobs),
|
||||
last_message_id: last_saved_id,
|
||||
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
|
||||
});
|
||||
|
||||
@@ -161,9 +161,9 @@ Tell the bot your time zone once ("I'm in Lagos", "I'm on New York time") and it
|
||||
|
||||
If it's given and still misses:
|
||||
|
||||
- Open the knowledgebase's documents. A document still **being read** isn't searchable yet; one that **couldn't be read** names why (a scan with no text, a file too big). Write the text in instead, or upload a version with text in it.
|
||||
- Open the knowledgebase's documents. A document still **being read** isn't searchable yet; one that **couldn't be read** names why (a scan with no text, a file too big). Write the text in instead, or upload a version with text in it. The retry icon on that document, or Retry failed in the knowledgebase's menu, reads the failed ones again and leaves the ones that succeeded.
|
||||
- Bots search by meaning only with an embedding model, picked once for the whole install in **Settings, Models** under Embeddings. Without one they match words, which misses questions worded differently from the document. Picking or changing the model reads every document again on its own; a document shows **needs re-indexing** until it's done.
|
||||
- If a document still says it needs re-indexing, use the refresh icon on its knowledgebase's row to read them all again.`,
|
||||
- If a document still says it needs re-indexing, open the knowledgebase's menu and choose Re-index to read them all again.`,
|
||||
},
|
||||
{
|
||||
id: "connect-browser",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useContext } from "react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import HeaderMenuItem from "@/src/pages/admin/bots/[bot_id]/(partials)/header-menu-item";
|
||||
import { SettingsRowMenuClose } from "./settings-row-menu";
|
||||
|
||||
type Props = {
|
||||
icon: LucideIcon;
|
||||
title: string;
|
||||
description?: string;
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One action in a settings row's three-dot menu. It closes the menu, then
|
||||
* runs, so a confirm dialog or a modal is the only thing left open.
|
||||
*/
|
||||
export default function SettingsRowMenuItem({ icon, title, description, disabled, loading, onClick }: Props) {
|
||||
const close = useContext(SettingsRowMenuClose);
|
||||
|
||||
return (
|
||||
<HeaderMenuItem
|
||||
icon={icon}
|
||||
title={title}
|
||||
description={description}
|
||||
disabled={disabled}
|
||||
loading={loading}
|
||||
onClick={() => {
|
||||
close();
|
||||
onClick();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Paper from "@moduletrace/twui/elements/Paper";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The panel a settings row's three-dot menu opens: the same surface as
|
||||
* the conversation header's menu.
|
||||
*/
|
||||
export default function SettingsRowMenuPanel({ children }: Props) {
|
||||
return (
|
||||
<Paper
|
||||
role="menu"
|
||||
className="min-w-[220px] p-0! py-1 gap-0! items-stretch rounded-default bg-surface dark:bg-surface border-hairline dark:border-hairline shadow-popover! dark:shadow-popover!"
|
||||
>
|
||||
<Stack className="w-full gap-0! items-stretch">{children}</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createContext, useState, type ReactNode } from "react";
|
||||
import Dropdown from "@moduletrace/twui/elements/Dropdown";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { EllipsisVertical } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Closes the open menu. An item that then asks to confirm, or opens a
|
||||
* modal, calls it first so the menu never sits over that.
|
||||
*/
|
||||
export const SettingsRowMenuClose = createContext<() => void>(() => {});
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* What the button is called, for the tooltip and screen readers.
|
||||
*/
|
||||
title: string;
|
||||
disabled?: boolean;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The three-dot menu on a settings row. One icon stands in for the row's
|
||||
* actions, which open as a menu. An item closes it through
|
||||
* `SettingsRowMenuClose` before it confirms or opens a modal.
|
||||
*/
|
||||
export default function SettingsRowMenu({ title, disabled, children }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<SettingsRowMenuClose.Provider value={() => setOpen(false)}>
|
||||
<Dropdown
|
||||
position="bottom-right"
|
||||
externalOpen={open}
|
||||
externalSetOpen={setOpen}
|
||||
target={
|
||||
<Button
|
||||
title={title}
|
||||
aria-label={title}
|
||||
aria-haspopup="menu"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
disabled={disabled}
|
||||
className="shrink-0 p-2! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
|
||||
>
|
||||
<EllipsisVertical size={16} aria-hidden />
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</Dropdown>
|
||||
</SettingsRowMenuClose.Provider>
|
||||
);
|
||||
}
|
||||
+27
-3
@@ -24,6 +24,7 @@ function render({
|
||||
}) {
|
||||
return renderToString(
|
||||
<HostDirectoryLinkRow
|
||||
kind="computer"
|
||||
name="Main computer"
|
||||
href="/admin/settings/computers/1"
|
||||
access={access}
|
||||
@@ -51,10 +52,32 @@ describe("HostDirectoryLinkRow", () => {
|
||||
|
||||
expect(html).toContain("Main computer");
|
||||
expect(html).toContain("/admin/settings/computers/1");
|
||||
expect(html).toContain("Computer");
|
||||
expect(html).toContain("Read and write");
|
||||
expect(html).toContain("checked");
|
||||
});
|
||||
|
||||
test("a workspace wears its own picture and says it is a workspace", () => {
|
||||
const html = renderToString(
|
||||
<HostDirectoryLinkRow
|
||||
kind="workspace"
|
||||
name="Moduletrace"
|
||||
href="/admin/settings/workspaces/4"
|
||||
image_media_id={12}
|
||||
access="read-write"
|
||||
state="unknown"
|
||||
gate_deletes
|
||||
onAccess={() => {}}
|
||||
onDeletes={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Workspace");
|
||||
expect(html).toContain("/media/");
|
||||
expect(html).toContain("12");
|
||||
});
|
||||
|
||||
test("a folder the bots can't write in shows the command to run", () => {
|
||||
const html = render({
|
||||
state: "read-only",
|
||||
@@ -70,7 +93,7 @@ describe("HostDirectoryLinkRow", () => {
|
||||
|
||||
expect(html).toContain("Read only");
|
||||
expect(html).not.toContain("The bots can't write there yet");
|
||||
expect(html).toContain("Read and write");
|
||||
expect(html).not.toContain("Give access");
|
||||
});
|
||||
|
||||
test("a check that couldn't run says why", () => {
|
||||
@@ -104,10 +127,11 @@ describe("HostDirectoryLinkRow", () => {
|
||||
expect(html).not.toContain("setfacl");
|
||||
});
|
||||
|
||||
test("a link whose bots can't write offers to give them access again", () => {
|
||||
test("a link whose bots can't write keeps its check and its menu", () => {
|
||||
const html = render({ state: "partial", onGrant: () => {} });
|
||||
|
||||
expect(html).toContain("Give access");
|
||||
expect(html).toContain("Some bots can't write");
|
||||
expect(html).toContain("Main computer menu");
|
||||
});
|
||||
|
||||
test("a read-only link never offers to give access", () => {
|
||||
|
||||
@@ -1,23 +1,37 @@
|
||||
import { CircleAlert } from "lucide-react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import type { ReactNode } from "react";
|
||||
import { CircleAlert, KeyRound, Lock, RefreshCw, ShieldOff, Unlink } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import ComputerIconTile from "@/src/components/general/computer-icon-tile";
|
||||
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
|
||||
import {
|
||||
HostDirectoryAccesses,
|
||||
type HostDirectoryAccess,
|
||||
type HostDirectoryCheckState,
|
||||
} from "@/src/dict/host-directory-dict";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import HostDirectoryCheckTag from "../../(partials)/host-directory-check-tag";
|
||||
import HostDirectoryCommandNote from "../../(partials)/host-directory-command-note";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* A computer, or a workspace. The picture is the workspace's own;
|
||||
* a computer always wears the monitor.
|
||||
*/
|
||||
kind: "computer" | "workspace";
|
||||
/**
|
||||
* The computer or workspace it is mounted in.
|
||||
*/
|
||||
name: string;
|
||||
href: string;
|
||||
/**
|
||||
* The workspace's picture. Left out for a computer, and for a
|
||||
* workspace that has none.
|
||||
*/
|
||||
image_media_id?: number | null;
|
||||
access: HostDirectoryAccess;
|
||||
state: HostDirectoryCheckState;
|
||||
checked_at?: number | null;
|
||||
@@ -57,11 +71,13 @@ type Props = {
|
||||
/**
|
||||
* One place a host directory is mounted: a computer, or a workspace (on
|
||||
* every computer it is on), what its bots can do there, and what the last
|
||||
* check found.
|
||||
* check found. The avatar says which kind it is.
|
||||
*/
|
||||
export default function HostDirectoryLinkRow({
|
||||
kind,
|
||||
name,
|
||||
href,
|
||||
image_media_id,
|
||||
access,
|
||||
state,
|
||||
checked_at,
|
||||
@@ -81,94 +97,101 @@ export default function HostDirectoryLinkRow({
|
||||
const access_title =
|
||||
HostDirectoryAccesses.find((item) => item.value == access)?.title ||
|
||||
"Read and write";
|
||||
const place = kind == "workspace" ? "Workspace" : "Computer";
|
||||
|
||||
const notes: ReactNode[] = [];
|
||||
|
||||
if (error) {
|
||||
notes.push(
|
||||
<Span key="error" role="alert" className="flex items-center gap-1.5 text-[12px] leading-4 text-ink">
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
Couldn't check it: {error}
|
||||
</Span>,
|
||||
);
|
||||
}
|
||||
|
||||
if (stale && !error) {
|
||||
notes.push(
|
||||
<Span key="stale" role="status" className="flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary">
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
A bot was added since the last check, so its account hasn't been tested. Check again.
|
||||
</Span>,
|
||||
);
|
||||
}
|
||||
|
||||
if (command) notes.push(<HostDirectoryCommandNote key="command" command={command} />);
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch border-t border-solid border-hairline py-1.5 first:border-t-0">
|
||||
<Row className="w-full gap-x-2 gap-y-1! flex-wrap items-center">
|
||||
<Link
|
||||
href={href}
|
||||
title={name}
|
||||
className="min-w-0 truncate text-[13px] leading-[18px] text-ink hover:underline"
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary">
|
||||
{access_title}
|
||||
</Span>
|
||||
<Stack className="w-full gap-1! items-stretch border-t border-solid border-hairline py-1 first:border-t-0">
|
||||
<SettingsListRow
|
||||
avatar={
|
||||
kind == "workspace" ? (
|
||||
<WorkspaceAvatar image_media_id={image_media_id} />
|
||||
) : (
|
||||
<ComputerIconTile />
|
||||
)
|
||||
}
|
||||
title={name}
|
||||
href={href}
|
||||
badge={place}
|
||||
subtitle={access_title}
|
||||
>
|
||||
<HostDirectoryCheckTag state={state} checked_at={checked_at} />
|
||||
<Row className="ml-auto shrink-0 gap-1! flex-nowrap">
|
||||
{onGrant && access == "read-write" && (stale || state == "partial" || state == "read-only") ? (
|
||||
<SettingsRowAction
|
||||
title="Give every bot that sees this folder access to it"
|
||||
label={granting ? "Giving access" : "Give access"}
|
||||
disabled={busy || checking || granting}
|
||||
onClick={onGrant}
|
||||
/>
|
||||
) : null}
|
||||
{onCheck ? (
|
||||
<SettingsRowAction
|
||||
title="Check that the bots can read and write it now"
|
||||
label={checking ? "Checking" : "Check"}
|
||||
<SettingsRowMenu title={`${name} menu`} disabled={busy || checking}>
|
||||
<SettingsRowMenuPanel>
|
||||
{onGrant && access == "read-write" && (stale || state == "partial" || state == "read-only") ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={KeyRound}
|
||||
title={granting ? "Giving access" : "Give access"}
|
||||
description="Give every bot that sees this folder access to it"
|
||||
loading={granting}
|
||||
disabled={busy || checking || granting}
|
||||
onClick={onGrant}
|
||||
/>
|
||||
) : null}
|
||||
{onCheck ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RefreshCw}
|
||||
title={checking ? "Checking" : "Check"}
|
||||
description="Check that the bots can read and write it now"
|
||||
loading={checking}
|
||||
disabled={busy || checking}
|
||||
onClick={onCheck}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowMenuItem
|
||||
icon={access == "read-write" ? Lock : KeyRound}
|
||||
title={access == "read-write" ? "Read only" : "Read and write"}
|
||||
description={
|
||||
access == "read-write"
|
||||
? "Mount it read only, so the bots can't change it"
|
||||
: "Let the bots write there"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onCheck}
|
||||
onClick={onAccess}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowAction
|
||||
title={
|
||||
access == "read-write"
|
||||
? "Mount it read only, so the bots can't change it"
|
||||
: "Let the bots write there"
|
||||
}
|
||||
label={
|
||||
access == "read-write"
|
||||
? "Read only"
|
||||
: "Read and write"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onAccess}
|
||||
/>
|
||||
<SettingsRowAction
|
||||
title={
|
||||
gate_deletes
|
||||
? "Stop asking: the bots can delete in it without your approval"
|
||||
: "Ask you before a bot deletes anything in it"
|
||||
}
|
||||
label={
|
||||
gate_deletes ? "Ask before deletes" : "Delete freely"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onDeletes}
|
||||
/>
|
||||
<SettingsRowAction
|
||||
title={`Unmount it from ${name}`}
|
||||
label="Remove"
|
||||
disabled={busy || checking}
|
||||
onClick={onRemove}
|
||||
/>
|
||||
</Row>
|
||||
</Row>
|
||||
{error ? (
|
||||
<Span
|
||||
role="alert"
|
||||
className="flex items-center gap-1.5 text-[12px] leading-4 text-ink"
|
||||
>
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
Couldn't check it: {error}
|
||||
</Span>
|
||||
) : null}
|
||||
{stale && !error ? (
|
||||
<Span
|
||||
role="status"
|
||||
className="flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary"
|
||||
>
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0" />
|
||||
A bot was added since the last check, so its account
|
||||
hasn't been tested. Check again.
|
||||
</Span>
|
||||
) : null}
|
||||
{command ? (
|
||||
<HostDirectoryCommandNote command={command} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem
|
||||
icon={gate_deletes ? ShieldOff : Lock}
|
||||
title={gate_deletes ? "Ask before deletes" : "Delete freely"}
|
||||
description={
|
||||
gate_deletes
|
||||
? "Stop asking: the bots can delete in it without your approval"
|
||||
: "Ask you before a bot deletes anything in it"
|
||||
}
|
||||
disabled={busy || checking}
|
||||
onClick={onDeletes}
|
||||
/>
|
||||
<SettingsRowMenuItem
|
||||
icon={Unlink}
|
||||
title="Remove"
|
||||
description={`Unmount it from ${name}`}
|
||||
disabled={busy || checking}
|
||||
onClick={onRemove}
|
||||
/>
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
{notes.length ? <Stack className="w-full gap-1! items-stretch px-3 pb-2">{notes}</Stack> : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { FolderTree } from "lucide-react";
|
||||
import { FolderTree, Pencil, Trash2 } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
@@ -18,7 +18,9 @@ import hostDirectoryCheckStale from "@/src/utils/host-directory-check-stale";
|
||||
import hostDirectoryPermissionCommand from "@/src/utils/host-directory-permission-command";
|
||||
import InlineAddSelect from "@/src/components/general/inline-add-select";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import HostDirectoryLinkRow from "./host-directory-link-row";
|
||||
|
||||
type Props = {
|
||||
@@ -41,8 +43,10 @@ type Props = {
|
||||
|
||||
type LinkView = {
|
||||
key: string;
|
||||
kind: "computer" | "workspace";
|
||||
name: string;
|
||||
href: string;
|
||||
image_media_id?: number | null;
|
||||
access: HostDirectoryAccess;
|
||||
state: HostDirectoryCheckState;
|
||||
checked_at?: number | null;
|
||||
@@ -177,6 +181,7 @@ export default function HostDirectoryRow({
|
||||
|
||||
return {
|
||||
key: `computer-${link.id}`,
|
||||
kind: "computer",
|
||||
name: link.computer_name || `Computer ${link.computer_id}`,
|
||||
href: `/admin/settings/computers/${link.computer_id}`,
|
||||
access,
|
||||
@@ -228,7 +233,9 @@ export default function HostDirectoryRow({
|
||||
|
||||
return {
|
||||
key: `workspace-${link.id}`,
|
||||
kind: "workspace",
|
||||
name: link.workspace_name || `Workspace ${link.workspace_id}`,
|
||||
image_media_id: link.image_media_id,
|
||||
href: `/admin/settings/workspaces/${link.workspace_id}`,
|
||||
access,
|
||||
state,
|
||||
@@ -314,26 +321,27 @@ export default function HostDirectoryRow({
|
||||
title={name}
|
||||
subtitle={source}
|
||||
>
|
||||
<SettingsRowAction
|
||||
title={`Edit ${name}`}
|
||||
label="Edit"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={onEdit}
|
||||
/>
|
||||
<SettingsRowAction
|
||||
title={`Remove ${name}`}
|
||||
label="Remove"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={remove}
|
||||
/>
|
||||
<SettingsRowMenu title={`${name} menu`} disabled={Boolean(busy)}>
|
||||
<SettingsRowMenuPanel>
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={onEdit} />
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Remove"
|
||||
description="Its computers and workspaces stop seeing the folder. Nothing in the folder itself is deleted."
|
||||
onClick={remove}
|
||||
/>
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
<Stack className="w-full gap-2! items-stretch px-3 pt-1 pb-3">
|
||||
{links.length ? (
|
||||
links.map((link) => (
|
||||
<HostDirectoryLinkRow
|
||||
key={link.key}
|
||||
kind={link.kind}
|
||||
name={link.name}
|
||||
href={link.href}
|
||||
image_media_id={link.image_media_id}
|
||||
access={link.access}
|
||||
state={link.state}
|
||||
checked_at={link.checked_at}
|
||||
|
||||
@@ -107,5 +107,14 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
|
||||
await post({ path: "knowledgebases/delete-document", body: { document_id: document.id } });
|
||||
};
|
||||
|
||||
return { documents, busy, status, upload, saveText, remove };
|
||||
const retry = async ({ document }: { document: KnowledgebaseDocument }) => {
|
||||
if (busy || !window.confirm(`Read ${document.name} again? Documents that already succeeded stay as they are.`)) return;
|
||||
|
||||
await post({
|
||||
path: "knowledgebases/retry-failed-documents",
|
||||
body: { knowledgebase_id, document_id: document.id },
|
||||
});
|
||||
};
|
||||
|
||||
return { documents, busy, status, upload, saveText, remove, retry };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileText, NotebookPen, Pencil, Trash2 } from "lucide-react";
|
||||
import { FileText, NotebookPen, Pencil, RotateCcw, Trash2 } from "lucide-react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import RowIconButton from "@/src/components/general/row-icon-button";
|
||||
@@ -17,6 +17,10 @@ type Props = {
|
||||
* can't edit.
|
||||
*/
|
||||
onEdit?: () => void;
|
||||
/**
|
||||
* Reads this document again. Given only when its last read failed.
|
||||
*/
|
||||
onRetry?: () => void;
|
||||
onDelete?: () => void;
|
||||
};
|
||||
|
||||
@@ -24,7 +28,7 @@ type Props = {
|
||||
* One document in a knowledgebase: what it is and how much of it bots can
|
||||
* search, or why it couldn't be read.
|
||||
*/
|
||||
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onDelete }: Props) {
|
||||
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onRetry, onDelete }: Props) {
|
||||
return (
|
||||
<SettingsListRow
|
||||
avatar={<IconTile Icon={document.source == "text" ? NotebookPen : FileText} />}
|
||||
@@ -44,6 +48,9 @@ export default function KnowledgebaseDocumentRow({ document, embedding_model, bu
|
||||
subtitle={knowledgebaseDocumentSummary({ document, embedding_model })}
|
||||
>
|
||||
<Row className="gap-0! flex-nowrap">
|
||||
{onRetry ? (
|
||||
<RowIconButton icon={RotateCcw} title={`Retry ${document.name}`} disabled={busy} onClick={onRetry} />
|
||||
) : null}
|
||||
{onEdit ? <RowIconButton icon={Pencil} title={`Edit ${document.name}`} disabled={busy} onClick={onEdit} /> : null}
|
||||
{onDelete ? (
|
||||
<RowIconButton icon={Trash2} title={`Delete ${document.name}`} disabled={busy} onClick={onDelete} />
|
||||
|
||||
+6
-1
@@ -34,7 +34,7 @@ type Props = {
|
||||
* done.
|
||||
*/
|
||||
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, embedding_model, onClose }: Props) {
|
||||
const { documents, busy, status, upload, saveText, remove } = useKnowledgebaseDocuments({
|
||||
const { documents, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
|
||||
knowledgebase_id: knowledgebase.id,
|
||||
});
|
||||
/**
|
||||
@@ -78,6 +78,11 @@ export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, e
|
||||
embedding_model={embedding_model}
|
||||
busy={busy}
|
||||
onEdit={can_edit && document.source == "text" ? () => setWriting(document.id) : undefined}
|
||||
onRetry={
|
||||
can_edit && document.ingest_error && !document.indexing
|
||||
? () => retry({ document })
|
||||
: undefined
|
||||
}
|
||||
onDelete={can_edit ? () => remove({ document }) : undefined}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { FileText, Library, Pencil, RefreshCw, Trash2, Users } from "lucide-react";
|
||||
import { FileText, Library, Pencil, RefreshCw, RotateCcw, Trash2, Users } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import RowIconButton from "@/src/components/general/row-icon-button";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ExtensionTargets, KnowledgebasesOverviewPayload, PublicKnowledgebase } from "@/src/types";
|
||||
import ExtensionAccessModal from "../../(partials)/extension-access-modal";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import extensionAccessLabel from "../../(utils)/extension-access-label";
|
||||
import updatedAgo from "../../(utils)/updated-ago";
|
||||
import knowledgebaseIndexState from "@/src/utils/knowledgebase-index-state";
|
||||
@@ -29,8 +30,9 @@ type Props = {
|
||||
|
||||
/**
|
||||
* One knowledgebase: how many documents it holds and how much of them is
|
||||
* searchable, and who gets it. Documents, Edit and Access open in a modal;
|
||||
* Re-index reads every document again with the install's embedding model.
|
||||
* searchable, and who gets it. Its actions live in the three-dot menu:
|
||||
* documents, who gets it, and for a super admin editing, retrying the
|
||||
* ones that failed, reading every document again, and deleting it.
|
||||
*/
|
||||
export default function KnowledgebaseRow({ knowledgebase, targets, embedding_model, onChanged, onError }: Props) {
|
||||
const [open, setOpen] = useState<"documents" | "edit" | "access">();
|
||||
@@ -93,54 +95,54 @@ export default function KnowledgebaseRow({ knowledgebase, targets, embedding_mod
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Row className="gap-0! flex-nowrap">
|
||||
<RowIconButton
|
||||
icon={FileText}
|
||||
title={`Open the documents in ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() => setOpen("documents")}
|
||||
/>
|
||||
{targets.can_edit ? (
|
||||
<RowIconButton
|
||||
icon={Pencil}
|
||||
title={`Edit ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() => setOpen("edit")}
|
||||
/>
|
||||
) : null}
|
||||
<RowIconButton
|
||||
icon={Users}
|
||||
title={`Choose who gets ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() => setOpen("access")}
|
||||
/>
|
||||
{targets.can_edit && knowledgebase.document_count ? (
|
||||
<RowIconButton
|
||||
icon={RefreshCw}
|
||||
title={`Re-index ${knowledgebase.name}: read every document again`}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/reindex-knowledgebase",
|
||||
confirm: `Read every document in ${knowledgebase.name} again? Bots keep finding the old passages until the new ones are in.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<RowIconButton
|
||||
icon={Trash2}
|
||||
title={`Delete ${knowledgebase.name}`}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/delete-knowledgebase",
|
||||
confirm: `Delete ${knowledgebase.name} and every document in it? Bots lose it at once.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</Row>
|
||||
<SettingsRowMenu title={`${knowledgebase.name} menu`} disabled={busy}>
|
||||
<SettingsRowMenuPanel>
|
||||
<SettingsRowMenuItem icon={FileText} title="Documents" onClick={() => setOpen("documents")} />
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
|
||||
{targets.can_edit && knowledgebase.warning_count ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RotateCcw}
|
||||
title="Retry failed"
|
||||
description={`Read again the ${knowledgebase.warning_count} ${knowledgebase.warning_count == 1 ? "document" : "documents"} that failed. The ones that already succeeded stay as they are.`}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/retry-failed-documents",
|
||||
confirm: `Read again the ${knowledgebase.warning_count} ${knowledgebase.warning_count == 1 ? "document" : "documents"} in ${knowledgebase.name} that failed? The ones that already succeeded stay as they are.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit && knowledgebase.document_count ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RefreshCw}
|
||||
title="Re-index"
|
||||
description="Read every document again. Bots keep finding the old passages until the new ones are in."
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/reindex-knowledgebase",
|
||||
confirm: `Read every document in ${knowledgebase.name} again? Bots keep finding the old passages until the new ones are in.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Delete"
|
||||
description="Delete it and every document in it. Bots lose it at once."
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "knowledgebases/delete-knowledgebase",
|
||||
confirm: `Delete ${knowledgebase.name} and every document in it? Bots lose it at once.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
{open == "documents" ? (
|
||||
<KnowledgebaseDocumentsModal
|
||||
|
||||
@@ -54,7 +54,11 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
|
||||
bot: {
|
||||
id: bot_id,
|
||||
...(await grabBotFace({ bot_id, user_id: user.id })),
|
||||
task: await grabActiveBotTask({ bot_id, user_id: user.id }),
|
||||
/**
|
||||
* The task of this session: the newest active one may be a
|
||||
* run in another conversation, which the page would drop.
|
||||
*/
|
||||
task: await grabActiveBotTask({ bot_id, user_id: user.id, session_id: session.id }),
|
||||
},
|
||||
step: await grabSessionReplyStep({ session_id: session.id }),
|
||||
open_jobs: await grabSessionOpenReplies({ session_id: session.id }),
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import grabKnowledgebasesOverview from "@/src/functions/backend/db/knowledgebases/grab-knowledgebases-overview";
|
||||
import listKnowledgebaseDocuments from "@/src/functions/backend/db/knowledgebases/list-knowledgebase-documents";
|
||||
import retryFailedDocuments from "@/src/functions/backend/db/knowledgebases/retry-failed-documents";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { KnowledgebaseIdRequestSchema } from "@/src/schemas/knowledgebase-schema";
|
||||
import type { KnowledgebaseDocumentsPayload, KnowledgebasesOverviewPayload } 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";
|
||||
import { z } from "zod";
|
||||
|
||||
const RequestSchema = KnowledgebaseIdRequestSchema.extend({
|
||||
/**
|
||||
* Set when the documents list retries one document; the answer is then
|
||||
* that list. Left out, the knowledgebase's row retries every failed
|
||||
* document and the answer is the overview.
|
||||
*/
|
||||
document_id: z.coerce.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Super admin only: reads again the documents whose last read failed.
|
||||
* Ones that already succeeded stay as they are.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<KnowledgebasesOverviewPayload | KnowledgebaseDocumentsPayload>
|
||||
> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
throw new AppError(`Only a super admin can do that.`);
|
||||
}
|
||||
|
||||
const { knowledgebase_id, document_id } = parseWithSchema({ schema: RequestSchema, data: body });
|
||||
const queued = await retryFailedDocuments({ knowledgebase_id, document_id });
|
||||
|
||||
await logEvent({
|
||||
title: "Knowledgebase failed documents retried",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} retried ${queued} failed ${queued == 1 ? "document" : "documents"} of the knowledgebase #${knowledgebase_id}.`,
|
||||
metadata: { knowledgebase_id, document_id, queued },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
const msg = queued
|
||||
? `Reading ${queued} failed ${queued == 1 ? "document" : "documents"} again.`
|
||||
: "Nothing failed to read.";
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg,
|
||||
singleRes: document_id
|
||||
? await listKnowledgebaseDocuments({ knowledgebase_id })
|
||||
: await grabKnowledgebasesOverview({ user_id: user.id }),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -436,6 +436,10 @@ export type HostDirectoryComputerLink = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTE
|
||||
*/
|
||||
export type HostDirectoryWorkspaceLink = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
|
||||
workspace_name?: string | null;
|
||||
/**
|
||||
* The workspace's picture, for its row. Null means the workspace icon.
|
||||
*/
|
||||
image_media_id?: number | null;
|
||||
/**
|
||||
* The computers the workspace is on, where this folder is mounted.
|
||||
*/
|
||||
@@ -691,7 +695,17 @@ export type BotUpdatedData = {
|
||||
id: number;
|
||||
face: BotFace;
|
||||
status_line: string;
|
||||
/**
|
||||
* The newest of the user's active tasks, null when there is none. Kept
|
||||
* for a reader that wants one; `tasks` has them all, since the newest
|
||||
* may be in another conversation.
|
||||
*/
|
||||
task: BotTaskWithSteps | null;
|
||||
/**
|
||||
* Every active task the user has with the bot, newest first: the
|
||||
* conversation picks the one from its own session.
|
||||
*/
|
||||
tasks?: BotTaskWithSteps[];
|
||||
/**
|
||||
* The computer the bot is on, when the push knows it (a switch, or the
|
||||
* live relay). Null means its main one.
|
||||
|
||||
@@ -287,6 +287,43 @@ I'll report what the run actually finds when it reports back.`;
|
||||
expect(problems[0]).toContain("list_graphics");
|
||||
});
|
||||
|
||||
test("names a proposal that was never made", () => {
|
||||
/**
|
||||
* Session 146: the model wrote `[proposal:19]` before proposal 19
|
||||
* existed (it guessed the next number), and the user read "I didn't
|
||||
* get the proposal" four times. Only the tool's own ref may appear.
|
||||
*/
|
||||
const problems = replyClaimProblems({
|
||||
text: "Proposed as [proposal:19]: Co-Marketing.",
|
||||
tool_uses: [{ name: "send_reply", ok: true }],
|
||||
missing_proposal_ids: [19],
|
||||
missing_hook_proposal_ids: [4],
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain("[proposal:19]");
|
||||
expect(problems[0]).toContain("was ever made");
|
||||
|
||||
expect(
|
||||
replyClaimProblems({
|
||||
text: "Proposed as [proposal:19]: Co-Marketing.",
|
||||
tool_uses: [{ name: "propose_skill", ok: true }],
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("names a hook proposal that was never made", () => {
|
||||
const problems = replyClaimProblems({
|
||||
text: "The hook is on the card: [hook-proposal:4]",
|
||||
tool_uses: [{ name: "send_reply", ok: true }],
|
||||
missing_hook_proposal_ids: [4],
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain("[hook-proposal:4]");
|
||||
expect(problems[0]).toContain("was ever made");
|
||||
});
|
||||
|
||||
test("an answer that holds up has no problems", () => {
|
||||
expect(replyClaimProblems({ text: "Task #20 is cancelled.", tool_uses: [] })).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -41,6 +41,14 @@ type Params = {
|
||||
* hand-written one is made up or copied from an earlier message.
|
||||
*/
|
||||
written_card_refs?: string[];
|
||||
/**
|
||||
* `[proposal:ID]` / `[hook-proposal:ID]` refs in the text that name no
|
||||
* proposal the user was ever made: the model guessed the next id and
|
||||
* described a card nobody got ("I didn't get the proposal", four times
|
||||
* in one conversation).
|
||||
*/
|
||||
missing_proposal_ids?: number[];
|
||||
missing_hook_proposal_ids?: number[];
|
||||
/**
|
||||
* A run of the bot's, a job it handed over or a room it asked, still
|
||||
* open from this conversation: its result is still to come.
|
||||
@@ -98,6 +106,8 @@ export default function replyClaimProblems({
|
||||
unresolved_setting_refs = [],
|
||||
missing_graphic_ids = [],
|
||||
written_card_refs = [],
|
||||
missing_proposal_ids = [],
|
||||
missing_hook_proposal_ids = [],
|
||||
has_open_work,
|
||||
status,
|
||||
}: Params): string[] {
|
||||
@@ -133,6 +143,22 @@ export default function replyClaimProblems({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A proposal ref that names nothing the user was made: a guessed number.
|
||||
* The card only exists once the tool that proposes returned it, so a
|
||||
* ref written beside the answer describes one nobody got.
|
||||
*/
|
||||
if (missing_proposal_ids.length || missing_hook_proposal_ids.length) {
|
||||
const refs = [
|
||||
...missing_proposal_ids.map((id) => `[proposal:${id}]`),
|
||||
...missing_hook_proposal_ids.map((id) => `[hook-proposal:${id}]`),
|
||||
];
|
||||
|
||||
problems.push(
|
||||
`It names ${refs.join(", ")}, and no such proposal was ever made to the user. A proposal exists only once the tool that proposes one returned its ref (propose_skill, propose_browser, propose_hook and the like); the app puts that ref under your message itself, so never write one or guess the next number. Call the tool again if the proposal should be made now.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A card ref the model wrote itself: the app adds every one of these
|
||||
* from the tool that made the card, so a written one is a card that was
|
||||
|
||||
@@ -3,7 +3,7 @@ type Params = {
|
||||
/**
|
||||
* The ref's kind, as in `[file:12]`, `[task:20]` or `[suggestion:4]`.
|
||||
*/
|
||||
kind: "file" | "task" | "suggestion" | "question" | "plan" | "graphic";
|
||||
kind: "file" | "task" | "suggestion" | "question" | "plan" | "graphic" | "proposal" | "hook-proposal";
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import stripAppRecords from "./strip-app-records";
|
||||
import stripCardRefs from "./strip-card-refs";
|
||||
import stripUnresolvedSettingRefs from "./strip-unresolved-setting-refs";
|
||||
|
||||
/**
|
||||
* What the app takes out of an answer before anything reads it: a
|
||||
* `[setting:...]` pill that leads nowhere and an app record line the run's
|
||||
* own tools don't support. Both are text the app would never show as its
|
||||
* own word, so they are removed rather than sent back for a rewrite: three
|
||||
* faults in one run used to cost the user an answer that was otherwise
|
||||
* right (`reviewBotReply`).
|
||||
* `[setting:...]` pill that leads nowhere, an app record line the run's
|
||||
* own tools don't support, and the ref of a card the app adds itself
|
||||
* (`[question:]`, `[suggestion:]`, `[plan:]`). All are text the app would
|
||||
* never show as its own word, so they are removed rather than sent back for
|
||||
* a rewrite: three faults in one run used to cost the user an answer that
|
||||
* was otherwise right (`reviewBotReply`).
|
||||
*/
|
||||
export default function sanitizeAnswerText({ text }: { text: string }) {
|
||||
return stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) });
|
||||
return stripCardRefs({ text: stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) }) });
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { AppCardRefTools, type AppCardRefKind } from "./reply-claim-problems";
|
||||
|
||||
type Params = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
const CardRefKinds = Object.keys(AppCardRefTools) as AppCardRefKind[];
|
||||
|
||||
/**
|
||||
* One card ref alone in its code span (which still links), with the span.
|
||||
*/
|
||||
const codeSpan = ({ kind }: { kind: AppCardRefKind }) => new RegExp(`\`\\s*\\[${kind}:\\d+\\]\\s*\`[ \\t]?`, "gi");
|
||||
|
||||
/**
|
||||
* A ref between words leaves one space behind, never two: `[ \t]*` around it
|
||||
* stays on the same line, so paragraph breaks survive.
|
||||
*/
|
||||
const inline = ({ kind }: { kind: AppCardRefKind }) => new RegExp(`[ \\t]*\\[${kind}:\\d+\\][ \\t]*`, "gi");
|
||||
|
||||
/**
|
||||
* A bot's own text with the refs of the cards the app adds under a message
|
||||
* taken out (`[question:24]`, `[suggestion:7]`, `[plan:3]`). The app writes
|
||||
* every one of those from the tool that made the card, so one in the model's
|
||||
* text was written by hand, and the user reads it as a card that was never
|
||||
* made ("not available") or as a second copy of one. Taken out rather than
|
||||
* sent back for a rewrite: three faults in one run cost the user an answer,
|
||||
* and a model that sees the ref in its own history learns to write it again
|
||||
* (session 146: a whole thread of `[question:N]` refs it had never made).
|
||||
*/
|
||||
export default function stripCardRefs({ text }: Params): string {
|
||||
if (!CardRefKinds.some((kind) => new RegExp(`\\[${kind}:\\d+\\]`, "i").test(text))) return text;
|
||||
|
||||
let stripped = text;
|
||||
|
||||
for (const kind of CardRefKinds) {
|
||||
stripped = stripped.replace(codeSpan({ kind }), "").replace(inline({ kind }), " ");
|
||||
}
|
||||
|
||||
return stripped
|
||||
.replace(/[ \t]+$/gm, "")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unfinishedAnswerText from "./unfinished-answer-text";
|
||||
|
||||
describe("unfinishedAnswerText", () => {
|
||||
test("a table row that stops after its label is unfinished", () => {
|
||||
const text = ["| Skill | Focus |", "|-------|-------|", "| **revops** | Lead routing"].join("\n");
|
||||
|
||||
expect(unfinishedAnswerText({ text }) ?? "").toContain("table row");
|
||||
});
|
||||
|
||||
test("a separator is not an open row", () => {
|
||||
expect(unfinishedAnswerText({ text: "| Skill | Focus |\n|-------|-------|" })).toBeNull();
|
||||
});
|
||||
|
||||
test("a table row whose last cell never closed is unfinished", () => {
|
||||
const text = "| **revops** | Lead routing, scoring";
|
||||
|
||||
expect(unfinishedAnswerText({ text })).toContain("table row");
|
||||
});
|
||||
|
||||
test("a finished table is a reply", () => {
|
||||
const text = ["| Skill | Focus |", "| **revops** | Lead routing |", "", "Want me to pull one in full?"].join("\n");
|
||||
|
||||
expect(unfinishedAnswerText({ text })).toBeNull();
|
||||
});
|
||||
|
||||
test("a fence left open is unfinished", () => {
|
||||
expect(unfinishedAnswerText({ text: "The script:\n\n```ts\nconst n = 1" })).toContain("code fence");
|
||||
});
|
||||
|
||||
test("a closed fence is a reply", () => {
|
||||
expect(unfinishedAnswerText({ text: "```ts\nconst n = 1\n```\n\nThat is the whole script." })).toBeNull();
|
||||
});
|
||||
|
||||
test("a heading or list marker with nothing under it is unfinished", () => {
|
||||
expect(unfinishedAnswerText({ text: "What I found\n\n##" })).toContain("heading");
|
||||
expect(unfinishedAnswerText({ text: "Next:\n\n-" })).toContain("heading");
|
||||
expect(unfinishedAnswerText({ text: "1." })).toContain("heading");
|
||||
});
|
||||
|
||||
test("a finished heading and a pipe in prose are replies", () => {
|
||||
expect(unfinishedAnswerText({ text: "## What I found\n\nTwo repos, nothing pulled yet." })).toBeNull();
|
||||
expect(unfinishedAnswerText({ text: "Use a | between the columns when you write it." })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Why an answer stops inside a structure the model meant to finish, or
|
||||
* null when the text can stand as a reply. The check is structural: a
|
||||
* table row with no close, a fence left open, a heading or list marker
|
||||
* with nothing under it. It never decides that a follow-up was owed.
|
||||
* That is the model's call (`suggest_next_steps`), and reading it out of
|
||||
* prose is what `send_reply` exists to stop.
|
||||
*/
|
||||
export default function unfinishedAnswerText({ text }: { text: string }): string | null {
|
||||
const trimmed = text.trim();
|
||||
|
||||
if (!trimmed) return null;
|
||||
|
||||
if (openFence({ text: trimmed })) {
|
||||
return "The message stops inside a code fence that was never closed. Finish the fence, or take it out, and send the whole message again.";
|
||||
}
|
||||
|
||||
const last = lastContentLine({ text: trimmed });
|
||||
|
||||
if (openTableRow({ line: last })) {
|
||||
return "The message stops in the middle of a markdown table row. Finish that row and the table, or take the unfinished row out, and send the whole message again.";
|
||||
}
|
||||
|
||||
if (bareMarker({ line: last })) {
|
||||
return "The message stops on a heading or a list marker with nothing under it. Finish that part, or take the marker out, and send the whole message again.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A fence is open when an odd number of fence lines remain. A fence line
|
||||
* is ``` or ~~~ with nothing but an optional language tag after it, so a
|
||||
* row of dashes in a table is not one.
|
||||
*/
|
||||
function openFence({ text }: { text: string }) {
|
||||
let open = false;
|
||||
|
||||
for (const line of text.split("\n")) {
|
||||
if (/^ {0,3}(`{3,}|~{3,})[^`~]*$/.test(line.trimEnd())) open = !open;
|
||||
}
|
||||
|
||||
return open;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last line that holds something. Trailing blank lines are how a
|
||||
* model ends a paragraph, not how it ends a table.
|
||||
*/
|
||||
function lastContentLine({ text }: { text: string }) {
|
||||
const lines = text.split("\n");
|
||||
|
||||
for (let index = lines.length - 1; index >= 0; index--) {
|
||||
const line = lines[index]!.trim();
|
||||
|
||||
if (line) return line;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* A table row that opened and never closed: `| **revops** |` with the
|
||||
* rest of the cell on no line at all, or a row whose last cell is still
|
||||
* being written (`| **revops** | Lead routing`). A finished row ends with
|
||||
* `|`. A separator (`|---|---|`) is finished too. A line that merely
|
||||
* mentions a pipe in prose is left alone.
|
||||
*/
|
||||
function openTableRow({ line }: { line: string }) {
|
||||
if (!line.startsWith("|")) return false;
|
||||
if (line.endsWith("|")) return false;
|
||||
if (/^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(line)) return false;
|
||||
|
||||
return (line.match(/\|/g) || []).length >= 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A heading, or a list marker, whose line holds nothing else. A heading
|
||||
* with its text, and a list item with its text, are finished lines.
|
||||
*/
|
||||
function bareMarker({ line }: { line: string }) {
|
||||
return /^#{1,6}$/.test(line) || /^[-*+]$/.test(line) || /^\d{1,3}[.)]$/.test(line);
|
||||
}
|
||||
Reference in New Issue
Block a user