import grabCrewRequests from "@/src/functions/backend/db/asks/grab-crew-requests"; import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers"; import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings/grab-skill-limits"; import grabWorkspaceAdminTools from "@/src/harness/tools/bot/grab-workspace-admin-tools"; import workspaceAdminsNote from "./workspace-admins-note"; import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db"; import { ActionCheckNote, RequestScopeNote, QuestionsNote, SecretsNote, SettingsNote, GraphicsNote, botFilesNote, ConnectorsNote, ComputerFilesNote, ScheduledRunNote, HookRunNote, InstallRequestNote, TasksNote, TaskRunNote, AskRulesNote, AskTaskRunNote, crewRequestsNote, WorkspaceLearningNote, TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote, taskPlanNote, wrapUpWorktreeNote, PlanStepNote, } from "@/src/data/harness-prompts"; import { grabContextBudgetTokens, grabHarnessMaxToolSteps, grabRunMaxPromptTokens, grabUnattendedMaxToolSteps, } from "@/src/functions/backend/db/app-settings/grab-run-limits"; import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers"; import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt"; import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan"; import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view"; import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces"; import runTextLoop from "@/src/harness/text/run-text-loop"; import redactTrace from "@/src/harness/trace/redact-trace"; import maskPasswordFieldValues from "@/src/utils/mask-password-field-values"; import { isUnlimitedLimit, smallerRunLimit } from "@/src/utils/run-limit"; import openComputerTools from "@/src/harness/tools/computer/open-computer-tools"; import openBotBrowsers, { type OpenBotBrowsers } from "@/src/harness/tools/browsers/open-bot-browsers"; import openBotConnectors, { type OpenBotConnectors } from "@/src/harness/tools/connectors/open-bot-connectors"; import { BrowserRunKinds, type BrowserRunKind } from "@/src/dict/browser-dict"; import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/extensions/open-bot-extensions"; import openBotSkills, { type OpenBotSkills } from "@/src/harness/tools/skills/open-bot-skills"; import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases"; import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools"; import groupTools from "@/src/harness/tools/group-tools"; import grabCoordinatorKnowledgebaseTools from "@/src/harness/tools/bot/knowledgebases/grab-coordinator-knowledgebase-tools"; import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session"; 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"; import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool"; import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool"; import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool"; import setUserWorkspaceRoleTool from "@/src/harness/tools/bot/set-user-workspace-role-tool"; import askToTakeOverTool from "@/src/harness/tools/computer/ask-to-take-over-tool"; import sendReplyTool from "@/src/harness/tools/bot/send-reply-tool"; import startTaskTool from "@/src/harness/tools/bot/start-task-tool"; import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job"; import importFileTool from "@/src/harness/tools/computer/import-file-tool"; import searchComputersTool from "@/src/harness/tools/computer/search-computers-tool"; import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools"; 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 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"; import composeBrowsersNote from "./compose-browsers-note"; import computerRef from "@/src/utils/computer-ref"; import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes"; import composeJobBrief from "./compose-job-brief"; import grabSessionCarryOver from "./grab-session-carry-over"; 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 ScheduledRunFailedError from "./scheduled-run-failed-error"; import BotJobFatalError from "./bot-job-fatal-error"; import reviewRunAnswer from "./review-run-answer"; import planStepReviewNote from "./plan-step-review"; import 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"; import taskRequestNote from "./task-request-note"; import namedFilesNote from "./named-files-note"; import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message"; import planBotTask from "./plan-bot-task"; import unsentAnswerMessage from "./unsent-answer-message"; import shouldPlanBotTask from "./should-plan-bot-task"; import { AppData } from "@/src/data/app-data"; import pushUserTurn from "@/src/harness/text/push-user-turn"; import type { HarnessMessage } from "@/src/harness/types"; type Params = BotJobContext & { bot: Pick & { id: number }; /** * The user whose conversation the job is in. */ user_id: number; }; /** * Works through a task in its session's workspace (if any): the bot * follows its brief with its full prompt, * its own tools, search_computers across all its computers, its MCP * servers' and custom tools (`openBotExtensions`) and, when the job has a * computer, that computer's tools (over MCP), until it answers. That answer is the report for the user. * When only the user can go on (a login, a captcha), the bot asks them to * take over (`ask_user_to_take_over`) and the report needs them. * A scheduled run acts on its own (`ScheduledRunNote`), as does a hook * call (`HookRunNote`, its payload only data); one that reports it failed * (`report_run_failed`) throws, so the queue retries it. * One the user asked for in their chat opens with their own words, in * front of the brief the bot wrote (`taskRequestNote`), so the way they * named survives the summary. * A task the user follows takes in what they write in its conversation * from when it was queued (`taskIncoming`): already there at the start, * between steps, past a report not yet out, and by the wrap up. A * correction changes the work; anything else is left to the chat. * Every model turn is reported as a step (`report`). */ export default async function runBotTask({ bot, user_id, job, params, signal, stop_signal, report, trace, }: Params): Promise { const workspace_id = job.workspace_id || null; /** * Where the run works on a computer: the user's folder in the bot's. */ const dirs = computerRunDirs({ bot_id: bot.id, bot_kind: bot.kind, user_id, workspace_id }); /** * The secrets the bot captured or showed and the graphics it made or * changed, whose chips the report always carries. */ const shown: string[] = []; /** * The tracker tasks the run worked on, linked under its report. */ const task_ids: number[] = []; /** * The files the run may read, and what its computer tools export from * them (`export_file`): read before the computer is opened, since its * tool list needs them. */ const scopes = await grabRunScopes({ bot, user_id, workspace_id }); /** * The conversation the run answers in: read before its tools open, so a * delete inside a host folder can ask its user there. */ const session_id = await jobSessionId({ job }); const computer = job.computer_id ? await openComputerTools({ computer_id: job.computer_id, bot_id: bot.id, user_id, workspace_id, session_id, dirs, scopes, onSecretRef: ({ ref }) => shown.push(ref), signal, }) : null; /** * A password can reach a model by ways the app never sees, a page that * had one filled in being the one that did: what a task sends out is * read here too, so a password field's value never reaches the user. */ const redact_text = (text: string) => maskPasswordFieldValues({ text: computer ? computer.redact(text) : text }); let extensions: OpenBotExtensions | undefined; let browsers: OpenBotBrowsers | undefined; let skills: OpenBotSkills | undefined; let connectors: OpenBotConnectors | undefined; try { const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id }); const computers = await grabBotComputers({ bot_id: bot.id, workspace_id }); /** * `import_file` reads only the computer this run works on: what it * made is there. The row is read again when the list no longer has * it, so the tool still names the job's computer. */ const job_computers = job.computer_id ? computers.filter((row) => Number(row.id) == Number(job.computer_id)) : []; const import_computers = job_computers.length ? job_computers : job.computer_id ? [{ id: job.computer_id }] : []; /** * What the bot's types let it do here. A coordinator's task can * also change workspaces, and a workspace admin's its workspace: * the findings it was asked to record go there, not only in the * report. */ const powers = await grabBotRunPowers({ bot_id: bot.id, workspace_id }); const coordinator_workspaces = powers.is_coordinator ? (await grabUserWorkspaces({ user_id })).filter((w) => !w.archived) : []; const scheduled = Boolean(params.schedule_id); /** * Started by a call to one of the user's hooks: acts on its own * like a routine, and treats the call's payload as data. */ const hooked = Boolean(params.hook_id); /** * A routine or hook run starts from its brief alone: what the thread * said is the user's conversation, not the run's context. */ const carry_over = scheduled || hooked ? "" : await grabSessionCarryOver({ session_id, bot_id: bot.id, workspace_id, signal, }).catch(() => ""); const take_overs: string[] = []; /** * The next steps the bot suggested: added to the message without * needing the user. */ const suggestions: string[] = []; /** * Files the bot wrote and asked to send with its report. */ const attachments: number[] = []; /** * Runs `send_reply` queued with this report: if the report is never * posted (the review refused it), they are cancelled with it. */ const queued_jobs: number[] = []; /** * A session nobody follows from this bot's chat: a crew request's or * a hook's. Such a run acts on its own, like a routine. */ const hidden = Boolean(session_id) && (await isHiddenSession({ session_id: Number(session_id) })); /** * Only a task the user follows in their conversation asks them * questions: routines and hook calls act on their own, and a crew * request's run works in a session nobody reads from this bot's chat. */ const can_ask = Boolean(session_id) && !scheduled && !hooked && !hidden; /** * The plan whose step queued this run (`send_reply`'s work or * `start_task`, both carrying `params.plan_id`): a long step is * exactly where a bot forgets the plan, so the run works that step * and its report ends on the card that moves the plan on. */ const plan_row = Number(params.plan_id) ? await grabBotPlan({ plan_id: Number(params.plan_id) }).catch(() => null) : null; const plan = plan_row ? toBotPlanView({ row: plan_row }) : null; /** * Only a run the user follows can end on the plan's card, so only * one of those is held to it: a routine's or a hook's run has no * card to put up and reports as usual. */ const on_plan_step = can_ask && Boolean(plan && plan.status == "active" && plan.current_step != null); /** * The coordinator weighing a worker's install request * (`request_install`): it answers it with answer_install_request. */ const install_request_id = powers.is_coordinator ? Number(params.install_request_id) || 0 : 0; let failure = null as string | null; /** * A take-over defaults to the computer the task runs on. */ const take_over_computers = [ ...computers.filter((c) => c.id == job.computer_id), ...computers.filter((c) => c.id != job.computer_id), ]; /** * A workspace admin's task keeps the workspace's context and its * members' instructions; it hands nothing over (no session to report * back to mid-task). */ const admin_tools = !powers.is_coordinator && workspace_id && powers.is_workspace_admin ? (await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, scopes, onTask: ({ task_id }) => task_ids.push(task_id), })).tools : []; const tools = [ ...(await grabBotTools({ user_id, bot_id: bot.id, workspace_id, computers, session_id, is_coordinator: powers.is_coordinator, admin_workspace_ids: powers.admin_workspace_ids, scopes, hooked, onTask: ({ task_id }) => task_ids.push(task_id), })), ...admin_tools, /** * The plan's own step: it finishes the step, or says the plan * is wrong. Writing or cancelling a plan is a reply's job, never * a run's, so those stay out. */ ...(on_plan_step ? grabBotPlanTools({ user_id, bot_id: bot.id, session_id: session_id!, workspace_id, job_id: job.id, on_step: true, onPlan: ({ ref }) => shown.push(ref), }) : []), /** * Part of a crew request (`start_task`/`delegate_task` in an * answer session): the bot can send the asker an interim word * while the work is open; the result itself goes back on its own. */ ...(Number(params.ask_id) ? [ updateRequesterTool({ user_id, session_id: Number(session_id), ask_id: Number(params.ask_id), redact: redact_text, }), ] : []), ...(powers.is_coordinator ? [ createWorkspaceTool({ user_id, session_id, workspaces: coordinator_workspaces, }), ...(coordinator_workspaces.length ? [ updateWorkspaceTool({ user_id, workspaces: coordinator_workspaces, workspace_id, scopes, }), listWorkspacePeopleTool({ workspaces: coordinator_workspaces, workspace_id }), setUserWorkspaceRoleTool({ user_id, workspaces: coordinator_workspaces, workspace_id, }), ] : []), ] : []), /** * The install's knowledgebases: the coordinator lists them in * any run, and fills, re-indexes or deletes them only in a task * the user follows (`can_ask`), never one a schedule or hook * started. */ ...(powers.is_coordinator ? grabCoordinatorKnowledgebaseTools({ user_id, bot_id: bot.id, workspace_id, computer_id: job.computer_id || null, attended: can_ask, }) : []), ...(computers.length ? [ searchComputersTool({ bot_id: bot.id, user_id, computers, workspace_id, dirs }), ...(hooked ? [] : [ askToTakeOverTool({ computers: take_over_computers, in_task: true, onAsk: ({ ref }) => take_overs.push(ref), }), ]), ] : []), ...grabBotSecretTools({ user_id, bot_id: bot.id, session_id, workspace_id, computer_id: job.computer_id || null, in_task: true, onRequest: hooked ? undefined : ({ ref }) => take_overs.push(ref), onShow: ({ ref }) => shown.push(ref), }), ...(can_ask ? [ askUserTool({ user_id, bot_id: bot.id, session_id, workspace_id, in_task: true, plan_id: on_plan_step ? plan?.id : null, onAsk: ({ ref }) => take_overs.push(ref), redact: redact_text, }), suggestNextStepsTool({ user_id, bot_id: bot.id, session_id, workspace_id, onSuggest: ({ ref }) => suggestions.push(ref), redact: redact_text, }), ] : []), ...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []), /** * A worker has no sudo on its computer: it asks the * coordinator to install, from a task the user follows (the * answer wakes it there). */ ...(computer && dirs.run_as && can_ask && job.computer_id && !powers.is_coordinator ? [ requestInstallTool({ user_id, bot_id: bot.id, session_id, workspace_id, computer_id: job.computer_id, }), ] : []), ...(install_request_id && job.id ? [answerInstallRequestTool({ request_id: install_request_id, job_id: job.id })] : []), ...(computer?.tools || []), ...(job.computer_id ? [ importFileTool({ computers: import_computers, scopes, bot_id: bot.id, user_id, dirs, }), ] : []), ...(await grabBotFileTools({ bot, user_id, workspace_id, session_id, scopes, onAttach: ({ media_id }) => attachments.push(media_id), })), ...grabBotGraphicTools({ bot_id: bot.id, user_id, session_id, workspace_id, job_id: job.id || null, onGraphic: ({ ref }) => shown.push(ref), }), ]; extensions = await openBotExtensions({ bot_id: bot.id, user_id, workspace_id, computer_id: job.computer_id || null, dirs, taken: tools.map((tool) => tool.name), signal, }); /** * A run nobody follows (a hook call, or a crew request's child task in * a hidden session) never reaches the user's real browsers: it acts * unattended, like a routine without the owner's routine allowance * (H7). A child task of a crew request inherits its parent's hidden * session, so without this it would have been classed "attended". * The parent reply also hands its kind down (`start_task` `run_kind`), * so a child stays unattended even if the session check ever misses. */ const inherited_kind = BrowserRunKinds.includes(params.run_kind as BrowserRunKind) ? (params.run_kind as BrowserRunKind) : null; const browser_run_kind = hooked || hidden || inherited_kind === "unattended" ? "unattended" : scheduled || inherited_kind === "routine" ? "routine" : "attended"; browsers = await openBotBrowsers({ user_id, bot_id: bot.id, workspace_id, run_kind: browser_run_kind, taken: [...tools, ...extensions.tools].map((tool) => tool.name), signal, }); /** * A task works with the accounts that already work: nobody is * waiting on this run to be asked to connect one, so a connector * without an account gets no tools (it is named in the note). */ connectors = await openBotConnectors({ user_id, bot_id: bot.id, workspace_id, attended: false, taken: [...tools, ...extensions.tools, ...browsers.tools].map((tool) => tool.name), signal, }); skills = openBotSkills({ skills: extensions.skills, shown_chars: await grabSkillBodyShownChars(), taken: [...tools, ...extensions.tools, ...browsers.tools, ...connectors.tools].map((tool) => tool.name), }); const knowledge = openBotKnowledgebases({ knowledgebases: extensions.knowledgebases, taken: [...tools, ...extensions.tools, ...browsers.tools, ...connectors.tools, ...skills.tools].map( (tool) => tool.name, ), }); /** * The install's limit, or less when the brief's writer set a * budget (`start_task` `max_steps`). A routine run or a hook call, * which nobody watches, gets the smaller unattended limit (never * more than a task's). */ const task_steps = await grabHarnessMaxToolSteps(); const install_steps = scheduled || hooked ? smallerRunLimit({ a: task_steps, b: await grabUnattendedMaxToolSteps() }) : task_steps; const budget = Math.floor(Number(params.max_steps) || 0); const max_steps = budget > 0 ? smallerRunLimit({ a: budget, b: install_steps }) : install_steps; /** * What the run is told it has. Unlimited is said as such rather * than as a number: the job's deadline still ends it, and a run * told "at most 0 steps" would stop before it began. */ const steps_note = isUnlimitedLimit(max_steps) ? `This run has no step limit: work until the job is done. Its job still stops it after a while, so save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.` : `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`; /** * What the user wrote since the run was queued, for a run they * follow: what's there now goes after the brief. */ const incoming = can_ask && session_id ? await taskIncoming({ session_id, queued_at: Number(job.created_at) || Date.now(), user_id }) : null; const arrived = (await incoming?.take()) || []; /** * What the user asked for, in their own words. The brief is the * bot's summary of it, and a summary can lose the way they named * ("using the ArtCraft MCP"), which leaves the run free to reach the * same result another way (`taskRequestNote`). Routines, hook calls * and crew requests weren't asked for in a chat, so there is no * request to put in front of the brief. */ const request_message = job.message_id && !scheduled && !hooked && !Number(params.ask_id) ? await grabUserBotMessage({ user_id, message_id: job.message_id }).catch(() => null) : null; const request_note = taskRequestNote({ message: request_message }); const brief: HarnessMessage = { role: "user", content: composeJobBrief({ title: job.title, instructions: job.instructions, params, }), }; /** * The brief names the files the work is about. Where they actually * stand is the app's to check, once, rather than the run's to find * out: a source a rebuild took off the computer is still in the * bot's files, and this is what says so (`namedFilesNote`). */ const named_files_note = computer ? await namedFilesNote({ computer: computer.computer, dirs, scopes, text: [request_note, String(brief.content)].filter(Boolean).join("\n\n"), signal, }) : ""; const opening: HarnessMessage[] = request_note ? [{ role: "user", content: request_note }, brief] : [brief]; if (arrived.length) { pushUserTurn({ transcript: opening, content: TaskIncomingNote }); for (const turn of arrived) { if (turn.role == "user") pushUserTurn({ transcript: opening, content: turn.content }); } } const system = [ prompt, carry_over, TaskRunNote({ can_ask }), steps_note, scheduled ? ScheduledRunNote : "", hooked ? HookRunNote : "", install_request_id ? InstallRequestNote : "", Number(params.ask_id) ? AskTaskRunNote : "", botFilesNote({ bot_id: bot.id }), /** * Only when the run has a computer: the note describes its folders * and its browser, and a run with none has no computer tools at all * (the closing note below is what tells it so). */ computer ? ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }) : "", named_files_note, TasksNote, /** * The plan's step this run works: it finishes that step, or asks * the user on the card, and the report says which. This is the * note a long step would otherwise lose the plan without. */ on_plan_step && plan ? PlanStepNote({ plan }) : "", ActionCheckNote, RequestScopeNote({ can_ask }), can_ask ? QuestionsNote : "", SecretsNote, SettingsNote, GraphicsNote, workspace_id ? WorkspaceLearningNote : "", powers.is_coordinator ? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.` : admin_tools.some((tool) => tool.name == "update_workspace") ? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.` : "", powers.is_coordinator || powers.is_workspace_admin ? "" : await workspaceAdminsNote({ bot_id: bot.id, workspace_id }), powers.is_coordinator || hooked ? "" : AskRulesNote, powers.is_coordinator || hooked ? "" : crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id, since: Date.now() - AppData.CrewRequestsRecentMs }) }), computer ? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}` : workspace_id ? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.` : `You have no computer for this task.`, computers.length > 1 ? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.` : "", computer?.envs.length ? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs .map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`) .join("\n")}` : "", composeBrowsersNote({ browsers: browsers.browsers, has_computer_browser: Boolean(computer), run_kind: browser_run_kind, }), skills.note, knowledge.note, extensions.note, connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "", ] .filter(Boolean) .join("\n\n"); /* * The plan this run works from, written in one turn before it takes * a step (`planBotTask`). It shares this run's prompt, so it costs * little more than the plan, and it saves the steps a long run * spends finding out what it is doing. A run whose plan can't be * written starts the way it always did. A routine or a hook call * already has its plan (the brief, the runbook), so it works that. */ const planned = !scheduled && !hooked && shouldPlanBotTask({ max_steps }) ? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch( (error) => { if (signal.aborted) throw error; return null; }, ) : null; if (planned) { pushUserTurn({ transcript: opening, content: taskPlanNote({ plan: planned.plan }) }); await report({ index: -1, text: `Plan: ${planned.plan.goal}`, tool_calls: [], candidate: planned.candidate, }); } const result = await runTextLoop({ system, messages: opening, tools: groupTools({ tools: [ ...tools, /** * A task report ends with `send_reply`, the same protocol a * reply uses: its status says whether anything runs after * it, and a `working` report must name the run. `start_task` * stays here for work the run hands on before it reports. */ sendReplyTool({ user_id, bot_id: bot.id, session_id, computers, message_id: job.message_id || undefined, job_id: job.id, run_kind: browser_run_kind, plan_id: on_plan_step ? plan?.id : null, onQueue: ({ job_id }) => queued_jobs.push(job_id), }), startTaskTool({ user_id, bot_id: bot.id, session_id, computers, message_id: job.message_id || undefined, run_kind: browser_run_kind, plan_id: on_plan_step ? plan?.id : null, }), ...extensions.tools, ...browsers.tools, ...connectors.tools, ...skills.tools, ...knowledge.tools, ], }), max_steps, max_prompt_tokens: await grabRunMaxPromptTokens(), context_budget: await grabContextBudgetTokens(), bot_id: bot.id, workspace_id, signal, stop_signal, onStep: (step) => report({ ...step, text: step.text ? redact_text(step.text) : step.text }), /** * The trace also holds a computer's own secrets: what the bot * captured mid-run (`capture_secret`) never reaches the * stored trace, whatever the job's envs are. */ trace: (entry) => trace(computer ? redactTrace({ trace: entry, redact: computer.redact }) : entry), /** * What the run wrote is on disk, and the run's memory of writing * it is what drifts: the folders are read at the wrap up so the * report can be written from the tree instead of from memory. * No computer, no folders of the run's own, so nothing to read. */ wrap_up_note: computer ? async () => { const summary = await worktreeSummary({ computer: computer.computer, dirs, signal }).catch( () => "", ); return summary ? wrapUpWorktreeNote({ summary }) : ""; } : undefined, ...(incoming ? { incoming: incoming.take, incoming_notes: { working: TaskIncomingNote, redraft: TaskRedraftNote, wrap_up: TaskWrapUpIncomingNote, }, } : {}), /** * 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. * * A report of a plan's step is also held to the step's ending: * the plan moves on from its card, so a report without one * leaves the plan waiting on the user to say "move on". */ review: ({ text, tool_uses, status }) => reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes, job_id: job.id })({ text, tool_uses, status, }).then((note) => { if (note) return note; return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status }); }), /** * A report goes out only through `send_reply`, so it can't say * work is under way with the run's own open job behind it. */ require_closing_answer: true, /** * The model that wrote the plan, when there was one: the run * works it on that model when it is still the one to use. */ prefer_key: planned?.candidate.key, }); if (failure) { throw new ScheduledRunFailedError(redact_text(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 }); for (const queued of queued_jobs) { await cancelBotJob({ user_id, job_id: queued }).catch(() => null); } throw new BotJobFatalError(unsentAnswerMessage({ note: result.review_note })); } const text = stripAppRecords({ text: result.text }); /** * Nothing said is nothing to send: an empty report lands in the * thread as a bubble with no text and the user has no idea what the * run did. The job fails with why instead, which they do see - the * same guard a reply has (`run-bot-reply`), since `completeBotJob` * posts whatever text it is given (L5). */ if (!text.trim() && !shown.length && !suggestions.length && !attachments.length) { for (const queued of queued_jobs) { await cancelBotJob({ user_id, job_id: queued }).catch(() => null); } throw new BotJobFatalError(`The run ended without a report to send.`); } /** * Work queued in an earlier turn and then withdrawn by the report * that ended the run (`done` or `blocked`): the user reads that * nothing runs, so nothing may. */ if (result.status !== "working") { for (const queued of queued_jobs) { await cancelBotJob({ user_id, job_id: queued }).catch(() => null); } } return { ...withTakeOverRefs({ text: redact_text(text), refs: take_overs, shown: [...shown, ...suggestions], }), attachments: attachments.length ? attachments : undefined, tool_log: result.tool_uses, task_ids, plan_message_id: on_plan_step ? plan?.id : undefined, /** * The wrap up was announced (`steps` counts its turns), so the * run never got to the end of the work it was given. */ exhausted: !isUnlimitedLimit(max_steps) && result.steps > max_steps, }; } finally { await extensions?.close(); await browsers?.close(); await connectors?.close(); 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); } }