Compare commits

...
26 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 66bdcff208 Bump version to 0.28.20
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:12 +01:00
tbenandClaude Opus 5.5 d2d250e426 Render bot- and user-written markdown everywhere instead of raw text
TaskMarkdown becomes the shared MarkdownText (with a boxed, scrolling
variant). Proposal briefs, runbooks and prompts, card reasons and
research, plan goals and steps, questions, a hook's brief and the bot
panel's instructions and memory now render through it; code-like values
stay word for word.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:06 +01:00
tbenandClaude Opus 5.5 a569483456 Show the absolute folder a hook's runner starts in
runner_dir is relative to the bot's folder, not a run's ~, and a bare
"whatsapp" led a bot to point its runner at a folder that never
existed. The proposal card, list_hooks and propose_hook now give the
full path (hookRunnerStartPath, resolved like syncHookRunners), and the
form's help text explains the difference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:06 +01:00
tbenandClaude Opus 5.5 ef0237ecf0 Bump version to 0.28.19
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:25:57 +01:00
tbenandClaude Opus 5.5 02c49a3c9b Show why a hook's runner check failed, to the user and to the bot
The hook row and modal name the failure and when the runner was last
checked, and list_hooks describes the runner, its folder (inside the
bot's folder, not ~) and a failed check, pointing at propose_hook rather
than a process started by hand. Also reword Run silently: every hook has
its own thread, the setting is whether a run takes the conversation over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:25:57 +01:00
tbenandClaude Opus 5.5 f7ac9dbb08 Bump version to 0.28.18
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 05:06:13 +01:00
tbenandClaude Opus 5.5 a8e2c891a4 List the whole crew in the coordinator's Crew tab on a workspace page
The tab read the page's crew, which in a workspace is only that
workspace's bots, so a bot needing the user elsewhere went unlisted.
In a workspace it now reads the whole crew itself (useWholeCrew) and
keeps it current from face pushes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 05:03:10 +01:00
tbenandClaude Opus 5.5 8a75bb2a43 Open a session of its own for each started task hand-over, with the result reported back
A started hand-over (delegate_task with a new brief, or a task handed over with
start: true) used to queue its run in whatever session the target bot was on.
It now goes through startHandOverRun: a new session titled from the work, and,
when a bot handed it over, a bot_asks row of kind hand_over (no gate, the
user's quote is the say-so). The target gets the back bar, update_requester
and answer_requester, and its report goes back to and wakes the bot that
handed it over, as a crew request's answer does. Hand-overs don't count
toward the open-request cap, aren't stopped with the run that handed them
over, and show the task's own working row. The thread no longer calls a
hand-over's opening brief unanswered while its task is queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:56:40 +01:00
tbenandClaude Opus 5.5 f98b9391b0 Archive a consistent database snapshot instead of the live file in data backups
tar exited 1 with "./db/cobble: file changed as we read it" on every
production export. The database now goes in as a VACUUM INTO copy, the
live file and its journal are left out, and tar's exit 1 (a file changed
mid-read, archive still whole) counts as success.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:24:48 +01:00
tbenandClaude Opus 5.5 9cc7359334 Add a Crew tab to the coordinator's panel linking bots that need you to their chat
Faces now record the workspace of the job that set them
(bot_user_faces.workspace_id), so each worker that needs the user or is
working links to the right chat: its workspace conversation or its own.
Existing faces are placed at boot from each bot's latest job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:11:59 +01:00
tbenandClaude Opus 5.5 05d8f9e9da Show the bot's id in its panel header
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:31:52 +01:00
tbenandClaude Opus 5.5 a9fe487cbd Bump version to 0.28.17
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:04:26 +01:00
tbenandClaude Opus 5.5 435e080c06 Fix plan last steps, task hand-offs, card retries and failure notices from production
- A plan's last step ends with its report alone: the review no longer asks
  for a "Finish the plan" card that contradicted complete_plan_step.
- Retry on a failed plan step resumes the plan and re-runs that step.
- A task run handing work on is no longer refused against its own job.
- "handed to [bot:N]" status lines no longer read as work under way.
- A refused card gets its own note, keeps the message written beside it,
  and gets one more turn once it goes up; ask_user reads {label} options
  and JSON-string questions.
- Failure notices name the closing failure instead of blaming the review.
- A reply claiming the plan is over while the record disagrees is sent back.
- A provider's content-filter refusal fails the run at once with a clear
  message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:04:26 +01:00
tben 037119c1df Bump version to 0.28.16
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-27 07:22:55 +01:00
tben b37539f0c4 Inject open tasks and the conversation plan into every run, add paused tasks, and let bots pause plans 2026-11-27 07:22:55 +01:00
tben 1660857a3c Bump version to 0.28.15
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 15:34:39 +01:00
tben ccbd3efddf Let the composer's slash commands reach everything the header menu offers 2026-11-26 15:34:39 +01:00
tben 15d4f85e14 Bump version to 0.28.14
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 14:29:11 +01:00
tben 39055f8028 Let a bot send a late answer back on an ended crew request 2026-11-26 14:27:45 +01:00
tben 87be48ffb5 Relay a crew request's ack and late results, and stop only the runs the user stopped 2026-11-26 13:30:16 +01:00
tben 7bc9ab93ad Bump version to 0.28.13
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 09:39:18 +01:00
tben 0eee6781c4 Tell a refused card from a failed send, and stop losing what a run did
The harness audit's tier 1 and tier 2, from the Model Tester's runs.

A card the tool refused is not send_reply failing. runTextLoop stamped
replyClosingFailedNote whenever any closing call failed, so job 699 spent three
turns re-drafting an answer that had already shipped, beside a trace that blamed
the wrong tool. It now splits the failures: a refused card gets a new
replyCardFailedNote naming the card, and only a failed send_reply gets the old
note. suggest_next_steps states its caps in the schema (the 120-character step
limit it enforces), the wrap-up saving turn is traced, and the closing slice no
longer reads the whole run's tool history when a turn called nothing.

Providers tell the truth now: an error body carried by a 200 goes through
toHarnessError, so an oversized request is fatal with the context-window advice
and a dead key benches the provider (52 such rows, one task limping for 18
minutes); a 405 benches like a 404; a crash in an adapter writes a failed-call
row before it goes up; the error reported is a provider-wide or fatal one, not
simply the last. A pinned model that can't serve the harness says so instead of
answering on an automatic pick, an image or video call with references hands
over to a generation model only while that harness's fallback is on, and an
empty answer from a thinking model is named for what it was.

Nothing is promised that a run doesn't carry: ComputerFilesNote and the chat
take-over line stay out of a run without a computer, TaskRunNote names ask_user
only to a run that may ask, load_tools says when a name is already inline, and
an unknown browser tool is told its slug when the run has one. An interim crew
update goes through the run's redaction: it lands in another bot's conversation,
where a raw env value would sit forever.

The queue and plans hold their record: a job locks with the pid as well as its
family, so two processes can no longer renew each other's locks (startup still
releases the family's rows); stopping or cancelling a plan's step pauses it the
way a failure does; a step keeps the run that finished it, so a step whose report
never went out is put back instead of skipped; a job that failed, retried and
then answered no longer reads completed beside its old error; the stopped line
follows a conversation that carried on; and a finished row with no timestamp is
pruned at all. The model picker warns when a text model's capabilities were
guessed from its name, which is how a vision model was pinned as a worker's text
model and every reply ended as a draft.
2026-11-26 09:38:35 +01:00
tben 01d6cffa8d Bump version to 0.28.12
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 06:04:31 +01:00
tben 8897f0b23f Let a knowledgebase document be read, and open its original
Clicking a document reads it over the list: written text as markdown, a file's extracted text as it is, cut at KnowledgebaseTextMaxChars and flagged when there is more. A file document's Open original loads its uploaded media row in the existing file preview, which crew managers now reach through grabKnowledgebaseDocumentMedia.

The bot composer's knowledgebase rows get the same documents list, read-only.
2026-11-26 06:04:26 +01:00
tben 2dc6972de4 Bump version to 0.28.11
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 14:07:34 +01:00
tben 82fa223691 Refuse a carry while the user's latest message is unanswered 2026-11-25 14:07:34 +01:00
209 changed files with 5183 additions and 828 deletions
+17 -14
View File
File diff suppressed because one or more lines are too long
+18 -1
View File
@@ -52,7 +52,7 @@ import {
CustomToolKinds,
CustomToolStatuses,
} from "@/src/dict/custom-tool-dict";
import { AskStatuses } from "@/src/dict/ask-dict";
import { AskKinds, AskStatuses } from "@/src/dict/ask-dict";
import {
TaskAuthors,
TaskMediaKinds,
@@ -356,6 +356,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The ask the asking bot was itself working on when it asked (a nested request). Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "requester_job_id",
fieldDescription: `The asking bot's run that made the request, so stopping that run ends this request and no other ask from the same conversation. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "title",
fieldDescription: `A short label for the request`,
@@ -397,6 +402,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The asked bot's session before the request opened one of its own, so its conversation can offer the way back. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "kind",
fieldDescription: `What opened it: \`ask\` (ask_bot, through the coordinator's gate) or \`hand_over\` (a task handed over and started on the user's own words, so no gate)`,
dataType: "TEXT",
options: AskKinds.map((k) => k.value),
defaultValue: "ask",
},
],
indexes: [
{
@@ -2670,6 +2682,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Short status sentence, e.g. "Waiting on you"`,
dataType: "TEXT",
},
{
fieldName: "workspace_id",
fieldDescription: `The workspace of the conversation whose job set this face, null for the bot's own chat (or a face no job set). Not a foreign key: it only says which chat the coordinator's Crew list links to`,
dataType: "INTEGER",
},
],
uniqueConstraints: [
{
+13 -1
View File
@@ -303,6 +303,10 @@ export type BUN_SQLITE_COBBLE_BOT_ASKS = {
* The ask the asking bot was itself working on when it asked (a nested request). Not a foreign key
*/
parent_ask_id?: number | "";
/**
* The asking bot's run that made the request, so stopping that run ends this request and no other ask from the same conversation. Not a foreign key
*/
requester_job_id?: number | "";
/**
* A short label for the request
*/
@@ -332,6 +336,10 @@ export type BUN_SQLITE_COBBLE_BOT_ASKS = {
* The asked bot's session before the request opened one of its own, so its conversation can offer the way back. Not a foreign key
*/
previous_session_id?: number | "";
/**
* What opened it: `ask` (ask_bot, through the coordinator's gate) or `hand_over` (a task handed over and started on the user's own words, so no gate)
*/
kind?: "ask" | "hand_over" | "";
}
export type BUN_SQLITE_COBBLE_BOT_SESSIONS = {
@@ -579,7 +587,7 @@ export type BUN_SQLITE_COBBLE_TASKS = {
* The brief (markdown): what to do, where, and how you'll know it's done
*/
description?: string;
status?: "todo" | "doing" | "blocked" | "done" | "cancelled" | "";
status?: "todo" | "doing" | "blocked" | "paused" | "done" | "cancelled" | "";
/**
* What the user has to do to unblock it; only meaningful while `status` is blocked
*/
@@ -1679,6 +1687,10 @@ export type BUN_SQLITE_COBBLE_BOT_USER_FACES = {
* Short status sentence, e.g. "Waiting on you"
*/
status_line?: string;
/**
* The workspace of the conversation whose job set this face, null for the bot's own chat (or a face no job set). Not a foreign key: it only says which chat the coordinator's Crew list links to
*/
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA = {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.10",
"version": "0.28.20",
"module": "index.ts",
"type": "module",
"private": true,
+3 -2
View File
@@ -9,7 +9,8 @@ import processBotJob from "./process-bot-job";
import reportLostBotJobs from "./report-lost-bot-jobs";
import { setBotsQueueWaker } from "./wake-bots-queue";
const worker = AppData.BotQueueWorker;
/** Per-process lock id: the family plus this process's pid. */
const worker = `${AppData.BotQueueWorker}-${process.pid}`;
const running = { task: 0, reply: 0 };
let polling = false;
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -41,7 +42,7 @@ export default async function botsQueue() {
* it fails, polling still starts, and the lock timeout releases them.
*/
try {
const released = await releaseWorkerBotJobs({ worker });
const released = await releaseWorkerBotJobs({ family: AppData.BotQueueWorker });
if (released) {
bunext.bunextLog.info(`Bots queue: released ${released} cut-off job(s)`);
@@ -0,0 +1,47 @@
import { describe, expect, test } from "bun:test";
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
import planFinishedClaimNote from "./plan-finished-claim-note";
const paused = { id: 2, status: "paused", current_step: 2, total_steps: 3 };
const active_last = { id: 2, status: "active", current_step: 2, total_steps: 3 };
describe("planFinishedClaimNote", () => {
test("a paused plan claimed as finished is sent back (job 810)", () => {
const note = planFinishedClaimNote({
plan: paused,
text: "**All tasks complete.** Plan #2 finished.",
tool_uses: [{ name: "complete_plan_step", ok: false }],
});
expect(note).toContain("Plan #2 is over");
expect(note).toContain("paused, at step 3 of 3");
expect(note).toContain("update_plan");
});
test("the run that ticked the last step may say the plan is finished", () => {
expect(
planFinishedClaimNote({
plan: active_last,
text: "Plan #2 is now complete.",
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toBeNull();
});
test("a step's completion is not the plan's", () => {
expect(
planFinishedClaimNote({ plan: paused, text: "Plan #2 Step 3 (cross-task wrap-up) complete.", tool_uses: [] }),
).toBeNull();
});
test("a message that claims nothing about the plan, or a run with no plan, passes", () => {
expect(planFinishedClaimNote({ plan: paused, text: "Task #8 is done.", tool_uses: [] })).toBeNull();
expect(planFinishedClaimNote({ plan: null, text: "Plan #2 finished.", tool_uses: [] })).toBeNull();
});
test("the fault note promises no work of its own", () => {
const note = planFinishedClaimNote({ plan: paused, text: "The plan is finished.", tool_uses: [] })!;
expect(claimsWorkUnderWay({ text: note })).toBe(false);
});
});
@@ -0,0 +1,50 @@
import type { HarnessToolUse } from "@/src/harness/types";
type Params = {
/**
* The plan this run sits in, as it stood when the run began: the one it
* was queued for, or the one open in its conversation.
*/
plan: { id: number; status: string; current_step: number | null; total_steps: number } | null;
text: string;
tool_uses: HarnessToolUse[];
};
/**
* "Plan #2 finished", "the plan is now complete": the plan itself claimed
* as over, never one of its steps ("Plan #2 Step 3 complete").
*/
const FinishedClaim =
/\b(?:the\s+)?plan(?:\s*#\d+)?(?:\s+(?:is|has\s+been|was|marked))?(?:\s+now)?\s+(?:finished|completed?|done)\b/i;
/**
* Sends back a reply that says the plan is over when the app's record says
* it isn't. Job 810 wrote "All tasks complete. Plan #2 finished." right
* after `complete_plan_step` refused it ("Plan #2 is paused"), and the
* conversation said the plan was done while its card said paused.
*
* A run that finished the plan's last step itself has made the claim true.
* A plan already done is not open, so it never reaches here.
*/
export default function planFinishedClaimNote({ plan, text, tool_uses }: Params) {
if (!plan || plan.status == "done") return null;
if (!FinishedClaim.test(text.replace(/[*_`]/g, ""))) return null;
const ticked = tool_uses.some((use) => use.ok && use.name == "complete_plan_step");
const on_last = plan.current_step != null && plan.current_step + 1 >= plan.total_steps;
if (ticked && on_last && plan.status == "active") return null;
const where =
plan.current_step == null
? `${plan.status}`
: `${plan.status}, at step ${plan.current_step + 1} of ${plan.total_steps}`;
const fix =
plan.status == "paused"
? `To finish it, the user resumes it on its card (or asks you to, and you use update_plan with status "active"), and its step is then worked and ticked with complete_plan_step.`
: `Finish its current step with complete_plan_step first, or write where it really stands.`;
return `Your message says Plan #${plan.id} is over, but the app's record has it ${where}. Write where the plan really stands. ${fix}`;
}
+35 -8
View File
@@ -29,16 +29,25 @@ describe("planStepReviewNote", () => {
expect(note({ uses })).toBeNull();
});
test("the last step's card offers to finish the plan", () => {
test("ticking the last step finishes the plan, so its report needs no card (jobs 809, 811)", () => {
const last = { ...plan, current_step: 2 };
const ticked = [{ name: "complete_plan_step", ok: true }];
expect(
planStepReviewNote({
plan: last,
on_step: true,
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toContain("Finish the plan");
expect(planStepReviewNote({ plan: last, on_step: true, tool_uses: ticked, status: "done" })).toBeNull();
expect(planStepReviewNote({ plan: last, on_step: false, tool_uses: ticked, status: "done" })).toBeNull();
});
test("the last step left unfinished is sent back to finish it, without asking for a card", () => {
const fault = planStepReviewNote({
plan: { ...plan, current_step: 2 },
on_step: true,
tool_uses: [{ name: "write_file", ok: true }],
});
expect(fault).toContain("its last step");
expect(fault).toContain("complete_plan_step");
expect(fault).toContain("no card goes with this report");
expect(fault).not.toContain("Finish the plan");
});
test("a failed finish does not pass", () => {
@@ -60,6 +69,24 @@ describe("planStepReviewNote", () => {
expect(note({ on_step: false, uses: [{ name: "write_file", ok: true }] })).toBeNull();
});
test("an ordinary reply that ticked a step without its card is sent back for the card", () => {
const fault = note({ on_step: false, uses: [{ name: "complete_plan_step", ok: true }] });
expect(fault).toContain("finished step 2 of Plan #3");
expect(fault).toContain("ask_user");
expect(fault).toContain("Continue to step 3");
expect(
note({
on_step: false,
uses: [
{ name: "complete_plan_step", ok: true },
{ name: "ask_user", ok: true },
],
}),
).toBeNull();
});
test("a plan with no step left is left alone", () => {
expect(planStepReviewNote({ plan: { ...plan, current_step: null }, on_step: true, tool_uses: [] })).toBeNull();
});
+29 -5
View File
@@ -11,7 +11,8 @@ type PlanStep = {
type Params = {
/**
* The plan the run works, when it was queued for one of its steps.
* The plan this run sits in: the one it was queued for, or the one
* open in its conversation.
*/
plan: PlanStep | null;
/**
@@ -34,10 +35,17 @@ const EndingTools = ["ask_user", "update_plan", ...PlanWorkStartingTools];
* Checks a plan step's reply before it goes out: the step ends on a card
* whose first option continues the plan, so the plan moves on from the card
* in front of the user, never from the bot remembering to ask. A reply that
* reports the step and ends is sent back.
* reports the step and ends is sent back. It holds for an ordinary reply
* too, once it has ticked a step with `complete_plan_step`: a step marked
* done with no card under its report leaves the plan with nothing to move
* on from.
*/
export default function planStepReviewNote({ plan, on_step, tool_uses, status }: Params) {
if (!on_step || !plan || plan.current_step == null) return null;
if (!plan || plan.current_step == null) return null;
const ticked = tool_uses.some((use) => use.ok && use.name == "complete_plan_step");
if (!on_step && !ticked) return null;
/**
* A reply that says what stopped it, or hands the work to a run of its
@@ -53,5 +61,21 @@ export default function planStepReviewNote({ plan, on_step, tool_uses, status }:
const next = step + 1;
const last_step = next > plan.total_steps;
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`;
}
/**
* Ticking the last step finishes the plan (`completeBotPlanStep` sets it
* `done`), so there is nothing left for a card to move on to: the report
* alone ends it, as `complete_plan_step` tells the bot. Asking for a
* "Finish the plan" card there contradicted that answer, and every
* rewrite was refused until the job failed and the finished plan was
* paused again (jobs 809 and 811, Plan #2).
*/
if (last_step && ticked) return null;
if (last_step) {
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}"), its last step, and ended without finishing it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. That finishes the plan, so no card goes with this report. If it needs the user for something first, ask that with ask_user and say the plan is holding at this step. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it.`;
}
return on_step
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "Continue to step ${next}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "Continue to step ${next}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
}
+5 -2
View File
@@ -146,10 +146,13 @@ export default async function processBotJob({
* it to idle, and a late `working` or `asleep` would push over that and
* leave a bot that shows work with nothing behind it.
*/
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id">) => {
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id" | "workspace_id">) => {
if (!user_id || unattended || controller.signal.aborted) return;
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
await pushBotNotice({
bot_id,
bot: await setBotFace({ bot_id, user_id, workspace_id: job.workspace_id || null, ...face }),
});
};
/**
+93 -12
View File
@@ -31,8 +31,10 @@ import {
PlanActiveNote,
PlanPausedNote,
PlanModeNote,
OpenTasksNote,
} from "@/src/data/harness-prompts";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
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";
@@ -57,6 +59,7 @@ import openBotExtensions from "@/src/harness/tools/extensions/open-bot-extension
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 grabOpenAskBySession from "@/src/functions/backend/db/asks/grab-open-ask-by-session";
import grabEndedAskBySession from "@/src/functions/backend/db/asks/grab-ended-ask-by-session";
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";
@@ -83,12 +86,14 @@ import stripAppRecords from "@/src/utils/strip-app-records";
import hasUnansweredMessage from "./has-unanswered-message";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import planFinishedClaimNote from "./plan-finished-claim-note";
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
import answerRequesterTool from "@/src/harness/tools/bot/answer-requester-tool";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
@@ -196,6 +201,13 @@ export default async function runBotReply({
: await grabSessionPlan({ session_id });
const plan = plan_row ? toBotPlanView({ row: plan_row }) : null;
/**
* Whether this reply finished a plan step with `complete_plan_step`,
* however it was queued. The message then carries the plan's card, and
* the card it ends on is what starts the next step.
*/
let plan_ticked = false;
/**
* A step job queued before the user paused (or dropped) the plan has
* nothing to do: it ends without a word, rather than reporting a step
@@ -362,6 +374,23 @@ export default async function runBotReply({
* workspace's admin.
*/
const powers = await grabBotRunPowers({ bot_id: bot.id, workspace_id });
/**
* The tasks this run could be working, injected into its prompt so an
* open task is never forgotten (a production bot left a Doing task
* open for months until the user said "close that task"). Paused ones
* are the user's to park: the bot reads them with `list_tasks`, they
* just don't ask for attention.
*/
const open_tasks = (
await grabTasks({
bot_id: bot.id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
workspace_id,
open_only: true,
limit: AppData.TaskDigestCount,
})
).filter((task) => task.status != "paused");
/**
* A crew request's session and a hook's run are hidden: nobody follows
* them.
@@ -394,6 +423,17 @@ export default async function runBotReply({
* back to the bot that asked while the work is still open).
*/
const ask_id_for_updates = job_ask_id || (open_ask?.id ? Number(open_ask.id) : 0);
/**
* The request this conversation answered and that has since ended: the
* one place a late or corrected answer can go back from, so the bot
* doesn't open a fresh request through the gate for what belongs to
* that one (an ended request's answer session, once the user resumes
* it, had no way to finish back).
*/
const ended_ask =
!ask_id_for_updates && session_id
? await grabEndedAskBySession({ session_id: Number(session_id), user_id }).catch(() => null)
: null;
let led: WorkspaceAdminTools | null = null;
const tools = await grabBotChatTools({
@@ -547,6 +587,17 @@ export default async function runBotReply({
user_id,
session_id: Number(session_id),
ask_id: ask_id_for_updates,
redact: redact_reply,
}),
]
: []),
...(ended_ask?.id && Number(ended_ask.target_bot_id) == Number(bot.id)
? [
answerRequesterTool({
user_id,
bot_id: bot.id,
ask_id: Number(ended_ask.id),
redact: redact_reply,
}),
]
: []),
@@ -594,11 +645,13 @@ export default async function runBotReply({
*/
plan_mode,
/**
* The plan whose step this reply works, when it does:
* the card it ends on is the plan's next move
* (`postBotQuestionAnswers`).
* The plan whose step this reply works: the card it ends
* on is the plan's next move
* (`postBotQuestionAnswers`). Read when the card is put
* up, so a reply that finishes a step as it goes links
* the card to that plan.
*/
plan_id: on_plan_step ? plan?.id : null,
plan_id: () => (on_plan_step || plan_ticked ? plan?.id ?? null : null),
onAsk: ({ ref }) => proposals.push(ref),
redact: redact_reply,
}),
@@ -618,7 +671,24 @@ export default async function runBotReply({
bot_id: bot.id,
session_id,
workspace_id,
job_id: job.id,
on_step: on_plan_step,
/**
* An ordinary reply may work and tick the plan's current
* step when the message asked for exactly that work, and
* may park or pick up the plan when the user said so. A
* paused plan gets the same tools so it can resume and
* work the step in one reply; finishing a step of a plan
* that is still paused is refused at the row. Not in
* Plan mode: nothing writes there.
*/
can_complete:
!on_plan_step &&
!plan_mode &&
(plan?.status == "active" || plan?.status == "paused"),
onCompleted: () => {
plan_ticked = true;
},
/**
* A plan nobody approved yet needs the user, so
* it goes with the refs that set `needs_you`: the
@@ -661,7 +731,10 @@ export default async function runBotReply({
reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id, plan_mode })({ text, tool_uses, status }).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
return (
planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status }) ??
planFinishedClaimNote({ plan, text, tool_uses })
);
});
const result = await runTextLoop({
@@ -669,24 +742,32 @@ export default async function runBotReply({
prompt,
carry_over,
long_session_note,
chatReplyNote({ bot_id: bot.id }),
chatReplyNote({ bot_id: bot.id, can_take_over: computers.length > 0 }),
plan_mode ? PlanModeNote : "",
is_retry ? RerunReplyNote : "",
retry_failure ? RetryFailureNote({ reason: retry_failure.reason }) : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: computers.length > 0 }),
/**
* Only with a computer: the note is about the run's folders and
* browser there, and a reply without one has neither tool.
*/
computers.length
? ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: true })
: "",
TasksNote,
TaskReminderNote,
open_tasks.length
? `${OpenTasksNote({ tasks: open_tasks })}\n\n${TaskReminderNote}`
: "",
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
RequestScopeNote({ can_ask: Boolean(attended) && !asked }),
attended && !asked ? PlansNote : "",
attended && !asked && plan?.status == "planned" ? PlanWaitingNote({ plan }) : "",
attended && !asked && plan?.status == "paused" ? PlanPausedNote({ plan }) : "",
attended && !asked && plan?.status == "planned" ? PlanWaitingNote({ plan, plan_mode }) : "",
attended && !asked && plan?.status == "paused" ? PlanPausedNote({ plan, plan_mode }) : "",
attended && !asked && plan?.status == "active"
? on_plan_step
? PlanStepNote({ plan })
: PlanActiveNote({ plan })
: PlanActiveNote({ plan, plan_mode })
: "",
attended ? QuestionsNote : "",
SecretsNote,
@@ -818,7 +899,7 @@ export default async function runBotReply({
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_message_id: message_plan_id ?? (on_plan_step ? plan?.id : undefined),
plan_message_id: message_plan_id ?? ((on_plan_step || plan_ticked) ? 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
+114 -18
View File
@@ -29,6 +29,9 @@ import {
taskPlanNote,
wrapUpWorktreeNote,
PlanStepNote,
PlanActiveNote,
PlanPausedNote,
OpenTasksNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -39,7 +42,9 @@ import {
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import grabSessionPlan from "@/src/functions/backend/db/bot-plans/grab-session-plan";
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import runTextLoop from "@/src/harness/text/run-text-loop";
import redactTrace from "@/src/harness/trace/redact-trace";
@@ -74,6 +79,8 @@ import grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools"
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
import reportRunFailedTool from "@/src/harness/tools/bot/report-run-failed-tool";
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
import answerRequesterTool from "@/src/harness/tools/bot/answer-requester-tool";
import grabEndedAskBySession from "@/src/functions/backend/db/asks/grab-ended-ask-by-session";
import answerInstallRequestTool from "@/src/harness/tools/bot/answer-install-request-tool";
import requestInstallTool from "@/src/harness/tools/computer/request-install-tool";
import worktreeSummary from "@/src/harness/tools/computer/worktree-summary";
@@ -89,6 +96,7 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
import BotJobFatalError from "./bot-job-fatal-error";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import planFinishedClaimNote from "./plan-finished-claim-note";
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -283,11 +291,58 @@ export default async function runBotTask({
* card to put up and reports as usual.
*/
const on_plan_step = can_ask && Boolean(plan && plan.status == "active" && plan.current_step != null);
/**
* The conversation's open plan, when this run is not a step's own
* work: a long task run is where a bot loses the plan (it used to
* see no plan at all unless the app queued it for a step). An
* attended run that is asked for the plan's current step may work
* and tick it like a step's own run; nothing here starts a step on
* its own.
*/
const session_plan_row =
!Number(params.plan_id) && session_id && can_ask
? await grabSessionPlan({ session_id: Number(session_id) }).catch(() => null)
: null;
const session_plan =
session_plan_row && (session_plan_row.status == "active" || session_plan_row.status == "paused")
? toBotPlanView({ row: session_plan_row })
: null;
let ticked_plan_id: number | null = null;
const can_complete_plan_step =
!on_plan_step &&
can_ask &&
(session_plan?.status == "active" || session_plan?.status == "paused");
/**
* The tasks this run could be working, injected into its prompt so
* an open task is never forgotten. Paused ones are the user's to
* park: the bot reads them with `list_tasks`, they just don't ask
* for attention.
*/
const open_tasks = (
await grabTasks({
bot_id: bot.id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
workspace_id,
open_only: true,
limit: AppData.TaskDigestCount,
})
).filter((task) => task.status != "paused");
/**
* The coordinator weighing a worker's install request
* (`request_install`): it answers it with answer_install_request.
*/
const install_request_id = powers.is_coordinator ? Number(params.install_request_id) || 0 : 0;
/**
* The request this run's session answered, once it has ended (and
* this run isn't part of one): so a task the user asked for here
* can send its finished answer back to the bot that asked, instead
* of opening a fresh request the gate reads as a new handoff.
*/
const ended_ask =
!Number(params.ask_id) && session_id
? await grabEndedAskBySession({ session_id: Number(session_id), user_id }).catch(() => null)
: null;
let failure = null as string | null;
/**
@@ -326,23 +381,32 @@ export default async function runBotTask({
scopes,
hooked,
onTask: ({ task_id }) => task_ids.push(task_id),
job_id: job.id,
})),
...admin_tools,
/**
* The plan's own step: it finishes the step, or says the plan
* is wrong. Writing or cancelling a plan is a reply's job, never
* a run's, so those stay out.
* The plan this run sits in. Writing or cancelling a plan stays
* a reply's job. A step's own run finishes its step; an
* attended run that isn't one may tick a step only when the
* message asked for that step's work, and then owes the plan
* its card.
*/
...(on_plan_step
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id: session_id!,
workspace_id,
on_step: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
...(on_plan_step || can_complete_plan_step
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id: session_id!,
workspace_id,
job_id: job.id,
on_step: on_plan_step,
can_complete: can_complete_plan_step,
writes_plan: false,
onCompleted: ({ plan_id }) => {
ticked_plan_id = plan_id;
},
onPlan: ({ ref }) => shown.push(ref),
})
: []),
/**
* Part of a crew request (`start_task`/`delegate_task` in an
* answer session): the bot can send the asker an interim word
@@ -354,6 +418,17 @@ export default async function runBotTask({
user_id,
session_id: Number(session_id),
ask_id: Number(params.ask_id),
redact: redact_text,
}),
]
: []),
...(ended_ask?.id && Number(ended_ask.target_bot_id) == Number(bot.id)
? [
answerRequesterTool({
user_id,
bot_id: bot.id,
ask_id: Number(ended_ask.id),
redact: redact_text,
}),
]
: []),
@@ -429,7 +504,7 @@ export default async function runBotTask({
session_id,
workspace_id,
in_task: true,
plan_id: on_plan_step ? plan?.id : null,
plan_id: () => (on_plan_step ? plan?.id ?? null : ticked_plan_id),
onAsk: ({ ref }) => take_overs.push(ref),
redact: redact_text,
}),
@@ -638,16 +713,33 @@ export default async function runBotTask({
const system = [
prompt,
carry_over,
TaskRunNote,
TaskRunNote({ can_ask }),
steps_note,
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
Number(params.ask_id) ? AskTaskRunNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
/**
* Only when the run has a computer: the note describes its folders
* and its browser, and a run with none has no computer tools at all
* (the closing note below is what tells it so).
*/
computer ? ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }) : "",
named_files_note,
TasksNote,
open_tasks.length ? OpenTasksNote({ tasks: open_tasks }) : "",
/**
* The plan this run sits in when it isn't a step's own work:
* an attended run may work that plan's current step when the
* message asked for it, and must tick it and end on the card
* like the run the app queued for the step.
*/
!on_plan_step && session_plan
? session_plan.status == "active"
? PlanActiveNote({ plan: session_plan })
: PlanPausedNote({ plan: session_plan })
: "",
/**
* The plan's step this run works: it finishes that step, or asks
* the user on the card, and the report says which. This is the
@@ -756,6 +848,7 @@ export default async function runBotTask({
session_id,
computers,
message_id: job.message_id || undefined,
job_id: job.id,
run_kind: browser_run_kind,
plan_id: on_plan_step ? plan?.id : null,
}),
@@ -824,7 +917,10 @@ export default async function runBotTask({
}).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
return (
planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status }) ??
planFinishedClaimNote({ plan: plan ?? session_plan, text, tool_uses })
);
}),
/**
* A report goes out only through `send_reply`, so it can't say
@@ -895,7 +991,7 @@ export default async function runBotTask({
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_message_id: on_plan_step ? plan?.id : undefined,
plan_message_id: on_plan_step ? plan?.id : ticked_plan_id ?? undefined,
/**
* The wrap up was announced (`steps` counts its turns), so the
* run never got to the end of the work it was given.
+34 -1
View File
@@ -1,5 +1,16 @@
import { describe, expect, test } from "bun:test";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import {
closingNoTextNote,
closingToolGoneNote,
replyCardFailedNote,
replyCardOnlyFailedNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
} from "@/src/data/harness-prompts";
import planStepReviewNote from "./plan-step-review";
import unsentAnswerMessage from "./unsent-answer-message";
/**
@@ -29,6 +40,28 @@ describe("unsentAnswerMessage", () => {
);
});
test("closing failures name the call that failed, never the review (jobs 680, 694, 700)", () => {
expect(unsentAnswerMessage({ note: replyClosingFailedNote })).toContain("call that sends the message");
expect(unsentAnswerMessage({ note: replyClosingRequiredNote })).toContain("never sent the message");
expect(unsentAnswerMessage({ note: replyClosingMixedNote })).toContain("other work");
expect(unsentAnswerMessage({ note: replyCardOnlyFailedNote({ tools: ["ask_user"] }) })).toContain("card");
expect(unsentAnswerMessage({ note: replyCardFailedNote({ tools: ["suggest_next_steps"] }) })).toContain("card");
for (const note of [replyClosingFailedNote, replyClosingRequiredNote, replyCardOnlyFailedNote({ tools: ["ask_user"] })]) {
expect(unsentAnswerMessage({ note })).not.toContain("app's record");
}
});
test("a plan step that ended wrong says so", () => {
const note = planStepReviewNote({
plan: { id: 2, title: "Finish", current_step: 0, total_steps: 3 },
on_step: true,
tool_uses: [],
});
expect(unsentAnswerMessage({ note: note! })).toContain("plan step");
});
test("a check against the record keeps saying so", () => {
expect(unsentAnswerMessage({ note: "It names task #16, and no such task exists." })).toBe(
`The answer didn't hold up against the app's record, so it wasn't sent.`,
+51 -4
View File
@@ -1,4 +1,14 @@
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import {
closingFailedNote,
closingMixedNote,
closingNoTextNote,
closingToolGoneNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
} from "@/src/data/harness-prompts";
type Params = {
/**
@@ -9,8 +19,21 @@ type Params = {
};
/**
* The failure notice a run that never sent its answer leaves. The note
* the loop returned picks the line, so an empty close is not called a lie.
* The openings of the notes built per call (`replyCardFailedNote`,
* `replyCardOnlyFailedNote`, `planStepReviewNote`, `unfinishedAnswerText`):
* their tails name tools or steps, so they are told apart by how they start.
*/
const CardRefusedOpenings = ["The card was not put up", "send_reply went through and your message is kept"];
const PlanStepOpenings = ["This reply works step", "This reply finished step"];
const UnfinishedOpening = "The message stops ";
/**
* The failure notice a run that never sent its answer leaves. The note the
* loop returned picks the line, so a run that failed for its own mechanics
* is never called a lie: "didn't hold up against the app's record" is only
* for an answer the review actually checked and refused. Before, every
* closing failure fell through to that line (jobs 680, 694, 700), and the
* user read five failures as a bot caught out when none was.
*/
export default function unsentAnswerMessage({ note }: Params) {
if (note === replyNoTextNote) {
@@ -29,5 +52,29 @@ export default function unsentAnswerMessage({ note }: Params) {
return `The run's last turn called a tool it no longer had, so its message wasn't sent.`;
}
if (note === replyClosingFailedNote) {
return `The call that sends the message kept being refused, so the message wasn't sent.`;
}
if (note === replyClosingRequiredNote) {
return `The reply put its card up but never sent the message with it, so it wasn't sent.`;
}
if (note === replyClosingMixedNote || note === closingMixedNote) {
return `The reply kept doing other work in the turn meant to send its message, so it wasn't sent.`;
}
if (note === closingFailedNote || CardRefusedOpenings.some((opening) => note.startsWith(opening))) {
return `The card under the message kept being refused, so the message wasn't sent.`;
}
if (PlanStepOpenings.some((opening) => note.startsWith(opening))) {
return `The reply didn't end its plan step the way the plan needs, so it wasn't sent.`;
}
if (note.startsWith(UnfinishedOpening)) {
return `The message stopped part-way through (an unclosed table, list or code block), so it wasn't sent.`;
}
return `The answer didn't hold up against the app's record, so it wasn't sent.`;
}
}
@@ -1,4 +1,5 @@
import ContinueSessionButton from "./continue-session-button";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import useShownSession from "@/src/hooks/use-shown-session";
import conversationHref from "@/src/utils/conversation-href";
import {
@@ -37,6 +38,8 @@ type Props = {
* Runs as it opens, e.g. closing the menu it was opened from.
*/
on_open?: () => void;
/** The composer command that opens this modal (`/sessions`). */
command?: string;
};
/**
@@ -52,8 +55,11 @@ export default function BotSessionsModal({
target,
target_wrapper_props,
on_open,
command,
}: Props) {
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const on_screen = useShownSession({ bot_id: Number(bot.id), workspace_id });
const sessions = useBotSessions({
bot_id: Number(bot.id),
+9 -18
View File
@@ -1,34 +1,25 @@
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import linkComputerRefs from "@/src/utils/link-computer-refs";
/**
* Kept module-level: a new array on every render makes `react-markdown`
* parse the message again.
*/
const RemarkPlugins = [remarkGfm];
import MarkdownText from "./markdown-text";
type Props = {
label: string;
text: string;
/**
* Long text (a hook's brief): kept to a box that scrolls.
*/
boxed?: boolean;
};
/**
* What a hook call's run answered, rendered like a chat message (raw HTML
* never).
* Markdown about a hook under its label (what a call's run answered, the
* hook's brief), rendered like a chat message (raw HTML never).
*/
export default function HookCallAnswer({ label, text }: Props) {
export default function HookCallAnswer({ label, text, boxed }: Props) {
return (
<Stack className="w-full gap-0.5! items-stretch">
<Span className="text-[11px] leading-4 text-ink-secondary">{label}</Span>
<Stack className="w-full gap-2.5! items-start break-words">
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
</Stack>
<MarkdownText text={text} boxed={boxed} />
</Stack>
);
}
+11 -3
View File
@@ -11,7 +11,7 @@ import type { BotHookWithNames } from "@/src/types";
import conversationHref from "@/src/utils/conversation-href";
import hookRunnerState from "@/src/utils/hook-runner-state";
import relativeTime from "@/src/utils/relative-time";
import HookCallText from "./hook-call-text";
import HookCallAnswer from "./hook-call-answer";
import HookCalls from "./hook-calls";
import TaskFactRow from "./task-fact-row";
@@ -101,7 +101,15 @@ export default function HookDetailModal({ hook, can_manage = false, onClose, onE
<TaskFactRow label="Runner">
{runner.running
? `Up since ${relativeTime({ at: Number(hook.runner_started_at) || Date.now() })}`
: hook.runner_last_error || "Down"}
: "Down"}
</TaskFactRow>
{runner.error ? (
<TaskFactRow label="Check failed">{runner.error}</TaskFactRow>
) : null}
<TaskFactRow label="Last checked">
{hook.runner_checked_at
? relativeTime({ at: Number(hook.runner_checked_at) })
: "Not yet"}
</TaskFactRow>
{hook.runner_command ? (
<TaskFactRow label="Runner command">
@@ -130,7 +138,7 @@ export default function HookDetailModal({ hook, can_manage = false, onClose, onE
</TaskFactRow>
{hook.last_error ? <TaskFactRow label="Last error">{hook.last_error}</TaskFactRow> : null}
</Stack>
{hook.instructions ? <HookCallText label="Brief" text={hook.instructions} full /> : null}
{hook.instructions ? <HookCallAnswer label="Brief" text={hook.instructions} boxed /> : null}
{status ? <SettingsStatus status={status} /> : null}
<Row className="w-full gap-2! justify-end">
{can_manage && runner?.configured ? (
+2 -2
View File
@@ -289,7 +289,7 @@ export default function HookForm({
autoComplete="off"
placeholder="whatsapp"
defaultValue={hook?.runner_dir || ""}
info={`Where it starts, inside the bot's folder: "whatsapp" is the bot's whatsapp folder. Empty starts in the bot's folder itself.`}
info={`Where it starts, relative to the bot's folder (/home/cb-<bot>/workspace), not to a run's ~: "whatsapp" is /home/cb-<bot>/workspace/whatsapp, while a folder a bot made at ~/whatsapp is "users/<user>/whatsapp". Empty starts in the bot's folder itself.`}
onChange={(e) => setRunnerDir(e.target.value)}
/>
<Select
@@ -317,7 +317,7 @@ export default function HookForm({
) : null}
<Checkbox
title="Run silently"
label="Keep its runs in the hook's own thread: they never take over the conversation or notify me. Read them from the hook, or in the bot's sessions."
label="Run without taking over the conversation: its thread stays out of the rail, its runs don't notify me or change the bot's face. Unchecked, each run makes its thread the conversation's active session."
checked={silent}
changeHandler={setSilent}
labelProps={{ className: "w-full" }}
@@ -1,10 +1,10 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import TaskMarkdown from "./task-markdown";
import MarkdownText from "./markdown-text";
describe("TaskMarkdown", () => {
describe("MarkdownText", () => {
test("renders the markdown, not as written", () => {
const html = renderToString(<TaskMarkdown text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
const html = renderToString(<MarkdownText text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
expect(html).not.toContain("## Steps");
expect(html).not.toContain("**Check**");
@@ -13,7 +13,7 @@ describe("TaskMarkdown", () => {
});
test("opens links in a new tab, bare ones too", () => {
const html = renderToString(<TaskMarkdown text={"See [the docs](https://example.com) or https://example.org"} />);
const html = renderToString(<MarkdownText text={"See [the docs](https://example.com) or https://example.org"} />);
expect(html).toContain('href="https://example.com"');
expect(html).toContain('href="https://example.org"');
@@ -22,7 +22,7 @@ describe("TaskMarkdown", () => {
});
test("shows refs as chips", () => {
const html = renderToString(<TaskMarkdown text={"Ask [bot:2] about [task:20]."} />);
const html = renderToString(<MarkdownText text={"Ask [bot:2] about [task:20]."} />);
expect(html).not.toContain("[bot:2]");
expect(html).toContain("bot 2");
@@ -30,7 +30,7 @@ describe("TaskMarkdown", () => {
});
test("never renders raw HTML", () => {
const html = renderToString(<TaskMarkdown text={"<script>alert(1)</script> <b>hi</b>"} />);
const html = renderToString(<MarkdownText text={"<script>alert(1)</script> <b>hi</b>"} />);
expect(html).not.toContain("<script>");
expect(html).not.toContain("<b>");
@@ -17,17 +17,25 @@ const RemarkPlugins = [remarkGfm];
type Props = {
text: string;
/**
* Long text (a brief, a runbook, a memory): kept to a sunken box that
* scrolls, so it never pushes the rest of a card out of sight.
*/
boxed?: boolean;
className?: string;
};
/**
* A task's description or a note on it, rendered like a bot's message
* (raw HTML never rendered, links in a new tab, refs as their chips). The
* crew the chips link to is the page's own when no conversation around it
* gives one. The message elements reach this file again through the task
* chip, so they're read when it renders, never at load.
* Bot- or user-written markdown anywhere outside a message (a task's
* description and notes, a hook's or routine's brief, a skill's runbook,
* a card's reason, a bot's instructions and memory), rendered like a bot's
* message: raw HTML never rendered, links in a new tab, refs as their
* chips. Never show such text raw. The crew the chips link to is the
* page's own when no conversation around it gives one. The message
* elements reach this file again through the chips and cards, so they're
* read when it renders, never at load.
*/
export default function TaskMarkdown({ text, className }: Props) {
export default function MarkdownText({ text, boxed, className }: Props) {
const { pageProps } = useContext(AppContext);
const crew_bots = useContext(CrewBotsContext);
const crew_workspaces = useContext(CrewWorkspacesContext);
@@ -37,7 +45,13 @@ export default function TaskMarkdown({ text, className }: Props) {
return (
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
<Stack className={twMerge("w-full min-w-0 gap-2! items-stretch", className)}>
<Stack
className={twMerge(
"w-full min-w-0 gap-2! items-stretch break-words",
boxed && "max-h-80 overflow-y-auto rounded-default-xs bg-sunken px-3 py-2",
className,
)}
>
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
+2 -2
View File
@@ -17,7 +17,7 @@ import TaskNoteRow from "@/src/components/general/task-note-row";
import TaskSubtaskRow from "@/src/components/general/task-subtask-row";
import TaskSubtasksModal from "@/src/components/general/task-subtasks-modal";
import SubtaskLinkForm from "@/src/components/general/subtask-link-form";
import TaskMarkdown from "@/src/components/general/task-markdown";
import MarkdownText from "@/src/components/general/markdown-text";
import type { BotFace } from "@/src/dict/bot-dict";
import { AppContext } from "@/src/pages/__root";
import { AppData } from "@/src/data/app-data";
@@ -474,7 +474,7 @@ export default function TaskDetailPanel({
<Span className="text-[13px] leading-[18px] text-ink">{`Waiting on you: ${task.blocked_reason}`}</Span>
) : null}
{task.description ? <TaskMarkdown text={task.description} /> : null}
{task.description ? <MarkdownText text={task.description} /> : null}
{task.workspace_id && !task.bot_id ? (
<Stack className="w-full gap-1! items-stretch">
+2 -2
View File
@@ -3,7 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { TaskNote } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import TaskMarkdown from "./task-markdown";
import MarkdownText from "./markdown-text";
type Props = {
note: TaskNote;
@@ -26,7 +26,7 @@ export default function TaskNoteRow({ note }: Props) {
</Span>
) : null}
</Row>
{note.text ? <TaskMarkdown text={note.text} /> : null}
{note.text ? <MarkdownText text={note.text} /> : null}
</Stack>
);
}
+3 -1
View File
@@ -13,7 +13,9 @@ type Props = {
className?: string;
};
const MoveStatuses = TaskStatuses.filter((it) => ["todo", "doing", "done"].includes(it.value));
const MoveStatuses = TaskStatuses.filter((it) =>
["todo", "doing", "paused", "done"].includes(it.value),
);
/**
* The buttons that move a task along (To do, Doing, Done), the one it's
+6 -1
View File
@@ -10,7 +10,12 @@ export default async function pruneBotsQueue() {
Date.now() - AppData.BotQueueRetentionDays * 24 * 60 * 60 * 1000;
const res = await BunSQLite.sql({
sql: `DELETE FROM bots_queue WHERE status IN ('completed', 'failed') AND finished_at IS NOT NULL AND finished_at < ? RETURNING id`,
/**
* `updated_at` stands in for a row finished without a timestamp (an
* older build, or a writer that set the status directly): without it
* such a row sits in the queue for ever.
*/
sql: `DELETE FROM bots_queue WHERE status IN ('completed', 'failed') AND COALESCE(finished_at, updated_at) < ? RETURNING id`,
values: [cutoff],
});
+13 -2
View File
@@ -389,8 +389,12 @@ export const AppData = {
*/
ScheduledRunRetryMs: 5 * 60 * 1000,
/**
* The queue handler's lock name. Stable across restarts, so on startup
* it can release the jobs it was running when the process stopped.
* The queue handler's lock family. The id a handler locks with adds the
* process's pid (`src/bots-queue/index.ts`), so two processes (a dev
* server and the app, or two replicas) can never renew each other's
* locks: a heartbeat then fails, and the handler that lost the job stops.
* Startup still releases the family's jobs, so a restart doesn't leave
* its own cut-off runs waiting out the lock timeout.
*/
BotQueueWorker: "main",
BotQueuePollMs: 3000,
@@ -537,6 +541,13 @@ export const AppData = {
* many `list_tasks` hands back at once.
*/
TaskReminderDigestCount: 3,
/**
* Open tasks put in front of every run (`OpenTasksNote`): a bot that
* never sees its own list is how a Doing task sits for weeks. Paused
* ones are left out (the user parked them), so this is what a run is
* reminded of at most.
*/
TaskDigestCount: 8,
TaskListToolLimit: 20,
/**
* Automatic model picks (`rankAutoModels`). A free model from outside
+3 -2
View File
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test";
import { TaskStatuses } from "@/src/dict/task-dict";
import { CoordinatorSystemPrompt } from "./coordinator-system-prompt";
import { SiteData } from "./site-data";
@@ -24,8 +25,8 @@ describe("CoordinatorSystemPrompt", () => {
});
test("uses the real task statuses, not invented ones", () => {
for (const status of ["todo", "doing", "blocked", "done", "cancelled"]) {
expect(CoordinatorSystemPrompt).toContain(status);
for (const { value } of TaskStatuses) {
expect(CoordinatorSystemPrompt).toContain(value);
}
// Words from the previous draft that no tool accepts.
+1 -1
View File
@@ -72,7 +72,7 @@ A tool result is the source of truth.
- Read the change back when the tool allows it. If it can't be read back, say the write was confirmed but not independently verified.
- Never claim to have read, saved, attached, deleted or verified something you didn't, and never claim to know what the user's screen shows.
Task states are \`todo\`, \`doing\`, \`blocked\` (with a \`blocked_reason\`), \`done\` and \`cancelled\`, moved with \`update_task\`. Queued is not running, started is not done, and done is not verified. Check state with tools instead of trusting the conversation.
Task states are \`todo\`, \`doing\`, \`blocked\` (with a \`blocked_reason\`), \`paused\` (the user parked it), \`done\` and \`cancelled\`, moved with \`update_task\`. Queued is not running, started is not done, and done is not verified. Check state with tools instead of trusting the conversation.
When a call fails, read the error, fix the cause, retry only with a reason to expect a different outcome, then check the result. Never repeat an identical failing call. After repeated failures, stop and say what's known and what's uncertain. Don't hand the user a technical problem you can solve yourself.
+80 -11
View File
@@ -17,6 +17,8 @@ import {
TaskRunNote,
TaskWrapUpIncomingNote,
TasksNote,
OpenTasksNote,
PlanModeNote,
wrapUpWorktreeNote,
PlansNote,
PlanStepNote,
@@ -231,10 +233,13 @@ describe("wrapUpWorktreeNote", () => {
});
describe("TaskRunNote", () => {
const attended = TaskRunNote({ can_ask: true });
const unattended = TaskRunNote({ can_ask: false });
test("says a brief can be wrong about the tree, and that handing on finishes the task", () => {
expect(TaskRunNote).toContain("A brief can be wrong about the repository");
expect(TaskRunNote).toContain("the tree wins");
expect(TaskRunNote).toContain("start_task with separate for the rest");
expect(attended).toContain("A brief can be wrong about the repository");
expect(attended).toContain("the tree wins");
expect(attended).toContain("start_task with separate for the rest");
});
test("gives the plan permission to hand work on", () => {
@@ -242,11 +247,17 @@ describe("TaskRunNote", () => {
});
test("says the user's own words win over the brief, and the way they named is the way it is done", () => {
expect(TaskRunNote).toContain("the run opens with their own words");
expect(TaskRunNote).toContain("the brief after it is your summary of it");
expect(TaskRunNote).toContain("the way they named (a tool, app, service or path) is the way it is done");
expect(TaskRunNote).toContain("never reach the same result some other way without asking first");
expect(TaskRunNote).not.toContain("\u2014");
expect(attended).toContain("the run opens with their own words");
expect(attended).toContain("the brief after it is your summary of it");
expect(attended).toContain("the way they named (a tool, app, service or path) is the way it is done");
expect(attended).toContain("never reach the same result some other way without asking first");
expect(attended).not.toContain("\u2014");
});
test("names ask_user only for a run the user watches", () => {
expect(attended).toContain("ask_user");
expect(attended).toContain("ask_user_to_take_over");
expect(unattended).not.toContain("ask_user");
});
});
@@ -334,8 +345,13 @@ describe("plan notes", () => {
expect(note).toContain('"Pause the plan"');
});
test("the last step's card offers to finish the plan", () => {
expect(PlanStepNote({ plan: { ...plan, current_step: 2 } })).toContain('"Finish the plan"');
test("the last step ends the plan with its report alone, no card", () => {
const note = PlanStepNote({ plan: { ...plan, current_step: 2 } });
expect(note).toContain("This is the last step");
expect(note).toContain("no card");
expect(note).not.toContain("Finish the plan");
expect(note).not.toContain("Every finished step ends on a card");
});
test("lists the steps with where each one stands and what it produced", () => {
@@ -350,9 +366,62 @@ describe("plan notes", () => {
expect(PlanActiveNote({ plan })).toContain("leave the plan where it is");
});
test("an active plan lets an ordinary reply tick the step and ends on the card", () => {
const note = PlanActiveNote({ plan });
expect(note).toContain("work it now: finish it with complete_plan_step");
expect(note).toContain('"Continue to step 3"');
expect(note).toContain('"Pause the plan"');
expect(note).toContain('status "paused"');
});
test("in Plan mode an active plan is refined, not worked", () => {
const note = PlanActiveNote({ plan, plan_mode: true });
expect(note).toContain("the plan is yours to pick up and refine here, not to work");
expect(note).toContain("update_plan");
expect(note).not.toContain("complete_plan_step");
expect(PlanModeNote).toContain("The plan is the point of this mode");
expect(PlanModeNote).toContain("refine it with update_plan as many times");
});
test("in Plan mode a waiting or paused plan is refined too", () => {
expect(PlanWaitingNote({ plan: { ...plan, status: "planned" }, plan_mode: true })).toContain(
"rewrite the steps with update_plan",
);
expect(PlanWaitingNote({ plan: { ...plan, status: "planned" } })).toContain("they make them on the card");
expect(PlanPausedNote({ plan: { ...plan, status: "paused" }, plan_mode: true })).toContain(
"the plan is yours to refine here with update_plan",
);
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain('status "active"');
});
test("a paused plan is the user's to resume", () => {
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain("paused by the user");
});
});
describe("open tasks digest", () => {
test("names each open task with its ref and status", () => {
const note = OpenTasksNote({
tasks: [
{ id: 33, title: "Fix the hero crop", status: "doing" },
{ id: 46, title: null, status: "todo" },
],
});
expect(note).toContain("- [task:33] Fix the hero crop (doing)");
expect(note).toContain("- [task:46] (todo)");
});
test("tells the run to keep the list true and never report a move it didn't make", () => {
const note = OpenTasksNote({ tasks: [{ id: 1, title: "One", status: "blocked" }] });
expect(note).toContain("Keep this list true as you work");
expect(note).toContain("update_task");
});
test("reads a row whose columns are missing", () => {
expect(OpenTasksNote({ tasks: [{}] })).toContain("- [task] (open)");
});
});
+120 -30
View File
@@ -77,7 +77,13 @@ function ownFolderRef({ bot_id }: { bot_id: number | string }) {
* Added to a bot's prompt when it answers the user in chat. `bot_id` is the
* bot itself: the examples it reads are its own refs.
*/
export const chatReplyNote = ({ bot_id }: { bot_id: number | string }) => `# Replying in chat
export const chatReplyNote = ({
bot_id,
can_take_over = true,
}: {
bot_id: number | string;
can_take_over?: boolean;
}) => `# Replying in chat
You are chatting with the user. Answer their latest messages directly and briefly, in markdown.
@@ -87,8 +93,11 @@ You are chatting with the user. Answer their latest messages directly and briefl
- send_reply({status:"working", work:{title, instructions, computer_id?}}) for work that takes more than a moment, or anything on a computer (running commands, editing files, browsing). The app queues the run before your message goes out; a task you start is your own work, so never say you handed it to anyone else. Its result is posted here when it's done.
- send_reply({status:"blocked"}) when the work can't go on; say why in the message.
- When a message mixes both, answer the quick parts and queue the rest with status "working" and work.
- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.
- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
${
can_take_over
? `- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.\n`
: ""
}- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
- Never claim you did something you didn't do.
@@ -376,7 +385,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
* `bot_id` is the coordinator itself, so the ref example it copies is its
* own rather than a worker's.
*/
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). Each started run opens a session of its own in their conversation, they can send you a word on the way, and their report comes back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
/**
* Added to the coordinator's chat prompt instead while it has no workers,
@@ -397,7 +406,7 @@ export const workspaceAdminNote = ({
members: { id?: number | "" }[];
}) => `# Leading ${workspace_name}
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); each started run opens a session of its own in their conversation here, they can send you a word on the way, and their report comes back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
/**
* Added to a workspace member's prompt while the workspace has an admin,
@@ -408,10 +417,18 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
/**
* Added to a bot's prompt when it works through a queued task.
*
* `can_ask` decides whether it may name `ask_user`: a routine, a hook call or
* a hidden session has no card the user would see (the tool is taken away
* there), so the note must not order a call that isn't offered.
*/
export const TaskRunNote = `# Working on a task
export const TaskRunNote = ({ can_ask }: { can_ask: boolean }) => `# Working on a task
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest${
can_ask
? `: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user`
: `, or state the outcome plainly`
}. Keep the report short and in markdown.
When they asked for this work in their chat, the run opens with their own words: that message is the request itself, and the brief after it is your summary of it. Where the two disagree the words win, and the way they named (a tool, app, service or path) is the way it is done. If that way can't work, the report says what blocked it and what the alternatives are; never reach the same result some other way without asking first.
@@ -423,7 +440,11 @@ Work larger than one run is handed on, not half-done: start_task with separate f
The report ends with send_reply and the text beside it: status "done" when nothing follows it, "working" when you handed work on and it is still running, or "blocked" when it can't finish. A report without it is a draft and is never sent.
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same.${
can_ask
? ` If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`
: ""
}`;
/**
* Told to a task run with what the user wrote in its conversation since
@@ -624,6 +645,24 @@ export const replyClosingMixedNote = `send_reply's turn can also call suggest_ne
*/
export const replyClosingFailedNote = `send_reply did not go through (its error is above), so the message was not sent. Status "working" needs work queued in the call or a run you already started; fix that and call send_reply again with the message, or use status "done" or "blocked".`;
/**
* Told when `send_reply` went through and only the card beside it was refused
* (a step over its length cap, an argument the tool rejected): the message is
* kept, so the model must not rewrite it. Naming send_reply as the failed
* call here spent three turns of one run re-writing an answer that had already
* shipped, and logged the failure against the wrong tool.
*/
export const replyCardFailedNote = ({ tools }: { tools: string[] }) =>
`send_reply went through and your message is kept. The card call did not: ${tools.join(" and ")} refused (its error is above). Fix those arguments, or drop the card, and call send_reply again in the same turn with the same message.`;
/**
* Told when a card was refused in a turn that never called `send_reply`:
* the card's error is what to fix. Telling the model `send_reply` failed
* there sent it after a status error that never happened (job 694).
*/
export const replyCardOnlyFailedNote = ({ tools }: { tools: string[] }) =>
`The card was not put up: ${tools.join(" and ")} refused its arguments (the error is above), so nothing reached the user. Fix those arguments exactly as the error says and call it again, with send_reply in the same turn carrying your message (the message you wrote beside the card is kept for it). Or drop the card and answer with send_reply alone.`;
/**
* 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
@@ -752,23 +791,40 @@ Tasks are the crew's to-do list. A task belongs to one bot, on its own list or i
- list_tasks shows what's open: yours, a workspace's, or (as the coordinator) all of it. Check it before you plan work, so you don't start something already tracked.
- create_task adds one, with a brief: what to do, where, and what done looks like. Only add a task for work that will take more than this reply; never one for something you're doing now.
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, paused when the user has parked the work for now, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
- On a workspace-wide task, read its log first (list_tasks with task_id) to see which bot did what and when, take a part nobody has done yet, and log each part you finish with update_task. Every note is recorded under your name and id, so the log is how the crew stays in step.
- A deliverable is a file: save it first with write_file, make_pdf or generate_image, then pass its [file:ID] ref in deliverable_file_ids, so the task carries what it produced.
- When you name a task, write its [task:ID] ref, e.g. [task:12], so the user can open it. Only tasks from list_tasks or create_task have one; a run from send_reply's work, start_task or delegate_task is not a task.`;
/**
* Added to a chat reply: when and how to bring pending tasks up, so the bot
* reminds the user without nagging.
* Added to every run: the bot's open tasks as the app reads them, so it
* works against the list instead of remembering to look it up. Paused ones
* are left out: the user parked them, and the run needn't push them.
*/
export const OpenTasksNote = ({
tasks,
}: {
tasks: { id?: number | string; title?: string | null; status?: string }[];
}) => `# Your open tasks
These are open on your list now, as the app reads them:
${tasks.map((task) => `- ${task.id ? `[task:${task.id}]` : "[task]"}${task.title ? ` ${task.title}` : ""} (${task.status || "open"})`).join("\n")}
- Keep this list true as you work, without waiting to be asked: when a doing task's work is finished and verified, move it to done; when only the user can unblock one, move it to blocked with the reason; when they say work on one is parked, move it to paused.
- Never report a task as done, started or moved without update_task answering for it in this run.`;
/**
* Added to a chat reply: when and how to bring the digest tasks up, so the
* bot reminds the user without nagging.
*/
export const TaskReminderNote = `# Mentioning pending tasks
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or when the work you're answering is done and you're about to offer what comes next, call list_tasks before you write your answer and put the reminder in the answer itself.
You have open tasks above to keep up with. When the message is an opening ("hello", "what's up"), or when the work you're answering is done and you're about to offer what comes next, put the reminder in the answer itself.
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} tasks: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} of the tasks above: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
- Never invent a task: name only what list_tasks returned.
- Never send the answer and then call list_tasks: only your last message goes out, so the answer you wrote first would never reach the user. Look first, then answer once.`;
- Never invent a task: name only ones the list above or list_tasks returned. That list is the newest ${AppData.TaskDigestCount} open ones: for more, or for another bot's or a workspace's, call list_tasks first, never guess.`;
/**
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
@@ -1078,11 +1134,16 @@ When a plan you worked through is one the same work comes back to (a new project
/**
* A plan waiting on the user: the bot wrote it and may not start it yet,
* whatever the user writes in the meantime.
* whatever the user writes in the meantime. In Plan mode the bot may still
* refine it (the mode's whole point), it just can't start it.
*/
export const PlanWaitingNote = ({ plan }: { plan: PlanPrompt }) => `# Your plan is waiting on the user
export const PlanWaitingNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mode?: boolean }) => `# Your plan is waiting on the user
Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting for the user to approve it or change its steps. Its steps are not work yet: don't start them, don't report on them, and don't write another plan. Answer what the user wrote; if they asked for changes to the plan, they make them on the card.`;
Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting for the user to approve it or change its steps. Its steps are not work yet: don't start them, don't report on them, and don't write another plan. Answer what the user wrote.${
plan_mode
? ` This reply runs in Plan mode, so the plan is yours to refine here: when they ask for changes, rewrite the steps with update_plan (the whole list), as many times as they want, and say in a line what changed. Starting it is still theirs: they approve it on the card.`
: ` If they asked for changes to the plan, they make them on the card.`
}`;
/**
* Given to the run that works one step of an approved plan: that step only,
@@ -1093,7 +1154,15 @@ export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
const index = plan.current_step ?? 0;
const step = plan.steps[index];
const next = index + 2;
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
const last_step = next > plan.steps.length;
/**
* The last step's tick finishes the plan, so its report ends the plan
* on its own: a "Finish the plan" card would move nothing on, and the
* review used to demand one while the tool said none was needed.
*/
const ending = last_step
? `- **This is the last step.** complete_plan_step finishes the plan, so the report goes out with send_reply alone and no card: there is no next step to continue to.`
: `- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "Continue to step ${next}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.`;
return `# Your plan, step ${index + 1} of ${plan.steps.length}
@@ -1103,10 +1172,10 @@ ${planStepLines({ plan })}
This run works step ${index + 1} only: ${step?.text || ""}
- One step per run. The next step starts when the user answers this report's card, so don't start it now and don't do two.
- One step per run.${last_step ? "" : " The next step starts when the user answers this report's card, so don't start it now and don't do two."}
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "${next_label}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan${last_step ? "" : " and the step after this one"}, so repeating it only makes the reply longer than it needs to be.
${ending}
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask that question on the card, and say the plan is holding at this step.
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same run, and say what changed.`;
};
@@ -1114,9 +1183,18 @@ This run works step ${index + 1} only: ${step?.text || ""}
/**
* Given to any other run in a conversation whose plan is approved and being
* worked: the plan is in the prompt, and the user's own message comes first.
* The run may work a step when the message asks for it (`complete_plan_step`
* is offered), and it can park the plan when they asked: the card still
* gates every step nobody approved.
*/
export const PlanActiveNote = ({ plan }: { plan: PlanPrompt }) => {
export const PlanActiveNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mode?: boolean }) => {
const index = plan.current_step;
const step = index == null ? null : plan.steps[index];
const next = (index ?? 0) + 2;
const work_step =
next > plan.steps.length
? `finish it with complete_plan_step in this run. It is the last step, so that finishes the plan and the report goes out alone, with no card.`
: `finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "Continue to step ${next}", second "Pause the plan"). A report that ticked the step without that card is sent back.`;
return `# The plan in this conversation
@@ -1124,18 +1202,29 @@ Plan #${plan.id} "${plan.title}" is approved and in progress${index == null ? ""
${planStepLines({ plan })}
- Its steps are worked one per reply, each ending on a card the user answers to start the next one. This reply isn't working a step, so don't work one here: if they ask you to carry on, say the next step is step ${(index ?? 0) + 1} and they start it from the plan's card (Continue on the plan, under the report above), then answer whatever else they asked.
- If they asked something else, answer that and leave the plan where it is: it carries on from there.
- The steps are theirs to change on the card. If the work moved on from one of them, update_plan and say what changed.`;
${
plan_mode
? `- This reply runs in Plan mode: the plan is yours to pick up and refine here, not to work. When what they say bears on the steps, rewrite them with update_plan (the whole list, done steps first and unchanged), as many times as the conversation asks, and say in a line what changed. Don't work or tick a step, and don't pause or resume the plan: that waits until the mode is off.`
: `- Its steps are normally worked one per reply, each ending on a card the user answers to start the next one. This reply isn't a step the app queued: answer whatever the user asked first.
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: ${work_step}
- If they asked something else, answer that and leave the plan where it is: it carries on from there. Don't work a step as a side errand.
- If the user's answer to the plan's card was typed rather than a click, it is theirs to read here: carry on with the step when it says to, and park the plan with update_plan and status "paused" when it says to wait.
- Only pause or resume when they asked, with update_plan and its status. Never end a plan on your own: cancelling is theirs. The steps are theirs to change on the card too; if the work moved on from one of them, update_plan and say what changed.`
}`;
};
/**
* A paused plan: the user stopped it, so its steps wait until they say
* otherwise. The bot still answers them.
* otherwise. The bot still answers them, and can pick the plan back up when
* they ask.
*/
export const PlanPausedNote = ({ plan }: { plan: PlanPrompt }) => `# A paused plan
export const PlanPausedNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mode?: boolean }) => `# A paused plan
Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_step ?? 0) + 1} of ${plan.steps.length}. Don't work its steps and don't finish them: answer what the user asks, and leave picking it back up to them (they resume it from the card).`;
Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_step ?? 0) + 1} of ${plan.steps.length}. Don't work its steps and don't finish them: answer what the user asks, and leave picking it back up to them (they resume it from the card).${
plan_mode
? ` This reply runs in Plan mode: the plan is yours to refine here with update_plan (the whole step list, as many times as they ask), without starting it again.`
: ` If this message asks you to carry on, set the plan running again with update_plan and status "active", then work the step it stands on and end on the step's card like any step reply.`
}`;
/**
* Plan mode: the user turned it on in the composer, so this reply plans and
@@ -1148,7 +1237,8 @@ export const PlanModeNote = `# Plan mode
The user sent this message with Plan mode on. This reply plans, reads and asks; it changes nothing, anywhere.
- Read what you need: files, tasks, schedules, hooks, graphics, knowledgebases, skills, past conversations, computers and the crew are all readable. Then say what you found and what you would do.
- When the work is several pieces that build on each other, write the plan with create_plan (3 to 6 steps) and let them approve it. Nothing in it starts until they do, and working its steps is a later reply. Approving it ends Plan mode.
- **The plan is the point of this mode.** When the work is several pieces that build on each other, it ends on a plan card, not in prose: write it with create_plan (3 to 6 steps) and let them approve it. Nothing in it starts until they do, and working its steps is a later reply. Approving it ends Plan mode.
- When the conversation already has a plan (its note above names it: waiting, in progress or paused), that is the plan to work on here: refine it with update_plan as many times as the user wants changes, sending the whole step list each time. Don't write a second plan over it, and don't work or tick its steps: that waits until they turn the mode off.
- When a choice is theirs, ask it with ask_user instead of picking for them. Answering it does not end Plan mode: their answer is another planning turn.
- Nothing is written, run or changed in this mode: no files written, no tasks, schedules, hooks, memory or instructions changed, no secrets, no crew changes, no computers, browsers, MCP servers or custom tools. Those tools are still in your list and calling one is refused with the reason, so don't say you did any of it, don't say a run is under way, and don't look for another way in.
- When the result belongs in a file or somewhere outside the chat (a document, a task, a memory), don't paste it and never say a tool is missing: Plan mode is what stops the save. Say so in one sentence, and either write it as a plan they can approve (its steps save it) or say what you will do once they turn Plan mode off. A short template they asked to read can stay in the message.
+23 -1
View File
@@ -85,4 +85,26 @@ export const AskAnswerJobTitle = "Crew request";
* requests one place keeps (`AppData.AskKeepDays`, `AskMaxPerPlace`).
*/
export const AskKeepDaysSettingKey = "ask_keep_days";
export const AskMaxPerPlaceSettingKey = "ask_max_per_place";
export const AskMaxPerPlaceSettingKey = "ask_max_per_place";
/**
* What opened a request. `ask` is `ask_bot`, which goes through the
* coordinator's gate. `hand_over` is a task one bot handed another and
* started because the user said so (`delegate_task`, `hand_over_task`): no
* gate, but the same thread of its own, interim updates and result back.
*/
export const AskKinds = [
{
title: "Crew request",
value: "ask",
},
{
title: "Hand-over",
value: "hand_over",
},
] as const;
export type AskKind = (typeof AskKinds)[number]["value"];
export function isHandOverAsk({ kind }: { kind?: string | null }) {
return kind == "hand_over";
}
+7 -3
View File
@@ -18,6 +18,10 @@ export const TaskStatuses = [
title: "Blocked",
value: "blocked",
},
{
title: "Paused",
value: "paused",
},
{
title: "Done",
value: "done",
@@ -31,10 +35,10 @@ export const TaskStatuses = [
export type TaskStatus = (typeof TaskStatuses)[number]["value"];
/**
* The statuses a task still needs work in: what a reminder may name and
* what a digest shows.
* The statuses a task still needs work in: a paused task is open (it waits
* for the user to pick it up), but the run digest leaves it out.
*/
export const OpenTaskStatuses = ["todo", "doing", "blocked"] as const;
export const OpenTaskStatuses = ["todo", "doing", "blocked", "paused"] as const;
/**
* Every status as a zod-friendly tuple of its values.
@@ -0,0 +1,34 @@
import { Database } from "bun:sqlite";
type Params = {
/**
* The live database file.
*/
source: string;
/**
* Where the copy goes. Must not exist yet.
*/
target: string;
};
/**
* Copies a live SQLite database into one consistent file with
* `VACUUM INTO`, which reads the whole database inside one read
* transaction, so writes made while it runs are either all in the copy or
* none of them. A data archive used to tar the live file, which the app
* writes every few seconds, so tar failed with "file changed as we read
* it" and the copy it kept was torn anyway.
*
* Its own read-only connection, so it needs no extension loaded (the
* vec0 tables' rows are plain shadow tables) and never touches the app's.
*/
export default function snapshotDatabaseFile({ source, target }: Params) {
const db = new Database(source, { readonly: true });
try {
db.run("PRAGMA busy_timeout = 5000;");
db.run("VACUUM INTO ?", [target]);
} finally {
db.close();
}
}
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import { Database } from "bun:sqlite";
import writeDataBackupArchive from "./write-data-backup-archive";
const dirs: string[] = [];
@@ -25,6 +26,24 @@ function write({ root, relative, content = "x" }: { root: string; relative: stri
fs.writeFileSync(target, content);
}
/**
* A real database at `db/cobble`: the archive snapshots it, so a stand-in
* file would not open.
*/
function writeDatabase({ root, rows = 1 }: { root: string; rows?: number }) {
fs.mkdirSync(path.join(root, "db"), { recursive: true });
const db = new Database(path.join(root, "db", "cobble"), { create: true });
db.run("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)");
db.transaction(() => {
for (let i = 0; i < rows; i++) db.run("INSERT INTO notes (body) VALUES (?)", [`note ${i}`]);
})();
return db;
}
afterEach(() => {
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
@@ -44,7 +63,7 @@ describe("writeDataBackupArchive", () => {
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
writeDatabase({ root: data_dir }).close();
write({ root: data_dir, relative: "db/.backups/cobble-1" });
write({ root: data_dir, relative: ".bun-sqlite/.tmp/temp.db" });
write({ root: data_dir, relative: "computers/1/bots/3/users/1/work.txt" });
@@ -91,11 +110,53 @@ describe("writeDataBackupArchive", () => {
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
writeDatabase({ root: data_dir }).close();
write({ root: archive_dir, relative: "cobble-data-1.tar.gz" });
const created = await writeDataBackupArchive();
expect(fs.existsSync(created.path)).toBe(true);
});
});
test("archives a consistent copy of the database while it is being written", async () => {
const data_dir = makeRoot();
const archive_dir = makeRoot();
const extract_dir = makeRoot();
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
const db = writeDatabase({ root: data_dir, rows: 2000 });
// An open write transaction leaves a journal beside the file,
// which tar would otherwise read half-written.
db.run("BEGIN");
db.run("INSERT INTO notes (body) VALUES ('uncommitted')");
const created = await writeDataBackupArchive();
db.run("ROLLBACK");
db.close();
const root = created.name.replace(/\.tar\.gz$/, "");
const members = new TextDecoder()
.decode(Bun.spawnSync(["tar", "-tzf", created.path]).stdout)
.split("\n")
.filter(Boolean);
expect(members).toContain(`${root}/db/cobble`);
expect(members.some((member) => member.includes(".snapshot"))).toBe(false);
expect(members.some((member) => member.endsWith("-journal"))).toBe(false);
Bun.spawnSync(["tar", "-xzf", created.path, "-C", extract_dir]);
const copy = new Database(path.join(extract_dir, root, "db", "cobble"), { readonly: true });
const { n } = copy.query("SELECT count(*) AS n FROM notes").get() as { n: number };
const { integrity_check } = copy.query("PRAGMA integrity_check").get() as { integrity_check: string };
copy.close();
expect(integrity_check).toBe("ok");
expect(n).toBe(2000);
});
});
@@ -6,6 +6,14 @@ import grabDirNames from "@/src/utils/grab-dir-names";
import grabBackupArchiveDir from "@/src/utils/grab-backup-archive-dir";
import grabDataBackups from "./grab-data-backups";
import listArchiveExclusions from "./list-archive-exclusions";
import snapshotDatabaseFile from "./snapshot-database-file";
import BunSQLiteConfig from "@/bun-sqlite.config";
/**
* The live database's sidecars: the rollback journal, or WAL and its
* index. The snapshot replaces all of them.
*/
const DatabaseSidecarSuffixes = ["", "-journal", "-wal", "-shm"];
export type CreatedDataBackup = {
name: string;
@@ -17,9 +25,15 @@ export type CreatedDataBackup = {
* bot and workspace files, MCP installs, Chrome profiles) into
* `BACKUP_ARCHIVE_DIR` and keeps only the newest
* `AppData.DataBackupsKept`. Every entry sits under one root folder named
* after the archive, so extracting it lands one folder. The SQLite file
* inside is only as consistent as the moment tar read it; `db/.backups` is
* for consistent snapshots.
* after the archive, so extracting it lands one folder.
*
* The database is never tarred live: the app writes it every few seconds,
* so tar exited 1 with "./db/cobble: file changed as we read it" and kept
* a torn copy. A `VACUUM INTO` snapshot (`snapshotDatabaseFile`) goes in
* at `db/<db_name>` instead, and the live file and its journal are left
* out. Anything else changing mid-read (a bot saving a file, Chrome
* writing its cookies) is only tar's exit 1, which still means a whole
* archive, so that is a success; 2 and up fail the run.
*
* It leaves out what is rebuilt on demand or kept elsewhere
* (`listArchiveExclusions`): a computer's own folders, Chrome profile
@@ -41,10 +55,27 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
const part_path = `${archive_path}.part`;
const excl_dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
const excl_path = path.join(excl_dir, "exclude.txt");
const db_file = path.join(DATA_DIR, "db", BunSQLiteConfig.db_name);
const has_db = fs.existsSync(db_file);
// Staged under a name of its own: the live file's member path is
// excluded, and tar would drop a staged file of the same name too.
const snapshot_member = `./db/${BunSQLiteConfig.db_name}.snapshot`;
try {
const exclusions = await listArchiveExclusions({ data_dir: DATA_DIR });
if (has_db) {
for (const suffix of DatabaseSidecarSuffixes) {
exclusions.push(`./db/${BunSQLiteConfig.db_name}${suffix}`);
}
fs.mkdirSync(path.join(excl_dir, "db"), { recursive: true });
snapshotDatabaseFile({
source: db_file,
target: path.join(excl_dir, snapshot_member),
});
}
fs.writeFileSync(excl_path, exclusions.map((line) => `${line}\n`).join(""));
const proc = Bun.spawn(
@@ -58,8 +89,14 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
// Two expressions: the root `.` itself and every `./`
// member, so the whole archive sits under one folder named
// after it and an extract drops a single folder.
// The database snapshot first takes the live file's
// place (`db/<db_name>`).
"--transform",
`s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
`s,^\\./db/${BunSQLiteConfig.db_name}\\.snapshot$,${archive_root}/db/${BunSQLiteConfig.db_name},;s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
// A file written while tar reads it (a bot's save, a
// Chrome profile) is exit 1, not a broken archive.
"--warning=no-file-changed",
"--warning=no-file-removed",
// The exclusions are exact member paths
// (`listArchiveExclusions`), never patterns: a folder a
// bot named `node_modules!` or `Cache*` must not take a
@@ -69,6 +106,7 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
"-C",
DATA_DIR,
".",
...(has_db ? ["-C", excl_dir, snapshot_member] : []),
],
{
cwd: process.cwd(),
@@ -85,7 +123,9 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
proc.exited,
]);
if (exit_code !== 0) {
// GNU tar: 1 is "some files differ" (changed while read), and the
// archive is still whole; 2 is a fatal error.
if (exit_code !== 0 && exit_code !== 1) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
@@ -49,4 +49,15 @@ describe("askOutcomeMessage", () => {
test("names an unnamed request without empty quotes", () => {
expect(askOutcomeMessage({ ask: { ...ask, title: "" }, status: "refused" })).toContain("your crew request");
});
test("a hand-over's report says it was work handed over, not a request the coordinator passed on", () => {
const handed = { ...ask, kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
const text = askOutcomeMessage({ ask: handed, status: "answered", outcome: "Shipped." });
expect(text).toBe('[bot:12] finished "Cite the sheet" [ask:3], which you handed over. Their report:\n\nShipped.');
expect(askOutcomeMessage({ ask: handed, status: "failed", outcome: "No computer." })).toContain(
"couldn't finish",
);
expect(askOutcomeMessage({ ask: handed, status: "stopped" })).not.toContain("coordinator");
});
});
@@ -1,5 +1,5 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import type { AskStatus } from "@/src/dict/ask-dict";
import { isHandOverAsk, type AskStatus } from "@/src/dict/ask-dict";
import askRef from "@/src/utils/ask-ref";
import botRef from "@/src/utils/bot-ref";
@@ -20,6 +20,20 @@ export default function askOutcomeMessage({ ask, status, outcome }: Params) {
const pill = ask.id ? ` ${askRef({ id: ask.id })}` : "";
const target = ask.target_bot_id ? botRef({ id: ask.target_bot_id }) : "the crew";
if (isHandOverAsk({ kind: ask.kind })) {
const handed = ask.title ? `"${ask.title}"` : "the work";
if (status == "stopped") {
return `${handed}${pill}, which you handed to ${target}, was stopped: ${outcome || "the user stopped it."}`;
}
if (status == "failed" || status == "refused") {
return `${target} couldn't finish ${handed}${pill}, which you handed over:\n\n${outcome || "No reason was given."}`;
}
return `${target} finished ${handed}${pill}, which you handed over. Their report:\n\n${outcome || ""}`;
}
if (status == "refused") {
return `The coordinator turned down ${title}${pill}:\n\n${ask.gate_note || outcome || "No reason was given."}`;
}
@@ -1,5 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import botRef from "@/src/utils/bot-ref";
import { isHandOverAsk } from "@/src/dict/ask-dict";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -21,6 +22,18 @@ export default function askRequestMessage({ ask, requester_name, place }: Params
const requester = ask.requester_bot_id ? botRef({ id: ask.requester_bot_id }) : `"${requester_name}"`;
const where = place ? `, from the ${place} workspace` : "";
/**
* A task handed over on the user's word: the work is this run's, and
* its result goes back to the bot that handed it over on its own.
*/
if (isHandOverAsk({ kind: ask.kind })) {
return `${requester} handed this over to you (hand-over #${ask.id}${where}):
> ${(ask.request || "").trim().replace(/\n/g, "\n> ")}
Work it in this conversation. Your report goes back to ${requester} when the run ends; update_requester sends it a word meanwhile.`;
}
return `The coordinator passed on a request from ${requester} (ask #${ask.id}${where}):
> ${(ask.request || "").trim().replace(/\n/g, "\n> ")}
@@ -34,4 +34,13 @@ describe("askUpdateMessage", () => {
expect(text).toContain("your crew request");
});
test("an answer sent after the request ended says so instead of still open", () => {
const text = askUpdateMessage({ ask, text: "Banner finished: [file:389].", ended: true });
expect(text).toContain("[bot:3] sent a response on");
expect(text).toContain("Banner finished: [file:389].");
expect(text).toContain("had already ended");
expect(text).not.toContain("still open");
});
});
@@ -1,6 +1,7 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import askRef from "@/src/utils/ask-ref";
import botRef from "@/src/utils/bot-ref";
import { isHandOverAsk } from "@/src/dict/ask-dict";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -12,6 +13,11 @@ type Params = {
* The run that produced this result failed.
*/
failed?: boolean;
/**
* The request had already ended when this was sent (`answer_requester`):
* it's the answer arriving late, not one piece of work still running.
*/
ended?: boolean;
};
/**
@@ -19,9 +25,10 @@ type Params = {
* bot finished one piece of the work, but more is still running, so the
* request isn't ended yet. Stored on the user's side like the final outcome
* (`from_ask_id`), and says plainly that more may follow so the asking bot
* doesn't treat it as the whole answer.
* doesn't treat it as the whole answer. With `ended`, it's the same shape
* for a request that had already finished: a late or corrected answer.
*/
export default function askUpdateMessage({ ask, text, failed }: Params) {
export default function askUpdateMessage({ ask, text, failed, ended }: Params) {
const title = ask.title ? `"${ask.title}"` : "your crew request";
const pill = ask.id ? ` ${askRef({ id: ask.id })}` : "";
const target = ask.target_bot_id ? botRef({ id: ask.target_bot_id }) : "the crew";
@@ -30,5 +37,10 @@ export default function askUpdateMessage({ ask, text, failed }: Params) {
? `${target} couldn't finish one piece of ${title}${pill}:`
: `${target} sent a response on ${title}${pill}:`;
return `${head}\n\n${text}\n\n_The request is still open - more may follow._`;
const what = isHandOverAsk({ kind: ask.kind }) ? "hand-over" : "request";
const tail = ended
? `_The ${what} had already ended; this is the answer, sent afterwards._`
: `_The ${what} is still open - more may follow._`;
return `${head}\n\n${text}\n\n${tail}`;
}
@@ -12,7 +12,8 @@ type Params = {
export default async function countOpenAsks({ user_id, requester_bot_id }: Params) {
const res = await BunSQLite.sql<{ n: number }>({
sql: `SELECT COUNT(*) AS n FROM bot_asks
WHERE user_id = ? AND requester_bot_id = ? AND status IN ('pending', 'working')`,
WHERE user_id = ? AND requester_bot_id = ? AND status IN ('pending', 'working')
AND COALESCE(kind, 'ask') = 'ask'`,
values: [Number(user_id), Number(requester_bot_id)],
});
@@ -20,6 +20,11 @@ type Params = {
target_bot_id: number | string;
title: string;
request: string;
/**
* The run making the request, recorded so stopping that run ends this
* request and no other ask made from the same conversation.
*/
requester_job_id?: number | string | null;
};
/**
@@ -34,6 +39,7 @@ export default async function createAsk({
target_bot_id,
title,
request,
requester_job_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_ASKS> {
if (requester.kind == "coordinator") {
throw new AppError(`The coordinator hands work out itself; it doesn't ask the crew.`);
@@ -101,6 +107,7 @@ export default async function createAsk({
target_bot_id: Number(target_bot_id),
origin_session_id: Number(origin_session_id),
parent_ask_id: parent_ask_id ? Number(parent_ask_id) : undefined,
requester_job_id: requester_job_id ? Number(requester_job_id) : undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: request.trim(), max: AppData.AskBriefMaxChars }),
status: "pending",
@@ -122,6 +129,7 @@ export default async function createAsk({
target_bot_id: Number(target_bot_id),
origin_session_id: Number(origin_session_id),
parent_ask_id: parent_ask_id ? Number(parent_ask_id) : undefined,
requester_job_id: requester_job_id ? Number(requester_job_id) : undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: request.trim(), max: AppData.AskBriefMaxChars }),
status: "pending",
@@ -34,7 +34,9 @@ export type ConversationAsk = {
* The crew request the bot is answering for this user, if one is open. The
* answer runs in the bot's own conversation, and stays `working` while any
* run it started is still open, so the row under the last message reads this
* to say who it's answering for as long as the work is under way.
* to say who it's answering for as long as the work is under way. A
* hand-over is a task run, so its thread shows the task's own working row
* (with its progress) instead.
*/
export default async function grabConversationAsk({
user_id,
@@ -52,7 +54,8 @@ export default async function grabConversationAsk({
FROM bot_asks a
LEFT JOIN bots b ON b.id = a.requester_bot_id
LEFT JOIN workspaces w ON w.id = a.workspace_id
WHERE a.user_id = ? AND a.target_bot_id = ? AND a.status = 'working' ${place}
WHERE a.user_id = ? AND a.target_bot_id = ? AND a.status = 'working'
AND COALESCE(a.kind, 'ask') = 'ask' ${place}
ORDER BY a.id DESC
LIMIT 1`,
values,
@@ -0,0 +1,35 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
type Params = {
/**
* The conversation to look up: a crew request's answer ran in its own
* session, recorded on the request as `session_id`.
*/
session_id: number | string;
/**
* Only if it's this user's, when the caller knows them.
*/
user_id?: number | string;
};
/**
* The request this session answered, once it has ended (answered, stopped
* or failed): the mirror of `grabOpenAskBySession`. A chat here after the
* end is the one place a late or corrected answer is written, so this is
* how the run knows to offer `answer_requester` instead of letting the
* bot open a fresh request through the gate for what belongs to this one.
*/
export default async function grabEndedAskBySession({
session_id,
user_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_ASKS | null> {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: user_id
? `SELECT * FROM bot_asks WHERE session_id = ? AND user_id = ? AND status NOT IN ('pending', 'working') ORDER BY id DESC LIMIT 1`
: `SELECT * FROM bot_asks WHERE session_id = ? AND status NOT IN ('pending', 'working') ORDER BY id DESC LIMIT 1`,
values: user_id ? [Number(session_id), Number(user_id)] : [Number(session_id)],
});
return res.payload?.[0] || null;
}
@@ -17,6 +17,7 @@ import type { HarnessToolUse } from "@/src/harness/types";
*/
let ask: BUN_SQLITE_COBBLE_BOT_ASKS;
let open_work: boolean;
let reopened: BUN_SQLITE_COBBLE_BOT_ASKS | null;
let finished: Array<{ status: string; outcome?: string | null }> = [];
let told: Array<{ text: string }> = [];
let shared: string[] = [];
@@ -40,6 +41,9 @@ mock.module("@/src/functions/backend/db/asks/finish-ask", () => ({
return ask;
},
}));
mock.module("@/src/functions/backend/db/asks/reopen-failed-ask", () => ({
default: async () => reopened,
}));
mock.module("@/src/functions/backend/db/asks/tell-ask-requester", () => ({
default: async ({ text }: { text: string }) => {
told.push({ text });
@@ -91,6 +95,7 @@ const real_answer = "Done. The post is built and saved: [file:650].";
beforeEach(() => {
ask = workingAsk();
open_work = false;
reopened = null;
finished = [];
told = [];
shared = [];
@@ -98,11 +103,22 @@ beforeEach(() => {
});
describe("onAskJobEnded - the answer reply", () => {
test("an answer that started work still running keeps the request open and relays nothing", async () => {
test("an answer that started work still running keeps the request open and relays the ack as an update", async () => {
open_work = true;
await onAskJobEnded({ job: answerJob(), text: claim, tool_uses: started_task });
expect(finished).toEqual([]);
expect(told.length).toBe(1);
expect(told[0]?.text).toContain(claim);
expect(told[0]?.text).toContain("still open");
});
test("a failed answer with work open relays nothing", async () => {
open_work = true;
await onAskJobEnded({ job: answerJob(), text: "The model call died.", failed: true });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
@@ -153,6 +169,24 @@ describe("onAskJobEnded - the answer reply", () => {
});
});
describe("onAskJobEnded - a hand-over's run", () => {
test("its report ends the hand-over answered", async () => {
ask = { ...workingAsk(), kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: answerJob(), text: real_answer });
expect(finished).toEqual([{ status: "answered", outcome: real_answer }]);
});
test("a failed run passes on why it failed", async () => {
ask = { ...workingAsk(), kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: answerJob(), text: "The computer is down.", failed: true });
expect(finished).toEqual([{ status: "failed", outcome: "The computer is down." }]);
});
});
describe("onAskJobEnded - a run the answer handed the work to", () => {
test("a result while more work is open is relayed as an update and keeps the request open", async () => {
open_work = true;
@@ -203,6 +237,49 @@ describe("onAskJobEnded - a run the answer handed the work to", () => {
});
});
describe("onAskJobEnded - a result landing after the request already failed", () => {
test("a late child result is delivered and the request reads answered", async () => {
ask = { ...workingAsk(), status: "failed" } as BUN_SQLITE_COBBLE_BOT_ASKS;
reopened = ask;
await onAskJobEnded({ job: childJob(), text: real_answer });
expect(finished).toEqual([]);
expect(shared).toEqual([real_answer]);
expect(told.length).toBe(1);
expect(told[0]?.text).toContain("which answered");
expect(told[0]?.text).toContain(real_answer);
});
test("a late failure changes nothing", async () => {
ask = { ...workingAsk(), status: "failed" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: childJob(), text: "", failed: true });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
test("a request someone else re-ended first is not written twice", async () => {
ask = { ...workingAsk(), status: "failed" } as BUN_SQLITE_COBBLE_BOT_ASKS;
reopened = null;
await onAskJobEnded({ job: childJob(), text: real_answer });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
test("a stopped request is not reopened", async () => {
ask = { ...workingAsk(), status: "stopped" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: childJob(), text: real_answer });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
});
describe("onAskJobEnded - the gate's review and guards", () => {
test("a failed review fails the request and clears its hidden session", async () => {
const review_job = { id: 490, bot_id: 1, session_id: 66, params: `{"ask_id":3,"stage":"review"}` } as BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -4,12 +4,14 @@ import parseJobJson from "@/src/bots-queue/parse-job-json";
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
import { WorkStartingTools } from "@/src/utils/reply-claim-problems";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import { AskStages } from "@/src/dict/ask-dict";
import { AskStages, isHandOverAsk } from "@/src/dict/ask-dict";
import hasOpenWork from "../bots-queue/has-open-work";
import deleteEmptyAskSession from "../bot-sessions/delete-empty-ask-session";
import askUpdateMessage from "./ask-update-message";
import askOutcomeMessage from "./ask-outcome-message";
import finishAsk from "./finish-ask";
import grabAsk from "./grab-ask";
import reopenFailedAskAnswered from "./reopen-failed-ask";
import shareAskFiles from "./share-ask-files";
import tellAskRequester from "./tell-ask-requester";
@@ -44,7 +46,32 @@ export default async function onAskJobEnded({ job, text, failed, tool_uses = []
const ask = await grabAsk({ ask_id });
if (!ask?.id || (ask.status != "pending" && ask.status != "working")) return;
if (!ask?.id) return;
/**
* A request that already failed can still get a result: the answer run
* can die after it had queued the work, and the asking bot was told it
* couldn't answer while the deliverable exists. When that run comes back
* with the real answer, it goes to the asking bot and the request reads
* answered, instead of the result being dropped quietly. A stopped or
* refused request stays ended: the user or the coordinator said so.
*/
if (ask.status == "failed") {
const late = (text || "").trim();
if (failed || !late || params.stage == AskStages.review) return;
const shared = stripQuestionRefs({ text: await shareAskFiles({ ask, answer: late }) }).text;
const reopened = await reopenFailedAskAnswered({ ask_id: ask.id, outcome: shared });
if (!reopened?.id) return;
await tellAskRequester({ ask, text: askOutcomeMessage({ ask, status: "answered", outcome: shared }) });
return;
}
if (ask.status != "pending" && ask.status != "working") return;
if (params.stage == AskStages.review) {
/**
@@ -83,18 +110,42 @@ export default async function onAskJobEnded({ job, text, failed, tool_uses = []
/**
* The answer started work that is still running (a task, a hand-over,
* a nested request): the acknowledgement is not the answer. The
* request stays open and the results come back as they land; the
* ack itself is not relayed, so the asking bot isn't woken for a
* promise.
* a nested request): the acknowledgement is not the whole answer. The
* request stays open and the results come back as they land. The ack
* is relayed as an update too, because it can carry work already done
* - measurements, files, copy to check - and the asking bot should
* have it, especially if the run it just queued is stopped or fails
* and nothing further comes.
*/
if (await hasOpenWork({ bot_id: job.bot_id!, session_id: answer_session_id })) return;
if (await hasOpenWork({ bot_id: job.bot_id!, session_id: answer_session_id })) {
const ack = (text || "").trim();
if (ack && !failed) {
const shared = await shareAskFiles({ ask, answer: ack });
await tellAskRequester({
ask,
text: askUpdateMessage({
ask,
text: stripQuestionRefs({ text: shared }).text,
}),
});
}
return;
}
if (failed) {
await finishAsk({
ask,
status: "failed",
outcome: "The bot it was passed to couldn't answer. Try again, or ask another bot.",
/**
* A hand-over's run is the work itself: why it failed is what
* the bot that handed it over needs to hear.
*/
outcome: isHandOverAsk({ kind: ask.kind })
? (text || "").trim() || "The run failed."
: "The bot it was passed to couldn't answer. Try again, or ask another bot.",
});
return;
@@ -0,0 +1,25 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
type Params = {
ask_id: number | string;
outcome: string;
};
/**
* Turns a request that failed too early into an answered one once a run
* that was working on it comes back with a result: the answer run can die
* after it had already queued the work, and the request must not stay
* recorded as failed when an answer exists. Only flips a `failed` row, so
* a stopped or answered request is never reopened; null when something
* else ended it in the meantime.
*/
export default async function reopenFailedAskAnswered({ ask_id, outcome }: Params): Promise<BUN_SQLITE_COBBLE_BOT_ASKS | null> {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `UPDATE bot_asks SET status = 'answered', outcome = ?, updated_at = ?
WHERE id = ? AND status = 'failed' RETURNING *`,
values: [outcome, Date.now(), Number(ask_id)],
});
return res.payload?.[0] || null;
}
@@ -0,0 +1,218 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS, BUN_SQLITE_COBBLE_BOTS, BunSQLiteTables } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { AskStages } from "@/src/dict/ask-dict";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import AppError from "@/src/utils/app-error";
import askPreviousSessionId from "@/src/utils/ask-previous-session-id";
import { truncateText } from "@/src/utils/truncate-text";
import grabActiveBotSession from "../bot-sessions/grab-active-bot-session";
import startBotSession from "../bot-sessions/start-bot-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabOpenHandOverRun from "../bots-queue/grab-open-hand-over-run";
import insertBotMessage from "../bots/insert-bot-message";
import insertUserMessage from "../bots/insert-user-message";
import grabWorkspaceName from "../workspaces/grab-workspace-name";
import askRequestMessage from "./ask-request-message";
import grabOpenAskBySession from "./grab-open-ask-by-session";
type Params = {
/**
* The user the work runs for.
*/
user_id: number | string;
/**
* The bot taking the work, and where it runs (null: its own chat).
*/
bot: BUN_SQLITE_COBBLE_BOTS;
workspace_id: number | null;
title: string;
brief: string;
/**
* The tracker task this run works, when a task is handed over.
*/
tracker_task_id?: number | null;
computer_id?: number | null;
/**
* The bot handing it over and the session it did from. None when a user
* hands a task over from the UI.
*/
requested_by_bot_id?: number | string | null;
requested_by_session_id?: number | string | null;
/**
* Who hands it over, for the line that opens the session when no
* hand-over record is made.
*/
notice: string;
task_ids?: number[];
};
export type HandOverRun = {
job_id: number;
session_id: number;
/**
* The hand-over's record (`bot_asks`, kind `hand_over`), when a bot
* handed the work over.
*/
ask_id: number | null;
};
/**
* Starts work handed to a bot the way `ask_bot`'s answer starts: in a
* session of its own (`startBotSession`), titled from the work, so it never
* lands in whatever the bot's conversation was on. When a bot handed it
* over, the session is a hand-over's (`bot_asks` with kind `hand_over`, no
* gate: the user asked for it in their own words), so its thread leads back
* to the session before it, the run (and any reply there while it is open)
* can send that bot a word with `update_requester`, its report goes back and
* wakes that bot (`onAskJobEnded`), and a late answer goes with
* `answer_requester`. Handed over from inside a crew request's answer, the
* run carries that request instead, so its result still reaches the bot
* that asked.
*/
export default async function startHandOverRun({
user_id,
bot,
workspace_id,
title,
brief,
tracker_task_id,
computer_id,
requested_by_bot_id,
requested_by_session_id,
notice,
task_ids,
}: Params): Promise<HandOverRun> {
const bot_id = Number(bot.id);
const open = await grabOpenHandOverRun({
user_id,
bot_id,
tracker_task_id,
title,
requested_by_session_id,
});
if (open) {
throw new AppError(
`${bot.name} already has "${open.title || title}" ${open.status == "pending" ? "queued" : "under way"} (run #${open.id}). Don't hand it over again; its result comes back when it ends.`,
);
}
const parent = requested_by_session_id
? await grabOpenAskBySession({ session_id: requested_by_session_id, user_id }).catch(() => null)
: null;
const previous = await grabActiveBotSession({ user_id, bot_id, workspace_id });
const session = await startBotSession({ user_id, bot_id, workspace_id });
const session_id = Number(session.id);
/**
* Titled from the work, so the sessions list says what it is before the
* bot writes anything (`nameBotSession` renames it later).
*/
await BunSQLite.sql({
sql: "UPDATE bot_sessions SET title = ? WHERE id = ? AND title IS NULL",
values: [title.slice(0, 120), session_id],
}).catch(() => null);
const requested = {
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
};
const tracker = tracker_task_id ? { tracker_task_id: Number(tracker_task_id) } : {};
if (!requested_by_bot_id || parent?.id) {
const job_id = Number(
await enqueueBotJob({
user_id,
bot_id,
session_id,
title,
instructions: brief,
params: { ...tracker, ...(parent?.id ? { ask_id: Number(parent.id) } : {}) },
computer_id: computer_id || undefined,
...requested,
}),
);
await pushBotNotice({
bot_id,
message: await insertBotMessage({ bot_id, session_id, workspace_id, text: notice, task_ids }),
});
return { job_id, session_id, ask_id: null };
}
const ask_row: BUN_SQLITE_COBBLE_BOT_ASKS = {
user_id: Number(user_id),
workspace_id: workspace_id || undefined,
requester_bot_id: Number(requested_by_bot_id),
target_bot_id: bot_id,
origin_session_id: Number(requested_by_session_id) || undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: brief.trim(), max: AppData.AskBriefMaxChars }),
status: "working",
kind: "hand_over",
session_id,
previous_session_id: askPreviousSessionId({ previous_session_id: previous?.id, session_id }) || undefined,
};
const inserted = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_ASKS, (typeof BunSQLiteTables)[number]>({
table: "bot_asks",
data: [ask_row],
});
const ask_id = Number(inserted.postInsertReturn?.insertId) || 0;
if (!inserted.success || !ask_id) {
throw new Error(`Couldn't record the hand-over: ${inserted.msg}`);
}
const ask = { ...ask_row, id: ask_id };
const message = await insertUserMessage({
bot_id,
session_id,
workspace_id,
text: askRequestMessage({ ask, requester_name: "", place: await grabWorkspaceName({ workspace_id }) }),
from_ask_id: ask_id,
});
await pushBotNotice({ bot_id, message });
let job_id: number;
try {
job_id = Number(
await enqueueBotJob({
user_id,
bot_id,
session_id,
title,
instructions: brief,
params: { ...tracker, ask_id, stage: AskStages.answer },
computer_id: computer_id || undefined,
...requested,
}),
);
} catch (error) {
/**
* Nothing will work it: the tool call fails and says why, so the
* record ends without waking anyone.
*/
await BunSQLite.sql({
sql: `UPDATE bot_asks SET status = 'failed', outcome = ?, updated_at = ? WHERE id = ?`,
values: ["It couldn't be started.", Date.now(), ask_id],
}).catch(() => null);
throw error;
}
await BunSQLite.sql({
sql: `UPDATE bot_asks SET job_id = ?, updated_at = ? WHERE id = ?`,
values: [job_id, Date.now(), ask_id],
});
return { job_id, session_id, ask_id };
}
+30 -6
View File
@@ -8,7 +8,15 @@ type Params = {
user_id: number | string;
requester_bot_id: number | string;
/**
* The sessions being stopped: the asks they made are stopped with them.
* The runs being stopped: the asks made from them are stopped with them.
* Matched by the ask's own `requester_job_id`, so a request made by an
* earlier run of the same conversation is not taken away when the user
* stops an unrelated later one.
*/
job_ids: (number | string)[];
/**
* Fallback for asks made before `requester_job_id` was recorded: the
* sessions being stopped still stop the open asks that came from them.
*/
session_ids: (number | string)[];
};
@@ -17,16 +25,32 @@ type Params = {
* Stops every request a bot made from a run the user just stopped: the ask
* ends as `stopped` (the asking bot is told, but not woken, since its run is
* the one that was stopped) and whatever run was working it is cancelled.
* A hand-over is left alone: the user asked for that work themselves, and
* stopping the bot that handed it over (often still writing its reply when
* Stop is pressed) is not stopping the work; its report still comes back.
*/
export default async function stopAsks({ user_id, requester_bot_id, session_ids }: Params) {
if (!session_ids.length) return [];
export default async function stopAsks({ user_id, requester_bot_id, job_ids, session_ids }: Params) {
if (!job_ids.length && !session_ids.length) return [];
const placeholders = session_ids.map(() => "?").join(", ");
const job_placeholders = job_ids.length ? job_ids.map(() => "?").join(", ") : "";
const session_placeholders = session_ids.length ? session_ids.map(() => "?").join(", ") : "";
const match = [
job_ids.length ? `(requester_job_id IN (${job_placeholders}))` : "",
session_ids.length ? `(requester_job_id IS NULL AND origin_session_id IN (${session_placeholders}))` : "",
]
.filter(Boolean)
.join(" OR ");
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `SELECT * FROM bot_asks WHERE user_id = ? AND requester_bot_id = ?
AND origin_session_id IN (${placeholders}) AND status IN ('pending', 'working')`,
values: [Number(user_id), Number(requester_bot_id), ...session_ids.map(Number)],
AND (${match}) AND status IN ('pending', 'working') AND COALESCE(kind, 'ask') = 'ask'`,
values: [
Number(user_id),
Number(requester_bot_id),
...job_ids.map(Number),
...session_ids.map(Number),
],
});
const stopped: BUN_SQLITE_COBBLE_BOT_ASKS[] = [];
@@ -36,13 +36,20 @@ export default async function tellAskRequester({ ask, text, wake = true }: Param
const origin = await grabUserBotSession({ session_id: ask.origin_session_id!, user_id: Number(ask.user_id)! });
/**
* The asking bot's own place: the origin's, which a hand-over from the
* coordinator's own chat into a workspace doesn't share with the request
* (`ask.workspace_id` is where the work runs).
*/
const workspace_id = origin ? Number(origin.workspace_id) || null : Number(ask.workspace_id) || null;
const session =
origin?.status == "active"
? origin
: await ensureBotSession({
user_id: Number(ask.user_id)!,
bot_id: requester.id,
workspace_id: Number(ask.workspace_id) || null,
workspace_id,
});
if (!session?.id) {
@@ -52,7 +59,7 @@ export default async function tellAskRequester({ ask, text, wake = true }: Param
const message = await insertUserMessage({
bot_id: requester.id,
session_id: session.id,
workspace_id: Number(ask.workspace_id) || null,
workspace_id: Number(session.workspace_id) || null,
text,
from_ask_id: Number(ask.id),
});
@@ -16,6 +16,12 @@ type Params = {
* What the step produced, in a line or two.
*/
summary: string;
/**
* The run finishing it, kept on the step so a report that never went out
* (a refused answer, a stop) puts the step back instead of leaving the
* card offering the next one over a step nobody delivered.
*/
job_id?: number | string;
};
/**
@@ -27,7 +33,7 @@ type Params = {
* time: a plan waiting on the user can't be worked, and neither can one
* that's paused, ended, or has nothing left.
*/
export default async function completeBotPlanStep({ plan_id, session_id, summary }: Params) {
export default async function completeBotPlanStep({ plan_id, session_id, summary, job_id }: Params) {
const row = await grabBotPlan({ plan_id });
if (Number(row.session_id) != Number(session_id)) {
@@ -58,7 +64,12 @@ export default async function completeBotPlanStep({ plan_id, session_id, summary
throw new AppError(`Every step of plan #${row.id} is already done.`);
}
steps[index] = { text: working.text, state: "done", note };
steps[index] = {
text: working.text,
state: "done",
note,
...(Number(job_id) ? { done_job_id: Number(job_id) } : {}),
};
const next = currentPlanStepIndex({ steps });
const now = Date.now();
@@ -27,7 +27,7 @@ export default async function createBotPlan({ user_id, bot_id, session_id, works
if (open) {
throw new AppError(
`There's already a plan open in this conversation (#${open.id}, "${open.title || "untitled"}"): work that one, or cancel it before writing another.`,
`There's already a plan open in this conversation (#${open.id}, "${open.title || "untitled"}"): work that one, or refine it with update_plan, or cancel it before writing another.`,
);
}
@@ -0,0 +1,45 @@
import { describe, expect, test } from "bun:test";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import { reopenWorkedPlanStep } from "./pause-failed-plan-step";
/**
* A run that finished a plan step and then never delivered its report must
* leave that step to work again, not a card showing it done and offering the
* step after it.
*/
describe("reopenWorkedPlanStep", () => {
const steps = parseBotPlanSteps({
text: JSON.stringify([
{ text: "Collect", state: "done", note: "14 pages", done_job_id: 700 },
{ text: "Score", state: "done", note: "8 kept", done_job_id: 701 },
{ text: "Write", state: "pending", note: "" },
]),
});
test("puts back the step that run finished, with its note kept", () => {
const { steps: reopened, reopened: changed } = reopenWorkedPlanStep({ steps, job_id: 701 });
expect(changed).toBe(true);
expect(reopened.map((step) => step.state)).toEqual(["done", "pending", "pending"]);
expect(reopened[1]?.note).toBe("8 kept");
/**
* The step before it, delivered by another run, is untouched.
*/
expect(reopened[0]).toEqual(steps[0]);
});
test("a run that finished no step changes nothing", () => {
const { steps: same, reopened } = reopenWorkedPlanStep({ steps, job_id: 999 });
expect(reopened).toBe(false);
expect(same).toBe(steps);
});
test("a step written before the run was recorded is left done", () => {
const older = parseBotPlanSteps({ text: JSON.stringify([{ text: "Collect", state: "done", note: "14" }]) });
const { steps: same, reopened } = reopenWorkedPlanStep({ steps: older, job_id: 700 });
expect(reopened).toBe(false);
expect(same.map((step) => step.state)).toEqual(["done"]);
});
});
@@ -1,19 +1,45 @@
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 parseBotPlanSteps, { type BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
import grabBotPlan from "./grab-bot-plan";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
};
/**
* The step one run finished, put back to pending (its note kept: the retry
* reads what the earlier attempt made). `reopened` says whether that run had
* finished a step at all, which is what lets a plan read `done` come back
* when the run that ended it never delivered its report.
*/
export function reopenWorkedPlanStep({
steps,
job_id,
}: {
steps: BotPlanStepRecord[];
job_id: number;
}): { steps: BotPlanStepRecord[]; reopened: boolean } {
const worked = steps.findIndex((step) => step.done_job_id === job_id);
const step = worked < 0 ? undefined : steps[worked];
if (!step) return { steps, reopened: false };
const next = [...steps];
next[worked] = { ...step, state: "pending" };
return { steps: next, reopened: true };
}
/**
* 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.
* stands). A step this run finished is put back with it, since the report that
* delivered it never went out. 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;
@@ -22,14 +48,30 @@ export default async function pauseFailedPlanStep({ job }: Params) {
const row = await grabBotPlan({ plan_id }).catch(() => null);
if (!row?.id || row.status != "active") return null;
if (!row?.id) return null;
if (Number(row.session_id) != Number(job.session_id)) return null;
/**
* A step this run marked done is put back before the plan pauses: its
* report never reached the user (a refused answer, a stop, a lost run),
* so the card must not show it delivered or offer the step after it. A
* plan the user ended meanwhile is left alone; `done` is reopened only
* when this very run was the one that finished the last step.
*/
const { steps, reopened } = reopenWorkedPlanStep({
steps: parseBotPlanSteps({ text: row.steps }),
job_id: Number(job.id),
});
if (row.status != "active" && !(row.status == "done" && reopened)) return null;
const now = Date.now();
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)],
sql: `UPDATE bot_plans SET steps = ?, status = 'paused', updated_at = ?
WHERE id = ? AND status IN ('active', 'done') RETURNING id`,
values: [JSON.stringify(steps), now, Number(row.id)],
});
if (!res.payload?.length) return null;
@@ -129,7 +129,7 @@ describe("postBotQuestionAnswers", () => {
expect(paused).toHaveLength(0);
});
test("any other answer to a plan's card pauses the plan and still answers", async () => {
test("any other answer to a plan's card leaves the plan where it stands and lets the reply decide", async () => {
question.plan_id = 3;
await postBotQuestionAnswers({
@@ -137,8 +137,7 @@ describe("postBotQuestionAnswers", () => {
user_id: 1,
});
expect(paused).toHaveLength(1);
expect(paused[0]!.status).toBe("paused");
expect(paused).toHaveLength(0);
expect(step_jobs).toEqual([]);
expect(enqueued).toHaveLength(1);
});
@@ -152,6 +151,7 @@ describe("postBotQuestionAnswers", () => {
});
expect(step_jobs).toEqual([]);
expect(paused).toHaveLength(1);
expect(paused).toHaveLength(0);
expect(enqueued).toHaveLength(1);
});
});
@@ -1,17 +1,15 @@
import type { BUN_SQLITE_COBBLE_BOT_QUESTIONS, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import { logError } from "@/src/functions/backend/logger";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import type { BotQuestionView } from "@/src/types";
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
import planContinueAnswer from "@/src/utils/plan-continue-answer";
import conversationLock from "../bot-sessions/conversation-lock";
import conversationLock, { conversationLockKey } from "../bot-sessions/conversation-lock";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import insertUserMessage from "../bots/insert-user-message";
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
import setBotPlanStatus from "../bot-plans/set-bot-plan-status";
import enqueuePlanStep from "../bot-plans/enqueue-plan-step";
import grabBotQuestion from "./grab-bot-question";
@@ -28,8 +26,11 @@ type Params = {
* where the question was asked, never to whichever bot's page was open.
*
* A card a plan's step ended on is the plan's own next move: Continue
* starts its next step, and anything else pauses it, so the plan never
* waits on the user to say "move on" in the chat.
* starts its next step, and anything else leaves the plan where it stands:
* the reply the answer wakes reads it and either works the step now or
* parks the plan with `update_plan`, as the words on the card say.
* Pausing it here, unseen, was how one production plan got cancelled: the
* bot woke to a plan it had to explain and read "not paused" as "ended".
*
* Best effort: a failure is logged and never undoes the answer.
*/
@@ -43,7 +44,7 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
const bot_id = Number(row.bot_id);
await conversationLock.run({
key: `${user_id}:${bot_id}:${workspace_id || 0}`,
key: conversationLockKey({ user_id, bot_id, workspace_id }),
task: async () => {
const session = await pickSession({ row, user_id });
@@ -68,18 +69,6 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
const plan_id = Number(row.plan_id) || 0;
const continue_plan = plan_id > 0 && planContinueAnswer({ view });
if (plan_id > 0 && !continue_plan) {
await setBotPlanStatus({ plan_id, user_id, status: "paused" })
.then(async () => {
await pushBotPlan({
plan_id,
session_id: Number(session.id),
bot_id,
});
})
.catch(() => null);
}
if (continue_plan) {
const step_job = await enqueuePlanStep({ plan_id }).catch(() => null);
@@ -3,9 +3,11 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import AppError from "@/src/utils/app-error";
import insertBotMessage from "../bots/insert-bot-message";
import conversationLock, { conversationLockKey } from "./conversation-lock";
import createBotSession from "./create-bot-session";
import grabActiveBotSession from "./grab-active-bot-session";
import grabUserBotSession from "./grab-user-bot-session";
import unansweredMessageSql from "./unanswered-message-sql";
type Params = {
/**
@@ -57,8 +59,27 @@ type Params = {
* session (`allow_inactive`, `next_status` closed), keeping the link to
* the routine or hook and the conversation's active session untouched.
* Returns that first message, for the caller to push.
*
* A reply's carry is refused while the user has written something that
* reply hasn't answered: closing the session now leaves their message
* behind in it while the answer goes to the new one.
*/
export default async function carryOverBotSession({
export default async function carryOverBotSession(params: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
/**
* The reply writes to the conversation like a send does, so it waits
* its turn: a message the user writes while it works lands in one
* session or the other, never in one closed under it. A routine's or a
* silent hook's own thread (`allow_inactive`, no job) moves on its own.
*/
if (!params.job_id) return await carryOverSession(params);
return await conversationLock.run({
key: conversationLockKey(params),
task: () => carryOverSession(params),
});
}
async function carryOverSession({
session_id,
user_id,
bot_id,
@@ -104,6 +125,23 @@ export default async function carryOverBotSession({
throw new AppError(`This session has no messages yet: it's already fresh.`);
}
if (job_id) {
const unanswered = unansweredMessageSql({ session_id: active.id, job_id });
const waiting = (
await BunSQLite.sql<{ unanswered: number }>({
sql: `SELECT ${unanswered.sql} AS unanswered`,
values: unanswered.values,
})
).payload?.[0]?.unanswered;
if (waiting) {
throw new AppError(
`The user wrote something this reply hasn't answered yet. Answer it in this session first, and carry the conversation over in a later reply.`,
);
}
}
const now = Date.now();
await BunSQLite.sql({
@@ -6,8 +6,18 @@ import createKeyLock from "@/src/utils/create-key-lock";
* flight together (a double submit, a retry firing beside the first) both
* read the same full session, one rolls the conversation over, and the
* other writes into the session that was just closed, where the user never
* sees it.
* sees it. A reply carrying the conversation on is one of those writes.
*/
const conversationLock = createKeyLock();
type KeyParams = {
user_id: number | string;
bot_id: number;
workspace_id?: number | null;
};
export function conversationLockKey({ user_id, bot_id, workspace_id }: KeyParams) {
return `${user_id}:${bot_id}:${workspace_id || 0}`;
}
export default conversationLock;
@@ -0,0 +1,80 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import unansweredMessageSql from "./unanswered-message-sql";
/**
* A carry must notice the user's words it would leave behind: a message
* written after the one the reply answers (or after a plan's step was
* queued) is unanswered, and the session it is in is not safe to close.
* Crew messages and the message the job answers are not the user's new
* words.
*/
const db = new Database(":memory:");
db.run(
`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT,
from_ask_id INTEGER, from_install_request_id INTEGER, created_at INTEGER)`,
);
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, message_id INTEGER, created_at INTEGER)`);
db.run(`INSERT INTO bots_queue VALUES (10, 100, 1000), (11, NULL, 2000)`);
db.run(`INSERT INTO bot_messages VALUES
(100, 5, 'user', NULL, NULL, 900),
(101, 5, 'user', NULL, NULL, 1100),
(102, 5, 'user', 3, NULL, 1200),
(103, 5, 'user', NULL, 4, 1300),
(104, 5, 'bot', NULL, NULL, 1400),
(200, 6, 'user', NULL, NULL, 2100),
(201, 6, 'bot', NULL, NULL, 2200)`);
function unanswered({ session_id, job_id }: { session_id: number; job_id: number }) {
const condition = unansweredMessageSql({ session_id, job_id });
return Boolean(
(
db.query(`SELECT ${condition.sql} AS unanswered`).get(...condition.values) as
| { unanswered: number }
| null
)?.unanswered,
);
}
describe("unansweredMessageSql", () => {
test("a message written after the one the job answers is unanswered", () => {
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(true);
});
test("the message the job answers is not", () => {
db.run(`DELETE FROM bot_messages WHERE id IN (101, 102, 103)`);
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
db.run(`INSERT INTO bot_messages VALUES
(101, 5, 'user', NULL, NULL, 1100),
(102, 5, 'user', 3, NULL, 1200),
(103, 5, 'user', NULL, 4, 1300)`);
});
test("a crew message is never the user's words", () => {
db.run(`DELETE FROM bot_messages WHERE id = 101`);
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
db.run(`INSERT INTO bot_messages VALUES (101, 5, 'user', NULL, NULL, 1100)`);
});
test("a step queued with no message counts what the user wrote after it", () => {
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(true);
db.run(`DELETE FROM bot_messages WHERE id = 200`);
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(false);
db.run(`INSERT INTO bot_messages VALUES (200, 6, 'user', NULL, NULL, 2100)`);
});
test("a job queued after the session's messages counts none of them", () => {
expect(unanswered({ session_id: 5, job_id: 11 })).toBe(false);
});
});
@@ -0,0 +1,30 @@
import type { SqlCondition } from "@/src/utils/crew-access/types";
type Params = {
/**
* The session the reply is answering in.
*/
session_id: number | string;
/**
* The reply's own job: the message it answers is `bots_queue.message_id`.
*/
job_id: number | string;
};
/**
* The SQL for a user message the reply's job hasn't answered: one written
* after the message the job answers, or, for a job queued with no message
* (a plan's step), after the job was queued. Crew messages are left out:
* they wake a bot, they aren't the user's own words. A run carrying the
* conversation on while its answer is one of these leaves it behind in the
* session it closes, unanswered.
*/
export default function unansweredMessageSql({ session_id, job_id }: Params): SqlCondition {
return {
sql: `EXISTS (SELECT 1 FROM bot_messages m JOIN bots_queue q ON q.id = ?
WHERE m.session_id = ? AND m.author = 'user'
AND m.from_ask_id IS NULL AND m.from_install_request_id IS NULL
AND (m.id > q.message_id OR (q.message_id IS NULL AND m.created_at > q.created_at)))`,
values: [Number(job_id), Number(session_id)],
};
}
@@ -17,10 +17,10 @@ type Params = {
export default async function answeringAskFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
}: Params): Promise<{ face: BotFace; status_line: string; workspace_id: number | null } | null> {
const running = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT q.id FROM bots_queue q
await BunSQLite.sql<{ id: number; workspace_id: number | null }>({
sql: `SELECT q.id, q.workspace_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`,
@@ -28,5 +28,7 @@ export default async function answeringAskFace({
})
).payload?.[0];
return running ? { face: "working", status_line: BotReplyJobTitle } : null;
return running
? { face: "working", status_line: BotReplyJobTitle, workspace_id: Number(running.workspace_id) || null }
: null;
}
@@ -5,6 +5,8 @@ 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 pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import botFaceAfterJob from "./bot-face-after-job";
type Params = {
@@ -59,5 +61,13 @@ export default async function cancelBotJob({ user_id, job_id }: Params) {
await settleInstallRequest({ job, text: BotJobCancelledError, failed: true });
/**
* Its plan pauses with it, the way a stopped or failed run's does: no
* card would ever offer the step again otherwise.
*/
const paused_plan = await pauseFailedPlanStep({ job }).catch(() => null);
if (paused_plan) await pushBotPlan(paused_plan).catch(() => null);
return job;
}
@@ -169,7 +169,13 @@ export default async function completeBotJob({
}
await BunSQLite.sql({
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
/**
* A job that failed, was retried and then answered must not stay
* marked with the old failure: the Details modal reads last_error off
* the row (job #699 shipped as "completed" beside "The model returned
* an empty answer.").
*/
sql: `UPDATE bots_queue SET result = ?, finished_at = ?, last_error = NULL WHERE id = ?`,
values: [result, now, job.id],
});
@@ -217,6 +223,7 @@ export default async function completeBotJob({
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
workspace_id: job.workspace_id || null,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
@@ -1,38 +1,16 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import openBotTaskSql from "./open-bot-task-sql";
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* Only a task with this title. Without it, any open task.
*/
title?: string;
/**
* Only a task on this computer.
*/
computer_id?: number | string | null;
};
type Params = Parameters<typeof openBotTaskSql>[0];
/**
* The bot's latest task in this session that's still queued or working
* (with this title, on this computer, when given), if any, so the same
* work isn't started twice.
* work isn't started twice. The run asking (`exclude_job_id`) is never its
* own obstacle.
*/
export default async function grabOpenBotTask({ bot_id, session_id, title, computer_id }: Params) {
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
${computer_id ? `AND computer_id = ?` : ""}
ORDER BY id DESC LIMIT 1`,
values: [
bot_id,
session_id,
...(title != undefined ? [title] : []),
...(computer_id ? [Number(computer_id)] : []),
],
});
export default async function grabOpenBotTask(params: Params) {
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>(openBotTaskSql(params));
return res.payload?.[0] || null;
}
@@ -0,0 +1,60 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
bot_id: number | string;
/**
* The tracker task being handed over: one run of it at a time, whichever
* session it opened.
*/
tracker_task_id?: number | string | null;
/**
* A new brief's title and the conversation it was handed over from: the
* same work handed over twice from there.
*/
title?: string;
requested_by_session_id?: number | string | null;
};
/**
* The bot's open run of work already handed to it, if any. Every started
* hand-over opens a session of its own, so the per-session check
* (`grabOpenBotTask`) would never see the first one: this reads every
* session of the user's with that bot.
*/
export default async function grabOpenHandOverRun({
user_id,
bot_id,
tracker_task_id,
title,
requested_by_session_id,
}: Params) {
const task_id = Number(tracker_task_id) || 0;
const from = Number(requested_by_session_id) || 0;
if (!task_id && !(title && from)) return null;
const match = [
task_id ? `json_extract(COALESCE(params, '{}'), '$.tracker_task_id') = ?` : "",
title && from ? `(requested_by_session_id = ? AND lower(trim(title)) = lower(trim(?)))` : "",
]
.filter(Boolean)
.join(" OR ");
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND kind = 'task' AND status IN ('pending', 'processing')
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ?)
AND (${match})
ORDER BY id DESC LIMIT 1`,
values: [
Number(bot_id),
Number(user_id),
Number(bot_id),
...(task_id ? [task_id] : []),
...(title && from ? [from, title] : []),
],
});
return res.payload?.[0] || null;
}
@@ -16,16 +16,16 @@ type Params = {
* The face a bot should show one user while other jobs for them are
* still running: thinking while a reply runs (it's short, and its chat
* needs the row), else working on a task (in its workspace, if it runs in
* one). Null when none is running. Work in a crew request's hidden session
* one), with the workspace of that job's conversation. Null when none is running. Work in a crew request's hidden session
* or a silent hook's thread never counts: it shows there, never on the face.
*/
export default async function grabRunningBotJobFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
}: Params): Promise<{ face: BotFace; status_line: string; workspace_id: number | null } | null> {
const jobs = (
await BunSQLite.sql<{ kind: string; workspace_name: string | null }>({
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
await BunSQLite.sql<{ kind: string; workspace_id: number | null; workspace_name: string | null }>({
sql: `SELECT q.kind, q.workspace_id, w.name AS workspace_name FROM bots_queue q
LEFT JOIN workspaces w ON w.id = q.workspace_id
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
@@ -34,11 +34,21 @@ export default async function grabRunningBotJobFace({
})
).payload || [];
if (jobs.some((job) => job.kind == "reply")) return { face: "working", status_line: BotReplyJobTitle };
const reply = jobs.find((job) => job.kind == "reply");
if (reply) {
return { face: "working", status_line: BotReplyJobTitle, workspace_id: Number(reply.workspace_id) || null };
}
const task = jobs.find((job) => job.kind == "task");
if (task) return { face: "working", status_line: taskStatusLine({ workspace_name: task.workspace_name }) };
if (task) {
return {
face: "working",
status_line: taskStatusLine({ workspace_name: task.workspace_name }),
workspace_id: Number(task.workspace_id) || null,
};
}
return null;
}
@@ -116,6 +116,7 @@ export default async function notifyBotJobFailed({
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
workspace_id: job.workspace_id || null,
})
: null;
@@ -0,0 +1,60 @@
import { Database } from "bun:sqlite";
import { beforeEach, describe, expect, test } from "bun:test";
import openBotTaskSql from "./open-bot-task-sql";
const db = new Database(":memory:");
beforeEach(() => {
db.run(`CREATE TABLE IF NOT EXISTS bots_queue (
id INTEGER PRIMARY KEY,
status TEXT,
kind TEXT,
bot_id INTEGER,
session_id INTEGER,
computer_id INTEGER,
title TEXT
)`);
db.run(`DELETE FROM bots_queue`);
});
function insert(row: { id: number; status: string; title?: string; computer_id?: number }) {
db.run(
`INSERT INTO bots_queue (id, status, kind, bot_id, session_id, computer_id, title) VALUES (?, ?, 'task', 3, 95, ?, ?)`,
[row.id, row.status, row.computer_id ?? 1, row.title ?? "Fix baseline"],
);
}
function found(params: Partial<Parameters<typeof openBotTaskSql>[0]>) {
const query = openBotTaskSql({ bot_id: 3, session_id: 95, ...params });
return (db.query(query.sql).all(...query.values) as { id: number }[]).map((row) => row.id);
}
describe("openBotTaskSql", () => {
test("finds the open run on the computer", () => {
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1 })).toEqual([680]);
});
test("a task run handing work on is not its own obstacle (jobs 680, 700)", () => {
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([]);
expect(found({ title: "Fix baseline", exclude_job_id: 680 })).toEqual([]);
});
test("another open run still counts when the asking run is left out", () => {
insert({ id: 679, status: "pending" });
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([679]);
});
test("finished runs and other computers never count", () => {
insert({ id: 1, status: "completed" });
insert({ id: 2, status: "processing", computer_id: 2 });
expect(found({ computer_id: 1 })).toEqual([]);
});
});
@@ -0,0 +1,45 @@
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* Only a task with this title. Without it, any open task.
*/
title?: string;
/**
* Only a task on this computer.
*/
computer_id?: number | string | null;
/**
* The run asking: a task run handing its work on is not the open run
* that work would wait behind. Without it, a task report's `send_reply`
* with `work` was refused against its own job (jobs 680 and 700), and a
* finished report was thrown away.
*/
exclude_job_id?: number | string | null;
};
/**
* The bot's latest task in this session that's still queued or working
* (with this title, on this computer, when given), leaving out the run
* that asks.
*/
export default function openBotTaskSql({ bot_id, session_id, title, computer_id, exclude_job_id }: Params) {
const exclude = Number(exclude_job_id) || 0;
return {
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
${computer_id ? `AND computer_id = ?` : ""}
${exclude ? `AND id != ?` : ""}
ORDER BY id DESC LIMIT 1`,
values: [
bot_id,
session_id,
...(title != undefined ? [title] : []),
...(computer_id ? [Number(computer_id)] : []),
...(exclude ? [exclude] : []),
],
};
}
@@ -7,6 +7,8 @@ import type {
import insertBotMessage from "../bots/insert-bot-message";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import { AskStages } from "@/src/dict/ask-dict";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -34,6 +36,12 @@ export default async function relayJobToRequester({ job, text, failed, task_ids
return null;
}
/**
* A hand-over's run is its request's answer: `onAskJobEnded` reports it
* back (and wakes the bot that handed it over), so it isn't told twice.
*/
if (parseJobJson({ text: job.params })?.stage == AskStages.answer) return null;
const worker = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOTS>({
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
@@ -1,7 +1,12 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
worker: string;
/**
* The handler's family (`AppData.BotQueueWorker`), not its own id: the id
* carries the process's pid, so a restart releases what the previous
* process of this install was running.
*/
family: string;
};
/**
@@ -9,12 +14,12 @@ type Params = {
* instead of waiting out the lock timeout. For startup, after a restart
* cut those jobs off. The cut-off attempt isn't counted.
*/
export default async function releaseWorkerBotJobs({ worker }: Params) {
export default async function releaseWorkerBotJobs({ family }: Params) {
const now = Date.now();
const res = await BunSQLite.sql({
sql: `UPDATE bots_queue SET status = 'pending', attempts = MAX(attempts - 1, 0), available_at = ?, locked_at = NULL, locked_by = NULL, updated_at = ? WHERE status = 'processing' AND locked_by = ? RETURNING id`,
values: [now, now, worker],
sql: `UPDATE bots_queue SET status = 'pending', attempts = MAX(attempts - 1, 0), available_at = ?, locked_at = NULL, locked_by = NULL, updated_at = ? WHERE status = 'processing' AND (locked_by = ? OR locked_by LIKE ?) RETURNING id`,
values: [now, now, family, `${family}-%`],
});
return res.payload?.length || 0;
@@ -13,9 +13,12 @@ import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import stopAsk from "../asks/stop-ask";
import stopAsks from "../asks/stop-asks";
import grabAsk from "../asks/grab-ask";
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
import settleInstallRequest from "../install-requests/settle-install-request";
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import attachJobTracesToMessage from "./attach-job-traces-to-message";
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
import withMessageUsage from "../usage/with-message-usage";
@@ -126,6 +129,15 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
await recordHookCallResponse({ job: stopped, status: "failed", response: BotJobStoppedError, now });
/**
* A plan whose step this run was working pauses with it, the way a
* failed run's does (`notifyBotJobFailed`): nothing else would ever
* advance it, and the card would show that step running for ever.
*/
const paused_plan = await pauseFailedPlanStep({ job: stopped }).catch(() => null);
if (paused_plan) await pushBotPlan(paused_plan).catch(() => null);
/**
* A coordinator stopped on an install request: the worker that
* asked is told.
@@ -187,19 +199,44 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
}
for (const ask_id of ask_ids) {
/**
* When the answer run already finished, the request isn't left
* silent: its acknowledgement went back as an update (with the
* files and anything it asked to check), so the stopped reason
* tells the asker that what it already has stands and only the
* queued work is gone. A stopped answer run means there truly is
* no answer.
*/
const ask = await grabAsk({ ask_id }).catch(() => null);
const answered =
!!ask?.job_id &&
!!(
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue WHERE id = ? AND status = 'completed' LIMIT 1`,
values: [Number(ask.job_id)],
}).catch(() => null)
)?.payload?.length;
await stopAsk({
ask_id,
reason: "The user stopped the run answering it, so there is no answer.",
reason: answered
? "The user stopped the work it had queued before it finished. Anything it had already answered stands."
: "The user stopped the run answering it, so there is no answer.",
}).catch(() => null);
}
/**
* And the requests a run of its own had open go with it: its bot isn't
* woken about work the user just stopped.
* woken about work the user just stopped. Matched by the run that made
* each request, so stopping one run never ends an ask another run of
* the same conversation is waiting on; asks made before that was
* recorded keep the old session match.
*/
await stopAsks({
user_id,
requester_bot_id: bot_id,
job_ids: jobs.map((job) => Number(job.id)),
session_ids: open.map((job) => Number(job.session_id)),
}).catch(() => []);
@@ -236,9 +273,23 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
if (answered) continue;
/**
* The session this run's conversation is in now, not the one it was
* queued in: a reply that carried the conversation into a new session
* between the UPDATE above and here would put the stopped line in a
* thread the user has left, and the live conversation would show
* nothing.
*/
const current = (
await BunSQLite.sql<{ session_id: number | null }>({
sql: `SELECT session_id FROM bots_queue WHERE id = ?`,
values: [Number(job.id)],
}).catch(() => null)
)?.payload?.[0]?.session_id;
const message = await insertBotMessage({
bot_id: Number(bot_id),
session_id,
session_id: Number(current || session_id),
workspace_id: job.workspace_id || null,
text: stoppedJobReport({ job }),
}).catch(() => null);
@@ -8,15 +8,20 @@ type Params = {
/**
* A bot's face and status line as one user sees it: idle when it has
* none for them.
* none for them, and the workspace of the conversation that set it
* (`face_workspace_id`, null for its own chat).
*/
export default async function grabBotFace({ bot_id, user_id }: Params) {
const row = (
await BunSQLite.sql<{ face: BotFace; status_line: string }>({
sql: `SELECT face, status_line FROM bot_user_faces WHERE bot_id = ? AND user_id = ? LIMIT 1`,
await BunSQLite.sql<{ face: BotFace; status_line: string; workspace_id: number | null }>({
sql: `SELECT face, status_line, workspace_id FROM bot_user_faces WHERE bot_id = ? AND user_id = ? LIMIT 1`,
values: [bot_id, user_id],
})
).payload?.[0];
return { face: (row?.face || "idle") as BotFace, status_line: row?.status_line || "" };
return {
face: (row?.face || "idle") as BotFace,
status_line: row?.status_line || "",
face_workspace_id: Number(row?.workspace_id) || null,
};
}
@@ -0,0 +1,25 @@
import BunSQLite from "@moduletrace/bun-sqlite";
/**
* Faces set before `bot_user_faces.workspace_id` existed say nothing of the
* chat they came from, so a bot that needed the user in a workspace linked
* to its own chat from the coordinator's Crew tab. A face that needs the
* user or shows work takes the workspace of that bot's latest job for that
* user. Faces set since then carry their own; one whose latest job was in
* the bot's own chat stays null, so running it again changes nothing.
*/
export default async function migrateFaceWorkspaces() {
const res = await BunSQLite.sql({
sql: `UPDATE bot_user_faces SET workspace_id = (
SELECT q.workspace_id FROM bots_queue q
JOIN bot_sessions s ON s.id = q.session_id
WHERE q.bot_id = bot_user_faces.bot_id AND s.user_id = bot_user_faces.user_id
ORDER BY q.id DESC LIMIT 1
)
WHERE workspace_id IS NULL AND face IN ('needs-you', 'working')`,
});
if (!res.success) {
throw new Error(`Couldn't place the existing bot faces: ${res.error}`);
}
}
+15 -6
View File
@@ -9,6 +9,12 @@ type Params = {
user_id: number | string;
face: BotFace;
status_line?: string;
/**
* The workspace of the conversation the job is in, null for the bot's
* own chat: where the coordinator's Crew list links a bot that needs
* the user or is working.
*/
workspace_id?: number | string | null;
};
export type BotFaceChange = {
@@ -16,27 +22,30 @@ export type BotFaceChange = {
user_id: number;
face: BotFace;
status_line: string;
workspace_id: number | null;
};
/**
* Sets a bot's face (its status) and status line as one user sees it
* (`bot_user_faces`). Other users keep their own. Callers must check the
* bot first.
* bot first. A face set without `workspace_id` reads as the bot's own chat.
*/
export default async function setBotFace({
bot_id,
user_id,
face,
status_line = "",
workspace_id = null,
}: Params): Promise<BotFaceChange> {
const now = Date.now();
const place = Number(workspace_id) || null;
await BunSQLite.sql({
sql: `INSERT INTO bot_user_faces (created_at, updated_at, bot_id, user_id, face, status_line)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET face = excluded.face, status_line = excluded.status_line, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, face, status_line],
sql: `INSERT INTO bot_user_faces (created_at, updated_at, bot_id, user_id, face, status_line, workspace_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET face = excluded.face, status_line = excluded.status_line, workspace_id = excluded.workspace_id, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, face, status_line, place],
});
return { id: Number(bot_id), user_id: Number(user_id), face, status_line };
return { id: Number(bot_id), user_id: Number(user_id), face, status_line, workspace_id: place };
}
@@ -11,7 +11,10 @@ type Params = {
pinned_ids?: number[];
};
type ModelRow = BUN_SQLITE_COBBLE_HARNESS_MODELS & { provider_name?: string };
type ModelRow = BUN_SQLITE_COBBLE_HARNESS_MODELS & {
provider_name?: string;
provider_kind?: string;
};
export type HarnessModelEntry = {
row: ModelRow;
@@ -31,7 +34,7 @@ export default async function grabHarnessModelEntries({
const rows =
(
await BunSQLite.sql<ModelRow>({
sql: `SELECT m.*, p.name AS provider_name FROM harness_models m
sql: `SELECT m.*, p.name AS provider_name, p.kind AS provider_kind FROM harness_models m
JOIN harness_providers p ON p.id = m.provider_id
WHERE (m.available = 1 AND p.enabled = 1)
${ids.length ? `OR m.id IN (${ids.map(() => "?").join(", ")})` : ""}
@@ -57,6 +60,14 @@ export default async function grabHarnessModelEntries({
input_modalities: model.input_modalities,
supported_parameters: model.supported_parameters,
context_length: model.context_length,
/**
* Only OpenRouter's catalog says what a model takes; every
* other provider is listed by id and guessed from its name
* (`guessModelModalities`, via `list-models.ts`). Said on the
* option so the picker can warn about a text model pinned
* from a list that never said it calls tools.
*/
capabilities_guessed: row.provider_kind != "openrouter",
},
};
});
@@ -25,7 +25,7 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
) as number[];
const [bot, workspace, computers] = await Promise.all([
BunSQLite.sql<{ name: string }>({ sql: `SELECT name FROM bots WHERE id = ?`, values: [proposal.bot_id] }),
BunSQLite.sql<{ name: string; kind: string | null }>({ sql: `SELECT name, kind FROM bots WHERE id = ?`, values: [proposal.bot_id] }),
proposal.workspace_id
? BunSQLite.sql<{ name: string }>({ sql: `SELECT name FROM workspaces WHERE id = ?`, values: [proposal.workspace_id] })
: null,
@@ -56,6 +56,8 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
current,
workspace_name: workspace?.payload?.[0]?.name || null,
computers: new Map((computers?.payload || []).map((c) => [Number(c.id), c.name || ""])),
bot_id: proposal.bot_id,
bot_kind: bot.payload?.[0]?.kind || null,
}),
reason: proposal.reason,
};
@@ -0,0 +1,40 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type {
BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS,
BUN_SQLITE_COBBLE_MEDIA,
} from "@/db/types/db";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import grabUserTypes from "../users/grab-user-types";
type Params = {
media_id: number | string;
user_id: number | string;
};
/**
* A knowledgebase document's own file (its private `media` row) for a crew
* manager, the same people Settings > Knowledgebases shows its documents
* to, so "Open original" loads it.
*/
export default async function grabKnowledgebaseDocumentMedia({
media_id,
user_id,
}: Params): Promise<BUN_SQLITE_COBBLE_MEDIA | null> {
const document = (
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS, "id">>({
sql: `SELECT id FROM knowledgebase_documents WHERE media_id = ? LIMIT 1`,
values: [Number(media_id)],
})
).payload?.[0];
if (!document?.id) return null;
if (!canManageCrew({ user_types: await grabUserTypes({ user_id }) })) return null;
const media = await BunSQLite.sql<BUN_SQLITE_COBBLE_MEDIA>({
sql: `SELECT * FROM media WHERE id = ? LIMIT 1`,
values: [Number(media_id)],
});
return media.payload?.[0] || null;
}
@@ -5,7 +5,7 @@ type Params = {
document: {
source?: string | null;
content?: string | null;
media_id?: number | null;
media_id?: number | string | null;
name?: string | null;
mime_type?: string | null;
};
@@ -18,11 +18,12 @@ type Params = {
export default async function grabKnowledgebaseDocumentText({ document }: Params) {
if (document.source == "text") return document.content || "";
if (!document.media_id) return "";
const media_id = Number(document.media_id) || 0;
if (!media_id) return "";
const media = await BunSQLite.sql<{ media_write_path?: string; text_content?: string }>({
sql: `SELECT media_write_path, text_content FROM media WHERE id = ? LIMIT 1`,
values: [document.media_id],
values: [media_id],
}).then((res) => res.payload?.[0]);
return (
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS } from "@/db/types/db";
import type { KnowledgebaseDocumentsPayload } from "@/src/types";
import grabInstallEmbeddingModel from "./grab-install-embedding-model";
import grabKnowledgebase from "./grab-knowledgebase";
import { KnowledgebaseDocumentIndexingSql } from "./knowledgebase-document-indexing-sql";
import parseKnowledgebaseDocumentRow from "./parse-knowledgebase-document-row";
@@ -10,7 +11,8 @@ type Params = {
};
/**
* A knowledgebase's documents, newest first, without their text.
* A knowledgebase's documents, newest first, without their text, and the
* install's embedding model for their lines.
*/
export default async function listKnowledgebaseDocuments({
knowledgebase_id,
@@ -18,7 +20,7 @@ export default async function listKnowledgebaseDocuments({
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & { indexing?: number }>({
sql: `SELECT id, knowledgebase_id, name, source, mime_type, size, chunk_count, embedding_model,
sql: `SELECT id, knowledgebase_id, name, source, media_id, mime_type, size, chunk_count, embedding_model,
ingested_at, ingest_error, created_at, ${KnowledgebaseDocumentIndexingSql} AS indexing
FROM knowledgebase_documents d WHERE knowledgebase_id = ? ORDER BY id DESC`,
values: [knowledgebase.id],
@@ -27,5 +29,6 @@ export default async function listKnowledgebaseDocuments({
return {
knowledgebase_id: knowledgebase.id,
documents: (rows.payload || []).map((row) => parseKnowledgebaseDocumentRow({ row })),
embedding_model: await grabInstallEmbeddingModel(),
};
}
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS } from "@/db/types/db";
import parseKnowledgebaseDocumentRow from "./parse-knowledgebase-document-row";
const parse = ({ media_id }: { media_id?: unknown }) =>
parseKnowledgebaseDocumentRow({
row: {
id: 1,
knowledgebase_id: 2,
name: "notes.md",
source: "file",
media_id,
} as BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS,
});
describe("parseKnowledgebaseDocumentRow", () => {
test("carries the file's media row, which Open original loads", () => {
expect(parse({ media_id: 12 }).media_id).toBe(12);
});
test("has no media row for a written document or a missing one", () => {
expect(parse({ media_id: undefined }).media_id).toBeNull();
expect(parse({ media_id: "" }).media_id).toBeNull();
});
});
@@ -18,6 +18,7 @@ export default function parseKnowledgebaseDocumentRow({ row }: Params): Knowledg
knowledgebase_id: Number(row.knowledgebase_id),
name: row.name || "",
source: row.source == "text" ? "text" : "file",
media_id: Number(row.media_id) || null,
mime_type: row.mime_type || "",
size: Number(row.size) || 0,
chunk_count: Number(row.chunk_count) || 0,
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_MEDIA, BunSQLiteTables } from "@/db/types/db";
import grabSharedPictureMedia from "@/src/functions/backend/db/access/grab-shared-picture-media";
import grabBotFileMedia from "@/src/functions/backend/db/bot-files/grab-bot-file-media";
import grabKnowledgebaseDocumentMedia from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase-document-media";
import grabTaskMediaFile from "@/src/functions/backend/db/tasks/grab-task-media-file";
type Params = {
@@ -20,7 +21,9 @@ type Params = {
* - a bot's or workspace's file, to whoever reaches the folder it lives in
* (`grabBotFileMedia`),
* - a file attached to a task, to whoever reaches the task
* (`grabTaskMediaFile`).
* (`grabTaskMediaFile`),
* - a knowledgebase document's file, to crew managers
* (`grabKnowledgebaseDocumentMedia`).
*
* Null when it is not theirs to see, so a request never turns into a path
* before this has passed.
@@ -51,6 +54,7 @@ export default async function grabUserMedia({
(await grabSharedPictureMedia({ media_id })) ||
(await grabBotFileMedia({ media_id, user_id })) ||
(await grabTaskMediaFile({ media_id, user_id })) ||
(await grabKnowledgebaseDocumentMedia({ media_id, user_id })) ||
undefined
);
}
+2 -2
View File
@@ -53,7 +53,7 @@ type Params = {
*/
statuses?: string[];
/**
* Only the open ones (todo, doing, blocked).
* Only the open ones (todo, doing, blocked, paused).
*/
open_only?: boolean;
limit?: number;
@@ -136,7 +136,7 @@ export default async function grabTasks({
LEFT JOIN workspaces w ON w.id = t.workspace_id
LEFT JOIN tasks p ON p.id = t.parent_task_id
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY CASE t.status WHEN 'blocked' THEN 0 WHEN 'doing' THEN 1 WHEN 'todo' THEN 2 WHEN 'done' THEN 3 ELSE 4 END,
ORDER BY CASE t.status WHEN 'blocked' THEN 0 WHEN 'doing' THEN 1 WHEN 'todo' THEN 2 WHEN 'paused' THEN 3 WHEN 'done' THEN 4 ELSE 5 END,
t.updated_at DESC, t.id DESC
${limit ? `LIMIT ${Number(limit)}` : ""}`,
values: [...face.values, ...OpenTaskStatuses, ...values],
@@ -4,9 +4,8 @@ import AppError from "@/src/utils/app-error";
import handOverPlace from "@/src/utils/hand-over-place";
import grabUserConversation from "../bot-sessions/grab-user-conversation";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabOpenBotTask from "../bots-queue/grab-open-bot-task";
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import startHandOverRun from "../asks/start-hand-over-run";
import grabOpenHandOverRun from "../bots-queue/grab-open-hand-over-run";
import grabBotById from "../bots/grab-bot-by-id";
import insertBotMessage from "../bots/insert-bot-message";
import grabBotComputers from "../computers/grab-bot-computers";
@@ -64,6 +63,10 @@ export type HandedOverTask = {
* The job doing the work; null when it wasn't started.
*/
job_id: number | string | null;
/**
* The session the run opened; null when it wasn't started.
*/
session_id: number | null;
bot_name: string;
workspace_id: number | null;
/**
@@ -79,9 +82,13 @@ export type HandedOverTask = {
* it to be worked, so by default it only moves: the task goes to the new
* bot's list as to do, no job is queued and the notice says so. With
* `start` true (the user asked for the work to begin now) the task goes to
* doing, its log says who handed it over, and a job is queued in the new
* bot's conversation with the task's brief and `params.tracker_task_id`, so
* the bot moves this same task along and the job's end is noted on it.
* doing, its log says who handed it over, and a job is queued with the
* task's brief and `params.tracker_task_id`, so the bot moves this same task
* along and the job's end is noted on it. That run gets a session of its own
* (`startHandOverRun`), as a crew request's answer does: handed over by a
* bot, its report goes back to that bot and the run can send it a word on
* the way. A task that only moves leaves its notice in the conversation the
* new bot is in, since nothing runs yet.
*/
export default async function handOverTask({
user_id,
@@ -122,13 +129,12 @@ export default async function handOverTask({
* The user must reach the bot there: its own chat, or the workspace.
*/
const conversation = await grabUserConversation({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const title = (task.title || "Task").slice(0, 80);
const open = start ? await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title }) : null;
const open = start ? await grabOpenHandOverRun({ user_id, bot_id: bot.id, tracker_task_id: task.id }) : null;
if (open) {
throw new AppError(
`${bot.name} already has "${title}" ${open.status == "pending" ? "queued" : "under way"} (job #${open.id}).`,
`${bot.name} already has "${title}" ${open.status == "pending" ? "queued" : "under way"} (run #${open.id}).`,
);
}
@@ -147,28 +153,22 @@ export default async function handOverTask({
.filter(Boolean)
.join("\n\n");
/**
* When the hand-over comes from a crew request being answered, the run
* carries the ask_id too, so its result goes back to the bot that asked.
*/
const ask =
start && requested_by_session_id
? await grabOpenAskBySession({ session_id: requested_by_session_id, user_id })
: null;
const job_id = start
? await enqueueBotJob({
const run = start
? await startHandOverRun({
user_id,
bot_id: bot.id,
session_id: Number(session.id),
bot,
workspace_id: run_workspace_id,
title,
instructions: brief,
params: { tracker_task_id: Number(task.id), ...(ask?.id ? { ask_id: Number(ask.id) } : {}) },
computer_id: computers[0]?.id || undefined,
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
brief,
tracker_task_id: Number(task.id),
computer_id: computers[0]?.id || null,
requested_by_bot_id,
requested_by_session_id,
notice: `${handed_by} handed me task #${task.id}: **${title}**`,
task_ids: [Number(task.id)],
})
: null;
const job_id = run?.job_id ?? null;
const status = start ? "doing" : "todo";
await updateTask({
@@ -185,20 +185,25 @@ export default async function handOverTask({
bot_id: requested_by_bot_id || null,
});
await pushBotNotice({
bot_id: bot.id,
message: await insertBotMessage({
if (!start) {
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
await pushBotNotice({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**${start ? "" : ". It's on my list; I'll start when you say."}`,
task_ids: [Number(task.id)],
}),
});
message: await insertBotMessage({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**. It's on my list; I'll start when you say.`,
task_ids: [Number(task.id)],
}),
});
}
return {
task: { ...moved, status },
job_id,
session_id: run?.session_id ?? null,
bot_name: conversation.bot.name || bot.name || "The bot",
workspace_id: run_workspace_id,
joined,
+12 -3
View File
@@ -58,7 +58,7 @@ export default async function generateImage({
if (has_references && !ordered.length && image.length) {
throw new HarnessError({
message: `None of the image models here takes reference images. A super admin can pick one under Image editing in Settings, under Models.`,
message: `None of the image models here takes reference images. A super admin can pick one under Image editing in Settings, under Models, or turn Image editing's fallback on to send the call to a generation model that takes them.`,
code: "unavailable",
});
}
@@ -107,7 +107,9 @@ export default async function generateImage({
}
/**
* Image editing's setting and candidates, or undefined while it's off.
* Image editing's setting and candidates. Turned off still reports its
* fallback, so a call with references can hand over to a generation model
* that takes images (with fallback off it never leaves the harness).
*/
async function grabEdit({
bot_id,
@@ -118,7 +120,14 @@ async function grabEdit({
}) {
const setting = await grabHarnessSetting({ harness: "image_edit", bot_id, workspace_id });
if (!setting.enabled) return undefined;
if (!setting.enabled) {
/**
* Turned off still hands its fallback flag down: a call with
* references may go to a generation model that takes images, but only
* while fallback is on, or it would leave the harness quietly.
*/
return { picked: false, fallback: setting.fallback, candidates: [] };
}
return {
picked: Boolean(setting.model_id),
@@ -0,0 +1,43 @@
/**
* The shapes providers use when their own content filter refused the
* request (Alibaba's Model Studio: "Input text data may contain
* inappropriate content.", code `data_inspection_failed`; Azure's
* `content_filter`; OpenAI's usage-policy refusals).
*/
const ContentFilterPhrases = [
"inappropriate content",
"data_inspection_failed",
"data inspection failed",
"content_filter",
"content filter",
"content management policy",
"content_policy_violation",
"content policy",
"responsibleaipolicyviolation",
"violates our usage polic",
"flagged by our moderation",
];
type Params = {
status: number;
/**
* The provider's own words, already read out of its error body.
*/
detail?: string;
};
/**
* Whether the provider's content filter refused the call. The flagged text
* is somewhere in the run's transcript (often a page or a tool's output,
* not the user's request), so retrying the same transcript is refused the
* same way: job 698 lost 41 turns to it. A refusal is a 4xx; a filter that
* is down ("content safety screening is temporarily unavailable", a 503) is
* an outage, and stays retryable.
*/
export default function isContentFilterError({ status, detail }: Params) {
if (status < 400 || status >= 500) return false;
const text = (detail || "").toLowerCase();
return ContentFilterPhrases.some((phrase) => text.includes(phrase));
}
@@ -47,6 +47,7 @@ const chat: HarnessAdapter["chat"] = async ({
provider_name:
provider.name || grabProviderPreset({ kind: provider.kind }).title,
candidate_key: candidate.key,
url: res.url,
});
};
@@ -1,7 +1,7 @@
import HarnessError from "../../harness-error";
import toHarnessError from "../to-harness-error";
import type { HarnessChatResult, HarnessToolCall } from "../../types";
import readReasoning from "./read-reasoning";
import redactProviderError from "../redact-provider-error";
type WireToolCall = {
id?: string;
@@ -15,6 +15,10 @@ type Params = {
json: any;
provider_name: string;
candidate_key?: string;
/**
* Where the call went, so a refusal names the address it came from.
*/
url?: string;
};
/**
@@ -25,15 +29,22 @@ export default function readChatResponse({
json,
provider_name,
candidate_key,
url,
}: Params): HarnessChatResult {
if (json?.error) {
const status = Number(json.error.code) || undefined;
throw new HarnessError({
message: `${provider_name}: ${redactProviderError({ text: json.error.message || "The model failed." })}`,
status,
retryable: !status || status == 429 || status >= 500,
/**
* Built by the classifier, not by hand: a 200 carrying an error body
* skipped `toHarnessError` whole, so an oversized request read as a
* plain refusal that benched nothing and re-fired on every turn (52
* failed rows, one task limping through its fallbacks for 18 minutes).
* Overflow, a dead key and the provider's own words are decided there.
*/
throw toHarnessError({
status: Number(json.error.code) || 400,
body: JSON.stringify({ error: json.error }),
provider_name,
candidate_key,
url,
});
}
@@ -187,4 +187,32 @@ describe("toHarnessError", () => {
expect(error.fatal).toBe(false);
expect(error.message).not.toContain("Settings > Models");
});
test("a provider's content filter refusing the run is fatal and says so (job 698)", () => {
const error = toHarnessError({
status: 400,
body: JSON.stringify({
error: { code: "data_inspection_failed", message: "Input text data may contain inappropriate content." },
}),
provider_name: "Alibaba Cloud Token Plan",
url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions",
});
expect(error.fatal).toBe(true);
expect(error.retryable).toBe(false);
expect(error.message).toContain("Input text data may contain inappropriate content.");
expect(error.message).toContain("content filter refused this run");
expect(error.message).toContain("not necessarily your message");
});
test("a content filter that is down is an outage, never a refusal", () => {
const error = toHarnessError({
status: 503,
body: JSON.stringify({ error: { message: "content safety screening is temporarily unavailable" } }),
provider_name: "Nvidia Cloud",
});
expect(error.fatal).toBe(false);
expect(error.retryable).toBe(true);
});
});
+14 -4
View File
@@ -1,5 +1,6 @@
import HarnessError from "../harness-error";
import isContextOverflowError from "./is-context-overflow-error";
import isContentFilterError from "./is-content-filter-error";
import parseRetryAt from "./parse-retry-at";
import redactProviderError from "./redact-provider-error";
@@ -66,17 +67,26 @@ export default function toHarnessError({
*/
const overflow = isContextOverflowError({ status, detail: provider_detail });
/**
* The provider's content filter refused something in the transcript:
* the same transcript is refused again on every retry, so the run stops
* here and says plainly that it was the provider's filter (job 698).
*/
const filtered = !overflow && isContentFilterError({ status, detail: provider_detail });
const advice = overflow
? "\nSet this model's context window under Settings > Models: a model with none declared is assumed to have 1,000,000."
: "";
: filtered
? `\n${provider_name}'s content filter refused this run: something in the conversation or what its tools read was flagged, not necessarily your message. Run it again with a narrower request, or use a model from another provider under Settings > Models.`
: "";
const retryable = [408, 409, 425, 429].includes(status) || status >= 500;
const retryable = !filtered && ([408, 409, 425, 429].includes(status) || status >= 500);
return new HarnessError({
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow ? 320 : 400)}${advice}`,
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow || filtered ? 320 : 400)}${advice}`,
status,
retryable,
fatal: overflow,
fatal: overflow || filtered,
retry_at: retryable && headers ? parseRetryAt({ headers }) : undefined,
provider_wide: status == 401 || status == 402,
candidate_key,
+8 -3
View File
@@ -14,8 +14,13 @@ import type { HarnessCooldowns } from "./create-cooldowns";
*/
const slot = globalCache<HarnessCooldowns>({ name: "cobble.harnessCooldowns" });
const HarnessCooldowns = slot.get() || createCooldowns();
/**
* Not named `HarnessCooldowns`: the type of that name is imported above, and
* an `export default` of a name both declare resolves to the type for some
* compilers, so every importer of this value is then called a type-only import.
*/
const cooldowns = slot.get() || createCooldowns();
slot.set(HarnessCooldowns);
slot.set(cooldowns);
export default HarnessCooldowns;
export default cooldowns;
@@ -101,6 +101,25 @@ export default async function resolveHarnessCandidates({
modelServesHarness({ model: entry, harness }),
);
/**
* A pick that can't run is not "no model set up": with fallback off the
* call would otherwise answer on a free automatic pick while the setting
* names a model, and the usage row would say `auto` (this is how a pinned
* tool-less model ran eleven replies and none of them closed).
*/
if (setting.model_id && !pinned && !setting.fallback) {
const title = Harnesses.find((h) => h.value == harness)?.title;
const slug = rows.find((row) => row.id == setting.model_id)?.slug;
throw new HarnessError({
message:
`${slug || "The picked model"} can't be used for ${title ? title.toLowerCase() : harness} ` +
`(it's unavailable, its provider isn't usable, or it doesn't serve this harness), and fallback is off. ` +
`Pick a model that serves it under Models, or turn fallback on.`,
code: "unavailable",
});
}
/**
* Each fallback model names its own provider, so the setting's
* provider limit doesn't apply to them.
+34 -3
View File
@@ -165,7 +165,26 @@ export default async function withCandidates<T>({
return { result, candidate };
} catch (error: unknown) {
if (!(error instanceof HarnessError)) throw error;
if (!(error instanceof HarnessError)) {
/**
* A bug in an adapter is not swallowed (it goes up as it is),
* but it stops being invisible: with no row the message's
* Details modal showed nothing at all for the call that ended
* the run.
*/
if (log_failures) {
await recordHarnessFailure({
harness: harness_of?.get(candidate.key) || harness,
candidate,
error: new HarnessError({
message: error instanceof Error ? error.message : String(error),
candidate_key: candidate.key,
}),
});
}
throw error;
}
if (error.code == "aborted") throw error;
/**
* A fatal failure is the run's own: another model fails the same
@@ -229,7 +248,13 @@ export default async function withCandidates<T>({
}
}
const last = errors[errors.length - 1];
/**
* The error worth reading, not simply the last one: a dead key on the
* first candidate and a 400 on the second left the bot told its user the
* request was bad, when the provider's key was the whole story.
*/
const last =
errors.find((error) => error.provider_wide || error.fatal) || errors[errors.length - 1];
if (!last) {
const next = soonestRest({ candidates: ordered, cooldowns, now: now() });
@@ -369,7 +394,13 @@ function coolDown({
return at;
}
if (error.status == 403 || error.status == 404) {
/**
* A 405 says the path isn't there at all (`toHarnessError` calls it a
* missing endpoint), so another turn on the same base URL answers the
* same way: benched like a 404, or a wrong base URL is paid for on every
* turn, forever.
*/
if (error.status == 403 || error.status == 404 || error.status == 405) {
cooldowns.set({ key: candidate.key, at: until });
return until;
}
+13 -2
View File
@@ -37,7 +37,10 @@ export type GenerateTextParams = {
*/
limits?: HarnessCallLimits;
/**
* Overrides the saved generation settings (media reading wants 0).
* Overrides the saved generation settings (media reading wants 0). Sent as
* given: `prepareMessagesForModel` and `readImage` build their own call, and
* anything passed here must already be keys the candidate advertises, since
* this path does not filter them the way `grabChatParams` does.
*/
params?: HarnessWireParams;
signal?: AbortSignal;
@@ -146,8 +149,16 @@ export default async function generateText({
: { text: "", reasoning: null };
if (!stripped.text && !answer.tool_calls.length) {
/**
* Named for what happened: a thinking model whose content came
* back empty or all inline tags reaches here, and "an empty
* answer" sent a bot to explain a model it had just been
* charged for (job 699 attempt 1).
*/
throw new HarnessError({
message: `The model returned an empty answer.`,
message: answer.reasoning || stripped.reasoning
? `The model answered with only its thinking: no message and no tool call.`
: `The model returned an empty answer.`,
retryable: true,
candidate_key: candidate.key,
});
+159 -1
View File
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, closingToolGoneNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, StoppedRunNote, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, closingToolGoneNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyCardFailedNote, replyClosingFailedNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, StoppedRunNote, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { HarnessTrace } from "../trace/types";
@@ -2202,6 +2202,164 @@ describe("runTextLoop required send_reply", () => {
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingRequiredNote });
});
test("a card the tool refused beside a good send_reply names the card, not send_reply", async () => {
/**
* Job 699: `send_reply` returned ok and `suggest_next_steps` refused a
* step over its length cap. The note said "send_reply did not go
* through", so the model spent three turns re-writing a message that
* had already shipped, and the trace logged closing_failed against the
* wrong tool.
*/
const cappedSteps: HarnessTool<{ steps: string[] }> = {
name: "suggest_next_steps",
description: "Offers the next steps as buttons.",
schema: z.object({
steps: z.array(z.string().max(AppData.BotSuggestionStepMaxChars, "Keep each step under 120 characters")),
}),
run: async ({ args }) => {
suggested.push(...args.steps);
return "Suggested. The buttons are under your message.";
},
};
const long_step =
"Summarise every tab open in the browser on the computer, name the ones you think are stale, and tell me which I can close today.";
expect(long_step.length).toBeGreaterThan(AppData.BotSuggestionStepMaxChars);
const { generate, seen } = scripted([
{
text: "Nine tabs are open.",
tool_calls: [
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
{ id: "c1", name: "suggest_next_steps", arguments: JSON.stringify({ steps: [long_step] }) },
],
},
{
text: "Nine tabs are open.",
tool_calls: [
{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` },
{ id: "c2", name: "suggest_next_steps", arguments: `{"steps":["Close the extras"]}` },
],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "What's open?" }],
tools: [sendReply, cappedSteps],
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(seen[1]!.messages.at(-1)).toMatchObject({
role: "user",
content: replyCardFailedNote({ tools: ["suggest_next_steps"] }),
});
expect(result.text).toBe("Nine tabs are open.");
expect(result.tool_uses).toEqual([
{ name: "send_reply", ok: true },
{ name: "suggest_next_steps", ok: false },
{ name: "send_reply", ok: true },
{ name: "suggest_next_steps", ok: true },
]);
});
test("a send_reply that failed is still blamed, even beside a failed card", async () => {
const failingSend: HarnessTool<{ status?: string }> = {
name: "send_reply",
description: "Sends the message.",
schema: z.object({ status: z.string().optional() }),
run: async () => {
throw new Error('Status "working" needs work queued in the call.');
},
};
const refusedSteps: HarnessTool<{ steps: string[] }> = {
name: "suggest_next_steps",
description: "Offers the next steps as buttons.",
schema: z.object({ steps: z.array(z.string()) }),
run: async () => {
throw new Error("Keep each step under 120 characters");
},
};
const { generate, seen } = scripted([
{
text: "I'm on it.",
tool_calls: [
{ id: "s1", name: "send_reply", arguments: `{"status":"working"}` },
{ id: "c1", name: "suggest_next_steps", arguments: `{"steps":["Look again"]}` },
],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Check the browser." }],
tools: [failingSend, refusedSteps],
generate,
resolveCandidates,
require_closing_answer: true,
});
/**
* Both closing calls failed, so the message never went out and the old
* note is the right one: it names send_reply, which is what has to be
* fixed. Only a card failing on its own takes the new note.
*/
expect(seen[1]!.messages.at(-1)!.content).toBe(replyClosingFailedNote);
expect(result.text).toBe("");
});
/**
* Job 694: the first turn wrote the message beside an `ask_user` whose
* options were objects, the second passed the questions as a string,
* and the third put the card up with no text. The model was told
* send_reply had failed (it was never called), the message from turn
* one was lost, and the run failed with the card finally up.
*/
test("a refused card is blamed on the card, keeps its message, and the run gets to close once it goes up", async () => {
let card_calls = 0;
const pickyAsk: HarnessTool<{ options: string[] }> = {
name: "ask_user",
description: "Asks the user.",
schema: z.object({ options: z.array(z.string()) }),
run: async () => {
card_calls++;
return "Asked. The card is on your message.";
},
};
const { generate, seen } = scripted([
{
text: "Two decisions before I generate.",
tool_calls: [{ id: "a1", name: "ask_user", arguments: `{"options":[{"label":"Crop"},{"label":"Keep"}]}` }],
},
{ tool_calls: [{ id: "a2", name: "ask_user", arguments: `{"options":"[\\"Crop\\",\\"Keep\\"]"}` }] },
{ tool_calls: [{ id: "a3", name: "ask_user", arguments: `{"options":["Crop","Keep"]}` }] },
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Harden the prompt." }],
tools: [sendReply, pickyAsk],
generate,
resolveCandidates,
require_closing_answer: true,
});
const told = seen[1]!.messages.at(-1)!.content as string;
expect(told).not.toBe(replyClosingFailedNote);
expect(told).toContain("The card was not put up");
expect(told).toContain("ask_user");
expect(card_calls).toBe(1);
expect(seen).toHaveLength(4);
expect(result.review_note).toBeUndefined();
expect(result.text).toBe("Two decisions before I generate.");
});
test("send_reply with no message beside it is told once", async () => {
const { generate, seen } = scripted([
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
+83 -6
View File
@@ -12,6 +12,8 @@ import {
oversizedRequestNote,
repairedAnswerNote,
repeatedAnswerNote,
replyCardFailedNote,
replyCardOnlyFailedNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
@@ -668,6 +670,20 @@ export default async function runTextLoop({
* nothing left to say.
*/
let card_text = "";
/**
* The message a turn wrote beside a card the tool refused. It isn't the
* reply yet (it points at a card no one can see), but it is the sentence
* the card belongs under: once a later turn puts the card up, it becomes
* `card_text`. Job 694 wrote it on its first turn, fixed the card's
* arguments twice, and then had nothing left to send.
*/
let failed_card_text = "";
/**
* A card call was refused earlier in this run. When the card then goes
* up, the run has made progress, so it gets one more turn for
* `send_reply` instead of failing on the retries the refusals used up.
*/
let card_refused = false;
/**
* A run whose prompt no longer fits the working context, with nothing
* trimmable left, has been told, once (`oversizedRequestNote`).
@@ -1088,6 +1104,13 @@ export default async function runTextLoop({
* ends).
*/
if (wrap_up_saving && answer.tool_calls.length && !tool_calls.length) {
/**
* Traced before the note, like the stray-call turn below: the run
* did call these, and a debug view that skipped the turn showed a
* wrap up with nothing in it.
*/
await traceTurn({ index, answer, calls: answer.tool_calls, started_at: turn_started_at });
pushUserTurn({
transcript,
content: `Only ${wrap_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
@@ -1272,6 +1295,7 @@ export default async function runTextLoop({
*/
draft_text = "";
card_text = "";
failed_card_text = "";
told_closing_text = false;
continue;
}
@@ -1490,8 +1514,33 @@ export default async function runTextLoop({
* to ask again, which the once-per-run guard refuses, and the same
* note looped for the whole budget (H1).
*/
const closing_uses = tool_uses.slice(-tool_calls.length).filter((use) => isClosingTool({ name: use.name }));
const closing_failed = closing_uses.some((use) => !use.ok);
const closing_uses = (tool_calls.length ? tool_uses.slice(-tool_calls.length) : []).filter((use) =>
isClosingTool({ name: use.name }),
);
const failed_closing = closing_uses.filter((use) => !use.ok);
const closing_failed = failed_closing.length > 0;
/**
* Which closing call failed decides the note. A card the tool refused
* (`suggest_next_steps` over its length cap) is not `send_reply`
* failing: its message is kept, and telling the model the send did not
* go through sent it re-writing the answer for nothing (job 699, three
* turns and a `closing_failed` trace against the wrong tool).
*/
const send_reply_failed = failed_closing.some((use) => use.name === SendReplyToolName);
const failed_cards = failed_closing.filter((use) => use.name !== SendReplyToolName).map((use) => use.name);
/**
* A card refused in a turn with no `send_reply` is the card's
* failure, not the send's: telling the model "send_reply did not go
* through" there hid the schema error it had to fix (job 694, three
* turns on `ask_user`'s options).
*/
const closing_failed_note = send_reply_failed
? replyClosingFailedNote
: called_send_reply
? replyCardFailedNote({ tools: failed_cards })
: require_closing_answer
? replyCardOnlyFailedNote({ tools: failed_cards })
: closingFailedNote;
const closing_worked = closing && !closing_failed && closing_required;
/**
* The message this turn wrote beside the call. An earlier draft is
@@ -1519,6 +1568,35 @@ export default async function runTextLoop({
* and pairing it with "Which date rule?" put "I checked the date
* rules." under it.
*/
const card_went_up = asked_something && closing && !closing_failed;
/**
* A refused card keeps the message written beside it for the turn
* that puts the card up; a turn that drops the card (no card call)
* never gets it, since it pointed at a card that isn't there.
*/
if (asked_something && closing_failed && written_text) {
failed_card_text = written_text;
}
if (card_went_up && !written_text && !card_text.trim() && failed_card_text.trim()) {
card_text = failed_card_text;
}
if (card_went_up) failed_card_text = "";
/**
* The card is up after refusals spent the retries: one more turn for
* `send_reply`, since the run made the progress the bound is there to
* demand (job 694 put its card up on the third try and then failed).
*/
if (card_went_up && card_refused && !called_send_reply) {
closing_retries = Math.min(closing_retries, AppData.MaxClosingRetries - 1);
card_refused = false;
}
if (asked_something && closing_failed) card_refused = true;
const carry_card = Boolean(card_text.trim()) && !unfinishedAnswerText({ text: card_text });
const carry_draft =
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
@@ -1544,7 +1622,7 @@ export default async function runTextLoop({
return {
text: "",
review_note: closing_failed
? replyClosingFailedNote
? closing_failed_note
: !closing
? replyClosingMixedNote
: replyClosingRequiredNote,
@@ -1572,9 +1650,7 @@ export default async function runTextLoop({
closing_retries++;
const note = closing_failed
? called_send_reply || require_closing_answer
? replyClosingFailedNote
: closingFailedNote
? closing_failed_note
: !closing
? called_send_reply
? replyClosingMixedNote
@@ -1705,6 +1781,7 @@ export default async function runTextLoop({
*/
draft_text = "";
card_text = "";
failed_card_text = "";
told_closing_text = false;
continue;
}
@@ -0,0 +1,89 @@
import { describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
/**
* `answer_requester` closes the gap where a request's answer session is
* resumed after the request ended: the finished or corrected answer goes
* straight back to the bot that asked, on the ended request's own record,
* instead of a fresh `ask_bot` the gate reads as a new handoff. It shares
* the answer's files, strips question refs, refuses while the request is
* still open (the machinery relays that itself), and only for the bot the
* request was passed to.
*/
let ask: BUN_SQLITE_COBBLE_BOT_ASKS | null;
let shared: string[] = [];
let told: Array<{ text: string }> = [];
const signal = new AbortController().signal;
mock.module("@/src/functions/backend/db/asks/grab-ask", () => ({
default: async () => ask,
}));
mock.module("@/src/functions/backend/db/asks/share-ask-files", () => ({
default: async ({ answer }: { answer: string }) => {
shared.push(answer);
return answer;
},
}));
mock.module("@/src/functions/backend/db/asks/tell-ask-requester", () => ({
default: async ({ text }: { text: string }) => {
told.push({ text });
return { session_id: 56, message: { id: 900 } };
},
}));
const answerRequesterTool = (await import("./answer-requester-tool")).default;
const endedAsk = {
id: 24,
status: "answered",
title: "Sample blog post banner",
target_bot_id: 8,
requester_bot_id: 6,
} as BUN_SQLITE_COBBLE_BOT_ASKS;
describe("answerRequesterTool", () => {
test("a late answer goes back on the ended request and wakes the asker", async () => {
ask = endedAsk;
shared = [];
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
const res = await tool.run({ args: { text: "Banner finished: [file:389]." }, signal });
expect(shared).toEqual(["Banner finished: [file:389]."]);
expect(told.length).toBe(1);
expect(told[0]?.text).toContain("Banner finished: [file:389].");
expect(told[0]?.text).toContain("had already ended");
expect(String(res)).toContain("Sent to the bot that asked");
});
test("an open request is refused: its answer goes back on its own", async () => {
ask = { ...endedAsk, status: "working" };
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
await expect(tool.run({ args: { text: "Here." }, signal })).rejects.toThrow("still open");
expect(told).toEqual([]);
});
test("only the bot the request was passed to can answer it back", async () => {
ask = endedAsk;
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 9, ask_id: 24 });
await expect(tool.run({ args: { text: "Here." }, signal })).rejects.toThrow("didn't answer that request");
expect(told).toEqual([]);
});
test("a stopped request can still be answered late", async () => {
ask = { ...endedAsk, status: "stopped" };
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
await tool.run({ args: { text: "Finished after all." }, signal });
expect(told.length).toBe(1);
});
});
@@ -0,0 +1,83 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import grabAsk from "@/src/functions/backend/db/asks/grab-ask";
import askUpdateMessage from "@/src/functions/backend/db/asks/ask-update-message";
import shareAskFiles from "@/src/functions/backend/db/asks/share-ask-files";
import tellAskRequester from "@/src/functions/backend/db/asks/tell-ask-requester";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import type { HarnessTool } from "../../types";
type Params = {
user_id: number | string;
/**
* The bot answering: only the bot the request was passed to may send
* its answer back.
*/
bot_id: number | string;
/**
* The ended request this conversation answered, found by the caller
* through `grabEndedAskBySession`.
*/
ask_id: number | string;
/**
* What the run typed, run through the run's secret redaction before it
* is stored: the answer lands in another bot's conversation, where a
* raw env value would sit in a message forever.
*/
redact?: (text: string) => string;
};
type Args = {
text: string;
};
/**
* The gap `ask_bot` kept falling into: the request ended (often `blocked`,
* or stopped), the user carries on in the answer session and gets the work
* done, and the bot's only way back to the asking bot was a brand-new
* request - which the gate reads as a fresh handoff and can refuse, leaving
* the asker never told. This tool posts the finished answer straight back to
* the conversation the request came from, on the ended request's own record
* (`from_ask_id`, with its files shared), and wakes the asking bot. It ends
* nothing and reopens nothing: the request's row keeps the status it ended
* with, and the message says plainly it arrived after the end.
*/
export default function answerRequesterTool({ user_id, bot_id, ask_id, redact = (text) => text }: Params): HarnessTool<Args> {
return {
name: "answer_requester",
description: `Send the bot that asked you a late or corrected answer to the request this conversation answered - after that request had already ended (blocked, stopped or answered). It lands in the conversation the request came from, shares any files it names, and wakes that bot. Use this instead of ask_bot for finishing what that request asked: a new request goes through the coordinator again and reads as a different handoff. Your ordinary answer here is the message; this tool is only for getting it back to the bot that asked.`,
schema: z.object({
text: z
.string()
.trim()
.min(1)
.max(AppData.AskBriefMaxChars)
.describe(`The answer (markdown): what you finished, with [file:ID] refs for what you produced`),
}),
run: async ({ args }) => {
const ask = await grabAsk({ ask_id, user_id });
if (!ask?.id) {
throw new Error(`That request isn't here anymore.`);
}
if (ask.status == "pending" || ask.status == "working") {
throw new Error(
`This request is still open: your answer goes back on its own when your work ends, and update_requester sends a word meanwhile.`,
);
}
if (Number(ask.target_bot_id) != Number(bot_id)) {
throw new Error(`This conversation didn't answer that request, so it has no answer to send back.`);
}
const shared = stripQuestionRefs({
text: await shareAskFiles({ ask, answer: redact(args.text) }),
}).text;
await tellAskRequester({ ask, text: askUpdateMessage({ ask, text: shared, ended: true }) });
return `Sent to the bot that asked, on "${ask.title}" [ask:${ask.id}]. Its conversation wakes for it.`;
},
};
}
+7 -1
View File
@@ -20,6 +20,11 @@ type Params = {
* Where it works: in a workspace, only its members can be asked.
*/
workspace_id?: number | string | null;
/**
* The run asking, recorded on the ask so stopping that run ends this
* request and no other ask from the same conversation.
*/
job_id?: number | string | null;
};
type Args = {
@@ -37,7 +42,7 @@ type Args = {
* call, never the model's: in a workspace its members, otherwise every worker
* the user reaches.
*/
export default function askBotTool({ user_id, bot_id, session_id, workspace_id }: Params): HarnessTool<Args> {
export default function askBotTool({ user_id, bot_id, session_id, workspace_id, job_id }: Params): HarnessTool<Args> {
return {
name: "ask_bot",
description: `Ask another bot for something you need (what it knows, a file it has, work in its line). The coordinator reads every request first: it passes it to the bot that should answer, sends it to a better-placed bot, or turns it down with the reason. An approved request's answer comes back here as a message, which wakes you to act on it: don't wait or check on it. If a task you'd start needs the answer, don't start it in the same reply: it would run without it, so start it once the answer wakes you. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
@@ -104,6 +109,7 @@ export default function askBotTool({ user_id, bot_id, session_id, workspace_id }
target_bot_id: named?.id || askable[0]!.id!,
title: args.title,
request,
requester_job_id: job_id,
});
return `Asked ${named ? `${named.name} [bot:${named.id}]` : "the crew"} (ask #${ask.id}). The coordinator reads it first; its outcome comes back here as a message and you'll be woken for it. Tell the user you asked; don't ask again while it's open.`;
@@ -59,7 +59,7 @@ export default function continueInNewSessionTool({
return {
name: "continue_in_new_session",
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line.`,
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line. If the user wrote something while you worked, answer that here first: the conversation only moves once everything they said is answered.`,
schema: z.object({
summary: z
.string()

Some files were not shown because too many files have changed in this diff Show More