@sema-agent/core
Version:
Stateless, task-oriented AI agent core
868 lines • 58.1 kB
JavaScript
import { randomBytes } from "node:crypto";
import { Type } from "typebox";
import { defineTool, errorResult } from "../../core/tools.js";
import { backgroundLifecycleOf, bashBackgroundUnavailable, modelShellExec, mountedModelShellOf, startedShellDeclaration } from "./bash-model-shell.js";
import { callOccupant } from "../../core/task-registry-shared.js";
import { markTruncated, RollingTailBuffer } from "../../core/exec-output-tail.js";
import { BACKGROUND_START_FAILURE_KINDS, createBackgroundOutputFile, envDeclaresRetain, retainsBackgroundProcesses } from "../../core/background-shell.js";
import { delimitUntrusted } from "../../core/untrusted-text.js";
import { resolveImageProcessor } from "../../core/image-downsample.js";
import { isDriveAbsoluteSpelling, shellDriveSpellingOf, withinAnyRoot } from "./safety.js";
import { admitImageBytes, sniffImageMime } from "../../core/image-admission.js";
import { isDeadCwd, diagnoseDeadCwd } from "./dead-cwd.js";
import { boundaryIsTheSandbox, hasDestroy, isDeploymentEnvCode, isIsolated } from "../../core/remote-env.js";
import { ghRateLimitHint } from "./gh-rate-limit.js";
import { backgroundLifetimeNote, backgroundOutputFileNote, ONE_SHOT_BACKGROUND_COMMAND_NOTE } from "./fs-bash-background-text.js";
import { admitsBackgroundLaunch, resolveCompletionSink } from "../../core/task-notification.js";
import { resolveBashTimeoutCaps, bashTimeoutCapsSec, bashTimeoutArgRefusal, bashTimeoutParamDescription, bashMaxOutputChars, clipShellOutput, writeShellOverflowFile, shellRecoveryHint, zeroOutputSentence, targetUnavailableCard, targetUnavailableSentence, bashFailureCard, CWD_SENTINEL, stripCwdSentinel, } from "./fs-shared.js";
import { envErrorDetail, failureMessageOnce } from "./env-error-detail.js";
import { shellQuote } from "./search.js";
import { isExtensionCallId } from "../../core/extension-call-id.js";
import { bashClassifyDefaultAllow, BASH_READONLY_DEFAULT_ALLOW, classifyBoundedReadonlyPollLoopDetailed, classifyCompoundReadonlyFacts, parseLeadingCommandName } from "./bash-readonly-classifier.js";
import { probeRefusalSentence, readOnlyShellVerdictIn } from "../../core/read-only-shell.js";
import { lapsedBy, sandboxRefusalText, sandboxResultNote } from "../../core/command-sandbox.js";
import { toolFace } from "../../core/tool-catalog-entries.js";
import { SHELL_LEX_DIALECT, argvOf, assignedWords, expansionHidesRun, expansionsInHeredocBody, lexShell, subscriptHidesRun } from "../../shell/lex.js";
import { arithmeticAssignedNames } from "./shell-read-bindings.js";
import { thrownText } from "../../core/thrown-value.js";
import { patternKillRefusal } from "./pattern-kill-guard.js";
import { callScopeOf } from "../../core/isolation-scope.js";
import { execFailureBreachLedger, readExecFailure, withOutcomeNote } from "../../core/exec-outcome.js";
import { backgroundFailureWord, capturedBeforeFailure, envRefusedLead, outcomeUnknownResult, stateNotStartedResult, stateWhileRunning } from "./bash-failure-output.js";
import { findActionsOf, findWordOf } from "./find-actions.js";
import { programRow } from "./program-read-model.js";
function shellCommandOf(args) {
const command = args?.command;
return typeof command === "string" ? command : undefined;
}
const CONCURRENT_READERS = new Set(BASH_READONLY_DEFAULT_ALLOW);
function readOnlyFaceRefusal(shell, command, allow) {
const parsed = parseLeadingCommandName(command);
const verdict = "reject" in parsed ? { readOnly: false, reason: parsed.reject } : readOnlyShellVerdictIn(shell, command, { readers: allow });
return verdict.readOnly ? undefined : verdict.reason;
}
function isBackgroundShellCall(args) {
return args?.run_in_background === true;
}
export function bashReversibilityProbe(allow, boundary) {
return bashReversibilityProbeIn(SHELL_LEX_DIALECT, allow, boundary);
}
export function bashReversibilityProbeIn(shell, allow, boundary) {
const allowSet = new Set(allow ?? bashClassifyDefaultAllow());
return (args) => {
const command = shellCommandOf(args);
if (command === undefined)
return { reversible: false };
if (isBackgroundShellCall(args))
return { reversible: false };
const home = typeof boundary === "function" ? boundary() : boundary;
const fold = home?.homeDir !== undefined ? { homeDir: home.homeDir } : undefined;
const { reason, unlistedProgram } = classifyCompoundReadonlyFacts(shell, command, allowSet, fold);
if (reason === undefined)
return { reversible: true };
return classifyBoundedReadonlyPollLoopDetailed(shell, command, allowSet, fold).reason === undefined ? { reversible: true } : { reversible: false, reason: probeRefusalSentence(command, reason, unlistedProgram) };
};
}
export { FULL_SHELL_CONTRACT_ID } from "../../core/tool-catalog-entries.js";
const EXIT1_INTERPRETATION = {
grep: "No matches found",
rg: "No matches found",
egrep: "No matches found",
fgrep: "No matches found",
find: "Some directories were inaccessible",
diff: "Files differ",
test: "Condition is false",
"[": "Condition is false",
};
export function bashExitOneInterpretation(shell, command) {
const lexed = lexShell(shell, command);
if ("parseFailure" in lexed)
return undefined;
const last = [...lexed.segments].reverse().find((s) => s.tokens.length > 0);
const argv = last === undefined ? [] : argvOf(last);
let i = 0;
while (i < argv.length && argv[i].assignment?.bare === true && argv[i].atCommandPosition)
i++;
const tokens = argv.map((w) => w.folded);
const name = tokens[i]?.split("/").pop() ?? "";
if (name === "git") {
for (let j = i + 1; j < tokens.length; j++) {
const t = tokens[j];
if (t.startsWith("-")) {
if (t === "-C" || t === "-c")
j++;
continue;
}
if (t === "grep")
return "No matches found";
if (t === "diff")
return "Files differ";
return undefined;
}
return undefined;
}
if (name === "find") {
const row = programRow("find");
const words = argv.slice(i + 1).map(findWordOf);
return row !== undefined && !words.some((w) => w.rewritten === true) && findActionsOf(row, words).actions.length === 0 ? EXIT1_INTERPRETATION.find : undefined;
}
return EXIT1_INTERPRETATION[name];
}
async function dataUriImageFromStdout(stdout, imageProcessor) {
const t = stdout.trim();
const m = /^data:image\/[a-z0-9.+_-]+;base64,([A-Za-z0-9+/=\s]+)$/i.exec(t);
if (!m)
return undefined;
const bytes = Buffer.from(m[1].replace(/\s/g, ""), "base64");
const mime = sniffImageMime(bytes);
if (mime === undefined)
return undefined;
const admitted = await admitImageBytes(bytes, mime, await resolveImageProcessor(imageProcessor));
return admitted.ok ? admitted.block : undefined;
}
const AUTO_BACKGROUND_BLOCKED_FIRST_WORDS = new Set(["sleep"]);
function pastAutoBackgroundWrapperPrefixes(words) {
const folded = words.map((w) => w.folded);
let i = 0;
for (;;) {
const w = folded[i];
let next = i;
if (words[i]?.assignment?.bare === true && words[i].atCommandPosition && words[i].assignment.value.raw !== "")
next = i + 1;
else if (w === "time" || w === "nohup" || w === "command" || w === "builtin" || w === "noglob")
next = i + 1;
else if (w === "timeout") {
let j = i + 1;
while (/^-[A-Za-z]/.test(folded[j] ?? ""))
j++;
if (/^\d+(?:\.\d+)?[smhd]?$/.test(folded[j] ?? ""))
next = j + 1;
}
else if (w === "nice") {
next = i + 1;
if (folded[next] === "-n" && /^-?\d+$/.test(folded[next + 1] ?? ""))
next += 2;
else if (/^-n?-?\d+$/.test(folded[next] ?? ""))
next += 1;
}
else if (w === "stdbuf") {
let j = i + 1;
while (/^-[ioe]./.test(folded[j] ?? ""))
j++;
if (j > i + 1)
next = j;
}
if (next === i || next >= folded.length)
return words.slice(i);
i = next;
}
}
function commandBasename(token) {
const idx = token.lastIndexOf("/");
return idx === -1 ? token : token.slice(idx + 1);
}
const COMMAND_STRING_SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash"]);
function commandStringPayload(tokens) {
const word = commandBasename(tokens[0] ?? "");
if (word === "eval")
return tokens.slice(1).join(" ");
if (!COMMAND_STRING_SHELLS.has(word))
return undefined;
const flagIdx = tokens.findIndex((t, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(t));
return flagIdx === -1 ? undefined : tokens[flagIdx + 1];
}
const AUTO_BACKGROUND_MAX_WRAPPER_DEPTH = 3;
function arithmeticInFront(text, depth) {
return arithmeticAssignedNames(text).length > 0 || (expansionsInHeredocBody(text)?.some((x) => x.unresolved !== undefined || x.expansion.kind === "command" || (x.expansion.kind === "arithmetic" ? depth >= AUTO_BACKGROUND_MAX_WRAPPER_DEPTH || arithmeticInFront(x.expansion.body ?? "", depth + 1) : expansionHidesRun(x.expansion))) ?? true);
}
export function shouldAutoBackgroundCommand(command) {
return canAutoBackground(SHELL_LEX_DIALECT, command, 0);
}
function canAutoBackground(shell, command, depth) {
const lexed = lexShell(shell, command);
if ("parseFailure" in lexed)
return false;
const segments = lexed.segments;
const hidden = (e) => e !== undefined && e.kind !== "command" && e.kind !== "process" && e.kind !== "arithmetic" && expansionHidesRun(e);
const words = segments.flatMap((s) => s.tokens.flatMap((t) => (t.kind === "word" ? assignedWords(t) : t.kind === "redirect" && t.target !== undefined ? [t.target] : [])));
if (words.some((w) => w.unresolved === "parameter_text" || w.assignment?.form === "compound" || subscriptHidesRun(w) || w.expansions.some((p) => hidden(p.expansion))))
return false;
const heredocs = segments.flatMap((s) => s.tokens.flatMap((t) => (t.kind === "heredoc" && !t.quoted ? [expansionsInHeredocBody(t.body)] : [])));
if (heredocs.some((b) => b === undefined || b.some((x) => x.unresolved !== undefined || hidden(x.expansion))))
return false;
const arithmetic = [...words.flatMap((w) => w.expansions), ...heredocs.flatMap((b) => b ?? [])].flatMap((p) => (p.expansion?.kind === "arithmetic" ? [p.expansion.body ?? ""] : []));
const bodies = [...segments.flatMap((s) => s.substitutions), ...heredocs.flatMap((b) => (b ?? []).flatMap((x) => (x.expansion.kind === "command" ? [x.expansion.body ?? ""] : [])))].filter(((left) => (b) => { const k = left.indexOf(b); if (k < 0)
return true; left.splice(k, 1); return false; })([...arithmetic]));
if ((bodies.length > 0 && depth >= AUTO_BACKGROUND_MAX_WRAPPER_DEPTH) || bodies.some((b) => !canAutoBackground(shell, b, depth + 1)) || arithmetic.some((b) => arithmeticInFront(b, depth + 1)))
return false;
const runs = segments.map((s) => pastAutoBackgroundWrapperPrefixes(argvOf(s)).map((w) => w.folded)).filter((t) => t.length > 0);
if (runs.length === 0)
return true;
for (const tokens of runs) {
const word = commandBasename(tokens[0]);
if (word === "git")
return false;
if (depth < AUTO_BACKGROUND_MAX_WRAPPER_DEPTH) {
for (let i = 0; i < tokens.length; i++) {
const payload = commandStringPayload(tokens.slice(i));
if (payload !== undefined && payload.trim() !== "" && !canAutoBackground(shell, payload, depth + 1))
return false;
}
}
if (word === "xargs" && tokens.slice(1).some((t) => commandBasename(t) === "git"))
return false;
}
return !AUTO_BACKGROUND_BLOCKED_FIRST_WORDS.has(commandBasename(runs[0][0]));
}
function msTimeoutToRequestedSec(timeoutMs) {
if (timeoutMs === undefined || !Number.isFinite(timeoutMs))
return undefined;
return Math.max(1, Math.round(timeoutMs / 1000));
}
const TOOL_PROGRESS_BOUND = Object.freeze({ intervalMs: 1_000, tailLines: 20, tailMaxBytes: 16 * 1024 });
function lastLines(text, n) {
const body = text.endsWith("\n") ? text.slice(0, -1) : text;
const lines = body.split("\n");
return lines.length <= n ? body : lines.slice(-n).join("\n");
}
const EPILOGUE_HOLD_MAX_CHARS = 4096;
function createEpilogueFilter(marker) {
let held = "";
let inside = false;
return (chunk) => {
let buf = held + chunk;
held = "";
let out = "";
for (;;) {
if (inside) {
const close = buf.indexOf(marker);
if (close === -1)
break;
buf = buf.slice(close + marker.length);
inside = false;
continue;
}
const open = buf.indexOf(marker);
if (open === -1)
break;
out += buf.slice(0, open);
buf = buf.slice(open + marker.length);
inside = true;
}
if (inside) {
if (buf.length > EPILOGUE_HOLD_MAX_CHARS) {
inside = false;
return out + marker + buf;
}
held = buf;
return out;
}
for (let n = Math.min(marker.length - 1, buf.length); n > 0; n--) {
if (buf.endsWith(marker.slice(0, n))) {
held = buf.slice(buf.length - n);
return out + buf.slice(0, buf.length - n);
}
}
return out + buf;
};
}
function describeSafely(sink, body) {
if (sink === undefined)
return;
try {
const returned = sink(body);
if (typeof returned?.then === "function")
void returned.then(undefined, () => { });
}
catch {
}
}
function startLivenessTicks(onTick, filterStderr) {
const tail = new RollingTailBuffer(TOOL_PROGRESS_BOUND.tailMaxBytes);
const perStream = { stdout: new RollingTailBuffer(TOOL_PROGRESS_BOUND.tailMaxBytes), stderr: new RollingTailBuffer(TOOL_PROGRESS_BOUND.tailMaxBytes) };
let totalBytes = 0;
let totalLines = 0;
let cached;
const feedTo = (stream) => (chunk) => {
if (chunk === "")
return;
const bytes = Buffer.from(chunk, "utf8");
totalBytes += bytes.length;
totalLines += chunk.split("\n").length - 1;
tail.push(bytes);
stream.push(bytes);
};
const feedStdout = feedTo(perStream.stdout);
const feedStderr = feedTo(perStream.stderr);
const kept = (b) => {
const r = b.result();
return markTruncated(r.text, r.droppedBytes);
};
const describeTo = (t) => describeSafely(onTick, t);
const tick = () => {
if (totalBytes === 0) {
describeTo({});
return;
}
if (cached?.atBytes !== totalBytes)
cached = { atBytes: totalBytes, text: lastLines(tail.result().text, TOOL_PROGRESS_BOUND.tailLines) };
describeTo({ output: cached.text, totalLines, totalBytes });
};
const timer = setInterval(tick, TOOL_PROGRESS_BOUND.intervalMs);
timer.unref?.();
return {
onStdout: feedStdout,
onStderr: filterStderr === undefined ? feedStderr : (chunk) => feedStderr(filterStderr(chunk)),
stop: () => clearInterval(timer),
wrote: () => totalBytes > 0,
streamed: () => ({ stdout: kept(perStream.stdout), stderr: kept(perStream.stderr) }),
};
}
async function runShell(env, reading, cwd, toolName, command, timeoutSec, caps, signal, cwdRef, detach, readOnly, containmentRoots, onTick, readFloor, imageProcessor, commandSandbox, refusalTold, announce) {
const sandboxStart = commandSandbox?.start();
if (sandboxStart !== undefined && !sandboxStart.ok)
return { content: sandboxRefusalText(toolName, { by: "plan", reason: sandboxStart.reason }), details: { type: "bash", sandboxUnavailable: true }, isError: true };
const requestedSec = Math.max(1, Math.floor(timeoutSec ?? caps.defaultSec));
let timeout = Math.min(caps.maxSec, requestedSec);
const cappedByMaxTimeout = requestedSec > caps.maxSec;
const effectiveCwd = cwdRef ? cwdRef.current : cwd;
const cwdMarker = cwdRef ? `${CWD_SENTINEL}${randomBytes(8).toString("hex")}` : CWD_SENTINEL;
const toRun = cwdRef
? `eval ${shellQuote(command)}\n__cc_rc=$?\n{ set +vx; } 2>/dev/null\nprintf '%s%s%s' '${cwdMarker}' "$(pwd)" '${cwdMarker}' 1>&2\nexit $__cc_rc`
: command;
const execEnv = cwdRef ? { env: { PWD: effectiveCwd } } : undefined;
const live = onTick === undefined ? undefined : startLivenessTicks(onTick, cwdRef ? createEpilogueFilter(cwdMarker) : undefined);
let res;
try {
res = await modelShellExec(reading, toRun, readFloor, {
cwd: effectiveCwd,
timeout,
abortSignal: signal,
...execEnv,
...(live !== undefined ? { onStdout: live.onStdout, onStderr: live.onStderr } : {}),
...(sandboxStart?.ok === true && sandboxStart.sandbox !== undefined ? { sandbox: sandboxStart.sandbox } : {}),
...(detach
? {
detachSignal: detach.signal,
autoBackgroundOnTimeout: detach.autoBackgroundEligible === true,
}
: {}),
});
}
finally {
live?.stop();
}
if (!res.ok) {
const failure = res.error;
const reading = readExecFailure(failure, { wroteOutput: live?.wrote() === true });
if (reading.breach !== undefined && announce !== undefined)
announce.ledger.announce(announce.onNotice, env, { breach: reading.breach, code: failure.code, face: "exec", ...(announce.sessionId !== undefined ? { sessionId: announce.sessionId } : {}) });
const card = bashFailureCard(reading.word);
const streamed = live?.streamed();
const outcomeUnknown = (lead, flags) => outcomeUnknownResult(env, failure, reading.word, toolName, lead, flags, readOnly, streamed);
if (reading.breach === "never_started_after_output")
return await outcomeUnknown(`the execution environment said the command did not start (${envErrorDetail(failure.message)}), but the command had already written output.`, {});
if (reading.kind === "state")
return reading.outcome === "unknown" ? await outcomeUnknown(...stateWhileRunning(reading.word, failure.message)) : stateNotStartedResult(reading.word, toolName, failure.message, card);
if (reading.word === "sandbox_unavailable")
return { content: sandboxRefusalText(toolName, { by: "environment", detail: envErrorDetail(res.error.message), refusedBy: res.error.refusedBy, ...lapsedBy(commandSandbox, res.error.refusedBy, envErrorDetail(res.error.message)) }), details: { ...card, sandboxUnavailable: true, refusedBy: res.error.refusedBy ?? "environment" }, isError: true };
if (reading.word === "spawn_error" || reading.word === "shell_unavailable" || reading.word === "refused") {
const diagnosis = await diagnoseDeadCwd(env, toolName, effectiveCwd, cwd, cwdRef, signal);
if (diagnosis === undefined && reading.word === "refused") {
return {
content: `Error (${toolName.slice(0, 64)}): the execution target refused this command before it started (${envErrorDetail(res.error.message)}); nothing ran. The same command from the same working directory is refused the same way.`,
details: { ...card, refused: true },
isError: true,
};
}
throw Object.assign(new Error(diagnosis ?? `Error (${toolName}): command did not run: ${envErrorDetail(failureMessageOnce(res.error, refusalTold))}`), { details: card });
}
if (reading.word === "transport_lost") {
return await outcomeUnknown(`connection to the execution environment was lost, and the command may still be running (${envErrorDetail(res.error.message)}).`, { transportLost: true });
}
if (reading.word === "target_unavailable") {
return { content: targetUnavailableSentence(toolName, envErrorDetail(res.error.message)), details: targetUnavailableCard(), isError: true };
}
if (reading.kind === "cut") {
const { stdout: pStdout, stderr: pStderr, captured, overflowFile: cutOverflowFile } = await capturedBeforeFailure(env, res.error, streamed);
const noOutputSec = res.error.code === "liveness_no_output" && typeof res.error.noOutputSec === "number" && Number.isFinite(res.error.noOutputSec) && Math.floor(res.error.noOutputSec) >= 1
? Math.floor(res.error.noOutputSec)
: undefined;
const headline = res.error.code === "timeout"
? cappedByMaxTimeout
? `Command timed out after ${timeout}s — requested ${requestedSec}s, capped at ${caps.maxSec}s (engine ceiling: requests above ${caps.maxSec}s are reduced to it). The process was killed; output produced before the cutoff is shown below. Re-running with a larger timeout gets the same ${caps.maxSec}s ceiling — use run_in_background for work that needs longer, a narrower command, or resume from the partial progress below.`
: `Command timed out after ${timeout}s (timeout limit: ${timeout}s). The process was killed; output produced before the cutoff is shown below. Re-running the same command will likely time out again — consider run_in_background for long commands, a narrower command, or resuming from the partial progress below.`
: res.error.code === "liveness_no_output"
? `Command was killed after producing no output for ${noOutputSec !== undefined ? `${noOutputSec}s` : "the environment's no-output window"} (a command that writes nothing to stdout or stderr that long is treated as hung; this is not the timeout you requested). Output produced before the cutoff is shown below. Re-running the same command will likely stall the same way — make it print progress as it works, use run_in_background for long quiet commands, or split it into smaller steps.`
: res.error.code === "aborted"
? `Command was interrupted (aborted) before completion. Output produced before the interrupt is shown below.`
: `Command started but its completion could not be observed — a host-side output-stream callback failed mid-run and the process was terminated (${envErrorDetail(res.error.message)}). Output captured before the cut is shown below; its effects up to that point may have landed. Verify before assuming it needs a full re-run.`;
const zeroOutput = captured.length === 0;
const body = !zeroOutput ? `\n${delimitUntrusted("partial command output", captured)}` : `\n${zeroOutputSentence(res.error, timeout, noOutputSec)}`;
const overflowNote = cutOverflowFile !== undefined ? shellRecoveryHint(cutOverflowFile, readOnly) : "";
return {
content: `Error (${toolName}): ${headline}${body}${overflowNote}`,
details: {
...card,
stdout: pStdout,
stderr: pStderr,
exitCode: null,
...(cutOverflowFile !== undefined ? { output_file: cutOverflowFile } : {}),
...(res.error.code === "timeout"
? {
timedOut: true,
timeoutSec: timeout,
...(cappedByMaxTimeout ? { requestedTimeoutSec: requestedSec, cappedToMaxTimeoutSec: caps.maxSec } : {}),
}
: res.error.code === "liveness_no_output"
? { livenessNoOutput: true, ...(noOutputSec !== undefined ? { noOutputSec } : {}) }
: res.error.code === "aborted"
? { aborted: true }
: { callbackError: true }),
},
...(zeroOutput ? { isError: true } : {}),
};
}
return isDeploymentEnvCode(reading.word) ? await outcomeUnknown(...envRefusedLead(failure, reading.word, announce?.onEnvRefusal)) : await outcomeUnknown(`the command failed in the execution environment (${envErrorDetail(res.error.message)}).`, {});
}
if (res.value.detached && detach) {
return await detach.onDetached(res.value.detached.shellId, res.value.stdout, res.value.stderr, res.value.detached.cause);
}
let { stderr } = res.value;
const { stdout, exitCode } = res.value;
const sandboxNote = sandboxStart !== undefined ? sandboxResultNote(sandboxStart, command, res.value.sandbox) : "";
if (cwdRef) {
const epilogue = stripCwdSentinel(stderr, cwdMarker);
stderr = epilogue.stderr;
if (epilogue.cwd !== undefined) {
const captured = epilogue.cwd.trim();
const windowsWorld = isDriveAbsoluteSpelling(cwdRef.current);
const drive = windowsWorld ? shellDriveSpellingOf("win", captured) : undefined;
if (isDriveAbsoluteSpelling(captured))
cwdRef.current = captured;
else if (drive !== undefined)
cwdRef.current = drive;
else if (captured.startsWith("/") && !windowsWorld)
cwdRef.current = captured;
}
}
if (sandboxNote !== "")
stderr += sandboxNote;
let cwdOutsideNote = "";
if (cwdRef && containmentRoots !== undefined && containmentRoots.length > 0 && !withinAnyRoot(containmentRoots, cwdRef.current)) {
const cwdCanon = await env.canonicalPath(cwdRef.current, signal);
if (!(cwdCanon.ok && withinAnyRoot(containmentRoots, cwdCanon.value))) {
cwdOutsideNote = `NOTE: working directory is now outside the task root(s) (${cwdRef.current}); relative paths in the structured file tools (Read/Edit/Write/Grep/Glob) will resolve there and may be refused. Pass absolute in-root paths, or \`cd\` back inside.`;
}
}
const survivedCapNote = cappedByMaxTimeout
? `NOTE: requested timeout ${requestedSec}s was capped to the ${caps.maxSec}s engine ceiling (requests above the max are reduced to it) — no effect on this run (the command completed in time); use run_in_background for work that needs longer.`
: "";
const clippedStdout = clipShellOutput(stdout);
const clippedStderr = clipShellOutput(stderr);
const stdoutImage = await dataUriImageFromStdout(stdout, imageProcessor);
if (stdoutImage) {
const imgOverflowFile = stderr.length > bashMaxOutputChars() ? await writeShellOverflowFile(env, "", stderr) : undefined;
const imgOverflowNote = imgOverflowFile !== undefined ? shellRecoveryHint(imgOverflowFile, readOnly) : "";
return {
content: [
stdoutImage,
{ type: "text", text: `exit code: ${exitCode}\n[Image data detected in stdout and shown above]${stderr.trim() !== "" ? `\n--- stderr ---\n${clippedStderr}` : ""}${imgOverflowNote}${cwdOutsideNote ? `\n${cwdOutsideNote}` : ""}${survivedCapNote ? `\n${survivedCapNote}` : ""}` },
],
details: { type: "bash", stdout: "[image data]", stderr: clippedStderr, exitCode, isImage: true, ...(imgOverflowFile !== undefined ? { output_file: imgOverflowFile } : {}), ...(cappedByMaxTimeout ? { requestedTimeoutSec: requestedSec, cappedToMaxTimeoutSec: caps.maxSec } : {}) },
};
}
const cleanOverflowFile = stdout.length > bashMaxOutputChars() || stderr.length > bashMaxOutputChars() ? await writeShellOverflowFile(env, stdout, stderr) : undefined;
const overflowNote = cleanOverflowFile !== undefined ? shellRecoveryHint(cleanOverflowFile, readOnly) : "";
const exit1Note = exitCode === 1 ? bashExitOneInterpretation(reading.shell, command) : undefined;
const parts = [`exit code: ${exitCode}${exit1Note ? ` (${exit1Note} — exit 1 from this command is not an error)` : ""}`, `--- stdout ---\n${clippedStdout || "(empty)"}`];
if (stderr.trim() !== "")
parts.push(`--- stderr ---\n${clippedStderr}`);
if (overflowNote)
parts.push(overflowNote.trim());
if (cwdOutsideNote)
parts.push(cwdOutsideNote);
if (survivedCapNote)
parts.push(survivedCapNote);
return {
content: parts.join("\n"),
details: {
type: "bash",
stdout: clippedStdout,
stderr: clippedStderr,
exitCode,
...(exit1Note ? { returnCodeInterpretation: exit1Note } : {}),
...(cleanOverflowFile !== undefined ? { output_file: cleanOverflowFile } : {}),
...(cappedByMaxTimeout ? { requestedTimeoutSec: requestedSec, cappedToMaxTimeoutSec: caps.maxSec } : {}),
},
};
}
function bashDescription(coAuthor, caps, bgOffered = false, bgRetained = false, bgSessionScoped = false, bgEnvIsolatedOwned = false, confinement, shellFirst, shell) {
const coAuthorLines = coAuthor === false
? "- Follow the deployment's commit-message conventions."
: `- End git commit messages with:\nCo-Authored-By: ${coAuthor}`;
return `${shell === "zsh" ? "Executes a zsh command and returns its output. This environment starts commands on zsh, not bash: the engine does not read zsh text ahead of a run, so each command is treated as one it cannot read: asked about (or handed to the judge, in auto mode) before it runs, unless the permission mode or a rule covering the whole tool already answers it." : "Executes a bash command and returns its output."}
- Working directory persists between calls, but prefer absolute paths — each call starts in the directory the previous call ended in, so a \`cd\` carries over and moves the base for every later command. Shell state (env vars, functions) does not persist; the shell is re-initialized each call.
${shellFirst ? "" : DEDICATED_TOOLS_LINES}- \`timeout\` is in milliseconds: default ${caps.defaultMs}, max ${caps.maxMs}.${bgOffered ? `\n- \`run_in_background\` runs the command detached: it keeps running across turns and re-invokes you when it exits. No \`&\` needed.${backgroundLifetimeNote(bgRetained, bgSessionScoped, bgEnvIsolatedOwned, "description")}` : ""}
# Git
- Interactive flags (\`-i\`, e.g. \`git rebase -i\`, \`git add -i\`) are not supported in this environment.
- Use the \`gh\` CLI for GitHub operations (PRs, issues, API).
- Commit or push only when the user asks. If on the default branch, branch first.
${coAuthorLines}
# Notes
- ${BASH_CONFINEMENT_NOTE[confinement]} Every call is subject to the deployment's approval policy (it may be denied or require confirmation); a denied call should not be retried verbatim.
- Treat evidence of a deployment restriction — "Operation not permitted", "Read-only file system", a denied path, or a network failure — as a boundary, not a bug: adjust within the allowed scope or report the limit; don't reach for a destructive or privilege-escalating workaround.`;
}
const DEDICATED_TOOLS_LINES = `- IMPORTANT: Avoid using this tool to run \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or after you have verified that a dedicated tool cannot accomplish your task. Instead, use the appropriate dedicated tool as this will provide a much better experience for the user.
- File search by name: use the Glob tool (NOT \`find\` or \`ls\`); content search: use the Grep tool (NOT \`grep\`/\`rg\` in the shell).
`;
const BASH_CONFINEMENT_NOTE = {
command: "Commands run in the session's OS sandbox by default; see the sandbox instructions for what it allows.",
env: "Commands run inside the isolated execution environment, not on the operator's machine.",
none: "The shell is NOT sandboxed by this tool: a command can read or write any reachable path and use the network.",
};
async function adoptBackgroundShell(req) {
const { env, shellId, registry, description, toolUseId, ctxTaskId, ctxIsolationScope, ctxTaskArtifacts, occupant, wiring } = req;
const sessionScoped = wiring.sessionId !== undefined;
const owner = sessionScoped ? wiring.sessionId : (ctxTaskId ?? wiring.taskOwner);
const scope = callScopeOf({ isolationScope: ctxIsolationScope }, { scope: wiring.taskScope });
const onNotify = wiring.onNotify;
const outputFile = await createBackgroundOutputFile(env, "bash-task-");
try {
const taskId = registry.registerBackgroundBash({
env,
shellId,
description,
toolUseId,
...(owner !== undefined ? { owner } : {}),
...(scope !== undefined ? { scope } : {}),
...(sessionScoped ? { sessionScoped: true } : {}),
...occupant,
...(outputFile !== undefined ? { outputFile } : {}),
...(ctxTaskArtifacts !== undefined ? { taskArtifacts: ctxTaskArtifacts } : {}),
onTerminal: (n) => onNotify(n, { priority: "next" }),
...(wiring.retainBackgroundProcesses !== undefined ? { retainBackgroundProcesses: wiring.retainBackgroundProcesses } : {}),
});
return { ok: true, taskId, outputFile };
}
catch (e) {
const reason = thrownText(e);
let kill;
try {
kill = await env.killBackground(shellId);
}
catch {
kill = undefined;
}
if (kill !== undefined && (kill.ok || kill.error.code === "not_found"))
return { ok: false, reason, killed: true };
return { ok: false, reason, killed: false, killMsg: kill !== undefined && !kill.ok ? envErrorDetail(kill.error.message) : "killBackground threw" };
}
}
export function createBashTool(env, rootCanonical, coAuthor = false, cwdRef = { current: rootCanonical }, taskOpts) {
const modelShell = mountedModelShellOf(taskOpts?.modelShell, "createBashTool"), bgEnv = backgroundLifecycleOf(env, modelShell), bgStarts = bgEnv !== undefined;
const timeoutCaps = resolveBashTimeoutCaps(taskOpts);
const timeoutCapsSecView = bashTimeoutCapsSec(timeoutCaps);
const refusalTold = new Set();
const breachLedger = execFailureBreachLedger();
const bgOffered = bgStarts && taskOpts.taskRegistry !== undefined;
const bgRetained = bgStarts && retainsBackgroundProcesses({ env: envDeclaresRetain(env), task: taskOpts.retainBackgroundProcesses === true });
const bgSessionScoped = taskOpts.sessionId !== undefined && taskOpts.taskRegistry !== undefined;
const bgEnvIsolatedOwned = hasDestroy(env) && isIsolated(env);
const cardOf = (shellFirst) => bashDescription(coAuthor, timeoutCaps, bgOffered, bgRetained, bgSessionScoped, bgEnvIsolatedOwned, taskOpts.commandSandbox !== undefined ? "command" : isIsolated(env) ? "env" : "none", shellFirst, modelShell.shell);
return defineTool({
name: "Bash",
...toolFace("bash"), ...startedShellDeclaration(modelShell.shell),
description: cardOf(false),
descriptionVariants: [{ id: "shell-first", traits: {}, facts: { shellFirstSession: true }, text: cardOf(true) }],
parameters: Type.Object({
command: Type.String({ description: "The command to execute" }),
timeout: Type.Optional(Type.Number({ description: bashTimeoutParamDescription(timeoutCaps, false) })),
description: Type.Optional(Type.String({
description: 'Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does.\n' +
"\n" +
"For simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n" +
'- ls → "List files in current directory"\n' +
'- git status → "Show working tree status"\n' +
'- npm install → "Install package dependencies"\n' +
"\n" +
"For commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does:\n" +
'- find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"\n' +
'- git reset --hard origin/main → "Discard all local changes and match remote main"\n' +
"- curl -s url | jq '.data[]' → \"Fetch JSON from URL and extract data array elements\"",
})),
...(bgOffered
? {
run_in_background: Type.Optional(Type.Boolean({
description: "Set to true to run this command in the background.",
})),
}
: {}),
...(taskOpts.commandSandbox !== undefined
? { dangerouslyDisableSandbox: Type.Optional(Type.Boolean({ description: "Set this to true to dangerously override sandbox mode and run commands without sandboxing." })) }
: {}),
}),
isConcurrencySafe: (args) => {
const command = shellCommandOf(args);
if (command === undefined || isBackgroundShellCall(args))
return false;
return readOnlyShellVerdictIn(modelShell.shell, command, { readers: CONCURRENT_READERS }).readOnly;
},
execute: async (args, ctx) => {
const { command, timeout, run_in_background, description } = args;
const timeoutRefusal = bashTimeoutArgRefusal(timeout, timeoutCaps);
if (timeoutRefusal !== undefined)
return errorResult(timeoutRefusal, { type: "bash_invalid_timeout", code: "bash_invalid_timeout" });
const refused = (await taskOpts.shellReadAdmission?.("Bash", ctx.toolCallId, command, ctx.signal)) ?? (await patternKillRefusal(modelShell.shell, command, env, cwdRef.current, ctx.signal));
if (refused !== undefined)
return refused;
if (run_in_background) {
const registry = taskOpts.taskRegistry;
const onNotify = resolveCompletionSink(ctx.onTaskNotification, taskOpts.onTaskNotification);
const start = modelShell.start;
if (bgEnv === undefined || start.spawnBackground === undefined || registry === undefined || !admitsBackgroundLaunch(onNotify))
return bashBackgroundUnavailable();
if (cwdRef && (await isDeadCwd(env, cwdRef.current, ctx.signal))) {
const diagnosis = await diagnoseDeadCwd(env, "Bash", cwdRef.current, rootCanonical, cwdRef, ctx.signal);
if (diagnosis !== undefined)
throw new Error(diagnosis);
}
if (ctx.signal?.aborted === true)
return errorResult("Error (Bash): the call was cancelled before the background command started.");
const requestedTimeoutSec = timeout !== undefined ? Math.max(1, Math.round(timeout / 1000)) : undefined;
const readFloor = taskOpts.readFloor?.(ctx.toolCallId);
const sandbox = taskOpts.commandSandbox?.start();
if (sandbox !== undefined && !sandbox.ok)
return errorResult(sandboxRefusalText("Bash", { by: "plan", reason: sandbox.reason }), { type: "bash", sandboxUnavailable: true });
const r = await start.spawnBackground(command, {
cwd: cwdRef.current,
...(requestedTimeoutSec !== undefined ? { timeout: requestedTimeoutSec } : {}),
...(readFloor !== undefined ? { readFloor } : {}),
...(sandbox?.sandbox !== undefined ? { sandbox: sandbox.sandbox } : {}),
});
const bgWord = r.ok ? undefined : r.error.code;
const bgCardWord = r.ok ? undefined : backgroundFailureWord(bgWord, () => breachLedger.announce(taskOpts.onNotice, env, { breach: "word_outside_set", code: bgWord, face: "spawnBackground", ...(taskOpts.sessionId !== undefined ? { sessionId: taskOpts.sessionId } : {}) }));
const bgCard = bgCardWord === undefined ? undefined : bashFailureCard(bgCardWord);
if (!r.ok && r.error.code === "sandbox_unavailable")
return errorResult(sandboxRefusalText("Bash", { by: "environment", detail: envErrorDetail(r.error.message), refusedBy: r.error.refusedBy, ...lapsedBy(taskOpts.commandSandbox, r.error.refusedBy, envErrorDetail(r.error.message)) }), { ...bgCard, sandboxUnavailable: true, refusedBy: r.error.refusedBy ?? "environment" });
if (!r.ok && (bgCardWord === "unknown" || BACKGROUND_START_FAILURE_KINDS[bgCardWord] === "unknown"))
return errorResult(`Error (Bash): ${withOutcomeNote(`the background start failed in the execution environment (${envErrorDetail(failureMessageOnce(r.error, isExtensionCallId(ctx.toolCallId) ? undefined : refusalTold))}), and the command may have started`, { outcomeUnknown: true })}`, { ...bgCard, outcomeUnknown: true });
if (!r.ok)
return errorResult(`Error (Bash): the background process could not be started: ${envErrorDetail(failureMessageOnce(r.error, isExtensionCallId(ctx.toolCallId) ? undefined : refusalTold))}`, bgCard);
const bgCaps = bgEnv.backgroundCapabilities;
const appliedTimeoutSec = typeof bgCaps.defaultBgTimeoutSec === "number" && typeof bgCaps.maxBgTimeoutSec === "number"
? Math.min(requestedTimeoutSec ?? bgCaps.defaultBgTimeoutSec, bgCaps.maxBgTimeoutSec)
: undefined;
const bgCappedByMax = appliedTimeoutSec !== undefined && requestedTimeoutSec !== undefined && typeof bgCaps.maxBgTimeoutSec === "number" && requestedTimeoutSec > bgCaps.maxBgTimeoutSec;
const budgetNote = appliedTimeoutSec !== undefined
? bgCappedByMax
? ` Time budget: requested ${requestedTimeoutSec}s, capped at ${bgCaps.maxBgTimeoutSec}s (env ceiling: requests above ${bgCaps.maxBgTimeoutSec}s are reduced to it) — the process may run up to ${appliedTimeoutSec}s.`
: ` Time budget: the process may run up to ${appliedTimeoutSec}s (hard cap ${bgCaps.maxBgTimeoutSec}s).`
: "";
const lifetimeNote = backgroundLifetimeNote(bgRetained, bgSessionScoped, bgEnvIsolatedOwned);
{
const adopted = await adoptBackgroundShell({
env: bgEnv,
shellId: r.value.shellId,
registry,
description: description ?? command,
toolUseId: ctx.toolCallId,
ctxTaskId: ctx.taskId,
ctxIsolationScope: ctx.isolationScope,
ctxTaskArtifacts: ctx.taskArtifacts,
occupant: callOccupant(ctx, taskOpts),
wiring: { sessionId: taskOpts.sessionId, taskOwner: taskOpts.taskOwner, taskScope: taskOpts.taskScope, onNotify, retainBackgroundProcesses: taskOpts.retainBackgroundProcesses },
});
if (!adopted.ok) {
if (adopted.killed) {
return errorResult(`Error (Bash): background process was started but could not be registered (${adopted.reason}); it has been terminated.`);
}
return {
content: `Error (Bash): background process was started but could not be registered (${adopted.reason}), and the cleanup kill failed (${adopted.killMsg}). ` +
`The process could NOT be terminated — it may still be running, but it has no task_id, so TaskStop cannot reach it and no completion will arrive. ` +
`If it must be stopped, kill it manually (e.g. \`pkill -f\` on its command line).`,
details: { type: "bash", registerFailed: true, killFailed: true },
isError: true,
};
}
const { taskId, outputFile } = adopted;
const interimNote = backgroundOutputFileNote(outputFile);
if (taskOpts.oneShot === true) {
return `Command running in background; task_id=${taskId}.${interimNote} ${ONE_SHOT_BACKGROUND_COMMAND_NOTE} TaskStop("${taskId}") to stop.` + budgetNote + lifetimeNote;
}
return (`Command running in background; task_id=${taskId}.${interimNote} You will be notified when it completes — do not poll; ` +
`end your turn if nothing else is pending. TaskStop("${taskId}") to stop.` +
budgetNote +
lifetimeNote);
}
}
const detachHub = taskOpts.detachHub;
const detachRegistry = taskOpts.taskRegistry;
const autoBackgroundArmed = taskOpts.autoBackgroundOnTimeout === true && canAutoBackground(modelShell.shell, command, 0);
let backgroundedForQueuedMessage = false;
let backgroundedByTurnCut = false;
const wantsTicks = taskOpts.onToolProgress !== undefined || (autoBackgroundArmed && detachHub !== undefined && taskOpts.queuedHumanInput !== undefined);
const onTick = !wantsTicks
? undefined
: (t) => {
describeSafely(taskOpts.onToolProgress, { toolCallId: ctx.toolCallId, toolName: "Bash", ...t });
if (!autoBackgroundArmed || backgroundedForQueuedMessage || detachHub === undefined)
return;
if (ctx.signal?.aborted === true)
return;
if (taskOpts.queuedHumanInput?.() !== true)
return;
backgroundedForQueuedMessage = true;
detachHub.request(ctx.toolCallId);
};
const detachEnv = modelShell.background.detach ? bgEnv : undefined;
const detachSink = resolveCompletionSink(ctx.onTaskNotification, taskOpts.onTaskNotification);
const detachChain = detachHub !== undefined && detachRegistry !== undefined && detachEnv !== undefined && admitsBackgroundLaunch(detachSink)
? {
signal: detachHub.signalFor(ctx.toolCallId),
onDetached: async (shellId, stdoutSoFar, stderrSoFar, cause) => {
const onNotify = detachSink;
const adopted = await adoptBackgroundShell({
env: detachEnv,
shellId: shellId,
registry: detachRegistry,
description: description ?? command,
toolUseId: ctx.toolCallId,
ctxTaskId: ctx.taskId,
ctxIsolationScope: ctx.isolationScope,
ctxTaskArtifacts: ctx.taskArtifacts,
occupant: callOccupant(ctx, taskOpts),
wiring: { sessionId: taskOpts.sessionId, taskOwner: taskOpts.taskOwner, taskScope: taskOpts.taskScope, onNotify, retainBackgroundProcesses: taskOpts.retainBackgroundProcesses },
});
if (!adopted.ok) {
const outTail = stdoutSoFar.slice(-1_000);
const errTail = stderrSoFar.slice(-1_000);
const tails = (outTail ? `\n--- output so far (tail) ---\n${outTail}` : "") +
(errTail ? `\n--- stderr so far (tail) ---\n${errTail}` : "");
if (adopted.killed) {
return {
content: `Error (Bash): command was detached to the background but could not be registered (${adopted.reason}); ` +
`it has been terminated (an unregistered background process would have no task_id and could not be read or stopped).` +
tails,
details: { type: "bash", detached: true, registerFailed: true },
isError: true,
};
}
return {
content: `Error (Bash): command was detached to the background but could not be registered (${adopted.reason}), and the cleanup kill failed (${adopted.killMsg}). ` +
`The process could NOT be terminated — it may still be running, but it has no task_id, so TaskStop cannot reach it and no completion will arrive. ` +
`If it must be stopped, kill it manually (e.g. \`pkill -f\` on its command line).` +
tails,
details: { type: "bash", detached: true, registerFailed: true, killFailed: true },
isError: true,
};
}
const { taskId, outputFile } = adopted;
const tail = stdoutSoFar.slice(-1_000);
const adoptCaps = detachEnv.backgroundCapabilities;
const adoptBudgetNote = typeof adoptCaps.defaultBgTimeoutSec === "number" && typeof adoptCaps.maxBgTimeoutSec === "number"
? ` Time budget: the process may run up to ${Math.min(adoptCaps.defaultBgTimeoutSec, adoptCaps.maxBgTimeoutSec)}s (hard cap ${adoptCaps.maxBgTimeoutSec}s).`
: "";
return {
content: (cause === "timeout"
? `Command exceeded its timeout but is still running — moved to background instead of being killed (task_id=${taskId}). `
: backgroundedByTurnCut
? `Command is still running and was moved to the background when the turn was ended to deliver the message that follows (task_id=${taskId}). It was NOT stopped and nothing about it failed. `
: backgroundedForQueuedMessage
? `Command is still running and was moved to the background so a queued message could be delivered without waiting for it (task_id=${taskId}). It was NOT stopped and nothing about it failed. `
: `Command moved to background; task_id=${taskId}. `) +
`${backgroundOutputFileNote(outputFile).trimStart()} ` +
`TaskStop("${taskId}") to stop it. ` +
(taskOpts.oneShot === true
? ONE_SHOT_BACKGROUND_COMMAND_NOTE
: `You will be notified when it completes — do not poll.`) +
adoptBudgetNote +
backgroundLifetimeNote(bgRetained, bgSessionScoped, bgEnvIsolatedOwned) +
(tail ? `\n--- output so far (tail) ---\n${tail}` : ""),
details: { type: "bash", detached: true, task_id: taskId, ...(description !== undefined ? { description } : {}), ...(outputFile !== undefined ? { output_file: outputFile } : {}), ...(cause === "timeout" || backgroundedForQueuedMessage || backgroundedByTurnCut ? { autoBackgrounded: true } : {}), ...(cause !== "timeout" && backgroundedByTurnCut ? { backgroundedByTurnAbort: true } : {}) },
};
},
autoBackgroundEligible: taskOpts.autoBackgroundOnTimeout === true && canAutoBackground(modelShell.shell, command, 0),
}
: undefined;
const turnSignal = ctx.signal;
const movesAside = taskOpts.turnCutMovesCommandAside;
const onTurnCut = autoBackgroundArmed && detachChain !== undefined && detachHub !== undefined && movesAside !== undefined && turnSignal !== undefined && !turnSignal.aborted
? () => {
if (detachChain.signal.aborted)
return;
let moves;
try {
moves = movesAside(turnSignal);
}
catch {
return;
}
if (!moves)
return;
backgroundedByTurnCut = true;
detachHub.request(ctx.toolCallId);
}
: undefined;
if (onTurnCut !== undefined)
turnSignal?.addEventListener("abort", onTurnCut, { once: true });
let res;
try {
res = await runShell(env, modelShell, rootCanonical, "Bash", command, msTimeoutToRequestedSec(timeout), timeoutCapsSecView, ctx.signal, cwdRef, detachChain, false, [rootCanonical, ...(taskOpts.additionalRoots ?? [])], onTick, taskOpts.readFloor?.(ctx.toolCallId), taskOpts.imageProcessor, taskOpts.commandSandbox, isExtensionCallId(ctx.toolCallId) ? undefined : refusalTold, { onNotice: taskOpts.onNotice, ledger: breachLedger, ...(taskOpts.onEnvRefusal !== undefined ? { onEnvRefusal: taskOpts.onEnvRefusal } : {}), ...(taskOpts.sessionId !== undefined ? { sessionId: taskOpts.sessionId } : {}) });
}
finally {
if (onTurnCut !== undefined)
turnSignal?.removeEventListener("abort", onTurnCut);
taskOpts.detachHub?.gc(ctx.toolCallId);
}
const detached = typeof res !== "string" && res.details.detached === true;
const resText = typeof res === "string" ? res : typeof res.content === "string" ? res.content : undefined;
const hint = detached || resText === undefined ? undefined : ghRateLimitHint(command, resText, undefined, taskOpts.monitorToolActive, taskOpts.reminderMark);
const withHint = hint === undefined ? res : typeof res === "string" ? `${res}\n\n${hint}` : { ...res, content: `${resText}\n\n${hint}` };
if (typeof withHint === "string" || description === undefined)
return withHint;
if (withHint.details.detached)
return withHint;
return { ...withHint, details: { ...withHint.details, description } };
},
});
}
export function createBashReadonlyTool(env, rootCanonical, allow, opts) {
const modelShell = mountedModelShellOf(opts?.modelShell, "createBashReadonlyTool");
const timeoutCaps = resolveBashTimeoutCaps(opts);
const timeoutCapsSecView = bashTimeoutCapsSec(timeoutCaps);
const breachLedger = execFailureBreachLedger();
const sample = [...allow].slice(0, 6).join(", ");
return defineTool({
name: "Bash",
...toolFace("bash-readonly"), ...startedShellDeclaration(modelShell.shell),
description: `Run a SINGLE read-only inspection command (e.g. ${sample}, …) and return its output. Shell ` +
"operators (pipes, redirects, ;, &&, command substitution, subshells) are rejected and only " +
"allowlisted commands run. Reads are confined to the workspace root(s): a path outside them is " +
"refused, as is one that cannot be resolved statically (e.g. a `~` path). " +
(boundaryIsTheSandbox(env) ? "" : "A path that leads outside via a symlink counts as outside, including one a glob pattern expands to or a recursive read traverses. ") +
"Still subject to the deployment's approval policy.",
parameters: Type.Object({
command: Type.String({ description: "A single allowlisted read-only command (no shell operators)." }),
timeout: Type.Optional(Type.Number({ description: bashTimeoutParamDescription(timeoutCaps, true) })),
}),
execute: async (args, ctx) => {
const { command, timeout } = args;
const timeoutRefusal = bashTimeoutArgRefusal(timeout, timeoutCaps);
if (timeoutRefusal !== undefined)
return errorResult(timeoutRefusal, { type: "bash_invalid_timeout", code: "bash_invalid_timeout" });
const reason = readOnlyFaceRefusal(modelShell.shell, command, allow);
if (reason)
return errorResult(`Error (Bash): ${reason}`);
const refused = await opts.shellReadAdmission?.("Bash", ctx.toolCallId, command, ctx.signal);
if (refused !== undefined)
return refused;
const readOnlyTick = opts.onToolProgress === undefined ? undefined : (t) => describeSafely(opts.onToolProgress, { toolCallId: ctx.toolCallId, toolName: "Bash", ...t });
return await runShell(env, modelShell, rootCanonical, "Bash", command, msTimeoutToRequestedSec(timeout), timeoutCapsSecView, ctx.signal, undefined, undefined, true, undefined, readOnlyTick, opts.readFloor?.(ctx.toolCallId), opts.imageProcessor, opts.commandSandbox, undefined, { onNotice: opts.onNotice, ledger: breachLedger, ...(opts.onEnvRefusal !== undefined ? { onEnvRefusal: opts.onEnvRefusal } : {}) });
},
});
}