Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15d4f85e14 | ||
|
|
39055f8028 | ||
|
|
87be48ffb5 | ||
|
|
7bc9ab93ad | ||
|
|
0eee6781c4 |
@@ -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`,
|
||||
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.12",
|
||||
"version": "0.28.14",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -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)`);
|
||||
|
||||
@@ -57,6 +57,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 +90,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";
|
||||
@@ -394,6 +396,17 @@ export default async function runBotReply({
|
||||
* back to the bot that asked while the work is still open).
|
||||
*/
|
||||
const ask_id_for_updates = job_ask_id || (open_ask?.id ? Number(open_ask.id) : 0);
|
||||
/**
|
||||
* The request this conversation answered and that has since ended: the
|
||||
* one place a late or corrected answer can go back from, so the bot
|
||||
* doesn't open a fresh request through the gate for what belongs to
|
||||
* that one (an ended request's answer session, once the user resumes
|
||||
* it, had no way to finish back).
|
||||
*/
|
||||
const ended_ask =
|
||||
!ask_id_for_updates && session_id
|
||||
? await grabEndedAskBySession({ session_id: Number(session_id), user_id }).catch(() => null)
|
||||
: null;
|
||||
let led: WorkspaceAdminTools | null = null;
|
||||
|
||||
const tools = await grabBotChatTools({
|
||||
@@ -547,6 +560,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,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
@@ -618,6 +642,7 @@ export default async function runBotReply({
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
job_id: job.id,
|
||||
on_step: on_plan_step,
|
||||
/**
|
||||
* A plan nobody approved yet needs the user, so
|
||||
@@ -669,12 +694,18 @@ 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,
|
||||
can_hand_over ? HandOverTaskNote : "",
|
||||
|
||||
@@ -74,6 +74,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";
|
||||
@@ -288,6 +290,16 @@ export default async function runBotTask({
|
||||
* (`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,6 +338,7 @@ export default async function runBotTask({
|
||||
scopes,
|
||||
hooked,
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
job_id: job.id,
|
||||
})),
|
||||
...admin_tools,
|
||||
/**
|
||||
@@ -339,6 +352,7 @@ export default async function runBotTask({
|
||||
bot_id: bot.id,
|
||||
session_id: session_id!,
|
||||
workspace_id,
|
||||
job_id: job.id,
|
||||
on_step: true,
|
||||
onPlan: ({ ref }) => shown.push(ref),
|
||||
})
|
||||
@@ -354,6 +368,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,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
@@ -638,14 +663,19 @@ export default async function runBotTask({
|
||||
const system = [
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
TaskRunNote({ can_ask }),
|
||||
steps_note,
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
install_request_id ? InstallRequestNote : "",
|
||||
Number(params.ask_id) ? AskTaskRunNote : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
/**
|
||||
* Only when the run has a computer: the note describes its folders
|
||||
* and its browser, and a run with none has no computer tools at all
|
||||
* (the closing note below is what tells it so).
|
||||
*/
|
||||
computer ? ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }) : "",
|
||||
named_files_note,
|
||||
TasksNote,
|
||||
/**
|
||||
|
||||
@@ -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],
|
||||
});
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -231,10 +231,13 @@ describe("wrapUpWorktreeNote", () => {
|
||||
});
|
||||
|
||||
describe("TaskRunNote", () => {
|
||||
const attended = TaskRunNote({ can_ask: true });
|
||||
const unattended = TaskRunNote({ can_ask: false });
|
||||
|
||||
test("says a brief can be wrong about the tree, and that handing on finishes the task", () => {
|
||||
expect(TaskRunNote).toContain("A brief can be wrong about the repository");
|
||||
expect(TaskRunNote).toContain("the tree wins");
|
||||
expect(TaskRunNote).toContain("start_task with separate for the rest");
|
||||
expect(attended).toContain("A brief can be wrong about the repository");
|
||||
expect(attended).toContain("the tree wins");
|
||||
expect(attended).toContain("start_task with separate for the rest");
|
||||
});
|
||||
|
||||
test("gives the plan permission to hand work on", () => {
|
||||
@@ -242,11 +245,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");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -408,10 +417,18 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
|
||||
|
||||
/**
|
||||
* Added to a bot's prompt when it works through a queued task.
|
||||
*
|
||||
* `can_ask` decides whether it may name `ask_user`: a routine, a hook call or
|
||||
* a hidden session has no card the user would see (the tool is taken away
|
||||
* there), so the note must not order a call that isn't offered.
|
||||
*/
|
||||
export const TaskRunNote = `# Working on a task
|
||||
export const TaskRunNote = ({ can_ask }: { can_ask: boolean }) => `# Working on a task
|
||||
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest${
|
||||
can_ask
|
||||
? `: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user`
|
||||
: `, or state the outcome plainly`
|
||||
}. Keep the report short and in markdown.
|
||||
|
||||
When they asked for this work in their chat, the run opens with their own words: that message is the request itself, and the brief after it is your summary of it. Where the two disagree the words win, and the way they named (a tool, app, service or path) is the way it is done. If that way can't work, the report says what blocked it and what the alternatives are; never reach the same result some other way without asking first.
|
||||
|
||||
@@ -423,7 +440,11 @@ Work larger than one run is handed on, not half-done: start_task with separate f
|
||||
|
||||
The report ends with send_reply and the text beside it: status "done" when nothing follows it, "working" when you handed work on and it is still running, or "blocked" when it can't finish. A report without it is a draft and is never sent.
|
||||
|
||||
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same.${
|
||||
can_ask
|
||||
? ` If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`
|
||||
: ""
|
||||
}`;
|
||||
|
||||
/**
|
||||
* Told to a task run with what the user wrote in its conversation since
|
||||
@@ -624,6 +645,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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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[] = [];
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -5,6 +5,8 @@ import AppError from "@/src/utils/app-error";
|
||||
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
|
||||
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import botFaceAfterJob from "./bot-face-after-job";
|
||||
|
||||
type Params = {
|
||||
@@ -59,5 +61,13 @@ export default async function cancelBotJob({ user_id, job_id }: Params) {
|
||||
|
||||
await settleInstallRequest({ job, text: BotJobCancelledError, failed: true });
|
||||
|
||||
/**
|
||||
* Its plan pauses with it, the way a stopped or failed run's does: no
|
||||
* card would ever offer the step again otherwise.
|
||||
*/
|
||||
const paused_plan = await pauseFailedPlanStep({ job }).catch(() => null);
|
||||
|
||||
if (paused_plan) await pushBotPlan(paused_plan).catch(() => null);
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
@@ -169,7 +169,13 @@ export default async function completeBotJob({
|
||||
}
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
|
||||
/**
|
||||
* A job that failed, was retried and then answered must not stay
|
||||
* marked with the old failure: the Details modal reads last_error off
|
||||
* the row (job #699 shipped as "completed" beside "The model returned
|
||||
* an empty answer.").
|
||||
*/
|
||||
sql: `UPDATE bots_queue SET result = ?, finished_at = ?, last_error = NULL WHERE id = ?`,
|
||||
values: [result, now, job.id],
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
worker: string;
|
||||
/**
|
||||
* The handler's family (`AppData.BotQueueWorker`), not its own id: the id
|
||||
* carries the process's pid, so a restart releases what the previous
|
||||
* process of this install was running.
|
||||
*/
|
||||
family: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -9,12 +14,12 @@ type Params = {
|
||||
* instead of waiting out the lock timeout. For startup, after a restart
|
||||
* cut those jobs off. The cut-off attempt isn't counted.
|
||||
*/
|
||||
export default async function releaseWorkerBotJobs({ worker }: Params) {
|
||||
export default async function releaseWorkerBotJobs({ family }: Params) {
|
||||
const now = Date.now();
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `UPDATE bots_queue SET status = 'pending', attempts = MAX(attempts - 1, 0), available_at = ?, locked_at = NULL, locked_by = NULL, updated_at = ? WHERE status = 'processing' AND locked_by = ? RETURNING id`,
|
||||
values: [now, now, worker],
|
||||
sql: `UPDATE bots_queue SET status = 'pending', attempts = MAX(attempts - 1, 0), available_at = ?, locked_at = NULL, locked_by = NULL, updated_at = ? WHERE status = 'processing' AND (locked_by = ? OR locked_by LIKE ?) RETURNING id`,
|
||||
values: [now, now, family, `${family}-%`],
|
||||
});
|
||||
|
||||
return res.payload?.length || 0;
|
||||
|
||||
@@ -13,9 +13,12 @@ import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
|
||||
import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
import stopAsk from "../asks/stop-ask";
|
||||
import stopAsks from "../asks/stop-asks";
|
||||
import grabAsk from "../asks/grab-ask";
|
||||
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
|
||||
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import withMessageUsage from "../usage/with-message-usage";
|
||||
@@ -126,6 +129,15 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
|
||||
|
||||
await recordHookCallResponse({ job: stopped, status: "failed", response: BotJobStoppedError, now });
|
||||
|
||||
/**
|
||||
* A plan whose step this run was working pauses with it, the way a
|
||||
* failed run's does (`notifyBotJobFailed`): nothing else would ever
|
||||
* advance it, and the card would show that step running for ever.
|
||||
*/
|
||||
const paused_plan = await pauseFailedPlanStep({ job: stopped }).catch(() => null);
|
||||
|
||||
if (paused_plan) await pushBotPlan(paused_plan).catch(() => null);
|
||||
|
||||
/**
|
||||
* A coordinator stopped on an install request: the worker that
|
||||
* asked is told.
|
||||
@@ -187,19 +199,44 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
|
||||
}
|
||||
|
||||
for (const ask_id of ask_ids) {
|
||||
/**
|
||||
* When the answer run already finished, the request isn't left
|
||||
* silent: its acknowledgement went back as an update (with the
|
||||
* files and anything it asked to check), so the stopped reason
|
||||
* tells the asker that what it already has stands and only the
|
||||
* queued work is gone. A stopped answer run means there truly is
|
||||
* no answer.
|
||||
*/
|
||||
const ask = await grabAsk({ ask_id }).catch(() => null);
|
||||
|
||||
const answered =
|
||||
!!ask?.job_id &&
|
||||
!!(
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bots_queue WHERE id = ? AND status = 'completed' LIMIT 1`,
|
||||
values: [Number(ask.job_id)],
|
||||
}).catch(() => null)
|
||||
)?.payload?.length;
|
||||
|
||||
await stopAsk({
|
||||
ask_id,
|
||||
reason: "The user stopped the run answering it, so there is no answer.",
|
||||
reason: answered
|
||||
? "The user stopped the work it had queued before it finished. Anything it had already answered stands."
|
||||
: "The user stopped the run answering it, so there is no answer.",
|
||||
}).catch(() => null);
|
||||
}
|
||||
|
||||
/**
|
||||
* And the requests a run of its own had open go with it: its bot isn't
|
||||
* woken about work the user just stopped.
|
||||
* woken about work the user just stopped. Matched by the run that made
|
||||
* each request, so stopping one run never ends an ask another run of
|
||||
* the same conversation is waiting on; asks made before that was
|
||||
* recorded keep the old session match.
|
||||
*/
|
||||
await stopAsks({
|
||||
user_id,
|
||||
requester_bot_id: bot_id,
|
||||
job_ids: jobs.map((job) => Number(job.id)),
|
||||
session_ids: open.map((job) => Number(job.session_id)),
|
||||
}).catch(() => []);
|
||||
|
||||
@@ -236,9 +273,23 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
|
||||
|
||||
if (answered) continue;
|
||||
|
||||
/**
|
||||
* The session this run's conversation is in now, not the one it was
|
||||
* queued in: a reply that carried the conversation into a new session
|
||||
* between the UPDATE above and here would put the stopped line in a
|
||||
* thread the user has left, and the live conversation would show
|
||||
* nothing.
|
||||
*/
|
||||
const current = (
|
||||
await BunSQLite.sql<{ session_id: number | null }>({
|
||||
sql: `SELECT session_id FROM bots_queue WHERE id = ?`,
|
||||
values: [Number(job.id)],
|
||||
}).catch(() => null)
|
||||
)?.payload?.[0]?.session_id;
|
||||
|
||||
const message = await insertBotMessage({
|
||||
bot_id: Number(bot_id),
|
||||
session_id,
|
||||
session_id: Number(current || session_id),
|
||||
workspace_id: job.workspace_id || null,
|
||||
text: stoppedJobReport({ job }),
|
||||
}).catch(() => null);
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ export default async function generateImage({
|
||||
|
||||
if (has_references && !ordered.length && image.length) {
|
||||
throw new HarnessError({
|
||||
message: `None of the image models here takes reference images. A super admin can pick one under Image editing in Settings, under Models.`,
|
||||
message: `None of the image models here takes reference images. A super admin can pick one under Image editing in Settings, under Models, or turn Image editing's fallback on to send the call to a generation model that takes them.`,
|
||||
code: "unavailable",
|
||||
});
|
||||
}
|
||||
@@ -107,7 +107,9 @@ export default async function generateImage({
|
||||
}
|
||||
|
||||
/**
|
||||
* Image editing's setting and candidates, or undefined while it's off.
|
||||
* Image editing's setting and candidates. Turned off still reports its
|
||||
* fallback, so a call with references can hand over to a generation model
|
||||
* that takes images (with fallback off it never leaves the harness).
|
||||
*/
|
||||
async function grabEdit({
|
||||
bot_id,
|
||||
@@ -118,7 +120,14 @@ async function grabEdit({
|
||||
}) {
|
||||
const setting = await grabHarnessSetting({ harness: "image_edit", bot_id, workspace_id });
|
||||
|
||||
if (!setting.enabled) return undefined;
|
||||
if (!setting.enabled) {
|
||||
/**
|
||||
* Turned off still hands its fallback flag down: a call with
|
||||
* references may go to a generation model that takes images, but only
|
||||
* while fallback is on, or it would leave the harness quietly.
|
||||
*/
|
||||
return { picked: false, fallback: setting.fallback, candidates: [] };
|
||||
}
|
||||
|
||||
return {
|
||||
picked: Boolean(setting.model_id),
|
||||
|
||||
@@ -47,6 +47,7 @@ const chat: HarnessAdapter["chat"] = async ({
|
||||
provider_name:
|
||||
provider.name || grabProviderPreset({ kind: provider.kind }).title,
|
||||
candidate_key: candidate.key,
|
||||
url: res.url,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import toHarnessError from "../to-harness-error";
|
||||
import type { HarnessChatResult, HarnessToolCall } from "../../types";
|
||||
import readReasoning from "./read-reasoning";
|
||||
import redactProviderError from "../redact-provider-error";
|
||||
|
||||
type WireToolCall = {
|
||||
id?: string;
|
||||
@@ -15,6 +15,10 @@ type Params = {
|
||||
json: any;
|
||||
provider_name: string;
|
||||
candidate_key?: string;
|
||||
/**
|
||||
* Where the call went, so a refusal names the address it came from.
|
||||
*/
|
||||
url?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -25,15 +29,22 @@ export default function readChatResponse({
|
||||
json,
|
||||
provider_name,
|
||||
candidate_key,
|
||||
url,
|
||||
}: Params): HarnessChatResult {
|
||||
if (json?.error) {
|
||||
const status = Number(json.error.code) || undefined;
|
||||
|
||||
throw new HarnessError({
|
||||
message: `${provider_name}: ${redactProviderError({ text: json.error.message || "The model failed." })}`,
|
||||
status,
|
||||
retryable: !status || status == 429 || status >= 500,
|
||||
/**
|
||||
* Built by the classifier, not by hand: a 200 carrying an error body
|
||||
* skipped `toHarnessError` whole, so an oversized request read as a
|
||||
* plain refusal that benched nothing and re-fired on every turn (52
|
||||
* failed rows, one task limping through its fallbacks for 18 minutes).
|
||||
* Overflow, a dead key and the provider's own words are decided there.
|
||||
*/
|
||||
throw toHarnessError({
|
||||
status: Number(json.error.code) || 400,
|
||||
body: JSON.stringify({ error: json.error }),
|
||||
provider_name,
|
||||
candidate_key,
|
||||
url,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,13 @@ import type { HarnessCooldowns } from "./create-cooldowns";
|
||||
*/
|
||||
const slot = globalCache<HarnessCooldowns>({ name: "cobble.harnessCooldowns" });
|
||||
|
||||
const HarnessCooldowns = slot.get() || createCooldowns();
|
||||
/**
|
||||
* Not named `HarnessCooldowns`: the type of that name is imported above, and
|
||||
* an `export default` of a name both declare resolves to the type for some
|
||||
* compilers, so every importer of this value is then called a type-only import.
|
||||
*/
|
||||
const cooldowns = slot.get() || createCooldowns();
|
||||
|
||||
slot.set(HarnessCooldowns);
|
||||
slot.set(cooldowns);
|
||||
|
||||
export default HarnessCooldowns;
|
||||
export default cooldowns;
|
||||
@@ -101,6 +101,25 @@ export default async function resolveHarnessCandidates({
|
||||
modelServesHarness({ model: entry, harness }),
|
||||
);
|
||||
|
||||
/**
|
||||
* A pick that can't run is not "no model set up": with fallback off the
|
||||
* call would otherwise answer on a free automatic pick while the setting
|
||||
* names a model, and the usage row would say `auto` (this is how a pinned
|
||||
* tool-less model ran eleven replies and none of them closed).
|
||||
*/
|
||||
if (setting.model_id && !pinned && !setting.fallback) {
|
||||
const title = Harnesses.find((h) => h.value == harness)?.title;
|
||||
const slug = rows.find((row) => row.id == setting.model_id)?.slug;
|
||||
|
||||
throw new HarnessError({
|
||||
message:
|
||||
`${slug || "The picked model"} can't be used for ${title ? title.toLowerCase() : harness} ` +
|
||||
`(it's unavailable, its provider isn't usable, or it doesn't serve this harness), and fallback is off. ` +
|
||||
`Pick a model that serves it under Models, or turn fallback on.`,
|
||||
code: "unavailable",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Each fallback model names its own provider, so the setting's
|
||||
* provider limit doesn't apply to them.
|
||||
|
||||
@@ -165,7 +165,26 @@ export default async function withCandidates<T>({
|
||||
|
||||
return { result, candidate };
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof HarnessError)) throw error;
|
||||
if (!(error instanceof HarnessError)) {
|
||||
/**
|
||||
* A bug in an adapter is not swallowed (it goes up as it is),
|
||||
* but it stops being invisible: with no row the message's
|
||||
* Details modal showed nothing at all for the call that ended
|
||||
* the run.
|
||||
*/
|
||||
if (log_failures) {
|
||||
await recordHarnessFailure({
|
||||
harness: harness_of?.get(candidate.key) || harness,
|
||||
candidate,
|
||||
error: new HarnessError({
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
candidate_key: candidate.key,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
if (error.code == "aborted") throw error;
|
||||
/**
|
||||
* A fatal failure is the run's own: another model fails the same
|
||||
@@ -229,7 +248,13 @@ export default async function withCandidates<T>({
|
||||
}
|
||||
}
|
||||
|
||||
const last = errors[errors.length - 1];
|
||||
/**
|
||||
* The error worth reading, not simply the last one: a dead key on the
|
||||
* first candidate and a 400 on the second left the bot told its user the
|
||||
* request was bad, when the provider's key was the whole story.
|
||||
*/
|
||||
const last =
|
||||
errors.find((error) => error.provider_wide || error.fatal) || errors[errors.length - 1];
|
||||
|
||||
if (!last) {
|
||||
const next = soonestRest({ candidates: ordered, cooldowns, now: now() });
|
||||
@@ -369,7 +394,13 @@ function coolDown({
|
||||
return at;
|
||||
}
|
||||
|
||||
if (error.status == 403 || error.status == 404) {
|
||||
/**
|
||||
* A 405 says the path isn't there at all (`toHarnessError` calls it a
|
||||
* missing endpoint), so another turn on the same base URL answers the
|
||||
* same way: benched like a 404, or a wrong base URL is paid for on every
|
||||
* turn, forever.
|
||||
*/
|
||||
if (error.status == 403 || error.status == 404 || error.status == 405) {
|
||||
cooldowns.set({ key: candidate.key, at: until });
|
||||
return until;
|
||||
}
|
||||
|
||||
@@ -37,7 +37,10 @@ export type GenerateTextParams = {
|
||||
*/
|
||||
limits?: HarnessCallLimits;
|
||||
/**
|
||||
* Overrides the saved generation settings (media reading wants 0).
|
||||
* Overrides the saved generation settings (media reading wants 0). Sent as
|
||||
* given: `prepareMessagesForModel` and `readImage` build their own call, and
|
||||
* anything passed here must already be keys the candidate advertises, since
|
||||
* this path does not filter them the way `grabChatParams` does.
|
||||
*/
|
||||
params?: HarnessWireParams;
|
||||
signal?: AbortSignal;
|
||||
@@ -146,8 +149,16 @@ export default async function generateText({
|
||||
: { text: "", reasoning: null };
|
||||
|
||||
if (!stripped.text && !answer.tool_calls.length) {
|
||||
/**
|
||||
* Named for what happened: a thinking model whose content came
|
||||
* back empty or all inline tags reaches here, and "an empty
|
||||
* answer" sent a bot to explain a model it had just been
|
||||
* charged for (job 699 attempt 1).
|
||||
*/
|
||||
throw new HarnessError({
|
||||
message: `The model returned an empty answer.`,
|
||||
message: answer.reasoning || stripped.reasoning
|
||||
? `The model answered with only its thinking: no message and no tool call.`
|
||||
: `The model returned an empty answer.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, closingToolGoneNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, StoppedRunNote, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, closingToolGoneNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyCardFailedNote, replyClosingFailedNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, StoppedRunNote, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -2202,6 +2202,115 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingRequiredNote });
|
||||
});
|
||||
|
||||
test("a card the tool refused beside a good send_reply names the card, not send_reply", async () => {
|
||||
/**
|
||||
* Job 699: `send_reply` returned ok and `suggest_next_steps` refused a
|
||||
* step over its length cap. The note said "send_reply did not go
|
||||
* through", so the model spent three turns re-writing a message that
|
||||
* had already shipped, and the trace logged closing_failed against the
|
||||
* wrong tool.
|
||||
*/
|
||||
const cappedSteps: HarnessTool<{ steps: string[] }> = {
|
||||
name: "suggest_next_steps",
|
||||
description: "Offers the next steps as buttons.",
|
||||
schema: z.object({
|
||||
steps: z.array(z.string().max(AppData.BotSuggestionStepMaxChars, "Keep each step under 120 characters")),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
suggested.push(...args.steps);
|
||||
return "Suggested. The buttons are under your message.";
|
||||
},
|
||||
};
|
||||
const long_step =
|
||||
"Summarise every tab open in the browser on the computer, name the ones you think are stale, and tell me which I can close today.";
|
||||
|
||||
expect(long_step.length).toBeGreaterThan(AppData.BotSuggestionStepMaxChars);
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Nine tabs are open.",
|
||||
tool_calls: [
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
{ id: "c1", name: "suggest_next_steps", arguments: JSON.stringify({ steps: [long_step] }) },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Nine tabs are open.",
|
||||
tool_calls: [
|
||||
{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
{ id: "c2", name: "suggest_next_steps", arguments: `{"steps":["Close the extras"]}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "What's open?" }],
|
||||
tools: [sendReply, cappedSteps],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({
|
||||
role: "user",
|
||||
content: replyCardFailedNote({ tools: ["suggest_next_steps"] }),
|
||||
});
|
||||
expect(result.text).toBe("Nine tabs are open.");
|
||||
expect(result.tool_uses).toEqual([
|
||||
{ name: "send_reply", ok: true },
|
||||
{ name: "suggest_next_steps", ok: false },
|
||||
{ name: "send_reply", ok: true },
|
||||
{ name: "suggest_next_steps", ok: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a send_reply that failed is still blamed, even beside a failed card", async () => {
|
||||
const failingSend: HarnessTool<{ status?: string }> = {
|
||||
name: "send_reply",
|
||||
description: "Sends the message.",
|
||||
schema: z.object({ status: z.string().optional() }),
|
||||
run: async () => {
|
||||
throw new Error('Status "working" needs work queued in the call.');
|
||||
},
|
||||
};
|
||||
const refusedSteps: HarnessTool<{ steps: string[] }> = {
|
||||
name: "suggest_next_steps",
|
||||
description: "Offers the next steps as buttons.",
|
||||
schema: z.object({ steps: z.array(z.string()) }),
|
||||
run: async () => {
|
||||
throw new Error("Keep each step under 120 characters");
|
||||
},
|
||||
};
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "I'm on it.",
|
||||
tool_calls: [
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"working"}` },
|
||||
{ id: "c1", name: "suggest_next_steps", arguments: `{"steps":["Look again"]}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Check the browser." }],
|
||||
tools: [failingSend, refusedSteps],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* Both closing calls failed, so the message never went out and the old
|
||||
* note is the right one: it names send_reply, which is what has to be
|
||||
* fixed. Only a card failing on its own takes the new note.
|
||||
*/
|
||||
expect(seen[1]!.messages.at(-1)!.content).toBe(replyClosingFailedNote);
|
||||
expect(result.text).toBe("");
|
||||
});
|
||||
|
||||
test("send_reply with no message beside it is told once", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
oversizedRequestNote,
|
||||
repairedAnswerNote,
|
||||
repeatedAnswerNote,
|
||||
replyCardFailedNote,
|
||||
replyClosingFailedNote,
|
||||
replyClosingMixedNote,
|
||||
replyClosingRequiredNote,
|
||||
@@ -1088,6 +1089,13 @@ export default async function runTextLoop({
|
||||
* ends).
|
||||
*/
|
||||
if (wrap_up_saving && answer.tool_calls.length && !tool_calls.length) {
|
||||
/**
|
||||
* Traced before the note, like the stray-call turn below: the run
|
||||
* did call these, and a debug view that skipped the turn showed a
|
||||
* wrap up with nothing in it.
|
||||
*/
|
||||
await traceTurn({ index, answer, calls: answer.tool_calls, started_at: turn_started_at });
|
||||
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
content: `Only ${wrap_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
|
||||
@@ -1490,8 +1498,26 @@ export default async function runTextLoop({
|
||||
* to ask again, which the once-per-run guard refuses, and the same
|
||||
* note looped for the whole budget (H1).
|
||||
*/
|
||||
const closing_uses = tool_uses.slice(-tool_calls.length).filter((use) => isClosingTool({ name: use.name }));
|
||||
const closing_failed = closing_uses.some((use) => !use.ok);
|
||||
const closing_uses = (tool_calls.length ? tool_uses.slice(-tool_calls.length) : []).filter((use) =>
|
||||
isClosingTool({ name: use.name }),
|
||||
);
|
||||
const failed_closing = closing_uses.filter((use) => !use.ok);
|
||||
const closing_failed = failed_closing.length > 0;
|
||||
/**
|
||||
* Which closing call failed decides the note. A card the tool refused
|
||||
* (`suggest_next_steps` over its length cap) is not `send_reply`
|
||||
* failing: its message is kept, and telling the model the send did not
|
||||
* go through sent it re-writing the answer for nothing (job 699, three
|
||||
* turns and a `closing_failed` trace against the wrong tool).
|
||||
*/
|
||||
const send_reply_failed = failed_closing.some((use) => use.name === SendReplyToolName);
|
||||
const failed_cards = failed_closing.filter((use) => use.name !== SendReplyToolName).map((use) => use.name);
|
||||
const closing_failed_note =
|
||||
send_reply_failed || !called_send_reply
|
||||
? called_send_reply || require_closing_answer
|
||||
? replyClosingFailedNote
|
||||
: closingFailedNote
|
||||
: replyCardFailedNote({ tools: failed_cards });
|
||||
const closing_worked = closing && !closing_failed && closing_required;
|
||||
/**
|
||||
* The message this turn wrote beside the call. An earlier draft is
|
||||
@@ -1544,7 +1570,7 @@ export default async function runTextLoop({
|
||||
return {
|
||||
text: "",
|
||||
review_note: closing_failed
|
||||
? replyClosingFailedNote
|
||||
? closing_failed_note
|
||||
: !closing
|
||||
? replyClosingMixedNote
|
||||
: replyClosingRequiredNote,
|
||||
@@ -1572,9 +1598,7 @@ export default async function runTextLoop({
|
||||
closing_retries++;
|
||||
|
||||
const note = closing_failed
|
||||
? called_send_reply || require_closing_answer
|
||||
? replyClosingFailedNote
|
||||
: closingFailedNote
|
||||
? closing_failed_note
|
||||
: !closing
|
||||
? called_send_reply
|
||||
? replyClosingMixedNote
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, mock, test } from "bun:test";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
|
||||
|
||||
/**
|
||||
* `answer_requester` closes the gap where a request's answer session is
|
||||
* resumed after the request ended: the finished or corrected answer goes
|
||||
* straight back to the bot that asked, on the ended request's own record,
|
||||
* instead of a fresh `ask_bot` the gate reads as a new handoff. It shares
|
||||
* the answer's files, strips question refs, refuses while the request is
|
||||
* still open (the machinery relays that itself), and only for the bot the
|
||||
* request was passed to.
|
||||
*/
|
||||
let ask: BUN_SQLITE_COBBLE_BOT_ASKS | null;
|
||||
let shared: string[] = [];
|
||||
let told: Array<{ text: string }> = [];
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
mock.module("@/src/functions/backend/db/asks/grab-ask", () => ({
|
||||
default: async () => ask,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/asks/share-ask-files", () => ({
|
||||
default: async ({ answer }: { answer: string }) => {
|
||||
shared.push(answer);
|
||||
return answer;
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/asks/tell-ask-requester", () => ({
|
||||
default: async ({ text }: { text: string }) => {
|
||||
told.push({ text });
|
||||
return { session_id: 56, message: { id: 900 } };
|
||||
},
|
||||
}));
|
||||
|
||||
const answerRequesterTool = (await import("./answer-requester-tool")).default;
|
||||
|
||||
const endedAsk = {
|
||||
id: 24,
|
||||
status: "answered",
|
||||
title: "Sample blog post banner",
|
||||
target_bot_id: 8,
|
||||
requester_bot_id: 6,
|
||||
} as BUN_SQLITE_COBBLE_BOT_ASKS;
|
||||
|
||||
describe("answerRequesterTool", () => {
|
||||
test("a late answer goes back on the ended request and wakes the asker", async () => {
|
||||
ask = endedAsk;
|
||||
shared = [];
|
||||
told = [];
|
||||
|
||||
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
|
||||
const res = await tool.run({ args: { text: "Banner finished: [file:389]." }, signal });
|
||||
|
||||
expect(shared).toEqual(["Banner finished: [file:389]."]);
|
||||
expect(told.length).toBe(1);
|
||||
expect(told[0]?.text).toContain("Banner finished: [file:389].");
|
||||
expect(told[0]?.text).toContain("had already ended");
|
||||
expect(String(res)).toContain("Sent to the bot that asked");
|
||||
});
|
||||
|
||||
test("an open request is refused: its answer goes back on its own", async () => {
|
||||
ask = { ...endedAsk, status: "working" };
|
||||
told = [];
|
||||
|
||||
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
|
||||
|
||||
await expect(tool.run({ args: { text: "Here." }, signal })).rejects.toThrow("still open");
|
||||
expect(told).toEqual([]);
|
||||
});
|
||||
|
||||
test("only the bot the request was passed to can answer it back", async () => {
|
||||
ask = endedAsk;
|
||||
told = [];
|
||||
|
||||
const tool = answerRequesterTool({ user_id: 1, bot_id: 9, ask_id: 24 });
|
||||
|
||||
await expect(tool.run({ args: { text: "Here." }, signal })).rejects.toThrow("didn't answer that request");
|
||||
expect(told).toEqual([]);
|
||||
});
|
||||
|
||||
test("a stopped request can still be answered late", async () => {
|
||||
ask = { ...endedAsk, status: "stopped" };
|
||||
told = [];
|
||||
|
||||
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
|
||||
await tool.run({ args: { text: "Finished after all." }, signal });
|
||||
|
||||
expect(told.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabAsk from "@/src/functions/backend/db/asks/grab-ask";
|
||||
import askUpdateMessage from "@/src/functions/backend/db/asks/ask-update-message";
|
||||
import shareAskFiles from "@/src/functions/backend/db/asks/share-ask-files";
|
||||
import tellAskRequester from "@/src/functions/backend/db/asks/tell-ask-requester";
|
||||
import stripQuestionRefs from "@/src/utils/strip-question-refs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
/**
|
||||
* The bot answering: only the bot the request was passed to may send
|
||||
* its answer back.
|
||||
*/
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* The ended request this conversation answered, found by the caller
|
||||
* through `grabEndedAskBySession`.
|
||||
*/
|
||||
ask_id: number | string;
|
||||
/**
|
||||
* What the run typed, run through the run's secret redaction before it
|
||||
* is stored: the answer lands in another bot's conversation, where a
|
||||
* raw env value would sit in a message forever.
|
||||
*/
|
||||
redact?: (text: string) => string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The gap `ask_bot` kept falling into: the request ended (often `blocked`,
|
||||
* or stopped), the user carries on in the answer session and gets the work
|
||||
* done, and the bot's only way back to the asking bot was a brand-new
|
||||
* request - which the gate reads as a fresh handoff and can refuse, leaving
|
||||
* the asker never told. This tool posts the finished answer straight back to
|
||||
* the conversation the request came from, on the ended request's own record
|
||||
* (`from_ask_id`, with its files shared), and wakes the asking bot. It ends
|
||||
* nothing and reopens nothing: the request's row keeps the status it ended
|
||||
* with, and the message says plainly it arrived after the end.
|
||||
*/
|
||||
export default function answerRequesterTool({ user_id, bot_id, ask_id, redact = (text) => text }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "answer_requester",
|
||||
description: `Send the bot that asked you a late or corrected answer to the request this conversation answered - after that request had already ended (blocked, stopped or answered). It lands in the conversation the request came from, shares any files it names, and wakes that bot. Use this instead of ask_bot for finishing what that request asked: a new request goes through the coordinator again and reads as a different handoff. Your ordinary answer here is the message; this tool is only for getting it back to the bot that asked.`,
|
||||
schema: z.object({
|
||||
text: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(AppData.AskBriefMaxChars)
|
||||
.describe(`The answer (markdown): what you finished, with [file:ID] refs for what you produced`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const ask = await grabAsk({ ask_id, user_id });
|
||||
|
||||
if (!ask?.id) {
|
||||
throw new Error(`That request isn't here anymore.`);
|
||||
}
|
||||
|
||||
if (ask.status == "pending" || ask.status == "working") {
|
||||
throw new Error(
|
||||
`This request is still open: your answer goes back on its own when your work ends, and update_requester sends a word meanwhile.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (Number(ask.target_bot_id) != Number(bot_id)) {
|
||||
throw new Error(`This conversation didn't answer that request, so it has no answer to send back.`);
|
||||
}
|
||||
|
||||
const shared = stripQuestionRefs({
|
||||
text: await shareAskFiles({ ask, answer: redact(args.text) }),
|
||||
}).text;
|
||||
|
||||
await tellAskRequester({ ask, text: askUpdateMessage({ ask, text: shared, ended: true }) });
|
||||
|
||||
return `Sent to the bot that asked, on "${ask.title}" [ask:${ask.id}]. Its conversation wakes for it.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -20,6 +20,11 @@ type Params = {
|
||||
* Where it works: in a workspace, only its members can be asked.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* The run asking, recorded on the ask so stopping that run ends this
|
||||
* request and no other ask from the same conversation.
|
||||
*/
|
||||
job_id?: number | string | null;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -37,7 +42,7 @@ type Args = {
|
||||
* call, never the model's: in a workspace its members, otherwise every worker
|
||||
* the user reaches.
|
||||
*/
|
||||
export default function askBotTool({ user_id, bot_id, session_id, workspace_id }: Params): HarnessTool<Args> {
|
||||
export default function askBotTool({ user_id, bot_id, session_id, workspace_id, job_id }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "ask_bot",
|
||||
description: `Ask another bot for something you need (what it knows, a file it has, work in its line). The coordinator reads every request first: it passes it to the bot that should answer, sends it to a better-placed bot, or turns it down with the reason. An approved request's answer comes back here as a message, which wakes you to act on it: don't wait or check on it. If a task you'd start needs the answer, don't start it in the same reply: it would run without it, so start it once the answer wakes you. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
|
||||
@@ -104,6 +109,7 @@ export default function askBotTool({ user_id, bot_id, session_id, workspace_id }
|
||||
target_bot_id: named?.id || askable[0]!.id!,
|
||||
title: args.title,
|
||||
request,
|
||||
requester_job_id: job_id,
|
||||
});
|
||||
|
||||
return `Asked ${named ? `${named.name} [bot:${named.id}]` : "the crew"} (ask #${ask.id}). The coordinator reads it first; its outcome comes back here as a message and you'll be woken for it. Tell the user you asked; don't ask again while it's open.`;
|
||||
|
||||
@@ -187,6 +187,7 @@ export default async function grabBotChatTools({
|
||||
can_delete_tasks: Boolean(attended),
|
||||
onPropose,
|
||||
onTask,
|
||||
job_id,
|
||||
})),
|
||||
sendReplyTool({
|
||||
user_id,
|
||||
|
||||
@@ -52,6 +52,11 @@ type Params = {
|
||||
* The run is a hook call, so it gets no hook tools.
|
||||
*/
|
||||
hooked?: boolean;
|
||||
/**
|
||||
* The run's own job, recorded on asks the bot makes so stopping exactly
|
||||
* that run ends exactly those requests.
|
||||
*/
|
||||
job_id?: number | string | null;
|
||||
/**
|
||||
* A chat reply the user follows, which may delete tasks.
|
||||
*/
|
||||
@@ -85,6 +90,7 @@ export default async function grabBotTools({
|
||||
admin_workspace_ids,
|
||||
scopes = [],
|
||||
hooked,
|
||||
job_id,
|
||||
can_delete_tasks,
|
||||
onPropose,
|
||||
onTask,
|
||||
@@ -125,7 +131,7 @@ export default async function grabBotTools({
|
||||
*/
|
||||
...(session_id && !is_coordinator && !hooked
|
||||
? [
|
||||
askBotTool({ user_id, bot_id, session_id, workspace_id }),
|
||||
askBotTool({ user_id, bot_id, session_id, workspace_id, job_id }),
|
||||
listAsksTool({ user_id, bot_id }),
|
||||
]
|
||||
: []),
|
||||
|
||||
@@ -7,6 +7,11 @@ import type { HarnessTool } from "../../../types";
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The run working the step, kept on it so a report the app never sent
|
||||
* puts the step back (`pauseFailedPlanStep`).
|
||||
*/
|
||||
job_id?: number | string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -20,7 +25,7 @@ type Args = {
|
||||
* ends on, so a step is only ever finished by a run that did the work, one
|
||||
* at a time.
|
||||
*/
|
||||
export default function completePlanStepTool({ bot_id, session_id }: Params): HarnessTool<Args> {
|
||||
export default function completePlanStepTool({ bot_id, session_id, job_id }: Params): HarnessTool<Args> {
|
||||
let completed = false;
|
||||
|
||||
return {
|
||||
@@ -47,6 +52,7 @@ export default function completePlanStepTool({ bot_id, session_id }: Params): Ha
|
||||
plan_id: args.plan_id,
|
||||
session_id,
|
||||
summary: args.summary,
|
||||
job_id,
|
||||
});
|
||||
|
||||
completed = true;
|
||||
|
||||
@@ -18,6 +18,11 @@ type Params = {
|
||||
* Called with each plan's ref, so the message carries its card.
|
||||
*/
|
||||
onPlan: (params: { ref: string; waiting?: boolean }) => void;
|
||||
/**
|
||||
* The run these tools belong to, kept on a step the run finishes (see
|
||||
* `completeBotPlanStep`).
|
||||
*/
|
||||
job_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -35,7 +40,15 @@ type Params = {
|
||||
* finish it with no card under its report, and the plan would sit active
|
||||
* with nothing to start the next one.
|
||||
*/
|
||||
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, onPlan }: Params) {
|
||||
export default function grabBotPlanTools({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
on_step,
|
||||
onPlan,
|
||||
job_id,
|
||||
}: Params) {
|
||||
const tools: HarnessTool[] = [];
|
||||
|
||||
if (!on_step) {
|
||||
@@ -45,7 +58,7 @@ export default function grabBotPlanTools({ user_id, bot_id, session_id, workspac
|
||||
|
||||
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
|
||||
|
||||
if (on_step) tools.push(completePlanStepTool({ bot_id, session_id }));
|
||||
if (on_step) tools.push(completePlanStepTool({ bot_id, session_id, job_id }));
|
||||
|
||||
return tools;
|
||||
}
|
||||
|
||||
@@ -51,7 +51,9 @@ export default function suggestNextStepsTool({ user_id, bot_id, session_id, work
|
||||
.max(AppData.BotSuggestionTitleMaxChars)
|
||||
.optional()
|
||||
.describe(`A short heading for the row, e.g. "What I can do next" (defaults to "Next steps")`),
|
||||
steps: BotSuggestionStepsSchema.describe("The suggested steps, best first, each written as the message the user would send"),
|
||||
steps: BotSuggestionStepsSchema.describe(
|
||||
`The suggested steps, best first, at most ${AppData.BotSuggestionMaxSteps}, each under ${AppData.BotSuggestionStepMaxChars} characters and written as the message the user would send`,
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (suggested) {
|
||||
|
||||
@@ -22,6 +22,12 @@ type Params = {
|
||||
* Called with each update sent, so the run knows it said something.
|
||||
*/
|
||||
onSend?: (params: { message_id: number }) => void;
|
||||
/**
|
||||
* What the run typed, run through the run's secret redaction before it is
|
||||
* stored: an update lands in another bot's conversation, where a raw env
|
||||
* value or a password field's content would sit in a message forever.
|
||||
*/
|
||||
redact?: (text: string) => string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -37,7 +43,7 @@ type Args = {
|
||||
* back on its own when the work ends. At most
|
||||
* `AppData.BotReplyInterimMessagesMax` per run.
|
||||
*/
|
||||
export default function updateRequesterTool({ user_id, session_id, ask_id, onSend }: Params): HarnessTool<Args> {
|
||||
export default function updateRequesterTool({ user_id, session_id, ask_id, onSend, redact = (text) => text }: Params): HarnessTool<Args> {
|
||||
let sent = 0;
|
||||
|
||||
return {
|
||||
@@ -63,7 +69,7 @@ export default function updateRequesterTool({ user_id, session_id, ask_id, onSen
|
||||
|
||||
const posted = await tellAskRequester({
|
||||
ask,
|
||||
text: askUpdateMessage({ ask, text: stripQuestionRefs({ text: args.text }).text }),
|
||||
text: askUpdateMessage({ ask, text: stripQuestionRefs({ text: redact(args.text) }).text }),
|
||||
});
|
||||
|
||||
sent++;
|
||||
|
||||
@@ -51,11 +51,21 @@ export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): H
|
||||
|
||||
if (fresh.length) onLoad(fresh);
|
||||
|
||||
/**
|
||||
* A name already offered inline isn't in the loadable list at all,
|
||||
* so without this a run that had the tool in hand was sent looking
|
||||
* for it in a list it wasn't in, and gave up (production:
|
||||
* `load_tools("browser")`).
|
||||
*/
|
||||
const ready = missing.filter((name) => isLoaded(name));
|
||||
|
||||
return [
|
||||
fresh.length ? `Loaded: ${fresh.join(", ")}. Call them from your next step.` : "",
|
||||
already.length ? `Already loaded: ${already.join(", ")}.` : "",
|
||||
missing.length
|
||||
? `Not in the list: ${missing.join(", ")}. Use the exact names or family names under "Tools you can load".`
|
||||
? `Not in the list: ${missing.join(", ")}.${
|
||||
ready.length ? ` Already yours, no loading needed: ${ready.join(", ")}.` : ""
|
||||
} Use the exact names or family names under "Tools you can load", and a computer or browser tool a reply doesn't carry is work for send_reply with status "working".`
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import describeHarnessFailure from "@/src/harness/describe-harness-failure";
|
||||
import recordBotFile from "@/src/functions/backend/db/bot-files/record-bot-file";
|
||||
import loadReferenceImages from "@/src/harness/image/load-reference-images";
|
||||
import generateVideo from "@/src/harness/video/generate-video";
|
||||
@@ -129,8 +130,7 @@ export default function generateVideoTool(context: StorageToolContext): HarnessT
|
||||
bot_id: context.bot_id,
|
||||
workspace_id: context.workspace_id,
|
||||
}).catch((error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Video generation isn't working: ${message}`);
|
||||
throw new Error(`Video generation isn't working: ${describeHarnessFailure({ error })}`);
|
||||
});
|
||||
|
||||
if (!made.length) {
|
||||
|
||||
@@ -28,4 +28,32 @@ describe("unknownToolMessage", () => {
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
expect(text).not.toContain("start_task");
|
||||
});
|
||||
|
||||
/**
|
||||
* The user's own browser's tools carry the browser's slug, so a reply that
|
||||
* has one is not short of a browser: it named the tool the wrong way.
|
||||
*/
|
||||
test("names the slug when the run's browser tools have one", () => {
|
||||
const text = unknownToolMessage({
|
||||
name: "browser_navigate",
|
||||
tools: [{ name: "send_reply" }, { name: "work-laptop__browser_navigate" }],
|
||||
});
|
||||
|
||||
expect(text).toContain(`the browser's slug, e.g. "work-laptop__browser_navigate"`);
|
||||
expect(text).not.toContain("only exist in a task");
|
||||
});
|
||||
|
||||
/**
|
||||
* A task run's own `browser_*` tools have no slug, so an excluded one must
|
||||
* not be told to look for a prefixed name it does not have.
|
||||
*/
|
||||
test("keeps the task message for a computer browser tool", () => {
|
||||
const text = unknownToolMessage({
|
||||
name: "browser_close",
|
||||
tools: [{ name: "browser_navigate" }, { name: "computer_bash" }],
|
||||
});
|
||||
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
expect(text).not.toContain("slug");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,9 +7,14 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Computer tools: the app's own shell and file tools and Playwright MCP's
|
||||
* browser tools, which only a task run on a computer has.
|
||||
* browser tools, which only a task run on a computer has. A user's own
|
||||
* browser is named with its slug (`<slug>__browser_navigate`), so the prefix
|
||||
* test is not enough to know a call wanted the computer's browser.
|
||||
*/
|
||||
const ComputerToolPattern = /^(?:computer_|browser_)/;
|
||||
const WantsBrowserPattern = /(?:^|__)browser_/;
|
||||
/** A user's own browser's tool, named under the browser's slug. */
|
||||
const SlugBrowserPattern = /__browser_/;
|
||||
|
||||
/**
|
||||
* What a call to a tool the run doesn't have gets back. A computer or
|
||||
@@ -21,6 +26,18 @@ const ComputerToolPattern = /^(?:computer_|browser_)/;
|
||||
export default function unknownToolMessage({ name, tools }: Params) {
|
||||
const available = `Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
|
||||
|
||||
/**
|
||||
* A reply with the user's own browser does have browser tools, just under
|
||||
* the browser's slug: telling it they only exist in a task was a lie that
|
||||
* ended with "I have no browser" (production, Nov 2026). A task run's own
|
||||
* `browser_*` tools carry no slug, so they keep the message below.
|
||||
*/
|
||||
const own = WantsBrowserPattern.test(name) ? tools.find((t) => SlugBrowserPattern.test(t.name)) : undefined;
|
||||
|
||||
if (own) {
|
||||
return `Error: There is no tool called "${name}". Your browser tools carry the browser's slug, e.g. "${own.name}". ${available}`;
|
||||
}
|
||||
|
||||
if (!ComputerToolPattern.test(name)) {
|
||||
return `Error: There is no tool called "${name}". ${available}`;
|
||||
}
|
||||
|
||||
@@ -106,7 +106,9 @@ export default async function generateVideo({
|
||||
}
|
||||
|
||||
/**
|
||||
* Video editing's setting and candidates, or undefined while it's off.
|
||||
* Video editing's setting and candidates. Turned off still reports its
|
||||
* fallback, the way image editing does, so the order is the same decision
|
||||
* in both lanes.
|
||||
*/
|
||||
async function grabEdit({
|
||||
bot_id,
|
||||
@@ -117,7 +119,7 @@ async function grabEdit({
|
||||
}) {
|
||||
const setting = await grabHarnessSetting({ harness: "video_edit", bot_id, workspace_id });
|
||||
|
||||
if (!setting.enabled) return undefined;
|
||||
if (!setting.enabled) return { picked: false, fallback: setting.fallback, candidates: [] };
|
||||
|
||||
return {
|
||||
picked: Boolean(setting.model_id),
|
||||
|
||||
@@ -51,10 +51,7 @@ describe("orderVideoCandidates", () => {
|
||||
).toEqual(["video_edit:flux-video-edit"]);
|
||||
});
|
||||
|
||||
test("video editing off or unpicked goes to the generation models that take videos", () => {
|
||||
expect(
|
||||
slugs(orderVideoCandidates({ images: false, videos: true, video: [veo, seedance] })),
|
||||
).toEqual(["video:seedance"]);
|
||||
test("video editing unpicked goes to the generation models that take videos, with fallback on", () => {
|
||||
expect(
|
||||
slugs(
|
||||
orderVideoCandidates({
|
||||
@@ -67,14 +64,30 @@ describe("orderVideoCandidates", () => {
|
||||
).toEqual(["video:seedance"]);
|
||||
});
|
||||
|
||||
test("an edit pick that can't take the images passed falls to generation", () => {
|
||||
test("video editing off with no fallback has nothing to try, as image editing does", () => {
|
||||
expect(
|
||||
slugs(orderVideoCandidates({ images: false, videos: true, video: [veo, seedance] })),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
slugs(
|
||||
orderVideoCandidates({
|
||||
images: false,
|
||||
videos: true,
|
||||
video: [veo, seedance],
|
||||
edit: { picked: false, fallback: false, candidates: [] },
|
||||
}),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("an edit pick that can't take the images passed falls to generation, with fallback on", () => {
|
||||
expect(
|
||||
slugs(
|
||||
orderVideoCandidates({
|
||||
images: true,
|
||||
videos: true,
|
||||
video: [veo, seedance],
|
||||
edit: { picked: true, fallback: false, candidates: [flux_edit] },
|
||||
edit: { picked: true, fallback: true, candidates: [flux_edit] },
|
||||
}),
|
||||
),
|
||||
).toEqual(["video:seedance"]);
|
||||
|
||||
@@ -22,7 +22,7 @@ type Params = {
|
||||
*/
|
||||
video: HarnessCandidate[];
|
||||
/**
|
||||
* Video editing's setting and candidates; undefined when it's off.
|
||||
* Video editing's setting and candidates; no pick while it's off.
|
||||
*/
|
||||
edit?: {
|
||||
/**
|
||||
@@ -59,7 +59,9 @@ export default function orderVideoCandidates({ images, videos, video, edit }: Pa
|
||||
? edit.candidates.filter(takes).map((candidate) => ({ candidate, harness: "video_edit" as const }))
|
||||
: [];
|
||||
|
||||
const ordered = !edits.length ? generation : [...edits, ...(edit?.fallback ? generation : [])];
|
||||
// The hand-over to generation, whether the edit pick failed or there is
|
||||
// none, happens only with fallback on: the same rule as image editing.
|
||||
const ordered = [...edits, ...(edit?.fallback ? generation : [])];
|
||||
const seen = new Set<string>();
|
||||
|
||||
return ordered.filter(({ candidate }) => {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import HarnessGuessedModelNote from "./harness-guessed-model-note";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
|
||||
const model = (capabilities_guessed?: boolean): HarnessModelOption => ({
|
||||
id: 908359,
|
||||
provider_id: 12,
|
||||
provider_name: "Liquid AI",
|
||||
slug: "lfm3-vl-2b",
|
||||
name: "lfm3-vl-2b",
|
||||
free: false,
|
||||
capabilities_guessed,
|
||||
});
|
||||
|
||||
describe("HarnessGuessedModelNote", () => {
|
||||
test("says the capabilities are guessed for a model listed by id only", () => {
|
||||
const html = renderToString(<HarnessGuessedModelNote model={model(true)} />);
|
||||
|
||||
expect(html).toContain("lists model ids only");
|
||||
expect(html).toContain("lfm3-vl-2b");
|
||||
expect(html).toContain("never calls tools");
|
||||
});
|
||||
|
||||
test("says nothing for a model whose catalog declared its capabilities", () => {
|
||||
expect(renderToString(<HarnessGuessedModelNote model={model(false)} />)).toBe("");
|
||||
expect(renderToString(<HarnessGuessedModelNote model={model()} />)).toBe("");
|
||||
expect(renderToString(<HarnessGuessedModelNote />)).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
model?: HarnessModelOption;
|
||||
};
|
||||
|
||||
/**
|
||||
* A word when the picked text model's capabilities were guessed: only
|
||||
* OpenRouter's catalog says what a model takes, so every other provider is
|
||||
* listed by id and read from its name (`guessModelModalities`), which always
|
||||
* answers that it calls tools. Said out loud because a vision model was
|
||||
* pinned this way as a worker's text model and answered every reply as prose
|
||||
* that never closed with `send_reply`: the run failed, and nothing on the
|
||||
* page said the model was never a tool-caller.
|
||||
*/
|
||||
export default function HarnessGuessedModelNote({ model }: Props) {
|
||||
if (!model?.capabilities_guessed) return null;
|
||||
|
||||
return (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`${model.provider_name} lists model ids only, so ${model.name}'s capabilities are guessed from its name: nothing here can tell that it takes images, or that it never calls tools. A model that can't drive a run fails quietly (answers that end as drafts, reports that never close), so watch its first runs and unpin it if the bot stops calling tools. OpenRouter is the one provider whose catalog says what each model takes.`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import harnessDefaultName from "../(utils)/harness-default-name";
|
||||
import nextHarnessModelValue from "../(utils)/next-harness-model-value";
|
||||
import nextHarnessProviderValue from "../(utils)/next-harness-provider-value";
|
||||
import HarnessCurrentModel from "./harness-current-model";
|
||||
import HarnessGuessedModelNote from "./harness-guessed-model-note";
|
||||
import HarnessModelSelect from "./harness-model-select";
|
||||
import HarnessOptionsCheckboxes from "./harness-options-checkboxes";
|
||||
import HarnessParamsButton from "./harness-params-button";
|
||||
@@ -37,6 +38,8 @@ export default function HarnessSettingGroup({ harness, value, onChange, referenc
|
||||
: harness.models;
|
||||
const picked = models.find((model) => model.id == value.model_id);
|
||||
const on_bot_page = harness.default !== undefined;
|
||||
/** The model this row's settings would show the user the truth about. */
|
||||
const shown = value.inherit ? harness.default?.current : picked || harness.current;
|
||||
const falls_back_title = harnessFallbackTitle({ harness: harness.harness });
|
||||
const default_name = harnessDefaultName({
|
||||
harness_default: harness.default,
|
||||
@@ -75,7 +78,7 @@ export default function HarnessSettingGroup({ harness, value, onChange, referenc
|
||||
)}
|
||||
{harness.harness == "image" ? (
|
||||
<HarnessReferenceModelNote
|
||||
model={value.inherit ? harness.default?.current : picked || harness.current}
|
||||
model={shown}
|
||||
reference_model={reference_model}
|
||||
/>
|
||||
) : null}
|
||||
@@ -84,13 +87,16 @@ export default function HarnessSettingGroup({ harness, value, onChange, referenc
|
||||
harness={value.inherit && harness.default ? { ...harness, ...harness.default } : harness}
|
||||
/>
|
||||
{harness.harness == "text" ? (
|
||||
<HarnessWindowNote model={value.inherit ? harness.default?.current : picked || harness.current} />
|
||||
<>
|
||||
<HarnessWindowNote model={shown} />
|
||||
<HarnessGuessedModelNote model={shown} />
|
||||
</>
|
||||
) : null}
|
||||
<HarnessOptionsCheckboxes
|
||||
harness={harness}
|
||||
value={value}
|
||||
provider={provider}
|
||||
model={value.inherit ? harness.default?.current : picked || harness.current}
|
||||
model={shown}
|
||||
falls_back_title={falls_back_title}
|
||||
onChange={onChange}
|
||||
/>
|
||||
|
||||
@@ -836,6 +836,13 @@ export type HarnessModelOption = {
|
||||
* every run, which the picker says out loud.
|
||||
*/
|
||||
context_length?: number;
|
||||
/**
|
||||
* True when the app guessed what the model takes (its provider lists
|
||||
* ids only, so `guessModelModalities` decided from the name), rather than
|
||||
* reading it from a catalog that says. The picker warns about a text
|
||||
* model picked this way: a guessed `supports_tools` is not a promise.
|
||||
*/
|
||||
capabilities_guessed?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,12 @@ export type BotPlanStepRecord = {
|
||||
* What the step produced, written when it was completed.
|
||||
*/
|
||||
note: string;
|
||||
/**
|
||||
* The run that finished it (`complete_plan_step`). Kept so a step whose
|
||||
* report never went out can be put back by `pauseFailedPlanStep`: the
|
||||
* card must not show as delivered what the user was never sent.
|
||||
*/
|
||||
done_job_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -39,12 +45,14 @@ export default function parseBotPlanSteps({ text }: { text: string | null | unde
|
||||
if (!step_text) return [];
|
||||
|
||||
const state = typeof row.state == "string" && states.includes(row.state) ? (row.state as BotPlanStepState) : "pending";
|
||||
const done_job_id = Number(row.done_job_id);
|
||||
|
||||
return [
|
||||
{
|
||||
text: step_text,
|
||||
state,
|
||||
note: typeof row.note == "string" ? row.note : "",
|
||||
...(Number.isSafeInteger(done_job_id) && done_job_id > 0 ? { done_job_id } : {}),
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user