Keep Plan mode on through an ask_user answer

Session 135 answered a coordinator's ask_user card and the next reply
proposed and created a custom tool while the header still said Plan mode
was on. Two gaps let it happen.

The card's answer was posted as an ordinary user message and queued as a
plain reply, so run-bot-reply read plan_mode as false and applied no
allowlist. bot_questions now records plan_mode from the run that asked,
and postBotQuestionAnswers carries it onto the message and the queued
reply, for both the answer and the skip. Only Tab, or approving a plan,
leaves the mode; the prompt's "their answer runs with the save allowed"
escape is gone from PlanModeNote, planModeFileEscape and their review
fault.

The mode also hid write tools, so a refused call came back as "There is
no tool called ...", which is untrue and hides the reason. filterPlanModeTools
becomes gatePlanModeTools: every tool keeps its name, description and
schema, and only run is replaced with the Plan mode refusal, so the bot
reads why it stopped and can say so. load_tools is gated the same way, so
a deferred tool can't be pulled in.

prose-choice-question now reads an offer ending in a colon ("Want me to:")
and treats "want me to", "should i" and "shall i" as choice cues, so the
reply that closed session 135 is sent back to ask_user instead of being
shipped as prose options.
This commit is contained in:
2026-11-21 17:19:49 +01:00
parent 91b92cab0d
commit ce89480c15
21 changed files with 355 additions and 79 deletions
+2 -2
View File
@@ -93,7 +93,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its avatar or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. The thread follows new messages while it sits at its bottom and offers "Jump to latest" (`ScrollToBottomButton`) when scrolled up; End does what that button does and Home goes back to the top of the messages loaded so far, both keeping away from a field being typed in, an open menu and an open modal (`typingInField`, `scrollThreadToTop`). On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; the gesture is a plain state machine in `(utils)/pull-to-refresh-gesture.ts`, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with `AppData.PullToRefreshEndSlackPx` of slack through `atThreadEnd`, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` holds the tools to `PlanModeToolNames` (reads and the plan/question/suggestion cards, never `load_tools`), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and asks with `ask_user` whether to save it (the answer runs without the mode), and `planModeFileEscape` sends a reply back when it hands the save to the user instead.
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` gates every tool outside `PlanModeToolNames` (`gatePlanModeTools`: the write tools stay listed with their own name, description and schema, and calling one throws the Plan mode reason, never "there is no tool called ...", since only `run` is replaced; `load_tools` is gated too, so a deferred MCP or browser tool can't be pulled in), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. **Answering or skipping an `ask_user` card is not a way out:** the card carries `bot_questions.plan_mode` from the run that asked, and `postBotQuestionAnswers` runs the answer as a Plan mode reply too (only Tab, or approving a plan, turns the mode off). A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and either writes a plan they approve or tells them to turn Plan mode off, and `planModeFileEscape` sends a reply back when it hands the save to the user instead.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[secret:ID]` (masked env, Reveal/Copy), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). A plan, questions, a proposal, a hook proposal and a secret request show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so `MarkdownParagraph` (`(partials)/markdown-paragraph.tsx`) lifts those refs out of the paragraph they were written in (`isCardRefHref` in `(utils)/card-ref-href.ts`), which React would otherwise refuse inside a `p`. Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload, and a chip whose card the user just decided (`primeRefView`) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (`subscribeRefView`; `useBotPlan` instead re-reads on `server:bot-plan`). Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
- **Message images:** a bot message shows the images it's about under its text (`MessageImages` in `(partials)/`, on `BotMessageLine` and `CrewMessageLine`): its image attachments plus every image `[file:ID]` it names (`liveFileRefIds`, which keeps the renderer's code rules), deduped when a named file is also attached (`file_id`). Each is a `MessageAttachment` thumbnail opening the shared `FilePreviewModal`; in a thread its gallery is the whole conversation (`sessionImageGallery` + `SessionGalleryContext` from `MessageThread`): every image in the session, bot and user, in message order, deduped by URL, falling back to the message's own images outside a thread. Non-image files and unreachable refs show nothing. Named files resolve through `useBotFile`/`useReferencedFiles` (page props first, then the cached `api/admin/bots/files` read shared with `FileRefChip`). A thumbnail URL serves the original when no smaller copy was made (`mediaServeWritePath`), since bot files keep no thumbnail.
@@ -129,7 +129,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
- 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?, 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), asks the user to choose in the text (a question with a numbered or bulleted list of options under it, `proseChoiceQuestion`) without an `ask_user` call in the run, so they would retype an option instead of clicking one (session 133 shipped two), 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 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), asks the user to choose in the text (a question, or an offer ending in ":" such as "Want me to:", with a numbered or bulleted list of options under it, `proseChoiceQuestion`) without an `ask_user` call in the run, so they would retype an option instead of clicking one (session 133 shipped two), 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.
+6
View File
@@ -2000,6 +2000,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "plan_mode",
fieldDescription: `Asked in a Plan mode reply: their answer and skip are run in Plan mode too, since answering is not a way out of the mode`,
dataType: "INTEGER",
defaultValue: 0,
},
],
indexes: [
{
+4
View File
@@ -1292,6 +1292,10 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
* The session's workspace; null for the bot's own chat. Not a foreign key
*/
workspace_id?: number | "";
/**
* Asked in a Plan mode reply: their answer and skip are run in Plan mode too, since answering is not a way out of the mode
*/
plan_mode?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
+2 -2
View File
@@ -29,8 +29,8 @@ type Params = {
*/
job_id?: number | string;
/**
* The reply was sent with Plan mode on, so the writing tools are left
* out on purpose (`PlanModeToolNames`).
* The reply was sent with Plan mode on, so the writing tools are gated on
* purpose (`PlanModeToolNames`).
*/
plan_mode?: boolean;
/**
+2 -1
View File
@@ -10,7 +10,8 @@ type Params = {
job_id?: number | string;
/**
* The run is a reply with Plan mode on (`PlanModeToolNames`), so a file
* can't be saved until the user leaves the mode or answers a card.
* can't be saved until the user leaves the mode (Tab) or approves a
* plan. Answering a card does not leave it.
*/
plan_mode?: boolean;
scopes: StorageScope[];
+11 -5
View File
@@ -43,7 +43,7 @@ import BotJobFatalError from "@/src/bots-queue/bot-job-fatal-error";
import runTextLoop from "@/src/harness/text/run-text-loop";
import type { HarnessTool } from "@/src/harness/types";
import grabBotChatTools from "@/src/harness/tools/bot/grab-bot-chat-tools";
import filterPlanModeTools from "@/src/harness/tools/bot/plan-mode-tools";
import gatePlanModeTools from "@/src/harness/tools/bot/plan-mode-tools";
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes";
@@ -155,8 +155,9 @@ export default async function runBotReply({
const on_plan_step = Number(job_params.plan_id) > 0;
/**
* The user sent the message with Plan mode on (`bot_messages.plan_mode`):
* the answer plans and reads, and changes nothing. The tools are filtered
* to `PlanModeToolNames`, and `send_reply` refuses work.
* the answer plans and reads, and changes nothing. Every write tool
* stays listed and refuses (`gatePlanModeTools`), and `send_reply`
* refuses work.
*/
const plan_mode = Boolean(job_params.plan_mode);
/**
@@ -488,7 +489,7 @@ export default async function runBotReply({
/**
* Every tool the reply may call, built once so Plan mode can hold the
* whole list to its allowlist (`filterPlanModeTools`).
* whole list to its allowlist (`gatePlanModeTools`).
*/
const reply_tools: HarnessTool[] = [
...tools,
@@ -540,6 +541,11 @@ export default async function runBotReply({
bot_id: bot.id,
session_id,
workspace_id,
/**
* Recorded on the card: its answer stays in Plan mode
* when it was asked in it (`postBotQuestionAnswers`).
*/
plan_mode,
onAsk: ({ ref }) => proposals.push(ref),
}),
suggestNextStepsTool({
@@ -660,7 +666,7 @@ export default async function runBotReply({
.filter(Boolean)
.join("\n\n"),
messages: await messagesToTurns({ messages: history, user_id }),
tools: plan_mode ? filterPlanModeTools({ tools: reply_tools }) : reply_tools,
tools: plan_mode ? gatePlanModeTools({ tools: reply_tools }) : reply_tools,
max_steps: reply_max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
+7 -7
View File
@@ -1033,19 +1033,19 @@ Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_s
/**
* Plan mode: the user turned it on in the composer, so this reply plans and
* reads, and changes nothing. The tools are filtered to the allowlist
* (`PlanModeToolNames`) and `send_reply` refuses work, so this note is what
* tells the bot why its usual ways are gone.
* reads, and changes nothing. Every write tool stays listed and refuses
* (`gatePlanModeTools`) and `send_reply` refuses work, so this note is what
* tells the bot why, and that answering a question is not a way out.
*/
export const PlanModeNote = `# Plan mode
The user sent this message with Plan mode on. This reply plans, reads and asks; it changes nothing, anywhere.
- Read what you need: files, tasks, schedules, hooks, graphics, knowledgebases, skills, past conversations, computers and the crew are all readable. Then say what you found and what you would do.
- When the work is several pieces that build on each other, write the plan with create_plan (3 to 6 steps) and let them approve it. Nothing in it starts until they do, and working its steps is a later reply.
- When a choice is theirs, ask it with ask_user instead of picking for them.
- Nothing is written, run or changed in this mode: no files written, no tasks, schedules, hooks, memory or instructions changed, no secrets, no crew changes, no computers, browsers, MCP servers or custom tools. Don't say you did any of that, and don't say a run is under way.
- When the result belongs in a file or somewhere outside the chat (a document, a task, a memory), don't paste it and never say a tool is missing: Plan mode is what stops the save. Say so in one sentence and ask once with ask_user whether to save it, with "Save it and send the file" first; their answer runs with the save allowed, so write it then. A short template they asked to read can stay in the message.
- When the work is several pieces that build on each other, write the plan with create_plan (3 to 6 steps) and let them approve it. Nothing in it starts until they do, and working its steps is a later reply. Approving it ends Plan mode.
- When a choice is theirs, ask it with ask_user instead of picking for them. Answering it does not end Plan mode: their answer is another planning turn.
- Nothing is written, run or changed in this mode: no files written, no tasks, schedules, hooks, memory or instructions changed, no secrets, no crew changes, no computers, browsers, MCP servers or custom tools. Those tools are still in your list and calling one is refused with the reason, so don't say you did any of it, don't say a run is under way, and don't look for another way in.
- When the result belongs in a file or somewhere outside the chat (a document, a task, a memory), don't paste it and never say a tool is missing: Plan mode is what stops the save. Say so in one sentence, and either write it as a plan they can approve (its steps save it) or tell them to turn Plan mode off (Tab) and you will write it. A short template they asked to read can stay in the message.
- End with send_reply: done sends the plan or the answer, blocked says what stopped you. Work can't be queued here.
- Say what you would do and what it depends on, not that you are doing it.`;
@@ -7,6 +7,10 @@ type Params = {
bot_id: number | string;
session_id: number | string;
workspace_id?: number | string | null;
/**
* Asked in a Plan mode reply: the answers are run in Plan mode too.
*/
plan_mode?: boolean;
title: string;
questions: BotQuestionItem[];
};
@@ -15,7 +19,7 @@ type Params = {
* Stores questions a bot asks the user, pending until they answer or skip
* them in its card. Returns its id.
*/
export default async function createBotQuestion({ user_id, bot_id, session_id, workspace_id, title, questions }: Params) {
export default async function createBotQuestion({ user_id, bot_id, session_id, workspace_id, plan_mode, title, questions }: Params) {
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_QUESTIONS, (typeof BunSQLiteTables)[number]>({
table: "bot_questions",
data: [
@@ -27,6 +31,7 @@ export default async function createBotQuestion({ user_id, bot_id, session_id, w
bot_id: Number(bot_id),
session_id: Number(session_id),
workspace_id: workspace_id ? Number(workspace_id) : undefined,
plan_mode: plan_mode ? 1 : 0,
},
],
});
@@ -0,0 +1,96 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BotQuestionView } from "@/src/types";
/**
* The answers to a bot's questions as the conversation receives them. The
* production fault this pins: session 135's bot asked in Plan mode, the
* user answered on the card, and the answer was queued as an ordinary
* reply, so the write tools came back and it proposed a custom tool the
* user never asked for. Answering a question is not a way out of the mode.
*
* The side-effect helpers are mocked; the branch under test is the one that
* carries the mode from the card onto the message and the job.
*/
let question: { bot_id: number; session_id: number; workspace_id: number | null; plan_mode: number };
let inserted: Array<Record<string, unknown>> = [];
let enqueued: Array<Record<string, unknown>> = [];
let pushed: number[] = [];
mock.module("@/src/functions/backend/db/bot-questions/grab-bot-question", () => ({
default: async () => ({ id: 30, ...question }),
}));
mock.module("@/src/functions/backend/db/bot-sessions/grab-user-bot-session", () => ({
default: async ({ session_id }: { session_id: number }) => ({
id: session_id,
workspace_id: null,
status: "active",
ask_id: null,
hook_id: null,
}),
}));
mock.module("@/src/functions/backend/db/bot-sessions/ensure-bot-session", () => ({
default: async () => ({ id: 135, workspace_id: null, status: "active" }),
}));
mock.module("@/src/functions/backend/db/bots/insert-user-message", () => ({
default: async (params: Record<string, unknown>) => {
inserted.push(params);
return { id: 982, ...params };
},
}));
mock.module("@/src/functions/backend/db/bots-queue/enqueue-bot-reply", () => ({
default: async (params: Record<string, unknown>) => {
enqueued.push(params);
},
}));
mock.module("@/src/bots-queue/push-bot-notice", () => ({
default: async ({ message }: { message: { id: number } }) => {
pushed.push(message.id);
},
}));
mock.module("@/src/bots-queue/wake-bots-queue", () => ({
default: () => {},
}));
mock.module("@/src/functions/backend/logger", () => ({
logError: async () => {},
}));
const { default: postBotQuestionAnswers } = await import("./post-bot-question-answers");
afterAll(() => {
mock.restore();
});
const view = {
id: 30,
status: "answered",
questions: [{ question: "Which mailbox?", kind: "single", options: ["Work", "Personal"], allow_other: false }],
answers: [{ choices: [0], other: "" }],
} as unknown as BotQuestionView;
beforeEach(() => {
question = { bot_id: 1, session_id: 135, workspace_id: null, plan_mode: 0 };
inserted = [];
enqueued = [];
pushed = [];
});
describe("postBotQuestionAnswers", () => {
test("runs the answer in Plan mode when the question was asked in it", async () => {
question.plan_mode = 1;
await postBotQuestionAnswers({ view, user_id: 1 });
expect(inserted).toHaveLength(1);
expect(inserted[0]!.plan_mode).toBe(true);
expect(enqueued).toHaveLength(1);
expect(enqueued[0]!.params).toEqual({ plan_mode: true });
expect(pushed).toEqual([982]);
});
test("runs an ordinary answer as an ordinary reply", async () => {
await postBotQuestionAnswers({ view, user_id: 1 });
expect(inserted[0]!.plan_mode).toBe(false);
expect(enqueued[0]!.params).toBeUndefined();
});
});
@@ -31,11 +31,19 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
const session = await pickSession({ row, user_id });
/**
* Asked in Plan mode, answered and skipped in it: a question is
* about what to plan, so its answer must not unlock the write
* tools (the only ways out are Tab and approving a plan).
*/
const plan_mode = Boolean(row.plan_mode);
const message = await insertUserMessage({
bot_id: Number(row.bot_id),
session_id: Number(session.id),
workspace_id: session.workspace_id || null,
text: botQuestionAnswersText({ view }),
plan_mode,
});
await pushBotNotice({ bot_id: row.bot_id, message });
@@ -45,6 +53,7 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
bot_id: row.bot_id,
session_id: Number(session.id),
message_id: Number(message.id),
...(plan_mode ? { params: { plan_mode: true } } : {}),
});
wakeBotsQueue();
+1 -1
View File
@@ -110,7 +110,7 @@ type Params = {
onAttach?: (params: { media_id: number; name: string }) => void;
/**
* Plan mode: the reply plans and reads, and starts nothing. `send_reply`
* refuses work, and `run-bot-reply` filters the tools to the allowlist.
* refuses work, and `run-bot-reply` gates the tools to the allowlist.
*/
plan_mode?: boolean;
};
+68 -31
View File
@@ -1,50 +1,87 @@
import { describe, expect, test } from "bun:test";
import type { HarnessTool } from "../../types";
import filterPlanModeTools, { PlanModeToolNames } from "./plan-mode-tools";
import gatePlanModeTools, { PlanModeToolNames } from "./plan-mode-tools";
const tool = (name: string): HarnessTool => ({
name,
description: name,
run: async () => "",
description: `${name} description`,
run: async () => `${name} ran`,
});
describe("Plan mode's tool allowlist", () => {
test("keeps the reads and the mode's own cards", () => {
const kept = filterPlanModeTools({
const runTool = (planned: HarnessTool) => planned.run({ args: {}, signal: new AbortController().signal });
describe("Plan mode's tool gate", () => {
test("keeps every tool listed, so a write is seen and refused rather than missing", () => {
const names = ["read_file", "list_tasks", "create_plan", "write_file", "propose_custom_tool", "computer_bash", "load_tools"];
const planned = gatePlanModeTools({ tools: names.map((name) => tool(name)) });
expect(planned.map((planned_tool) => planned_tool.name)).toEqual(names);
});
test("leaves the reads and the mode's own cards running", async () => {
const planned = gatePlanModeTools({
tools: [tool("read_file"), tool("list_tasks"), tool("create_plan"), tool("send_reply"), tool("ask_user")],
});
expect(kept.map((kept_tool) => kept_tool.name)).toEqual(["read_file", "list_tasks", "create_plan", "send_reply", "ask_user"]);
for (const planned_tool of planned) {
expect(await runTool(planned_tool)).toBe(`${planned_tool.name} ran`);
}
});
test("drops every write, computer, browser and extension tool", () => {
const kept = filterPlanModeTools({
tools: [
tool("write_file"),
tool("import_file"),
tool("update_memory"),
tool("create_task"),
tool("create_graphic"),
tool("react_to_message"),
tool("ask_bot"),
tool("start_task"),
tool("delegate_task"),
tool("hand_over_task"),
tool("computer_bash"),
tool("browser_navigate"),
tool("load_tools"),
tool("show_secret"),
tool("send_message"),
],
});
test("refuses every write, computer, browser and extension tool with the Plan mode reason", async () => {
const blocked = [
"write_file",
"import_file",
"update_memory",
"create_task",
"create_graphic",
"react_to_message",
"ask_bot",
"start_task",
"delegate_task",
"hand_over_task",
"computer_bash",
"browser_navigate",
"load_tools",
"show_secret",
"send_message",
"propose_custom_tool",
];
expect(kept).toEqual([]);
const planned = gatePlanModeTools({ tools: blocked.map((name) => tool(name)) });
for (const planned_tool of planned) {
const refusal = await runTool(planned_tool).catch((error: Error) => error.message);
expect(refusal).toContain("Plan mode is on for this reply");
expect(refusal).toContain(`${planned_tool.name} did not run`);
expect(refusal).toContain("turn Plan mode off (Tab)");
}
});
test("holds a tool nobody named yet out, so the list stays an allowlist", () => {
const tools = [tool("read_file"), tool("a_tool_shipped_later")];
test("keeps a blocked tool's description, schema and deferral, so the model still sees what it is", async () => {
const deferred: HarnessTool = {
...tool("browser_navigate"),
description: "Open a page in the browser",
parameters: { type: "object" },
deferred: true,
timeout_ms: 5_000,
};
expect(filterPlanModeTools({ tools }).map((kept_tool) => kept_tool.name)).toEqual(["read_file"]);
const planned = gatePlanModeTools({ tools: [deferred] })[0]!;
expect(planned.description).toBe("Open a page in the browser");
expect(planned.parameters).toEqual({ type: "object" });
expect(planned.deferred).toBe(true);
expect(planned.timeout_ms).toBe(5_000);
expect(planned.run).not.toBe(deferred.run);
});
test("holds a tool nobody named yet off, so the list stays an allowlist", async () => {
const [planned] = gatePlanModeTools({ tools: [tool("a_tool_shipped_later")] });
await expect(runTool(planned!)).rejects.toThrow("a_tool_shipped_later did not run");
});
test("every allowed name is lowercase with underscores", () => {
+34 -7
View File
@@ -4,7 +4,7 @@ import type { HarnessTool } from "../../types";
/**
* Everything a reply may still call with Plan mode on. It is an allowlist,
* never a denylist: a tool added to a factory later is left out until it
* never a denylist: a tool added to a factory later is refused until it
* is named here on purpose, so a planning run can't gain a way to write
* just because someone shipped one.
*
@@ -52,10 +52,37 @@ export const PlanModeToolNames = [
const allowed = new Set<string>(PlanModeToolNames);
/**
* The run's tools, held to the plan-mode allowlist. Applied after every
* factory has had its say, so the mode holds whatever the run's bot type,
* workspace, extensions, browsers or skills would otherwise hand it.
* What a write tool called in Plan mode answers the model, worded like
* `send_reply`'s refusal. It says the tool did nothing and why, so the
* bot tells the user Plan mode stopped it instead of inventing a reason
* or looking for another way in. A tool that vanished from the list
* instead read as "there is no tool called ...", which was untrue.
*/
export default function filterPlanModeTools({ tools }: { tools: HarnessTool[] }): HarnessTool[] {
return tools.filter((tool) => allowed.has(tool.name));
}
function planModeRefusal({ name }: { name: string }) {
return `Plan mode is on for this reply: it plans and reads, and changes nothing, so ${name} did not run and nothing was changed. Say plainly that Plan mode stops it, and that they can turn Plan mode off (Tab) to have it done; otherwise finish with send_reply.`;
}
/**
* The run's tools with every write held off. Applied after every factory
* has had its say, so the mode holds whatever the run's bot type,
* workspace, extensions, browsers or skills would otherwise hand it.
*
* The tools stay listed, with their own name, description and schema: the
* bot is meant to see the write it is reaching for and be told why it
* can't, rather than wonder why the tool it needs doesn't exist. Only
* `run` is replaced, and it throws so the call is reported as failed.
* `load_tools` is here too, so a deferred MCP or browser tool can never
* be pulled into a planning run.
*/
export default function gatePlanModeTools({ tools }: { tools: HarnessTool[] }): HarnessTool[] {
return tools.map((tool) =>
allowed.has(tool.name)
? tool
: {
...tool,
run: async () => {
throw new Error(planModeRefusal({ name: tool.name }));
},
},
);
}
@@ -2,10 +2,12 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
let created = 0;
let next_id = 41;
let last_params: Record<string, unknown> = {};
mock.module("@/src/functions/backend/db/bot-questions/create-bot-question", () => ({
default: async () => {
default: async (params: Record<string, unknown>) => {
created++;
last_params = params;
return next_id++;
},
}));
@@ -39,6 +41,24 @@ describe("askUserTool", () => {
expect(tool.schema?.safeParse({ questions: Array.from({ length: 7 }, () => question) }).success).toBe(false);
});
test("records Plan mode on the card, so the answer stays in it", async () => {
last_params = {};
const planned = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, plan_mode: true, onAsk: () => {} });
await planned.run({ args: { questions: [question] }, signal: new AbortController().signal });
expect(last_params.plan_mode).toBe(true);
});
test("an ordinary card carries no Plan mode", async () => {
last_params = {};
const ordinary = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: () => {} });
await ordinary.run({ args: { questions: [question] }, signal: new AbortController().signal });
expect(last_params.plan_mode).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`
@@ -12,6 +12,12 @@ type Params = {
*/
session_id: number | string;
workspace_id?: number | string | null;
/**
* The run asked in Plan mode: its answer is run in Plan mode too, since
* answering a question is not a way out of the mode (only Tab or an
* approved plan is).
*/
plan_mode?: boolean;
/**
* Whether the run is a task, which stops and reports rather than waits.
*/
@@ -40,6 +46,7 @@ export default function askUserTool({
bot_id,
session_id,
workspace_id,
plan_mode,
in_task,
onAsk,
}: Params): HarnessTool<Args> {
@@ -75,6 +82,7 @@ export default function askUserTool({
bot_id,
session_id,
workspace_id,
plan_mode: Boolean(plan_mode),
title: args.title?.trim() || "",
questions: args.questions.map((item) => ({
question: item.question,
+2 -2
View File
@@ -78,8 +78,8 @@ export const SendBotMessageRequestSchema = z.object({
client_id: z.string().trim().max(64).optional(),
/**
* Plan mode: the reply plans and inspects, and changes nothing. For a
* user who clicked Plan in the composer or pressed Tab, the run is
* held to the read-only tools (`PlanModeToolNames`).
* user who clicked Plan in the composer or pressed Tab, the run's write
* tools are gated (`PlanModeToolNames`).
*/
plan_mode: z.boolean().optional(),
}).refine((body) => body.text || body.media_ids.length, "Write a message or attach a file first");
+7 -6
View File
@@ -7,10 +7,11 @@ export type PlanModeFileEscape = "missing_tool" | "save_it_yourself";
/**
* The claim that the app has no way to write a file, or the request that the
* user save it, in a reply sent with Plan mode on. The tool exists and Plan
* mode is the only thing that stops it, so the answer should have asked to
* save instead of handing over the document. 969 in session 133 said "Since
* I don't have a write_file tool available in this environment, here's the
* complete document for you to save" and pasted the whole roadmap.
* mode is the only thing that stops it, so the answer should have said the
* mode stops the save and offered to write it once they turn the mode off
* or approve a plan. 969 in session 133 said "Since I don't have a
* write_file tool available in this environment, here's the complete
* document for you to save" and pasted the whole roadmap.
*/
const MissingWriteTool =
/\b(?:don'?t|do not|doesn'?t|didn'?t)\s+(?:have|get|see)\b[^.!?\n]{0,40}\b(?:write_file|write tools?|file[- ]writing tools?)\b/i;
@@ -24,8 +25,8 @@ const SaveItYourself =
/**
* What in a Plan mode answer gives the write back to the user instead of
* asking to leave the mode: a made-up missing tool, or an instruction to
* save the document themselves. Null when the answer asks, or when it only
* says Plan mode stops it and offers to save.
* save the document themselves. Null when the answer offers to write it once
* the mode is off or a plan is approved, or only says Plan mode stops it.
*/
export default function planModeFileEscape({ text }: Params): PlanModeFileEscape | null {
if (MissingWriteTool.test(text) || WriteToolUnavailable.test(text)) return "missing_tool";
+39
View File
@@ -32,6 +32,45 @@ Which would you like?
expect(proseChoiceQuestion({ text: "The audit is done. Want me to send it?" })).toBeNull();
});
test("leaves a colon heading with no offer cue alone", () => {
const text = `Which files I read:
- src/server.ts
- src/hosted/messenger/paths.ts`;
expect(proseChoiceQuestion({ text })).toBeNull();
});
test("leaves an options heading alone when it asks nothing", () => {
const text = `The options are:
- Hosting for a year
- A domain name`;
expect(proseChoiceQuestion({ text })).toBeNull();
});
test("finds the offer from session 135, which ends in a colon", () => {
const text = `Tool **email_smtp_imap_manager** (custom tool #1) is created and enabled. No bots have it yet - I can grant access to specific bots or all bots when you say.
Want me to:
- Give it to one or more bots now?
- Run a quick test against one of your mailboxes (you'd provide the connection details via env vars first)?`;
expect(proseChoiceQuestion({ text })).toEqual({
question: "Want me to:",
options: 2,
});
});
test("finds an offer written with a colon and no question mark", () => {
const text = `The report is written.
Should I:
- Send it to the team
- Leave it for you to review first`;
expect(proseChoiceQuestion({ text })?.options).toBe(2);
});
test("leaves a section heading over facts alone", () => {
const text = `What's included?
- Hosting for a year
+24 -8
View File
@@ -20,10 +20,19 @@ type Params = {
};
/**
* A question that asks the user to choose, rather than one that heads a
* section ("What's included?" over a list of facts).
* A line that asks the user to choose, rather than one that heads a section
* ("What's included?" over a list of facts).
*/
const ChoiceCue = /\b(which|would you like|choose|pick|prefer|option)\b/i;
const ChoiceCue = /\b(which|would you like|want me to|should i|shall i|do you want(?: me)? to|choose|pick|prefer|option)\b/i;
/**
* The cues that make a line ending in ":" an offer rather than a heading.
* "Want me to:" heads the choices in a bot's answer and carries no question
* mark, so the question-mark test alone missed it (session 135's last
* message offered two next steps that way). A colon after "Options" or
* "Which files I read" is a heading over facts, so only an offer counts.
*/
const OfferCue = /\b(would you like|want me to|should i|shall i|do you want(?: me)? to)\b/i;
const ListItem = /^\s*(?:[-*+]|\d{1,2}[.)])\s+\S/;
const Fence = /^\s*(?:```|~~~)/;
@@ -34,11 +43,13 @@ const Fence = /^\s*(?:```|~~~)/;
* it. A reply that ends this way with no `ask_user` call makes the user
* retype an option instead of clicking one; session 133 shipped two of
* them ("What would you like to do?" with three numbered choices, and
* "Which would you like?" with Option A and B).
* "Which would you like?" with Option A and B), and session 135's "Want me
* to:" with two bullets.
*
* The list must follow the question in the same block, and the question
* must carry a choice cue, so "Want me to send it?" or a heading over a
* table of facts is left alone. Fenced code is never read as an ask.
* must carry a choice cue, so "Want me to send it?" with no list, or a
* heading over a table of facts, is left alone. Fenced code is never read
* as an ask.
*/
export default function proseChoiceQuestion({ text }: Params): ProseChoiceQuestion | null {
const lines = text.split("\n");
@@ -52,9 +63,14 @@ export default function proseChoiceQuestion({ text }: Params): ProseChoiceQuesti
continue;
}
if (in_fence || !line.includes("?") || !ChoiceCue.test(line)) continue;
if (in_fence) continue;
const question = line.replace(/\*\*|__/g, "").trim();
const plain = line.replace(/\*\*|__/g, "").trim();
const asks = plain.includes("?") || (plain.endsWith(":") && OfferCue.test(plain));
if (!asks || !ChoiceCue.test(plain)) continue;
const question = plain;
let options = 0;
for (let next = index + 1; next < lines.length && next <= index + 16; next += 1) {
+2 -1
View File
@@ -464,7 +464,8 @@ describe("replyClaimProblems: the app's own state", () => {
expect(problems.length).toBe(1);
expect(problems[0]).toContain("Plan mode");
expect(problems[0]).toContain("ask_user");
expect(problems[0]).toContain("turn Plan mode off (Tab)");
expect(problems[0]).not.toContain("their answer runs with the save allowed");
});
test("the same words outside Plan mode are not about the mode", () => {
+4 -4
View File
@@ -64,9 +64,9 @@ type Params = {
*/
status?: ReplyStatus;
/**
* The reply is running with Plan mode on: the tools that write are left
* out on purpose, so a file can't be saved until the user leaves the
* mode or answers an `ask_user` card (which runs with the save allowed).
* The reply is running with Plan mode on: every tool that writes is
* gated, so a file can't be saved until the user leaves the mode (Tab)
* or approves a plan. Answering an `ask_user` card does not leave it.
*/
plan_mode?: boolean;
};
@@ -211,7 +211,7 @@ export default function replyClaimProblems({
if (file_escape) {
problems.push(
`It is Plan mode, and the answer ${file_escape == "missing_tool" ? "says there is no write tool" : "asks the user to save the document themselves"}. write_file exists and Plan mode is the only thing stopping it. Don't paste the document and don't call the tool missing: say in one sentence that Plan mode stops the save, and call ask_user with "Save it and send the file" first; their answer runs with the save allowed, so write the file then. A short template the user asked to read can stay in the message.`,
`It is Plan mode, and the answer ${file_escape == "missing_tool" ? "says there is no write tool" : "asks the user to save the document themselves"}. write_file exists and Plan mode is the only thing stopping it. Don't paste the document and don't call the tool missing: say in one sentence that Plan mode stops the save, and either write it as a plan they can approve (its steps save it) or tell them to turn Plan mode off (Tab) and you will write it. Answering a question does not end Plan mode. A short template the user asked to read can stay in the message.`,
);
}