Compare commits

..
2 Commits
Author SHA1 Message Date
tben 4209fd9647 Bump version
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-17 04:54:41 +01:00
tben c21bafb737 Close the ways work went quiet, and ask before changing the crew
A review of the queue, the turn loop and the consent gates found 29 ways a
run could go silent, act on nobody's word, or lose what it produced. Each
one is fixed here.

Stuck and lost work:

- A task claim took three jobs for one computer, so every task slot sat
  waiting in `computer_lock` behind the one running, and replies stalled
  with them. A claim now takes one job per computer and skips a computer
  that already has one (`claim-bot-jobs`).
- A send stored the prompt and then enqueued in the same try: a throw left
  a message with no job behind it, so the thinking row stayed up for good.
  The insert, the enqueue (which deletes the message if it fails), the
  attachments and the push are now separate steps, and `client_id` makes a
  resend idempotent instead of posting the prompt twice.
- `open_jobs` in the catch-up read tells the thread whether a reply is
  still to come, so a job that ends without a message can't leave the row
  up (`grab-session-open-replies`, `useReplyCatchUp`).
- A completed job inserted its answer after marking itself done: a throw
  lost it, with no notice. The answer lands first (and is taken back if
  the completion fails), and nothing in the way of clearing up can lose it.
- A failed plan step left the plan active with nothing to advance it: it
  is paused now (`pause-failed-plan-step`).
- Deleting a bot left its open crew requests `working` forever, costing
  the asker its cap: they end with a reason and wake the asker
  (`end-asks-for-bot`).
- A deferral refunded the attempt even when the run had spent real tool
  work; cancelBotJob failed a possibly-running job without aborting it or
  fixing the face; a face stayed `working` while only pending jobs were
  left; a failed row with no bot was rescanned every poll. All four are
  fixed, and the face now has one place that decides it
  (`bot-face-after-job`, `answering-ask-face` keeps a crew request's
  answer on show).

Acting without consent:

- `set_workspace_computer` was the one workspace mutation with no role
  check.
- Any run could rewrite a bot's core instructions and core memory: those
  are the admin's now, and a refusal says what to use instead.
