Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9fe487cbd | ||
|
|
435e080c06 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.16",
|
||||
"version": "0.28.17",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
|
||||
import planFinishedClaimNote from "./plan-finished-claim-note";
|
||||
|
||||
const paused = { id: 2, status: "paused", current_step: 2, total_steps: 3 };
|
||||
const active_last = { id: 2, status: "active", current_step: 2, total_steps: 3 };
|
||||
|
||||
describe("planFinishedClaimNote", () => {
|
||||
test("a paused plan claimed as finished is sent back (job 810)", () => {
|
||||
const note = planFinishedClaimNote({
|
||||
plan: paused,
|
||||
text: "**All tasks complete.** Plan #2 finished.",
|
||||
tool_uses: [{ name: "complete_plan_step", ok: false }],
|
||||
});
|
||||
|
||||
expect(note).toContain("Plan #2 is over");
|
||||
expect(note).toContain("paused, at step 3 of 3");
|
||||
expect(note).toContain("update_plan");
|
||||
});
|
||||
|
||||
test("the run that ticked the last step may say the plan is finished", () => {
|
||||
expect(
|
||||
planFinishedClaimNote({
|
||||
plan: active_last,
|
||||
text: "Plan #2 is now complete.",
|
||||
tool_uses: [{ name: "complete_plan_step", ok: true }],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("a step's completion is not the plan's", () => {
|
||||
expect(
|
||||
planFinishedClaimNote({ plan: paused, text: "Plan #2 Step 3 (cross-task wrap-up) complete.", tool_uses: [] }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("a message that claims nothing about the plan, or a run with no plan, passes", () => {
|
||||
expect(planFinishedClaimNote({ plan: paused, text: "Task #8 is done.", tool_uses: [] })).toBeNull();
|
||||
expect(planFinishedClaimNote({ plan: null, text: "Plan #2 finished.", tool_uses: [] })).toBeNull();
|
||||
});
|
||||
|
||||
test("the fault note promises no work of its own", () => {
|
||||
const note = planFinishedClaimNote({ plan: paused, text: "The plan is finished.", tool_uses: [] })!;
|
||||
|
||||
expect(claimsWorkUnderWay({ text: note })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The plan this run sits in, as it stood when the run began: the one it
|
||||
* was queued for, or the one open in its conversation.
|
||||
*/
|
||||
plan: { id: number; status: string; current_step: number | null; total_steps: number } | null;
|
||||
text: string;
|
||||
tool_uses: HarnessToolUse[];
|
||||
};
|
||||
|
||||
/**
|
||||
* "Plan #2 finished", "the plan is now complete": the plan itself claimed
|
||||
* as over, never one of its steps ("Plan #2 Step 3 complete").
|
||||
*/
|
||||
const FinishedClaim =
|
||||
/\b(?:the\s+)?plan(?:\s*#\d+)?(?:\s+(?:is|has\s+been|was|marked))?(?:\s+now)?\s+(?:finished|completed?|done)\b/i;
|
||||
|
||||
/**
|
||||
* Sends back a reply that says the plan is over when the app's record says
|
||||
* it isn't. Job 810 wrote "All tasks complete. Plan #2 finished." right
|
||||
* after `complete_plan_step` refused it ("Plan #2 is paused"), and the
|
||||
* conversation said the plan was done while its card said paused.
|
||||
*
|
||||
* A run that finished the plan's last step itself has made the claim true.
|
||||
* A plan already done is not open, so it never reaches here.
|
||||
*/
|
||||
export default function planFinishedClaimNote({ plan, text, tool_uses }: Params) {
|
||||
if (!plan || plan.status == "done") return null;
|
||||
|
||||
if (!FinishedClaim.test(text.replace(/[*_`]/g, ""))) return null;
|
||||
|
||||
const ticked = tool_uses.some((use) => use.ok && use.name == "complete_plan_step");
|
||||
const on_last = plan.current_step != null && plan.current_step + 1 >= plan.total_steps;
|
||||
|
||||
if (ticked && on_last && plan.status == "active") return null;
|
||||
|
||||
const where =
|
||||
plan.current_step == null
|
||||
? `${plan.status}`
|
||||
: `${plan.status}, at step ${plan.current_step + 1} of ${plan.total_steps}`;
|
||||
|
||||
const fix =
|
||||
plan.status == "paused"
|
||||
? `To finish it, the user resumes it on its card (or asks you to, and you use update_plan with status "active"), and its step is then worked and ticked with complete_plan_step.`
|
||||
: `Finish its current step with complete_plan_step first, or write where it really stands.`;
|
||||
|
||||
return `Your message says Plan #${plan.id} is over, but the app's record has it ${where}. Write where the plan really stands. ${fix}`;
|
||||
}
|
||||
@@ -29,16 +29,25 @@ describe("planStepReviewNote", () => {
|
||||
expect(note({ uses })).toBeNull();
|
||||
});
|
||||
|
||||
test("the last step's card offers to finish the plan", () => {
|
||||
test("ticking the last step finishes the plan, so its report needs no card (jobs 809, 811)", () => {
|
||||
const last = { ...plan, current_step: 2 };
|
||||
const ticked = [{ name: "complete_plan_step", ok: true }];
|
||||
|
||||
expect(
|
||||
planStepReviewNote({
|
||||
plan: last,
|
||||
on_step: true,
|
||||
tool_uses: [{ name: "complete_plan_step", ok: true }],
|
||||
}),
|
||||
).toContain("Finish the plan");
|
||||
expect(planStepReviewNote({ plan: last, on_step: true, tool_uses: ticked, status: "done" })).toBeNull();
|
||||
expect(planStepReviewNote({ plan: last, on_step: false, tool_uses: ticked, status: "done" })).toBeNull();
|
||||
});
|
||||
|
||||
test("the last step left unfinished is sent back to finish it, without asking for a card", () => {
|
||||
const fault = planStepReviewNote({
|
||||
plan: { ...plan, current_step: 2 },
|
||||
on_step: true,
|
||||
tool_uses: [{ name: "write_file", ok: true }],
|
||||
});
|
||||
|
||||
expect(fault).toContain("its last step");
|
||||
expect(fault).toContain("complete_plan_step");
|
||||
expect(fault).toContain("no card goes with this report");
|
||||
expect(fault).not.toContain("Finish the plan");
|
||||
});
|
||||
|
||||
test("a failed finish does not pass", () => {
|
||||
|
||||
@@ -61,7 +61,21 @@ export default function planStepReviewNote({ plan, on_step, tool_uses, status }:
|
||||
const next = step + 1;
|
||||
const last_step = next > plan.total_steps;
|
||||
|
||||
/**
|
||||
* Ticking the last step finishes the plan (`completeBotPlanStep` sets it
|
||||
* `done`), so there is nothing left for a card to move on to: the report
|
||||
* alone ends it, as `complete_plan_step` tells the bot. Asking for a
|
||||
* "Finish the plan" card there contradicted that answer, and every
|
||||
* rewrite was refused until the job failed and the finished plan was
|
||||
* paused again (jobs 809 and 811, Plan #2).
|
||||
*/
|
||||
if (last_step && ticked) return null;
|
||||
|
||||
if (last_step) {
|
||||
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}"), its last step, and ended without finishing it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. That finishes the plan, so no card goes with this report. If it needs the user for something first, ask that with ask_user and say the plan is holding at this step. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it.`;
|
||||
}
|
||||
|
||||
return on_step
|
||||
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
|
||||
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
|
||||
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "Continue to step ${next}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
|
||||
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "Continue to step ${next}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import planStepReviewNote from "./plan-step-review";
|
||||
import planFinishedClaimNote from "./plan-finished-claim-note";
|
||||
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
|
||||
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
|
||||
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
|
||||
@@ -730,7 +731,10 @@ export default async function runBotReply({
|
||||
reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id, plan_mode })({ text, tool_uses, status }).then((note) => {
|
||||
if (note) return note;
|
||||
|
||||
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
|
||||
return (
|
||||
planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status }) ??
|
||||
planFinishedClaimNote({ plan, text, tool_uses })
|
||||
);
|
||||
});
|
||||
|
||||
const result = await runTextLoop({
|
||||
|
||||
@@ -96,6 +96,7 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
|
||||
import BotJobFatalError from "./bot-job-fatal-error";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import planStepReviewNote from "./plan-step-review";
|
||||
import planFinishedClaimNote from "./plan-finished-claim-note";
|
||||
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
@@ -847,6 +848,7 @@ export default async function runBotTask({
|
||||
session_id,
|
||||
computers,
|
||||
message_id: job.message_id || undefined,
|
||||
job_id: job.id,
|
||||
run_kind: browser_run_kind,
|
||||
plan_id: on_plan_step ? plan?.id : null,
|
||||
}),
|
||||
@@ -915,7 +917,10 @@ export default async function runBotTask({
|
||||
}).then((note) => {
|
||||
if (note) return note;
|
||||
|
||||
return planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status });
|
||||
return (
|
||||
planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status }) ??
|
||||
planFinishedClaimNote({ plan: plan ?? session_plan, text, tool_uses })
|
||||
);
|
||||
}),
|
||||
/**
|
||||
* A report goes out only through `send_reply`, so it can't say
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
|
||||
import {
|
||||
closingNoTextNote,
|
||||
closingToolGoneNote,
|
||||
replyCardFailedNote,
|
||||
replyCardOnlyFailedNote,
|
||||
replyClosingFailedNote,
|
||||
replyClosingMixedNote,
|
||||
replyClosingRequiredNote,
|
||||
replyDraftNote,
|
||||
replyNoTextNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import planStepReviewNote from "./plan-step-review";
|
||||
import unsentAnswerMessage from "./unsent-answer-message";
|
||||
|
||||
/**
|
||||
@@ -29,6 +40,28 @@ describe("unsentAnswerMessage", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("closing failures name the call that failed, never the review (jobs 680, 694, 700)", () => {
|
||||
expect(unsentAnswerMessage({ note: replyClosingFailedNote })).toContain("call that sends the message");
|
||||
expect(unsentAnswerMessage({ note: replyClosingRequiredNote })).toContain("never sent the message");
|
||||
expect(unsentAnswerMessage({ note: replyClosingMixedNote })).toContain("other work");
|
||||
expect(unsentAnswerMessage({ note: replyCardOnlyFailedNote({ tools: ["ask_user"] }) })).toContain("card");
|
||||
expect(unsentAnswerMessage({ note: replyCardFailedNote({ tools: ["suggest_next_steps"] }) })).toContain("card");
|
||||
|
||||
for (const note of [replyClosingFailedNote, replyClosingRequiredNote, replyCardOnlyFailedNote({ tools: ["ask_user"] })]) {
|
||||
expect(unsentAnswerMessage({ note })).not.toContain("app's record");
|
||||
}
|
||||
});
|
||||
|
||||
test("a plan step that ended wrong says so", () => {
|
||||
const note = planStepReviewNote({
|
||||
plan: { id: 2, title: "Finish", current_step: 0, total_steps: 3 },
|
||||
on_step: true,
|
||||
tool_uses: [],
|
||||
});
|
||||
|
||||
expect(unsentAnswerMessage({ note: note! })).toContain("plan step");
|
||||
});
|
||||
|
||||
test("a check against the record keeps saying so", () => {
|
||||
expect(unsentAnswerMessage({ note: "It names task #16, and no such task exists." })).toBe(
|
||||
`The answer didn't hold up against the app's record, so it wasn't sent.`,
|
||||
|
||||
@@ -1,4 +1,14 @@
|
||||
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
|
||||
import {
|
||||
closingFailedNote,
|
||||
closingMixedNote,
|
||||
closingNoTextNote,
|
||||
closingToolGoneNote,
|
||||
replyClosingFailedNote,
|
||||
replyClosingMixedNote,
|
||||
replyClosingRequiredNote,
|
||||
replyDraftNote,
|
||||
replyNoTextNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -9,8 +19,21 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The failure notice a run that never sent its answer leaves. The note
|
||||
* the loop returned picks the line, so an empty close is not called a lie.
|
||||
* The openings of the notes built per call (`replyCardFailedNote`,
|
||||
* `replyCardOnlyFailedNote`, `planStepReviewNote`, `unfinishedAnswerText`):
|
||||
* their tails name tools or steps, so they are told apart by how they start.
|
||||
*/
|
||||
const CardRefusedOpenings = ["The card was not put up", "send_reply went through and your message is kept"];
|
||||
const PlanStepOpenings = ["This reply works step", "This reply finished step"];
|
||||
const UnfinishedOpening = "The message stops ";
|
||||
|
||||
/**
|
||||
* The failure notice a run that never sent its answer leaves. The note the
|
||||
* loop returned picks the line, so a run that failed for its own mechanics
|
||||
* is never called a lie: "didn't hold up against the app's record" is only
|
||||
* for an answer the review actually checked and refused. Before, every
|
||||
* closing failure fell through to that line (jobs 680, 694, 700), and the
|
||||
* user read five failures as a bot caught out when none was.
|
||||
*/
|
||||
export default function unsentAnswerMessage({ note }: Params) {
|
||||
if (note === replyNoTextNote) {
|
||||
@@ -29,5 +52,29 @@ export default function unsentAnswerMessage({ note }: Params) {
|
||||
return `The run's last turn called a tool it no longer had, so its message wasn't sent.`;
|
||||
}
|
||||
|
||||
if (note === replyClosingFailedNote) {
|
||||
return `The call that sends the message kept being refused, so the message wasn't sent.`;
|
||||
}
|
||||
|
||||
if (note === replyClosingRequiredNote) {
|
||||
return `The reply put its card up but never sent the message with it, so it wasn't sent.`;
|
||||
}
|
||||
|
||||
if (note === replyClosingMixedNote || note === closingMixedNote) {
|
||||
return `The reply kept doing other work in the turn meant to send its message, so it wasn't sent.`;
|
||||
}
|
||||
|
||||
if (note === closingFailedNote || CardRefusedOpenings.some((opening) => note.startsWith(opening))) {
|
||||
return `The card under the message kept being refused, so the message wasn't sent.`;
|
||||
}
|
||||
|
||||
if (PlanStepOpenings.some((opening) => note.startsWith(opening))) {
|
||||
return `The reply didn't end its plan step the way the plan needs, so it wasn't sent.`;
|
||||
}
|
||||
|
||||
if (note.startsWith(UnfinishedOpening)) {
|
||||
return `The message stopped part-way through (an unclosed table, list or code block), so it wasn't sent.`;
|
||||
}
|
||||
|
||||
return `The answer didn't hold up against the app's record, so it wasn't sent.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,8 +345,13 @@ describe("plan notes", () => {
|
||||
expect(note).toContain('"Pause the plan"');
|
||||
});
|
||||
|
||||
test("the last step's card offers to finish the plan", () => {
|
||||
expect(PlanStepNote({ plan: { ...plan, current_step: 2 } })).toContain('"Finish the plan"');
|
||||
test("the last step ends the plan with its report alone, no card", () => {
|
||||
const note = PlanStepNote({ plan: { ...plan, current_step: 2 } });
|
||||
|
||||
expect(note).toContain("This is the last step");
|
||||
expect(note).toContain("no card");
|
||||
expect(note).not.toContain("Finish the plan");
|
||||
expect(note).not.toContain("Every finished step ends on a card");
|
||||
});
|
||||
|
||||
test("lists the steps with where each one stands and what it produced", () => {
|
||||
|
||||
@@ -655,6 +655,14 @@ export const replyClosingFailedNote = `send_reply did not go through (its error
|
||||
export const replyCardFailedNote = ({ tools }: { tools: string[] }) =>
|
||||
`send_reply went through and your message is kept. The card call did not: ${tools.join(" and ")} refused (its error is above). Fix those arguments, or drop the card, and call send_reply again in the same turn with the same message.`;
|
||||
|
||||
/**
|
||||
* Told when a card was refused in a turn that never called `send_reply`:
|
||||
* the card's error is what to fix. Telling the model `send_reply` failed
|
||||
* there sent it after a status error that never happened (job 694).
|
||||
*/
|
||||
export const replyCardOnlyFailedNote = ({ tools }: { tools: string[] }) =>
|
||||
`The card was not put up: ${tools.join(" and ")} refused its arguments (the error is above), so nothing reached the user. Fix those arguments exactly as the error says and call it again, with send_reply in the same turn carrying your message (the message you wrote beside the card is kept for it). Or drop the card and answer with send_reply alone.`;
|
||||
|
||||
/**
|
||||
* Put under an answer the review kept faulting once its unsupported parts
|
||||
* were taken out (`repairAnswerText`): the user is told part of it is gone
|
||||
@@ -1146,7 +1154,15 @@ export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
|
||||
const index = plan.current_step ?? 0;
|
||||
const step = plan.steps[index];
|
||||
const next = index + 2;
|
||||
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
|
||||
const last_step = next > plan.steps.length;
|
||||
/**
|
||||
* The last step's tick finishes the plan, so its report ends the plan
|
||||
* on its own: a "Finish the plan" card would move nothing on, and the
|
||||
* review used to demand one while the tool said none was needed.
|
||||
*/
|
||||
const ending = last_step
|
||||
? `- **This is the last step.** complete_plan_step finishes the plan, so the report goes out with send_reply alone and no card: there is no next step to continue to.`
|
||||
: `- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "Continue to step ${next}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.`;
|
||||
|
||||
return `# Your plan, step ${index + 1} of ${plan.steps.length}
|
||||
|
||||
@@ -1156,10 +1172,10 @@ ${planStepLines({ plan })}
|
||||
|
||||
This run works step ${index + 1} only: ${step?.text || ""}
|
||||
|
||||
- One step per run. The next step starts when the user answers this report's card, so don't start it now and don't do two.
|
||||
- One step per run.${last_step ? "" : " The next step starts when the user answers this report's card, so don't start it now and don't do two."}
|
||||
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
|
||||
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
|
||||
- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "${next_label}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.
|
||||
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan${last_step ? "" : " and the step after this one"}, so repeating it only makes the reply longer than it needs to be.
|
||||
${ending}
|
||||
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask that question on the card, and say the plan is holding at this step.
|
||||
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same run, and say what changed.`;
|
||||
};
|
||||
@@ -1175,7 +1191,10 @@ export const PlanActiveNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mod
|
||||
const index = plan.current_step;
|
||||
const step = index == null ? null : plan.steps[index];
|
||||
const next = (index ?? 0) + 2;
|
||||
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
|
||||
const work_step =
|
||||
next > plan.steps.length
|
||||
? `finish it with complete_plan_step in this run. It is the last step, so that finishes the plan and the report goes out alone, with no card.`
|
||||
: `finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "Continue to step ${next}", second "Pause the plan"). A report that ticked the step without that card is sent back.`;
|
||||
|
||||
return `# The plan in this conversation
|
||||
|
||||
@@ -1187,7 +1206,7 @@ ${
|
||||
plan_mode
|
||||
? `- This reply runs in Plan mode: the plan is yours to pick up and refine here, not to work. When what they say bears on the steps, rewrite them with update_plan (the whole list, done steps first and unchanged), as many times as the conversation asks, and say in a line what changed. Don't work or tick a step, and don't pause or resume the plan: that waits until the mode is off.`
|
||||
: `- Its steps are normally worked one per reply, each ending on a card the user answers to start the next one. This reply isn't a step the app queued: answer whatever the user asked first.
|
||||
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "${next_label}", second "Pause the plan"). A report that ticked the step without that card is sent back.
|
||||
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: ${work_step}
|
||||
- If they asked something else, answer that and leave the plan where it is: it carries on from there. Don't work a step as a side errand.
|
||||
- If the user's answer to the plan's card was typed rather than a click, it is theirs to read here: carry on with the step when it says to, and park the plan with update_plan and status "paused" when it says to wait.
|
||||
- Only pause or resume when they asked, with update_plan and its status. Never end a plan on your own: cancelling is theirs. The steps are theirs to change on the card too; if the work moved on from one of them, update_plan and say what changed.`
|
||||
|
||||
@@ -1,38 +1,16 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import openBotTaskSql from "./open-bot-task-sql";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* Only a task with this title. Without it, any open task.
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* Only a task on this computer.
|
||||
*/
|
||||
computer_id?: number | string | null;
|
||||
};
|
||||
type Params = Parameters<typeof openBotTaskSql>[0];
|
||||
|
||||
/**
|
||||
* The bot's latest task in this session that's still queued or working
|
||||
* (with this title, on this computer, when given), if any, so the same
|
||||
* work isn't started twice.
|
||||
* work isn't started twice. The run asking (`exclude_job_id`) is never its
|
||||
* own obstacle.
|
||||
*/
|
||||
export default async function grabOpenBotTask({ bot_id, session_id, title, computer_id }: Params) {
|
||||
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
|
||||
sql: `SELECT id, status, title FROM bots_queue
|
||||
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
|
||||
AND status IN ('pending', 'processing')
|
||||
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
|
||||
${computer_id ? `AND computer_id = ?` : ""}
|
||||
ORDER BY id DESC LIMIT 1`,
|
||||
values: [
|
||||
bot_id,
|
||||
session_id,
|
||||
...(title != undefined ? [title] : []),
|
||||
...(computer_id ? [Number(computer_id)] : []),
|
||||
],
|
||||
});
|
||||
export default async function grabOpenBotTask(params: Params) {
|
||||
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>(openBotTaskSql(params));
|
||||
|
||||
return res.payload?.[0] || null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import openBotTaskSql from "./open-bot-task-sql";
|
||||
|
||||
const db = new Database(":memory:");
|
||||
|
||||
beforeEach(() => {
|
||||
db.run(`CREATE TABLE IF NOT EXISTS bots_queue (
|
||||
id INTEGER PRIMARY KEY,
|
||||
status TEXT,
|
||||
kind TEXT,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
computer_id INTEGER,
|
||||
title TEXT
|
||||
)`);
|
||||
db.run(`DELETE FROM bots_queue`);
|
||||
});
|
||||
|
||||
function insert(row: { id: number; status: string; title?: string; computer_id?: number }) {
|
||||
db.run(
|
||||
`INSERT INTO bots_queue (id, status, kind, bot_id, session_id, computer_id, title) VALUES (?, ?, 'task', 3, 95, ?, ?)`,
|
||||
[row.id, row.status, row.computer_id ?? 1, row.title ?? "Fix baseline"],
|
||||
);
|
||||
}
|
||||
|
||||
function found(params: Partial<Parameters<typeof openBotTaskSql>[0]>) {
|
||||
const query = openBotTaskSql({ bot_id: 3, session_id: 95, ...params });
|
||||
|
||||
return (db.query(query.sql).all(...query.values) as { id: number }[]).map((row) => row.id);
|
||||
}
|
||||
|
||||
describe("openBotTaskSql", () => {
|
||||
test("finds the open run on the computer", () => {
|
||||
insert({ id: 680, status: "processing" });
|
||||
|
||||
expect(found({ computer_id: 1 })).toEqual([680]);
|
||||
});
|
||||
|
||||
test("a task run handing work on is not its own obstacle (jobs 680, 700)", () => {
|
||||
insert({ id: 680, status: "processing" });
|
||||
|
||||
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([]);
|
||||
expect(found({ title: "Fix baseline", exclude_job_id: 680 })).toEqual([]);
|
||||
});
|
||||
|
||||
test("another open run still counts when the asking run is left out", () => {
|
||||
insert({ id: 679, status: "pending" });
|
||||
insert({ id: 680, status: "processing" });
|
||||
|
||||
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([679]);
|
||||
});
|
||||
|
||||
test("finished runs and other computers never count", () => {
|
||||
insert({ id: 1, status: "completed" });
|
||||
insert({ id: 2, status: "processing", computer_id: 2 });
|
||||
|
||||
expect(found({ computer_id: 1 })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* Only a task with this title. Without it, any open task.
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* Only a task on this computer.
|
||||
*/
|
||||
computer_id?: number | string | null;
|
||||
/**
|
||||
* The run asking: a task run handing its work on is not the open run
|
||||
* that work would wait behind. Without it, a task report's `send_reply`
|
||||
* with `work` was refused against its own job (jobs 680 and 700), and a
|
||||
* finished report was thrown away.
|
||||
*/
|
||||
exclude_job_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot's latest task in this session that's still queued or working
|
||||
* (with this title, on this computer, when given), leaving out the run
|
||||
* that asks.
|
||||
*/
|
||||
export default function openBotTaskSql({ bot_id, session_id, title, computer_id, exclude_job_id }: Params) {
|
||||
const exclude = Number(exclude_job_id) || 0;
|
||||
|
||||
return {
|
||||
sql: `SELECT id, status, title FROM bots_queue
|
||||
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
|
||||
AND status IN ('pending', 'processing')
|
||||
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
|
||||
${computer_id ? `AND computer_id = ?` : ""}
|
||||
${exclude ? `AND id != ?` : ""}
|
||||
ORDER BY id DESC LIMIT 1`,
|
||||
values: [
|
||||
bot_id,
|
||||
session_id,
|
||||
...(title != undefined ? [title] : []),
|
||||
...(computer_id ? [Number(computer_id)] : []),
|
||||
...(exclude ? [exclude] : []),
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The shapes providers use when their own content filter refused the
|
||||
* request (Alibaba's Model Studio: "Input text data may contain
|
||||
* inappropriate content.", code `data_inspection_failed`; Azure's
|
||||
* `content_filter`; OpenAI's usage-policy refusals).
|
||||
*/
|
||||
const ContentFilterPhrases = [
|
||||
"inappropriate content",
|
||||
"data_inspection_failed",
|
||||
"data inspection failed",
|
||||
"content_filter",
|
||||
"content filter",
|
||||
"content management policy",
|
||||
"content_policy_violation",
|
||||
"content policy",
|
||||
"responsibleaipolicyviolation",
|
||||
"violates our usage polic",
|
||||
"flagged by our moderation",
|
||||
];
|
||||
|
||||
type Params = {
|
||||
status: number;
|
||||
/**
|
||||
* The provider's own words, already read out of its error body.
|
||||
*/
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the provider's content filter refused the call. The flagged text
|
||||
* is somewhere in the run's transcript (often a page or a tool's output,
|
||||
* not the user's request), so retrying the same transcript is refused the
|
||||
* same way: job 698 lost 41 turns to it. A refusal is a 4xx; a filter that
|
||||
* is down ("content safety screening is temporarily unavailable", a 503) is
|
||||
* an outage, and stays retryable.
|
||||
*/
|
||||
export default function isContentFilterError({ status, detail }: Params) {
|
||||
if (status < 400 || status >= 500) return false;
|
||||
|
||||
const text = (detail || "").toLowerCase();
|
||||
|
||||
return ContentFilterPhrases.some((phrase) => text.includes(phrase));
|
||||
}
|
||||
@@ -187,4 +187,32 @@ describe("toHarnessError", () => {
|
||||
expect(error.fatal).toBe(false);
|
||||
expect(error.message).not.toContain("Settings > Models");
|
||||
});
|
||||
|
||||
test("a provider's content filter refusing the run is fatal and says so (job 698)", () => {
|
||||
const error = toHarnessError({
|
||||
status: 400,
|
||||
body: JSON.stringify({
|
||||
error: { code: "data_inspection_failed", message: "Input text data may contain inappropriate content." },
|
||||
}),
|
||||
provider_name: "Alibaba Cloud Token Plan",
|
||||
url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions",
|
||||
});
|
||||
|
||||
expect(error.fatal).toBe(true);
|
||||
expect(error.retryable).toBe(false);
|
||||
expect(error.message).toContain("Input text data may contain inappropriate content.");
|
||||
expect(error.message).toContain("content filter refused this run");
|
||||
expect(error.message).toContain("not necessarily your message");
|
||||
});
|
||||
|
||||
test("a content filter that is down is an outage, never a refusal", () => {
|
||||
const error = toHarnessError({
|
||||
status: 503,
|
||||
body: JSON.stringify({ error: { message: "content safety screening is temporarily unavailable" } }),
|
||||
provider_name: "Nvidia Cloud",
|
||||
});
|
||||
|
||||
expect(error.fatal).toBe(false);
|
||||
expect(error.retryable).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import HarnessError from "../harness-error";
|
||||
import isContextOverflowError from "./is-context-overflow-error";
|
||||
import isContentFilterError from "./is-content-filter-error";
|
||||
import parseRetryAt from "./parse-retry-at";
|
||||
import redactProviderError from "./redact-provider-error";
|
||||
|
||||
@@ -66,17 +67,26 @@ export default function toHarnessError({
|
||||
*/
|
||||
const overflow = isContextOverflowError({ status, detail: provider_detail });
|
||||
|
||||
/**
|
||||
* The provider's content filter refused something in the transcript:
|
||||
* the same transcript is refused again on every retry, so the run stops
|
||||
* here and says plainly that it was the provider's filter (job 698).
|
||||
*/
|
||||
const filtered = !overflow && isContentFilterError({ status, detail: provider_detail });
|
||||
|
||||
const advice = overflow
|
||||
? "\nSet this model's context window under Settings > Models: a model with none declared is assumed to have 1,000,000."
|
||||
: "";
|
||||
: filtered
|
||||
? `\n${provider_name}'s content filter refused this run: something in the conversation or what its tools read was flagged, not necessarily your message. Run it again with a narrower request, or use a model from another provider under Settings > Models.`
|
||||
: "";
|
||||
|
||||
const retryable = [408, 409, 425, 429].includes(status) || status >= 500;
|
||||
const retryable = !filtered && ([408, 409, 425, 429].includes(status) || status >= 500);
|
||||
|
||||
return new HarnessError({
|
||||
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow ? 320 : 400)}${advice}`,
|
||||
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow || filtered ? 320 : 400)}${advice}`,
|
||||
status,
|
||||
retryable,
|
||||
fatal: overflow,
|
||||
fatal: overflow || filtered,
|
||||
retry_at: retryable && headers ? parseRetryAt({ headers }) : undefined,
|
||||
provider_wide: status == 401 || status == 402,
|
||||
candidate_key,
|
||||
|
||||
@@ -2311,6 +2311,55 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(result.text).toBe("");
|
||||
});
|
||||
|
||||
/**
|
||||
* Job 694: the first turn wrote the message beside an `ask_user` whose
|
||||
* options were objects, the second passed the questions as a string,
|
||||
* and the third put the card up with no text. The model was told
|
||||
* send_reply had failed (it was never called), the message from turn
|
||||
* one was lost, and the run failed with the card finally up.
|
||||
*/
|
||||
test("a refused card is blamed on the card, keeps its message, and the run gets to close once it goes up", async () => {
|
||||
let card_calls = 0;
|
||||
const pickyAsk: HarnessTool<{ options: string[] }> = {
|
||||
name: "ask_user",
|
||||
description: "Asks the user.",
|
||||
schema: z.object({ options: z.array(z.string()) }),
|
||||
run: async () => {
|
||||
card_calls++;
|
||||
return "Asked. The card is on your message.";
|
||||
},
|
||||
};
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Two decisions before I generate.",
|
||||
tool_calls: [{ id: "a1", name: "ask_user", arguments: `{"options":[{"label":"Crop"},{"label":"Keep"}]}` }],
|
||||
},
|
||||
{ tool_calls: [{ id: "a2", name: "ask_user", arguments: `{"options":"[\\"Crop\\",\\"Keep\\"]"}` }] },
|
||||
{ tool_calls: [{ id: "a3", name: "ask_user", arguments: `{"options":["Crop","Keep"]}` }] },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Harden the prompt." }],
|
||||
tools: [sendReply, pickyAsk],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
const told = seen[1]!.messages.at(-1)!.content as string;
|
||||
|
||||
expect(told).not.toBe(replyClosingFailedNote);
|
||||
expect(told).toContain("The card was not put up");
|
||||
expect(told).toContain("ask_user");
|
||||
expect(card_calls).toBe(1);
|
||||
expect(seen).toHaveLength(4);
|
||||
expect(result.review_note).toBeUndefined();
|
||||
expect(result.text).toBe("Two decisions before I generate.");
|
||||
});
|
||||
|
||||
test("send_reply with no message beside it is told once", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
repairedAnswerNote,
|
||||
repeatedAnswerNote,
|
||||
replyCardFailedNote,
|
||||
replyCardOnlyFailedNote,
|
||||
replyClosingFailedNote,
|
||||
replyClosingMixedNote,
|
||||
replyClosingRequiredNote,
|
||||
@@ -669,6 +670,20 @@ export default async function runTextLoop({
|
||||
* nothing left to say.
|
||||
*/
|
||||
let card_text = "";
|
||||
/**
|
||||
* The message a turn wrote beside a card the tool refused. It isn't the
|
||||
* reply yet (it points at a card no one can see), but it is the sentence
|
||||
* the card belongs under: once a later turn puts the card up, it becomes
|
||||
* `card_text`. Job 694 wrote it on its first turn, fixed the card's
|
||||
* arguments twice, and then had nothing left to send.
|
||||
*/
|
||||
let failed_card_text = "";
|
||||
/**
|
||||
* A card call was refused earlier in this run. When the card then goes
|
||||
* up, the run has made progress, so it gets one more turn for
|
||||
* `send_reply` instead of failing on the retries the refusals used up.
|
||||
*/
|
||||
let card_refused = false;
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
@@ -1280,6 +1295,7 @@ export default async function runTextLoop({
|
||||
*/
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
failed_card_text = "";
|
||||
told_closing_text = false;
|
||||
continue;
|
||||
}
|
||||
@@ -1512,12 +1528,19 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const send_reply_failed = failed_closing.some((use) => use.name === SendReplyToolName);
|
||||
const failed_cards = failed_closing.filter((use) => use.name !== SendReplyToolName).map((use) => use.name);
|
||||
const closing_failed_note =
|
||||
send_reply_failed || !called_send_reply
|
||||
? called_send_reply || require_closing_answer
|
||||
? replyClosingFailedNote
|
||||
: closingFailedNote
|
||||
: replyCardFailedNote({ tools: failed_cards });
|
||||
/**
|
||||
* A card refused in a turn with no `send_reply` is the card's
|
||||
* failure, not the send's: telling the model "send_reply did not go
|
||||
* through" there hid the schema error it had to fix (job 694, three
|
||||
* turns on `ask_user`'s options).
|
||||
*/
|
||||
const closing_failed_note = send_reply_failed
|
||||
? replyClosingFailedNote
|
||||
: called_send_reply
|
||||
? replyCardFailedNote({ tools: failed_cards })
|
||||
: require_closing_answer
|
||||
? replyCardOnlyFailedNote({ tools: failed_cards })
|
||||
: closingFailedNote;
|
||||
const closing_worked = closing && !closing_failed && closing_required;
|
||||
/**
|
||||
* The message this turn wrote beside the call. An earlier draft is
|
||||
@@ -1545,6 +1568,35 @@ export default async function runTextLoop({
|
||||
* and pairing it with "Which date rule?" put "I checked the date
|
||||
* rules." under it.
|
||||
*/
|
||||
const card_went_up = asked_something && closing && !closing_failed;
|
||||
|
||||
/**
|
||||
* A refused card keeps the message written beside it for the turn
|
||||
* that puts the card up; a turn that drops the card (no card call)
|
||||
* never gets it, since it pointed at a card that isn't there.
|
||||
*/
|
||||
if (asked_something && closing_failed && written_text) {
|
||||
failed_card_text = written_text;
|
||||
}
|
||||
|
||||
if (card_went_up && !written_text && !card_text.trim() && failed_card_text.trim()) {
|
||||
card_text = failed_card_text;
|
||||
}
|
||||
|
||||
if (card_went_up) failed_card_text = "";
|
||||
|
||||
/**
|
||||
* The card is up after refusals spent the retries: one more turn for
|
||||
* `send_reply`, since the run made the progress the bound is there to
|
||||
* demand (job 694 put its card up on the third try and then failed).
|
||||
*/
|
||||
if (card_went_up && card_refused && !called_send_reply) {
|
||||
closing_retries = Math.min(closing_retries, AppData.MaxClosingRetries - 1);
|
||||
card_refused = false;
|
||||
}
|
||||
|
||||
if (asked_something && closing_failed) card_refused = true;
|
||||
|
||||
const carry_card = Boolean(card_text.trim()) && !unfinishedAnswerText({ text: card_text });
|
||||
const carry_draft =
|
||||
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
|
||||
@@ -1729,6 +1781,7 @@ export default async function runTextLoop({
|
||||
*/
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
failed_card_text = "";
|
||||
told_closing_text = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,11 @@ import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
|
||||
import saveBotPlanSteps from "@/src/functions/backend/db/bot-plans/save-bot-plan-steps";
|
||||
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
|
||||
import {
|
||||
BotPlanGoalSchema,
|
||||
BotPlanStepTextsSchema,
|
||||
BotPlanTitleSchema,
|
||||
} from "@/src/schemas/bot-plan-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import botPlanRef from "@/src/utils/bot-plan-ref";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
@@ -37,29 +41,50 @@ type Args = {
|
||||
* paused, because pausing was not a thing it could do). Approval and
|
||||
* ending stay on the card.
|
||||
*/
|
||||
export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }: Params): HarnessTool<Args> {
|
||||
export default function updatePlanTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
onPlan,
|
||||
}: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "update_plan",
|
||||
description: `Change the plan you're working: rewrite its steps when what you found makes the rest of it wrong (send the whole list, in order, the steps already done first and unchanged: their notes are what was worked), or set its status to "paused" or "active" when the user asked to park the plan or pick it back up. Say in your reply what changed and why, in a line. Don't use it to make the plan look finished, and don't pause or resume on your own judgement: only when the message asked.`,
|
||||
schema: z.object({
|
||||
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
|
||||
steps: BotPlanStepTextsSchema.optional().describe(`The plan's steps as they should now read, done ones first and unchanged`),
|
||||
title: BotPlanTitleSchema.optional().describe(`A new title, only when the work turned out to be something else`),
|
||||
goal: BotPlanGoalSchema.optional().describe(`A new goal, only when what "done" means has changed`),
|
||||
plan_id: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe(`The plan's id, as your prompt gives it`),
|
||||
steps: BotPlanStepTextsSchema.optional().describe(
|
||||
`The plan's steps as they should now read, done ones first and unchanged`,
|
||||
),
|
||||
title: BotPlanTitleSchema.optional().describe(
|
||||
`A new title, only when the work turned out to be something else`,
|
||||
),
|
||||
goal: BotPlanGoalSchema.optional().describe(
|
||||
`A new goal, only when what "done" means has changed`,
|
||||
),
|
||||
status: z
|
||||
.enum(["paused", "active"])
|
||||
.optional()
|
||||
.describe(`"paused" parks a running plan where it stands, "active" picks a paused one back up: only when the user asked`),
|
||||
.describe(
|
||||
`"paused" parks a running plan where it stands, "active" picks a paused one back up: only when the user asked`,
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (!args.steps && !args.status) {
|
||||
throw new AppError(`Send the new steps or a status to set: update_plan changes one of them.`);
|
||||
throw new AppError(
|
||||
`Send the new steps or a status to set: update_plan changes one of them.`,
|
||||
);
|
||||
}
|
||||
|
||||
const row = await grabBotPlan({ plan_id: args.plan_id });
|
||||
|
||||
if (Number(row.session_id) != Number(session_id)) {
|
||||
throw new AppError(`Plan #${args.plan_id} belongs to another conversation: change that conversation's plan.`);
|
||||
throw new AppError(
|
||||
`Plan #${args.plan_id} belongs to another conversation: change that conversation's plan.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.steps) {
|
||||
@@ -81,8 +106,14 @@ export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }:
|
||||
);
|
||||
}
|
||||
|
||||
const result = await setBotPlanStatus({ plan_id: args.plan_id, user_id, status: args.status });
|
||||
const at = currentPlanStepIndex({ steps: parseBotPlanSteps({ text: result.row.steps }) });
|
||||
const result = await setBotPlanStatus({
|
||||
plan_id: args.plan_id,
|
||||
user_id,
|
||||
status: args.status,
|
||||
});
|
||||
const at = currentPlanStepIndex({
|
||||
steps: parseBotPlanSteps({ text: result.row.steps }),
|
||||
});
|
||||
|
||||
moved =
|
||||
args.status == "paused"
|
||||
@@ -93,7 +124,10 @@ export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }:
|
||||
onPlan({ ref: botPlanRef({ plan_id: args.plan_id }) });
|
||||
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
|
||||
|
||||
return moved || `Plan #${args.plan_id} is updated and its card shows the new steps. Say in a line what changed and why, then carry on with the step you're on.`;
|
||||
return (
|
||||
moved ||
|
||||
`Plan #${args.plan_id} is updated and its card shows the new steps. Say in a line what changed and why, then carry on with the step you're on.`
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -29,6 +29,11 @@ type Params = {
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
work: BotTaskWork;
|
||||
/**
|
||||
* The run queuing the work. A task run handing its work on is itself an
|
||||
* open run on that computer, and was refused against its own job.
|
||||
*/
|
||||
job_id?: number | string;
|
||||
/**
|
||||
* The tool that asked, so a refusal tells the model to call that tool
|
||||
* again rather than one it no longer has.
|
||||
@@ -54,9 +59,10 @@ export default async function queueBotTask({
|
||||
run_kind,
|
||||
plan_id,
|
||||
work,
|
||||
job_id: asking_job_id,
|
||||
tool_name,
|
||||
}: Params): Promise<{ job_id: number; ahead: number; ask_id?: number }> {
|
||||
const same = await grabOpenBotTask({ bot_id, session_id, title: work.title });
|
||||
const same = await grabOpenBotTask({ bot_id, session_id, title: work.title, exclude_job_id: asking_job_id });
|
||||
|
||||
if (same) {
|
||||
throw new Error(
|
||||
@@ -66,7 +72,7 @@ export default async function queueBotTask({
|
||||
|
||||
const computer_id = work.computer_id ?? computers[0]?.id ?? undefined;
|
||||
|
||||
const open = work.separate ? null : await grabOpenBotTask({ bot_id, session_id, computer_id });
|
||||
const open = work.separate ? null : await grabOpenBotTask({ bot_id, session_id, computer_id, exclude_job_id: asking_job_id });
|
||||
|
||||
if (open) {
|
||||
throw new Error(
|
||||
|
||||
@@ -21,8 +21,13 @@ mock.module("@/src/functions/backend/db/bots-queue/enqueue-bot-job", () => ({
|
||||
return next_job_id++;
|
||||
},
|
||||
}));
|
||||
const open_task_calls: Array<{ exclude_job_id?: number | string | null }> = [];
|
||||
|
||||
mock.module("@/src/functions/backend/db/bots-queue/grab-open-bot-task", () => ({
|
||||
default: async () => null,
|
||||
default: async (params: { exclude_job_id?: number | string | null }) => {
|
||||
open_task_calls.push(params);
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/asks/grab-open-ask-by-session", () => ({
|
||||
default: async () => null,
|
||||
@@ -84,6 +89,18 @@ describe("sendReplyTool", () => {
|
||||
expect(result).toContain("Your message beside this call goes out with it");
|
||||
});
|
||||
|
||||
test("a task report handing work on leaves its own job out of the open-run checks (jobs 680, 700)", async () => {
|
||||
open_task_calls.length = 0;
|
||||
|
||||
await tool({ job_id: 680 }).run({
|
||||
args: { status: "working", work: { title: "Finish the composite", instructions: "Place the layers." } },
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(open_task_calls.length).toBeGreaterThan(0);
|
||||
expect(open_task_calls.every((call) => call.exclude_job_id === 680)).toBe(true);
|
||||
});
|
||||
|
||||
test("queues the work once even if the call runs again", async () => {
|
||||
const reply = tool();
|
||||
const args = {
|
||||
|
||||
@@ -156,6 +156,7 @@ export default function sendReplyTool({
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
job_id,
|
||||
tool_name: "send_reply",
|
||||
work: args.work,
|
||||
});
|
||||
|
||||
@@ -30,6 +30,11 @@ type Params = {
|
||||
* the child run's report ends on the card that moves the plan on.
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
/**
|
||||
* The task run handing work on, so its own open job is not the run the
|
||||
* new one is refused against.
|
||||
*/
|
||||
job_id?: number | string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -65,6 +70,7 @@ export default function startTaskTool({
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
job_id: asking_job_id,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const listed = computers
|
||||
.map((computer) => `${computer.id} (${computer.name || computer.kind})`)
|
||||
@@ -104,6 +110,7 @@ export default function startTaskTool({
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
job_id: asking_job_id,
|
||||
tool_name: "start_task",
|
||||
work: {
|
||||
title: args.title,
|
||||
|
||||
@@ -16,6 +16,12 @@ import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import rerunReplyProblem from "@/src/utils/rerun-reply-problem";
|
||||
import retryReplyProblem from "@/src/utils/retry-reply-problem";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
|
||||
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
|
||||
import enqueuePlanStep from "@/src/functions/backend/db/bot-plans/enqueue-plan-step";
|
||||
import planStepRetryTarget from "@/src/utils/plan-step-retry-target";
|
||||
|
||||
/**
|
||||
* Runs the bot's last reply again, queues a failed reply after its failure
|
||||
@@ -52,8 +58,8 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, b
|
||||
const message = await grabUserBotMessage({ user_id: user.id, message_id });
|
||||
|
||||
const job = (
|
||||
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "id" | "kind">>({
|
||||
sql: `SELECT id, kind FROM bots_queue WHERE id = ? LIMIT 1`,
|
||||
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "id" | "kind" | "params" | "session_id">>({
|
||||
sql: `SELECT id, kind, params, session_id FROM bots_queue WHERE id = ? LIMIT 1`,
|
||||
values: [message.failed_job_id || 0],
|
||||
})
|
||||
).payload?.[0];
|
||||
@@ -146,7 +152,30 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, b
|
||||
throw new AppError(problem);
|
||||
}
|
||||
|
||||
await enqueueBotReply({
|
||||
/**
|
||||
* A failed plan step paused its plan, and an ordinary reply can't
|
||||
* tick a paused plan's step: it is retried as that step, with the
|
||||
* plan running again, so the retry can finish what the plan holds.
|
||||
*/
|
||||
const plan_id = Number(parseJobJson({ text: job?.params })?.plan_id) || 0;
|
||||
const plan = plan_id ? await grabBotPlan({ plan_id }).catch(() => null) : null;
|
||||
const retry_step = planStepRetryTarget({
|
||||
plan_id,
|
||||
job_session_id: Number(message.session_id),
|
||||
plan: plan ? { session_id: plan.session_id, status: plan.status } : null,
|
||||
});
|
||||
|
||||
let step_job: number | null = null;
|
||||
|
||||
if (retry_step && plan) {
|
||||
const { row, started } = await setBotPlanStatus({ plan_id, user_id: user.id, status: "active" });
|
||||
|
||||
await pushBotPlan({ plan_id: row.id, session_id: row.session_id, bot_id: row.bot_id });
|
||||
|
||||
step_job = started ? await enqueuePlanStep({ plan_id: row.id }) : null;
|
||||
}
|
||||
|
||||
if (!step_job) await enqueueBotReply({
|
||||
user_id: user.id,
|
||||
bot_id: Number(message.bot_id),
|
||||
session_id: Number(message.session_id),
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { BotQuestionItemsSchema } from "./bot-question-schema";
|
||||
|
||||
const question = { question: "How should the prompt handle the legs?", kind: "single" };
|
||||
|
||||
describe("BotQuestionItemsSchema", () => {
|
||||
test("takes options as plain strings", () => {
|
||||
const parsed = BotQuestionItemsSchema.parse([{ ...question, options: ["Crop them", "Keep them"] }]);
|
||||
|
||||
expect(parsed[0]!.options).toEqual(["Crop them", "Keep them"]);
|
||||
});
|
||||
|
||||
test("reads an option written as an object by its label (job 694, first try)", () => {
|
||||
const parsed = BotQuestionItemsSchema.parse([
|
||||
{
|
||||
...question,
|
||||
options: [
|
||||
{ label: "Crop them", description: "Removes the contradiction." },
|
||||
{ text: "Keep them" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(parsed[0]!.options).toEqual(["Crop them", "Keep them"]);
|
||||
});
|
||||
|
||||
test("reads questions passed as a JSON string of the array (job 694, second try)", () => {
|
||||
const text = `\n${JSON.stringify([{ ...question, options: ["Crop them", "Keep them"] }])}\n`;
|
||||
|
||||
expect(BotQuestionItemsSchema.parse(text)[0]!.options).toEqual(["Crop them", "Keep them"]);
|
||||
});
|
||||
|
||||
test("still refuses what it can't read", () => {
|
||||
expect(BotQuestionItemsSchema.safeParse("not json").success).toBe(false);
|
||||
expect(BotQuestionItemsSchema.safeParse([{ ...question, options: [{ description: "no label" }, "Keep"] }]).success).toBe(false);
|
||||
expect(BotQuestionItemsSchema.safeParse([{ ...question, options: ["Same", "same"] }]).success).toBe(false);
|
||||
});
|
||||
|
||||
test("the model is still shown options as plain strings", () => {
|
||||
const schema = z.toJSONSchema(z.object({ questions: BotQuestionItemsSchema }), { target: "draft-7", io: "input" }) as {
|
||||
properties: { questions: { type: string; items: { properties: { options: { items: { type: string } } } } } };
|
||||
};
|
||||
|
||||
expect(schema.properties.questions.type).toBe("array");
|
||||
expect(schema.properties.questions.items.properties.options.items.type).toBe("string");
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,36 @@ import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotQuestionKinds } from "@/src/dict/bot-question-dict";
|
||||
|
||||
/**
|
||||
* An option written as `{ label, description }` (or `text`/`value`), the
|
||||
* shape models reach for, is its label. Refused as "expected string", the
|
||||
* card took job 694 three turns to put up.
|
||||
*/
|
||||
function optionLabel(value: unknown) {
|
||||
if (!value || typeof value != "object" || Array.isArray(value)) return value;
|
||||
|
||||
const option = value as Record<string, unknown>;
|
||||
const label = option.label ?? option.text ?? option.value;
|
||||
|
||||
return typeof label == "string" ? label : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Questions passed as a JSON string of the array (job 694's second try) are
|
||||
* read as that array. Anything else is left for the schema to refuse.
|
||||
*/
|
||||
function questionsArray(value: unknown) {
|
||||
if (typeof value != "string") return value;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value.trim());
|
||||
|
||||
return Array.isArray(parsed) ? parsed : value;
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One question as a bot writes it (`ask_user`) and as it's stored.
|
||||
*/
|
||||
@@ -10,22 +40,28 @@ export const BotQuestionItemSchema = z.object({
|
||||
kind: z
|
||||
.enum(BotQuestionKinds)
|
||||
.describe("single: the user picks exactly one option (radios). multiple: any number, at least one (checkboxes)."),
|
||||
options: z
|
||||
.array(z.string().trim().min(1).max(200))
|
||||
.min(2, "Give at least two options")
|
||||
.max(AppData.BotQuestionMaxOptions, `Give at most ${AppData.BotQuestionMaxOptions} options`)
|
||||
.refine((options) => new Set(options.map((option) => option.toLowerCase())).size == options.length, "Options must differ")
|
||||
.describe("The answers to choose from, each short and distinct"),
|
||||
options: z.preprocess(
|
||||
(value) => (Array.isArray(value) ? value.map(optionLabel) : value),
|
||||
z
|
||||
.array(z.string().trim().min(1).max(200))
|
||||
.min(2, "Give at least two options")
|
||||
.max(AppData.BotQuestionMaxOptions, `Give at most ${AppData.BotQuestionMaxOptions} options`)
|
||||
.refine((options) => new Set(options.map((option) => option.toLowerCase())).size == options.length, "Options must differ")
|
||||
.describe("The answers to choose from, each a plain string, short and distinct"),
|
||||
),
|
||||
allow_other: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("Let the user type an answer of their own besides the options. Set it unless the options cover every case."),
|
||||
});
|
||||
|
||||
export const BotQuestionItemsSchema = z
|
||||
.array(BotQuestionItemSchema)
|
||||
.min(1, "Ask at least one question")
|
||||
.max(AppData.BotQuestionMaxQuestions, `Ask at most ${AppData.BotQuestionMaxQuestions} questions at once`);
|
||||
export const BotQuestionItemsSchema = z.preprocess(
|
||||
questionsArray,
|
||||
z
|
||||
.array(BotQuestionItemSchema)
|
||||
.min(1, "Ask at least one question")
|
||||
.max(AppData.BotQuestionMaxQuestions, `Ask at most ${AppData.BotQuestionMaxQuestions} questions at once`),
|
||||
);
|
||||
|
||||
export const BotQuestionIdSchema = z.object({
|
||||
question_id: z.coerce.number().int().positive("Pick the questions"),
|
||||
|
||||
@@ -71,6 +71,12 @@ describe("claimsWorkUnderWay", () => {
|
||||
"I'm starting to think the brief is wrong.",
|
||||
"I started the invoice last week.",
|
||||
"Task #48 is doing, nothing is running yet.",
|
||||
/**
|
||||
* Job 809's plan report: status lines about a hand-over made
|
||||
* days before, refused twice as work claimed under way.
|
||||
*/
|
||||
"- **#5 Technical quick wins** - handed to [bot:6] (PR #10 open, 7 of 9 items implemented)",
|
||||
"- Task #5: Handed to [bot:6] (PR #10 open, 7/9 items implemented)",
|
||||
]) {
|
||||
expect(claimsWorkUnderWay({ text })).toBe(false);
|
||||
}
|
||||
|
||||
@@ -31,9 +31,12 @@ const UnderWayPatterns = [
|
||||
/**
|
||||
* "What I sent @SEO Expert", "I've passed the brief on to [bot:6]": a
|
||||
* request claimed as made. Only `ask_bot` makes one, so the app's
|
||||
* record decides whether it's true.
|
||||
* record decides whether it's true. Only the bot's own claim counts
|
||||
* ("I sent", "I've passed"): a status line such as "#5 - handed to
|
||||
* [bot:6] (PR #10 open)" reports a hand-over made days before, and
|
||||
* faulting it refused an honest plan report twice (job 809).
|
||||
*/
|
||||
/\b(?:sent|passed|forwarded|handed)\b[^.!?\n]{0,80}(?:@[a-z0-9_-]+|\[bot:\d+\])/i,
|
||||
/\bI(?:(?:'|’)ve)?\s+(?:just\s+|now\s+|already\s+)?(?:sent|passed|forwarded|handed)\b[^.!?\n]{0,80}(?:@[a-z0-9_-]+|\[bot:\d+\])/i,
|
||||
/**
|
||||
* "I'm starting the hydration work on computer 1", "I've kicked off
|
||||
* the run": a run claimed as started, without the "now" or the
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import planStepRetryTarget from "./plan-step-retry-target";
|
||||
|
||||
describe("planStepRetryTarget", () => {
|
||||
test("a failed step of a plan its failure paused is retried as that step (Plan #2)", () => {
|
||||
expect(planStepRetryTarget({ plan_id: 2, job_session_id: 102, plan: { session_id: 102, status: "paused" } })).toBe(true);
|
||||
});
|
||||
|
||||
test("a reply that was not a plan step is retried as a reply", () => {
|
||||
expect(planStepRetryTarget({ plan_id: 0, job_session_id: 102, plan: null })).toBe(false);
|
||||
});
|
||||
|
||||
test("a plan the user ended or resumed meanwhile is left alone", () => {
|
||||
for (const status of ["cancelled", "done", "active"]) {
|
||||
expect(planStepRetryTarget({ plan_id: 2, job_session_id: 102, plan: { session_id: 102, status } })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("a plan of another conversation is never picked up from here", () => {
|
||||
expect(planStepRetryTarget({ plan_id: 2, job_session_id: 7, plan: { session_id: 102, status: "paused" } })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The failed job's `params.plan_id`, if it was a plan's step.
|
||||
*/
|
||||
plan_id: number;
|
||||
job_session_id: number;
|
||||
plan: { session_id?: number | string | null; status?: string | null } | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether Retry on a failed reply should run it again as its plan's step.
|
||||
* A failed step pauses its plan (`pauseFailedPlanStep`), and an ordinary
|
||||
* reply can't tick a step of a paused plan, so Retry used to answer with a
|
||||
* run that could only fail to finish it, or claim it had (job 810, Plan #2).
|
||||
* Only a plan of the same conversation that is still paused is picked up
|
||||
* again: one the user ended or resumed meanwhile is left as it is.
|
||||
*/
|
||||
export default function planStepRetryTarget({ plan_id, job_session_id, plan }: Params) {
|
||||
if (!plan_id || !plan) return false;
|
||||
|
||||
if (Number(plan.session_id) != job_session_id) return false;
|
||||
|
||||
return plan.status == "paused";
|
||||
}
|
||||
Reference in New Issue
Block a user