Make send_reply the only way a reply ends
A reply's prose alone was delivered as its answer, so a bot could say work had started when nothing was queued. Replies and task reports now close with send_reply({status, work?}): bare text is a draft, working must queue work or follow a real run, and queued work is cancelled with an unsent message. The review reads the declared status, and a task report no longer counts its own job as open work.
This commit is contained in:
@@ -14,6 +14,7 @@ describe("composeComputersNote", () => {
|
||||
"- [computer:4] Scraper (you're on it): Runs the crawlers\n- [computer:1] Main computer (main)",
|
||||
);
|
||||
expect(note).toContain("search_computers");
|
||||
expect(note).toContain("send_reply");
|
||||
expect(note).toContain("start_task");
|
||||
});
|
||||
|
||||
|
||||
@@ -61,6 +61,6 @@ Each is a Linux sandbox of your own (a shell, files, code runners and a browser)
|
||||
}
|
||||
|
||||
- To find which computer holds something (a file, a running app, a logged-in session), use search_computers: it runs one read-only command on all of them at once.
|
||||
- For anything else on a computer, start_task: the task runs on it with its tools and you post what you found here. Don't say you can't see a computer; search it or start a task.
|
||||
- For anything else on a computer, send_reply with status "working" and work (or start_task inside a task run): the task runs on it with its tools and you post what you found here. Don't say you can't see a computer; search it or start a task.
|
||||
- When you name a computer, write its ref exactly, e.g. ${computerRef({ id: computers[0]!.id || 0 })}. The user sees it as a button that switches you to that computer, so when they're looking for one, say which and that they can click it.`;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ export default function composeEnvsNote({ on_computer, tools_only, has_computer
|
||||
return [
|
||||
`# Your envs\n\nThese are already set for you here (keys and descriptions; you never see values). Don't ask the user for them, and don't call show_secret or run printenv to check them: this list is the check. A workspace, computer or install-wide env reaches every bot there the same way, so it never needs setting again per bot.`,
|
||||
on_computer.length
|
||||
? `On your computer, as $KEY in a task's shell and code (start_task; search_computers doesn't load them):\n${list(on_computer)}`
|
||||
? `On your computer, as $KEY in a task's shell and code (started with send_reply's work in a reply, or start_task inside a task run; search_computers doesn't load them):\n${list(on_computer)}`
|
||||
: "",
|
||||
tools_only.length
|
||||
? `${has_computer ? "Only in tools" : "In tools"}, as {{env.KEY}}${has_computer ? " (not set on computers)" : ""}:\n${list(tools_only)}`
|
||||
|
||||
@@ -7,8 +7,14 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
*/
|
||||
const open_graphics = new Set<number>([2]);
|
||||
|
||||
let open_work = false;
|
||||
const open_work_calls: Array<{ bot_id: number | string; session_id: number | string; exclude_job_id?: number | string }> = [];
|
||||
|
||||
mock.module("@/src/functions/backend/db/bots-queue/has-open-work", () => ({
|
||||
default: async () => false,
|
||||
default: async (params: { bot_id: number | string; session_id: number | string; exclude_job_id?: number | string }) => {
|
||||
open_work_calls.push(params);
|
||||
return open_work;
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-files/grab-bot-file", () => ({
|
||||
default: async () => null,
|
||||
@@ -31,10 +37,20 @@ afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const review = async ({ text, tool_uses = [] }: { text: string; tool_uses?: { name: string; ok: boolean }[] }) => {
|
||||
const review = async ({
|
||||
text,
|
||||
tool_uses = [],
|
||||
status,
|
||||
job_id,
|
||||
}: {
|
||||
text: string;
|
||||
tool_uses?: { name: string; ok: boolean }[];
|
||||
status?: "done" | "working" | "blocked";
|
||||
job_id?: number;
|
||||
}) => {
|
||||
const { default: reviewBotReply } = await import("./review-bot-reply");
|
||||
|
||||
return reviewBotReply({ text, tool_uses, bot_id: 1, user_id: 1, session_id: 123, scopes: [] });
|
||||
return reviewBotReply({ text, tool_uses, bot_id: 1, user_id: 1, session_id: 123, scopes: [], status, job_id });
|
||||
};
|
||||
|
||||
describe("reviewBotReply", () => {
|
||||
@@ -82,4 +98,35 @@ describe("reviewBotReply", () => {
|
||||
expect(await review({ text: "The chart: [graphic:2]", tool_uses: [{ name: "create_graphic", ok: true }] })).toBeNull();
|
||||
expect(await review({ text: "Here's the picture you asked for." })).toBeNull();
|
||||
});
|
||||
|
||||
/**
|
||||
* Session 75 message 951: the run deleted the old files, said it was
|
||||
* generating the banner next, and stopped. The status is now part of
|
||||
* the answer, so `done` is a contradiction the review can name even
|
||||
* while another run is open.
|
||||
*/
|
||||
test("faults a done message that says work is under way", async () => {
|
||||
const note = await review({
|
||||
text: "Now generating the single centered 6% signpost hero with the image generation tool.",
|
||||
status: "done",
|
||||
job_id: 560,
|
||||
});
|
||||
|
||||
expect(note).toContain(`status "done"`);
|
||||
});
|
||||
|
||||
test("passes a working message when a run is open, excluding this run's own job", async () => {
|
||||
open_work = true;
|
||||
open_work_calls.length = 0;
|
||||
|
||||
const note = await review({
|
||||
text: "I'm generating the banner now.",
|
||||
status: "working",
|
||||
job_id: 560,
|
||||
});
|
||||
|
||||
expect(note).toBeNull();
|
||||
expect(open_work_calls[0]).toEqual({ bot_id: 1, session_id: 123, exclude_job_id: 560 });
|
||||
open_work = false;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-
|
||||
import grabBotGraphic from "@/src/functions/backend/db/bot-graphics/grab-bot-graphic";
|
||||
import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import replyClaimProblems, { AppCardRefTools, type AppCardRefKind } from "@/src/utils/reply-claim-problems";
|
||||
import replyRefIds from "@/src/utils/reply-ref-ids";
|
||||
import unresolvedSettingRefs from "@/src/utils/unresolved-setting-refs";
|
||||
@@ -17,6 +18,15 @@ type Params = {
|
||||
bot_id: number | string;
|
||||
user_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The run being reviewed. A task run's own job is open while it writes
|
||||
* its report, so it must not count as work that is still to come.
|
||||
*/
|
||||
job_id?: number | string;
|
||||
/**
|
||||
* What the reply declared with `send_reply`.
|
||||
*/
|
||||
status?: ReplyStatus;
|
||||
/**
|
||||
* The run's folders (`grabRunScopes`).
|
||||
*/
|
||||
@@ -36,7 +46,7 @@ type Params = {
|
||||
* one wrote `[suggestion:11]` after the last real one was `[suggestion:10]`
|
||||
* and the user got buttons reading "not available".
|
||||
*/
|
||||
export default async function reviewBotReply({ text, tool_uses, bot_id, user_id, session_id, scopes }: Params) {
|
||||
export default async function reviewBotReply({ text, tool_uses, bot_id, user_id, session_id, job_id, status, scopes }: Params) {
|
||||
if (!text.trim()) return null;
|
||||
|
||||
const missing_file_ids: number[] = [];
|
||||
@@ -76,7 +86,8 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
unresolved_setting_refs: unresolvedSettingRefs({ text }),
|
||||
missing_graphic_ids,
|
||||
written_card_refs,
|
||||
has_open_work: await hasOpenWork({ bot_id, session_id }),
|
||||
has_open_work: await hasOpenWork({ bot_id, session_id, exclude_job_id: job_id }),
|
||||
status,
|
||||
});
|
||||
|
||||
if (!problems.length) return null;
|
||||
@@ -85,7 +96,7 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
|
||||
${problems.map((problem) => `- ${problem}`).join("\n")}
|
||||
|
||||
The tools you actually called in this reply: ${describeToolUses({ uses: tool_uses })}. Nothing else happened. Write the answer again, saying only what those tools returned and what the user told you. If the work still needs doing, call start_task now and say it's started; never describe results of work no tool did, and never promise a report nothing will send. If part of your answer was wrong, say so plainly.`;
|
||||
The tools you actually called in this reply: ${describeToolUses({ uses: tool_uses })}. Nothing else happened. Write the answer again, saying only what those tools returned and what the user told you. If the work still needs doing, call send_reply with status "working" and work now, and say it's started; never describe results of work no tool did, and never promise a report nothing will send. If part of your answer was wrong, say so plainly.`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import reviewBotReply from "./review-bot-reply";
|
||||
|
||||
@@ -6,6 +7,7 @@ type Params = {
|
||||
bot_id: number | string;
|
||||
user_id: number | string;
|
||||
session_id: number | string;
|
||||
job_id?: number | string;
|
||||
scopes: StorageScope[];
|
||||
};
|
||||
|
||||
@@ -15,7 +17,7 @@ type Params = {
|
||||
* record (`reviewBotReply`). One place so a task report is held to the
|
||||
* same record as a chat reply.
|
||||
*/
|
||||
export default function reviewRunAnswer({ bot_id, user_id, session_id, scopes }: Params) {
|
||||
return ({ text, tool_uses }: { text: string; tool_uses: HarnessToolUse[] }) =>
|
||||
reviewBotReply({ text, tool_uses, bot_id, user_id, session_id, scopes });
|
||||
export default function reviewRunAnswer({ bot_id, user_id, session_id, job_id, scopes }: Params) {
|
||||
return ({ text, tool_uses, status }: { text: string; tool_uses: HarnessToolUse[]; status?: ReplyStatus }) =>
|
||||
reviewBotReply({ text, tool_uses, bot_id, user_id, session_id, job_id, status, scopes });
|
||||
}
|
||||
|
||||
@@ -70,6 +70,7 @@ import withTakeOverRefs from "./with-take-over-refs";
|
||||
import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
|
||||
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
|
||||
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
@@ -100,7 +101,7 @@ type Params = BotJobContext & {
|
||||
* knowing where it is (its workspace, if the session is in one), what
|
||||
* happened in the session before (`grabSessionCarryOver`) and its
|
||||
* computers (`composeComputersNote`), with its chat tools (memory,
|
||||
* instructions, start_task, and for the coordinator delegate_task) plus
|
||||
* instructions, send_reply with its work, and for the coordinator delegate_task) plus
|
||||
* its MCP servers' and custom tools (`openBotExtensions`, script tools on
|
||||
* its current computer).
|
||||
* Messages the user sends while it works join the run (`incoming`): one
|
||||
@@ -287,6 +288,12 @@ export default async function runBotReply({
|
||||
* The tracker tasks the reply worked on, linked under it.
|
||||
*/
|
||||
const task_ids: number[] = [];
|
||||
/**
|
||||
* The runs `send_reply` queued with this message: if the message never
|
||||
* goes out, they go with it, so nothing works on a message the user
|
||||
* never saw.
|
||||
*/
|
||||
const queued_jobs: number[] = [];
|
||||
|
||||
/**
|
||||
* The files this run reaches: its file tools and the pictures it may
|
||||
@@ -314,7 +321,7 @@ export default async function runBotReply({
|
||||
*/
|
||||
const attended = !(await isHiddenSession({ session_id }));
|
||||
/**
|
||||
* The run's browser kind, also handed to `start_task` so a child run it
|
||||
* The run's browser kind, also handed to `send_reply`'s work so a child run it
|
||||
* queues inherits it (H7): a hidden session's reply never lets its
|
||||
* children reach the user's real browsers either.
|
||||
*/
|
||||
@@ -353,6 +360,8 @@ export default async function runBotReply({
|
||||
attended,
|
||||
run_kind: browser_run_kind,
|
||||
message_id: job.message_id || undefined,
|
||||
job_id: job.id,
|
||||
onQueue: ({ job_id }) => queued_jobs.push(job_id),
|
||||
onTakeOver: ({ ref }) => take_overs.push(ref),
|
||||
onPropose: ({ ref }) => proposals.push(ref),
|
||||
onWorkspaceAdmin: (admin) => {
|
||||
@@ -606,7 +615,13 @@ export default async function runBotReply({
|
||||
* Files, tasks and work the answer names are checked against
|
||||
* the app's record before it goes out.
|
||||
*/
|
||||
review: reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes }),
|
||||
review: reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id }),
|
||||
/**
|
||||
* The message goes out only through `send_reply`: text a turn
|
||||
* writes without it is a draft, so no answer can promise work
|
||||
* the app never queued.
|
||||
*/
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -617,6 +632,15 @@ export default async function runBotReply({
|
||||
if (result.review_note) {
|
||||
await dropUnsentQuestions({ refs: proposals });
|
||||
|
||||
/**
|
||||
* A run `send_reply` queued announced work in a message that is
|
||||
* not going out: it is cancelled with it, so nothing carries on
|
||||
* behind a message the user never saw.
|
||||
*/
|
||||
for (const queued of queued_jobs) {
|
||||
await cancelBotJob({ user_id, job_id: queued }).catch(() => null);
|
||||
}
|
||||
|
||||
throw new BotJobFatalError(`The answer didn't hold up against the app's record, so it wasn't sent.`);
|
||||
}
|
||||
|
||||
@@ -630,9 +654,24 @@ export default async function runBotReply({
|
||||
if (!answer && !shown.length && !attachments.length) {
|
||||
await dropUnsentQuestions({ refs: proposals });
|
||||
|
||||
for (const queued of queued_jobs) {
|
||||
await cancelBotJob({ user_id, job_id: queued }).catch(() => null);
|
||||
}
|
||||
|
||||
throw new BotJobFatalError(`The run ended without an answer to send.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Work queued in an earlier turn and then withdrawn by the message
|
||||
* that ended the run (`done` or `blocked`): the user reads that
|
||||
* nothing runs, so nothing may.
|
||||
*/
|
||||
if (result.status !== "working") {
|
||||
for (const queued of queued_jobs) {
|
||||
await cancelBotJob({ user_id, job_id: queued }).catch(() => null);
|
||||
}
|
||||
}
|
||||
|
||||
if (job.id && answering_id) {
|
||||
await markReplyAnswered({ job_id: job.id, message_id: answering_id });
|
||||
}
|
||||
|
||||
@@ -58,6 +58,9 @@ import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
|
||||
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
|
||||
import setUserWorkspaceRoleTool from "@/src/harness/tools/bot/set-user-workspace-role-tool";
|
||||
import askToTakeOverTool from "@/src/harness/tools/computer/ask-to-take-over-tool";
|
||||
import sendReplyTool from "@/src/harness/tools/bot/send-reply-tool";
|
||||
import startTaskTool from "@/src/harness/tools/bot/start-task-tool";
|
||||
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
|
||||
import importFileTool from "@/src/harness/tools/computer/import-file-tool";
|
||||
import searchComputersTool from "@/src/harness/tools/computer/search-computers-tool";
|
||||
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
|
||||
@@ -205,6 +208,11 @@ export default async function runBotTask({
|
||||
* Files the bot wrote and asked to send with its report.
|
||||
*/
|
||||
const attachments: number[] = [];
|
||||
/**
|
||||
* Runs `send_reply` queued with this report: if the report is never
|
||||
* posted (the review refused it), they are cancelled with it.
|
||||
*/
|
||||
const queued_jobs: number[] = [];
|
||||
const scheduled = Boolean(params.schedule_id);
|
||||
/**
|
||||
* Started by a call to one of the user's hooks: acts on its own
|
||||
@@ -640,7 +648,37 @@ export default async function runBotTask({
|
||||
const result = await runTextLoop({
|
||||
system,
|
||||
messages: opening,
|
||||
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
|
||||
tools: [
|
||||
...tools,
|
||||
/**
|
||||
* A task report ends with `send_reply`, the same protocol a
|
||||
* reply uses: its status says whether anything runs after
|
||||
* it, and a `working` report must name the run. `start_task`
|
||||
* stays here for work the run hands on before it reports.
|
||||
*/
|
||||
sendReplyTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
computers,
|
||||
message_id: job.message_id || undefined,
|
||||
job_id: job.id,
|
||||
run_kind: browser_run_kind,
|
||||
onQueue: ({ job_id }) => queued_jobs.push(job_id),
|
||||
}),
|
||||
startTaskTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
computers,
|
||||
message_id: job.message_id || undefined,
|
||||
run_kind: browser_run_kind,
|
||||
}),
|
||||
...extensions.tools,
|
||||
...browsers.tools,
|
||||
...skills.tools,
|
||||
...knowledge.tools,
|
||||
],
|
||||
max_steps,
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
@@ -686,7 +724,12 @@ export default async function runBotTask({
|
||||
* says work is under way when none is. A note sends it back;
|
||||
* one the review keeps faulting is never posted.
|
||||
*/
|
||||
review: reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes }),
|
||||
review: reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes, job_id: job.id }),
|
||||
/**
|
||||
* A report goes out only through `send_reply`, so it can't say
|
||||
* work is under way with the run's own open job behind it.
|
||||
*/
|
||||
require_closing_answer: true,
|
||||
/**
|
||||
* The model that wrote the plan, when there was one: the run
|
||||
* works it on that model when it is still the one to use.
|
||||
@@ -707,6 +750,10 @@ export default async function runBotTask({
|
||||
if (result.review_note) {
|
||||
await dropUnsentQuestions({ refs: take_overs });
|
||||
|
||||
for (const queued of queued_jobs) {
|
||||
await cancelBotJob({ user_id, job_id: queued }).catch(() => null);
|
||||
}
|
||||
|
||||
throw new BotJobFatalError(`The answer didn't hold up against the app's record, so it wasn't sent.`);
|
||||
}
|
||||
|
||||
@@ -720,9 +767,24 @@ export default async function runBotTask({
|
||||
* posts whatever text it is given (L5).
|
||||
*/
|
||||
if (!text.trim() && !shown.length && !suggestions.length && !attachments.length) {
|
||||
for (const queued of queued_jobs) {
|
||||
await cancelBotJob({ user_id, job_id: queued }).catch(() => null);
|
||||
}
|
||||
|
||||
throw new BotJobFatalError(`The run ended without a report to send.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Work queued in an earlier turn and then withdrawn by the report
|
||||
* that ended the run (`done` or `blocked`): the user reads that
|
||||
* nothing runs, so nothing may.
|
||||
*/
|
||||
if (result.status !== "working") {
|
||||
for (const queued of queued_jobs) {
|
||||
await cancelBotJob({ user_id, job_id: queued }).catch(() => null);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...withTakeOverRefs({
|
||||
text: computer ? computer.redact(text) : text,
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
* goal and no route, and the run reached the same result by a way the
|
||||
* user didn't ask for (a PNG to "layered PSD", locally, when they said to
|
||||
* use their ArtCraft MCP). The message that asked for the work is on the
|
||||
* job (`bots_queue.message_id`, from `start_task`), so the run reads the
|
||||
* job (`bots_queue.message_id`, from `send_reply`'s work or `start_task`), so the run reads the
|
||||
* request itself, and `TaskRunNote` says the words win over the brief.
|
||||
*
|
||||
* Empty for a message the user didn't write (a crew message that asked
|
||||
|
||||
@@ -678,6 +678,14 @@ export const AppData = {
|
||||
* the re-ask, and the same note loops for the whole token budget.
|
||||
*/
|
||||
MaxClosingRetries: 2,
|
||||
/**
|
||||
* How many messages a reply or task report may write without ending on
|
||||
* `send_reply` before the run stops without sending one. A bare message
|
||||
* is a draft, never the answer: the draft is sent back with the note
|
||||
* that nothing went out. Past this the run fails honestly and the user
|
||||
* gets Retry, rather than a message the app cannot stand behind.
|
||||
*/
|
||||
HarnessReplyDraftsMax: 2,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
|
||||
@@ -16,7 +16,7 @@ You deliver outcomes, not plans. Proposing, attempting or describing an action i
|
||||
A chat reply is short: about eight tool steps. Anything long, multi-step or on a computer belongs in a task.
|
||||
|
||||
- Answer questions and handle quick work directly in the reply.
|
||||
- Put your own long work in \`start_task\`. It runs in the background and its result is posted back here.
|
||||
- Put your own long work in \`send_reply\` with status "working" and \`work\` (or \`start_task\` inside a task run). It runs in the background and its result is posted back here.
|
||||
- Hand work that fits a worker to them with \`delegate_task\`. It runs in the background and is reported back here when they finish or fail.
|
||||
- Say that work is under way, not done, and say who is on it.
|
||||
- When the user asks to continue, retry or go ahead ("Try again", "Go ahead", "Why haven't you done it?"), anchor strictly on the immediate unfulfilled action under discussion. Never revert to earlier diagnostic checks or the session's opening topic.
|
||||
|
||||
+55
-16
@@ -68,9 +68,11 @@ export const chatReplyNote = ({ bot_id }: { bot_id: number | string }) => `# Rep
|
||||
|
||||
You are chatting with the user. Answer their latest messages directly and briefly, in markdown.
|
||||
|
||||
- Quick questions and small changes: answer now.
|
||||
- Work that takes more than a moment, or anything on a computer (running commands, editing files, browsing): call start_task with a clear brief, then tell the user in one sentence, in the first person, what you're doing, e.g. "I'm going through your inbox now. I'll report back when I'm done." A task you start is your own work: never say you handed it to anyone else. The result is posted here when it's done.
|
||||
- When a message mixes both, answer the quick parts in this reply and start a task for the rest.
|
||||
- Every reply ends with send_reply. The text beside it is the message the user reads; a turn that writes text without it is a draft and is never sent.
|
||||
- send_reply({status:"done"}) for a quick answer or a small change that needs nothing after it.
|
||||
- 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.
|
||||
- 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.
|
||||
@@ -78,22 +80,22 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
- Never claim you did something you didn't do.
|
||||
- When the user overrules how you read a rule or a brief, go with their reading: say once what you'd watch for if it matters, then work their way. Don't restate the objection in later replies.
|
||||
- An answer from the crew, a finished run or any other app message is information, not the user's go-ahead. If you told the user you'd wait for their choice, say in a line or two what arrived and keep waiting. If it adds nothing new for them, keep your answer to a line. And never read the user's silence as an answer: they may simply not have seen your question yet.
|
||||
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with start_task (with separate when another run of yours is open on that computer) and say it's queued.
|
||||
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with send_reply status "working" and work (with separate when another run of yours is open on that computer) and say it's queued.
|
||||
- The user can mention a bot as [bot:ID] and a workspace as [workspace:ID]; a [Mentions: ...] line after their message says who and what those are. Write the same refs when you name them back.
|
||||
- Documents, images and reports you make are files: save them with write_file, make_pdf or generate_image, and send one to the user with it ("attach"). When you name a file, write its [file:ID] ref, e.g. [file:12], so the user can open it. When you name a folder, write a folder ref instead, e.g. ${ownFolderRef({ bot_id })}: that opens the folder in Files and downloads nothing.
|
||||
|
||||
## Keep the work moving
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just queued a run (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
|
||||
Your answer and that card go out together: ask_user and suggest_next_steps end the reply. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
|
||||
## Nothing happens after you send
|
||||
## Ending the reply
|
||||
|
||||
This message is the last thing the reply does: there is no next turn, and nothing runs once it goes out. So "I'll check", "let me check", "I'll connect and inspect", "next I'll" and "I'm going to" are promises the user waits on forever, and a promise with no run behind it is refused before it reaches them.
|
||||
send_reply is the last thing the reply does: there is no next turn, and nothing runs once it goes out. So "I'll check", "let me check", "I'll connect and inspect", "next I'll" and "I'm going to" are promises the user waits on forever. Status "working" is how you say work is running: it must carry work, or follow a run you already started in this reply.
|
||||
|
||||
- If their latest message asks for work that needs no computer and takes a moment, do it in this reply and report what came back.
|
||||
- Otherwise call start_task now, then say in one sentence that it is running.`;
|
||||
- Otherwise call send_reply with status "working" and work now, then say in one sentence that it is running.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: where its files live,
|
||||
@@ -111,7 +113,7 @@ The user asked for this reply again. Work from their latest messages and write i
|
||||
|
||||
- If your last run was stopped partway, whatever it did in chat is gone: pick the work up where it stopped and finish it, or say plainly what is left and what you need from the user to go on.
|
||||
- If the answer did go out, write it again for what they asked, as if it were the first time. The earlier one stays in the thread, so don't repeat it word for word if you have something better to say, and don't assume they missed it.
|
||||
- Start the work now, in this reply or with start_task: never answer that you'll look into it.`;
|
||||
- Start the work now, in this reply or with send_reply status "working" and work: never answer that you'll look into it.`;
|
||||
|
||||
export const botFilesNote = ({ bot_id }: { bot_id: number | string }) => `# Your files
|
||||
|
||||
@@ -310,7 +312,7 @@ export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) =>
|
||||
* Added to the coordinator's chat prompt instead while it has no workers,
|
||||
* so it doesn't talk about a crew that doesn't exist.
|
||||
*/
|
||||
export const CoordinatorSoloNote = `You have no worker bots yet: you do all the work yourself, with start_task for anything long or on a computer. Never say you assigned, delegated or handed work to a worker or anyone else. If a kind of job keeps coming up, propose a new bot for it, and create it with create_bot once the user agrees.`;
|
||||
export const CoordinatorSoloNote = `You have no worker bots yet: you do all the work yourself, with send_reply status "working" and work in a reply (or start_task inside a task run) for anything long or on a computer. Never say you assigned, delegated or handed work to a worker or anyone else. If a kind of job keeps coming up, propose a new bot for it, and create it with create_bot once the user agrees.`;
|
||||
|
||||
/**
|
||||
* Added to a workspace admin's chat prompt in the workspace it leads, while
|
||||
@@ -349,6 +351,8 @@ A brief can be wrong about the repository: it is written from a report or an ear
|
||||
|
||||
Work larger than one run is handed on, not half-done: start_task with separate for the rest, and the report says what you finished, what you handed on and what the new run is for. That is finishing the task, not leaving it.
|
||||
|
||||
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.`;
|
||||
|
||||
/**
|
||||
@@ -497,6 +501,41 @@ export const closingMixedNote = `The card you put up is there: that call worked.
|
||||
*/
|
||||
export const closingNoTextNote = `The card you just put up has no message beside it, and a card on its own leaves the user nothing to read. Write the sentence that goes with it now, and stop there: what comes next waits on their answer.`;
|
||||
|
||||
/**
|
||||
* Told when a reply or task report wrote text without `send_reply`: the
|
||||
* message is a draft, and sending it would let prose promise work the app
|
||||
* never queued. Bounded by `AppData.HarnessReplyDraftsMax`, then the run
|
||||
* fails honestly rather than sending it.
|
||||
*/
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write it again beside send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. The text beside the call is what the user reads.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` worked but the turn said nothing beside it: the
|
||||
* user would get an empty line, and the status alone is not a message.
|
||||
*/
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so the user would get an empty line. Write the message beside send_reply now and call it again: status "done", "working" (with work, or after a run you started) or "blocked".`;
|
||||
|
||||
/**
|
||||
* Told when a turn tried to end without `send_reply` at all: a card alone or
|
||||
* a closing tool that isn't `send_reply` doesn't say whether work is
|
||||
* running, and its text is a draft.
|
||||
*/
|
||||
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running.`;
|
||||
|
||||
/**
|
||||
* Told when a turn called `send_reply` beside other tools: only its own turn
|
||||
* can send the message, since the other calls' results go into the
|
||||
* conversation after it.
|
||||
*/
|
||||
export const replyClosingMixedNote = `send_reply has to be the only call in its turn: this turn also did other work, so the message was not sent. Call send_reply on its own with the message beside it, after the tools you still need have run.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` itself refused the turn (status "working" with
|
||||
* nothing behind it, or work beside another status): the message was not
|
||||
* sent, and the status must match what is actually running.
|
||||
*/
|
||||
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".`;
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -539,7 +578,7 @@ From here, put what you establish in a file of your own (write it down as you go
|
||||
* what it does from here is paid for out of the answer's budget.
|
||||
*/
|
||||
export const tokensLowNote = ({ left }: { left: number }) =>
|
||||
`You have about ${Math.max(0, Math.round(left)).toLocaleString("en-US")} prompt tokens left in this run, and every further turn resends this whole conversation, so each one costs more than the last. Land the work now: write what you have to a file and finish the rest of the answer from it, or hand the rest on with start_task. Another round of gathering is not worth what is left.`;
|
||||
`You have about ${Math.max(0, Math.round(left)).toLocaleString("en-US")} prompt tokens left in this run, and every further turn resends this whole conversation, so each one costs more than the last. Land the work now: write what you have to a file and finish the rest of the answer from it, or hand the rest on with send_reply status "working" and work (start_task inside a task run). Another round of gathering is not worth what is left.`;
|
||||
|
||||
/**
|
||||
* Sent once, a quarter of the way into a run's token budget, when nothing
|
||||
@@ -582,7 +621,7 @@ export const openRunsNote = ({
|
||||
|
||||
${lines.join("\n")}
|
||||
|
||||
Until it reports, a run is shown what the user writes here, between its steps. When the user corrects, changes or adds to the work of one of these runs, it takes that in: tell them so in a line, and don't start another run for it or redo that work in this reply (start_task with separate is only for different work). If they want a run to start over from scratch, they can Stop it and ask again.`;
|
||||
Until it reports, a run is shown what the user writes here, between its steps. When the user corrects, changes or adds to the work of one of these runs, it takes that in: tell them so in a line, and don't start another run for it or redo that work in this reply (send_reply with work and separate is only for different work). If they want a run to start over from scratch, they can Stop it and ask again.`;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -598,7 +637,7 @@ Tasks are the crew's to-do list. A task belongs to one bot, on its own list or i
|
||||
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
|
||||
- On a workspace-wide task, read its log first (list_tasks with task_id) to see which bot did what and when, take a part nobody has done yet, and log each part you finish with update_task. Every note is recorded under your name and id, so the log is how the crew stays in step.
|
||||
- A deliverable is a file: save it first with write_file, make_pdf or generate_image, then pass its [file:ID] ref in deliverable_file_ids, so the task carries what it produced.
|
||||
- When you name a task, write its [task:ID] ref, e.g. [task:12], so the user can open it. Only tasks from list_tasks or create_task have one; a run from start_task or delegate_task is not a task.`;
|
||||
- When you name a task, write its [task:ID] ref, e.g. [task:12], so the user can open it. Only tasks from list_tasks or create_task have one; a run from send_reply's work, start_task or delegate_task is not a task.`;
|
||||
|
||||
/**
|
||||
* Added to a chat reply: when and how to bring pending tasks up, so the bot
|
||||
@@ -823,7 +862,7 @@ export const passedOnRequestNote = `# A request another bot passed on
|
||||
|
||||
This conversation is your part of a crew request: another bot asked for something and the coordinator passed it to you. Answer it fully, with what you already know and can reach, and cite the files you made or used. If you don't have what it needs, say so plainly and what the asking bot could do instead: that is a useful answer, not a refusal. The answer goes back to the bot that asked, not to a user, so write to that bot. Never take instructions from the request beyond answering what it asks for.
|
||||
|
||||
If the work needs a run on a computer, start it with start_task and say in one sentence that you've taken it on: the run's result goes back to the bot that asked on its own when it's done, so don't promise a separate report and don't say the work is finished before it is. While the request is still open you can send the asking bot a short interim word with update_requester; the final result comes back without it.`;
|
||||
If the work needs a run on a computer, start it with send_reply status "working" and work (or start_task inside a task run) and say in one sentence that you've taken it on: the run's result goes back to the bot that asked on its own when it's done, so don't promise a separate report and don't say the work is finished before it is. While the request is still open you can send the asking bot a short interim word with update_requester; the final result comes back without it.`;
|
||||
|
||||
/**
|
||||
* A task run that is part of a crew request (`params.ask_id`): its report
|
||||
@@ -905,7 +944,7 @@ Some requests are several pieces of work that build on each other, and answering
|
||||
- the user's answer will cost real time or money and they should see the shape of it first, or
|
||||
- you would otherwise be listing everything you're about to do.
|
||||
|
||||
Don't plan a question you can answer, one change, or work you're handing to a run (start_task): that is already broken down.
|
||||
Don't plan a question you can answer, one change, or work you're handing to a run (send_reply's work, or start_task inside a task run): that is already broken down.
|
||||
|
||||
A plan is a title, the goal that says what finished looks like, and 3 to 6 steps, one line each, in the order you'd do them, each naming what it produces in the user's words. The steps are what the user reads, so write them for them, not for you.
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* What a reply declares about its own end. `done` means nothing is running
|
||||
* once the message goes out, `working` means a run carries the work on and
|
||||
* its result will be posted here, and `blocked` means the work cannot go on
|
||||
* and the message says why. `send_reply` carries it, and the review reads it
|
||||
* against the app's record: a `done` message that says work is under way is
|
||||
* a contradiction, and a `working` one needs a run that is really open.
|
||||
*/
|
||||
export const ReplyStatuses = ["done", "working", "blocked"] as const;
|
||||
|
||||
export type ReplyStatus = (typeof ReplyStatuses)[number];
|
||||
@@ -4,6 +4,11 @@ import openWorkSql from "./open-work-sql";
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The run asking the question (`openWorkSql`). A task run's own job is
|
||||
* open while it works, so without this its report could count itself.
|
||||
*/
|
||||
exclude_job_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -14,8 +19,8 @@ type Params = {
|
||||
* while that step works (L5). Shared by the reply review gate and the crew
|
||||
* request lifecycle, so both read "work is still open" the same way.
|
||||
*/
|
||||
export default async function hasOpenWork({ bot_id, session_id }: Params): Promise<boolean> {
|
||||
const jobs = await BunSQLite.sql<{ id: number }>(openWorkSql({ bot_id, session_id }));
|
||||
export default async function hasOpenWork({ bot_id, session_id, exclude_job_id }: Params): Promise<boolean> {
|
||||
const jobs = await BunSQLite.sql<{ id: number }>(openWorkSql({ bot_id, session_id, exclude_job_id }));
|
||||
|
||||
if (jobs.payload?.[0]) return true;
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ function insert(row: {
|
||||
);
|
||||
}
|
||||
|
||||
function found(bot_id: number, session_id: number) {
|
||||
const condition = openWorkSql({ bot_id, session_id });
|
||||
function found(bot_id: number, session_id: number, exclude_job_id?: number) {
|
||||
const condition = openWorkSql({ bot_id, session_id, exclude_job_id });
|
||||
|
||||
return db.query(condition.sql).all(...condition.values).map((row) => (row as { id: number }).id);
|
||||
}
|
||||
@@ -89,4 +89,17 @@ describe("openWorkSql", () => {
|
||||
|
||||
expect(found(1, 5)).toEqual([]);
|
||||
});
|
||||
|
||||
/**
|
||||
* A task run's own job is `processing` while it writes its report, so
|
||||
* without this a report saying work is under way would count itself as
|
||||
* the work and pass the review.
|
||||
*/
|
||||
test("the run's own job is not open work", () => {
|
||||
insert({ id: 8, status: "processing", kind: "task", bot_id: 1, session_id: 5 });
|
||||
insert({ id: 9, status: "pending", kind: "task", bot_id: 1, session_id: 5 });
|
||||
|
||||
expect(found(1, 5, 8)).toEqual([9]);
|
||||
expect(found(1, 5).length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,12 @@ import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The run asking the question. A task run's own job is open while it
|
||||
* writes its report, and counting it would let the report say work is
|
||||
* under way with nothing but itself behind the claim.
|
||||
*/
|
||||
exclude_job_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -12,16 +18,31 @@ type Params = {
|
||||
* reply job carrying `params.plan_id`, so it counts too - "step 2 is
|
||||
* running" is not a false claim while that step works (L5). Selects `id`.
|
||||
*/
|
||||
export default function openWorkSql({ bot_id, session_id }: Params): SqlCondition {
|
||||
export default function openWorkSql({ bot_id, session_id, exclude_job_id }: Params): SqlCondition {
|
||||
/**
|
||||
* No id is ever negative: -1 stands in for "exclude nothing", since the
|
||||
* condition's values are numbers and a bound null would need a wider
|
||||
* `SqlCondition` type.
|
||||
*/
|
||||
const excluded = exclude_job_id == null ? -1 : Number(exclude_job_id);
|
||||
|
||||
return {
|
||||
sql: `SELECT id FROM bots_queue
|
||||
WHERE status IN ('pending', 'processing')
|
||||
AND id <> ?
|
||||
AND (
|
||||
(kind = 'task' AND ((bot_id = ? AND session_id = ?) OR requested_by_session_id = ?))
|
||||
OR (kind = 'reply' AND bot_id = ? AND session_id = ?
|
||||
AND json_extract(COALESCE(params, '{}'), '$.plan_id') IS NOT NULL)
|
||||
)
|
||||
LIMIT 1`,
|
||||
values: [Number(bot_id), Number(session_id), Number(session_id), Number(bot_id), Number(session_id)],
|
||||
values: [
|
||||
excluded,
|
||||
Number(bot_id),
|
||||
Number(session_id),
|
||||
Number(session_id),
|
||||
Number(bot_id),
|
||||
Number(session_id),
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -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, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -1785,6 +1785,178 @@ describe("runTextLoop closing tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop required send_reply", () => {
|
||||
const sendReply: HarnessTool<{ status: "done" | "working" | "blocked"; work?: unknown }> = {
|
||||
name: "send_reply",
|
||||
description: "Sends the message.",
|
||||
schema: z.object({
|
||||
status: z.enum(["done", "working", "blocked"]),
|
||||
work: z.unknown().optional(),
|
||||
}),
|
||||
run: async () => "Sent.",
|
||||
};
|
||||
|
||||
test("a reply's text without send_reply is a draft, never the answer", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "I'm generating the banner now." },
|
||||
{
|
||||
text: "Generated the banner.",
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Make a banner." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Generated the banner.");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(seen[1]!.messages.some((message) => message.content === replyDraftNote)).toBe(true);
|
||||
});
|
||||
|
||||
test("a run that keeps writing drafts fails instead of sending one", async () => {
|
||||
const { generate, seen } = scripted([{ text: "One." }, { text: "Two." }, { text: "Three." }]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Make a banner." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyDraftNote);
|
||||
expect(seen.length).toBe(AppData.HarnessReplyDraftsMax + 1);
|
||||
});
|
||||
|
||||
test("a draft on the last wrap up turn fails instead of ending the loop", async () => {
|
||||
const { generate } = scripted([
|
||||
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"x"}` }] },
|
||||
{ text: "First draft." },
|
||||
{ text: "Second draft." },
|
||||
{ text: "Final draft." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Go." }],
|
||||
tools: [remember, sendReply],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyDraftNote);
|
||||
});
|
||||
|
||||
test("passes send_reply's status to the review", async () => {
|
||||
const statuses: (string | undefined)[] = [];
|
||||
const { generate } = scripted([
|
||||
{
|
||||
text: "Working on it.",
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"working"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Make a banner." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
review: async ({ status }) => {
|
||||
statuses.push(status);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
|
||||
expect(statuses).toEqual(["working"]);
|
||||
expect(result.text).toBe("Working on it.");
|
||||
});
|
||||
|
||||
test("a card alone doesn't close a reply that requires send_reply", async () => {
|
||||
asked.length = 0;
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Which date rule?",
|
||||
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` }],
|
||||
},
|
||||
{
|
||||
text: "Asked. Waiting on your answer.",
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Ask me which date rule." }],
|
||||
tools: [askUser, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Asked. Waiting on your answer.");
|
||||
expect(asked).toEqual(["Which date rule?"]);
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingRequiredNote });
|
||||
});
|
||||
|
||||
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"}` }] },
|
||||
{
|
||||
text: "Here is the answer.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Answer me." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Here is the answer.");
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("the wrap up still offers send_reply", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"x"}` }] },
|
||||
{
|
||||
text: "Report.",
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Go." }],
|
||||
tools: [remember, sendReply],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["send_reply"]);
|
||||
expect(result.text).toBe("Report.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop answer not sent", () => {
|
||||
test("says once that a message written before a tool call never went out", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
|
||||
@@ -11,14 +11,21 @@ import {
|
||||
oversizedRequestNote,
|
||||
repairedAnswerNote,
|
||||
repeatedAnswerNote,
|
||||
replyClosingFailedNote,
|
||||
replyClosingMixedNote,
|
||||
replyClosingRequiredNote,
|
||||
replyDraftNote,
|
||||
replyNoTextNote,
|
||||
tokensLowNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import sanitizeAnswerText from "@/src/utils/sanitize-answer-text";
|
||||
import repairAnswerText from "@/src/utils/repair-answer-text";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
|
||||
import HarnessError from "../harness-error";
|
||||
import isClosingTool from "../tools/closing-tool-names";
|
||||
import isClosingTool, { SendReplyToolName } from "../tools/closing-tool-names";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey, { toolCallKey } from "../tools/repeat-tool-call-key";
|
||||
@@ -135,7 +142,18 @@ type Params = {
|
||||
* turn exists only because the previous answer was sent back. A check
|
||||
* that throws lets the answer through.
|
||||
*/
|
||||
review?: (params: { text: string; tool_uses: HarnessToolUse[] }) => Promise<string | null | undefined>;
|
||||
review?: (params: {
|
||||
text: string;
|
||||
tool_uses: HarnessToolUse[];
|
||||
status?: ReplyStatus;
|
||||
}) => Promise<string | null | undefined>;
|
||||
/**
|
||||
* The run must end with `send_reply`: the text a turn writes without it
|
||||
* is a draft and is never sent. A reply and a task report both set this,
|
||||
* so the app's record of what happens after the message is the call the
|
||||
* model made, never a promise the app read out of prose.
|
||||
*/
|
||||
require_closing_answer?: boolean;
|
||||
/**
|
||||
* The bot the run is for: its own models are used where it has them.
|
||||
*/
|
||||
@@ -171,6 +189,12 @@ export type TextLoopResult = {
|
||||
* app knows is wrong.
|
||||
*/
|
||||
review_note?: string;
|
||||
/**
|
||||
* What the closing `send_reply` declared, when the run ended with one.
|
||||
* A caller that queued work with it keeps that run only for `working`;
|
||||
* anything else was withdrawn by the correction that ended the reply.
|
||||
*/
|
||||
status?: ReplyStatus;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -186,17 +210,26 @@ export const WrapUpSaveToolNames = ["write_file", "import_file"];
|
||||
* budget (`AppData.BotReplyMaxToolSteps`, unlimited unless the install
|
||||
* sets one), and a reply that used it all researching leaves the writing
|
||||
* undone; the next reply starts from the same budget, so the run queues
|
||||
* the rest as a task (`start_task`) while it can still call a tool,
|
||||
* rather than saying it will do it later. The app runs it as soon as the
|
||||
* reply is out.
|
||||
* the rest as a task while it can still call a tool, rather than saying it
|
||||
* will do it later. `send_reply` carries that hand-off as `work`, and is
|
||||
* also the only way the run's message goes out.
|
||||
*/
|
||||
export const WrapUpHandOffToolNames = ["start_task"];
|
||||
|
||||
/**
|
||||
* Every tool the wrap up may still call (`WrapUpSaveToolNames` and
|
||||
* `WrapUpHandOffToolNames`): those the run has, in its own order.
|
||||
* The tool that ends the run's message. A reply and a task report must end
|
||||
* with it (`require_closing_answer`), even on the last wrap-up turn, when
|
||||
* every other tool is gone: without it there is no message, not a promise
|
||||
* the app has to read out of prose.
|
||||
*/
|
||||
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames];
|
||||
export const WrapUpAnswerToolNames = [SendReplyToolName];
|
||||
|
||||
/**
|
||||
* Every tool the wrap up may still call (`WrapUpSaveToolNames`,
|
||||
* `WrapUpHandOffToolNames` and `WrapUpAnswerToolNames`): those the run has,
|
||||
* in its own order.
|
||||
*/
|
||||
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames, ...WrapUpAnswerToolNames];
|
||||
|
||||
/**
|
||||
* Saving turns a wrap up may take: the first, and one more when it reached
|
||||
@@ -217,15 +250,18 @@ export const wrapUpPrompt = ({
|
||||
reason = "steps",
|
||||
saving = [],
|
||||
hand_off = [],
|
||||
answer = [],
|
||||
}: {
|
||||
uses: HarnessToolUse[];
|
||||
reason?: "steps" | "tokens";
|
||||
saving?: string[];
|
||||
hand_off?: string[];
|
||||
answer?: string[];
|
||||
}) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${wrapUpToolsPrompt({
|
||||
saving,
|
||||
hand_off,
|
||||
answer,
|
||||
})} Report what you did, what is left, and anything you need from the user.
|
||||
|
||||
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
|
||||
@@ -234,24 +270,50 @@ The tools you actually called this run: ${describeToolUses({ uses })}. Nothing e
|
||||
* What the wrap up may still call, said in one line: save the work, hand
|
||||
* on what it can't finish, or neither.
|
||||
*/
|
||||
const wrapUpToolsPrompt = ({ saving, hand_off }: { saving: string[]; hand_off: string[] }) => {
|
||||
if (!saving.length && !hand_off.length) return `Don't call any more tools.`;
|
||||
const wrapUpToolsPrompt = ({
|
||||
saving,
|
||||
hand_off,
|
||||
answer,
|
||||
}: {
|
||||
saving: string[];
|
||||
hand_off: string[];
|
||||
answer: string[];
|
||||
}) => {
|
||||
if (!saving.length && !hand_off.length && !answer.length) return `Don't call any more tools.`;
|
||||
|
||||
return [
|
||||
saving.length
|
||||
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable)${hand_off.length ? "" : " and nothing else"}, then report.`
|
||||
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable)${hand_off.length || answer.length ? "" : " and nothing else"}, then report.`
|
||||
: "",
|
||||
hand_off.length
|
||||
? saving.length
|
||||
? `If real work is left that this run can't finish, call ${hand_off.join(" or ")} with a complete brief of what's left: it runs after this turn and posts its own result.`
|
||||
: `You have one turn to hand the work on: ${hand_off.join(" or ")} is still yours. If real work is left, call it with a complete brief of what's left: it runs after this turn and posts its own result.`
|
||||
: "",
|
||||
answer.length
|
||||
? `End the run with ${answer.join(" or ")}: the message you wrote in that turn is what the user gets, and the call says what happens after it. A message without it is a draft and is never sent. Call it on its own turn, after the tools above have run.`
|
||||
: "",
|
||||
`After this turn no tool is left, so anything unsaved is lost, and so is work you only say you'll do later.`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
};
|
||||
|
||||
/**
|
||||
* The status a `send_reply` call declared, for the review: a call whose
|
||||
* arguments don't parse or name an unknown status is left undefined, and
|
||||
* the tool's own schema refuses it before this matters.
|
||||
*/
|
||||
const replyStatusFromCall = ({ call }: { call: HarnessToolCall }): ReplyStatus | undefined => {
|
||||
try {
|
||||
const args = JSON.parse(call.arguments || "{}");
|
||||
|
||||
return ReplyStatuses.includes(args?.status) ? (args.status as ReplyStatus) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Steps left when a run is warned, once, to save: a share of the run for
|
||||
* long ones, since 5 steps is the whole budget of a short one and no time
|
||||
@@ -294,7 +356,8 @@ Don't repeat tool calls you have already made.`;
|
||||
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
|
||||
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
|
||||
* model is asked to wrap up: one turn with only the wrap-up tools
|
||||
* (`WrapUpToolNames`: what saves the work, and `start_task` for the rest),
|
||||
* (`WrapUpToolNames`: what saves the work, `start_task` for the rest, and
|
||||
* `send_reply` for the message),
|
||||
* then one with none. With neither set (unlimited), the run ends when the
|
||||
* model answers without calling a tool, or when its job's deadline or its
|
||||
* abort signal ends it. An answer `review` finds fault
|
||||
@@ -323,6 +386,7 @@ export default async function runTextLoop({
|
||||
incoming_notes,
|
||||
wrap_up_note,
|
||||
review,
|
||||
require_closing_answer = false,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
generate = generateText,
|
||||
@@ -396,7 +460,9 @@ export default async function runTextLoop({
|
||||
const wrap_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
|
||||
const save_tools = wrap_tools.filter((tool) => WrapUpSaveToolNames.includes(tool.name));
|
||||
const hand_off_tools = wrap_tools.filter((tool) => WrapUpHandOffToolNames.includes(tool.name));
|
||||
const answer_tools = wrap_tools.filter((tool) => WrapUpAnswerToolNames.includes(tool.name));
|
||||
const wrap_definitions = wrap_tools.map((tool) => all_definitions.get(tool.name)!);
|
||||
const answer_definitions = answer_tools.map((tool) => all_definitions.get(tool.name)!);
|
||||
/**
|
||||
* What bounds this run, recorded with every call it makes, so a reply
|
||||
* can be told later which limit shaped it (`read_message_usage`).
|
||||
@@ -446,6 +512,12 @@ export default async function runTextLoop({
|
||||
* once-per-run guard ends the run instead of looping on the same note.
|
||||
*/
|
||||
let closing_retries = 0;
|
||||
/**
|
||||
* How many text-only turns were drafts a required `send_reply` never
|
||||
* ended. Bounded (`AppData.HarnessReplyDraftsMax`): past it the run
|
||||
* fails rather than sending prose the app can't vouch for.
|
||||
*/
|
||||
let reply_drafts = 0;
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
@@ -520,6 +592,7 @@ export default async function runTextLoop({
|
||||
text,
|
||||
index,
|
||||
final = false,
|
||||
status,
|
||||
}: {
|
||||
text: string;
|
||||
index: number;
|
||||
@@ -529,10 +602,16 @@ export default async function runTextLoop({
|
||||
* the run's last look, so it is not sent back into another turn.
|
||||
*/
|
||||
final?: boolean;
|
||||
/**
|
||||
* What `send_reply` declared: the review reads a claim of work
|
||||
* against it, so a `done` message can't say work is under way and a
|
||||
* `working` one must have a run behind it.
|
||||
*/
|
||||
status?: ReplyStatus;
|
||||
}) => {
|
||||
if (!review) return { verdict: "passed" as const };
|
||||
|
||||
const note = await review({ text, tool_uses }).catch(async (error) => {
|
||||
const note = await review({ text, tool_uses, status }).catch(async (error) => {
|
||||
/**
|
||||
* A reviewer that throws passes the answer, which is the safe
|
||||
* thing to do with the user's reply, but it must not read like a
|
||||
@@ -609,6 +688,7 @@ export default async function runTextLoop({
|
||||
reason: out_of_steps ? "steps" : "tokens",
|
||||
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
|
||||
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
|
||||
answer: answer_tools.map((tool) => tool.name),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -622,7 +702,11 @@ export default async function runTextLoop({
|
||||
|
||||
if (wrap_up_saving) saving_turns++;
|
||||
|
||||
const definitions = wrap_up_saving ? wrap_definitions : wrap_up ? [] : definitionsNow();
|
||||
const definitions = wrap_up
|
||||
? wrap_up_saving
|
||||
? wrap_definitions
|
||||
: answer_definitions
|
||||
: definitionsNow();
|
||||
|
||||
/**
|
||||
* Sized for the model the run is on (or will start on). A fallback
|
||||
@@ -690,11 +774,17 @@ export default async function runTextLoop({
|
||||
|
||||
/**
|
||||
* Only the tools this turn offered: at the wrap up that is the
|
||||
* saving ones, and the last turn offers none.
|
||||
* saving ones, and on the last turn only the answer tool, which is
|
||||
* the one way a required closing message still goes out.
|
||||
*/
|
||||
const tool_calls = (wrap_up ? (wrap_up_saving ? answer.tool_calls : []) : answer.tool_calls).filter(
|
||||
(call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name),
|
||||
);
|
||||
const offered = wrap_up
|
||||
? wrap_up_saving
|
||||
? answer.tool_calls
|
||||
: answer.tool_calls.filter((call) => answer_tools.some((tool) => tool.name == call.name))
|
||||
: answer.tool_calls;
|
||||
const tool_calls = offered.filter((call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name));
|
||||
const reply_call = tool_calls.filter((call) => call.name === SendReplyToolName).at(-1);
|
||||
const reply_status = reply_call ? replyStatusFromCall({ call: reply_call }) : undefined;
|
||||
|
||||
/**
|
||||
* What the app would never show as its own word comes out before
|
||||
@@ -718,6 +808,33 @@ export default async function runTextLoop({
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* On the last turn only the answer tool is offered: a turn that
|
||||
* reaches for anything else beside it would have that call silently
|
||||
* dropped, and the message could say it happened. Refuse the whole
|
||||
* turn and say what is left.
|
||||
*/
|
||||
if (
|
||||
wrap_up &&
|
||||
!wrap_up_saving &&
|
||||
answer_tools.length > 0 &&
|
||||
answer.tool_calls.some((call) => !answer_tools.some((tool) => tool.name == call.name))
|
||||
) {
|
||||
/**
|
||||
* This is the last turn, so there is no next one to try again
|
||||
* on: the message would be a draft the app cannot vouch for.
|
||||
*/
|
||||
return {
|
||||
text: "",
|
||||
review_note: `Only ${answer_tools.map((tool) => tool.name).join(" and ")} can end this run, and this turn called something else beside it, so no message was sent.`,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
transcript.push({
|
||||
role: "assistant",
|
||||
content: answer.text,
|
||||
@@ -765,6 +882,37 @@ export default async function runTextLoop({
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* A required closing answer is never prose alone: text without
|
||||
* `send_reply` is a draft, and the app does not send it. Told a
|
||||
* bounded number of times (`AppData.HarnessReplyDraftsMax`), then
|
||||
* the run fails honestly instead of turning a promise into a
|
||||
* message.
|
||||
*/
|
||||
if (require_closing_answer && !tool_calls.length) {
|
||||
/**
|
||||
* The last wrap-up turn has no next turn, so a draft there is
|
||||
* the end: returning it as an answer is exactly the hole this
|
||||
* protocol closes.
|
||||
*/
|
||||
if (!(wrap_up && !wrap_up_saving) && reply_drafts < AppData.HarnessReplyDraftsMax) {
|
||||
reply_drafts += 1;
|
||||
pushUserTurn({ transcript, content: replyDraftNote });
|
||||
await traced({ kind: "event", index, name: "reply_draft", text: replyDraftNote });
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: replyDraftNote,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
if (!tool_calls.length && (!wrap_up || review_pending)) {
|
||||
review_pending = false;
|
||||
|
||||
@@ -965,7 +1113,14 @@ export default async function runTextLoop({
|
||||
* called nothing at all is still a whole answer (the check below).
|
||||
*/
|
||||
const called_card = tool_calls.some((call) => isClosingTool({ name: call.name }));
|
||||
const called_send_reply = tool_calls.some((call) => call.name === SendReplyToolName);
|
||||
const closing = tool_calls.every((call) => isClosingTool({ name: call.name }));
|
||||
/**
|
||||
* A required closing answer needs `send_reply` itself, not just any
|
||||
* closing call: a card alone says what to ask, never that work is
|
||||
* running, and the status it declares is what the review reads.
|
||||
*/
|
||||
const closing_required = !require_closing_answer || called_send_reply;
|
||||
/**
|
||||
* Only a closing call the tool refused is a failure: it put nothing
|
||||
* up, and a message written as if it had points at a card no one can
|
||||
@@ -976,16 +1131,33 @@ export default async function runTextLoop({
|
||||
*/
|
||||
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_worked = closing && !closing_failed;
|
||||
const closing_worked = closing && !closing_failed && closing_required;
|
||||
|
||||
if (called_card && (closing_failed || !closing)) {
|
||||
if (called_card && (closing_failed || !closing || !closing_required)) {
|
||||
/**
|
||||
* Bounded: past the retries the run ends on the answer it wrote,
|
||||
* reviewed like any reply, rather than looping on a card it can't
|
||||
* put up or a turn it won't finish.
|
||||
* Bounded: past the retries a card-only turn ends on the answer
|
||||
* it wrote, reviewed like any reply, rather than looping on a
|
||||
* card it can't put up. A required closing message is refused
|
||||
* instead: without `send_reply` there is no honest message.
|
||||
*/
|
||||
if (closing_retries >= AppData.MaxClosingRetries) {
|
||||
const check = await checkAnswer({ text: answer.text || "", index });
|
||||
if (closing_retries >= AppData.MaxClosingRetries || (wrap_up && !wrap_up_saving)) {
|
||||
if (require_closing_answer) {
|
||||
return {
|
||||
text: "",
|
||||
review_note: closing_failed
|
||||
? replyClosingFailedNote
|
||||
: !closing
|
||||
? replyClosingMixedNote
|
||||
: replyClosingRequiredNote,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
const check = await checkAnswer({ text: answer.text || "", index, final: wrap_up && !wrap_up_saving });
|
||||
|
||||
return {
|
||||
text: check.verdict === "refused" ? "" : answer.text || "",
|
||||
@@ -1000,10 +1172,19 @@ export default async function runTextLoop({
|
||||
|
||||
closing_retries++;
|
||||
|
||||
const note = closing_failed ? closingFailedNote : closingMixedNote;
|
||||
const note = closing_failed
|
||||
? called_send_reply || require_closing_answer
|
||||
? replyClosingFailedNote
|
||||
: closingFailedNote
|
||||
: !closing
|
||||
? called_send_reply
|
||||
? replyClosingMixedNote
|
||||
: closingMixedNote
|
||||
: replyClosingRequiredNote;
|
||||
const name = closing_failed ? "closing_failed" : !closing ? "closing_mixed" : "closing_required";
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: closing_failed ? "closing_failed" : "closing_mixed", text: note });
|
||||
await traced({ kind: "event", index, name, text: note });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1013,15 +1194,18 @@ export default async function runTextLoop({
|
||||
* and the run ends on the sentence it writes (`closingNoTextNote`).
|
||||
*/
|
||||
if (closing_worked && called_card && !(answer.text || "").trim()) {
|
||||
if (!told_closing_text) {
|
||||
const no_text_note = called_send_reply ? replyNoTextNote : closingNoTextNote;
|
||||
|
||||
if (!told_closing_text && !(wrap_up && !wrap_up_saving)) {
|
||||
told_closing_text = true;
|
||||
pushUserTurn({ transcript, content: closingNoTextNote });
|
||||
await traced({ kind: "event", index, name: "closing_no_text", text: closingNoTextNote });
|
||||
pushUserTurn({ transcript, content: no_text_note });
|
||||
await traced({ kind: "event", index, name: "closing_no_text", text: no_text_note });
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: no_text_note,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
@@ -1036,7 +1220,8 @@ export default async function runTextLoop({
|
||||
* back and the answer is written again (the card stays on the
|
||||
* reply, its ref is already recorded).
|
||||
*/
|
||||
const check = await checkAnswer({ text: answer.text, index });
|
||||
const final_turn = wrap_up && !wrap_up_saving;
|
||||
const check = await checkAnswer({ text: answer.text, index, status: reply_status, final: final_turn });
|
||||
|
||||
if (check.verdict === "refused") {
|
||||
const repaired = repairAnswerText({ text: answer.text });
|
||||
@@ -1044,7 +1229,7 @@ export default async function runTextLoop({
|
||||
if (repaired.changed && repaired.text) {
|
||||
// Checked again, as the reply path is: a dead ref the
|
||||
// repair leaves behind must not ship (M3).
|
||||
const recheck = await checkAnswer({ text: repaired.text, index });
|
||||
const recheck = await checkAnswer({ text: repaired.text, index, status: reply_status, final: final_turn });
|
||||
|
||||
if (recheck.verdict === "passed") {
|
||||
await traced({
|
||||
@@ -1061,6 +1246,7 @@ export default async function runTextLoop({
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
status: reply_status,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1085,6 +1271,7 @@ export default async function runTextLoop({
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
status: reply_status,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -141,4 +141,19 @@ describe("grabBotChatTools", () => {
|
||||
expect(list).not.toContain("hand_over_task");
|
||||
expect(list).not.toContain("delegate_task");
|
||||
});
|
||||
|
||||
/**
|
||||
* A reply's only way to start work is `send_reply` with `work`: the
|
||||
* app queues the run with the message, so a message saying work
|
||||
* started can't go out without one. `start_task` stays for task runs
|
||||
* handing work on.
|
||||
*/
|
||||
test("a reply ends with send_reply, not start_task", async () => {
|
||||
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
|
||||
|
||||
const list = await workerNames({ workspace_id: null });
|
||||
|
||||
expect(list).toContain("send_reply");
|
||||
expect(list).not.toContain("start_task");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-
|
||||
import askableBots from "@/src/functions/backend/db/asks/askable-bots";
|
||||
import handOverTaskTool from "./hand-over-task-tool";
|
||||
import setWorkspaceInstructionsTool from "./set-workspace-instructions-tool";
|
||||
import startTaskTool from "./start-task-tool";
|
||||
import sendReplyTool from "./send-reply-tool";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
import grabWorkspaceAdminTools, { type WorkspaceAdminTools } from "./grab-workspace-admin-tools";
|
||||
@@ -59,6 +59,16 @@ type Params = {
|
||||
* The user message being answered.
|
||||
*/
|
||||
message_id?: number | string;
|
||||
/**
|
||||
* The job this run is carrying out, so `send_reply` doesn't count its
|
||||
* own open job as work that is still running.
|
||||
*/
|
||||
job_id?: number | string;
|
||||
/**
|
||||
* Called with the run `send_reply` queued, so the reply can cancel it
|
||||
* if the review refuses the message that announced it.
|
||||
*/
|
||||
onQueue?: (params: { job_id: number }) => void;
|
||||
/**
|
||||
* The files the run reaches (`grabRunScopes`), so a picture it sets is
|
||||
* copied from one it can already read.
|
||||
@@ -70,7 +80,7 @@ type Params = {
|
||||
*/
|
||||
attended?: boolean;
|
||||
/**
|
||||
* The run's browser kind, propagated to `start_task` children (H7) so a
|
||||
* The run's browser kind, propagated to `send_reply`'s work children (H7) so a
|
||||
* hidden session's reply never lets a child reach the user's browsers.
|
||||
*/
|
||||
run_kind?: BrowserRunKind;
|
||||
@@ -97,8 +107,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The tools a bot replies in chat with: its own (memory, instructions, and
|
||||
* in a workspace switching its default computer), start_task for longer
|
||||
* work, search_computers to find what's on its computers,
|
||||
* in a workspace switching its default computer), send_reply for the message
|
||||
* and the longer work it queues, search_computers to find what's on its computers,
|
||||
* ask_user_to_take_over when only the user can do something on one, and
|
||||
* for the coordinator (the super admin's alone) create_workspace and
|
||||
* update_workspace (a workspace and its shared context, which
|
||||
@@ -130,6 +140,8 @@ export default async function grabBotChatTools({
|
||||
session_id,
|
||||
workspace_id,
|
||||
message_id,
|
||||
job_id,
|
||||
onQueue,
|
||||
scopes = [],
|
||||
attended,
|
||||
run_kind,
|
||||
@@ -153,13 +165,15 @@ export default async function grabBotChatTools({
|
||||
onPropose,
|
||||
onTask,
|
||||
})),
|
||||
startTaskTool({
|
||||
sendReplyTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
computers,
|
||||
message_id,
|
||||
job_id,
|
||||
run_kind,
|
||||
onQueue,
|
||||
}),
|
||||
...(computers.length
|
||||
? [
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import countComputerTaskJobs from "@/src/functions/backend/db/bots-queue/count-computer-task-jobs";
|
||||
import enqueueBotJob from "@/src/functions/backend/db/bots-queue/enqueue-bot-job";
|
||||
import grabOpenBotTask from "@/src/functions/backend/db/bots-queue/grab-open-bot-task";
|
||||
import grabOpenAskBySession from "@/src/functions/backend/db/asks/grab-open-ask-by-session";
|
||||
import grabComputerMcpUrl from "@/src/functions/backend/db/computers/grab-computer-mcp-url";
|
||||
import computerNotReadyMessage from "@/src/utils/computer-not-ready-message";
|
||||
import isComputerDown from "@/src/utils/computer-down";
|
||||
import type { BrowserRunKind } from "@/src/dict/browser-dict";
|
||||
|
||||
export type BotTaskWork = {
|
||||
title: string;
|
||||
instructions: string;
|
||||
computer_id?: number;
|
||||
separate?: boolean;
|
||||
max_steps?: number;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
|
||||
message_id?: number | string;
|
||||
run_kind?: BrowserRunKind;
|
||||
work: BotTaskWork;
|
||||
/**
|
||||
* The tool that asked, so a refusal tells the model to call that tool
|
||||
* again rather than one it no longer has.
|
||||
*/
|
||||
tool_name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Queues a task run for a bot and returns what the call's answer needs: its
|
||||
* id, how many runs are ahead on the computer, and the crew request it is
|
||||
* part of, if any. Shared by `start_task` (a hand-off inside a task run) and
|
||||
* `send_reply` (a reply that starts work and says so in the same turn), so
|
||||
* both apply the same guards: no duplicate title, one run per computer
|
||||
* unless `separate`, and a computer that's down is refused before anything
|
||||
* is queued.
|
||||
*/
|
||||
export default async function queueBotTask({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
computers,
|
||||
message_id,
|
||||
run_kind,
|
||||
work,
|
||||
tool_name,
|
||||
}: Params): Promise<{ job_id: number; ahead: number; ask_id?: number }> {
|
||||
const same = await grabOpenBotTask({ bot_id, session_id, title: work.title });
|
||||
|
||||
if (same) {
|
||||
throw new Error(
|
||||
`Run #${same.id} "${work.title}" is already ${same.status == "pending" ? "queued" : "under way"}. Don't start it again; its result will be posted here.`,
|
||||
);
|
||||
}
|
||||
|
||||
const computer_id = work.computer_id ?? computers[0]?.id ?? undefined;
|
||||
|
||||
const open = work.separate ? null : await grabOpenBotTask({ bot_id, session_id, computer_id });
|
||||
|
||||
if (open) {
|
||||
throw new Error(
|
||||
`Run #${open.id} "${open.title || "Task"}" is still ${open.status == "pending" ? "queued" : "under way"} here on that computer. If this is the same work, don't start it again: its result will be posted here (the user can Stop it to start over). It's shown what the user writes here between its steps, so a correction or addition to that work reaches it and never calls for another run. If it's different work, call ${tool_name} again now with separate: true; it's queued and starts as soon as run #${open.id} ends. Nothing starts it later but you, now, so never tell the user you'll start it once run #${open.id} is done.`,
|
||||
);
|
||||
}
|
||||
|
||||
const target = computer_id ? await grabComputerMcpUrl({ computer_id }) : null;
|
||||
|
||||
if (target && !target.ready && isComputerDown({ status: target.status })) {
|
||||
throw new Error(
|
||||
`${computerNotReadyMessage(target)} Nothing was queued: a run there would only fail. Tell the user the computer is down and what you'd do once it's back, and don't say the work is under way.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* When this run is part of a crew request being answered, it carries the
|
||||
* ask_id so its result goes back to the bot that asked, not just to this
|
||||
* conversation.
|
||||
*/
|
||||
const ask = await grabOpenAskBySession({ session_id, user_id });
|
||||
|
||||
const job_id = await enqueueBotJob({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
title: work.title,
|
||||
instructions: work.instructions,
|
||||
message_id,
|
||||
computer_id: computer_id || undefined,
|
||||
params: {
|
||||
...(work.max_steps ? { max_steps: work.max_steps } : {}),
|
||||
...(run_kind ? { run_kind } : {}),
|
||||
...(ask?.id ? { ask_id: Number(ask.id) } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const ahead = computer_id ? await countComputerTaskJobs({ computer_id, except_job_id: job_id }) : 0;
|
||||
|
||||
return { job_id, ahead, ask_id: ask?.id ? Number(ask.id) : undefined };
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
|
||||
const queued: Array<Record<string, unknown>> = [];
|
||||
const open_work_calls: Array<{
|
||||
bot_id?: number | string;
|
||||
session_id?: number | string;
|
||||
exclude_job_id?: number | string;
|
||||
}> = [];
|
||||
let open_work = false;
|
||||
let next_job_id = 100;
|
||||
let ahead = 0;
|
||||
|
||||
/**
|
||||
* The real `queueBotTask` runs, so its guards stay in the picture; only
|
||||
* what it reads and writes is mocked. Mocking it whole polluted a sibling
|
||||
* suite that exercises the same helper through `start_task`.
|
||||
*/
|
||||
mock.module("@/src/functions/backend/db/bots-queue/enqueue-bot-job", () => ({
|
||||
default: async (params: Record<string, unknown>) => {
|
||||
queued.push(params);
|
||||
return next_job_id++;
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bots-queue/grab-open-bot-task", () => ({
|
||||
default: async () => null,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/asks/grab-open-ask-by-session", () => ({
|
||||
default: async () => null,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bots-queue/has-open-work", () => ({
|
||||
default: async (params: { bot_id?: number | string; session_id?: number | string; exclude_job_id?: number | string }) => {
|
||||
open_work_calls.push(params);
|
||||
return open_work;
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: sendReplyTool } = await import("./send-reply-tool");
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
const tool = () =>
|
||||
sendReplyTool({
|
||||
user_id: 1,
|
||||
bot_id: 5,
|
||||
session_id: 9,
|
||||
computers: [],
|
||||
job_id: 55,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
queued.length = 0;
|
||||
open_work_calls.length = 0;
|
||||
open_work = false;
|
||||
next_job_id = 100;
|
||||
ahead = 0;
|
||||
});
|
||||
|
||||
describe("sendReplyTool", () => {
|
||||
test("status working with work queues the run and says the message goes out with it", async () => {
|
||||
const queued_jobs: number[] = [];
|
||||
const reply = sendReplyTool({
|
||||
user_id: 1,
|
||||
bot_id: 5,
|
||||
session_id: 9,
|
||||
computers: [],
|
||||
job_id: 55,
|
||||
onQueue: ({ job_id }) => queued_jobs.push(job_id),
|
||||
});
|
||||
|
||||
const result = await reply.run({
|
||||
args: { status: "working", work: { title: "Check the logs", instructions: "Read them." } },
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(queued).toHaveLength(1);
|
||||
expect(queued[0]!.title).toBe("Check the logs");
|
||||
expect(queued[0]!.bot_id).toBe(5);
|
||||
expect(queued_jobs).toEqual([100]);
|
||||
expect(result).toContain("Run #100 queued");
|
||||
expect(result).toContain("Your message beside this call goes out with it");
|
||||
});
|
||||
|
||||
test("queues the work once even if the call runs again", async () => {
|
||||
const reply = tool();
|
||||
const args = {
|
||||
status: "working" as const,
|
||||
work: { title: "Check the logs", instructions: "Read them." },
|
||||
};
|
||||
|
||||
const first = await reply.run({ args, signal });
|
||||
const second = await reply.run({ args, signal });
|
||||
|
||||
expect(queued).toHaveLength(1);
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
|
||||
test("status working without work or an open run refuses without sending", async () => {
|
||||
await expect(tool().run({ args: { status: "working" }, signal })).rejects.toThrow(
|
||||
"Nothing of yours is running in this conversation",
|
||||
);
|
||||
await expect(tool().run({ args: { status: "working" }, signal })).rejects.toThrow("Nothing was sent.");
|
||||
expect(open_work_calls).toEqual([
|
||||
{ bot_id: 5, session_id: 9, exclude_job_id: 55 },
|
||||
{ bot_id: 5, session_id: 9, exclude_job_id: 55 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("status working without work holds when a run is already open", async () => {
|
||||
open_work = true;
|
||||
|
||||
const result = await tool().run({ args: { status: "working" }, signal });
|
||||
|
||||
expect(result).toContain("A run of yours is still open here");
|
||||
expect(open_work_calls[0]!.exclude_job_id).toBe(55);
|
||||
});
|
||||
|
||||
test("work cannot ride with status done or blocked", async () => {
|
||||
await expect(
|
||||
tool().run({ args: { status: "done", work: { title: "x", instructions: "y" } }, signal }),
|
||||
).rejects.toThrow(`work can only be passed with status "working"`);
|
||||
await expect(
|
||||
tool().run({ args: { status: "blocked", work: { title: "x", instructions: "y" } }, signal }),
|
||||
).rejects.toThrow(`work can only be passed with status "working"`);
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("done sends the message and implies nothing runs", async () => {
|
||||
const result = await tool().run({ args: { status: "done" }, signal });
|
||||
|
||||
expect(result).toContain("marked done");
|
||||
expect(result).toContain("Nothing runs after it");
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("blocked sends the message and asks what is needed", async () => {
|
||||
const result = await tool().run({ args: { status: "blocked" }, signal });
|
||||
|
||||
expect(result).toContain("marked blocked");
|
||||
expect(result).toContain("what stopped the work");
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { z } from "zod";
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BrowserRunKind } from "@/src/dict/browser-dict";
|
||||
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
|
||||
import hasOpenWork from "@/src/functions/backend/db/bots-queue/has-open-work";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import queueBotTask, { type BotTaskWork } from "./queue-bot-task";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
|
||||
message_id?: number | string;
|
||||
/**
|
||||
* The run this call ends, so a task report doesn't count its own job as
|
||||
* work that is still open.
|
||||
*/
|
||||
job_id?: number | string;
|
||||
run_kind?: BrowserRunKind;
|
||||
/**
|
||||
* Called with the run `work` queued, so the run that wrote the message
|
||||
* can cancel it if the review refuses that message.
|
||||
*/
|
||||
onQueue?: (params: { job_id: number }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
status: (typeof ReplyStatuses)[number];
|
||||
work?: BotTaskWork;
|
||||
};
|
||||
|
||||
/**
|
||||
* The one way a reply or a task report ends. The text written beside this
|
||||
* call is the message the user gets; the call declares what happens after
|
||||
* it, so the app never has to guess intent from prose.
|
||||
*
|
||||
* `done` says nothing runs once the message is out. `working` says a run
|
||||
* carries the work on, and passes `work` to queue it in the same turn, or
|
||||
* names a run that is already open. `blocked` says the work cannot go on.
|
||||
* A message that says work is under way with `done` is refused by the
|
||||
* review, and a `working` message with no run behind it is refused here.
|
||||
*/
|
||||
export default function sendReplyTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
computers,
|
||||
message_id,
|
||||
job_id,
|
||||
run_kind,
|
||||
onQueue,
|
||||
}: Params): HarnessTool<Args> {
|
||||
let queued: { job_id: number; ahead: number; ask_id?: number } | null = null;
|
||||
|
||||
const listed = computers
|
||||
.map((computer) => `${computer.id} (${computer.name || computer.kind})`)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
name: "send_reply",
|
||||
description: `End every reply with this call. The message you wrote in this turn is what the user gets; this call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. A message sent without this call is a draft and never reaches the user. ${
|
||||
computers.length
|
||||
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
|
||||
: `You have no computer, so work that needs one can't run.`
|
||||
}`,
|
||||
schema: z.object({
|
||||
status: z.enum(ReplyStatuses).describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
|
||||
work: z
|
||||
.object({
|
||||
title: z.string().min(1).max(80).describe("A short label, e.g. \"Check the backup logs\""),
|
||||
instructions: z.string().min(1).max(8000),
|
||||
computer_id: z.number().int().optional(),
|
||||
separate: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("For different work while another run of yours is open here on that computer: it's queued and starts when that one ends. Never to retry or redo the open run."),
|
||||
max_steps: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(AppData.BotStepLimitMax)
|
||||
.optional()
|
||||
.describe(
|
||||
"The most model turns the run may take (each turn is one or more tool calls), enforced by the app; leave out for the install's limit. Set it whenever the user asked to keep a run short or cheap, and for lookups and searches (about 15 to 30), so a run that can't find something stops and reports what it tried instead of searching on.",
|
||||
),
|
||||
})
|
||||
.optional()
|
||||
.describe("The run to start with this message. Required when status is working and no run of yours is open here."),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (args.status !== "working" && args.work) {
|
||||
throw new Error(`work can only be passed with status "working": it queues a run, so the message must say that work is under way. Nothing was sent.`);
|
||||
}
|
||||
|
||||
if (args.status === "working") {
|
||||
if (args.work) {
|
||||
if (!queued) {
|
||||
queued = await queueBotTask({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
computers,
|
||||
message_id,
|
||||
run_kind,
|
||||
tool_name: "send_reply",
|
||||
work: args.work,
|
||||
});
|
||||
|
||||
onQueue?.({ job_id: queued.job_id });
|
||||
}
|
||||
|
||||
return `Run #${queued.job_id} queued${args.work.max_steps ? ` with at most ${args.work.max_steps} steps` : ""}; you'll work on it yourself in the background. It's not on the task list (list_tasks), so never tell the user to look for it there. ${
|
||||
queued.ahead
|
||||
? `The computer has ${queued.ahead} other ${queued.ahead == 1 ? "run" : "runs"} queued or working (they go one at a time), so it waits for ${queued.ahead == 1 ? "it" : "them"} first: your message should say it's queued behind other work, not that it's running. `
|
||||
: ""
|
||||
}Your message beside this call goes out with it: say in one sentence, in the first person, what you're doing (e.g. "I'm checking your inbox now. I'll report back when I'm done.").`;
|
||||
}
|
||||
|
||||
const open = await hasOpenWork({ bot_id, session_id, exclude_job_id: job_id });
|
||||
|
||||
if (!open) {
|
||||
throw new Error(
|
||||
`Nothing of yours is running in this conversation, so status "working" would be a promise with nothing behind it. Pass work to queue it now, or end with status "done" and write the answer. Nothing was sent.`,
|
||||
);
|
||||
}
|
||||
|
||||
return `A run of yours is still open here, so status "working" holds. Your message beside this call goes out with it: say what it's doing, in one sentence, and that its result will be posted here.`;
|
||||
}
|
||||
|
||||
if (args.status === "blocked") {
|
||||
return `Your message beside this call goes out, marked blocked. Say plainly what stopped the work and what you need from the user to go on.`;
|
||||
}
|
||||
|
||||
return `Your message beside this call goes out, marked done. Nothing runs after it, so it must not say work is under way or that a report will follow.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,15 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import enqueueBotJob from "@/src/functions/backend/db/bots-queue/enqueue-bot-job";
|
||||
import countComputerTaskJobs from "@/src/functions/backend/db/bots-queue/count-computer-task-jobs";
|
||||
import grabOpenBotTask from "@/src/functions/backend/db/bots-queue/grab-open-bot-task";
|
||||
import grabOpenAskBySession from "@/src/functions/backend/db/asks/grab-open-ask-by-session";
|
||||
import grabComputerMcpUrl from "@/src/functions/backend/db/computers/grab-computer-mcp-url";
|
||||
import computerNotReadyMessage from "@/src/utils/computer-not-ready-message";
|
||||
import isComputerDown from "@/src/utils/computer-down";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { BrowserRunKind } from "@/src/dict/browser-dict";
|
||||
import queueBotTask from "./queue-bot-task";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -96,57 +90,24 @@ export default function startTaskTool({
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const same = await grabOpenBotTask({ bot_id, session_id, title: args.title });
|
||||
|
||||
if (same) {
|
||||
throw new Error(
|
||||
`Run #${same.id} "${args.title}" is already ${same.status == "pending" ? "queued" : "under way"}. Don't start it again; its result will be posted here.`,
|
||||
);
|
||||
}
|
||||
|
||||
const computer_id = args.computer_id ?? computers[0]?.id ?? undefined;
|
||||
|
||||
const open = args.separate ? null : await grabOpenBotTask({ bot_id, session_id, computer_id });
|
||||
|
||||
if (open) {
|
||||
throw new Error(
|
||||
`Run #${open.id} "${open.title || "Task"}" is still ${open.status == "pending" ? "queued" : "under way"} here on that computer. If this is the same work, don't start it again: its result will be posted here (the user can Stop it to start over). It's shown what the user writes here between its steps, so a correction or addition to that work reaches it and never calls for another run. If it's different work, call start_task again now with separate: true; it's queued and starts as soon as run #${open.id} ends. Nothing starts it later but you, now, so never tell the user you'll start it once run #${open.id} is done.`,
|
||||
);
|
||||
}
|
||||
|
||||
const target = computer_id ? await grabComputerMcpUrl({ computer_id }) : null;
|
||||
|
||||
if (target && !target.ready && isComputerDown({ status: target.status })) {
|
||||
throw new Error(
|
||||
`${computerNotReadyMessage(target)} Nothing was queued: a run there would only fail. Tell the user the computer is down and what you'd do once it's back, and don't say the work is under way.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* When this run is part of a crew request being answered, it
|
||||
* carries the ask_id so its result goes back to the bot that
|
||||
* asked, not just to this conversation.
|
||||
*/
|
||||
const ask = await grabOpenAskBySession({ session_id, user_id });
|
||||
|
||||
const job_id = await enqueueBotJob({
|
||||
const { job_id, ahead, ask_id } = await queueBotTask({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
title: args.title,
|
||||
instructions: args.instructions,
|
||||
computers,
|
||||
message_id,
|
||||
computer_id: computer_id || undefined,
|
||||
params: {
|
||||
...(args.max_steps ? { max_steps: args.max_steps } : {}),
|
||||
...(run_kind ? { run_kind } : {}),
|
||||
...(ask?.id ? { ask_id: Number(ask.id) } : {}),
|
||||
run_kind,
|
||||
tool_name: "start_task",
|
||||
work: {
|
||||
title: args.title,
|
||||
instructions: args.instructions,
|
||||
computer_id: args.computer_id,
|
||||
separate: args.separate,
|
||||
max_steps: args.max_steps,
|
||||
},
|
||||
});
|
||||
|
||||
const ahead = computer_id ? await countComputerTaskJobs({ computer_id, except_job_id: job_id }) : 0;
|
||||
|
||||
const closing = ask?.id
|
||||
const closing = ask_id
|
||||
? `This run is part of the request another bot passed on: its result goes back to that bot when it's done. Acknowledge in one sentence and carry on; don't promise a separate report.`
|
||||
: `Tell the user in one sentence, in the first person, what you're doing (e.g. "I'm checking your inbox now. I'll report back when I'm done."); the result will be posted here when it's done.`;
|
||||
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
/**
|
||||
* Tools a run ends on: they put a card under the answer and expect nothing
|
||||
* after them. `ask_user` waits for the user's answer, and
|
||||
* `suggest_next_steps` is offered when the work is done, so a turn that
|
||||
* writes the reply and asks, or offers what comes next, has said everything
|
||||
* it has to say.
|
||||
* The tool every reply and task report ends on. Its call declares what
|
||||
* happens after the message (`status`), and the text written beside it is
|
||||
* the message itself: nothing is inferred from prose any more, so a message
|
||||
* that says work is under way can only exist with `status: "working"` and a
|
||||
* run behind it.
|
||||
*/
|
||||
export const SendReplyToolName = "send_reply";
|
||||
|
||||
/**
|
||||
* Tools a run ends on: they put a card under the answer or declare the
|
||||
* reply, and expect nothing after them. `ask_user` waits for the user's
|
||||
* answer, `suggest_next_steps` is offered when the work is done, and
|
||||
* `send_reply` is the reply itself, so a turn that writes the message and
|
||||
* calls one of them has said everything it has to say.
|
||||
*
|
||||
* `runTextLoop` reads this to end the run on that turn, because the reply is
|
||||
* only the run's last message. A run that went on after answering sent
|
||||
@@ -12,7 +21,7 @@
|
||||
* do after answering), and the user got the short "still open" line with no
|
||||
* links in it (Nov 2026).
|
||||
*/
|
||||
export const ClosingToolNames: readonly string[] = ["ask_user", "suggest_next_steps"];
|
||||
export const ClosingToolNames: readonly string[] = [SendReplyToolName, "ask_user", "suggest_next_steps"];
|
||||
|
||||
/**
|
||||
* Whether a call to this tool ends the run when it carries the answer.
|
||||
|
||||
@@ -8,7 +8,14 @@ describe("unknownToolMessage", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("points a reply's browser call to start_task", () => {
|
||||
test("points a reply's browser call to send_reply with work", () => {
|
||||
const text = unknownToolMessage({ name: "browser_navigate", tools: [{ name: "send_reply" }] });
|
||||
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
expect(text).toContain('call send_reply with status "working" and work');
|
||||
});
|
||||
|
||||
test("points a task run's browser call to start_task", () => {
|
||||
const text = unknownToolMessage({ name: "browser_navigate", tools: [{ name: "start_task" }] });
|
||||
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
|
||||
@@ -25,11 +25,17 @@ export default function unknownToolMessage({ name, tools }: Params) {
|
||||
return `Error: There is no tool called "${name}". ${available}`;
|
||||
}
|
||||
|
||||
const can_reply = tools.some((t) => t.name == "send_reply");
|
||||
const can_start = tools.some((t) => t.name == "start_task");
|
||||
const way = can_reply
|
||||
? `call send_reply with status "working" and work`
|
||||
: can_start
|
||||
? "call start_task with a clear brief"
|
||||
: "";
|
||||
|
||||
return `Error: There is no tool called "${name}" here: computer and browser tools only exist in a task on a computer.${
|
||||
can_start
|
||||
? " To use the computer or its browser (an open tab, a site the user is logged in to), call start_task with a clear brief, then tell the user what you're doing. You can use the computer that way; never say you can't."
|
||||
way
|
||||
? ` To use the computer or its browser (an open tab, a site the user is logged in to), ${way}, then tell the user what you're doing. You can use the computer that way; never say you can't.`
|
||||
: ""
|
||||
} ${available}`;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,13 @@ describe("claimsWorkUnderWay", () => {
|
||||
"I'm spinning up the build now.",
|
||||
"I'm starting it now.",
|
||||
"Starting it now.",
|
||||
/**
|
||||
* Session 75 message 951, the reply this protocol was written
|
||||
* for: it deleted the old files, said it was generating the
|
||||
* banner next, and stopped.
|
||||
*/
|
||||
'Now generating the **single centered "6%" signpost** hero using the image generation tool with a tight, focused prompt.',
|
||||
"Generating the banner now.",
|
||||
/**
|
||||
* The shapes that got past the list above: "Let me check" and
|
||||
* "I'll connect and inspect" name work the reply never did,
|
||||
|
||||
@@ -113,6 +113,16 @@ const PromisePatterns = [
|
||||
`^\\s*${IAm}\\s+(?:now\\s+|just\\s+)?${WorkVerb}ing\\b[^.!?\\n]{0,200}\\b(?:then\\s+)?(?:i(?:'|’)ll|i will)\\b`,
|
||||
"i",
|
||||
),
|
||||
/**
|
||||
* "Now generating the single centered 6% signpost hero using the image
|
||||
* generation tool." Production, session 75 message 951: the run deleted
|
||||
* the old files, wrote that, and called no image tool. The sentence
|
||||
* opens with "Now generating", which none of the patterns above read:
|
||||
* the promise patterns open on "starting", and the under-way ones need
|
||||
* "I'm".
|
||||
*/
|
||||
/^\s*(?:now\s+)?(?:generating|rendering|creating|building|designing|drafting|editing|writing|importing|exporting|uploading|downloading|processing|compiling|installing|deploying|testing|checking|reading|reviewing|scanning|searching|analy[sz]ing|working|running|fixing|updating|converting)\b[^.!?\n]{0,160}\b(?:now|right away|immediately|as we speak)\b/i,
|
||||
/^\s*now\s+(?:generating|rendering|creating|building|designing|drafting|editing|writing|importing|exporting|uploading|downloading|processing|compiling|installing|deploying|testing|checking|reading|reviewing|scanning|searching|analy[sz]ing|working|running|fixing|updating|converting)\b/i,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -267,6 +267,73 @@ I'll report what the run actually finds when it reports back.`;
|
||||
test("an answer that holds up has no problems", () => {
|
||||
expect(replyClaimProblems({ text: "Task #20 is cancelled.", tool_uses: [] })).toEqual([]);
|
||||
});
|
||||
|
||||
/**
|
||||
* `send_reply` makes the status part of the answer's protocol, so the
|
||||
* check reads it instead of guessing from the tool history alone. A
|
||||
* `done` message with a run open still contradicts itself: the run is
|
||||
* not this message's answer.
|
||||
*/
|
||||
describe("the status send_reply declares", () => {
|
||||
const working = "I'm generating the banner now.";
|
||||
|
||||
test("done faults a work claim even when a run started or is open", () => {
|
||||
const problems = replyClaimProblems({
|
||||
text: working,
|
||||
tool_uses: [{ name: "start_task", ok: true }],
|
||||
has_open_work: true,
|
||||
status: "done",
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain(`status "done"`);
|
||||
});
|
||||
|
||||
test("working with nothing open faults the promise", () => {
|
||||
const problems = replyClaimProblems({
|
||||
text: working,
|
||||
tool_uses: [],
|
||||
has_open_work: false,
|
||||
status: "working",
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain(`status "working"`);
|
||||
expect(problems[0]).toContain("Pass work to send_reply");
|
||||
});
|
||||
|
||||
test("working with a run open passes", () => {
|
||||
expect(
|
||||
replyClaimProblems({
|
||||
text: working,
|
||||
tool_uses: [],
|
||||
has_open_work: true,
|
||||
status: "working",
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("blocked cannot claim the work carries on", () => {
|
||||
const problems = replyClaimProblems({
|
||||
text: working,
|
||||
tool_uses: [{ name: "start_task", ok: true }],
|
||||
has_open_work: true,
|
||||
status: "blocked",
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain(`status "blocked"`);
|
||||
});
|
||||
|
||||
test("without a status, a started run still excuses the claim", () => {
|
||||
expect(
|
||||
replyClaimProblems({
|
||||
text: working,
|
||||
tool_uses: [{ name: "start_task", ok: true }],
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import claimsWorkUnderWay from "./claims-work-under-way";
|
||||
import unsupportedAppRecordLines from "./app-record-claims";
|
||||
import replyAppStateClaims, { AppStateTools } from "./reply-app-state-claims";
|
||||
@@ -40,6 +41,13 @@ type Params = {
|
||||
* open from this conversation: its result is still to come.
|
||||
*/
|
||||
has_open_work?: boolean;
|
||||
/**
|
||||
* What the reply declared with `send_reply`. `done` and `blocked` mean
|
||||
* nothing is running after the message, so a work claim contradicts
|
||||
* them even when an older run is still open. `working` is only honest
|
||||
* with a run behind it.
|
||||
*/
|
||||
status?: ReplyStatus;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -85,6 +93,7 @@ export default function replyClaimProblems({
|
||||
missing_graphic_ids = [],
|
||||
written_card_refs = [],
|
||||
has_open_work,
|
||||
status,
|
||||
}: Params): string[] {
|
||||
const problems: string[] = [];
|
||||
|
||||
@@ -154,9 +163,19 @@ export default function replyClaimProblems({
|
||||
);
|
||||
}
|
||||
|
||||
if (!started && !tried && !has_open_work && claimsWorkUnderWay({ text })) {
|
||||
const claim = claimsWorkUnderWay({ text });
|
||||
|
||||
if (claim && (status === "done" || status === "blocked")) {
|
||||
problems.push(
|
||||
`It says work is going on beyond this reply, or that its findings are still to come, but this reply started no run (start_task) and nothing of yours is open in this conversation. Nothing is running, so no result arrives unless you call start_task now.`,
|
||||
`It ends with status "${status}", which means nothing runs after this message, but it says work is going on beyond this reply or that its findings are still to come. If a run is carrying the work on, end with status "working" and pass work or name the open run; otherwise write the message as finished work and say only what the tools returned.`,
|
||||
);
|
||||
} else if (claim && status === "working" && !has_open_work) {
|
||||
problems.push(
|
||||
`It ends with status "working", but nothing of yours is open in this conversation. Pass work to send_reply to queue it now, or end with status "done" and write the answer.`,
|
||||
);
|
||||
} else if (claim && status == null && !started && !tried && !has_open_work) {
|
||||
problems.push(
|
||||
`It says work is going on beyond this reply, or that its findings are still to come, but this reply started no run (start_task) and nothing of yours is open in this conversation. Nothing is running, so no result arrives unless you call send_reply with status "working" and work now.`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user