Compare commits

...
40 Commits
Author SHA1 Message Date
tben 037119c1df Bump version to 0.28.16
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
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
tben 1aa5fc4a05 Bump version to 0.28.10
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 11:39:05 +01:00
tben afdfad1ecf Read a worker's computer folder through its agent
Since worker bots got their own accounts, a worker's computer folder is
owned by cb-<bot> (2770) and a dev server running as a plain user can't
open it: the files browser treated the folder as missing, so a folder
chip said it may have been moved or deleted. Production runs as root and
never saw it.

When this process is denied a folder on the computers volume, list it
through the computer's agent instead (find as root, NUL-separated, no
symlinks), and stream its files from /api/files/download. The path
rules, size cap and computerPathAllowed check stay the same, and every
other volume reads the host exactly as before.
2026-11-25 11:38:00 +01:00
tben 5087f115e7 Trace a dropped last turn and let it answer once more
Job 687 finished a report and called a tool the last turn no longer
offers: the loop dropped the turn untraced and failed with a notice
blaming the review, which had never run.

The dropped turn and its calls are now traced, a closing_failed event
says what happened, and the model gets one more turn with send_reply
alone before the run gives up. The notice says the tool was gone
instead of that the answer failed the review.
2026-11-25 11:32:08 +01:00
tben 7816affdc8 Name the image model that ran and stop after one timeout 2026-11-25 11:14:10 +01:00
tben 6b048c5b4f Stop a run where it is and have it say what it did
Stop used to kill the job and post a fixed line. Now the run this process
is on is asked to stop at its step and write what it did so far, with only
send_reply offered (StoppedRunNote), and that message is the session's last
word with the run's calls and traces on it. The job completes as stopped:
idle face, no work of its own left running, no crew request or hand-over
answered.

stopBotJobs waits AppData.BotStopSummaryMs (20s, so Bun.serve's idleTimeout
is 30 in production) for that summary, then fails what is still open and
posts the plain stopped line with its run info attached, so a stop never
leaves the thread thinking. A run in another process, or one whose summary
is refused, gets the plain line the way it did before.
2026-11-25 11:04:58 +01:00
tben da304e000b Open the add-provider form in a modal 2026-11-25 10:36:51 +01:00
tben ee4af467b3 Bump version to 0.28.9
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 10:02:24 +01:00
tben b2c8a788da Ask for a routine's or hook's brief as the plan its run follows
Routines and hook calls never plan at run time, so the tools that make or
change one ask for the instructions as the steps in order, each naming what
it produces.
2026-11-25 09:59:04 +01:00
tben d38a15862a Never plan in routines or hooks, follow a carried session, and open the previous one as its own page
Routines and hook calls already have their plan (the brief, the runbook), so
they get neither the plan tools nor the planning turn, and the approve/in_run
paths those runs needed are gone.

A live conversation now follows its session into a newer one, from the push or
from the catch-up read that reports it, instead of waiting on the old thread
and showing "No answer came."; a page opened on an old session keeps its bar
and hides that row.

