Let follow-up cards share the send_reply turn
A bare send_reply was shipping the previous draft and ending the run, so suggest_next_steps never got a turn. The closing turn now carries the message and its cards, and a cut-off draft is sent back instead of sent.
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: `queueBotTask` (a reply's `send_reply` work, or `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 reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees, though a message written in the turn just before is taken as the one beside `send_reply` when it carries none (models that think the text travels with the call wrote the answer there), and a run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A finished draft is carried only after that one reminder still gets no text (`draft_carried`); a draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **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 task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), 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 run this reply started 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`).
|
||||
- **A reply's `send_reply` work and `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). `queueBotTask` 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 (`send_reply`'s work, `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.
|
||||
|
||||
@@ -507,13 +507,13 @@ export const closingNoTextNote = `The card you just put up has no message beside
|
||||
* never queued. Bounded by `AppData.HarnessReplyDraftsMax`, then the run
|
||||
* fails honestly rather than sending it.
|
||||
*/
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write it again beside send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. The text beside the call is what the user reads.`;
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. A call with no text beside it sends nothing, and an earlier draft is not filled in for you. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` worked but the turn said nothing beside it: the
|
||||
* user would get an empty line, and the status alone is not a message.
|
||||
*/
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so the user would get an empty line. Write the message beside send_reply now and call it again: status "done", "working" (with work, or after a run you started) or "blocked".`;
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. An earlier draft is not the message: write the whole message again beside send_reply and call it again, status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
|
||||
|
||||
/**
|
||||
* Told when a turn tried to end without `send_reply` at all: a card alone or
|
||||
@@ -527,7 +527,7 @@ export const replyClosingRequiredNote = `That turn ended without send_reply, so
|
||||
* can send the message, since the other calls' results go into the
|
||||
* conversation after it.
|
||||
*/
|
||||
export const replyClosingMixedNote = `send_reply has to be the only call in its turn: this turn also did other work, so the message was not sent. Call send_reply on its own with the message beside it, after the tools you still need have run.`;
|
||||
export const replyClosingMixedNote = `send_reply's turn can also call suggest_next_steps or ask_user, and nothing else: this turn did other work, so the message was not sent. Finish that work first, then call send_reply with the whole message beside it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` itself refused the turn (status "working" with
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -1933,14 +1933,38 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a message written in the turn before goes out with send_reply", async () => {
|
||||
test("send_reply with no text does not ship the previous draft on the first pass", async () => {
|
||||
/**
|
||||
* A model that writes the answer, then calls send_reply with
|
||||
* nothing beside it, means the sentence it just wrote. Asked to
|
||||
* write it again it wrote nothing, and the run failed with the
|
||||
* answer sitting in the transcript.
|
||||
* The model spent its stop on the draft. The next turn only stamped
|
||||
* send_reply on it, and that draft went out mid-table with no turn
|
||||
* left for a follow-up. The first bare call is told to write the
|
||||
* message again.
|
||||
*/
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
text: "No, I didn't add it anywhere.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Did you add a bot?" }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(3);
|
||||
expect(seen[2]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a finished draft goes out only after the one reminder still gets no text", async () => {
|
||||
const { generate } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
@@ -1956,12 +1980,11 @@ describe("runTextLoop required send_reply", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(seen[1]!.messages.some((message) => message.content === replyNoTextNote)).toBe(false);
|
||||
expect(result.steps).toBe(3);
|
||||
});
|
||||
|
||||
test("the message still goes out when a tool turn comes between it and send_reply", async () => {
|
||||
const { generate } = scripted([
|
||||
test("a tool turn between the draft and send_reply still gets the one reminder", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "No, I didn't add it anywhere." },
|
||||
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"checked"}` }] },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
@@ -1978,23 +2001,129 @@ describe("runTextLoop required send_reply", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("No, I didn't add it anywhere.");
|
||||
expect(result.steps).toBe(3);
|
||||
expect(result.steps).toBe(4);
|
||||
expect(seen[3]!.messages.at(-1)).toMatchObject({ role: "user", content: replyNoTextNote });
|
||||
});
|
||||
|
||||
test("a card is never paired with a message written earlier", async () => {
|
||||
asked.length = 0;
|
||||
test("send_reply and suggest_next_steps in one turn end the run and keep both", async () => {
|
||||
suggested.length = 0;
|
||||
const { generate } = scripted([
|
||||
{ text: "Which date rule?" },
|
||||
{
|
||||
text: "Both repos are scanned. Nothing was pulled in.",
|
||||
tool_calls: [
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "g1", name: "suggest_next_steps", arguments: `{"steps":["Pull email_frameworks.md in full"]}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [suggestNextSteps, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Both repos are scanned. Nothing was pulled in.");
|
||||
expect(result.steps).toBe(1);
|
||||
expect(suggested).toEqual(["Pull email_frameworks.md in full"]);
|
||||
expect(result.tool_uses.map((use) => use.name)).toEqual(["suggest_next_steps", "send_reply"]);
|
||||
});
|
||||
|
||||
test("send_reply beside a research tool is still mixed and unsent", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Scanned.",
|
||||
tool_calls: [
|
||||
{ id: "c1", name: "remember", arguments: `{"note":"scanned"}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Scanned both repos.",
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [remember, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Scanned both repos.");
|
||||
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingMixedNote });
|
||||
});
|
||||
|
||||
test("a table that stops mid-row is sent back once, then goes out finished", async () => {
|
||||
const cut = ["| Skill | Focus |", "| **revops** | Lead routing"].join("\n");
|
||||
const whole = ["| Skill | Focus |", "| **revops** | Lead routing |"].join("\n");
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: cut,
|
||||
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
{
|
||||
text: whole,
|
||||
tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe(whole);
|
||||
expect(result.steps).toBe(2);
|
||||
expect(String(seen[1]!.messages.at(-1)!.content)).toContain("table row");
|
||||
});
|
||||
|
||||
test("a cut-off draft is never carried, even after the reminder", async () => {
|
||||
const cut = ["| Skill | Focus |", "| **revops** | Lead routing"].join("\n");
|
||||
const { generate } = scripted([
|
||||
{ text: cut },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan the repos." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyNoTextNote);
|
||||
});
|
||||
|
||||
test("a card is never paired with a message written earlier", async () => {
|
||||
/**
|
||||
* The first bare send_reply is told to write the message again.
|
||||
* Writing nothing the second time must not fill the card's turn
|
||||
* with the earlier sentence: the card asked something else, and
|
||||
* that sentence is not its answer.
|
||||
*/
|
||||
asked.length = 0;
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "I checked the date rules." },
|
||||
{ tool_calls: [{ id: "s0", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
tool_calls: [
|
||||
{ id: "q2", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
|
||||
],
|
||||
},
|
||||
]);
|
||||
@@ -2010,6 +2139,8 @@ describe("runTextLoop required send_reply", () => {
|
||||
|
||||
expect(result.text).toBe("");
|
||||
expect(result.review_note).toBe(replyNoTextNote);
|
||||
expect(asked).toEqual(["Which date rule?"]);
|
||||
expect(seen[2]!.messages.some((message) => message.content === replyNoTextNote)).toBe(true);
|
||||
});
|
||||
|
||||
test("the wrap up still offers send_reply", async () => {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import sanitizeAnswerText from "@/src/utils/sanitize-answer-text";
|
||||
import repairAnswerText from "@/src/utils/repair-answer-text";
|
||||
import unfinishedAnswerText from "@/src/utils/unfinished-answer-text";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
|
||||
@@ -505,6 +506,12 @@ export default async function runTextLoop({
|
||||
* the sentence that goes with it (`closingNoTextNote`).
|
||||
*/
|
||||
let told_closing_text = false;
|
||||
/**
|
||||
* A message that stopped inside a table, a fence or a bare marker has
|
||||
* been sent back once (`unfinishedAnswerText`). Past that the run
|
||||
* fails rather than shipping the cut-off text.
|
||||
*/
|
||||
let told_unfinished = false;
|
||||
/**
|
||||
* How many turns the run has spent retrying a closing card: a closing
|
||||
* call that failed, or a card put up beside other work. Bounded
|
||||
@@ -519,12 +526,11 @@ export default async function runTextLoop({
|
||||
*/
|
||||
let reply_drafts = 0;
|
||||
/**
|
||||
* The last message a turn wrote with nothing beside it, held for the
|
||||
* run: a model that writes the answer and then calls `send_reply` with
|
||||
* nothing beside it means the sentence it wrote, and dropping it made
|
||||
* the app ask again until the run failed with the answer sitting in the
|
||||
* transcript. Kept across turns, since the call came after another turn
|
||||
* often enough; a card's message is never taken from here.
|
||||
* The last message a turn wrote with nothing beside it. Held so the
|
||||
* note that asks for it again can point at it. It is not the reply:
|
||||
* `send_reply` with no text beside it used to ship this unchanged, and
|
||||
* a scan that stopped mid-table went out as the answer, with no turn
|
||||
* left for the follow-up (session 130, message 874).
|
||||
*/
|
||||
let draft_text = "";
|
||||
/**
|
||||
@@ -1124,6 +1130,13 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const called_card = tool_calls.some((call) => isClosingTool({ name: call.name }));
|
||||
const called_send_reply = tool_calls.some((call) => call.name === SendReplyToolName);
|
||||
/**
|
||||
* A closing turn is `send_reply` plus the cards that belong under
|
||||
* that answer, and nothing else. `ask_user` and `suggest_next_steps`
|
||||
* are closing tools, so they share the turn. A research tool beside
|
||||
* `send_reply` is still mixed: its result arrives after the message,
|
||||
* and the message would describe work the turn had not finished.
|
||||
*/
|
||||
const closing = tool_calls.every((call) => isClosingTool({ name: call.name }));
|
||||
/**
|
||||
* A required closing answer needs `send_reply` itself, not just any
|
||||
@@ -1143,19 +1156,25 @@ export default async function runTextLoop({
|
||||
const closing_failed = closing_uses.some((use) => !use.ok);
|
||||
const closing_worked = closing && !closing_failed && closing_required;
|
||||
/**
|
||||
* The message this turn carries: its own, or the last one a turn
|
||||
* wrote with nothing beside it (`draft_text`). A model that writes
|
||||
* the answer and then calls `send_reply` with no text means that
|
||||
* sentence; asking for it again ended runs whose answer was already
|
||||
* in the transcript. A card is never paired with an older sentence:
|
||||
* "which date rule?" beside a message about something else is worse
|
||||
* than the note that asks for one.
|
||||
* The message this turn wrote beside the call. An earlier draft is
|
||||
* not filled in: the model spent its stop on that draft, and the
|
||||
* next turn only stamped `send_reply` on it, so a cut-off scan went
|
||||
* out with no follow-up. The draft is offered once, after the model
|
||||
* has been told to write it again and still sent nothing, and only
|
||||
* when that draft is a finished message.
|
||||
*/
|
||||
const written_text = (answer.text || "").trim();
|
||||
/**
|
||||
* A card is never paired with an older sentence: the card asked
|
||||
* something, and the draft was about something else. Filling it in
|
||||
* would put "I checked the date rules." under "Which date rule?".
|
||||
*/
|
||||
const asked_something = tool_calls.some(
|
||||
(call) => call.name !== SendReplyToolName && isClosingTool({ name: call.name }),
|
||||
);
|
||||
const message_text = written_text ? answer.text || "" : asked_something ? "" : draft_text;
|
||||
const carry_draft =
|
||||
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
|
||||
const message_text = written_text || (carry_draft ? draft_text : "");
|
||||
|
||||
if (called_card && (closing_failed || !closing || !closing_required)) {
|
||||
/**
|
||||
@@ -1242,19 +1261,41 @@ export default async function runTextLoop({
|
||||
/**
|
||||
* Checked before it goes out, as any reply is: a note comes
|
||||
* back and the answer is written again (the card stays on the
|
||||
* reply, its ref is already recorded). A message held from the
|
||||
* turn before went out with this call, which is what the model
|
||||
* meant by writing it there.
|
||||
* reply, its ref is already recorded). A draft carried after
|
||||
* the one reminder is said so, so the debug view shows why an
|
||||
* earlier turn's text went out.
|
||||
*/
|
||||
if (!written_text && message_text) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "draft_carried",
|
||||
text: "The message was written in an earlier turn, so it went out with this send_reply.",
|
||||
text: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
|
||||
});
|
||||
}
|
||||
|
||||
const unfinished = unfinishedAnswerText({ text: message_text });
|
||||
|
||||
if (unfinished) {
|
||||
if (!told_unfinished && !(wrap_up && !wrap_up_saving)) {
|
||||
told_unfinished = true;
|
||||
draft_text = "";
|
||||
pushUserTurn({ transcript, content: unfinished });
|
||||
await traced({ kind: "event", index, name: "unfinished", text: unfinished });
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: "",
|
||||
review_note: unfinished,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
const final_turn = wrap_up && !wrap_up_saving;
|
||||
const check = await checkAnswer({ text: message_text, index, status: reply_status, final: final_turn });
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ export default function askUserTool({
|
||||
|
||||
return {
|
||||
name: "ask_user",
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Call it in the same turn as send_reply, with the message beside that call: a later turn cannot add the card, because that turn would replace the answer. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
in_task
|
||||
? `. In a task, ask, then stop working on what you asked about and finish your report; the card goes out with it.`
|
||||
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
|
||||
@@ -60,7 +60,7 @@ export default function sendReplyTool({
|
||||
|
||||
return {
|
||||
name: "send_reply",
|
||||
description: `End every reply with this call. The message you wrote in this turn is what the user gets; this call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. A message sent without this call is a draft and never reaches the user. ${
|
||||
description: `End every reply with this call, in the same turn as the message. The text you write beside it is what the user gets; a call with no text sends nothing, and a message from an earlier turn is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
|
||||
computers.length
|
||||
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
|
||||
: `You have no computer, so work that needs one can't run.`
|
||||
|
||||
@@ -28,16 +28,16 @@ type Args = {
|
||||
/**
|
||||
* Offers the user concrete next steps as buttons under the bot's answer.
|
||||
* Clicking one puts it in their input; nothing waits on it, unlike
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It ends
|
||||
* the reply (`ClosingToolNames`): the buttons belong under the answer, and
|
||||
* a run that kept going would replace that answer with a later line.
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It shares
|
||||
* the closing turn with `send_reply` (`ClosingToolNames`): the buttons
|
||||
* belong under that answer, and a later turn would replace it.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
name: "suggest_next_steps",
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and put it up in the same turn as the answer it belongs under. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Call it in the same turn as send_reply, once the work is done, so the buttons belong to the message that turn sends (your best suggestion first). A later turn cannot add them: that turn would replace the answer. This never waits for a response: don't ask the user to pick one, don't put the answers on hold. When their answer decides what you do next, use ask_user in that same turn instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unfinishedAnswerText from "./unfinished-answer-text";
|
||||
|
||||
describe("unfinishedAnswerText", () => {
|
||||
test("a table row that stops after its label is unfinished", () => {
|
||||
const text = ["| Skill | Focus |", "|-------|-------|", "| **revops** | Lead routing"].join("\n");
|
||||
|
||||
expect(unfinishedAnswerText({ text }) ?? "").toContain("table row");
|
||||
});
|
||||
|
||||
test("a separator is not an open row", () => {
|
||||
expect(unfinishedAnswerText({ text: "| Skill | Focus |\n|-------|-------|" })).toBeNull();
|
||||
});
|
||||
|
||||
test("a table row whose last cell never closed is unfinished", () => {
|
||||
const text = "| **revops** | Lead routing, scoring";
|
||||
|
||||
expect(unfinishedAnswerText({ text })).toContain("table row");
|
||||
});
|
||||
|
||||
test("a finished table is a reply", () => {
|
||||
const text = ["| Skill | Focus |", "| **revops** | Lead routing |", "", "Want me to pull one in full?"].join("\n");
|
||||
|
||||
expect(unfinishedAnswerText({ text })).toBeNull();
|
||||
});
|
||||
|
||||
test("a fence left open is unfinished", () => {
|
||||
expect(unfinishedAnswerText({ text: "The script:\n\n```ts\nconst n = 1" })).toContain("code fence");
|
||||
});
|
||||
|
||||
test("a closed fence is a reply", () => {
|
||||
expect(unfinishedAnswerText({ text: "```ts\nconst n = 1\n```\n\nThat is the whole script." })).toBeNull();
|
||||
});
|
||||
|
||||
test("a heading or list marker with nothing under it is unfinished", () => {
|
||||
expect(unfinishedAnswerText({ text: "What I found\n\n##" })).toContain("heading");
|
||||
expect(unfinishedAnswerText({ text: "Next:\n\n-" })).toContain("heading");
|
||||
expect(unfinishedAnswerText({ text: "1." })).toContain("heading");
|
||||
});
|
||||
|
||||
test("a finished heading and a pipe in prose are replies", () => {
|
||||
expect(unfinishedAnswerText({ text: "## What I found\n\nTwo repos, nothing pulled yet." })).toBeNull();
|
||||
expect(unfinishedAnswerText({ text: "Use a | between the columns when you write it." })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Why an answer stops inside a structure the model meant to finish, or
|
||||
* null when the text can stand as a reply. The check is structural: a
|
||||
* table row with no close, a fence left open, a heading or list marker
|
||||
* with nothing under it. It never decides that a follow-up was owed.
|
||||
* That is the model's call (`suggest_next_steps`), and reading it out of
|
||||
* prose is what `send_reply` exists to stop.
|
||||
*/
|
||||
export default function unfinishedAnswerText({ text }: { text: string }): string | null {
|
||||
const trimmed = text.trim();
|
||||
|
||||
if (!trimmed) return null;
|
||||
|
||||
if (openFence({ text: trimmed })) {
|
||||
return "The message stops inside a code fence that was never closed. Finish the fence, or take it out, and send the whole message again.";
|
||||
}
|
||||
|
||||
const last = lastContentLine({ text: trimmed });
|
||||
|
||||
if (openTableRow({ line: last })) {
|
||||
return "The message stops in the middle of a markdown table row. Finish that row and the table, or take the unfinished row out, and send the whole message again.";
|
||||
}
|
||||
|
||||
if (bareMarker({ line: last })) {
|
||||
return "The message stops on a heading or a list marker with nothing under it. Finish that part, or take the marker out, and send the whole message again.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A fence is open when an odd number of fence lines remain. A fence line
|
||||
* is ``` or ~~~ with nothing but an optional language tag after it, so a
|
||||
* row of dashes in a table is not one.
|
||||
*/
|
||||
function openFence({ text }: { text: string }) {
|
||||
let open = false;
|
||||
|
||||
for (const line of text.split("\n")) {
|
||||
if (/^ {0,3}(`{3,}|~{3,})[^`~]*$/.test(line.trimEnd())) open = !open;
|
||||
}
|
||||
|
||||
return open;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last line that holds something. Trailing blank lines are how a
|
||||
* model ends a paragraph, not how it ends a table.
|
||||
*/
|
||||
function lastContentLine({ text }: { text: string }) {
|
||||
const lines = text.split("\n");
|
||||
|
||||
for (let index = lines.length - 1; index >= 0; index--) {
|
||||
const line = lines[index]!.trim();
|
||||
|
||||
if (line) return line;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* A table row that opened and never closed: `| **revops** |` with the
|
||||
* rest of the cell on no line at all, or a row whose last cell is still
|
||||
* being written (`| **revops** | Lead routing`). A finished row ends with
|
||||
* `|`. A separator (`|---|---|`) is finished too. A line that merely
|
||||
* mentions a pipe in prose is left alone.
|
||||
*/
|
||||
function openTableRow({ line }: { line: string }) {
|
||||
if (!line.startsWith("|")) return false;
|
||||
if (line.endsWith("|")) return false;
|
||||
if (/^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(line)) return false;
|
||||
|
||||
return (line.match(/\|/g) || []).length >= 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A heading, or a list marker, whose line holds nothing else. A heading
|
||||
* with its text, and a list item with its text, are finished lines.
|
||||
*/
|
||||
function bareMarker({ line }: { line: string }) {
|
||||
return /^#{1,6}$/.test(line) || /^[-*+]$/.test(line) || /^\d{1,3}[.)]$/.test(line);
|
||||
}
|
||||
Reference in New Issue
Block a user