/** * `pretty_task_bg_run`, `pretty_task_bg_status`, `pretty_task_bg_logs`, `pretty_task_bg_kill` and `pretty_task_bg_wait`: what the agent can * do with process tasks. * * The tools are thin. They translate a turn into a scope, call the store, and * render the result as text a model can read — all knowledge of shells, * files and process state stays behind the store. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ import type { AgentToolResult, ExtensionToolContext, ToolDefinition, } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { commandPreview, formatBytes, formatDuration } from "../base/format.js"; import { clampSearchMatches, DEFAULT_SEARCH_BYTES, DEFAULT_SEARCH_MATCHES, MAX_SEARCH_MATCHES, searchOutputFile, } from "../base/search.js"; import type { ProcessTask } from "../base/task.js"; import type { ChainTasks, ChainTaskView, QueuedStep, StopChainResult, } from "../chain/chain-tasks.js"; import { parseFollowSeconds, parseTimeoutSeconds, parseWaitSeconds } from "./limits.js"; import type { FollowTaskResult, ProcessTasks, ProcessTaskView, StopTaskResult, TaskScope, WaitTaskResult, } from "./process-tasks.js"; import type { CommandTemplate } from "./templates.js"; const RunParameters = Type.Object({ command: Type.Optional( Type.String({ description: "Shell command to run in the background. Omit it to use the command from `template`; when both are given, this command wins. The shell depends on the platform and on the extension's configuration; `shell` picks another one for this call. Write the command in the dialect of that shell: cmd joins with `&`, while sh and bash treat `&` as background and need `;` or `&&`. Output is stored as raw bytes.", }), ), template: Type.Optional( Type.String({ description: "Name of a command template. The project's `.pi/pretty-task.json` wins over the agent's `pretty-task.json`, which sits in `$PI_CODING_AGENT_DIR` (default `~/.pi/agent`). The template fills in `command`, `cwd` and `timeoutSeconds`; an explicit field on this call wins. An unknown name is rejected with the names that do exist.", }), ), name: Type.Optional( Type.String({ description: "Short purpose of the task, not its command: why it runs, in a few words the panel can show. Example: `为 CI 生成 changelog`. Optional; without it the task falls back to a label derived from the command.", }), ), timeoutSeconds: Type.Optional( Type.Number({ description: "Optional runtime cap in seconds. When it passes, the task is stopped with kill reason `timeout`; without it the task runs until it ends or is stopped.", }), ), shell: Type.Optional( Type.Union( [Type.Literal("default"), Type.Literal("cmd"), Type.Literal("bash"), Type.Literal("sh")], { description: "Shell for this call: `default` follows the configured shell, the others name one. Windows has `cmd` and `bash`, POSIX has `bash` and `sh`; anything else is rejected. Syntax is not translated: in cmd `&` runs the next command in turn, in bash it backgrounds the left side, so use `;` or `&&` there.", }, ), ), cwd: Type.Optional( Type.String({ description: "Directory the command runs in. A relative path is resolved against the session's working directory; the resolved absolute path is kept in the task record and shown by the panel and pretty_task_bg_status. The directory must already exist.", }), ), env: Type.Optional( Type.Record(Type.String(), Type.String(), { description: "Environment variables for this command only, merged over the extension's environment for the child. An empty string blanks a variable. Neither names nor values are written to the task record or printed by any tool.", }), ), after: Type.Optional( Type.String({ description: "Queue this command behind a task instead of starting it now. Pass a task id to put it behind that task, or a chain id (`ch-…`) to add it to that queue, even while it runs. The step is recorded at once as `waiting` and starts only after the step ahead ended with exit 0; a step that fails leaves the ones behind it `skipped`. Only process tasks and chains can be queued behind.", }), ), }); const StatusParameters = Type.Object({ id: Type.Optional( Type.String({ description: "Task or chain id to describe. Omit it to list the session's roots: its chains and the tasks that belong to no chain. A step or a loop fire answers by its own id, but is not a row of that list.", }), ), full: Type.Optional( Type.Boolean({ description: "Show the untruncated record, including the whole command." }), ), }); const LogsParameters = Type.Object({ id: Type.String({ description: "Task id to read output from." }), lines: Type.Optional( Type.Number({ description: "How many trailing lines to return. Defaults to 50." }), ), full: Type.Optional( Type.Boolean({ description: "Return the whole output file instead of a tail." }), ), follow: Type.Optional( Type.Boolean({ description: "Return only the output appended since this task's previous follow call in this session, waiting for new bytes instead of repeating what was already shown. `lines` and `full` do not apply. The answer says when the task has finished and nothing more will arrive.", }), ), timeoutSeconds: Type.Optional( Type.Number({ description: "With `follow`, how long to wait for new bytes before answering an empty delta. Defaults to 10 seconds; the longest single read is 60.", }), ), }); const KillParameters = Type.Object({ id: Type.String({ description: "Task or chain id to stop, with everything its command started. Stopping a chain stops the step at its cursor and marks the steps behind it `stopped`, so they never run.", }), }); const WaitParameters = Type.Object({ id: Type.String({ description: "Task id to wait for." }), timeoutSeconds: Type.Optional( Type.Number({ description: "How long to wait before returning the still-running task. Defaults to 60 seconds and is capped at 600. A timeout is not an error.", }), ), }); const GrepParameters = Type.Object({ id: Type.String({ description: "Task id whose output to search." }), pattern: Type.String({ description: "Plain text to look for, matched as a substring of a single line. Not a regular expression: `.` and `*` are ordinary characters. Case is ignored unless `ignoreCase` is false.", }), ignoreCase: Type.Optional( Type.Boolean({ description: "Match whatever the case. Defaults to true; pass false for an exact-case search.", }), ), maxMatches: Type.Optional( Type.Number({ description: `How many matching lines to return at most. Defaults to ${String(DEFAULT_SEARCH_MATCHES)}, never more than ${String(MAX_SEARCH_MATCHES)}.`, }), ), }); const DEFAULT_LOG_LINES = 50; const MAX_LOG_LINES = 2000; /** * `full` reads a much larger window than a tail, but still a window: the output * cap bounds the file (20 MiB unless configured), and this bound keeps one call * from reading all of it into memory. */ const FULL_MAX_BYTES = 4 * 1024 * 1024; const COMMAND_PREVIEW_LENGTH = 80; /** * One `pretty_task_bg_grep` answer is capped as a whole — header, matching lines and the * trailer together — so a noisy pattern cannot flood the context. The trailer is * paid for before the search runs, because its length decides how much room the * match list gets. */ const GREP_RESULT_BYTES = DEFAULT_SEARCH_BYTES; const GREP_TRAILER_BYTES = 48; /** Characters of the pattern the header and the verdict quote back at most. */ const PATTERN_PREVIEW_LENGTH = 120; function scopeOf(ctx: ExtensionToolContext): TaskScope { return { cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId() }; } function text(content: string): AgentToolResult> { return { content: [{ type: "text", text: content }], details: {} }; } /** `1 line`, `40 lines`: a line count as an answer reads it. */ function lineCount(lines: number): string { return `${String(lines)} ${lines === 1 ? "line" : "lines"}`; } /** * The pattern as an answer echoes it. A long pattern would otherwise be quoted * back in full and spend the byte budget the matching lines need — the caller * already knows what it asked for; `details` still carries it whole. */ function patternPreview(pattern: string): string { const quoted = JSON.stringify(pattern); return quoted.length <= PATTERN_PREVIEW_LENGTH ? quoted : `${quoted.slice(0, PATTERN_PREVIEW_LENGTH)}…`; } /** One task as a labelled block, the shape both `pretty_task_bg_run` and `pretty_task_bg_status` return. */ export function describeTask(view: ProcessTaskView, options: { full?: boolean } = {}): string { const { task } = view; const lines = [ `name: ${task.name}`, `id: ${task.id}`, `kind: ${task.kind}`, `status: ${task.status}`, `elapsed: ${formatDuration(view.elapsedMs)}`, `output: ${formatBytes(view.outputBytes)}`, `output file: ${task.outputPath}`, `cwd: ${task.cwd}`, `command: ${options.full === true ? task.command : commandPreview(task.command, COMMAND_PREVIEW_LENGTH)}`, ]; if (task.exitCode !== undefined && task.exitCode !== null) { lines.push(`exit code: ${String(task.exitCode)}`); } if (task.error !== undefined) lines.push(`error: ${task.error}`); if (task.killReason !== undefined) lines.push(`kill reason: ${task.killReason}`); return lines.join("\n"); } /** What a tool reports about one task, in a shape the caller can inspect. */ function taskDetails(view: ProcessTaskView) { return { id: view.task.id, name: view.task.name, kind: view.task.kind, status: view.task.status, elapsedMs: view.elapsedMs, outputBytes: view.outputBytes, pid: view.task.pid, exitCode: view.task.exitCode, parentId: view.task.parentId, command: view.task.command, cwd: view.task.cwd, outputPath: view.task.outputPath, killReason: view.task.killReason, error: view.task.error, }; } /** One step of a chain as a single row: its own record, condensed to what matters. */ function stepLine(step: ProcessTaskView, current: boolean): string { const { task } = step; const parts = [`${task.id} (${task.name})`, task.status]; if (task.exitCode !== undefined && task.exitCode !== null) parts.push(`exit ${String(task.exitCode)}`); if (task.killReason !== undefined) parts.push(`kill reason ${task.killReason}`); if (task.error !== undefined) parts.push(task.error); return `${current ? "→ " : " "}${parts.join(" · ")}`; } /** * A chain as a labelled block, its steps read from their own records: the queue * holds ids, so the only honest way to show a step's outcome is to ask the step * (ADR-0013). The cursor marks the step whose turn it is. */ export function describeChain( view: ChainTaskView, steps: readonly (ProcessTaskView | undefined)[], ): string { const { task } = view; const lines = [ `name: ${task.name}`, `id: ${task.id}`, `kind: chain`, `status: ${task.status}`, `elapsed: ${formatDuration(view.elapsedMs)}`, `steps: ${String(task.steps.length)} · cursor ${String(Math.min(task.cursor, task.steps.length))}/${String(task.steps.length)}`, ]; if (task.error !== undefined) lines.push(`error: ${task.error}`); if (task.killReason !== undefined) lines.push(`kill reason: ${task.killReason}`); steps.forEach((step, index) => { lines.push( step === undefined ? ` ${task.steps[index] ?? ""} (missing from this session)` : stepLine(step, index === task.cursor && task.status === "running"), ); }); return lines.join("\n"); } /** What a tool reports about one chain: the queue, plus each step's own record. */ function chainDetails(view: ChainTaskView, steps: readonly (ProcessTaskView | undefined)[]) { return { id: view.task.id, name: view.task.name, kind: view.task.kind, status: view.task.status, elapsedMs: view.elapsedMs, cursor: view.task.cursor, steps: view.task.steps, error: view.task.error, killReason: view.task.killReason, stepRecords: steps.map((step) => (step === undefined ? undefined : taskDetails(step))), }; } /** * Read by the model, so it has to say plainly why a freshly written template is * not in the list yet: the file is read once at load, not per call. */ /** * One task as the text a model reads and the details a caller inspects, built in * one place: the two are renderings of the same view, and written apart a field * added to a task lands in one and is forgotten in the other. */ function taskReport(view: ProcessTaskView, options: { full?: boolean } = {}) { return { content: [{ type: "text" as const, text: describeTask(view, options) }], details: taskDetails(view), }; } /** The same pairing for a queue: the block, plus each step's own record. */ function chainReport(view: ChainTaskView, steps: readonly (ProcessTaskView | undefined)[]) { return { content: [{ type: "text" as const, text: describeChain(view, steps) }], details: chainDetails(view, steps), }; } const RELOAD_NOTE = "Templates are read when the extension loads, so a file edited during this session applies only after /reload or a new session."; /** * The tool description carries the template names, because an agent cannot read * `.pi/pretty-task.json` on its own: without this line the names are only * discovered by failing a call. The budget keeps the description short enough * to stay in a model's attention even with a large template file. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ function runDescription(templates: ReadonlyMap): string { const base = "Run a shell command in the background and return a task id at once, without waiting for the command to finish. stdout and stderr are captured together in one output file. With `after`, it queues behind a task or chain instead."; // pi-lens-ignore: no-sort-without-comparator -- template names are plain words and the default string order is the intended one const names = [...templates.keys()].sort(); if (names.length === 0) { return `${base} No command templates are configured, so \`template\` is rejected. ${RELOAD_NOTE}`; } // Three shapes, cheapest that still fits: every name with its command, then names // alone, then as many names as the budget holds. The description must not grow // with the file, or a large `pretty-task.json` would bloat every request. const entries = names.map( (name) => `${name} (${commandHint(templates.get(name)?.command ?? "")})`, ); const list = withinBudget(entries, TEMPLATE_BUDGET) ?? withinBudget(names, TEMPLATE_BUDGET) ?? clipped(names, TEMPLATE_BUDGET); return `${base} Command templates available here: ${list}. ${RELOAD_NOTE}`; } /** Characters the template list may take in the description, commands included. */ const TEMPLATE_BUDGET = 300; /** The whole list, or nothing when it does not fit. */ function withinBudget(parts: readonly string[], budget: number): string | undefined { const shown: string[] = []; let room = budget; for (const part of parts) { if (part.length > room) return undefined; shown.push(part); room -= part.length + 2; } return shown.join(", "); } /** As many parts as fit, with an ellipsis standing for the rest. */ function clipped(parts: readonly string[], budget: number): string { const shown: string[] = []; let room = budget; for (const part of parts) { if (part.length + 1 > room) break; shown.push(part); room -= part.length + 2; } return `${shown.join(", ")}…`; } /** One template's command on a single line, short enough to sit in a sentence. */ function commandHint(command: string): string { const flat = command.replace(/\s+/g, " ").trim(); const room = 60; return flat.length <= room ? flat : `${flat.slice(0, room - 1)}…`; } /** The process-task tools, bound to one store, this session's templates and the queue. */ /** What an id names in this session: a process task, or the queue that holds steps. */ type Address = | { readonly kind: "task"; readonly view: ProcessTaskView } | { readonly kind: "chain"; readonly view: ChainTaskView }; /** * The sentence a tool answers a miss with. One copy, because seven copies of it * are seven chances for the tools to describe the same absence differently. */ function missing(id: string): string { return `No background task with id ${id} in this session.`; } /** * The known template names for an unknown-template error: all of them, or the first * ones and the total. The error is read in context too, so it never dumps a large file. */ function templateList(known: readonly string[]): string { if (known.length === 0) return "(none)"; const shown = known.slice(0, 20).map((name) => JSON.stringify(name)); if (known.length <= 20) return shown.join(", "); return `${shown.join(", ")}, … (${String(known.length)} in total)`; } /** How a follow describes its wait: finished, silent, or how much arrived. */ function followNote(followed: FollowTaskResult, windowMs: number): string { if (followed.finished) return "the task has finished; nothing more will arrive"; if (followed.timedOut) { return `no new output in ${formatDuration(windowMs)}; the task is still running`; } return `followed ${formatBytes(followed.deltaBytes)}`; } /** The first line of a wait: ended, cancelled, or still running when the wait ran out. */ function waitHeadline(id: string, result: WaitTaskResult): string { const { view, waited, cancelled } = result; if (waited) { return `Background task ${id} (${view.task.name}) ended as ${view.task.status} after ${formatDuration(view.elapsedMs)}.`; } if (cancelled) { return `The wait for ${id} (${view.task.name}) was cancelled; the task is still ${view.task.status} and was left running. Read it with pretty_task_bg_status id=${id}.`; } return `Background task ${id} (${view.task.name}) is still running after ${formatDuration(view.elapsedMs)}; it did not finish within the wait.`; } /** The first line of a chain stop, one wording per outcome. */ function chainStopHeadline(id: string, stopped: StopChainResult): string { const name = stopped.view.task.name; if (stopped.outcome === "stopped") { // The running step is named only when one was actually stopped. const step = stopped.step === undefined ? "" : `; its running step ${stopped.step.task.id} was stopped`; return `Stopped chain ${id} (${name})${step} and the steps behind it will not run.`; } if (stopped.outcome === "tree-survived") { return `Chain ${id} (${name}) was ended and the steps behind it will not run, but its running step ${stopped.step?.task.id ?? "at the cursor"} could not be stopped: ${stopped.detail ?? "its processes are still running"}.`; } return `Chain ${id} had already finished (${stopped.view.task.status}); nothing was signalled.`; } /** The first line of a stop: killed, already ended, or outlived the signal. */ function stopHeadline(id: string, result: StopTaskResult): string { const name = result.view.task.name; if (result.outcome === "killed") { return `Stopped background task ${id} (${name}) in ${formatDuration(result.tookMs)}.`; } if (result.outcome === "already-finished") { return `Background task ${id} had already finished (${result.view.task.status}); nothing was signalled.`; } return `Background task ${id} could not be stopped: ${result.detail ?? "its processes are still running"}.`; } export function processTaskTools( tasks: ProcessTasks, chains: ChainTasks, templates: ReadonlyMap = new Map(), ): ToolDefinition[] { /** * What an id names here, decided once. Every tool that takes an id asks this * instead of guessing the same way twice, so a chain is found the same way by * all of them and "there is no such task" is one sentence. */ const address = async (scope: TaskScope, id: string): Promise
=> { const task = await tasks.get(scope, id); if (task !== undefined) return { kind: "task", view: task }; const chain = await chains.get(scope, id); return chain === undefined ? undefined : { kind: "chain", view: chain }; }; /** A chain's steps, read through the process store: the queue holds ids, not copies. */ const stepViews = async ( scope: TaskScope, ids: readonly string[], ): Promise> => Promise.all(ids.map((id) => tasks.get(scope, id))); /** * What to say when output is asked of a chain. A chain spawns nothing, so the * honest answer is which step the question should have named. */ const chainOutputHint = (id: string, view: ChainTaskView): string => { const current = view.task.steps[view.task.cursor]; return current === undefined ? `Task ${id} is a chain and writes no output of its own: every step has its own. A chain spawns nothing, so read a step's output by its id.` : `Task ${id} is a chain and writes no output of its own: every step has its own. Its current step is ${current}; read that with its own id, or pretty_task_bg_status id=${id} for the queue.`; }; const run: ToolDefinition = { name: "pretty_task_bg_run", label: "Run in background", description: runDescription(templates), parameters: RunParameters, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { // Resolve the template before any store call: an unknown name must not // leave a task behind, and an explicit field on the call wins over the // template's value. `env` is deliberately never templated. const template = params.template === undefined ? undefined : templates.get(params.template); if (params.template !== undefined && template === undefined) { // pi-lens-ignore: no-sort-without-comparator -- template names are plain words and the default string order is the intended one const known = [...templates.keys()].sort(); const list = templateList(known); return text( `Unknown template ${JSON.stringify(params.template)}. Known templates: ${list}. The task was not started. ${RELOAD_NOTE}`, ); } const command = params.command ?? template?.command; if (command === undefined) { return text("Either command or template is required. The task was not started."); } const workingDirectory = params.cwd ?? template?.cwd; const timeoutSeconds = params.timeoutSeconds ?? template?.timeoutSeconds; // A bad runtime is reported before anything is spawned: a task that can // never be capped is worse than a rejected request. let timeoutMs: number | undefined; if (timeoutSeconds !== undefined) { try { timeoutMs = parseTimeoutSeconds(timeoutSeconds); } catch (error) { const reason = error instanceof Error ? error.message : String(error); return text(`${reason} The task was not started.`); } } let task: ProcessTask; if (params.after !== undefined) { // Queueing is the same call with a place to stand in a line: nothing is // spawned, the step is a record from the start, and its chain decides when // its turn comes (ADR-0013). const anchor = params.after.trim(); if (anchor.length === 0) { return text( "Pass the id of the task or chain to queue behind; pretty_task_bg_status lists the ids of this session. The task was not started.", ); } let queued: QueuedStep; try { queued = await chains.enqueue(scopeOf(ctx), anchor, { command, ...(params.name === undefined ? {} : { name: params.name }), ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(params.shell === undefined ? {} : { shell: params.shell }), ...(workingDirectory === undefined ? {} : { workingDirectory }), ...(params.env === undefined ? {} : { env: params.env }), }); } catch (error) { // A task of another kind, a chain that already ended, or an unknown id: // the store refuses before any record is written. const reason = error instanceof Error ? error.message : String(error); return text(`${reason} The task was not started.`); } const view = (await tasks.get(scopeOf(ctx), queued.step.id)) ?? { task: queued.step, elapsedMs: 0, outputBytes: queued.step.outputBytes, }; const position = queued.chain.steps.indexOf(queued.step.id) + 1; const where = `step ${String(position)} of ${String(queued.chain.steps.length)} in ${queued.chain.id} (${queued.chain.name})`; const headline = view.task.status === "waiting" ? `Queued ${queued.step.id} (${queued.step.name}) as ${where}; it starts when the step ahead ends with exit 0.` : `Queued ${queued.step.id} (${queued.step.name}) as ${where}; it is already ${view.task.status}.`; return { content: [ { type: "text", text: [ headline, "", describeTask(view), "", `Watch the queue with pretty_task_bg_status id=${queued.chain.id}; read this step with pretty_task_bg_logs id=${queued.step.id}.`, ].join("\n"), }, ], details: { ...taskDetails(view), chainId: queued.chain.id, position }, }; } try { task = await tasks.start({ ...scopeOf(ctx), command, ...(params.name === undefined ? {} : { name: params.name }), ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(params.shell === undefined ? {} : { shell: params.shell }), ...(workingDirectory === undefined ? {} : { workingDirectory }), ...(params.env === undefined ? {} : { env: params.env }), }); } catch (error) { // A shell this call cannot have, a shell that is not installed, or a // directory that cannot be used: the store throws before a record is // written, so the turn gets the reason and no task. const reason = error instanceof Error ? error.message : String(error); return text(`${reason} The task was not started.`); } const view = (await tasks.get(scopeOf(ctx), task.id)) ?? { task, elapsedMs: 0, outputBytes: task.outputBytes, }; return { content: [ { type: "text", text: [ `Started background task ${task.id} (${task.name}).`, "", describeTask(view), "", `Read its output with pretty_task_bg_logs id=${task.id}, search it with pretty_task_bg_grep id=${task.id}, check it with pretty_task_bg_status id=${task.id}.`, ].join("\n"), }, ], details: taskDetails(view), }; }, }; const status: ToolDefinition = { name: "pretty_task_bg_status", label: "Background task status", description: "Show background tasks of this session: status, elapsed time and output size. Pass an id for one task, or omit it to list them all.", parameters: StatusParameters, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const scope = scopeOf(ctx); const wantedId = params.id?.trim(); const full = params.full === true; if (wantedId !== undefined && wantedId.length > 0) { // A chain is a task of this session too. Asking for it shows the queue with // each step's own record, which is the only place a step's outcome lives. const found = await address(scope, wantedId); if (found === undefined) return text(missing(wantedId)); return found.kind === "task" ? taskReport(found.view, { full }) : chainReport(found.view, await stepViews(scope, found.view.task.steps)); } const [roots, queues] = await Promise.all([tasks.list(scope), chains.list(scope)]); if (roots.length === 0 && queues.length === 0) { return { content: [ { type: "text", text: "No background tasks in this session yet. Start one with pretty_task_bg_run.", }, ], details: { tasks: [] }, }; } // A step and a fire are records, not rows (ADR-0014): they appear inside the // queue that owns them, never beside it. const blocks: string[] = []; const chainRows: unknown[] = []; for (const chain of queues) { const steps = await stepViews(scope, chain.task.steps); blocks.push(describeChain(chain, steps)); chainRows.push(chainDetails(chain, steps)); } for (const view of roots) blocks.push(describeTask(view, { full })); return { content: [{ type: "text", text: blocks.join("\n\n") }], details: { tasks: [...chainRows, ...roots.map((view) => taskDetails(view))] }, }; }, }; const logs: ToolDefinition = { name: "pretty_task_bg_logs", label: "Background task output", description: "Return the tail of a background task's output, stdout and stderr in emission order. Ask again while it runs to see more, or pass `follow` to get only what arrived since the previous follow call.", parameters: LogsParameters, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { if (params.follow === true) { const windowMs = parseFollowSeconds(params.timeoutSeconds); const followed = await tasks.follow(scopeOf(ctx), params.id.trim(), windowMs); if (followed === undefined) { const chain = await chains.get(scopeOf(ctx), params.id.trim()); return text( chain === undefined ? missing(params.id) : chainOutputHint(chain.task.id, chain), ); } const { view } = followed; const note = followNote(followed, windowMs); const header = [ `name: ${view.task.name} · ${view.task.id} · ${view.task.kind} · ${view.task.status}`, `elapsed ${formatDuration(view.elapsedMs)} · output ${formatBytes(view.outputBytes)} · follow`, note, ].join("\n"); const delta = followed.delta.length > 0 ? followed.delta : "(no new output)"; return { content: [{ type: "text", text: `${header}\n\n${delta}` }], details: { id: view.task.id, status: view.task.status, follow: true, from: followed.from, offset: followed.offset, deltaBytes: followed.deltaBytes, finished: followed.finished, timedOut: followed.timedOut, }, }; } const full = params.full === true; const wanted = Math.floor(params.lines ?? DEFAULT_LOG_LINES); const lines = Number.isFinite(wanted) ? Math.min(MAX_LOG_LINES, Math.max(1, wanted)) : DEFAULT_LOG_LINES; const found = await tasks.logs(scopeOf(ctx), params.id.trim(), { lines: full ? Number.MAX_SAFE_INTEGER : lines, ...(full ? { maxBytes: FULL_MAX_BYTES } : {}), }); if (found === undefined) { const chain = await chains.get(scopeOf(ctx), params.id.trim()); return text( chain === undefined ? missing(params.id) : chainOutputHint(chain.task.id, chain), ); } const { view, tail } = found; const header = [ `name: ${view.task.name} · ${view.task.id} · ${view.task.kind} · ${view.task.status}`, `elapsed ${formatDuration(view.elapsedMs)} · output ${formatBytes(view.outputBytes)}`, // The output is the story here, so the reason it stopped belongs in the // same header as the status instead of being a line the reader must ask for. ...(view.task.killReason === undefined ? [] : [`kill reason: ${view.task.killReason}`]), ].join("\n"); const note = tail.truncated ? `\n(showing the last ${String(tail.lines)} lines)` : ""; const body = tail.text.length > 0 ? tail.text : "(no output yet)"; return { content: [{ type: "text", text: `${header}${note}\n\n${body}` }], details: { id: view.task.id, status: view.task.status, lines: tail.lines, truncated: tail.truncated, outputBytes: view.outputBytes, killReason: view.task.killReason, }, }; }, }; const wait: ToolDefinition = { name: "pretty_task_bg_wait", label: "Wait for a background task", description: "Wait for a background task to end, then return its final view. A timeout is not an error: it returns the running view with waited: false. Cancelling the call (Esc) ends the wait at once and leaves the task running.", parameters: WaitParameters, // The abort signal is honoured: an Esc must release the turn instead of // holding it until the deadline. The task itself is never touched. async execute(_toolCallId, params, signal, _onUpdate, ctx) { const id = params.id.trim(); if (id.length === 0) { return text( "Pass the id of the task to wait for; pretty_task_bg_status lists the ids of this session.", ); } // A wait that cannot be counted would hold the turn forever, so a bad // bound is reported before the store is called. let timeoutMs: number; try { timeoutMs = parseWaitSeconds(params.timeoutSeconds); } catch (error) { const reason = error instanceof Error ? error.message : String(error); return text(`${reason} Nothing was waited for.`); } const result = await tasks.wait(scopeOf(ctx), id, timeoutMs, signal); if (result === undefined) { // Waiting on a chain would wait on the wrong thing: its steps come and go. const chain = await chains.get(scopeOf(ctx), id); return text( chain === undefined ? missing(id) : `Task ${id} is a chain; wait for its step instead. pretty_task_bg_status id=${id} names the step at the cursor.`, ); } const { view, waited, cancelled } = result; const headline = waitHeadline(id, result); return { content: [{ type: "text", text: [headline, "", describeTask(view)].join("\n") }], details: { ...taskDetails(view), waited, cancelled }, }; }, }; const grep: ToolDefinition = { name: "pretty_task_bg_grep", label: "Search background task output", description: "Search a background task's whole output file for a plain substring and return only the matching lines, each prefixed with its line number. Case is ignored unless `ignoreCase` is false. The answer is bounded in lines and bytes, and it says how many matches it left out.", parameters: GrepParameters, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const id = params.id.trim(); if (id.length === 0) { return text( "Pass the id of the task to search; pretty_task_bg_status lists the ids of this session.", ); } if (params.pattern.length === 0) { return text( "Pass the text to look for. pretty_task_bg_grep matches a plain substring, and an empty one would match every line.", ); } const found = await address(scopeOf(ctx), id); if (found === undefined) return text(missing(id)); if (found.kind === "chain") return text(chainOutputHint(found.view.task.id, found.view)); const view = found.view; const ignoreCase = params.ignoreCase !== false; const maxMatches = clampSearchMatches(params.maxMatches); const header = [ `name: ${view.task.name} · ${view.task.id} · ${view.task.kind} · ${view.task.status}`, `elapsed ${formatDuration(view.elapsedMs)} · output ${formatBytes(view.outputBytes)} · ${ ignoreCase ? "case-insensitive" : "case-sensitive" } search for ${patternPreview(params.pattern)}`, ].join("\n"); // The cap covers the whole answer, so the header and the trailer are paid // for first and only what is left goes to the match list. const room = GREP_RESULT_BYTES - Buffer.byteLength(header) - GREP_TRAILER_BYTES; const search = await searchOutputFile(view.task.outputPath, { pattern: params.pattern, ignoreCase, maxMatches, maxBytes: Math.max(1, room), // Every caller in production reads the host's output files, so the host // is the fallback encoding. A test needing another one calls the reader. platform: process.platform, }); const details = { id: view.task.id, status: view.task.status, pattern: params.pattern, ignoreCase, maxMatches, matches: search.matches.length, total: search.total, omitted: search.omitted, scannedLines: search.scannedLines, clipped: search.clipped, outputBytes: view.outputBytes, }; const body = search.matches.map((match) => `${String(match.line)}: ${match.text}`).join("\n"); if (body.length === 0) { // An empty string would read as "nothing to say"; a search owes a verdict. // The two verdicts differ: nothing matched, or the header ate the budget. const verdict = search.total === 0 ? `No matches for ${patternPreview(params.pattern)} in ${lineCount(search.scannedLines)} of output.` : `Found ${lineCount(search.total)} matching lines, but none fit in this answer's byte budget.`; return { content: [{ type: "text", text: `${header}\n\n${verdict}` }], details, }; } const trailer = search.omitted > 0 ? `… ${String(search.omitted)} more matches` : ""; return { content: [ { type: "text", text: [header, "", body, ...(trailer.length > 0 ? ["", trailer] : [])].join("\n"), }, ], details, }; }, }; const kill: ToolDefinition = { name: "pretty_task_bg_kill", label: "Stop a background task", description: "Stop a background task and every process its command started: a polite signal, a short grace period, then force. A task that already finished is reported as such instead of failing.", parameters: KillParameters, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const id = params.id.trim(); if (id.length === 0) { return text( "Pass the id of the task to stop; pretty_task_bg_status lists the ids of this session.", ); } const scope = scopeOf(ctx); const found = await address(scope, id); if (found === undefined) return text(missing(id)); // A chain is stopped as a queue, not as a process: the step at the cursor is // killed and the ones behind it are told they will never run (ADR-0013). if (found.kind === "chain") { const stopped = await chains.stop(scope, id); if (stopped === undefined) return text(missing(id)); const steps = await stepViews(scope, stopped.view.task.steps); const headline = chainStopHeadline(id, stopped); return { content: [ { type: "text", text: [headline, "", describeChain(stopped.view, steps)].join("\n"), }, ], details: { ...chainDetails(stopped.view, steps), stopOutcome: stopped.outcome, }, }; } const result = await tasks.stop(scope, id); if (result === undefined) return text(missing(id)); const headline = stopHeadline(id, result); return { content: [{ type: "text", text: [headline, "", describeTask(result.view)].join("\n") }], details: { ...taskDetails(result.view), stopOutcome: result.outcome, tookMs: result.tookMs, }, }; }, }; return [run, status, logs, grep, kill, wait]; }