The thread's "Show the previous session" opens that session as its own page
instead of paging it inline.
2026-11-25 09:49:33 +01:00
tben e8b59997ac Keep ref pills their own colour in the user bubble
The bubble-wide link rule outranked a pill's text-ink, so chips with links
turned blue. Exclude links inside a ref chip's quote wrapper.
2026-11-25 09:39:38 +01:00
tben 7919bb39b8 Autofocus the all-bots search and restore the user bubble link colour 2026-11-25 09:35:06 +01:00
tben fcfc6874a8 Add session slash commands to the composer
/new starts a fresh session, /continue carries the conversation into a new one with a summary, and /clear deletes this session and starts a fresh one after a confirm. Up and Down walk the list, Enter runs the highlighted command, and a click fills it in first; a failed command comes back in the input with the server's reason.
2026-11-25 09:35:06 +01:00
tben e538ca029f Let members read the bot's instructions and memory in its panel
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 08:24:16 +01:00
tben f66c97448f Let members open the bot panel and keep their own memory about them
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Members read a bot's role and instructions, rewrite what it remembers about
them, and see its tools read-only; the stone and the name open the panel for
everyone. Also comments out the user bubble link colour.
2026-11-25 07:41:17 +01:00
tben 98948c559c Reload into the new build when a stale page sends a message
A page left open across a deploy kept sending from code the server no
longer serves. The root now puts the running build in a cobble-build meta
tag, the composer sends the build it was loaded from, and the send route
refuses an older one with stale_build before storing or queueing anything.
The composer keeps the typed text and uploaded attachments in the draft
and reloads, so the new build picks them up and the user sends again.
2026-11-25 07:30:35 +01:00
tben bab6683295 v0.28.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 07:00:02 +01:00
tben 1757311262 Tell a bot who it's working for, and show user ids in the People list
A bot asked a member to confirm their identity because no run's prompt
ever carried the user's name; it had guessed one from the workspace name.
Every run now gets a who-you're-working-for section from grabUserName
(first and last, else username), and each row on Settings > Users ends
with the user's id.
2026-11-25 06:59:22 +01:00
tben d4469e6848 Give every provider its generation settings, not just OpenRouter
Only OpenRouter's /models says what each model takes, so every other provider's models carried no supported_parameters and the settings page hid temperature, effort and the rest. A provider now declares them (its saved pick, else its preset's list, else its host's: Alibaba's Token Plan hosts included) and the sync writes them into every model that reports none of its own. Reasoning effort goes flat as reasoning_effort outside OpenRouter, where the nested form was ignored, and thinking on/off goes as a boolean.
2026-11-25 06:55:07 +01:00
tben 15a74cacde v0.28.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:52:19 +01:00
tben 67395500b5 Show a person's and a bot's picture at the size it is set up at
A picture preview was drawn whatever the size asked for, so setting up a
photo meant judging a thumbnail. BotAvatar passes its size through to the
image, UserAvatar gains xl and xxl, and the profile photo and the bot form's
preview use them.
2026-11-25 04:52:19 +01:00
tben 95c8ee7c39 v0.28.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:37:37 +01:00
tben edd451342e Give the routine form's brief room to read 2026-11-25 04:37:37 +01:00
tben b635eeb543 Keep the hook form's buttons from being clipped away by the modal 2026-11-25 04:36:05 +01:00
tben 4cadde55e2 Size the bot form's preview picture from the form
The preview takes an avatar size, so the new-bot form shows it at 100px
rather than the 56px it uses in a list.
2026-11-25 04:32:23 +01:00
tben e000b09898 Let a user delete a chat session
The sessions modal now deletes a session and everything in it, refused
while a run is open in it. Deleting the active one gives the conversation
a fresh session instead of leaving it pointing at a removed one, and the
list rows truncate their summary to the row's width.
2026-11-25 04:32:19 +01:00
tben 4852c39ad3 Scope a workspace run to its workspace
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A bot working in a workspace could reach every task in every other
workspace it belongs to, and every routine and hook it has anywhere.
botTaskScopesSql now takes the run's workspace and reaches only its
tasks: a coordinator or that workspace's admin all of them, a worker its
own and the workspace-wide ones there. grabTasks, grabRunTask and every
task tool pass it through, and create_task refuses to place a task in
another workspace from inside one.

Routines and hooks follow the same rule through the existing place
filters: list, update, delete, pause, search and read are narrowed to the
run's workspace, the coordinator's list showing every bot's there. A run
in the bot's own chat keeps its old reach, and update/delete schedule
keep no place filter when the run has none, since null there means "own
chat only".

v0.28.3
2026-11-25 03:52:51 +01:00
tben bf533330b1 Hold the drawer's computer preview until asked, and tell SSH computers apart
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
The Tools section streamed a bot's computer screen the moment the drawer
opened. It now shows the same block with a line and a Preview button, and
streams only once that is clicked.

Also show the bot's memory of the viewer in the drawer's settings tab, space
the panel fields so their labels stop overlapping, and draw an SSH computer
with a server icon instead of the container's monitor.
2026-11-24 16:50:51 +01:00
255 changed files with 6436 additions and 1162 deletions
+15 -15
View File
File diff suppressed because one or more lines are too long
+14
View File
@@ -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`,
@@ -673,6 +678,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
indexName: "idx_bot_messages_session_id_created_at",
indexTableFields: ["session_id", "created_at"],
},
{
indexName: "idx_bot_messages_carried_from_session_id",
indexTableFields: ["carried_from_session_id"],
},
{
indexName: "idx_bot_messages_reply_to_message_id",
indexTableFields: ["reply_to_message_id"],
@@ -3237,6 +3246,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
dataType: "INTEGER",
},
{
fieldName: "parameters",
fieldDescription: `JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none`,
dataType: "TEXT",
},
{
fieldName: "last_synced_at",
fieldDescription: `Unix timestamp of the last model list sync`,
+9 -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
*/
@@ -579,7 +583,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
*/
@@ -2009,6 +2013,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
*/
context_length?: number | "";
/**
* JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none
*/
parameters?: string;
/**
* Unix timestamp of the last model list sync
*/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.1",
"version": "0.28.16",
"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)`);
+40 -7
View File
@@ -4,18 +4,36 @@
* is waiting on (a model that never answers, a tool that hangs) instead of
* leaving it to find out on its next heartbeat, which can take minutes.
*
* Only the process running a job can abort it, so this is a bonus: the job
* is already failed in `bots_queue`, and a handler in another process
* Only the process running a job can abort it, so this is a bonus: a job
* that stops has already been asked to, and a handler in another process
* learns that on its next `updateBotJob`. Kept free of imports so the API
* routes can use it without pulling the queue handler into a page bundle.
*/
const running = new Map<number, () => void>();
type Entry = {
abort: () => void;
/**
* Stops the run where it is and leaves it one turn to say what it did
* (`StoppedRunNote`), instead of dropping its work.
*/
stop_summary?: () => void;
};
const running = new Map<number, Entry>();
/**
* Called by a handler once it holds a job, with the way to abort it.
* Called by a handler once it holds a job, with the way to abort it and to
* let it summarize what it did first.
*/
export function registerJobAbort({ job_id, abort }: { job_id: number | string; abort: () => void }) {
running.set(Number(job_id), abort);
export function registerJobAbort({
job_id,
abort,
stop_summary,
}: {
job_id: number | string;
abort: () => void;
stop_summary?: () => void;
}) {
running.set(Number(job_id), { abort, stop_summary });
}
/**
@@ -30,7 +48,7 @@ export function unregisterJobAbort({ job_id }: { job_id: number | string }) {
* it, so the row's new status is how it finds out.
*/
export function abortRunningJob({ job_id }: { job_id: number | string }) {
const abort = running.get(Number(job_id));
const abort = running.get(Number(job_id))?.abort;
if (!abort) return false;
@@ -38,3 +56,18 @@ export function abortRunningJob({ job_id }: { job_id: number | string }) {
return true;
}
/**
* Asks a job running here to stop at its next step and write what it did so
* far. False means it runs in another process, or not at all: the plain
* stopped message is what the user gets then.
*/
export function requestJobStopSummary({ job_id }: { job_id: number | string }) {
const stop_summary = running.get(Number(job_id))?.stop_summary;
if (!stop_summary) return false;
stop_summary();
return true;
}
+18
View File
@@ -60,6 +60,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();
});
+15 -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,7 @@ 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.`;
}
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 "${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.`
: `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 "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
}
+25 -1
View File
@@ -86,12 +86,27 @@ export default async function processBotJob({
const hook_id = Number(params.hook_id) || null;
const controller = new AbortController();
/**
* The user's Stop, which is not a cancellation: the run stops at its
* step and writes what it did so far, and that message is posted instead
* of the app's plain stopped line (`stop-bot-jobs` waits
* `AppData.BotStopSummaryMs` for it).
*/
const stop_controller = new AbortController();
let stop_requested = false;
/**
* Registered before the first read below: those queries can wait on a
* busy database, and a Stop that arrived while they ran found nothing
* to abort, so a stopped job went on running until its own next write.
*/
registerJobAbort({ job_id, abort: () => controller.abort() });
registerJobAbort({
job_id,
abort: () => controller.abort(),
stop_summary: () => {
stop_requested = true;
stop_controller.abort();
},
});
/**
* Its face changes only for the user it works for.
@@ -280,6 +295,7 @@ export default async function processBotJob({
params,
checkpoint: parseJobJson({ text: job.checkpoint }),
signal: run_signal,
stop_signal: stop_controller.signal,
update,
report,
trace,
@@ -319,6 +335,7 @@ export default async function processBotJob({
task_ids: outcome.task_ids,
plan_id: outcome.plan_message_id,
exhausted: outcome.exhausted,
stopped: stop_requested,
});
await pushBotNotice({ bot_id, ...completion });
@@ -363,6 +380,13 @@ export default async function processBotJob({
} catch (error: unknown) {
if (controller.signal.aborted) return;
/**
* A stopped run that couldn't write its summary leaves the job open:
* `stop-bot-jobs` fails it and posts the plain stopped line when its
* wait runs out, so a stop is never turned into a retryable failure.
*/
if (stop_requested) return;
/**
* Every model is cooling down (rate limits): nothing was tried, so
* wait for the first to come back without using an attempt.
+90 -11
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";
@@ -89,6 +92,7 @@ import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-f
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";
@@ -135,6 +139,7 @@ export default async function runBotReply({
user_id,
job,
signal,
stop_signal,
report,
trace,
}: Params): Promise<BotJobOutcome> {
@@ -195,6 +200,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
@@ -361,6 +373,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.
@@ -393,6 +422,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({
@@ -546,6 +586,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,
}),
]
: []),
@@ -593,11 +644,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,
}),
@@ -617,7 +670,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
@@ -668,24 +738,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,
@@ -731,6 +809,7 @@ export default async function runBotReply({
bot_id: bot.id,
workspace_id,
signal,
stop_signal,
onStep: report,
trace,
incoming,
@@ -816,7 +895,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 -38
View File
@@ -15,7 +15,6 @@ import {
ConnectorsNote,
ComputerFilesNote,
ScheduledRunNote,
ScheduledPlanNote,
HookRunNote,
InstallRequestNote,
TasksNote,
@@ -30,6 +29,9 @@ import {
taskPlanNote,
wrapUpWorktreeNote,
PlanStepNote,
PlanActiveNote,
PlanPausedNote,
OpenTasksNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -40,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";
@@ -75,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";
@@ -138,6 +144,7 @@ export default async function runBotTask({
job,
params,
signal,
stop_signal,
report,
trace,
}: Params): Promise<BotJobOutcome> {
@@ -283,11 +290,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 +380,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 +417,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 +503,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,
}),
@@ -489,22 +563,6 @@ export default async function runBotTask({
job_id: job.id || null,
onGraphic: ({ ref }) => shown.push(ref),
}),
/**
* A routine's plan is approved at once and worked through in
* the run, since nobody is there to approve it on a card
* (`ScheduledPlanNote`). A hook call gets none: its thread is a
* log of calls, not a conversation to read a plan in.
*/
...(scheduled && session_id
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
approve: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
];
extensions = await openBotExtensions({
@@ -654,17 +712,33 @@ export default async function runBotTask({
const system = [
prompt,
carry_over,
TaskRunNote,
TaskRunNote({ can_ask }),
steps_note,
scheduled ? ScheduledRunNote : "",
scheduled ? ScheduledPlanNote : "",
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
@@ -721,9 +795,10 @@ export default async function runBotTask({
* a step (`planBotTask`). It shares this run's prompt, so it costs
* little more than the plan, and it saves the steps a long run
* spends finding out what it is doing. A run whose plan can't be
* written starts the way it always did.
* written starts the way it always did. A routine or a hook call
* already has its plan (the brief, the runbook), so it works that.
*/
const planned = shouldPlanBotTask({ max_steps })
const planned = !scheduled && !hooked && shouldPlanBotTask({ max_steps })
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
(error) => {
if (signal.aborted) throw error;
@@ -788,6 +863,7 @@ export default async function runBotTask({
bot_id: bot.id,
workspace_id,
signal,
stop_signal,
onStep: (step) =>
report({ ...step, text: step.text ? redact_text(step.text) : step.text }),
/**
@@ -839,7 +915,7 @@ 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 });
}),
/**
* A report goes out only through `send_reply`, so it can't say
@@ -910,7 +986,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.
+8
View File
@@ -17,6 +17,14 @@ export type BotJobContext = {
* work and return; the result is discarded.
*/
signal: AbortSignal;
/**
* Aborted when the user stops this run from the chat. Unlike `signal`
* the job is not cancelled: the run stops at the step it is on and
* writes what it did so far (`StoppedRunNote`), which is posted as the
* run's message. `stop-bot-jobs` gives it
* `AppData.BotStopSummaryMs` before the plain stopped line goes out.
*/
stop_signal: AbortSignal;
/**
* Save progress and a checkpoint. The lock is renewed on a timer
* already, so call this for meaningful steps. False once the job is
+7 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { closingNoTextNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import unsentAnswerMessage from "./unsent-answer-message";
/**
@@ -23,6 +23,12 @@ describe("unsentAnswerMessage", () => {
);
});
test("a last turn that called a tool it no longer had says so", () => {
expect(unsentAnswerMessage({ note: closingToolGoneNote })).toBe(
`The run's last turn called a tool it no longer had, so its message wasn't sent.`,
);
});
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.`,
+5 -1
View File
@@ -1,4 +1,4 @@
import { closingNoTextNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
type Params = {
/**
@@ -25,5 +25,9 @@ export default function unsentAnswerMessage({ note }: Params) {
return `The reply ended as a draft instead of a sent message, so it wasn't sent.`;
}
if (note === closingToolGoneNote) {
return `The run's last turn called a tool it no longer had, so its message wasn't sent.`;
}
return `The answer didn't hold up against the app's record, so it wasn't sent.`;
}
+6 -1
View File
@@ -31,7 +31,11 @@ type Props = ComponentProps<typeof BotStone> & {
* never a circle, so it isn't mistaken for a person), else its stone. Its
* colour still marks it everywhere else, e.g. the unread dot.
*/
export default function BotAvatar({ image_media_id, src: picked, ...stone }: Props) {
export default function BotAvatar({
image_media_id,
src: picked,
...stone
}: Props) {
const saved = profileImageUrls({ media_id: image_media_id });
const thumbnail_src = picked || saved.thumbnail_src;
const src = picked || saved.src;
@@ -49,6 +53,7 @@ export default function BotAvatar({ image_media_id, src: picked, ...stone }: Pro
BotAvatarSizeClasses[size] || BotAvatarSizeClasses[32],
stone.className,
)}
size={size}
/>
);
}
+65 -48
View File
@@ -2,16 +2,23 @@ import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
import type { BotSessionListItem } from "@/src/types";
import messagePreview from "@/src/utils/message-preview";
import relativeTime from "@/src/utils/relative-time";
import RowIconButton from "./row-icon-button";
type Props = {
session: BotSessionListItem;
loading?: boolean;
disabled?: boolean;
onOpen: () => void;
/**
* Deletes the session and its messages; left out where sessions can't be
* deleted (the rail).
*/
onDelete?: () => void;
/**
* The session the page shows (`?session_id=`, else the active one):
* marked Current and greyed out.
@@ -25,7 +32,7 @@ type Props = {
* recent. The one on screen is Current (greyed out); any other opens on
* click (reopening a closed one, going back to the active one).
*/
export default function BotSessionRow({ session, loading, disabled, onOpen, current }: Props) {
export default function BotSessionRow({ session, loading, disabled, onOpen, onDelete, current }: Props) {
const preview = session.summary || session.last_message_text || "";
const at = session.last_activity_at || session.created_at;
const tag = session.routine_title
@@ -35,56 +42,66 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
: null;
return (
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"w-full justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{session.title || "Untitled session"}
</Span>
{tag ? (
<Row className="w-full flex-nowrap items-center gap-1">
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"grow min-w-0 justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{tag.label}
{session.title || "Untitled session"}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
{tag ? (
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
>
{tag.label}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Stack>
</Button>
</Stack>
</Button>
{onDelete ? (
<RowIconButton
icon={Trash2}
title={`Delete "${session.title || "Untitled"}"`}
disabled={Boolean(loading) || disabled}
onClick={onDelete}
/>
) : null}
</Row>
);
}
+43 -17
View File
@@ -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,13 +38,15 @@ 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;
};
/**
* The sessions icon (or another target) that opens a conversation's
* sessions. A conversation is split into sessions so a bot's context never
* grows without bound; this lists them, searches them, starts a fresh one,
* or reopens an old one to carry on.
* reopens an old one to carry on, or deletes one.
*/
export default function BotSessionsModal({
bot,
@@ -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),
@@ -139,22 +145,42 @@ export default function BotSessionsModal({
</Span>
) : null}
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
{sessions.sessions.map((session) => (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={on_screen?.id ? on_screen.id == session.id : session.status == "active"}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
/>
))}
{sessions.sessions.map((session) => {
const is_current = on_screen?.id
? on_screen.id == session.id
: session.status == "active";
return (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={is_current}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
onDelete={() => {
if (
!window.confirm(
`Delete "${session.title || "this session"}"? Its messages go with it, and this can't be undone.`,
)
) {
return;
}
sessions.deleteSession({
session_id: Number(session.id),
current: is_current,
});
}}
/>
);
})}
{sessions.loading ? (
<LoadingBlock className="w-full h-[300px]" />
) : !sessions.sessions.length ? (
+16 -1
View File
@@ -22,6 +22,11 @@ type Props = {
* Its height, e.g. `h-24`.
*/
className?: string;
/**
* Shows the text without letting it be edited; `onChange` is then never
* called.
*/
readOnly?: boolean;
onChange: (value: string) => void;
};
@@ -30,7 +35,16 @@ type Props = {
* under it. Loads the editor's scripts when it first shows
* (`loadAceScripts`).
*/
export default function CodeEditor({ title, content, mode, placeholder, info, className, onChange }: Props) {
export default function CodeEditor({
title,
content,
mode,
placeholder,
info,
className,
readOnly,
onChange,
}: Props) {
/**
* The editor keeps the handler it was created with; this keeps it
* calling the latest one.
@@ -50,6 +64,7 @@ export default function CodeEditor({ title, content, mode, placeholder, info, cl
content={content}
mode={mode}
placeholder={placeholder}
readOnly={readOnly}
fontSize="13px"
delay={0}
wrapperProps={{ className: twMerge("h-40", className) }}
+12 -5
View File
@@ -1,9 +1,16 @@
import { Monitor } from "lucide-react";
import computerIcon from "@/src/utils/computer-icon";
import IconTile from "./icon-tile";
/**
* A computer's avatar in lists: the monitor icon on a small tile.
* A computer's avatar in lists: its icon (`computerIcon`) on a small tile.
*/
export default function ComputerIconTile() {
return <IconTile Icon={Monitor} />;
}
export default function ComputerIconTile({
connection,
}: {
/**
* `ssh` wears a server instead of a monitor.
*/
connection?: string | null;
}) {
return <IconTile Icon={computerIcon({ connection })} />;
}
+2 -1
View File
@@ -193,8 +193,9 @@ export default function HookForm({
};
return (
// shrink-0: a capped flex column (the modal) would squash the form and clip the buttons away.
<Form
className="w-full gap-4! items-stretch pt-4 overflow-hidden px-1"
className="w-full shrink-0 gap-4! items-stretch pt-4 overflow-hidden px-1"
onSubmit={submit}
>
<Input
+8 -4
View File
@@ -34,7 +34,7 @@ export default function ImagePickField({
const input_ref = useRef<HTMLInputElement>(null);
return (
<Row className="w-full gap-4! flex-nowrap items-center">
<Row className="w-full gap-4! items-center">
{preview}
<Stack className="gap-2! min-w-0">
<Row className="gap-2!">
@@ -60,14 +60,17 @@ export default function ImagePickField({
disabled={disabled || loading}
onClick={() => {
onRemove();
if (input_ref.current) input_ref.current.value = "";
if (input_ref.current)
input_ref.current.value = "";
}}
>
Remove
</Button>
) : null}
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">{note}</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{note}
</Span>
</Stack>
{/*
* Raw on purpose: twui `Input` writes `value` on change, which
@@ -85,7 +88,8 @@ export default function ImagePickField({
if (!e.target.files?.[0]) return;
imageInputToBase64({ imageInput: e.target }).then((res) => {
if (res?.imageBase64Full) onPick({ data_url: res.imageBase64Full });
if (res?.imageBase64Full)
onPick({ data_url: res.imageBase64Full });
});
}}
/>
+10 -3
View File
@@ -19,7 +19,9 @@ type Props = {
export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
const [title, setTitle] = useState(cron_job.title || "");
const [schedule, setSchedule] = useState(cron_job.schedule || "");
const [instructions, setInstructions] = useState(cron_job.instructions || "");
const [instructions, setInstructions] = useState(
cron_job.instructions || "",
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -69,13 +71,18 @@ export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
/>
<CodeEditor
mode="markdown"
className="h-40"
className="h-[300px]"
title="Brief"
content={instructions}
info="What the bot does at every run, and how it knows it's done."
onChange={(value) => setInstructions(value)}
/>
<AddFormActions submit_label="Save" loading={loading} error={error} onCancel={onCancel} />
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
onCancel={onCancel}
/>
</Form>
);
}
+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
+5 -1
View File
@@ -12,6 +12,8 @@ const UserAvatarSizeClasses = {
sm: "size-6 text-[11px]",
md: "size-8 text-xs",
lg: "size-16 text-lg",
xl: "size-24 text-xl",
xxl: "size-32 text-2xl",
} as const;
type Props = {
@@ -47,7 +49,9 @@ export default function UserAvatar({
size = "md",
className,
}: Props) {
const photo = person?.profile_media_id ? grabMediaURL({ user: person }) : {};
const photo = person?.profile_media_id
? grabMediaURL({ user: person })
: {};
const src = passed_src || photo.media_thumbnail_url || photo.media_url;
const img_err_src = passed_src ? passed_err_src : photo.media_url;
const initials = passed_initials || userInitials(person || {});
+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],
});
+19 -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
@@ -1043,6 +1054,12 @@ export const AppData = {
* to have pushed the last ones (`LiveRelayPollMs`).
*/
BotJobStepsKeepMs: 60 * 1000,
/**
* How long a stop waits for the run to write what it did before it
* stopped (`StoppedRunNote`). Past it the plain stopped message goes out
* instead, so Stop never leaves the thread thinking.
*/
BotStopSummaryMs: 20 * 1000,
/**
* The debug view's detailed trace of a job (`bot_job_traces`, read and
* written only by `process-bot-job`): how many rows one job keeps, how
+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.
+72 -12
View File
@@ -17,13 +17,14 @@ import {
TaskRunNote,
TaskWrapUpIncomingNote,
TasksNote,
OpenTasksNote,
PlanModeNote,
wrapUpWorktreeNote,
PlansNote,
PlanStepNote,
PlanWaitingNote,
PlanActiveNote,
PlanPausedNote,
ScheduledPlanNote,
RetryFailureNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -232,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", () => {
@@ -243,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");
});
});
@@ -351,12 +361,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");
});
});
test("a routine's plan is approved at once and worked through in the run", () => {
expect(ScheduledPlanNote).toContain("approved at once");
expect(ScheduledPlanNote).toContain("work its steps in this run");
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)");
});
});
+116 -32
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.
@@ -129,6 +138,18 @@ The user asked for this reply again. Work from their latest messages and write i
- If the answer did go out, write it again for what they asked, as if it were the first time. The earlier one stays in the thread, so don't repeat it word for word if you have something better to say, and don't assume they missed it.
- Start the work now, in this reply or with send_reply status "working" and work: never answer that you'll look into it.`;
/**
* The turn a run gets when the user stops it from the chat: stop where it
* is, and say what happened so far, so the thread's last word comes from
* the run instead of the app's plain stopped line. `stop-bot-jobs` gives it
* `AppData.BotStopSummaryMs` before that line goes out anyway.
*/
export const StoppedRunNote = `# Stopped
The user stopped this run. Stop at the step you are on: don't call any tool that does work, and don't start, queue or promise anything new.
Write one short message for them that starts with "Stopped." and says what this run did so far and what is still undone, only from what it actually did (the tool calls it made and what came back). Then call send_reply with status "done".`;
/**
* Added beside `RerunReplyNote` when the attempt before this one failed:
* `reason` is the job's `last_error` (`grabRetryFailure`), so the run knows
@@ -396,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.
@@ -411,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
@@ -561,6 +594,15 @@ export const closingFailedNote = `The card that call was meant to put up was not
*/
export const closingMixedNote = `The card you put up is there: that call worked. This turn also did other work, so it isn't the reply yet. Don't put another card up - a run asks once - and don't call ask_user or suggest_next_steps again. Write the message that goes with the card you already created, and stop there.`;
/**
* Told when the run's last turn called a tool it no longer has: only
* `send_reply` is offered by then, so the call and the message beside it are
* dropped and nothing was sent. A finished report is the whole point of a
* run that got this far, so it is written again once before the run gives up
* (job 687 lost one to a stray call).
*/
export const closingToolGoneNote = `This run's last turn offers send_reply alone, and the tool you called is not one it can run any more: that call and the message beside it were dropped, so nothing was sent. Write the whole message again in that turn as send_reply's text or its message argument, with status "done" when nothing is running after it, "working" when something is, or "blocked" when it can't go on. Finish every table, list and code fence in it.`;
/**
* Told once when a closing call worked but the turn said nothing beside it:
* a card alone leaves the user with buttons and no answer, and a run that
@@ -603,6 +645,16 @@ 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.`;
/**
* 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
@@ -731,23 +783,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
@@ -1057,11 +1126,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,9 +1167,15 @@ 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 next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
return `# The plan in this conversation
@@ -1103,18 +1183,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: 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 "${next_label}", second "Pause the plan"). A report that ticked the step without that card is sent back.
- 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
@@ -1127,18 +1218,11 @@ 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.
- Every answer here carries a Turn Plan mode off button under it, so the way on is one click: say in one sentence what you will do once it is off, and stop there. Never hand the work back to them to paste or do by hand; turning the mode off (that button, or Tab) is the only thing in the way.
- End with send_reply: done sends the plan or the answer, blocked says what stopped you. Work can't be queued here.
- Say what you would do and what it depends on, not that you are doing it.`;
/**
* Added to a routine's run: nobody is there to approve a plan, so the bot
* writes one and works all of it in the run, reporting at the end.
*/
export const ScheduledPlanNote = `# A plan in a scheduled run
Nobody is watching this run, so a plan can't wait for approval. If this run's work is several pieces that build on each other, write it with create_plan anyway (it is approved at once here) and work its steps in this run: complete_plan_step after each one, with what it produced, so the conversation shows how far it got. Nothing interleaves with your run, so don't stop after one step. Your report at the end covers the whole plan: what each step produced and what is left.`;
+6
View File
@@ -25,6 +25,12 @@ export const PwaLoadingPath = "/loading.html";
export const PwaBuildInfoPath = "/build-info.json";
export const PwaPrecacheCachePrefix = "cobble-assets-";
export const PwaPrecacheMarkerPath = "/__cobble-precached";
/**
* The meta tag the root puts the running build in, so the page's own code
* knows which build it was loaded from (`loaded-build.ts`) and a send from
* an older one can be refused.
*/
export const PwaBuildMetaName = "cobble-build";
export type PwaIcon = {
src: string;
+11
View File
@@ -5,6 +5,7 @@ import {
harnessParametersFromOptions,
harnessParameterValue,
modelAdvertisesParameter,
providerSupportedParameters,
withHarnessParameters,
} from "./harness-parameter-dict";
@@ -68,4 +69,14 @@ describe("harness parameters", () => {
harnessParameterValue({ harness: "text", params: { temperature: 0 }, key: "temperature" }),
).toEqual({ value: 0, saved: true });
});
test("a provider's declared settings go under the names its models advertise", () => {
expect(
providerSupportedParameters({
keys: ["temperature", "reasoning_effort"],
}),
).toEqual(["temperature", "reasoning"]);
expect(providerSupportedParameters({})).toBeUndefined();
expect(providerSupportedParameters({ keys: [] })).toEqual([]);
});
});
+55
View File
@@ -8,6 +8,7 @@
* - `advertised`: the name a provider's model list uses for it, when it
* differs (OpenRouter's `supported_parameters`)
* - `wire`: how the field is written, for providers that nest it
* - `wire_boolean`: saved as "true"/"false", sent as a JSON boolean
*/
export const HarnessParameters = [
{
@@ -104,12 +105,42 @@ export const HarnessParameters = [
{ value: "high", title: "High" },
],
},
{
key: "enable_thinking",
title: "Thinking",
description: `Whether it thinks before it answers, which is slower and costs more. "Default" leaves each model's own setting alone. Providers that turn thinking on by another field ignore it.`,
value_type: "select",
wire_boolean: true,
options: [
{ value: "true", title: "On" },
{ value: "false", title: "Off" },
],
},
{
key: "thinking_budget",
title: "Thinking budget",
description: `How many tokens it may think with, up to 32768. Only some models take it, and usually only while thinking is on.`,
value_type: "number",
min: 0,
max: 32768,
step: 1,
},
] as const;
export type HarnessParameter = (typeof HarnessParameters)[number];
export type HarnessParameterKey = HarnessParameter["key"];
export type HarnessParameterValue = number | string;
/**
* The generation settings as they go on the wire: OpenRouter's reasoning
* effort nests as `reasoning: { effort }`, a boolean setting as a JSON
* boolean, the rest as they are.
*/
export type HarnessWireParams = Record<
string,
number | string | boolean | { effort: string }
>;
/**
* The harnesses whose models are chat models, so the only ones the
* generation settings apply to.
@@ -189,6 +220,30 @@ export function modelAdvertisesParameter({
);
}
/**
* The names a provider's declared settings go under: what its models'
* `supported_parameters` should carry, so the same advertised names
* OpenRouter's catalog uses. Undefined when the provider declares nothing,
* which leaves its models with none.
*/
export function providerSupportedParameters({
keys,
}: {
keys?: readonly HarnessParameterKey[] | null;
}) {
if (!keys) return undefined;
return keys.flatMap((key) => {
const parameter = HarnessParameters.find((p) => p.key == key);
if (!parameter) return [];
return [
"advertised" in parameter ? parameter.advertised : parameter.key,
];
});
}
/**
* The generation settings a saved `options` object holds.
*/
+13
View File
@@ -8,6 +8,9 @@
* tools support and prices; `openai-compatible` gives only ids, so
* capabilities are guessed from the names
* - `local`: runs on the user's own hardware, so its models count as free
* - `parameters`: the generation settings its models get when its own model
* list carries none (`HarnessParameters` keys). Empty for a provider whose
* catalog decides (OpenRouter) or whose host is checked instead (custom)
* - `image_path`: image generation endpoint
* - `image_edit_path`: where images made from reference images go. OpenRouter
* takes them on `image_path` (`input_references`); the others take a
@@ -22,6 +25,7 @@ export const HarnessProviderKinds = [
{
title: "OpenRouter",
value: "openrouter",
parameters: [],
base_url: "https://openrouter.ai/api/v1",
needs_key: true,
key_env: "OPENROUTER_API_KEY",
@@ -34,6 +38,7 @@ export const HarnessProviderKinds = [
{
title: "OpenAI",
value: "openai",
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "reasoning_effort"],
base_url: "https://api.openai.com/v1",
needs_key: true,
key_env: "OPENAI_API_KEY",
@@ -46,6 +51,7 @@ export const HarnessProviderKinds = [
{
title: "Anthropic",
value: "anthropic",
parameters: ["temperature", "top_p", "top_k"],
base_url: "https://api.anthropic.com/v1",
needs_key: true,
key_env: "ANTHROPIC_API_KEY",
@@ -58,6 +64,7 @@ export const HarnessProviderKinds = [
{
title: "Google Gemini",
value: "google",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
needs_key: true,
key_env: "GEMINI_API_KEY",
@@ -70,6 +77,7 @@ export const HarnessProviderKinds = [
{
title: "DeepSeek",
value: "deepseek",
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty"],
base_url: "https://api.deepseek.com",
needs_key: true,
key_env: "DEEPSEEK_API_KEY",
@@ -82,6 +90,7 @@ export const HarnessProviderKinds = [
{
title: "Groq",
value: "groq",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty", "reasoning_effort"],
base_url: "https://api.groq.com/openai/v1",
needs_key: true,
key_env: "GROQ_API_KEY",
@@ -94,6 +103,7 @@ export const HarnessProviderKinds = [
{
title: "Mistral",
value: "mistral",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
base_url: "https://api.mistral.ai/v1",
needs_key: true,
key_env: "MISTRAL_API_KEY",
@@ -106,6 +116,7 @@ export const HarnessProviderKinds = [
{
title: "xAI",
value: "xai",
parameters: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "seed", "reasoning_effort"],
base_url: "https://api.x.ai/v1",
needs_key: true,
key_env: "XAI_API_KEY",
@@ -118,6 +129,7 @@ export const HarnessProviderKinds = [
{
title: "Ollama",
value: "ollama",
parameters: ["temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"],
base_url: "http://localhost:11434/v1",
needs_key: false,
key_env: "",
@@ -130,6 +142,7 @@ export const HarnessProviderKinds = [
{
title: "Other (OpenAI-compatible)",
value: "custom",
parameters: [],
base_url: "",
needs_key: false,
key_env: "",
+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.
@@ -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");
});
});
@@ -12,6 +12,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 +24,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 +36,9 @@ 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 tail = ended
? `_The request had already ended; this is the answer, sent afterwards._`
: `_The request is still open - more may follow._`;
return `${head}\n\n${text}\n\n${tail}`;
}
@@ -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",
@@ -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([]);
});
@@ -203,6 +219,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;
@@ -8,8 +8,10 @@ import { AskStages } 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,12 +110,30 @@ 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({
@@ -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;
}
+27 -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)[];
};
@@ -18,15 +26,28 @@ type Params = {
* 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.
*/
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')`,
values: [
Number(user_id),
Number(requester_bot_id),
...job_ids.map(Number),
...session_ids.map(Number),
],
});
const stopped: BUN_SQLITE_COBBLE_BOT_ASKS[] = [];
@@ -9,18 +9,30 @@ type Params = {
* Only a call to this bot's hooks.
*/
bot_id?: number | string | null;
/**
* Only a call to a hook that runs in this workspace.
*/
workspace_id?: number | string | null;
};
/**
* One call to one of the user's hooks, whole: what it sent and what its
* run answered. Throws when it isn't theirs (or that bot's).
* run answered. Throws when it isn't theirs (or that bot's, or that
* workspace's).
*/
export default async function grabBotHookEvent({ user_id, event_id, bot_id }: Params) {
export default async function grabBotHookEvent({ user_id, event_id, bot_id, workspace_id }: Params) {
const res = await BunSQLite.sql<BotHookCall>({
sql: `SELECT e.*, h.title AS hook_title, h.bot_id, h.workspace_id
FROM bot_hook_events e JOIN bot_hooks h ON h.id = e.hook_id
WHERE e.id = ? AND h.user_id = ? AND (? IS NULL OR h.bot_id = ?)`,
values: [Number(event_id), user_id, bot_id ? Number(bot_id) : null, bot_id ? Number(bot_id) : null],
WHERE e.id = ? AND h.user_id = ? AND (? IS NULL OR h.bot_id = ?) AND (? IS NULL OR h.workspace_id = ?)`,
values: [
Number(event_id),
user_id,
bot_id ? Number(bot_id) : null,
bot_id ? Number(bot_id) : null,
workspace_id ? Number(workspace_id) : null,
workspace_id ? Number(workspace_id) : null,
],
});
const call = res.payload?.[0];
@@ -11,7 +11,9 @@ type Params = {
bot_id?: number | string;
/**
* With `bot_id`: only the hooks of that conversation (null is the
* bot's own chat), as `grabCronJobs` does for routines.
* bot's own chat), as `grabCronJobs` does for routines. Without
* `bot_id`: every bot's hooks in that workspace (a coordinator working
* there).
*/
workspace_id?: number | string | null;
/**
@@ -46,6 +48,9 @@ export default async function grabBotHooks({
where.push(scope.sql);
values.push(...scope.values);
}
} else if (workspace_id) {
where.push(`h.workspace_id = ?`);
values.push(workspace_id);
}
if (hook_id) {
@@ -4,13 +4,17 @@ import grabBotHooks from "./grab-bot-hooks";
type Params = {
user_id: number | string;
hook_id: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
};
/**
* One of the user's hooks. Throws when it isn't theirs.
*/
export default async function grabUserBotHook({ user_id, hook_id }: Params) {
const [hook] = await grabBotHooks({ user_id, hook_id });
export default async function grabUserBotHook({ user_id, hook_id, workspace_id }: Params) {
const [hook] = await grabBotHooks({ user_id, hook_id, workspace_id });
if (!hook?.id) {
throw new AppError(`Hook #${hook_id} not found.`);
@@ -8,6 +8,10 @@ export type SearchHookCallsParams = {
user_id: number | string;
hook_id?: number | string | null;
bot_id?: number | string | null;
/**
* Only calls to hooks that run in this workspace (a run working there).
*/
workspace_id?: number | string | null;
/**
* Words to find in what a call sent or what its run answered.
*/
@@ -33,6 +37,7 @@ export default function searchHookCallsSql({
user_id,
hook_id,
bot_id,
workspace_id,
query,
status,
before_id,
@@ -52,6 +57,11 @@ export default function searchHookCallsSql({
values.push(Number(bot_id));
}
if (workspace_id) {
where.push(`h.workspace_id = ?`);
values.push(Number(workspace_id));
}
if (status) {
where.push(`e.status = ?`);
values.push(status);
@@ -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,48 @@
import AppError from "@/src/utils/app-error";
import deleteSessionRows from "./delete-session-rows";
import grabUserBotSession from "./grab-user-bot-session";
import hasOpenSessionJob from "./has-open-session-job";
import startBotSession from "./start-bot-session";
type Params = {
session_id: number | string;
user_id: number | string;
};
/**
* Deletes one of the user's sessions and everything in it. Deleting the
* active one hands the conversation a fresh session, since a conversation
* always has one to write in. A session with a run in progress is refused:
* the run would keep writing into rows that are gone.
*/
export default async function deleteBotSession({
session_id,
user_id,
}: Params): Promise<void> {
const session = await grabUserBotSession({ session_id, user_id });
if (!session?.id) {
throw new AppError(`Session not found.`);
}
/**
* A bot's part of a crew request is only ever read there.
*/
if (session.ask_id) {
throw new AppError(`Session not found.`);
}
if (await hasOpenSessionJob({ session_id: session.id })) {
throw new AppError(`This session has a run in progress. Stop it first, then delete the session.`);
}
await deleteSessionRows({ session_ids: [session.id] });
if (session.status != "active") return;
await startBotSession({
user_id: session.user_id!,
bot_id: session.bot_id!,
workspace_id: session.workspace_id,
});
}
@@ -12,7 +12,9 @@ type Params = {
* traces, jobs, what the runs were billed (`token_usages`), job tasks,
* reactions, message files, messages, tasks, then the sessions.
* Files a message carried are unlinked, and their media row is deleted once
* nothing else points at it.
* nothing else points at it. A newer session's `previous_session_id` and a
* message's `carried_from_session_id` that named one of these are cleared,
* since neither is a foreign key.
*/
export default async function deleteSessionRows({ session_ids }: Params) {
const ids = session_ids.map(Number).filter(Boolean);
@@ -107,6 +109,20 @@ export default async function deleteSessionRows({ session_ids }: Params) {
values: ids,
});
await deleteBotPlanRows({ session_ids: ids });
/**
* A newer session may carry on from one of these, and a message may have
* carried one over: neither link is a foreign key, so it dangles.
*/
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET previous_session_id = NULL WHERE previous_session_id IN (${session_placeholders})`,
values: ids,
});
await BunSQLite.sql({
sql: `UPDATE bot_messages SET carried_from_session_id = NULL WHERE carried_from_session_id IN (${session_placeholders})`,
values: ids,
});
await BunSQLite.sql({
sql: `DELETE FROM bot_sessions WHERE id IN (${session_placeholders})`,
values: ids,
@@ -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)],
};
}
@@ -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;
}
@@ -1,6 +1,6 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import { BotNeedsYouStatusLine } from "@/src/dict/bot-queue-dict";
import { BotNeedsYouStatusLine, BotJobStoppedError } from "@/src/dict/bot-queue-dict";
import insertBotMessage from "../bots/insert-bot-message";
import deleteBotMessage from "../bots/delete-bot-message";
import setBotFace from "../bots/set-bot-face";
@@ -63,6 +63,14 @@ type Params = {
* a run that spent its whole budget and did no work says so itself.
*/
exhausted?: boolean;
/**
* The user stopped this run, and its message says what it did so far
* (`StoppedRunNote`). Nothing is answered by it: no crew request is
* finished, no hand-over is relayed, no handed-over task is touched
* (`stop-bot-jobs` ends the rest), and the bot goes idle rather than
* done.
*/
stopped?: boolean;
};
/**
@@ -75,7 +83,9 @@ type Params = {
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
* its whole step budget without finishing (`noteTrackerTask`). A hook
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job working a crew
* request ends it (`onAskJobEnded`) and leaves the bot's face alone. Throws if this handler no longer holds the job.
* request ends it (`onAskJobEnded`) and leaves the bot's face alone. A run the
* user stopped (`stopped`) only says what it did so far and goes idle: it
* answers nothing. Throws if this handler no longer holds the job.
*/
export default async function completeBotJob({
job_id,
@@ -88,6 +98,7 @@ export default async function completeBotJob({
task_ids = [],
plan_id,
exhausted,
stopped,
}: Params) {
const job = await grabLockedBotJob({ job_id, worker });
@@ -158,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],
});
@@ -198,31 +215,49 @@ export default async function completeBotJob({
bot =
!user_id || unattended
? null
: needs_you
? await setBotFace({
bot_id: job.bot_id,
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
: stopped
? await setBotFace({ bot_id: job.bot_id, user_id, face: "idle" })
: needs_you
? await setBotFace({
bot_id: job.bot_id,
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
await noteTrackerTask({ job, exhausted });
if (stopped) {
/**
* A stopped run answers nothing: the hook call it was in and an
* install request it was settling end as stopped, and the crew
* request it was answering is ended by `stop-bot-jobs`.
*/
await recordHookCallResponse({
job,
status: "failed",
response: BotJobStoppedError,
message_id: inserted?.id,
});
await recordHookCallResponse({
job,
status: "done",
response: result,
message_id: inserted?.id,
});
await settleInstallRequest({ job, text: BotJobStoppedError, failed: true });
} else {
await noteTrackerTask({ job, exhausted });
relay = silent
? null
: await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await recordHookCallResponse({
job,
status: "done",
response: result,
message_id: inserted?.id,
});
await onAskJobEnded({ job, text: silent ? "" : result, tool_uses: tool_log });
relay = silent
? null
: await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await settleInstallRequest({ job, text: result });
await onAskJobEnded({ job, text: silent ? "" : result, tool_uses: tool_log });
await settleInstallRequest({ job, text: result });
}
} catch (error) {
await logError({
title: `Bot job #${job.id} completed, its clearing up didn't`,
@@ -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;
@@ -1,9 +1,10 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { BotJobStoppedError, BotJobStoppedStep } from "@/src/dict/bot-queue-dict";
import insertBotMessage from "../bots/insert-bot-message";
import setBotFace, { type BotFaceChange } from "../bots/set-bot-face";
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
import { abortRunningJob, requestJobStopSummary } from "@/src/bots-queue/job-abort-registry";
import insertBotJobUpdate from "./insert-bot-job-update";
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
import openBotJobsSql from "./open-bot-jobs-sql";
@@ -12,10 +13,15 @@ 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";
type Params = {
bot_id: number | string;
@@ -27,7 +33,7 @@ type Params = {
export type StoppedBotJobs = {
/**
* The jobs that were open and are now failed as stopped.
* The jobs that were open when the stop came.
*/
jobs: BUN_SQLITE_COBBLE_BOTS_QUEUE[];
/**
@@ -45,13 +51,16 @@ export type StoppedBotJobs = {
/**
* Pulls the plug on a bot for one user: every job of it that could still
* run or is running in their conversations (replies it still owes, tasks
* it's on, across all of them) is failed as stopped, its task closed. A
* running handler finds out on its next `updateBotJob` (which returns
* false) and drops whatever it was producing. Each job gets a closing
* step, so a thread's working row says why it went quiet even after a
* reload, one message per session ends it out loud, and the bot goes
* idle. It's not a bus: nothing restarts by itself, so a stopped bot
* works again only when the user asks. A schedule the user set up still
* it's on, across all of them) is failed as stopped, its task closed.
*
* A run this process is running is asked to stop where it is and write what
* it did so far (`StoppedRunNote`), and that message is the session's last
* word. `AppData.BotStopSummaryMs` is all it gets: past that the job is
* failed and the plain stopped line goes out instead, so a stop never
* leaves the thread thinking. Each job gets a closing step too, so a
* thread's working row says why it went quiet even after a reload, and the
* bot goes idle. It's not a bus: nothing restarts by itself, so a stopped
* bot works again only when the user asks. A schedule the user set up still
* comes round, since that is work they asked for.
*/
export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<StoppedBotJobs | null> {
@@ -66,6 +75,24 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
if (!open.length) return null;
/**
* The runs this process can still write for are asked to stop and say
* what they did, one per session (`pickReportedJobs`): that is what the
* session reads, so a second summary there would stutter.
*/
const picked = pickReportedJobs({ jobs: open });
const summarizing: { job_id: number; session_id: number }[] = [];
const stop_started_at = Date.now();
for (const [session_id, job] of picked) {
if (job.status != "processing") continue;
if (!requestJobStopSummary({ job_id: Number(job.id) })) continue;
summarizing.push({ job_id: Number(job.id), session_id });
}
await waitForStopSummaries({ job_ids: summarizing.map((entry) => entry.job_id) });
const now = Date.now();
const jobs: BUN_SQLITE_COBBLE_BOTS_QUEUE[] = [];
@@ -102,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.
@@ -128,11 +164,13 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
/**
* A job it was doing for a crew request stops the request: the bot that
* asked is told, and the other side's run is cancelled.
* asked is told, and the other side's run is cancelled. Read from every
* job that was open, since a run that wrote its own summary is still a
* stop for the request it was answering.
*/
const ask_ids = new Set<number>();
for (const job of jobs) {
for (const job of open) {
const from_session = await grabSessionAskId({ session_id: Number(job.session_id) }).catch(
() => null,
);
@@ -152,61 +190,152 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
* own: the open request is found by the session it answers in.
*/
if (!asked && !from_session && job.session_id) {
const open = await grabOpenAskBySession({ session_id: Number(job.session_id) }).catch(
const open_ask = await grabOpenAskBySession({ session_id: Number(job.session_id) }).catch(
() => null,
);
if (open?.id) ask_ids.add(Number(open.id));
if (open_ask?.id) ask_ids.add(Number(open_ask.id));
}
}
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,
session_ids: jobs.map((job) => Number(job.session_id)),
job_ids: jobs.map((job) => Number(job.id)),
session_ids: open.map((job) => Number(job.session_id)),
}).catch(() => []);
/**
* A session whose run wrote its own summary already has its last word.
*/
const stopped_ids = new Set(jobs.map((job) => Number(job.id)));
const summarized_sessions = new Set(
summarizing.filter((entry) => !stopped_ids.has(entry.job_id)).map((entry) => entry.session_id),
);
const messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[] = [];
for (const [session_id, job] of pickReportedJobs({ jobs })) {
if (summarized_sessions.has(session_id)) continue;
/**
* A silent hook's call says it was stopped in its thread
* (`recordHookCallResponse`), nowhere the user reads.
*/
if (await isUnattendedHookSession({ session_id })) continue;
/**
* A run that wrote its summary just as the wait ran out has its row
* failed under it: its message is still there, so the plain line
* would only repeat it.
*/
const answered = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bot_messages WHERE session_id = ? AND author = 'bot' AND created_at >= ? LIMIT 1`,
values: [session_id, stop_started_at],
}).catch(() => null)
)?.payload?.length;
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);
if (message?.id) {
messages.push(message);
/**
* The run's debug logs go with the answer that took its place,
* the way a finished run's go with its own.
* The run's info goes with the message that took its place: its
* own calls and failures behind the usage chip, and its debug
* logs, the way a finished run's go with its own.
*/
await attachJobCallsToMessage({ job_id: Number(job.id), message_id: Number(message.id) });
await attachJobTracesToMessage({ job_id: Number(job.id), message_id: Number(message.id) });
messages.push((await withMessageUsage({ messages: [message] }).catch(() => [message]))[0] ?? message);
}
}
return {
jobs,
jobs: open,
messages,
bot: await setBotFace({ bot_id, user_id, face: "idle" }),
};
}
/**
* Waits for the runs asked to summarize to close their rows, never past
* `AppData.BotStopSummaryMs`: past it the plain stopped line goes out
* instead. Polled rather than awaited: another process's handler can only
* be read through the queue.
*/
async function waitForStopSummaries({ job_ids }: { job_ids: number[] }) {
if (!job_ids.length) return;
const deadline = Date.now() + AppData.BotStopSummaryMs;
const placeholders = job_ids.map(() => "?").join(", ");
while (Date.now() < deadline) {
const still_open = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue WHERE id IN (${placeholders}) AND status IN ('pending', 'processing')`,
values: job_ids,
}).catch(() => null)
)?.payload;
if (!still_open?.length) return;
await Bun.sleep(250);
}
}
@@ -3,13 +3,15 @@ import AppError from "@/src/utils/app-error";
import grabSystemPromptAppend from "../app-settings/grab-system-prompt-append";
import grabWorkspaceBot from "../workspaces/grab-workspace-bot";
import grabWorkspaceUserRole from "../workspaces/grab-workspace-user-role";
import grabUserName from "../users/grab-user-name";
import grabBotUserMemory from "./grab-bot-user-memory";
import grabUserBot from "./grab-user-bot";
type Params = {
bot_id: number | string;
/**
* The user the bot works with: only their memory joins the prompt.
* The user the bot works with: their name and their memory join the
* prompt.
*/
user_id: number | string;
/**
@@ -23,8 +25,9 @@ type Params = {
/**
* The full prompt for one of the user's bots (`composeBotPrompt`): who it
* is (its name and id), its core instructions, the install-wide appendix,
* its memory, what it remembers about this user, and in a workspace that
* workspace's context, what the bot has for it and who this user is there.
* who the user it's working for is, its memory, what it remembers about this
* user, and in a workspace that workspace's context, what the bot has for it
* and who this user is there.
*/
export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: Params) {
const bot = await grabUserBot({ bot_id, user_id });
@@ -45,6 +48,7 @@ export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: P
bot: { id: bot.id, name: bot.name, kind: bot.kind, role: bot.role },
system_prompt: bot.system_prompt,
appendix: await grabSystemPromptAppend(),
user_name: await grabUserName({ user_id }),
memory: bot.memory,
user_memory: await grabBotUserMemory({ bot_id: bot.id, user_id }),
workspace: found?.workspace,
@@ -8,6 +8,10 @@ type Params = {
* Only if it's this bot's (a bot managing its own schedules).
*/
bot_id?: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
};
/**
@@ -15,8 +19,8 @@ type Params = {
* The sessions its runs held stay, as the user's own threads (they're
* ordinary sessions once no routine owns them).
*/
export default async function deleteCronJob({ user_id, cron_job_id, bot_id }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id });
export default async function deleteCronJob({ user_id, cron_job_id, bot_id, workspace_id }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id, workspace_id });
const detached = await BunSQLite.sql({
sql: `UPDATE bot_sessions SET routine_id = NULL, updated_at = ? WHERE routine_id = ?`,
@@ -12,7 +12,8 @@ type Params = {
/**
* With `bot_id`: only the routines of that conversation, here
* (`routineScopeSql`). `null` is the bot's own chat, so it has to be
* given rather than left out to mean "everywhere".
* given rather than left out to mean "everywhere". Without `bot_id`:
* every bot's routines in that workspace (a coordinator working there).
*/
workspace_id?: number | string | null;
/**
@@ -48,6 +49,9 @@ export default async function grabCronJobs({
where.push(scope.sql);
values.push(...scope.values);
}
} else if (workspace_id) {
where.push(`c.workspace_id = ?`);
values.push(workspace_id);
}
if (cron_job_id) {
@@ -8,13 +8,17 @@ type Params = {
* Only if it's this bot's (a bot managing its own schedules).
*/
bot_id?: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
};
/**
* One of the user's schedules. Throws when it isn't theirs (or the bot's).
*/
export default async function grabUserCronJob({ user_id, cron_job_id, bot_id }: Params) {
const [cron_job] = await grabCronJobs({ user_id, bot_id, cron_job_id });
export default async function grabUserCronJob({ user_id, cron_job_id, bot_id, workspace_id }: Params) {
const [cron_job] = await grabCronJobs({ user_id, bot_id, workspace_id, cron_job_id });
if (!cron_job?.id) {
throw new AppError(`Schedule #${cron_job_id} not found.`);
@@ -10,6 +10,10 @@ type Params = {
* Only if it's this bot's (a bot managing its own schedules).
*/
bot_id?: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
/**
* Only the fields given are changed. `max_runs: null` runs it until
* it's stopped.
@@ -28,8 +32,8 @@ type Params = {
* on, counts the next run from now; turning a finished one back on (all
* its `max_runs` done) starts its count over. Returns the schedule.
*/
export default async function updateCronJob({ user_id, cron_job_id, bot_id, data }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id });
export default async function updateCronJob({ user_id, cron_job_id, bot_id, workspace_id, data }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id, workspace_id });
const schedule = data.schedule?.trim() || cron_job.schedule || "";
const schedule_changed = Boolean(data.schedule?.trim()) && schedule != cron_job.schedule;
@@ -79,5 +83,5 @@ export default async function updateCronJob({ user_id, cron_job_id, bot_id, data
throw new Error(`Couldn't update the schedule: ${res.error}`);
}
return await grabUserCronJob({ user_id, cron_job_id: cron_job.id! });
return await grabUserCronJob({ user_id, cron_job_id: cron_job.id!, bot_id, workspace_id });
}
@@ -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",
},
};
});
@@ -0,0 +1,26 @@
import { describe, expect, test } from "bun:test";
import modelSupportedParameters from "./model-supported-parameters";
describe("model supported parameters", () => {
test("the provider's own list wins", () => {
expect(
modelSupportedParameters({
model: { supported_parameters: ["temperature"] },
provider_parameters: ["temperature", "seed"],
}),
).toEqual(["temperature"]);
});
test("a model that lists none gets the provider's", () => {
expect(
modelSupportedParameters({
model: {},
provider_parameters: ["temperature", "seed"],
}),
).toEqual(["temperature", "seed"]);
});
test("nothing declared stays nothing", () => {
expect(modelSupportedParameters({ model: {} })).toBeNull();
});
});
@@ -0,0 +1,23 @@
import type { HarnessCatalogModel } from "@/src/harness/types";
type Params = {
model: Pick<HarnessCatalogModel, "supported_parameters">;
/**
* The names the provider's own row declares, for the models it lists
* without any (a custom provider lists ids only).
*/
provider_parameters?: string[] | null;
};
/**
* The parameters a `harness_models` row keeps: what the provider's own list
* said, else the settings the provider declares (its preset, its host or a
* super admin's pick). A model's own list wins, so OpenRouter's catalog is
* never overridden.
*/
export default function modelSupportedParameters({
model,
provider_parameters,
}: Params) {
return model.supported_parameters ?? provider_parameters ?? null;
}
@@ -0,0 +1,32 @@
import {
HarnessParameterKeys,
type HarnessParameterKey,
} from "@/src/dict/harness-parameter-dict";
type Params = {
text?: string | null;
};
/**
* The generation settings a provider row saved, or undefined when it saved
* none (which follows its preset or host instead). Unknown keys are dropped,
* so an older release's name can't reach a model's `supported_parameters`
* and be offered as a field that never gets sent.
*/
export default function parseProviderParameters({
text,
}: Params): HarnessParameterKey[] | undefined {
if (!text) return undefined;
try {
const value = JSON.parse(text);
if (!Array.isArray(value)) return undefined;
return value.filter((key): key is HarnessParameterKey =>
HarnessParameterKeys.includes(key as HarnessParameterKey),
);
} catch {
return undefined;
}
}
@@ -4,6 +4,7 @@ import type {
BunSQLiteTables,
} from "@/db/types/db";
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
import AppError from "@/src/utils/app-error";
import { encrypt } from "@/src/utils/crypt";
@@ -27,6 +28,11 @@ type Params = {
* leaves them unknown.
*/
context_length?: number;
/**
* The generation settings its models are offered. Left out follows its
* preset or host; an empty array means it takes none.
*/
parameters?: HarnessParameterKey[];
enabled: boolean;
};
@@ -42,6 +48,7 @@ export default async function saveHarnessProvider({
api_key,
clear_key,
context_length,
parameters,
enabled,
}: Params) {
const preset = grabProviderPreset({ kind });
@@ -75,6 +82,7 @@ export default async function saveHarnessProvider({
* cleared with null (the plugin binds it as NULL).
*/
context_length: (context_length && context_length > 0 ? context_length : null) as number,
parameters: (parameters ? JSON.stringify(parameters) : null) as string,
...key_update,
};
@@ -1,6 +1,9 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
import grabHarnessAdapter from "@/src/harness/providers/grab-harness-adapter";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import { providerSupportedParameters } from "@/src/dict/harness-parameter-dict";
import parseProviderParameters from "./parse-provider-parameters";
import resolveProviderConfig from "./resolve-provider-config";
import upsertHarnessModels from "./upsert-harness-models";
@@ -29,6 +32,15 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
provider_id: provider.id,
models,
provider_context_length: provider.context_length || null,
provider_parameters: providerSupportedParameters({
keys: providerParameterKeys({
kind: config.kind,
base_url: provider.base_url,
declared: parseProviderParameters({
text: provider.parameters,
}),
}),
}),
});
await BunSQLite.sql({
@@ -1,5 +1,7 @@
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import parseProviderParameters from "./parse-provider-parameters";
import type { PublicHarnessProvider } from "@/src/types";
type Params = {
@@ -14,19 +16,29 @@ export default function toPublicHarnessProvider({
provider,
}: Params): PublicHarnessProvider {
const preset = grabProviderPreset({ kind: provider.kind });
const base_url = provider.base_url || preset.base_url;
return {
id: provider.id || 0,
kind: preset.value,
name: provider.name || preset.title,
base_url: provider.base_url || preset.base_url,
base_url,
enabled: provider.enabled != 0,
has_key: Boolean(provider.api_key),
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
needs_key: preset.needs_key,
key_env: preset.key_env || undefined,
context_length: provider.context_length || undefined,
/**
* What its form shows ticked, and what its models get on the next
* sync: its saved pick, else its preset's or host's list.
*/
parameters: providerParameterKeys({
kind: preset.value,
base_url,
declared: parseProviderParameters({ text: provider.parameters }),
}),
last_synced_at: provider.last_synced_at || undefined,
sync_error: provider.sync_error || undefined,
};
}
}
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { HarnessCatalogModel } from "@/src/harness/types";
import modelContextLength from "./model-context-length";
import modelSupportedParameters from "./model-supported-parameters";
type Params = {
provider_id: number;
@@ -10,6 +11,11 @@ type Params = {
* of their own (a custom provider lists ids only).
*/
provider_context_length?: number | null;
/**
* The generation settings its provider declares, as the names a model's
* `supported_parameters` carries, for the models it lists without any.
*/
provider_parameters?: string[] | null;
now?: number;
};
@@ -49,6 +55,7 @@ export default async function upsertHarnessModels({
provider_id,
models,
provider_context_length,
provider_parameters,
now = Date.now(),
}: Params) {
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
@@ -63,27 +70,36 @@ export default async function upsertHarnessModels({
${Columns.filter((c) => c != "created_at" && c != "provider_id" && c != "slug")
.map((c) => `${c} = excluded.${c}`)
.join(", ")}`,
values: chunk.flatMap((model) => [
now,
now,
provider_id,
model.slug,
model.name || model.slug,
model.free ? 1 : 0,
1,
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
model.intelligence_score ?? null,
model.agentic_score ?? null,
model.released_at ?? null,
model.expires_at ?? null,
now,
]),
values: chunk.flatMap((model) => {
const supported_parameters = modelSupportedParameters({
model,
provider_parameters,
});
return [
now,
now,
provider_id,
model.slug,
model.name || model.slug,
model.free ? 1 : 0,
1,
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
supported_parameters
? JSON.stringify(supported_parameters)
: null,
model.intelligence_score ?? null,
model.agentic_score ?? null,
model.released_at ?? null,
model.expires_at ?? null,
now,
];
}),
});
if (!res.success) {
@@ -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
);
}
@@ -15,6 +15,10 @@ type Params = {
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in: only its tasks are in reach.
*/
workspace_id?: number | string | null;
};
/**
@@ -30,8 +34,9 @@ export default async function grabRunTask({
bot_id,
is_coordinator,
admin_workspace_ids,
workspace_id,
}: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const read = runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids });
const read = runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id });
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_TASKS>(read);
+9 -3
View File
@@ -23,6 +23,11 @@ type Params = {
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in: with `bot_id`, only that workspace's
* tasks are in reach (`botTaskScopesSql`).
*/
workspace_id?: number | string | null;
/**
* Only the tasks this bot has (anywhere, unless narrowed).
*/
@@ -48,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;
@@ -64,6 +69,7 @@ export default async function grabTasks({
bot_id,
is_coordinator,
admin_workspace_ids,
workspace_id,
only_bot_id,
with_workspace_wide,
only_workspace_id,
@@ -81,7 +87,7 @@ export default async function grabTasks({
where.push(access.sql);
values.push(...access.values);
} else if (bot_id != null) {
const access = botTaskScopesSql({ bot_id, is_coordinator: Boolean(is_coordinator), admin_workspace_ids });
const access = botTaskScopesSql({ bot_id, is_coordinator: Boolean(is_coordinator), admin_workspace_ids, workspace_id });
where.push(access.sql);
values.push(...access.values);
}
@@ -130,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],
@@ -21,8 +21,18 @@ db.run(`INSERT INTO tasks VALUES
(7, 'Another bot''s, in a workspace it works in', 11, 5, 'todo')`);
db.run(`INSERT INTO workspace_bots VALUES (5, 10)`);
function task(bot_id: number, task_id: number, options: { is_coordinator?: boolean; admin_workspace_ids?: number[] } = {}) {
const { sql, values } = runTaskSql({ task_id, bot_id, is_coordinator: options.is_coordinator ?? false, admin_workspace_ids: options.admin_workspace_ids });
function task(
bot_id: number,
task_id: number,
options: { is_coordinator?: boolean; admin_workspace_ids?: number[]; workspace_id?: number } = {},
) {
const { sql, values } = runTaskSql({
task_id,
bot_id,
is_coordinator: options.is_coordinator ?? false,
admin_workspace_ids: options.admin_workspace_ids,
workspace_id: options.workspace_id,
});
return db.query(sql).get(...values) as { id: number } | null;
}
@@ -50,6 +60,20 @@ describe("runTaskSql", () => {
expect(task(10, 6)).toBeNull();
});
test("working in a workspace, it reaches that workspace alone", () => {
expect(task(10, 3, { workspace_id: 5 })?.id).toBe(3);
expect(task(10, 4, { workspace_id: 5 })?.id).toBe(4);
expect(task(10, 1, { workspace_id: 5 })).toBeNull();
expect(task(10, 5, { workspace_id: 5 })).toBeNull();
expect(task(10, 6, { workspace_id: 5 })).toBeNull();
expect(task(10, 3, { workspace_id: 6 })).toBeNull();
});
test("the coordinator in a workspace reaches that workspace alone", () => {
expect(task(1, 5, { is_coordinator: true, workspace_id: 6 })?.id).toBe(5);
expect(task(1, 2, { is_coordinator: true, workspace_id: 6 })).toBeNull();
});
test("the coordinator reaches every task, whoever has it", () => {
expect(task(1, 2, { is_coordinator: true })?.id).toBe(2);
expect(task(1, 5, { is_coordinator: true })?.id).toBe(5);
@@ -60,6 +84,12 @@ describe("runTaskSql", () => {
expect(task(10, 5, { admin_workspace_ids: [6] })?.id).toBe(5);
expect(task(10, 6, { admin_workspace_ids: [6] })).toBeNull();
});
test("and in a run elsewhere, only what that run's workspace holds", () => {
expect(task(10, 5, { admin_workspace_ids: [6], workspace_id: 6 })?.id).toBe(5);
expect(task(10, 6, { admin_workspace_ids: [6], workspace_id: 6 })).toBeNull();
expect(task(10, 5, { admin_workspace_ids: [6], workspace_id: 5 })).toBeNull();
});
});
describe("taskRowSql", () => {
@@ -6,14 +6,19 @@ type Params = {
bot_id: number | string;
is_coordinator: boolean;
admin_workspace_ids?: number[];
/**
* The workspace the run is in: only its tasks are in reach
* (`botTaskScopesSql`).
*/
workspace_id?: number | string | null;
};
/**
* The read `grabRunTask` makes: the task, but only while the run reaches
* it. Split out so the reach rules can be run against real SQLite.
*/
export function runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids }: Params): SqlCondition {
const access = botTaskScopesSql({ bot_id, is_coordinator, admin_workspace_ids });
export function runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id }: Params): SqlCondition {
const access = botTaskScopesSql({ bot_id, is_coordinator, admin_workspace_ids, workspace_id });
return {
sql: `SELECT t.* FROM tasks t WHERE t.id = ? AND ${access.sql} LIMIT 1`,
@@ -0,0 +1,31 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
};
type UserNameRow = {
first_name: string | null;
last_name: string | null;
username: string | null;
};
/**
* The user's name as the app shows it (first and last, else username), or
* empty when they have neither. Every run's prompt gets it, so its bot knows
* who it's working for instead of asking them to confirm it.
*/
export default async function grabUserName({ user_id }: Params): Promise<string> {
const row = (
await BunSQLite.sql<UserNameRow>({
sql: `SELECT first_name, last_name, username FROM users WHERE id = ? LIMIT 1`,
values: [user_id],
})
).payload?.[0];
return (
[row?.first_name, row?.last_name].filter(Boolean).join(" ").trim() ||
row?.username?.trim() ||
""
);
}
@@ -0,0 +1,62 @@
import { AppData } from "@/src/data/app-data";
import downloadComputerFile from "@/src/functions/backend/computers/download-computer-file";
import { mimeTypeForFile } from "@/src/functions/backend/db/bot-files/media-type-for-file";
import grabComputerTarget from "@/src/functions/backend/db/computers/grab-computer-target";
import { canSeePath } from "./list-storage-entries";
import resolveStoragePath from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
type Params = {
resolved: ResolvedStorageSpec;
/**
* The file to open, relative to the volume's root.
*/
path?: string | null;
};
export type ComputerStorageFile = {
bytes: Buffer;
name: string;
size: number;
mime_type: string;
};
/**
* One file of a computer's workspace, streamed from its agent when the app
* itself can't read the folder (a dev server running as a plain user can't
* read a worker's folder). The same path rules and the same access check as
* the file on this machine (`grabStorageFile`), and the same size limit.
* Null when it isn't a file there, or the computer can't be reached.
*/
export default async function grabComputerStorageFile({
resolved,
path: requested,
}: Params): Promise<ComputerStorageFile | null> {
if (resolved.spec.volume != "computers") return null;
const resolved_path = resolveStoragePath({ root: resolved.root, path: requested });
if (!resolved_path.name) return null;
if (!canSeePath({ resolved, path: resolved_path.relative })) return null;
const target = await grabComputerTarget({ computer_id: resolved.spec.owner_id });
if (!target?.ready || target.connection != "docker") return null;
const file = `${AppData.ComputerWorkspaceDir}/${resolved_path.relative}`;
const download = await downloadComputerFile({
computer: target,
path: file,
max_bytes: AppData.StorageBrowserReadMaxBytes,
});
if (!download.ok) return null;
return {
bytes: download.bytes,
name: resolved_path.name,
size: download.size,
mime_type: mimeTypeForFile({ name: resolved_path.name }),
};
}
@@ -0,0 +1,36 @@
import { describe, expect, test } from "bun:test";
import { parseComputerDirectory } from "./list-computer-directory";
function field({ type, name, size = 0, modified = 0 }: { type: string; name: string; size?: number; modified?: number }) {
return `${type}\0${name}\0${size}\0${modified}\0`;
}
describe("parseComputerDirectory", () => {
test("reads a folder and a file, with its size and time", () => {
const output = field({ type: "d", name: "users", modified: 1763000000 }) +
field({ type: "f", name: "browser-tabs.md", size: 512, modified: 1763000000.75 });
expect(parseComputerDirectory({ output })).toEqual([
{ name: "users", kind: "folder", size: 0, modified_at: 1763000000000 },
{ name: "browser-tabs.md", kind: "file", size: 512, modified_at: 1763000000750 },
]);
});
test("leaves out anything but a folder or a file", () => {
const output = field({ type: "l", name: "escape" }) +
field({ type: "s", name: "socket" }) +
field({ type: "f", name: "kept.md", size: 1 });
expect(parseComputerDirectory({ output }).map((entry) => entry.name)).toEqual(["kept.md"]);
});
test("drops a last entry the answer was cut off in", () => {
const output = field({ type: "f", name: "kept.md", size: 1 }) + "f\0cut-off\0";
expect(parseComputerDirectory({ output }).map((entry) => entry.name)).toEqual(["kept.md"]);
});
test("reads nothing from an empty answer", () => {
expect(parseComputerDirectory({ output: "" })).toEqual([]);
});
});
@@ -0,0 +1,72 @@
import { AppData } from "@/src/data/app-data";
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
import grabComputerTarget from "@/src/functions/backend/db/computers/grab-computer-target";
import shellQuote from "@/src/utils/shell-quote";
export type ComputerDirectoryEntry = {
name: string;
kind: "file" | "folder";
size: number;
modified_at: number;
};
type Params = {
computer_id: number | string;
/**
* The folder inside the computer's workspace, relative to its root, e.g.
* `bots/14/users/1`. Empty for the root.
*/
relative: string;
};
/**
* One folder of a computer's workspace, read through its agent when the app
* itself can't open the folder: a dev server running as a plain user can't
* read a worker's folder (`cb-<bot>` owns it), while the agent runs as root
* on the computer. Hidden entries are listed like any other, and symlinks
* are left out, as the browser never follows them. Null when the computer
* can't be reached or the folder isn't there.
*/
export default async function listComputerDirectory({ computer_id, relative }: Params) {
const target = await grabComputerTarget({ computer_id });
if (!target?.ready || target.connection != "docker") return null;
const folder = relative ? `${AppData.ComputerWorkspaceDir}/${relative}` : AppData.ComputerWorkspaceDir;
const command = `sudo -n find ${shellQuote({ text: folder })} -mindepth 1 -maxdepth 1 -printf '%y\\000%f\\000%s\\000%T@\\000' 2>/dev/null`;
const result = await runComputerCommand({ computer: target, command, timeout_ms: 30_000 }).catch(() => null);
if (!result || result.exit_code != 0) return null;
return parseComputerDirectory({ output: result.output });
}
/**
* The agent's `find -printf` answer, four NUL-separated fields an entry:
* its type (`d` or `f`), name, size and modification time in seconds.
* Anything else a folder holds (a symlink, a socket) is left out, and a
* cut-off last entry (a truncated answer) is dropped whole.
*/
export function parseComputerDirectory({ output }: { output: string }) {
const fields = output.split("\0");
if (fields.at(-1) === "") fields.pop();
const entries: ComputerDirectoryEntry[] = [];
for (let index = 0; index + 3 < fields.length; index += 4) {
const [type, name, size, modified] = fields.slice(index, index + 4);
if (!name) continue;
if (type != "d" && type != "f") continue;
entries.push({
name,
kind: type == "d" ? "folder" : "file",
size: type == "f" ? Number(size) || 0 : 0,
modified_at: Math.round((Number(modified) || 0) * 1000),
});
}
return entries;
}
@@ -1,4 +1,4 @@
import { existsSync, lstatSync, readdirSync } from "node:fs";
import { lstatSync, readdirSync, type Dirent } from "node:fs";
import path from "node:path";
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_FILES } from "@/db/types/db";
@@ -6,6 +6,7 @@ import { AppData } from "@/src/data/app-data";
import grabMediaURL from "../media/grab-media-url";
import computerFolderLabel from "@/src/utils/computer-folder-label";
import computerPathAllowed from "@/src/utils/computer-path-allowed";
import listComputerDirectory, { type ComputerDirectoryEntry } from "./list-computer-directory";
import { isInsideRoot } from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
import type { StorageEntry } from "@/src/types";
@@ -58,13 +59,24 @@ export default async function listStorageEntries({
* starts, a bot's before its first file) shows as empty rather than as
* an error. `missing` keeps that apart from a path that isn't there at
* all, which a stale folder link lands on (the page says so, instead of
* claiming the folder is empty).
* claiming the folder is empty). A worker's computer folder that this
* process can't open (a dev server running as a plain user) is read
* through the computer's agent instead.
*/
if (!existsSync(absolute) || !canSeePath({ resolved, path: relative })) {
const host = hostFolderEntries({ absolute });
const rows =
host == "missing"
? null
: host == "unreadable"
? resolved.spec.volume == "computers"
? await listComputerDirectory({ computer_id: resolved.spec.owner_id, relative })
: null
: host;
if (!rows || !canSeePath({ resolved, path: relative })) {
return { entries: [], total: 0, offset, missing: true };
}
const rows = readdirSync(absolute, { withFileTypes: true });
const indexed = await botFileRows({ resolved, paths: rows.map((row) => joinPath({ relative, name: row.name })) });
const needle = search?.trim().toLowerCase() || "";
const entries: StorageEntry[] = [];
@@ -82,27 +94,13 @@ export default async function listStorageEntries({
if (!isInsideRoot({ root: resolved.root, absolute: entry_absolute })) continue;
let stats;
try {
stats = lstatSync(entry_absolute);
} catch {
continue;
}
/**
* A symlink is not followed: it may lead anywhere, and the
* volume's own folders are what this lists.
*/
if (stats.isSymbolicLink()) continue;
if (stats.isDirectory()) {
if (row.kind == "folder") {
entries.push({
name: row.name,
path: entry_path,
kind: "folder",
size: 0,
modified_at: Math.round(stats.mtimeMs),
modified_at: row.modified_at,
url: storageSpecHref({ spec: resolved.spec, path: entry_path }),
label: resolved.computer
? computerFolderLabel({ path: entry_path, names: resolved.computer.names }) || undefined
@@ -111,8 +109,6 @@ export default async function listStorageEntries({
continue;
}
if (!stats.isFile()) continue;
const file = indexed.get(entry_path);
const { media_url } = file?.media_id
? grabMediaURL({ media: { id: file.media_id } as any })
@@ -122,8 +118,8 @@ export default async function listStorageEntries({
name: row.name,
path: entry_path,
kind: "file",
size: stats.size,
modified_at: Math.round(stats.mtimeMs),
size: row.size,
modified_at: row.modified_at,
media_type: file?.media_type || undefined,
file_id: file?.id ? Number(file.id) : undefined,
url: media_url || fileUrl({ spec: resolved.spec, path: entry_path }),
@@ -199,6 +195,56 @@ export function canSeePath({ resolved, path }: { resolved: ResolvedStorageSpec;
return !resolved.computer || computerPathAllowed({ ...resolved.computer, path });
}
/**
* One folder's own entries on this machine, or why there are none: a
* missing folder, or one this process may not open (a worker's computer
* folder belongs to the worker's own account).
*/
function hostFolderEntries({
absolute,
}: {
absolute: string;
}): ComputerDirectoryEntry[] | "unreadable" | "missing" {
let rows: Dirent[];
try {
rows = readdirSync(absolute, { withFileTypes: true });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
return code == "EACCES" || code == "EPERM" ? "unreadable" : "missing";
}
const entries: ComputerDirectoryEntry[] = [];
for (const row of rows) {
let stats;
try {
stats = lstatSync(path.join(absolute, row.name));
} catch {
continue;
}
/**
* A symlink is not followed: it may lead anywhere, and the volume's
* own folders are what this lists.
*/
if (stats.isSymbolicLink()) continue;
if (stats.isDirectory()) {
entries.push({ name: row.name, kind: "folder", size: 0, modified_at: Math.round(stats.mtimeMs) });
continue;
}
if (!stats.isFile()) continue;
entries.push({ name: row.name, kind: "file", size: stats.size, modified_at: Math.round(stats.mtimeMs) });
}
return entries;
}
function joinPath({ relative, name }: { relative: string; name: string }) {
return relative ? `${relative}/${name}` : name;
}
@@ -9,6 +9,7 @@ type Params = {
| "new-session"
| "continue-session"
| "reopen-session"
| "delete-session"
| "session-messages"
| "older-messages";
body: Record<string, unknown>;
+9
View File
@@ -11,6 +11,12 @@ type Params = {
status?: number;
retryable?: boolean;
retry_at?: number;
/**
* The provider never answered within `AppData.HarnessRequestTimeoutMs`.
* A tool whose retry only waits the same span again (`generate_image`)
* reads it to stop instead of spending another three minutes.
*/
timed_out?: boolean;
provider_wide?: boolean;
candidate_key?: string;
resting?: boolean;
@@ -49,6 +55,7 @@ export default class HarnessError extends Error {
* Unix ms before which the failed candidate shouldn't be tried again.
*/
retry_at?: number;
timed_out: boolean;
/**
* The provider's key or account is the problem, so every model on it
* fails the same way.
@@ -75,6 +82,7 @@ export default class HarnessError extends Error {
status,
retryable = false,
retry_at,
timed_out = false,
provider_wide = false,
candidate_key,
resting = false,
@@ -89,6 +97,7 @@ export default class HarnessError extends Error {
this.status = status;
this.retryable = retryable;
this.retry_at = retry_at;
this.timed_out = timed_out;
this.provider_wide = provider_wide;
this.candidate_key = candidate_key;
this.resting = resting;
+26 -5
View File
@@ -7,6 +7,7 @@ import type { HarnessImageOutput, HarnessUsage } from "../types";
import buildUsageCall from "../usage/build-usage-call";
import recordHarnessUsage from "../usage/record-harness-usage";
import orderImageCandidates from "./order-image-candidates";
import referenceModelNote from "./reference-model-note";
type Params = {
prompt: string;
@@ -57,14 +58,21 @@ 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",
});
}
const harness_of = new Map(ordered.map(({ candidate, harness }) => [candidate.key, harness]));
/**
* A pick that can't take an image is skipped with references, so the
* failure names the model that actually ran and why the pick wasn't it.
*/
const note = has_references
? referenceModelNote({ image, tried: ordered[0]?.candidate.model })
: undefined;
const { result } = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
const made = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
harness: edit?.picked ? "image_edit" : "image",
harness_of,
candidates: ordered.map(({ candidate }) => candidate),
@@ -89,13 +97,19 @@ export default async function generateImage({
references,
signal: signal || new AbortController().signal,
}),
}).catch((error: unknown) => {
if (note && error instanceof Error) error.message = `${error.message} ${note}`;
throw error;
});
return result.images;
return made.result.images;
}
/**
* 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,
@@ -106,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,79 @@
import { describe, expect, test } from "bun:test";
import type { HarnessCandidate } from "../types";
import referenceModelNote from "./reference-model-note";
const candidate = ({
slug,
name,
modalities,
source,
}: {
slug: string;
name?: string;
modalities: string[];
source: HarnessCandidate["source"];
}): HarnessCandidate => ({
key: `2:${slug}`,
provider: { id: 2, kind: "custom", base_url: "https://example.test" },
model: {
slug,
name,
input_modalities: modalities,
output_modalities: ["image"],
supports_tools: false,
},
source,
});
describe("referenceModelNote", () => {
test("names the model that ran when the pick can't take a reference", () => {
const note = referenceModelNote({
image: [
candidate({ slug: "recraft-v4.1", name: "Recraft V4.1", modalities: ["text"], source: "pinned" }),
],
tried: {
slug: "qwen-image-3.0-pro",
name: "qwen-image-3.0-pro",
input_modalities: ["text", "image"],
output_modalities: ["image"],
supports_tools: false,
},
});
expect(note).toBe(
"Recraft V4.1 can't take reference images, so this went to qwen-image-3.0-pro instead.",
);
});
test("says nothing when the pick itself takes references", () => {
expect(
referenceModelNote({
image: [
candidate({
slug: "gemini-image",
modalities: ["text", "image"],
source: "pinned",
}),
],
}),
).toBeUndefined();
});
test("says nothing when image generation has no pick", () => {
expect(referenceModelNote({ image: [] })).toBeUndefined();
});
test("still says where it went when the model that ran has no name", () => {
expect(
referenceModelNote({
image: [candidate({ slug: "recraft", modalities: ["text"], source: "pinned" })],
tried: {
slug: "qwen-image",
input_modalities: ["text", "image"],
output_modalities: ["image"],
supports_tools: false,
},
}),
).toBe("recraft can't take reference images, so this went to qwen-image instead.");
});
});
+30
View File
@@ -0,0 +1,30 @@
import type { HarnessCandidate, HarnessModelInfo } from "../types";
type Params = {
/**
* Image generation's candidates, as resolved.
*/
image: HarnessCandidate[];
/**
* The model the call actually reached.
*/
tried?: HarnessModelInfo;
};
/**
* Why a call with a reference image never reached the model the Image
* setting picked: a model that can't take an image is skipped with
* references (`orderImageCandidates`), so the call went to Image editing's
* model instead. Said on the failure, because the bot reports only the model
* that ran and the user is left thinking its pick was used (Recraft was set
* a minute before a run spent 29 minutes on the old qwen edit pick).
*/
export default function referenceModelNote({ image, tried }: Params): string | undefined {
const pinned = image.find((candidate) => candidate.source == "pinned");
if (!pinned || pinned.model.input_modalities.includes("image")) return undefined;
return `${pinned.model.name || pinned.model.slug} can't take reference images, so this went to ${
tried ? tried.name || tried.slug : "another model"
} instead.`;
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { ReadImagePrompt } from "@/src/data/harness-prompts";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
import HarnessError from "../harness-error";
import grabHarnessAdapter from "../providers/grab-harness-adapter";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
@@ -56,7 +57,7 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
const { result } = await withCandidates<{
text: string;
usage?: HarnessUsage;
sent_params: Record<string, number | string | { effort: string }>;
sent_params: HarnessWireParams;
}>({
harness: "vision",
candidates,
@@ -2,6 +2,7 @@ import type { HarnessAdapter } from "../../types";
import grabProviderPreset from "../grab-provider-preset";
import providerRequest from "./provider-request";
import readChatResponse from "./read-chat-response";
import toWireChatParams from "./to-wire-chat-params";
import toWireMessages from "./to-wire-messages";
/**
@@ -24,7 +25,7 @@ const chat: HarnessAdapter["chat"] = async ({
// Generation settings first, so the core fields below always win:
// a saved parameter must never override the model, the messages,
// the tools or the token ceiling (R12).
...(params || {}),
...toWireChatParams({ params, kind: provider.kind }),
model: model.slug,
messages: toWireMessages({ messages }),
...(tools?.length
@@ -46,6 +47,7 @@ const chat: HarnessAdapter["chat"] = async ({
provider_name:
provider.name || grabProviderPreset({ kind: provider.kind }).title,
candidate_key: candidate.key,
url: res.url,
});
};
@@ -88,7 +88,14 @@ export default async function providerRequest({
: `Couldn't reach ${provider_name} at ${method} ${url}: ${error instanceof Error ? error.message : String(error)}`
: `${provider_name} stopped sending the response.`;
return new HarnessError({ message, retryable: true, candidate_key, method, url });
return new HarnessError({
message,
retryable: true,
candidate_key,
method,
url,
timed_out: phase == "headers" && controller.signal.aborted,
});
};
let res: Response;
@@ -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,
});
}

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