Compare commits

...
3 Commits
Author SHA1 Message Date
tben 15d4f85e14 Bump version to 0.28.14
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-26 14:29:11 +01:00
tben 39055f8028 Let a bot send a late answer back on an ended crew request 2026-11-26 14:27:45 +01:00
tben 87be48ffb5 Relay a crew request's ack and late results, and stop only the runs the user stopped 2026-11-26 13:30:16 +01:00
20 changed files with 500 additions and 22 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+5
View File
@@ -356,6 +356,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The ask the asking bot was itself working on when it asked (a nested request). Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "requester_job_id",
fieldDescription: `The asking bot's run that made the request, so stopping that run ends this request and no other ask from the same conversation. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "title",
fieldDescription: `A short label for the request`,
+4
View File
@@ -303,6 +303,10 @@ export type BUN_SQLITE_COBBLE_BOT_ASKS = {
* The ask the asking bot was itself working on when it asked (a nested request). Not a foreign key
*/
parent_ask_id?: number | "";
/**
* The asking bot's run that made the request, so stopping that run ends this request and no other ask from the same conversation. Not a foreign key
*/
requester_job_id?: number | "";
/**
* A short label for the request
*/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.13",
"version": "0.28.14",
"module": "index.ts",
"type": "module",
"private": true,
+23
View File
@@ -57,6 +57,7 @@ import openBotExtensions from "@/src/harness/tools/extensions/open-bot-extension
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
import grabOpenAskBySession from "@/src/functions/backend/db/asks/grab-open-ask-by-session";
import grabEndedAskBySession from "@/src/functions/backend/db/asks/grab-ended-ask-by-session";
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
import parseJobJson from "./parse-job-json";
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
@@ -89,6 +90,7 @@ import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-f
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
import answerRequesterTool from "@/src/harness/tools/bot/answer-requester-tool";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
@@ -394,6 +396,17 @@ export default async function runBotReply({
* back to the bot that asked while the work is still open).
*/
const ask_id_for_updates = job_ask_id || (open_ask?.id ? Number(open_ask.id) : 0);
/**
* The request this conversation answered and that has since ended: the
* one place a late or corrected answer can go back from, so the bot
* doesn't open a fresh request through the gate for what belongs to
* that one (an ended request's answer session, once the user resumes
* it, had no way to finish back).
*/
const ended_ask =
!ask_id_for_updates && session_id
? await grabEndedAskBySession({ session_id: Number(session_id), user_id }).catch(() => null)
: null;
let led: WorkspaceAdminTools | null = null;
const tools = await grabBotChatTools({
@@ -551,6 +564,16 @@ export default async function runBotReply({
}),
]
: []),
...(ended_ask?.id && Number(ended_ask.target_bot_id) == Number(bot.id)
? [
answerRequesterTool({
user_id,
bot_id: bot.id,
ask_id: Number(ended_ask.id),
redact: redact_reply,
}),
]
: []),
continueInNewSessionTool({
bot_id: bot.id!,
user_id,
+23
View File
@@ -74,6 +74,8 @@ import grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools"
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
import reportRunFailedTool from "@/src/harness/tools/bot/report-run-failed-tool";
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
import answerRequesterTool from "@/src/harness/tools/bot/answer-requester-tool";
import grabEndedAskBySession from "@/src/functions/backend/db/asks/grab-ended-ask-by-session";
import answerInstallRequestTool from "@/src/harness/tools/bot/answer-install-request-tool";
import requestInstallTool from "@/src/harness/tools/computer/request-install-tool";
import worktreeSummary from "@/src/harness/tools/computer/worktree-summary";
@@ -288,6 +290,16 @@ export default async function runBotTask({
* (`request_install`): it answers it with answer_install_request.
*/
const install_request_id = powers.is_coordinator ? Number(params.install_request_id) || 0 : 0;
/**
* The request this run's session answered, once it has ended (and
* this run isn't part of one): so a task the user asked for here
* can send its finished answer back to the bot that asked, instead
* of opening a fresh request the gate reads as a new handoff.
*/
const ended_ask =
!Number(params.ask_id) && session_id
? await grabEndedAskBySession({ session_id: Number(session_id), user_id }).catch(() => null)
: null;
let failure = null as string | null;
/**
@@ -326,6 +338,7 @@ export default async function runBotTask({
scopes,
hooked,
onTask: ({ task_id }) => task_ids.push(task_id),
job_id: job.id,
})),
...admin_tools,
/**
@@ -359,6 +372,16 @@ export default async function runBotTask({
}),
]
: []),
...(ended_ask?.id && Number(ended_ask.target_bot_id) == Number(bot.id)
? [
answerRequesterTool({
user_id,
bot_id: bot.id,
ask_id: Number(ended_ask.id),
redact: redact_text,
}),
]
: []),
...(powers.is_coordinator
? [
createWorkspaceTool({
@@ -34,4 +34,13 @@ describe("askUpdateMessage", () => {
expect(text).toContain("your crew request");
});
test("an answer sent after the request ended says so instead of still open", () => {
const text = askUpdateMessage({ ask, text: "Banner finished: [file:389].", ended: true });
expect(text).toContain("[bot:3] sent a response on");
expect(text).toContain("Banner finished: [file:389].");
expect(text).toContain("had already ended");
expect(text).not.toContain("still open");
});
});
@@ -12,6 +12,11 @@ type Params = {
* The run that produced this result failed.
*/
failed?: boolean;
/**
* The request had already ended when this was sent (`answer_requester`):
* it's the answer arriving late, not one piece of work still running.
*/
ended?: boolean;
};
/**
@@ -19,9 +24,10 @@ type Params = {
* bot finished one piece of the work, but more is still running, so the
* request isn't ended yet. Stored on the user's side like the final outcome
* (`from_ask_id`), and says plainly that more may follow so the asking bot
* doesn't treat it as the whole answer.
* doesn't treat it as the whole answer. With `ended`, it's the same shape
* for a request that had already finished: a late or corrected answer.
*/
export default function askUpdateMessage({ ask, text, failed }: Params) {
export default function askUpdateMessage({ ask, text, failed, ended }: Params) {
const title = ask.title ? `"${ask.title}"` : "your crew request";
const pill = ask.id ? ` ${askRef({ id: ask.id })}` : "";
const target = ask.target_bot_id ? botRef({ id: ask.target_bot_id }) : "the crew";
@@ -30,5 +36,9 @@ export default function askUpdateMessage({ ask, text, failed }: Params) {
? `${target} couldn't finish one piece of ${title}${pill}:`
: `${target} sent a response on ${title}${pill}:`;
return `${head}\n\n${text}\n\n_The request is still open - more may follow._`;
const tail = ended
? `_The request had already ended; this is the answer, sent afterwards._`
: `_The request is still open - more may follow._`;
return `${head}\n\n${text}\n\n${tail}`;
}
@@ -20,6 +20,11 @@ type Params = {
target_bot_id: number | string;
title: string;
request: string;
/**
* The run making the request, recorded so stopping that run ends this
* request and no other ask made from the same conversation.
*/
requester_job_id?: number | string | null;
};
/**
@@ -34,6 +39,7 @@ export default async function createAsk({
target_bot_id,
title,
request,
requester_job_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_ASKS> {
if (requester.kind == "coordinator") {
throw new AppError(`The coordinator hands work out itself; it doesn't ask the crew.`);
@@ -101,6 +107,7 @@ export default async function createAsk({
target_bot_id: Number(target_bot_id),
origin_session_id: Number(origin_session_id),
parent_ask_id: parent_ask_id ? Number(parent_ask_id) : undefined,
requester_job_id: requester_job_id ? Number(requester_job_id) : undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: request.trim(), max: AppData.AskBriefMaxChars }),
status: "pending",
@@ -122,6 +129,7 @@ export default async function createAsk({
target_bot_id: Number(target_bot_id),
origin_session_id: Number(origin_session_id),
parent_ask_id: parent_ask_id ? Number(parent_ask_id) : undefined,
requester_job_id: requester_job_id ? Number(requester_job_id) : undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: request.trim(), max: AppData.AskBriefMaxChars }),
status: "pending",
@@ -0,0 +1,35 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
type Params = {
/**
* The conversation to look up: a crew request's answer ran in its own
* session, recorded on the request as `session_id`.
*/
session_id: number | string;
/**
* Only if it's this user's, when the caller knows them.
*/
user_id?: number | string;
};
/**
* The request this session answered, once it has ended (answered, stopped
* or failed): the mirror of `grabOpenAskBySession`. A chat here after the
* end is the one place a late or corrected answer is written, so this is
* how the run knows to offer `answer_requester` instead of letting the
* bot open a fresh request through the gate for what belongs to this one.
*/
export default async function grabEndedAskBySession({
session_id,
user_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_ASKS | null> {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: user_id
? `SELECT * FROM bot_asks WHERE session_id = ? AND user_id = ? AND status NOT IN ('pending', 'working') ORDER BY id DESC LIMIT 1`
: `SELECT * FROM bot_asks WHERE session_id = ? AND status NOT IN ('pending', 'working') ORDER BY id DESC LIMIT 1`,
values: user_id ? [Number(session_id), Number(user_id)] : [Number(session_id)],
});
return res.payload?.[0] || null;
}
@@ -17,6 +17,7 @@ import type { HarnessToolUse } from "@/src/harness/types";
*/
let ask: BUN_SQLITE_COBBLE_BOT_ASKS;
let open_work: boolean;
let reopened: BUN_SQLITE_COBBLE_BOT_ASKS | null;
let finished: Array<{ status: string; outcome?: string | null }> = [];
let told: Array<{ text: string }> = [];
let shared: string[] = [];
@@ -40,6 +41,9 @@ mock.module("@/src/functions/backend/db/asks/finish-ask", () => ({
return ask;
},
}));
mock.module("@/src/functions/backend/db/asks/reopen-failed-ask", () => ({
default: async () => reopened,
}));
mock.module("@/src/functions/backend/db/asks/tell-ask-requester", () => ({
default: async ({ text }: { text: string }) => {
told.push({ text });
@@ -91,6 +95,7 @@ const real_answer = "Done. The post is built and saved: [file:650].";
beforeEach(() => {
ask = workingAsk();
open_work = false;
reopened = null;
finished = [];
told = [];
shared = [];
@@ -98,11 +103,22 @@ beforeEach(() => {
});
describe("onAskJobEnded - the answer reply", () => {
test("an answer that started work still running keeps the request open and relays nothing", async () => {
test("an answer that started work still running keeps the request open and relays the ack as an update", async () => {
open_work = true;
await onAskJobEnded({ job: answerJob(), text: claim, tool_uses: started_task });
expect(finished).toEqual([]);
expect(told.length).toBe(1);
expect(told[0]?.text).toContain(claim);
expect(told[0]?.text).toContain("still open");
});
test("a failed answer with work open relays nothing", async () => {
open_work = true;
await onAskJobEnded({ job: answerJob(), text: "The model call died.", failed: true });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
@@ -203,6 +219,49 @@ describe("onAskJobEnded - a run the answer handed the work to", () => {
});
});
describe("onAskJobEnded - a result landing after the request already failed", () => {
test("a late child result is delivered and the request reads answered", async () => {
ask = { ...workingAsk(), status: "failed" } as BUN_SQLITE_COBBLE_BOT_ASKS;
reopened = ask;
await onAskJobEnded({ job: childJob(), text: real_answer });
expect(finished).toEqual([]);
expect(shared).toEqual([real_answer]);
expect(told.length).toBe(1);
expect(told[0]?.text).toContain("which answered");
expect(told[0]?.text).toContain(real_answer);
});
test("a late failure changes nothing", async () => {
ask = { ...workingAsk(), status: "failed" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: childJob(), text: "", failed: true });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
test("a request someone else re-ended first is not written twice", async () => {
ask = { ...workingAsk(), status: "failed" } as BUN_SQLITE_COBBLE_BOT_ASKS;
reopened = null;
await onAskJobEnded({ job: childJob(), text: real_answer });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
test("a stopped request is not reopened", async () => {
ask = { ...workingAsk(), status: "stopped" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: childJob(), text: real_answer });
expect(finished).toEqual([]);
expect(told).toEqual([]);
});
});
describe("onAskJobEnded - the gate's review and guards", () => {
test("a failed review fails the request and clears its hidden session", async () => {
const review_job = { id: 490, bot_id: 1, session_id: 66, params: `{"ask_id":3,"stage":"review"}` } as BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -8,8 +8,10 @@ import { AskStages } from "@/src/dict/ask-dict";
import hasOpenWork from "../bots-queue/has-open-work";
import deleteEmptyAskSession from "../bot-sessions/delete-empty-ask-session";
import askUpdateMessage from "./ask-update-message";
import askOutcomeMessage from "./ask-outcome-message";
import finishAsk from "./finish-ask";
import grabAsk from "./grab-ask";
import reopenFailedAskAnswered from "./reopen-failed-ask";
import shareAskFiles from "./share-ask-files";
import tellAskRequester from "./tell-ask-requester";
@@ -44,7 +46,32 @@ export default async function onAskJobEnded({ job, text, failed, tool_uses = []
const ask = await grabAsk({ ask_id });
if (!ask?.id || (ask.status != "pending" && ask.status != "working")) return;
if (!ask?.id) return;
/**
* A request that already failed can still get a result: the answer run
* can die after it had queued the work, and the asking bot was told it
* couldn't answer while the deliverable exists. When that run comes back
* with the real answer, it goes to the asking bot and the request reads
* answered, instead of the result being dropped quietly. A stopped or
* refused request stays ended: the user or the coordinator said so.
*/
if (ask.status == "failed") {
const late = (text || "").trim();
if (failed || !late || params.stage == AskStages.review) return;
const shared = stripQuestionRefs({ text: await shareAskFiles({ ask, answer: late }) }).text;
const reopened = await reopenFailedAskAnswered({ ask_id: ask.id, outcome: shared });
if (!reopened?.id) return;
await tellAskRequester({ ask, text: askOutcomeMessage({ ask, status: "answered", outcome: shared }) });
return;
}
if (ask.status != "pending" && ask.status != "working") return;
if (params.stage == AskStages.review) {
/**
@@ -83,12 +110,30 @@ export default async function onAskJobEnded({ job, text, failed, tool_uses = []
/**
* The answer started work that is still running (a task, a hand-over,
* a nested request): the acknowledgement is not the answer. The
* request stays open and the results come back as they land; the
* ack itself is not relayed, so the asking bot isn't woken for a
* promise.
* a nested request): the acknowledgement is not the whole answer. The
* request stays open and the results come back as they land. The ack
* is relayed as an update too, because it can carry work already done
* - measurements, files, copy to check - and the asking bot should
* have it, especially if the run it just queued is stopped or fails
* and nothing further comes.
*/
if (await hasOpenWork({ bot_id: job.bot_id!, session_id: answer_session_id })) return;
if (await hasOpenWork({ bot_id: job.bot_id!, session_id: answer_session_id })) {
const ack = (text || "").trim();
if (ack && !failed) {
const shared = await shareAskFiles({ ask, answer: ack });
await tellAskRequester({
ask,
text: askUpdateMessage({
ask,
text: stripQuestionRefs({ text: shared }).text,
}),
});
}
return;
}
if (failed) {
await finishAsk({
@@ -0,0 +1,25 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
type Params = {
ask_id: number | string;
outcome: string;
};
/**
* Turns a request that failed too early into an answered one once a run
* that was working on it comes back with a result: the answer run can die
* after it had already queued the work, and the request must not stay
* recorded as failed when an answer exists. Only flips a `failed` row, so
* a stopped or answered request is never reopened; null when something
* else ended it in the meantime.
*/
export default async function reopenFailedAskAnswered({ ask_id, outcome }: Params): Promise<BUN_SQLITE_COBBLE_BOT_ASKS | null> {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `UPDATE bot_asks SET status = 'answered', outcome = ?, updated_at = ?
WHERE id = ? AND status = 'failed' RETURNING *`,
values: [outcome, Date.now(), Number(ask_id)],
});
return res.payload?.[0] || null;
}
+27 -6
View File
@@ -8,7 +8,15 @@ type Params = {
user_id: number | string;
requester_bot_id: number | string;
/**
* The sessions being stopped: the asks they made are stopped with them.
* The runs being stopped: the asks made from them are stopped with them.
* Matched by the ask's own `requester_job_id`, so a request made by an
* earlier run of the same conversation is not taken away when the user
* stops an unrelated later one.
*/
job_ids: (number | string)[];
/**
* Fallback for asks made before `requester_job_id` was recorded: the
* sessions being stopped still stop the open asks that came from them.
*/
session_ids: (number | string)[];
};
@@ -18,15 +26,28 @@ type Params = {
* ends as `stopped` (the asking bot is told, but not woken, since its run is
* the one that was stopped) and whatever run was working it is cancelled.
*/
export default async function stopAsks({ user_id, requester_bot_id, session_ids }: Params) {
if (!session_ids.length) return [];
export default async function stopAsks({ user_id, requester_bot_id, job_ids, session_ids }: Params) {
if (!job_ids.length && !session_ids.length) return [];
const placeholders = session_ids.map(() => "?").join(", ");
const job_placeholders = job_ids.length ? job_ids.map(() => "?").join(", ") : "";
const session_placeholders = session_ids.length ? session_ids.map(() => "?").join(", ") : "";
const match = [
job_ids.length ? `(requester_job_id IN (${job_placeholders}))` : "",
session_ids.length ? `(requester_job_id IS NULL AND origin_session_id IN (${session_placeholders}))` : "",
]
.filter(Boolean)
.join(" OR ");
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `SELECT * FROM bot_asks WHERE user_id = ? AND requester_bot_id = ?
AND origin_session_id IN (${placeholders}) AND status IN ('pending', 'working')`,
values: [Number(user_id), Number(requester_bot_id), ...session_ids.map(Number)],
AND (${match}) AND status IN ('pending', 'working')`,
values: [
Number(user_id),
Number(requester_bot_id),
...job_ids.map(Number),
...session_ids.map(Number),
],
});
const stopped: BUN_SQLITE_COBBLE_BOT_ASKS[] = [];
@@ -13,6 +13,7 @@ import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import stopAsk from "../asks/stop-ask";
import stopAsks from "../asks/stop-asks";
import grabAsk from "../asks/grab-ask";
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
import settleInstallRequest from "../install-requests/settle-install-request";
@@ -198,19 +199,44 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
}
for (const ask_id of ask_ids) {
/**
* When the answer run already finished, the request isn't left
* silent: its acknowledgement went back as an update (with the
* files and anything it asked to check), so the stopped reason
* tells the asker that what it already has stands and only the
* queued work is gone. A stopped answer run means there truly is
* no answer.
*/
const ask = await grabAsk({ ask_id }).catch(() => null);
const answered =
!!ask?.job_id &&
!!(
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue WHERE id = ? AND status = 'completed' LIMIT 1`,
values: [Number(ask.job_id)],
}).catch(() => null)
)?.payload?.length;
await stopAsk({
ask_id,
reason: "The user stopped the run answering it, so there is no answer.",
reason: answered
? "The user stopped the work it had queued before it finished. Anything it had already answered stands."
: "The user stopped the run answering it, so there is no answer.",
}).catch(() => null);
}
/**
* And the requests a run of its own had open go with it: its bot isn't
* woken about work the user just stopped.
* woken about work the user just stopped. Matched by the run that made
* each request, so stopping one run never ends an ask another run of
* the same conversation is waiting on; asks made before that was
* recorded keep the old session match.
*/
await stopAsks({
user_id,
requester_bot_id: bot_id,
job_ids: jobs.map((job) => Number(job.id)),
session_ids: open.map((job) => Number(job.session_id)),
}).catch(() => []);
@@ -0,0 +1,89 @@
import { describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
/**
* `answer_requester` closes the gap where a request's answer session is
* resumed after the request ended: the finished or corrected answer goes
* straight back to the bot that asked, on the ended request's own record,
* instead of a fresh `ask_bot` the gate reads as a new handoff. It shares
* the answer's files, strips question refs, refuses while the request is
* still open (the machinery relays that itself), and only for the bot the
* request was passed to.
*/
let ask: BUN_SQLITE_COBBLE_BOT_ASKS | null;
let shared: string[] = [];
let told: Array<{ text: string }> = [];
const signal = new AbortController().signal;
mock.module("@/src/functions/backend/db/asks/grab-ask", () => ({
default: async () => ask,
}));
mock.module("@/src/functions/backend/db/asks/share-ask-files", () => ({
default: async ({ answer }: { answer: string }) => {
shared.push(answer);
return answer;
},
}));
mock.module("@/src/functions/backend/db/asks/tell-ask-requester", () => ({
default: async ({ text }: { text: string }) => {
told.push({ text });
return { session_id: 56, message: { id: 900 } };
},
}));
const answerRequesterTool = (await import("./answer-requester-tool")).default;
const endedAsk = {
id: 24,
status: "answered",
title: "Sample blog post banner",
target_bot_id: 8,
requester_bot_id: 6,
} as BUN_SQLITE_COBBLE_BOT_ASKS;
describe("answerRequesterTool", () => {
test("a late answer goes back on the ended request and wakes the asker", async () => {
ask = endedAsk;
shared = [];
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
const res = await tool.run({ args: { text: "Banner finished: [file:389]." }, signal });
expect(shared).toEqual(["Banner finished: [file:389]."]);
expect(told.length).toBe(1);
expect(told[0]?.text).toContain("Banner finished: [file:389].");
expect(told[0]?.text).toContain("had already ended");
expect(String(res)).toContain("Sent to the bot that asked");
});
test("an open request is refused: its answer goes back on its own", async () => {
ask = { ...endedAsk, status: "working" };
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
await expect(tool.run({ args: { text: "Here." }, signal })).rejects.toThrow("still open");
expect(told).toEqual([]);
});
test("only the bot the request was passed to can answer it back", async () => {
ask = endedAsk;
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 9, ask_id: 24 });
await expect(tool.run({ args: { text: "Here." }, signal })).rejects.toThrow("didn't answer that request");
expect(told).toEqual([]);
});
test("a stopped request can still be answered late", async () => {
ask = { ...endedAsk, status: "stopped" };
told = [];
const tool = answerRequesterTool({ user_id: 1, bot_id: 8, ask_id: 24 });
await tool.run({ args: { text: "Finished after all." }, signal });
expect(told.length).toBe(1);
});
});
@@ -0,0 +1,83 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import grabAsk from "@/src/functions/backend/db/asks/grab-ask";
import askUpdateMessage from "@/src/functions/backend/db/asks/ask-update-message";
import shareAskFiles from "@/src/functions/backend/db/asks/share-ask-files";
import tellAskRequester from "@/src/functions/backend/db/asks/tell-ask-requester";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import type { HarnessTool } from "../../types";
type Params = {
user_id: number | string;
/**
* The bot answering: only the bot the request was passed to may send
* its answer back.
*/
bot_id: number | string;
/**
* The ended request this conversation answered, found by the caller
* through `grabEndedAskBySession`.
*/
ask_id: number | string;
/**
* What the run typed, run through the run's secret redaction before it
* is stored: the answer lands in another bot's conversation, where a
* raw env value would sit in a message forever.
*/
redact?: (text: string) => string;
};
type Args = {
text: string;
};
/**
* The gap `ask_bot` kept falling into: the request ended (often `blocked`,
* or stopped), the user carries on in the answer session and gets the work
* done, and the bot's only way back to the asking bot was a brand-new
* request - which the gate reads as a fresh handoff and can refuse, leaving
* the asker never told. This tool posts the finished answer straight back to
* the conversation the request came from, on the ended request's own record
* (`from_ask_id`, with its files shared), and wakes the asking bot. It ends
* nothing and reopens nothing: the request's row keeps the status it ended
* with, and the message says plainly it arrived after the end.
*/
export default function answerRequesterTool({ user_id, bot_id, ask_id, redact = (text) => text }: Params): HarnessTool<Args> {
return {
name: "answer_requester",
description: `Send the bot that asked you a late or corrected answer to the request this conversation answered - after that request had already ended (blocked, stopped or answered). It lands in the conversation the request came from, shares any files it names, and wakes that bot. Use this instead of ask_bot for finishing what that request asked: a new request goes through the coordinator again and reads as a different handoff. Your ordinary answer here is the message; this tool is only for getting it back to the bot that asked.`,
schema: z.object({
text: z
.string()
.trim()
.min(1)
.max(AppData.AskBriefMaxChars)
.describe(`The answer (markdown): what you finished, with [file:ID] refs for what you produced`),
}),
run: async ({ args }) => {
const ask = await grabAsk({ ask_id, user_id });
if (!ask?.id) {
throw new Error(`That request isn't here anymore.`);
}
if (ask.status == "pending" || ask.status == "working") {
throw new Error(
`This request is still open: your answer goes back on its own when your work ends, and update_requester sends a word meanwhile.`,
);
}
if (Number(ask.target_bot_id) != Number(bot_id)) {
throw new Error(`This conversation didn't answer that request, so it has no answer to send back.`);
}
const shared = stripQuestionRefs({
text: await shareAskFiles({ ask, answer: redact(args.text) }),
}).text;
await tellAskRequester({ ask, text: askUpdateMessage({ ask, text: shared, ended: true }) });
return `Sent to the bot that asked, on "${ask.title}" [ask:${ask.id}]. Its conversation wakes for it.`;
},
};
}
+7 -1
View File
@@ -20,6 +20,11 @@ type Params = {
* Where it works: in a workspace, only its members can be asked.
*/
workspace_id?: number | string | null;
/**
* The run asking, recorded on the ask so stopping that run ends this
* request and no other ask from the same conversation.
*/
job_id?: number | string | null;
};
type Args = {
@@ -37,7 +42,7 @@ type Args = {
* call, never the model's: in a workspace its members, otherwise every worker
* the user reaches.
*/
export default function askBotTool({ user_id, bot_id, session_id, workspace_id }: Params): HarnessTool<Args> {
export default function askBotTool({ user_id, bot_id, session_id, workspace_id, job_id }: Params): HarnessTool<Args> {
return {
name: "ask_bot",
description: `Ask another bot for something you need (what it knows, a file it has, work in its line). The coordinator reads every request first: it passes it to the bot that should answer, sends it to a better-placed bot, or turns it down with the reason. An approved request's answer comes back here as a message, which wakes you to act on it: don't wait or check on it. If a task you'd start needs the answer, don't start it in the same reply: it would run without it, so start it once the answer wakes you. Write the request as a full brief: what you need, why, and what a good answer looks like. Name a bot with bot_id if you know who can help; the coordinator decides. ${
@@ -104,6 +109,7 @@ export default function askBotTool({ user_id, bot_id, session_id, workspace_id }
target_bot_id: named?.id || askable[0]!.id!,
title: args.title,
request,
requester_job_id: job_id,
});
return `Asked ${named ? `${named.name} [bot:${named.id}]` : "the crew"} (ask #${ask.id}). The coordinator reads it first; its outcome comes back here as a message and you'll be woken for it. Tell the user you asked; don't ask again while it's open.`;
@@ -187,6 +187,7 @@ export default async function grabBotChatTools({
can_delete_tasks: Boolean(attended),
onPropose,
onTask,
job_id,
})),
sendReplyTool({
user_id,
+7 -1
View File
@@ -52,6 +52,11 @@ type Params = {
* The run is a hook call, so it gets no hook tools.
*/
hooked?: boolean;
/**
* The run's own job, recorded on asks the bot makes so stopping exactly
* that run ends exactly those requests.
*/
job_id?: number | string | null;
/**
* A chat reply the user follows, which may delete tasks.
*/
@@ -85,6 +90,7 @@ export default async function grabBotTools({
admin_workspace_ids,
scopes = [],
hooked,
job_id,
can_delete_tasks,
onPropose,
onTask,
@@ -125,7 +131,7 @@ export default async function grabBotTools({
*/
...(session_id && !is_coordinator && !hooked
? [
askBotTool({ user_id, bot_id, session_id, workspace_id }),
askBotTool({ user_id, bot_id, session_id, workspace_id, job_id }),
listAsksTool({ user_id, bot_id }),
]
: []),