- Schedules and irreversible crew deletion are off for a hook call (whose
  payload is someone else's words) and for any run nobody is following.
- A hidden session no longer gets secret cards or questions nobody can
  answer; `can_ask` checks `isHiddenSession` too.
- Answering a secret card no longer closes it on a swallowed failure: the
  user gets a button that sends the bot the message it never got.
- Redaction skipped values under four characters, and `read_message_usage`
  answered for any job id, not the run's own session.

Silently lost or wasted work in the loop:

- A reply is cleaned before review (unresolved `[setting:]` refs, app
  record lines, work claims), and a refused closing tool or a card with no
  text no longer ends the run on a sentence that promises something that
  isn't there.
- The wrap up no longer marks a message answered, a session carry-over
  takes queued replies with it, and a trimmed remembered result is read
  again instead of answered with "its output is above".
- An oversized newest result is cut last instead of sent whole, an empty
  answer fails with a reason rather than an empty bubble, orphan question
  cards are deleted, a reply that ran out of steps marks its task
  exhausted, and a throwing review is logged instead of swallowed.

AGENTS.md's two drifted lines are corrected (the crew request's face and
the task run's `can_ask`).

Verification: bun run typecheck clean; bun run test 2117 pass, 0 fail.
2026-11-17 04:54:27 +01:00
56 changed files with 1496 additions and 161 deletions
+2 -2
View File
@@ -99,7 +99,7 @@ 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`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
@@ -136,7 +136,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
### Crew requests (`bot_asks`)
A worker reaches another bot **only through the coordinator's gate**: `ask_bot` (every worker run with a session except hook calls; never the coordinator) queues a request (`createAsk`) for the run's user and place. Who can be asked is the app's call (`askableBots`): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (`AskGateNote`); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (`runAskReview`, queued by `enqueueAskReview`, dispatched from `run-bot-job` on `params.stage == "review"`) answering bounded JSON (`AskDecisionSchema`: `approve`, `redirect` or `refuse`, the bot, and a one-sentence reason) which `applyAskDecision` carries out. A refusal ends the request (`refused`) with its reason; an approval or a redirect sends the brief to the target (`enqueueAskAnswer`) as one reply job in **a new session of the target's conversation with that user for the request's workspace** (`startBotSession` with `workspace_id`, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (`from_ask_id`, `askRequestMessage`, pushed live) and the answer as the bot's reply; the target's own chat (and any other place it is read from) shows the request's row, whose `Open` link appears only outside the request's own thread (`answer_ask.session_id != session_id`), while the session carries `AskSessionBar`, built from `previous_session_id` (recorded when the request took its session, null when the bot had no conversation there before it, an empty active session counted as the request's own, `askPreviousSessionId`: with nothing to go back to, the bar is not shown at all), back to the conversation the user was in; an outcome message carries the `[ask:ID]` pill (`askRef`, `AskRefChip`, `api/admin/bots/ask`) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (`ensureAskSession`, status `ask`, deleted when empty). Stopping the target's run ends the request too (`stopBotJobs` reads `params.ask_id`, then `stopAsk`), and the bot that asked is told why and woken for it (`stopAsk`'s `reason` into `askOutcomeMessage`); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (`finishAsk`), except when the user stopped it. **Every session query that lists or picks a conversation must exclude hook sessions** (`visibleSessionSql`); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as `failed` (`onAskJobEnded`, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (`crew/ask-<id>/`) and the refs repointed (`shareAskFiles`). Caps: `AppData.AskMaxDepth` (nested requests, `parent_ask_id`; a bot waiting up the chain can't be asked), `AskMaxOpenPerBot`, `AskBriefMaxChars`. A request's run shows on the target bot's face and in its thread (the thinking row says `SEO Expert is answering Software Engineer's request in Moduletrace LTD…` with Stop, from `grabConversationAsk`; `answer_ask` in the page props, `answering_ask` in `botBusyState`) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (`grabRunningBotJobFace` excludes hook runs only); a hook call can't ask. A bot reads its own requests with `list_asks` (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run (which sees only its brief) gets its bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (`stopAsk`, `stopAsks`). **Retention:** ended requests go after the app setting `ask_keep_days` (daily `prune-asks`) and past `ask_max_per_place` per place, oldest first (`pruneAsksSql`; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through `deleteAskRows` -> `deleteSessionRows`, which clears each session's job steps, traces, jobs, billed `token_usages` and messages first, so no child row is left behind for the next `db:schema`). Sessions from before this feature (`bot_sessions.status = 'chatroom'`) are deleted at boot by `migrateChatroomsToAsks`.
A worker reaches another bot **only through the coordinator's gate**: `ask_bot` (every worker run with a session except hook calls; never the coordinator) queues a request (`createAsk`) for the run's user and place. Who can be asked is the app's call (`askableBots`): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (`AskGateNote`); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (`runAskReview`, queued by `enqueueAskReview`, dispatched from `run-bot-job` on `params.stage == "review"`) answering bounded JSON (`AskDecisionSchema`: `approve`, `redirect` or `refuse`, the bot, and a one-sentence reason) which `applyAskDecision` carries out. A refusal ends the request (`refused`) with its reason; an approval or a redirect sends the brief to the target (`enqueueAskAnswer`) as one reply job in **a new session of the target's conversation with that user for the request's workspace** (`startBotSession` with `workspace_id`, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (`from_ask_id`, `askRequestMessage`, pushed live) and the answer as the bot's reply; the target's own chat (and any other place it is read from) shows the request's row, whose `Open` link appears only outside the request's own thread (`answer_ask.session_id != session_id`), while the session carries `AskSessionBar`, built from `previous_session_id` (recorded when the request took its session, null when the bot had no conversation there before it, an empty active session counted as the request's own, `askPreviousSessionId`: with nothing to go back to, the bar is not shown at all), back to the conversation the user was in; an outcome message carries the `[ask:ID]` pill (`askRef`, `AskRefChip`, `api/admin/bots/ask`) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (`ensureAskSession`, status `ask`, deleted when empty). Stopping the target's run ends the request too (`stopBotJobs` reads `params.ask_id`, then `stopAsk`), and the bot that asked is told why and woken for it (`stopAsk`'s `reason` into `askOutcomeMessage`); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (`finishAsk`), except when the user stopped it. **Every session query that lists or picks a conversation must exclude hook sessions** (`visibleSessionSql`); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as `failed` (`onAskJobEnded`, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (`crew/ask-<id>/`) and the refs repointed (`shareAskFiles`). Caps: `AppData.AskMaxDepth` (nested requests, `parent_ask_id`; a bot waiting up the chain can't be asked), `AskMaxOpenPerBot`, `AskBriefMaxChars`. A request's run shows on the target bot's face and in its thread (the thinking row says `SEO Expert is answering Software Engineer's request in Moduletrace LTD…` with Stop, from `grabConversationAsk`; `answer_ask` in the page props, `answering_ask` in `botBusyState`) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (`grabRunningBotJobFace` excludes hook runs and crew-request runs both; `answeringAskFace` keeps an answer run's face while it works, since a sibling job's completion would otherwise put the bot to sleep mid-answer); a hook call can't ask. A bot reads its own requests with `list_asks` (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run (which sees only its brief) gets its bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (`stopAsk`, `stopAsks`). **Retention:** ended requests go after the app setting `ask_keep_days` (daily `prune-asks`) and past `ask_max_per_place` per place, oldest first (`pruneAsksSql`; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through `deleteAskRows` -> `deleteSessionRows`, which clears each session's job steps, traces, jobs, billed `token_usages` and messages first, so no child row is left behind for the next `db:schema`). Sessions from before this feature (`bot_sessions.status = 'chatroom'`) are deleted at boot by `migrateChatroomsToAsks`.
### Workspaces
+9
View File
@@ -616,12 +616,21 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Set on the message that opens a session the bot moved the conversation into (\`continue_in_new_session\`): the session it carries on from, whose summary is the message's text. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "client_id",
fieldDescription: `The composer's own id for a message it sent, so a send whose answer never arrived is recognised as the one already stored rather than posted twice`,
dataType: "TEXT",
},
],
indexes: [
{
indexName: "idx_bot_messages_bot_id_created_at",
indexTableFields: ["bot_id", "created_at"],
},
{
indexName: "idx_bot_messages_client_id",
indexTableFields: ["client_id"],
},
{
indexName: "idx_bot_messages_session_id_created_at",
indexTableFields: ["session_id", "created_at"],
+4
View File
@@ -436,6 +436,10 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
* Set on the message that opens a session the bot moved the conversation into (`continue_in_new_session`): the session it carries on from, whose summary is the message's text. Not a foreign key
*/
carried_from_session_id?: number | "";
/**
* The composer's own id for a message it sent, so a send whose answer never arrived is recognised as the one already stored rather than posted twice
*/
client_id?: string;
}
export type BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS = {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.22.0",
"version": "0.23.0",
"module": "index.ts",
"type": "module",
"private": true,
+28 -6
View File
@@ -87,6 +87,14 @@ export default async function processBotJob({
const schedule_id = Number(params.schedule_id) || null;
const hook_id = Number(params.hook_id) || null;
const controller = new AbortController();
/**
* Registered before the first read below: those queries can wait on a
* busy database, and a Stop that arrived while they ran found nothing
* to abort, so a stopped job went on running until its own next write.
*/
registerJobAbort({ job_id, abort: () => controller.abort() });
/**
* Its face changes only for the user it works for.
*/
@@ -102,7 +110,10 @@ export default async function processBotJob({
);
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }).catch(() => null));
const controller = new AbortController();
if (controller.signal.aborted) {
unregisterJobAbort({ job_id });
return;
}
/**
* The deadline is the one abort that is a failure, not a cancellation:
* the job's error is then the timeout's, not the "Cancelled." an
@@ -110,6 +121,10 @@ export default async function processBotJob({
*/
const timeout_message = `"${job.title || "The job"}" took too long and was stopped.`;
let timed_out = false;
/**
* Set once the run reports a step (a tool call): its attempt is spent.
*/
let worked = false;
/**
* A stopped job never touches the face again: `stopBotJobs` already set
@@ -128,8 +143,6 @@ export default async function processBotJob({
* is already failed in the queue, so an abort is a cancellation and its
* result is dropped (`controller.signal.aborted` below).
*/
registerJobAbort({ job_id, abort: () => controller.abort() });
const update: BotJobContext["update"] = async (params) => {
if (controller.signal.aborted) return false;
@@ -148,6 +161,14 @@ export default async function processBotJob({
try {
if (!(await update({ progress: described.text }))) return;
/**
* The run has done real work: a later wait for the models to
* come back must not give its attempt back, or a run that
* wrote files and then met a resting model replays from turn 1
* as many times as the outage lasts.
*/
worked = true;
const row = await insertBotJobUpdate({ job_id, bot_id, ...described });
await pushToSessionUser({
@@ -363,14 +384,15 @@ export default async function processBotJob({
* wait for the first to come back without using an attempt.
*/
if (error instanceof HarnessError && error.resting) {
await deferBotJob({
const deferred = await deferBotJob({
job_id,
worker,
until: error.retry_at || Date.now() + AppData.HarnessCooldownMs,
refund: true,
refund: !worked,
});
await setFace({ face: "asleep", status_line: BotWaitingStatusLine });
if (deferred) await setFace({ face: "asleep", status_line: BotWaitingStatusLine });
return;
}
+14 -1
View File
@@ -1,3 +1,4 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import grabUnreportedFailedBotJobs from "@/src/functions/backend/db/bots-queue/grab-unreported-failed-bot-jobs";
import notifyBotJobFailed from "@/src/functions/backend/db/bots-queue/notify-bot-job-failed";
import { logError } from "@/src/functions/backend/logger";
@@ -11,7 +12,19 @@ export default async function reportLostBotJobs() {
const jobs = await grabUnreportedFailedBotJobs();
for (const job of jobs) {
if (!job.bot_id) continue;
if (!job.bot_id) {
/**
* A job whose bot was deleted has nobody to tell, but it is
* stamped all the same: left unstamped, the same rows are read
* on every poll and never pruned.
*/
await BunSQLite.sql({
sql: `UPDATE bots_queue SET finished_at = ? WHERE id = ? AND finished_at IS NULL`,
values: [Date.now(), Number(job.id)],
}).catch(() => {});
continue;
}
const notice = await notifyBotJobFailed({
job,
+63 -6
View File
@@ -32,6 +32,7 @@ import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-
import workspaceAdminsNote from "./workspace-admins-note";
import type { WorkspaceAdminTools } from "@/src/harness/tools/bot/grab-workspace-admin-tools";
import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
import { isUnlimitedLimit } from "@/src/utils/run-limit";
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
@@ -45,6 +46,7 @@ import openBotBrowsers from "@/src/harness/tools/browsers/open-bot-browsers";
import openBotExtensions from "@/src/harness/tools/extensions/open-bot-extensions";
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
import parseJobJson from "./parse-job-json";
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
@@ -171,7 +173,7 @@ export default async function runBotReply({
/**
* What the user wrote since the run last looked.
*/
const incoming = async (): Promise<HarnessMessage[]> => {
const incoming = async ({ counted = true }: { counted?: boolean } = {}): Promise<HarnessMessage[]> => {
const fresh = await grabBotMessages({
session_id,
after_id: seen_id,
@@ -182,7 +184,13 @@ export default async function runBotReply({
if (!fresh.length) return [];
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
/**
* A message read by the wrap up is not what the answer answers: the
* answer was written for what came before it, and its own queued
* reply is the one that reads this. Marking it answered here made
* that reply finish silently, with nothing sent for it.
*/
if (counted) answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
return await messagesToTurns({ messages: fresh, user_id });
};
@@ -409,6 +417,12 @@ export default async function runBotReply({
*/
const open_runs = attended ? await grabOpenSessionRuns({ bot_id: bot.id, session_id }) : [];
/**
* What the run may spend: a reply handed a tracker task says when it
* used them all (`exhausted`).
*/
const reply_max_steps = await grabReplyMaxToolSteps();
try {
const result = await runTextLoop({
system: [
@@ -480,7 +494,13 @@ export default async function runBotReply({
session_id,
workspace_id,
computer_id: computers[0]?.id || null,
onRequest: ({ ref }) => proposals.push(ref),
/**
* A card is answered in a conversation the user follows:
* in a hidden session (a crew request, a hook call, a
* room) nobody sees it, so the bot is told to ask in the
* chat instead of leaving a request hanging.
*/
onRequest: attended ? ({ ref }) => proposals.push(ref) : undefined,
onShow: ({ ref }) => shown.push(ref),
}),
/**
@@ -539,7 +559,7 @@ export default async function runBotReply({
...skills.tools,
...knowledge.tools,
],
max_steps: await grabReplyMaxToolSteps(),
max_steps: reply_max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
bot_id: bot.id,
@@ -561,8 +581,24 @@ export default async function runBotReply({
* with why instead (`review_note`), and the job fails saying so. The
* user gets an honest failure, not a claim the app knows is false.
*/
if (result.review_note)
if (result.review_note) {
await dropUnsentQuestions({ refs: proposals });
throw new BotJobFatalError(`The answer didn't hold up against the app's record, so it wasn't sent.`);
}
const answer = stripAppRecords({ text: result.text }).trim();
/**
* Nothing said is nothing to send: an empty message lands in the
* thread as a bubble with no text, and the user has no idea what
* happened. The job fails with why instead, which they do see.
*/
if (!answer && !shown.length && !attachments.length) {
await dropUnsentQuestions({ refs: proposals });
throw new BotJobFatalError(`The run ended without an answer to send.`);
}
if (job.id && answering_id) {
await markReplyAnswered({ job_id: job.id, message_id: answering_id });
@@ -570,7 +606,7 @@ export default async function runBotReply({
return {
...withTakeOverRefs({
text: stripAppRecords({ text: result.text }),
text: answer,
refs: [...take_overs, ...proposals, ...plan_refs],
shown,
}),
@@ -578,6 +614,12 @@ export default async function runBotReply({
tool_log: result.tool_uses,
task_ids,
plan_id: on_plan_step ? plan?.id : undefined,
/**
* A reply handed a tracker task (`params.tracker_task_id`) that
* used every step it had stopped short of finishing it: left
* alone, the task looked like work still in hand.
*/
exhausted: !isUnlimitedLimit(reply_max_steps) && result.steps > reply_max_steps,
};
} finally {
await extensions.close();
@@ -585,6 +627,21 @@ export default async function runBotReply({
}
}
/**
* Cards whose message never went out are deleted: their answer only comes
* from the card, so a pending row left behind waits forever and counts as a
* question still asked.
*/
async function dropUnsentQuestions({ refs }: { refs: string[] }) {
for (const ref of refs) {
const question_id = Number(/\[question:(\d+)\]/.exec(ref)?.[1] || 0);
if (!question_id) continue;
await deleteBotQuestion({ question_id }).catch(() => null);
}
}
function newestUserMessageId({ messages }: { messages: Pick<BotMessageWithAttachments, "id" | "author">[] }) {
return Math.max(
0,
+8 -2
View File
@@ -46,6 +46,7 @@ import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/e
import openBotSkills, { type OpenBotSkills } from "@/src/harness/tools/skills/open-bot-skills";
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
@@ -186,9 +187,14 @@ export default async function runBotTask({
const hooked = Boolean(params.hook_id);
/**
* Only a task the user follows in their conversation asks them
* questions: routines and hook calls act on their own.
* questions: routines and hook calls act on their own, and a crew
* request's run works in a session nobody reads from this bot's chat.
*/
const can_ask = Boolean(session_id) && !scheduled && !hooked;
const can_ask =
Boolean(session_id) &&
!scheduled &&
!hooked &&
!(await isHiddenSession({ session_id: Number(session_id) }));
/**
* The coordinator weighing a worker's install request
* (`request_install`): it answers it with answer_install_request.
+22
View File
@@ -445,6 +445,28 @@ Nothing has run since that could change that answer, so calling it once more onl
export const answerNotSentNote = `The message you wrote before these tool results was never sent: a run sends only its final message, and you went on to call a tool after writing that one. If the user still needs any of it, write it again in your last message. Don't send work in progress as an answer and then carry on.`;
export const repeatedAnswerNote = `This is the message the app just sent back, word for word: nothing has changed since, so it will not go out either. Write it again from what the app's record shows. Take out what that record cannot support, and if the work still needs doing, call the tool that does it now rather than saying it is under way.`;
/**
* Told when a turn tried to end on a card and the card's tool refused it
* (wrong arguments, an answered card): nothing went up, so the answer must
* not read as if it had. The run carries on, which is what gives the model
* the turn it needs to fix the call.
*/
export const closingFailedNote = `The card that call was meant to put up was not created: the tool refused it, and its error is above. Your message was written as if it had gone up, and it has not. Fix the call and make it again, or answer without it, and write your message for what actually exists.`;
/**
* Told once when a closing call worked but the turn said nothing beside it:
* a card alone leaves the user with buttons and no answer, and a run that
* carries on from there works on the thing it just asked about.
*/
export const closingNoTextNote = `The card you just put up has no message beside it, and a card on its own leaves the user nothing to read. Write the sentence that goes with it now, and stop there: what comes next waits on their answer.`;
/**
* Put under an answer the review kept faulting once its unsupported parts
* were taken out (`repairAnswerText`): the user is told part of it is gone
* rather than losing the whole answer, and knows what to ask again.
*/
export const repairedAnswerNote = `_Part of this answer was left out: it described work no tool of this run did._`;
/**
* Told once, when the prompt no longer fits the working context even after
* everything trimmable was trimmed: what is left is what the user wrote,
@@ -0,0 +1,53 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import cancelAskJobs from "./cancel-ask-jobs";
import finishAsk from "./finish-ask";
type Params = {
bot_id: number | string;
};
/**
* Ends every request a bot is part of, before the bot row goes: the ones it
* asked and the ones it was asked. Left open, an ask stays `working` for
* good (nothing would ever end it), it is never pruned, and it spends the
* asking bot's open-request allowance (`AppData.AskMaxOpenPerBot`) so that
* bot can never ask anyone again. A request whose asked bot is gone ends
* with a failure the asking bot is woken with; one whose asking bot is gone
* is only closed, since there is nobody to tell.
*/
export default async function endAsksForBot({ bot_id }: Params) {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `SELECT * FROM bot_asks
WHERE status IN ('pending', 'working')
AND (requester_bot_id = ? OR target_bot_id = ?)`,
values: [Number(bot_id), Number(bot_id)],
});
const ended: BUN_SQLITE_COBBLE_BOT_ASKS[] = [];
for (const ask of res.payload || []) {
const asked = Number(ask.target_bot_id) == Number(bot_id);
const finished = await finishAsk({
ask,
status: "failed",
outcome: asked
? "The bot it was passed to was deleted, so it never answered."
: "The bot that asked was deleted.",
wake: asked && Number(ask.requester_bot_id) != Number(bot_id),
});
if (!finished) continue;
ended.push(finished);
/**
* Whatever was still running for it goes too, and its task closes
* with it (`cancelAskJobs`).
*/
await cancelAskJobs({ ask_id: Number(ask.id), reason: "The bot was deleted." });
}
return ended;
}
@@ -0,0 +1,42 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import grabBotPlan from "./grab-bot-plan";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
};
/**
* Pauses the plan a failed run was working a step of: nothing would ever
* advance it, so it would show that step in progress forever and every later
* reply in that conversation would be told the plan is under way and may not
* move it. Paused, the card offers the step again (Resume queues it as it
* stands). The step itself is left for that retry. A plan the user paused or
* ended meanwhile, or one of another conversation, is left alone.
*/
export default async function pauseFailedPlanStep({ job }: Params) {
const plan_id = Number(parseJobJson({ text: job.params })?.plan_id) || 0;
if (!plan_id || !job.session_id) return null;
const row = await grabBotPlan({ plan_id }).catch(() => null);
if (!row?.id || row.status != "active") return null;
if (Number(row.session_id) != Number(job.session_id)) return null;
const res = await BunSQLite.sql<{ id: number }>({
sql: `UPDATE bot_plans SET status = 'paused', updated_at = ?
WHERE id = ? AND status = 'active' RETURNING id`,
values: [Date.now(), Number(row.id)],
});
if (!res.payload?.length) return null;
return {
plan_id: Number(row.id),
session_id: Number(row.session_id),
bot_id: Number(row.bot_id),
};
}
@@ -0,0 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
question_id: number | string;
};
/**
* Deletes questions a bot asked whose message never went out. The card is
* the only way to answer them, so a row left behind waits for an answer
* nobody can give, and counts as still asked.
*/
export default async function deleteBotQuestion({ question_id }: Params) {
const res = await BunSQLite.sql({
sql: "DELETE FROM bot_questions WHERE id = ? AND status = 'pending'",
values: [question_id],
});
if (res.error) throw new Error(`Couldn't delete the question: ${res.msg || res.error}`);
return true;
}
@@ -119,5 +119,16 @@ export default async function carryOverBotSession({
});
}
/**
* Everything else still to come for the closed session moves with it.
* A queued job left behind answers into a session the conversation has
* left (`SessionMovedBar` where its reply should be), sets unread on a
* thread nobody opens again, and pushes nothing the user is looking at.
*/
await BunSQLite.sql({
sql: `UPDATE bots_queue SET session_id = ? WHERE session_id = ? AND status IN ('pending', 'processing')`,
values: [next.id!, active.id],
});
return message;
}
@@ -0,0 +1,32 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotFace } from "@/src/dict/bot-dict";
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
type Params = {
bot_id: number | string;
user_id: number | string;
};
/**
* The face a bot shows one user while it answers another bot's crew request
* for them. That run works in a hidden session, which
* `grabRunningBotJobFace` leaves out on purpose, so without this a job that
* finished beside it would put the bot to sleep while the request was still
* being answered. Null when no request is running.
*/
export default async function answeringAskFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
const running = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT q.id FROM bots_queue q
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ask_id IS NOT NULL)
LIMIT 1`,
values: [bot_id, user_id],
})
).payload?.[0];
return running ? { face: "working", status_line: BotReplyJobTitle } : null;
}
@@ -0,0 +1,55 @@
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import { BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
import setBotFace from "../bots/set-bot-face";
import answeringAskFace from "./answering-ask-face";
import countOpenBotJobs from "./count-open-bot-jobs";
import grabRunningBotJobFace from "./grab-running-bot-job-face";
type Params = {
bot_id: number | string;
user_id: number | string;
/**
* Of the job that just ended, so a bot with nothing left shows done
* after a task and idle after a reply.
*/
kind?: BUN_SQLITE_COBBLE_BOTS_QUEUE["kind"];
};
/**
* What a bot shows a user now that one of its jobs ended without asking
* for them: its resting face when nothing else is open, else the work still
* running, or waiting when what is left is only queued. Counted for the
* user alone: another user's job is never on this face.
*/
export default async function botFaceAfterJob({ bot_id, user_id, kind }: Params) {
/**
* A crew request's run shows its work too, so the face left to show is
* the one still processing. Asked first: its session is hidden, so the
* job counts of one that's still being answered read as nothing open.
*/
const running = await grabRunningBotJobFace({ bot_id, user_id });
if (running) return await setBotFace({ bot_id, user_id, ...running });
const answering = await answeringAskFace({ bot_id, user_id });
if (answering) return await setBotFace({ bot_id, user_id, ...answering });
const open = await countOpenBotJobs({ bot_id, user_id, conversations_only: true });
if (!open) {
return await setBotFace({ bot_id, user_id, face: kind == "task" ? "done" : "idle" });
}
/**
* Jobs are open for this user but none is running (`deferBotJob` put
* them back while every model rests, or they wait in the queue): the
* bot waits, rather than showing work that isn't happening.
*/
return await setBotFace({
bot_id,
user_id,
face: "asleep",
status_line: BotWaitingStatusLine,
});
}
@@ -2,8 +2,10 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import { BotJobCancelledError } from "@/src/dict/bot-queue-dict";
import AppError from "@/src/utils/app-error";
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
import settleInstallRequest from "../install-requests/settle-install-request";
import botFaceAfterJob from "./bot-face-after-job";
type Params = {
user_id: number | string;
@@ -12,8 +14,11 @@ type Params = {
/**
* Cancels a pending or running job in one of the user's conversations. It's marked failed
* with `BotJobCancelledError`; a running handler finds out on its next
* `updateBotJob` (which returns false) and stops. Its task is closed.
* with `BotJobCancelledError`; a running handler is aborted here and now when
* this process is the one running it (anywhere else it finds out on its
* next `updateBotJob`, which returns false) and stops. Its task is closed,
* and the bot's face for that user is worked out again, so a cancelled run
* never leaves it showing work that ended.
*/
export default async function cancelBotJob({ user_id, job_id }: Params) {
const now = Date.now();
@@ -39,6 +44,17 @@ export default async function cancelBotJob({ user_id, job_id }: Params) {
});
}
/**
* What it is waiting on is aborted now, so the run stops writing before
* the caller goes on: a cancelled run that kept its model call going
* still wrote its files and its steps.
*/
abortRunningJob({ job_id: Number(job.id) });
if (job.bot_id) {
await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
}
await recordHookCallResponse({ job, status: "failed", response: BotJobCancelledError, now });
await settleInstallRequest({ job, text: BotJobCancelledError, failed: true });
@@ -25,6 +25,12 @@ type Params = {
*
* bun-sqlite's `queue.claim` takes no filter, so the claim is its same
* single statement (atomic: two workers never claim one job) plus `kind`.
*
* One job per computer: only one task can work on a computer at a time, so
* claiming several of its tasks filled every task slot with jobs waiting on
* that computer's lock, and a second computer sat idle while its pending
* tasks were already claimed. A computer with a task in flight is skipped
* here instead, so the slots go to work that can run now.
*/
export default async function claimBotJobs({ worker, limit = 1, kind }: Params) {
const released = await BunSQLite.queue.release_stale<
@@ -44,9 +50,17 @@ export default async function claimBotJobs({ worker, limit = 1, kind }: Params)
sql: `UPDATE bots_queue SET status = 'processing', attempts = attempts + 1,
locked_at = ?, locked_by = ?, updated_at = ?
WHERE id IN (
SELECT id FROM bots_queue
SELECT MIN(id) FROM bots_queue
WHERE status = 'pending' AND available_at <= ? AND kind = ?
ORDER BY id LIMIT ?
AND (
computer_id IS NULL
OR computer_id NOT IN (
SELECT computer_id FROM bots_queue
WHERE status = 'processing' AND kind = 'task' AND computer_id IS NOT NULL
)
)
GROUP BY COALESCE(computer_id, -id)
ORDER BY MIN(id) LIMIT ?
) RETURNING *`,
values: [now, worker, now, now, kind, Math.floor(limit)],
});
@@ -2,18 +2,19 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import { BotNeedsYouStatusLine } from "@/src/dict/bot-queue-dict";
import insertBotMessage from "../bots/insert-bot-message";
import deleteBotMessage from "../bots/delete-bot-message";
import setBotFace from "../bots/set-bot-face";
import countOpenBotJobs from "./count-open-bot-jobs";
import botFaceAfterJob from "./bot-face-after-job";
import grabLockedBotJob from "./grab-locked-bot-job";
import relayJobToRequester from "./relay-job-to-requester";
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
import noteTrackerTask from "./note-tracker-task";
import jobSessionId from "./job-session-id";
import grabJobUserId from "./grab-job-user-id";
import grabRunningBotJobFace from "./grab-running-bot-job-face";
import withMessageUsage from "../usage/with-message-usage";
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
import attachJobTracesToMessage from "./attach-job-traces-to-message";
import { logError } from "@/src/functions/backend/logger";
import type { HarnessToolUse } from "@/src/harness/types";
import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
import onAskJobEnded from "../asks/on-ask-job-ended";
@@ -62,8 +63,8 @@ type Params = {
* to the user in the bot's conversation. Unless it has other jobs open
* for that user, the bot shows that user needs-you if asked, else done
* after a task and idle after a reply; with others open, it shows the one
* still running (a reply in another session mustn't hide a task's row).
* Nobody else's face changes. A handed-over job's result also goes to the bot that handed
* still running (a reply in another session mustn't hide a task's row) or
* waits for one held back by the queue. Nobody else's face changes. A handed-over job's result also goes to the bot that handed
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
* its whole step budget without finishing (`noteTrackerTask`). A hook
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job working a crew
@@ -86,34 +87,19 @@ export default async function completeBotJob({
throw new AppError(`This job is no longer held by ${worker}.`);
}
const res = await BunSQLite.queue.complete({
table: "bots_queue",
id: job.id,
});
if (!res.success) {
throw new Error(`Couldn't complete the job: ${res.msg || res.error}`);
}
const now = Date.now();
await BunSQLite.sql({
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
values: [result, now, job.id],
});
/**
* A handed-over task's run is about that task, whatever its tools did.
*/
const message_task_ids = [jobTrackerTaskId({ job }), ...task_ids];
if (job.task_id) {
await BunSQLite.sql({
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
values: [now, job.task_id],
});
}
/**
* The answer is written while this handler still holds the job: with
* the job marked done first, a throw here reached `failBotJob`, which
* found the job gone and swallowed it, so the answer was lost with no
* notice and the bot stayed at working.
*/
const inserted = silent
? null
: await insertBotMessage({
@@ -145,6 +131,34 @@ export default async function completeBotJob({
}).catch(() => {});
}
const res = await BunSQLite.queue.complete({
table: "bots_queue",
id: job.id,
});
if (!res.success) {
/**
* The job never ended, so its answer would sit under a run with no
* end: it's taken back out (its files stay) and the caller fails
* the job, which tells the user instead.
*/
if (inserted?.id) await deleteBotMessage({ message_id: inserted.id }).catch(() => {});
throw new Error(`Couldn't complete the job: ${res.msg || res.error}`);
}
await BunSQLite.sql({
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
values: [result, now, job.id],
});
if (job.task_id) {
await BunSQLite.sql({
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
values: [now, job.task_id],
});
}
/**
* Pushed live as it is returned, so it carries its usage now: the
* thread shows the tokens without a reload.
@@ -161,41 +175,49 @@ export default async function completeBotJob({
*/
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }));
const bot = !user_id || in_hook
? null
: needs_you
? await setBotFace({
bot_id: job.bot_id,
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: (await countOpenBotJobs({ bot_id: job.bot_id, user_id, conversations_only: true }))
? await restoreRunningFace({ bot_id: job.bot_id, user_id })
: await setBotFace({
bot_id: job.bot_id,
user_id,
face: job.kind == "reply" ? "idle" : "done",
});
/**
* The job is done and its answer saved, so what is left is clearing up:
* a throw in here is logged rather than failing a job that already
* ended and holding the answer back from the live push.
*/
let bot: Awaited<ReturnType<typeof setBotFace>> | null = null;
let relay: Awaited<ReturnType<typeof relayJobToRequester>> | null = null;
await noteTrackerTask({ job, exhausted });
try {
bot =
!user_id || in_hook
? null
: needs_you
? await setBotFace({
bot_id: job.bot_id,
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
await noteTrackerTask({ job, exhausted });
const relay = silent ? null : await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await recordHookCallResponse({
job,
status: "done",
response: result,
message_id: inserted?.id,
});
await onAskJobEnded({ job, text: silent ? "" : result });
relay = silent
? null
: await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await settleInstallRequest({ job, text: result });
await onAskJobEnded({ job, text: silent ? "" : result });
await settleInstallRequest({ job, text: result });
} catch (error) {
await logError({
title: `Bot job #${job.id} completed, its clearing up didn't`,
error,
}).catch(() => {});
}
return { message, bot, relay };
}
/**
* Puts back the face of a job still running for the user, if any.
*/
async function restoreRunningFace({ bot_id, user_id }: { bot_id: number; user_id: number }) {
const running = await grabRunningBotJobFace({ bot_id, user_id });
return running ? await setBotFace({ bot_id, user_id, ...running }) : null;
}
@@ -0,0 +1,23 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
session_id: number | string;
};
/**
* How many replies are still to come in a session: its queued ones and the
* one being written. Zero means nothing will answer there any more, which
* is how a thread tells a reply that ended without a word (a run that found
* every message already answered) from one still on its way.
*/
export default async function grabSessionOpenReplies({ session_id }: Params): Promise<number> {
const row = (
await BunSQLite.sql<{ count: number }>({
sql: `SELECT COUNT(*) AS count FROM bots_queue
WHERE session_id = ? AND kind = 'reply' AND status IN ('pending', 'processing')`,
values: [Number(session_id)],
})
).payload?.[0];
return Number(row?.count) || 0;
}
@@ -13,6 +13,8 @@ import onAskJobEnded from "../asks/on-ask-job-ended";
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
import settleInstallRequest from "../install-requests/settle-install-request";
import jobTrackerTaskId from "./job-tracker-task-id";
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
import attachJobTracesToMessage from "./attach-job-traces-to-message";
@@ -77,6 +79,16 @@ export default async function notifyBotJobFailed({
const user_id = await grabJobUserId({ job });
/**
* A plan whose step this run was working is paused with it: nothing
* would ever advance it, so its card would show that step in progress
* forever and every later reply would be told the plan is running and
* may not move it.
*/
const paused_plan = await pauseFailedPlanStep({ job }).catch(() => null);
if (paused_plan) await pushBotPlan(paused_plan);
/**
* A hook's run is followed by nobody, so it never shows on the bot's
* face. A crew request's does: the bot answering it is working.
@@ -0,0 +1,39 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
message_id: number | string;
};
/**
* Deletes one message of a conversation, and the links it had to files:
* the files themselves stay (they are the bot's or the user's, not the
* message's), so this is safe for a message that shouldn't have been
* written in the first place. Foreign keys are off outside the server, so
* the child rows go explicitly.
*/
export default async function deleteBotMessage({ message_id }: Params) {
await BunSQLite.sql({
sql: `DELETE FROM bot_message_media WHERE message_id = ?`,
values: [message_id],
});
/**
* A graphic the message showed is nobody's any more: it stays readable
* from its own page rather than pointing at a message that is gone.
*/
await BunSQLite.sql({
sql: `UPDATE bot_graphics SET message_id = NULL WHERE message_id = ?`,
values: [message_id],
}).catch(() => {});
const res = await BunSQLite.sql({
sql: `DELETE FROM bot_messages WHERE id = ?`,
values: [message_id],
});
if (!res.success) {
throw new Error(`Couldn't delete the message: ${res.msg || res.error}`);
}
return true;
}
@@ -4,6 +4,8 @@ import purgeStorage, { grabStorageMediaIds } from "@/src/functions/backend/db/bo
import { grabTaskMediaIds } from "@/src/functions/backend/db/tasks/purge-task-media";
import passOnBotTasks from "@/src/functions/backend/db/tasks/pass-on-bot-tasks";
import AppError from "@/src/utils/app-error";
import { logError } from "@/src/functions/backend/logger";
import endAsksForBot from "../asks/end-asks-for-bot";
import { clearEnvCache } from "../envs/grab-all-envs";
import grabUserBot from "./grab-user-bot";
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
@@ -69,6 +71,17 @@ export default async function deleteBot({ user_id, bot_id }: Params) {
clearEnvCache();
/**
* After the row is gone, so a request it asked isn't answered into a
* conversation that no longer exists. Left open, a request tied to this
* bot is never pruned and spends the other bot's open-request allowance
* for good.
*/
await endAsksForBot({ bot_id: bot.id! }).catch(async (error: unknown) => {
await logError({ title: `Requests of bot #${bot.id} not ended`, error }).catch(() => {});
return [];
});
if (bot.image_media_id) {
await deleteMedia({ id: bot.image_media_id, user_id: Number(user_id) }).catch(() => {});
}
@@ -0,0 +1,39 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
bot_id: number | string;
workspace_id?: number | null;
client_id: string;
};
/**
* The id of the message a send already stored under the composer's own id,
* or null when that send never landed. Scoped to the user, the bot and the
* place, and searched over every session of that conversation, since the
* send that stored it may have rolled the next one onto a new session.
*/
export default async function grabMessageIdByClientId({
user_id,
bot_id,
workspace_id,
client_id,
}: Params): Promise<number | null> {
const row = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT m.id FROM bot_messages m
JOIN bot_sessions s ON s.id = m.session_id
WHERE m.client_id = ? AND m.bot_id = ? AND m.author = 'user' AND s.user_id = ?
AND COALESCE(m.workspace_id, 0) = COALESCE(?, 0)
ORDER BY m.id DESC LIMIT 1`,
values: [
client_id,
Number(bot_id),
Number(user_id),
workspace_id ? Number(workspace_id) : null,
],
})
).payload?.[0];
return Number(row?.id) || null;
}
@@ -35,6 +35,11 @@ type Params = {
* to it, stored and shown like a crew request's outcome.
*/
from_install_request_id?: number;
/**
* The composer's own id for the send, so the same message sent twice
* (a lost answer, a retry) is recognised rather than stored again.
*/
client_id?: string;
};
/**
@@ -52,6 +57,7 @@ export default async function insertUserMessage({
media = [],
from_ask_id,
from_install_request_id,
client_id,
}: Params): Promise<BotMessageWithAttachments> {
const now = Date.now();
@@ -71,6 +77,7 @@ export default async function insertUserMessage({
reply_to_message_id: reply_to?.id || undefined,
from_ask_id,
from_install_request_id,
client_id,
},
],
});
@@ -104,6 +111,7 @@ export default async function insertUserMessage({
reply_to_message_id: reply_to?.id || undefined,
from_ask_id,
from_install_request_id,
client_id,
created_at: now,
updated_at: now,
attachments: media.map((file) => mediaToAttachment({ media: file })),
@@ -195,11 +195,29 @@ export async function grabMessageRunUsage({
/**
* What a job that is still open has spent so far, from its own calls and
* its recorded steps: a reply cannot look at itself through a message,
* since that is written when it ends.
* since that is written when it ends. Held to the session it is read from,
* so one run can read its own job and never another conversation's.
*/
export async function grabJobRunUsage({ job_id }: { job_id: number | string }) {
export async function grabJobRunUsage({
job_id,
session_id,
}: {
job_id: number | string;
session_id: number | string;
}) {
const calls = (
(await BunSQLite.sql<CallRow>({ sql: CallsSql.replace("%COLUMN%", "job_id"), values: [Number(job_id) || 0] })).payload || []
(
await BunSQLite.sql<CallRow>({
sql: `SELECT t.id, t.created_at, t.harness, t.provider_name, t.model_slug,
t.prompt_tokens, t.cached_tokens, t.completion_tokens, t.settings
FROM token_usages t
JOIN bots_queue q ON q.id = t.job_id
WHERE t.job_id = ? AND q.session_id = ?
ORDER BY t.created_at ASC, t.id ASC
LIMIT 500`,
values: [Number(job_id) || 0, Number(session_id) || 0],
})
).payload || []
).map((item) => toCall({ row: item }));
if (!calls.length) return null;
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import grabWorkspaceComputers from "./grab-workspace-computers";
import grabUserWorkspace from "./grab-user-workspace";
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
type Params = {
user_id: number | string;
@@ -12,12 +13,18 @@ type Params = {
/**
* Makes one of a workspace's computers its default, where its tasks run.
* Returns the workspace's computers, the new default first.
*
* Where a whole workspace's work runs is a crew decision, like linking the
* computer in the first place: a member's bot deciding it needs another one
* would move every bot there, for everyone, from one conversation.
*/
export default async function setWorkspaceComputer({
user_id,
workspace_id,
computer_id,
}: Params) {
await assertCrewManager({ user_id });
const workspace = await grabUserWorkspace({ workspace_id, user_id });
if (!workspace?.id) {
@@ -72,15 +72,20 @@ describe("fitTranscriptToContext", () => {
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 12 characters of this computer_bash output");
});
test("never trims the newest messages, even over budget", () => {
test("cuts the newest results only once every older one is gone", () => {
const transcript: HarnessMessage[] = [
{ role: "user", content: "go" },
{ role: "tool", tool_call_id: "1", content: big },
];
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 1000 });
expect(result.trimmed).toBe(0);
expect(transcript[1]!.content).toBe(big);
/**
* The newest result used to be left whole however far over budget the
* prompt was, so it went out anyway and every candidate refused it.
*/
expect(result.trimmed).toBe(1);
expect(String(transcript[1]!.content)).toContain("[Trimmed:");
expect(transcript[0]!.content).toBe("go");
});
test("keeps to the working context even when the window is far larger", () => {
@@ -93,9 +98,10 @@ describe("fitTranscriptToContext", () => {
});
expect(result.budget).toBe(15000);
expect(result.trimmed).toBe(1);
expect(result.trimmed).toBe(2);
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
expect(transcript[4]!.content).toBe(big);
expect(String(transcript[4]!.content)).toContain("[Trimmed:");
expect(transcript[6]!.content).toBe("recent");
});
test("cuts in one block, down to well under the budget, then leaves it alone", () => {
@@ -171,7 +177,29 @@ describe("fitTranscriptToContext", () => {
expect(result.trimmed).toBeGreaterThan(0);
expect(transcript[0]!.content).toBe(request);
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
expect(result.over_budget).toBe(true);
/**
* Every result was cut, the newest included: the request is what is
* left, and the run pays for it in full.
*/
expect(String(transcript[4]!.content)).toContain("[Trimmed:");
});
test("a brief that fits once the results are cut is not reported as over budget", () => {
const transcript: HarnessMessage[] = [
{ role: "user", content: "Look through the fixture and tell me what fails." },
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
{ role: "tool", tool_call_id: "1", content: big },
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
{ role: "tool", tool_call_id: "2", content: big },
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
{ role: "tool", tool_call_id: "3", content: "recent" },
];
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 131_072, budget_tokens: 12_000 });
expect(result.over_budget).toBe(false);
expect(result.trimmed).toBeGreaterThan(0);
expect(transcript[0]!.content).toBe("Look through the fixture and tell me what fails.");
});
test("says a transcript it trimmed down fits", () => {
@@ -175,6 +175,30 @@ export default function fitTranscriptToContext({
});
}
/**
* The newest results were never cut, and a run still over budget with
* nothing older to trim sent the whole prompt anyway: one 60k-character
* sweep plus a pasted brief went out every turn, and every candidate
* refused it. The newest results are what the run is working from, so
* they are cut last, and only once everything older is gone. A user's
* own text is never touched.
*/
for (let index = Math.max(trimmable, 0); index < transcript.length && total > target; index++) {
const message = transcript[index]!;
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
const name = names.get(message.tool_call_id);
replace({
index,
message: {
...message,
content: trimResult({ index, content: message.content, name }),
},
});
}
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
}
+67 -2
View File
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { alreadyRanToolNote, answerNotSentNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { HarnessTrace } from "../trace/types";
@@ -1435,7 +1435,6 @@ describe("runTextLoop closing tools", () => {
});
test("keeps going when the card comes with real work", async () => {
asked.length = 0;
const { generate } = scripted([
{
text: "Saved your preference and put the question up.",
@@ -1458,6 +1457,72 @@ describe("runTextLoop closing tools", () => {
expect(result.text).toBe("Noted. The question is under this message.");
expect(result.steps).toBe(2);
});
test("a card the tool refused is not the end of the run", async () => {
asked.length = 0;
const { generate, seen } = scripted([
{
text: "Here are my questions:",
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":5}` }],
},
{
text: "Which date rule should the articles follow?",
tool_calls: [{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Ask me which date rule." }],
tools: [askUser, remember],
generate,
resolveCandidates,
});
/**
* The card was never put up, so the answer promising one never went
* out: the run was told and asked again.
*/
expect(result.text).toBe("Which date rule should the articles follow?");
expect(result.steps).toBe(2);
expect(asked).toEqual(["Which date rule?"]);
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: closingFailedNote });
});
test("a card with nothing said beside it is told once, then ends where it is", async () => {
asked.length = 0;
const { generate, seen } = scripted([
{
text: "",
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
},
{
text: " ",
tool_calls: [{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Ask me which date rule." }],
tools: [askUser, remember],
generate,
resolveCandidates,
});
/**
* A card alone answers nothing, and going on would work on the very
* thing it just asked about. Told once, then the run ends: an empty
* answer fails the job with a reason the user can see, rather than
* starting work nobody asked for.
*/
expect(result.text).toBe("");
expect(result.steps).toBe(2);
expect(seen.length).toBe(2);
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: closingNoTextNote });
});
});
describe("runTextLoop answer not sent", () => {
+161 -21
View File
@@ -2,14 +2,20 @@ import { AppData } from "@/src/data/app-data";
import {
alreadyRanToolNote,
answerNotSentNote,
closingFailedNote,
closingNoTextNote,
commitEarlyNote,
contextTrimmedNote,
failedToolCallNote,
oversizedRequestNote,
repairedAnswerNote,
repeatedAnswerNote,
tokensLowNote,
} from "@/src/data/harness-prompts";
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
import sanitizeAnswerText from "@/src/utils/sanitize-answer-text";
import repairAnswerText from "@/src/utils/repair-answer-text";
import { logError } from "@/src/functions/backend/logger";
import HarnessError from "../harness-error";
import isClosingTool from "../tools/closing-tool-names";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
@@ -93,9 +99,10 @@ type Params = {
* last call), read after each round of tools and before an answer is
* returned. They join the transcript, so a message sent while the bot
* works can change what it does, and an answer they arrive in time for
* is written again with them in mind.
* is written again with them in mind. `counted` is false at the wrap up:
* those turns are read, not answered (`takeIncoming`).
*/
incoming?: () => Promise<HarnessMessage[]>;
incoming?: (params?: { counted?: boolean }) => Promise<HarnessMessage[]>;
/**
* What the run is told with what came in: `working` after a round of
* tools, `redraft` past an answer that hadn't gone out (defaults
@@ -352,12 +359,12 @@ export default async function runTextLoop({
const tool_uses: HarnessToolUse[] = [];
/**
* The reads this run already made, by the call they answer
* (`repeatToolCallKey`) and the step it was. A read repeated word for
* word gets this answer instead of being run again, and anything that
* may have written forgets them: a file read once, then edited, is
* read again.
* (`repeatToolCallKey`), the step it was and the transcript message its
* output went into. A read repeated word for word gets this answer
* instead of being run again, and anything that may have written forgets
* them: a file read once, then edited, is read again.
*/
const repeated_reads = new Map<string, number>();
const repeated_reads = new Map<string, { step: number; message: HarnessMessage }>();
/**
* The calls that failed, by the call they answer (`toolCallKey`), with
* the step the first of them ran on and the error it gave. An identical
@@ -409,6 +416,11 @@ export default async function runTextLoop({
* that the message never went out (`answerNotSentNote`).
*/
let told_answer_lost = false;
/**
* A card put up with nothing said beside it has been told, once, to write
* the sentence that goes with it (`closingNoTextNote`).
*/
let told_closing_text = false;
/**
* A run whose prompt no longer fits the working context, with nothing
* trimmable left, has been told, once (`oversizedRequestNote`).
@@ -482,7 +494,20 @@ export default async function runTextLoop({
const checkAnswer = async ({ text, index }: { text: string; index: number }) => {
if (!review) return { verdict: "passed" as const };
const note = await review({ text, tool_uses }).catch(() => null);
const note = await review({ text, tool_uses }).catch(async (error) => {
/**
* A reviewer that throws passes the answer, which is the safe
* thing to do with the user's reply, but it must not read like a
* review that found nothing: a reviewer that is broken every
* time leaves every answer unchecked, and nothing said so.
*/
await logError({
title: "Reviewing a reply failed, so its answer went out unchecked",
error,
}).catch(() => null);
return null;
});
if (!note) return { verdict: "passed" as const };
@@ -524,7 +549,7 @@ export default async function runTextLoop({
if (wrap_up && !wrap_up_announced) {
wrap_up_announced = true;
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index });
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index, counted: false });
/**
* The machine's own account of the work, when the caller has
@@ -632,6 +657,15 @@ export default async function runTextLoop({
(call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name),
);
/**
* What the app would never show as its own word comes out before
* anything reads the answer: a setting pill that leads nowhere and a
* record line this run's tools don't support are text, and sending
* the whole answer back for one costs a rewrite and, on the third,
* the answer (`sanitizeAnswerText`).
*/
if (answer.text) answer.text = sanitizeAnswerText({ text: answer.text });
/**
* A saving turn that reached for anything else is told what it has
* left, and gets that one round again (never more, so the run
@@ -693,6 +727,32 @@ export default async function runTextLoop({
const check = await checkAnswer({ text: answer.text || "", index });
if (check.verdict === "refused") {
/**
* A fault the app can take out is taken out instead of the
* whole answer: what is left is what the tools support, said
* to be part of the answer, so three faults no longer cost a
* user an answer that was right.
*/
const repaired = repairAnswerText({ text: answer.text || "" });
if (repaired.changed && repaired.text) {
await traced({
kind: "event",
index,
name: "repaired",
text: repairedAnswerNote,
});
return {
text: `${repaired.text}\n\n${repairedAnswerNote}`,
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
usage,
tool_uses,
};
}
return {
text: "",
review_note: check.note,
@@ -708,10 +768,14 @@ export default async function runTextLoop({
}
if (!tool_calls.length) {
/**
* Whitespace alone is no answer: it would land as an empty bubble
* (`run-bot-reply` treats it as none and fails with a reason).
*/
const said = (answer.text || "").trim();
return {
text:
answer.text ||
(wrap_up ? `I ran out of steps before I could finish.` : ""),
text: said || (wrap_up ? `I ran out of steps before I could finish.` : ""),
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
@@ -726,7 +790,15 @@ export default async function runTextLoop({
for (const call of tool_calls) {
const repeat_key = repeatToolCallKey({ call });
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
const remembered = repeat_key ? repeated_reads.get(repeat_key) : undefined;
/**
* A read answered from a step is answered only while its output
* is still in the prompt: trimming cut it down to its two ends
* (`fitTranscriptToContext`), which no longer holds what the run
* was reading. Pointing at it then made the model retry the same
* call until the token budget ran out.
*/
const already_read = remembered && transcript.includes(remembered.message) ? remembered.step : undefined;
const call_key = toolCallKey({ call });
const failed_before = call_key ? failed_calls.get(call_key) : undefined;
const give_up =
@@ -781,7 +853,7 @@ export default async function runTextLoop({
repeated_reads.clear();
} else if (already_read === undefined) {
if (content.startsWith("Error:")) repeated_reads.delete(repeat_key);
else repeated_reads.set(repeat_key, index);
else if (remembered) repeated_reads.delete(repeat_key);
}
if (give_up) {
@@ -800,18 +872,63 @@ export default async function runTextLoop({
failed_calls.clear();
}
transcript.push({ role: "tool", tool_call_id: call.id, content });
const tool_message: HarnessMessage = { role: "tool", tool_call_id: call.id, content };
transcript.push(tool_message);
if (repeat_key && already_read === undefined && !content.startsWith("Error:")) {
repeated_reads.set(repeat_key, { step: index, message: tool_message });
}
if (images.length) shown.push({ tool_name: call.name, images });
}
/**
* An answer that ends on a card is the whole reply: the question
* An answer that called a card is the whole reply: the question
* waits for the user, and what comes next was just offered. Going on
* would send the next turn's short line in its place, since the reply
* is only the run's last message (`ClosingToolNames`).
* is only the run's last message (`ClosingToolNames`). A turn that
* called nothing at all is still a whole answer (the check below).
*/
if (answer.text && tool_calls.every((call) => isClosingTool({ name: call.name }))) {
const called_card = tool_calls.some((call) => isClosingTool({ name: call.name }));
const closing = tool_calls.every((call) => isClosingTool({ name: call.name }));
/**
* The card has to be there: a closing call whose arguments the tool
* refused put nothing up, and a message written as if it had is a
* reply that points at a card no one can see.
*/
const closing_worked = closing && tool_uses.slice(-tool_calls.length).every((use) => use.ok);
if (called_card && !closing_worked) {
pushUserTurn({ transcript, content: closingFailedNote });
await traced({ kind: "event", index, name: "closing_failed", text: closingFailedNote });
continue;
}
/**
* A card with nothing beside it answers nothing, and the run would
* go on to work on the very thing it just asked about. Told once,
* and the run ends on the sentence it writes (`closingNoTextNote`).
*/
if (closing_worked && called_card && !(answer.text || "").trim()) {
if (!told_closing_text) {
told_closing_text = true;
pushUserTurn({ transcript, content: closingNoTextNote });
await traced({ kind: "event", index, name: "closing_no_text", text: closingNoTextNote });
continue;
}
return {
text: "",
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
usage,
tool_uses,
};
}
if (closing_worked && answer.text) {
/**
* Checked before it goes out, as any reply is: a note comes
* back and the answer is written again (the card stays on the
@@ -820,6 +937,26 @@ export default async function runTextLoop({
const check = await checkAnswer({ text: answer.text, index });
if (check.verdict === "refused") {
const repaired = repairAnswerText({ text: answer.text });
if (repaired.changed && repaired.text) {
await traced({
kind: "event",
index,
name: "repaired",
text: repairedAnswerNote,
});
return {
text: `${repaired.text}\n\n${repairedAnswerNote}`,
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
usage,
tool_uses,
};
}
return {
text: "",
review_note: check.note,
@@ -933,10 +1070,13 @@ export default async function runTextLoop({
/**
* Adds what the user wrote since the last look, after `note`. True when
* there was anything.
* there was anything. `counted` says whether the run will answer what it
* read: the wrap up writes the answer it already had to, so a message
* taken in there is left for its own reply (`run-bot-reply`), not marked
* answered by an answer written before it arrived.
*/
async function takeIncoming({ note, index }: { note: string; index: number }) {
const turns = (await incoming?.()) || [];
async function takeIncoming({ note, index, counted = true }: { note: string; index: number; counted?: boolean }) {
const turns = (await incoming?.({ counted })) || [];
const user_turns = turns.filter((turn) => turn.role == "user");
if (!user_turns.length) return false;
+18 -1
View File
@@ -13,6 +13,12 @@ type Params = {
* The user's worker bots.
*/
workers: BUN_SQLITE_COBBLE_BOTS[];
/**
* Whether the run is one the user is following in a conversation. A run
* nobody watches acts on a brief alone, and a brief can be written by
* any bot.
*/
attended?: boolean;
};
type Args = {
@@ -26,7 +32,7 @@ type Args = {
* Irreversible, so it only runs when the user asked for that exact bot to
* go.
*/
export default function deleteBotTool({ user_id, workers }: Params): HarnessTool<Args> {
export default function deleteBotTool({ user_id, workers, attended = false }: Params): HarnessTool<Args> {
const crew = workers.map((bot) => `${bot.id}: ${bot.name}`).join("; ");
return {
@@ -36,6 +42,17 @@ export default function deleteBotTool({ user_id, workers }: Params): HarnessTool
bot_id: z.number().int(),
}),
run: async ({ args }) => {
/**
* Nothing here can be undone, so it happens where the user can
* see it and say stop: a routine, a hook call or a task another
* bot handed over only has a brief to go on.
*/
if (!attended) {
throw new Error(
`Deleting a bot can't be undone, so it is done only in a conversation with the user, where they can confirm it. Nothing was deleted: say that it has to be asked for in the chat with them.`,
);
}
const fresh = await grabCrewWorkers();
const worker = fresh.find((bot) => bot.id == args.bot_id);
@@ -13,6 +13,12 @@ type Params = {
* The user's live workspaces.
*/
workspaces: BUN_SQLITE_COBBLE_WORKSPACES[];
/**
* Whether the run is one the user is following in a conversation. A run
* nobody watches acts on a brief alone, and a brief can be written by
* any bot.
*/
attended?: boolean;
};
type Args = {
@@ -28,6 +34,7 @@ type Args = {
export default function deleteWorkspaceTool({
user_id,
workspaces,
attended = false,
}: Params): HarnessTool<Args> {
const list = workspaces.map((w) => `${w.id}: ${w.name}`).join("; ");
@@ -38,6 +45,17 @@ export default function deleteWorkspaceTool({
workspace_id: z.number().int(),
}),
run: async ({ args }) => {
/**
* Nothing here can be undone, so it happens where the user can
* see it and say stop: a routine, a hook call or a task another
* bot handed over only has a brief to go on.
*/
if (!attended) {
throw new Error(
`Deleting a workspace can't be undone, so it is done only in a conversation with the user, where they can confirm it. Nothing was deleted: say that it has to be asked for in the chat with them.`,
);
}
const live = (await grabUserWorkspaces({ user_id })).filter((w) => !w.archived);
const workspace = live.find((w) => w.id == args.workspace_id);
+2 -2
View File
@@ -258,7 +258,7 @@ export default async function grabBotChatTools({
tools.push(findBotTool(), findWorkspaceTool({ user_id }), listWorkspaceBotsTool({ user_id }));
tools.push(deleteWorkspaceTool({ user_id, workspaces }));
tools.push(deleteWorkspaceTool({ user_id, workspaces, attended }));
if (!workers.length) return tools;
@@ -284,7 +284,7 @@ export default async function grabBotChatTools({
}),
);
tools.push(updateBotTool({ user_id, workers }), deleteBotTool({ user_id, workers }));
tools.push(updateBotTool({ user_id, workers }), deleteBotTool({ user_id, workers, attended }));
if (computers.length) {
const access = Object.fromEntries(
+23 -5
View File
@@ -15,6 +15,7 @@ import askBotTool from "./ask-bot-tool";
import listAsksTool from "./list-asks-tool";
import readMessageUsageTool from "./settings/read-message-usage-tool";
import readSettingsTool from "./settings/read-settings-tool";
import grabCrewRole from "@/src/functions/backend/db/access/grab-crew-role";
import type { StorageScope } from "@/src/utils/storage-access";
type Params = {
@@ -88,16 +89,33 @@ export default async function grabBotTools({
onPropose,
onTask,
}: Params): Promise<HarnessTool[]> {
const can_manage_crew = (await grabCrewRole({ user_id })) != "member";
return [
setPictureTool({ user_id, bot_id, scopes, is_coordinator }),
readSettingsTool(),
readMessageUsageTool({ session_id }),
updateMemoryTool({ user_id, bot_id, workspace_id }),
updateInstructionsTool({ user_id, bot_id, workspace_id }),
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
updateMemoryTool({ user_id, bot_id, workspace_id, can_manage_crew }),
...(can_manage_crew || workspace_id
? [updateInstructionsTool({ user_id, bot_id, workspace_id, can_manage_crew })]
: []),
/**
* A hook call runs on someone else's words: its brief and payload are
* fenced as data, so a payload that talks the model round must not be
* able to leave a lasting mark on what the bot remembers, how it works
* or when it runs. It reads, works and reports; those changes are made
* in the conversation it reports into. A routine is the user's own
* schedule, and a task run answers the user's own request, so both
* keep them.
*/
...(hooked
? []
: [
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
updateScheduleTool({ user_id, bot_id }),
deleteScheduleTool({ user_id, bot_id }),
]),
listSchedulesTool({ user_id, bot_id }),
updateScheduleTool({ user_id, bot_id }),
deleteScheduleTool({ user_id, bot_id }),
...grabBotHookTools({ user_id, bot_id, session_id, workspace_id, computers, hooked, onPropose }),
...(session_id ? [reactToMessageTool({ bot_id, user_id, session_id })] : []),
/**
@@ -80,7 +80,12 @@ Long runs cost more than the work suggests because every turn resends the prompt
if (!job_id) return describeMessageUsageList({ messages: await grabSessionMessageUsage({ session_id: run_session_id }) });
const usage = await grabJobRunUsage({ job_id });
/**
* Read within this conversation's session: a job id is not a
* handle to someone else's run, and the cost of a run says which
* provider, model and limits it used.
*/
const usage = await grabJobRunUsage({ job_id, session_id: run_session_id });
if (!usage) {
return `No model calls recorded for run #${job_id} yet.`;
@@ -13,6 +13,13 @@ type Params = {
* for the workspace unless it picks `core`.
*/
workspace_id?: number | string | null;
/**
* Whether the run's user manages the crew. A member's run writes the
* bot's instructions for the workspace it is in and never its core
* ones: those start every user's prompt, so one member's conversation
* would rewrite them for everyone else.
*/
can_manage_crew?: boolean;
};
type Args = {
@@ -20,28 +27,43 @@ type Args = {
scope?: "workspace" | "core";
};
const WorkspaceNote = `your instructions for this workspace, under "# Your instructions in ...": yours there, not the workspace's description or context. Keep everything that still applies.`;
/**
* Lets a bot rewrite its own instructions as it adapts to the user: its
* core instructions, or in a workspace (by default) its instructions for
* that workspace.
* that workspace. Calls itself only with the crew-manager case in reach
* (`grabBotTools`), since core instructions are what every user's run of
* the bot starts from.
*/
export default function updateInstructionsTool({
user_id,
bot_id,
workspace_id,
can_manage_crew = false,
}: Params): HarnessTool<Args> {
const instructions = z.string().trim().max(AppData.PromptMaxLength);
const may_write_core = Boolean(can_manage_crew);
return {
name: "update_instructions",
description: workspace_id
? `Replace your instructions with this full text (markdown). scope "workspace" (the default) is your instructions for this workspace, under "# Your instructions in ...": yours there, not the workspace's description or context; "core" is your core instructions, the start of your prompt in every workspace and your own chat. Both are shared: the workspace's with everyone working in it, your core ones with every user you work for. Change them only for how you should work for all of them, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`
: `Replace your core instructions with this full text (markdown): the start of your prompt, before any workspace or memory, shared with every user you work for. Change them only for how you should work for every user you work for, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`,
schema: workspace_id
? z.object({ instructions, scope: z.enum(["workspace", "core"]).default("workspace") })
: z.object({ instructions: instructions.min(1) }),
description:
!workspace_id
? `Replace your core instructions with this full text (markdown): the start of your prompt, before any workspace or memory, shared with every user you work for. Change them only for how you should work for every user you work for, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`
: may_write_core
? `Replace your instructions with this full text (markdown). scope "workspace" (the default) is ${WorkspaceNote} "core" is your core instructions, the start of your prompt in every workspace and your own chat. Both are shared: the workspace's with everyone working in it, your core ones with every user you work for. Change them only for how you should work for all of them, such as a standing rule for your job; a preference of this one user goes in your memory of them (update_memory, scope "user"). Keep everything that still applies.`
: `Replace your instructions for this workspace with this full text (markdown). ${WorkspaceNote} They are shared with everyone working here, so change them for how you should work here, never for what one user prefers: that goes in your memory of them (update_memory, scope "user").`,
schema:
workspace_id && may_write_core
? z.object({
instructions: instructions.min(1),
scope: z.enum(["workspace", "core"]).default("workspace"),
})
: z.object({ instructions: instructions.min(1) }),
run: async ({ args }) => {
if (workspace_id && args.scope != "core") {
const scope = workspace_id && may_write_core ? args.scope : "workspace";
if (workspace_id && scope != "core") {
await updateWorkspaceBot({
user_id,
workspace_id,
@@ -57,6 +79,10 @@ export default function updateInstructionsTool({
return `Instructions for this workspace saved and checked. They apply from your next run here. They are yours in this workspace, not its context: the workspace's own description and context did not change.`;
}
if (!may_write_core) {
return `Your core instructions are shared with every user you work for, so only an admin can change them. Nothing was saved: your instructions for this workspace are the ones you can write here (update_memory, scope "workspace", keeps what you learn about the work itself).`;
}
await updateBotSystemPrompt({
user_id,
bot_id,
@@ -66,4 +92,4 @@ export default function updateInstructionsTool({
return `Core instructions saved and checked. They apply from your next run, everywhere.`;
},
};
}
}
@@ -17,6 +17,12 @@ type Params = {
* the workspace unless it picks another scope.
*/
workspace_id?: number | string | null;
/**
* Whether the run's user manages the crew: core memory is shared with
* every user the bot works for, so a member's run writes only what is
* theirs (`user`) or the workspace's.
*/
can_manage_crew?: boolean;
};
type Args = {
@@ -41,8 +47,10 @@ export default function updateMemoryTool({
user_id,
bot_id,
workspace_id,
can_manage_crew = false,
}: Params): HarnessTool<Args> {
const memory = z.string().max(AppData.PromptMaxLength);
const may_write_core = Boolean(can_manage_crew);
return {
name: "update_memory",
@@ -54,6 +62,14 @@ export default function updateMemoryTool({
: z.object({ memory, scope: z.enum(["user", "core"]).default("user") }),
run: async ({ args }) => {
if (args.scope == "core") {
/**
* Core memory starts every user's run of this bot: one
* member's conversation must not rewrite it for the rest.
*/
if (!may_write_core) {
return `Your core memory is shared with every user you work for, so only an admin can change it. Nothing was saved: what holds for this user goes in your memory of them (scope "user"${workspace_id ? `, or "workspace" for what holds for the work here` : ""}).`;
}
await updateBotMemory({ user_id, bot_id, memory: args.memory });
await checkSavedText({ kind: "core_memory", bot_id, expected: args.memory });
return `Core memory saved and checked.`;
@@ -9,12 +9,13 @@ export default async function sendBotMessage({
text,
media_ids,
reply_to_message_id,
client_id,
}: SendBotMessageRequest) {
return await fetchApi<
SendBotMessageRequest,
APIResponseObject<BotMessageWithAttachments>
>(`/api/admin/bots/send-message`, {
method: "POST",
body: { bot_id, workspace_id, text, media_ids, reply_to_message_id },
body: { bot_id, workspace_id, text, media_ids, reply_to_message_id, client_id },
});
}
@@ -18,6 +18,11 @@ type Params = {
* The thread's last message: only newer ones are replayed.
*/
last_message_id?: number | null;
/**
* How many replies the session still has to come, as the read found it:
* zero means the one it was waiting on ended without a message.
*/
on_open_jobs?: (params: { open_jobs: number }) => void;
};
/**
@@ -33,10 +38,23 @@ type Params = {
* screen. The step is replayed as `server:bot-job-update`, so a run whose
* steps were pushed while the page slept still shows the one it's on.
* Reading it even when no reply is due is what lets a row stuck on a stale
* face or task clear itself without a reload.
* face or task clear itself without a reload. The replies the session still
* has to come are handed back too: a run that ended without a word leaves
* the thread's last message the user's, so the face alone can't tell it from
* one still on its way.
*/
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
export default function useReplyCatchUp({
session_id,
awaiting_reply,
last_message_id,
on_open_jobs,
}: Params) {
const last_message = useRef(Number(last_message_id) || 0);
/**
* Read through a ref, so a new callback on every render doesn't rebuild
* the check (and the poll's timer with it).
*/
const report_open_jobs = useRef(on_open_jobs);
/**
* The open session: a read that lands after the thread moved to
* another one is dropped instead of replaying into the wrong thread.
@@ -45,6 +63,7 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
last_message.current = Number(last_message_id) || 0;
open_session.current = session_id;
report_open_jobs.current = on_open_jobs;
const check = useCallback(async () => {
if (!session_id) return;
@@ -80,6 +99,16 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
* word an interim one) drops the row once its face moves on.
*/
if (res.bot?.id) replay({ data: { event: "server:bot-updated", data: res.bot } });
/**
* A thread whose last word is the user's waits on a reply; when none
* is left to come, the one it waited on ended without a message
* (every message in the session had been answered already) and the
* thinking row goes.
*/
if (typeof res.open_jobs == "number") {
report_open_jobs.current?.({ open_jobs: res.open_jobs });
}
}, [session_id]);
useRefocus({ onRefocus: () => void check() });
@@ -313,7 +313,19 @@ export default function Composer({
temp_id.current -= 1;
const client_id = temp_id.current;
const text_sent = text;
/**
* The text goes as the server will store it, trimmed: a message
* with a trailing newline was saved without it, and the bubble
* waiting for it never matched the saved one.
*/
const text_sent = text.trim();
/**
* The server's own handle for this send, so a send whose answer
* never arrived is recognised as the message already stored. Not
* the thread's temp id: that restarts after a reload and would
* match an older message of the same conversation.
*/
const request_id = crypto.randomUUID();
const media_ids = files.media_ids;
const attachments = files.pending.flatMap((item) =>
item.status == "ready" && item.attachment ? [item.attachment] : [],
@@ -356,6 +368,7 @@ export default function Composer({
text: text_sent,
media_ids,
reply_to_message_id: reply_to?.id || null,
client_id: request_id,
});
if (!res.success || !res.singleRes) {
@@ -28,6 +28,23 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
const [value, setValue] = useState("");
const [busy, setBusy] = useState<"save" | "decline">();
const [error, setError] = useState<string>();
/**
* The answer the bot never heard: the request was decided and the
* message that tells it didn't go, so the user gets a way to send it
* again instead of a card that closed on a promise nobody kept.
*/
const [unsent, setUnsent] = useState<string>();
const tellBot = async (params: { text: string }) => {
const res = await sendBotMessage({
bot_id: Number(pageProps?.bot?.id) || 0,
workspace_id: pageProps?.workspace?.id || null,
text: params.text,
media_ids: [],
}).catch(() => null);
return Boolean(res?.success);
};
const open = view.status == "pending";
@@ -61,17 +78,38 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
setValue("");
onDecided(res.singleRes);
await sendBotMessage({
bot_id: Number(pageProps?.bot?.id) || 0,
workspace_id: pageProps?.workspace?.id || null,
text: secretRequestMessage({ view: res.singleRes }),
media_ids: [],
}).catch(() => null);
const text = secretRequestMessage({ view: res.singleRes });
if (!(await tellBot({ text }))) {
/**
* The secret is saved; what's left is telling the bot, and that
* has to be possible from here rather than by remembering to
* type it in the chat.
*/
setUnsent(text);
setBusy(undefined);
setError(`Saved for you, but the bot wasn't told. Send it the message again below.`);
return;
}
setBusy(undefined);
onDone();
};
const resend = async () => {
if (!unsent) return;
setError(undefined);
if (!(await tellBot({ text: unsent }))) {
setError(`Couldn't tell the bot. Try again.`);
return;
}
setUnsent(undefined);
onDone();
};
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>What it is</MessageDetailsHeading>
@@ -104,6 +142,19 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
{error ? <Span className="mt-2 text-[13px] leading-5 text-ink">{error}</Span> : null}
{!open && unsent ? (
<Row className="mt-3 w-full gap-2! justify-end">
<Button
type="button"
size="small"
title="Send the bot the message it never got"
onClick={resend}
>
Tell the bot
</Button>
</Row>
) : null}
{open ? (
<Row className="mt-5 w-full gap-2! justify-end">
<Button
@@ -97,6 +97,13 @@ export default function Conversation() {
* session, which the composer gives way to a link to.
*/
const [moved_to_session_id, setMovedToSessionId] = useState<number | null>(null);
/**
* How many replies the session still has to come, as the last catch-up
* read found them, or null while that isn't known yet. A reply that ends
* without a message leaves the last word the user's, so without this the
* thread would wait on an answer that is never coming.
*/
const [open_reply_jobs, setOpenReplyJobs] = useState<number | null>(null);
const [has_other_unread, setHasOtherUnread] = useState(false);
/**
* The debug logs under the thinking row, which its bug button toggles.
@@ -212,6 +219,7 @@ export default function Conversation() {
});
progress.reset({ task: history.task });
setReplyStep(history.step || null);
setOpenReplyJobs(null);
},
});
@@ -230,7 +238,8 @@ export default function Conversation() {
*/
const awaiting_reply =
!moved_to_session_id &&
isAwaitingReply({ last_message: last_thread_message, face: live_bot?.face });
isAwaitingReply({ last_message: last_thread_message, face: live_bot?.face }) &&
(open_reply_jobs == null || open_reply_jobs > 0);
const reply_progress = useReplyProgress({
bot_id: bot?.id || 0,
@@ -243,6 +252,7 @@ export default function Conversation() {
session_id,
awaiting_reply,
last_message_id: last_saved_id,
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
});
/**
@@ -279,6 +289,13 @@ export default function Conversation() {
dropSentMessage({ pending: prev, message }),
);
/**
* A message the user sent, here or in another tab, has a reply
* queued behind it: what the last read said about open replies is
* out of date.
*/
if (message.author == "user") setOpenReplyJobs(null);
/**
* Before the history lands the thread has no session yet: the
* message waits in the thread, and the history merges with it.
@@ -493,12 +510,19 @@ export default function Conversation() {
previous_messages={thread_messages}
reply_to={reply_to}
onCancelReply={() => setReplyTo(null)}
onSendStart={({ message }) =>
onSendStart={({ message }) => {
/**
* A reply is queued for it, so
* the thread waits on one again
* (a session that had none left
* stopped polling).
*/
setOpenReplyJobs(null);
setPendingMessages((prev) => [
...prev,
message,
])
}
]);
}}
onSendFailed={({ temp_id }) =>
setPendingMessages((prev) =>
prev.filter(
@@ -23,7 +23,7 @@ export default function dropSentMessage({ pending, message }: Params): BotMessag
const index = pending.findIndex(
(item) =>
item.text == message.text &&
(item.text || "").trim() == (message.text || "").trim() &&
(item.reply_to?.id || null) == (message.reply_to_message_id || null) &&
(item.attachments?.length || 0) == (message.attachments?.length || 0),
);
+74 -12
View File
@@ -3,6 +3,9 @@ import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-u
import ensureBotSession from "@/src/functions/backend/db/bot-sessions/ensure-bot-session";
import insertUserMessage from "@/src/functions/backend/db/bots/insert-user-message";
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
import grabMessageIdByClientId from "@/src/functions/backend/db/bots/grab-message-id-by-client-id";
import deleteBotMessage from "@/src/functions/backend/db/bots/delete-bot-message";
import { logError } from "@/src/functions/backend/logger";
import grabAttachableMedia from "@/src/functions/backend/db/bots/grab-attachable-media";
import storeChatAttachments from "@/src/functions/backend/db/bot-files/store-chat-attachments";
import enqueueBotReply from "@/src/functions/backend/db/bots-queue/enqueue-bot-reply";
@@ -51,10 +54,11 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
throw new AppError(`This user can only read records.`);
}
const { bot_id, workspace_id, text, media_ids, reply_to_message_id } = parseWithSchema({
schema: SendBotMessageRequestSchema,
data: body,
});
const { bot_id, workspace_id, text, media_ids, reply_to_message_id, client_id } =
parseWithSchema({
schema: SendBotMessageRequestSchema,
data: body,
});
const max_chars = await grabBotMessageMaxChars();
@@ -65,6 +69,44 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
const conversation = await grabUserConversation({ user_id: user.id, bot_id, workspace_id });
const bot = conversation.bot;
/**
* A send whose answer never arrived is sent again with the same
* client id, and the message it stored is already there: answering
* that one, with its reply still queued (`enqueueBotReply` reuses the
* open job), keeps the thread from showing the message twice with
* the bot answering both copies.
*/
if (client_id) {
const stored_id = await grabMessageIdByClientId({
user_id: user.id,
bot_id: bot.id,
workspace_id: conversation.workspace_id,
client_id,
}).catch(() => null);
const stored = stored_id
? await grabUserBotMessage({ user_id: user.id, message_id: stored_id }).catch(
() => null,
)
: null;
if (stored?.id && stored.session_id) {
await enqueueBotReply({
user_id: user.id,
bot_id: bot.id,
session_id: Number(stored.session_id),
message_id: Number(stored.id),
});
wakeBotsQueue();
return {
success: true,
singleRes: stored,
};
}
}
const media = await grabAttachableMedia({ user_id: Number(user.id), media_ids });
const session = await ensureBotSession({
user_id: user.id,
@@ -100,24 +142,44 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
text,
reply_to,
media,
client_id,
});
try {
await enqueueBotReply({
user_id: user.id,
bot_id: bot.id,
session_id: Number(session.id),
message_id: message.id || 0,
});
} catch (error: unknown) {
/**
* A message with no reply queued would sit in the thread with
* nothing ever answering it, while the composer has already
* taken its pending bubble down: it is taken back out, so the
* send fails where the user can see it and send it again.
*/
await deleteBotMessage({ message_id: Number(message.id) }).catch(() => null);
throw error;
}
/**
* The files join the conversation's folder, so a later run can
* search what the user sent now.
* search what the user sent now. The message and its reply are
* stored and queued by now: a folder that can't be written costs a
* search hit, never the message.
*/
await storeChatAttachments({
bot_id: bot.id,
workspace_id: conversation.workspace_id,
user_id: user.id,
media,
});
await enqueueBotReply({
user_id: user.id,
bot_id: bot.id,
session_id: Number(session.id),
message_id: message.id || 0,
}).catch(async (error: unknown) => {
await logError({
title: `Files of message #${message.id} not added to its conversation`,
error,
}).catch(() => {});
});
wakeBotsQueue();
+5 -1
View File
@@ -4,6 +4,7 @@ import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
import grabSessionReplyStep from "@/src/functions/backend/db/bots-queue/grab-session-reply-step";
import grabSessionOpenReplies from "@/src/functions/backend/db/bots-queue/grab-session-open-replies";
import { AppData } from "@/src/data/app-data";
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
import type { SessionMessagesResponse } from "@/src/types";
@@ -17,7 +18,9 @@ import type { BunextAPIRouteHandler } from "@moduletrace/bunext/types";
* bot's face, status line and active task for that user (as
* `server:bot-updated` carries them) plus the step its reply is on (as
* `server:bot-job-update` does), so the open conversation can catch up on a
* reply, a face change or a step whose live push it missed.
* reply, a face change or a step whose live push it missed. `open_jobs` says
* whether anything is still to answer there, so a run that ended without a
* word can't leave the thread thinking.
*/
export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({ req, body }) => {
try {
@@ -54,6 +57,7 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
task: await grabActiveBotTask({ bot_id, user_id: user.id }),
},
step: await grabSessionReplyStep({ session_id: session.id }),
open_jobs: await grabSessionOpenReplies({ session_id: session.id }),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
+6
View File
@@ -63,6 +63,12 @@ export const SendBotMessageRequestSchema = z.object({
* The message this one replies to, quoted above it.
*/
reply_to_message_id: z.coerce.number().int().positive().nullish(),
/**
* The composer's own id for this send, so a send whose answer never
* arrived is recognised as the message already stored instead of
* being posted a second time.
*/
client_id: z.string().trim().max(64).optional(),
}).refine((body) => body.text || body.media_ids.length, "Write a message or attach a file first");
export type SendBotMessageRequest = z.infer<typeof SendBotMessageRequestSchema>;
+7
View File
@@ -579,6 +579,13 @@ export type SessionMessagesResponse = APIResponseObject<BotMessageWithAttachment
* step's push replays it and keeps its thinking row's line.
*/
step?: BotJobUpdateData | null;
/**
* How many replies the session still has to come (queued or being
* written). Zero says nothing will answer there any more: a thread whose
* last word is the user's stops waiting instead of thinking forever,
* which is what a run that ended without a message looks like.
*/
open_jobs?: number | null;
};
/**
+15
View File
@@ -28,4 +28,19 @@ describe("redactSecrets", () => {
redactSecrets({ text: "a 1 b", secrets: [{ key: "PIN", value: "1" }] }),
).toBe("a 1 b");
});
test("masks a three character code", () => {
expect(
redactSecrets({
text: "code 429 ping, again 429",
secrets: [{ key: "CODE", value: "429" }],
}),
).toBe("code [CODE] ping, again [CODE]");
});
test("leaves a two character value alone", () => {
expect(
redactSecrets({ text: "ab cd", secrets: [{ key: "PAIR", value: "cd" }] }),
).toBe("ab cd");
});
});
+6 -3
View File
@@ -8,12 +8,15 @@ type Params = {
/**
* Replaces every secret value in `text` with `[KEY]`, longest first so a
* value inside another is never half replaced. Values under 4 characters
* are left alone: too likely to match ordinary text.
* value inside another is never half replaced. Values under 3 characters
* are left alone: a one or two letter code matches ordinary text
* everywhere, and masking those would hide the result instead of the
* secret. A three character code (a short PIN, a country code) is masked,
* since it is the shortest thing that is still a secret.
*/
export default function redactSecrets({ text, secrets }: Params) {
const usable = secrets
.filter((secret) => secret.value.length >= 4)
.filter((secret) => secret.value.length >= 3)
.sort((a, b) => b.value.length - a.value.length);
let redacted = text;
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, test } from "bun:test";
import repairAnswerText from "./repair-answer-text";
import sanitizeAnswerText from "./sanitize-answer-text";
describe("sanitizeAnswerText", () => {
test("takes out a pill that goes nowhere and keeps the rest", () => {
expect(sanitizeAnswerText({ text: "Raise it in [setting:general:x] and it's done." })).toBe(
"Raise it in and it's done.",
);
});
test("takes out an app record line the bot wrote itself", () => {
expect(
sanitizeAnswerText({
text: "The scan is done.\n\n[App record: this message's run called start_task, read_file x2.]",
}),
).toBe("The scan is done.");
});
test("leaves an answer that holds up alone", () => {
expect(sanitizeAnswerText({ text: "Here it is: [file:12]." })).toBe("Here it is: [file:12].");
});
});
describe("repairAnswerText", () => {
test("takes out a claim of work under way and keeps the report", () => {
const repaired = repairAnswerText({
text: "Three contests are open. I'm scanning the rest now. The first closes on Friday.",
});
expect(repaired.changed).toBe(true);
expect(repaired.text).toContain("Three contests are open.");
expect(repaired.text).toContain("The first closes on Friday.");
expect(repaired.text).not.toContain("scanning the rest");
});
test("takes out a promise of a report", () => {
const repaired = repairAnswerText({ text: "Nothing to report yet. I'll report back when it's done." });
expect(repaired.changed).toBe(true);
expect(repaired.text).not.toContain("report back");
});
test("says it changed nothing when the answer holds up", () => {
const repaired = repairAnswerText({ text: "The log has three timeouts at 09:12." });
expect(repaired.changed).toBe(false);
expect(repaired.text).toBe("The log has three timeouts at 09:12.");
});
});
+19
View File
@@ -0,0 +1,19 @@
import claimsWorkUnderWay from "./claims-work-under-way";
import sanitizeAnswerText from "./sanitize-answer-text";
/**
* The answer with the parts the app's record can't support taken out,
* sentence by sentence: a sentence saying work goes on past this reply, or
* that a report is still to come, is removed when nothing was started and
* nothing of the run's is open. What is left is what the tools returned, so
* it holds up on its own. `changed` is false when there was nothing to take
* out, and the answer is then refused as it was before: an answer the app
* knows is wrong is never sent.
*/
export default function repairAnswerText({ text }: { text: string }) {
const sentences = text.split(/(?<=[.!?])\s+|\n/);
const kept = sentences.filter((sentence) => !sentence.trim() || !claimsWorkUnderWay({ text: sentence }));
const repaired = sanitizeAnswerText({ text: kept.join(" ") }).trim();
return { text: repaired, changed: kept.length != sentences.length };
}
+10 -2
View File
@@ -22,8 +22,16 @@ describe("replyClaimProblems", () => {
expect(replyClaimProblems({ text: underWay, tool_uses: [], has_open_work: true })).toEqual([]);
});
test("a start_task call that failed doesn't count", () => {
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name: "start_task", ok: false }] }).length).toBe(1);
test("a start_task a run was refused for is not the answer's fault", () => {
/**
* An honest "I couldn't start it" names no work it made up: the app
* refused the start, and faulting the note sent it back as a lie.
*/
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name: "start_task", ok: false }] })).toEqual([]);
});
test("a claim with no start attempt at all is still faulted", () => {
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name: "read_file", ok: true }] }).length).toBe(1);
});
test("names files and tasks that don't exist", () => {
+7 -1
View File
@@ -72,6 +72,12 @@ export default function replyClaimProblems({
}
const started = tool_uses.some((use) => use.ok && WorkStartingTools.includes(use.name));
/**
* A run that reached for `start_task` and was refused was not making the
* claim up: it is reporting what the app told it. Faulting that note sent
* an honest "I couldn't start it" back as a lie.
*/
const tried = tool_uses.some((use) => WorkStartingTools.includes(use.name));
/**
* A record line the answer wrote itself that claims work this reply
@@ -90,7 +96,7 @@ export default function replyClaimProblems({
);
}
if (!started && !has_open_work && claimsWorkUnderWay({ text })) {
if (!started && !tried && !has_open_work && claimsWorkUnderWay({ text })) {
problems.push(
`It says work is going on beyond this reply, or that its findings are still to come, but this reply started no run (start_task) and nothing of yours is open in this conversation. Nothing is running, so no result arrives unless you call start_task now.`,
);
+14
View File
@@ -0,0 +1,14 @@
import stripAppRecords from "./strip-app-records";
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`).
*/
export default function sanitizeAnswerText({ text }: { text: string }) {
return stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) });
}
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test";
import stripUnresolvedSettingRefs from "./strip-unresolved-setting-refs";
describe("stripUnresolvedSettingRefs", () => {
test("keeps a ref the app resolves", () => {
expect(stripUnresolvedSettingRefs({ text: "See [setting:run-limits:run_tokens]." })).toBe(
"See [setting:run-limits:run_tokens].",
);
});
test("keeps a ref to a whole page", () => {
expect(stripUnresolvedSettingRefs({ text: "In [setting:prompt-appendix]." })).toBe(
"In [setting:prompt-appendix].",
);
});
test("takes out a page that isn't there", () => {
expect(stripUnresolvedSettingRefs({ text: "Set [setting:general:run_tokens] higher." })).toBe(
"Set higher.",
);
});
test("takes out a field the page doesn't have", () => {
expect(stripUnresolvedSettingRefs({ text: "Change [setting:run-limits:nonsense]." })).toBe("Change .");
});
test("a ref quoted alone in a code span is still the ref", () => {
expect(stripUnresolvedSettingRefs({ text: "Write `[setting:general:x]` there." })).toBe("Write `` there.");
expect(stripUnresolvedSettingRefs({ text: "Write `[setting:run-limits:run_tokens]` there." })).toBe(
"Write `[setting:run-limits:run_tokens]` there.",
);
});
test("a ref inside example code is left as typed", () => {
const text = "The shape is `[setting:<page>:<field>]`, like [setting:run-limits:reply_steps].";
expect(stripUnresolvedSettingRefs({ text })).toBe(text);
});
test("a fenced block is left alone", () => {
const text = "```\n[setting:general:run_tokens]\n```";
expect(stripUnresolvedSettingRefs({ text })).toBe(text);
});
test("text with no ref at all comes back as it was", () => {
expect(stripUnresolvedSettingRefs({ text: "Nothing to see." })).toBe("Nothing to see.");
});
});
@@ -0,0 +1,59 @@
import { findGeneralSettingsField, findGeneralSettingsSection } from "@/src/dict/general-settings-dict";
/**
* Fenced code blocks (closed or still open at the end) and inline code
* spans, kept apart so a ref written inside example code stays as it was
* typed.
*/
const CodeParts = /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]+`)/g;
/**
* A code span holding nothing but one setting ref (`` `[setting:x:y]` ``):
* that one is the ref, as it is in a message (`linkComputerRefs`).
*/
const LoneRefInCode = /^`{1,2}[ \t]*\[setting:[a-z0-9_:-]+\][ \t]*`{1,2}$/i;
const SettingRefs = /\[setting:([a-z0-9-]+)(?::([a-z0-9_-]+))?\]/gi;
/**
* The refs in a piece of text that the app can't resolve: the section is no
* page of the settings and, when named, the field is not in it.
*/
function unresolvedIn({ text }: { text: string }): string[] {
const unresolved: string[] = [];
for (const match of text.matchAll(SettingRefs)) {
const ref = match[0];
const section = match[1] || "";
const field = match[2];
const found = findGeneralSettingsSection({ key: section });
const holds = found ? !field || Boolean(findGeneralSettingsField({ section, field })) : false;
if (!holds && !unresolved.includes(ref)) unresolved.push(ref);
}
return unresolved;
}
/**
* Removes the `[setting:...]` refs the app can't resolve: a ref that names
* no page and field still renders, as a pill that goes nowhere. Taking it
* out leaves the rest of the answer, where sending the whole answer back for
* one pill costs a rewrite and, on the third fault, the answer itself
* (`reviewBotReply`). A ref inside a code span is read like one in a
* message: alone it is the ref, inside longer code it is literal text.
*/
export default function stripUnresolvedSettingRefs({ text }: { text: string }) {
if (!text.toLowerCase().includes("[setting:")) return text;
return text
.split(CodeParts)
.map((part, index) => {
if (index % 2 == 1 && !LoneRefInCode.test(part)) return part;
const unresolved = unresolvedIn({ text: part });
return unresolved.reduce((kept, ref) => kept.split(ref).join(""), part);
})
.join("");
}