UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

109 lines (107 loc) • 7.04 kB
import { textContentHashOf } from "../canonical-json.js"; import { lapseSentenceOf, SANDBOX_LAPSED_SENTENCE } from "../command-sandbox.js"; import { mintSystemReminder } from "../reminder-mint.js"; import { conversationSegmentOf, restateToldSeat } from "./conversation-segment.js"; const LIST_SHOWN = 50; const listed = (entries) => (entries.length > LIST_SHOWN ? [...entries.slice(0, LIST_SHOWN), `(${entries.length - LIST_SHOWN} more)`] : [...entries]); const home = (p, at) => (p.startsWith("~/") && at !== undefined && at.startsWith("/") ? `${at.replace(/\/+$/, "")}/${p.slice(2)}` : p); const NETWORK_LINE = "Attempt requests and read the error rather than predicting whether a host is reachable; denied connections are reported in a `<sandbox_violations>` block explaining the reason; a file the sandbox denies is reported the same way."; const ESCAPE_RULES = `You should always default to running commands within the sandbox. Do NOT attempt to set \`dangerouslyDisableSandbox: true\` unless: - The user *explicitly* asks you to bypass sandbox - A specific command just failed and you see evidence of sandbox restrictions causing the failure. Note that commands can fail for many reasons unrelated to the sandbox (missing files, wrong arguments, network issues, etc.). Evidence of sandbox-caused failures includes: - "Operation not permitted" errors for file/network operations - Access denied to specific paths outside allowed directories - Network connection failures to non-whitelisted hosts - Unix socket connection errors When you see evidence of sandbox-caused failure: - Immediately retry with \`dangerouslyDisableSandbox: true\` (don't ask, just do it). This goes through the permission gate (a user prompt, or the auto-mode classifier when auto mode is active). - Briefly explain what sandbox restriction likely caused the failure. - Treat each command you execute with \`dangerouslyDisableSandbox: true\` individually. Even if you have recently run a command with this setting, you should default to running future commands within the sandbox. - A sandbox denial on a credential, a file or a host that the task does not involve is the boundary above at work: tell the user rather than retrying with \`dangerouslyDisableSandbox: true\`. - Do not suggest adding sensitive paths like ~/.bashrc, ~/.zshrc, ~/.ssh/*, or credential files to the sandbox allowlist.`; const ESCAPE_DISABLED = `The \`dangerouslyDisableSandbox\` parameter is disabled in this session's configuration; setting it does not take a command out of the sandbox. If a command the task needs fails on a sandbox restriction, tell the user which restriction it hit; changing the sandbox settings is their decision, not yours.`; export function renderSandboxInstructions(run, leg) { if (run.state !== "armed" || run.lapse.reason !== undefined) return undefined; const r = run.requirement; const at = leg.home; const fs = r.filesystem ?? {}; const filesystem = { read: { denyOnly: listed((fs.denyRead ?? []).map((p) => home(p, at))), ...(fs.allowRead !== undefined && fs.allowRead.length > 0 ? { allowWithinDeny: listed(fs.allowRead.map((p) => home(p, at))) } : {}) }, write: { allowOnly: listed([...new Set([...leg.writeRoots(), ...(fs.allowWrite ?? []).map((p) => home(p, at))])]), denyWithinAllow: listed((fs.denyWrite ?? []).map((p) => home(p, at))) }, }; const network = { allowedHosts: listed(r.network?.allowedDomains ?? []), deniedHosts: listed(r.network?.deniedDomains ?? []), ...(r.network?.strictAllowlist === true ? { strictAllowlist: true } : {}) }; const ignored = r.ignoreViolations !== undefined && Object.keys(r.ignoreViolations).length > 0 ? `\nIgnored violations: ${JSON.stringify(r.ignoreViolations)}` : ""; return `## Bash command sandbox By default, Bash tool commands run in a sandbox. This sandbox controls which directories and network hosts commands may access or modify without an explicit override. The sandbox has the following restrictions: Filesystem: ${JSON.stringify(filesystem)} Network: ${JSON.stringify(network)}${ignored} ${NETWORK_LINE} ${r.allowUnsandboxedCommands === false ? ESCAPE_DISABLED : ESCAPE_RULES}`; } export function sandboxFrame(told, text) { if (text !== undefined) { const digest = textContentHashOf(text); return told === digest ? undefined : { body: text, value: digest }; } return typeof told === "string" ? { body: SANDBOX_LAPSED_SENTENCE, value: null } : undefined; } export function sandboxFrameNow(run, leg) { const text = renderSandboxInstructions(run, leg); if (text !== undefined) return { body: text, value: textContentHashOf(text) }; const lapsed = lapseSentenceOf(run); return lapsed !== undefined ? { body: lapsed, value: null } : undefined; } export async function prepareSandboxFrameSeat(input) { if (input.text === undefined && input.told === undefined) return undefined; const segment = await input.session.getBranch().then(conversationSegmentOf, () => undefined); const told = input.told; const inSegment = told !== undefined && (segment === undefined ? input.text === undefined : told.segment === segment); const owed = sandboxFrame(inSegment ? told.value : undefined, input.text); return owed === undefined && input.text === undefined ? undefined : { ...(owed !== undefined ? { owed } : {}), segment, now: input.now }; } export function sandboxFrameText(prepared) { const owed = prepared.sandboxFrameSeat?.owed; return owed === undefined ? undefined : mintSystemReminder(owed.body, prepared.reminderMark); } export function registerSandboxFrameReceipt(prepared, text) { if (prepared.sandboxFrameSeat?.owed !== undefined) prepared.frameReceipts.pending.push({ source: "sandbox_instructions", text, commit: () => settleSandboxFrame(prepared) }); } function settleSandboxFrame(prepared) { const seat = prepared.sandboxFrameSeat; const owed = seat?.owed; if (seat === undefined || owed === undefined) return; seat.owed = undefined; recordSandboxFrame(prepared.announcedListingsRef, prepared.frameReceipts, owed.value, seat.segment); } function recordSandboxFrame(ref, ledger, value, segment) { if (segment === undefined) return; ref.commandSandbox = { value, segment }; ledger.listingSnapshotOwed = true; } export function sandboxFrameRestateOption(prepared) { const seat = prepared.sandboxFrameSeat; if (seat === undefined) return {}; return { sandboxFrameRestate: async () => { const now = seat.now(); if (now === undefined) return; await restateToldSeat(prepared, seat, { ...now, what: "the sandbox instructions", carried: seat.owed !== undefined && seat.owed.value === now.value, record: (value, segment) => recordSandboxFrame(prepared.announcedListingsRef, prepared.frameReceipts, value, segment), }); }, }; }