Review task reports, and refuse a wrap-up rewrite that still doesn't hold up
A saving wrap up with nothing to hand off named a missing tool. A reply sent back on its last step shipped the rewrite unchecked. Task reports now use the same record check as replies.
This commit is contained in:
@@ -128,7 +128,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`). A plan that can't be written or read starts the run unplanned, never blocks it. **The wrap up is told what is on disk:** a task run passes `Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders (`git status --porcelain` and `git diff --stat` per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it. **The files the brief names are checked once, before the run starts** (`namedFilesNote`, over `namedFiles`): a path that isn't on the computer but is still in the bot's files is handed over as its `[file:ID]` with `export_file`, and one with no copy anywhere says plainly not to go looking through the machine or the user's accounts. It is the app's answer, not the run's guess: a source a rebuild took off the computer once cost a run thirty turns probing the container and then the user's own accounts for a copy the app was holding the whole time.
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`, which shares the line shape with `appRecordLines`). Before a reply goes out, `reviewBotReply` (the loop's `review`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no `start_task`/`delegate_task`/`ask_bot` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the reply job fails instead (`review_note` -> `BotJobFatalError`), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`, which shares the line shape with `appRecordLines`). Before a reply or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no `start_task`/`delegate_task`/`ask_bot` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last; a retry (`params.retry_of`) always runs. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
|
||||
/**
|
||||
* The same record helpers `review-bot-reply.test.ts` stands in for: this
|
||||
* checks that a reply and a task report go through that review, with the
|
||||
* run's own bot, user, session and folders.
|
||||
*/
|
||||
mock.module("@/src/functions/backend/db/bots-queue/has-open-work", () => ({
|
||||
default: async () => false,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-files/grab-bot-file", () => ({
|
||||
default: async () => null,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-files/grab-bot-file-scope", () => ({
|
||||
default: async () => null,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-files/user-reaches-file-scope", () => ({
|
||||
default: async () => false,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/tasks/assert-user-reaches-task", () => ({
|
||||
default: async () => null,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-graphics/grab-bot-graphic", () => ({
|
||||
default: async () => null,
|
||||
}));
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
describe("reviewRunAnswer", () => {
|
||||
test("sends a task report back for a file the user can't open", async () => {
|
||||
const { default: reviewRunAnswer } = await import("./review-run-answer");
|
||||
const review = reviewRunAnswer({ bot_id: 4, user_id: 2, session_id: 9, scopes: [] });
|
||||
|
||||
const note = await review({ text: "Saved it as [file:41].", tool_uses: [] });
|
||||
|
||||
expect(note).toContain("[file:41]");
|
||||
expect(note).toContain("was not sent");
|
||||
});
|
||||
|
||||
test("lets an answer through when the record holds up", async () => {
|
||||
const { default: reviewRunAnswer } = await import("./review-run-answer");
|
||||
const review = reviewRunAnswer({ bot_id: 4, user_id: 2, session_id: 9, scopes: [] });
|
||||
|
||||
expect(await review({ text: "Nothing named, nothing started.", tool_uses: [] })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import reviewBotReply from "./review-bot-reply";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
user_id: number | string;
|
||||
session_id: number | string;
|
||||
scopes: StorageScope[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The check a reply and a task report share, as `runTextLoop`'s `review`:
|
||||
* files, tasks, graphics and work the answer names, against the app's
|
||||
* 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 });
|
||||
}
|
||||
@@ -69,7 +69,7 @@ import jobSessionId from "@/src/functions/backend/db/bots-queue/job-session-id";
|
||||
import withTakeOverRefs from "./with-take-over-refs";
|
||||
import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewBotReply from "./review-bot-reply";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
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";
|
||||
@@ -111,7 +111,7 @@ type Params = BotJobContext & {
|
||||
* The job records the newest one it read (`markReplyAnswered`). Finishes silently when an earlier
|
||||
* reply already read everything (`hasUnansweredMessage`). An answer naming
|
||||
* files or tasks that don't exist, or saying work is under way when none
|
||||
* is, is written again once (`reviewBotReply`).
|
||||
* is, is written again (`reviewRunAnswer`, up to `AppData.HarnessReviewRewrites`).
|
||||
*/
|
||||
export default async function runBotReply({
|
||||
bot,
|
||||
@@ -606,8 +606,7 @@ export default async function runBotReply({
|
||||
* Files, tasks and work the answer names are checked against
|
||||
* the app's record before it goes out.
|
||||
*/
|
||||
review: ({ text, tool_uses }) =>
|
||||
reviewBotReply({ text, tool_uses, bot_id: bot.id!, user_id, session_id, scopes }),
|
||||
review: reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes }),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -78,6 +78,8 @@ import withTakeOverRefs from "./with-take-over-refs";
|
||||
import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import ScheduledRunFailedError from "./scheduled-run-failed-error";
|
||||
import BotJobFatalError from "./bot-job-fatal-error";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
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";
|
||||
import taskIncoming from "./task-incoming";
|
||||
@@ -678,12 +680,36 @@ export default async function runBotTask({
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
/**
|
||||
* The same record a chat reply is checked against: a long run
|
||||
* is where a report names a file or task that isn't there, or
|
||||
* 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 }),
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
prefer_key: planned?.candidate.key,
|
||||
});
|
||||
|
||||
if (failure) {
|
||||
throw new ScheduledRunFailedError(computer ? computer.redact(failure) : failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* An answer the review kept faulting is never sent: the run stops
|
||||
* with why instead (`review_note`), and the job fails saying so.
|
||||
* The same wording a reply uses, so a failure notice reads the same
|
||||
* wherever the claim was written.
|
||||
*/
|
||||
if (result.review_note) {
|
||||
await dropUnsentQuestions({ refs: take_overs });
|
||||
|
||||
throw new BotJobFatalError(`The answer didn't hold up against the app's record, so it wasn't sent.`);
|
||||
}
|
||||
|
||||
const text = stripAppRecords({ text: result.text });
|
||||
|
||||
/**
|
||||
@@ -718,3 +744,18 @@ export default async function runBotTask({
|
||||
await computer?.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Question cards whose report never went out are deleted: their answer
|
||||
* only comes from the card, so a pending row left behind waits forever.
|
||||
* Take-over and secret refs on the same list are left as they are.
|
||||
*/
|
||||
async function dropUnsentQuestions({ refs }: { refs: string[] }) {
|
||||
for (const ref of refs) {
|
||||
const question_id = Number(/\[question:(\d+)\]/.exec(ref)?.[1] || 0);
|
||||
|
||||
if (!question_id) continue;
|
||||
|
||||
await deleteBotQuestion({ question_id }).catch(() => null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import runTextLoop, {
|
||||
RedraftNote,
|
||||
stepsLowNote,
|
||||
stepsLowWarningLeft,
|
||||
wrapUpPrompt,
|
||||
} from "./run-text-loop";
|
||||
|
||||
/**
|
||||
@@ -461,6 +462,20 @@ describe("runTextLoop", () => {
|
||||
|
||||
expect(prompt).toContain("one turn to save what the user needs: write_file");
|
||||
expect(prompt).toContain("call start_task with a complete brief of what's left");
|
||||
expect(prompt).not.toContain("and nothing else");
|
||||
});
|
||||
|
||||
test("a saving wrap up with nothing to hand off names only the save tools", () => {
|
||||
const prompt = wrapUpPrompt({
|
||||
uses: [],
|
||||
saving: ["write_file", "import_file"],
|
||||
hand_off: [],
|
||||
});
|
||||
|
||||
expect(prompt).toContain("write_file and import_file are still yours");
|
||||
expect(prompt).toContain("and nothing else");
|
||||
expect(prompt).not.toContain("call with");
|
||||
expect(prompt).not.toContain("start_task");
|
||||
});
|
||||
|
||||
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
|
||||
@@ -802,6 +817,34 @@ describe("runTextLoop", () => {
|
||||
expect(result.review_note).toBe("Not sent: nothing is running.");
|
||||
});
|
||||
|
||||
test("reviews a rewrite that lands on the wrap up, and refuses it there", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "I'm scanning now. Scan done: 5 contests." },
|
||||
{ text: "Scan done: 5 contests, still going." },
|
||||
]);
|
||||
const reviewed: string[] = [];
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the contests." }],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
review: async ({ text }) => {
|
||||
reviewed.push(text);
|
||||
return "Not sent: nothing is running.";
|
||||
},
|
||||
});
|
||||
|
||||
expect(reviewed).toEqual([
|
||||
"I'm scanning now. Scan done: 5 contests.",
|
||||
"Scan done: 5 contests, still going.",
|
||||
]);
|
||||
expect(seen).toHaveLength(2);
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe("Not sent: nothing is running.");
|
||||
});
|
||||
|
||||
test("a repair that leaves a dead ref behind is checked again, not shipped (M3)", async () => {
|
||||
const faulty = "I'm scanning now. [file:99] has the results.";
|
||||
const { generate } = scripted([
|
||||
|
||||
@@ -82,6 +82,12 @@ type Params = {
|
||||
*/
|
||||
context_budget?: RunLimit;
|
||||
signal?: AbortSignal;
|
||||
/**
|
||||
* The model a plan turn already used (`planBotTask`). Tried first among
|
||||
* the automatic picks, so the run works the plan on the model that
|
||||
* wrote it when that model is still the one to use.
|
||||
*/
|
||||
prefer_key?: string;
|
||||
/**
|
||||
* Called after each model turn, before its tools run. Use it for
|
||||
* progress and checkpoints.
|
||||
@@ -125,7 +131,9 @@ type Params = {
|
||||
* made. A note sends the answer back to be written again with it, up to
|
||||
* `AppData.HarnessReviewRewrites` times; null lets it through. Past that
|
||||
* the answer is never sent and the run returns its note (`review_note`).
|
||||
* Not on the wrap up, and a check that throws lets the answer through.
|
||||
* A rewrite is checked again even when it lands on the wrap up: that
|
||||
* 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>;
|
||||
/**
|
||||
@@ -231,13 +239,13 @@ const wrapUpToolsPrompt = ({ saving, hand_off }: { saving: string[]; hand_off: s
|
||||
|
||||
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) 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 ? "" : " 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.`
|
||||
: "",
|
||||
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.`
|
||||
: hand_off.length
|
||||
? `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.`
|
||||
: "",
|
||||
`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)
|
||||
@@ -308,6 +316,7 @@ export default async function runTextLoop({
|
||||
max_prompt_tokens,
|
||||
context_budget,
|
||||
signal = new AbortController().signal,
|
||||
prefer_key: planned_key,
|
||||
onStep,
|
||||
trace,
|
||||
incoming,
|
||||
@@ -405,13 +414,21 @@ export default async function runTextLoop({
|
||||
const step_ceiling = isUnlimitedLimit(max_steps) ? Infinity : max_steps;
|
||||
|
||||
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
|
||||
let prefer_key: string | undefined;
|
||||
let prefer_key = planned_key;
|
||||
/**
|
||||
* How many answers the review has sent back, and the last one it faulted,
|
||||
* whitespace collapsed, to see a model that wrote the same message back.
|
||||
*/
|
||||
let review_rewrites = 0;
|
||||
let faulted_answer: string | null = null;
|
||||
/**
|
||||
* The previous answer was sent back, so this turn exists to rewrite it.
|
||||
* Checked again even on the wrap up: that turn would otherwise return
|
||||
* the rewrite unchecked, and a claim the app already faulted would go
|
||||
* out. Cleared once the rewrite has been read, so the wrap up is not
|
||||
* an open-ended review loop.
|
||||
*/
|
||||
let review_pending = false;
|
||||
/**
|
||||
* A run that wrote a message and then called a tool has been told, once,
|
||||
* that the message never went out (`answerNotSentNote`).
|
||||
@@ -499,7 +516,20 @@ export default async function runTextLoop({
|
||||
* next rewrite on a copy. Past that the run stops: an answer the app
|
||||
* knows is wrong is never sent (`review_note`).
|
||||
*/
|
||||
const checkAnswer = async ({ text, index }: { text: string; index: number }) => {
|
||||
const checkAnswer = async ({
|
||||
text,
|
||||
index,
|
||||
final = false,
|
||||
}: {
|
||||
text: string;
|
||||
index: number;
|
||||
/**
|
||||
* The wrap up, or a turn that must not be written again: a fault
|
||||
* refuses the answer here. A rewrite the review is waiting on is
|
||||
* the run's last look, so it is not sent back into another turn.
|
||||
*/
|
||||
final?: boolean;
|
||||
}) => {
|
||||
if (!review) return { verdict: "passed" as const };
|
||||
|
||||
const note = await review({ text, tool_uses }).catch(async (error) => {
|
||||
@@ -527,9 +557,10 @@ export default async function runTextLoop({
|
||||
faulted_answer = written;
|
||||
review_rewrites += 1;
|
||||
|
||||
if (review_rewrites > AppData.HarnessReviewRewrites) return { verdict: "refused" as const, note };
|
||||
if (final || review_rewrites > AppData.HarnessReviewRewrites) return { verdict: "refused" as const, note };
|
||||
|
||||
pushUserTurn({ transcript, content: repeated ? `${note}\n\n${repeatedAnswerNote}` : note });
|
||||
review_pending = true;
|
||||
|
||||
return { verdict: "sent_back" as const };
|
||||
};
|
||||
@@ -716,10 +747,13 @@ export default async function runTextLoop({
|
||||
/**
|
||||
* An answer the user wrote past is drafted again. Not on the wrap
|
||||
* up: the run is out of steps, and a later reply picks them up.
|
||||
* A rewrite the review is still waiting on is checked first: taking
|
||||
* in a new message here would skip the check the send-back exists for.
|
||||
*/
|
||||
if (
|
||||
!tool_calls.length &&
|
||||
!wrap_up &&
|
||||
!review_pending &&
|
||||
(await takeIncoming({ note: incoming_notes?.redraft || RedraftNote, index }))
|
||||
) {
|
||||
await traced({
|
||||
@@ -731,8 +765,10 @@ export default async function runTextLoop({
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!tool_calls.length && !wrap_up) {
|
||||
const check = await checkAnswer({ text: answer.text || "", index });
|
||||
if (!tool_calls.length && (!wrap_up || review_pending)) {
|
||||
review_pending = false;
|
||||
|
||||
const check = await checkAnswer({ text: answer.text || "", index, final: wrap_up });
|
||||
|
||||
if (check.verdict === "refused") {
|
||||
/**
|
||||
@@ -750,7 +786,7 @@ export default async function runTextLoop({
|
||||
* (M3). So the repaired text is checked again, and goes
|
||||
* out only once the app's record supports all of it.
|
||||
*/
|
||||
const recheck = await checkAnswer({ text: repaired.text, index });
|
||||
const recheck = await checkAnswer({ text: repaired.text, index, final: wrap_up });
|
||||
|
||||
if (recheck.verdict === "passed") {
|
||||
await traced({
|
||||
@@ -783,6 +819,24 @@ export default async function runTextLoop({
|
||||
}
|
||||
|
||||
if (check.verdict === "sent_back") continue;
|
||||
|
||||
/**
|
||||
* A wrap-up rewrite the review let through is the answer. The
|
||||
* turn below is the ordinary wrap up, which a pending review
|
||||
* must not fall into and be checked a second time.
|
||||
*/
|
||||
if (wrap_up) {
|
||||
const said = (answer.text || "").trim();
|
||||
|
||||
return {
|
||||
text: said || `I ran out of steps before I could finish.`,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!tool_calls.length) {
|
||||
|
||||
Reference in New Issue
Block a user