UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

187 lines (186 loc) • 14.5 kB
import { deliverEngineNotice } from "../../core/types.js"; import { createTaskStopTool } from "../../core/task-registry.js"; import { callOccupant } from "../../core/task-registry-shared.js"; import {} from "./safety.js"; import { createRepoMapTool } from "./repo-map.js"; export * from "./fs-shared.js"; export * from "./fs-pdf.js"; export * from "./fs-read.js"; export * from "./fs-write.js"; export * from "./fs-search-tools.js"; export * from "./bash-readonly-classifier.js"; export * from "./fs-bash.js"; export * from "./read-deny.js"; export { readDenyHomesOf } from "./read-deny-home.js"; import { BASH_READONLY_DEFAULT_ALLOW } from "./bash-readonly-classifier.js"; export { BASH_CLASSIFY_EXTRA_ALLOW, bashClassifyDefaultAllow } from "./bash-readonly-classifier.js"; import { checkedReadDenyHomes, compileReadDeny, compileWriteDeny, readDenyBuiltinConfigOf, readDenyRowAnchor } from "./read-deny.js"; import { withGateTimeout } from "../../core/gate-bounded-await.js"; import { carriedReadFaceOf, carryHomeViews, homeViewsAt, placeReadDenyAtHome, placementViewsOf, readDenyPlacedLater, sayPlacementLost } from "./read-deny-home.js"; import { judgeReadFloorKept, readFloorSeat, screenReadDenyFloorRequired } from "./read-floor.js"; import { deploymentFaceClampNotice, resolveContainmentFace } from "./containment-face.js"; export * from "./containment-face.js"; import {} from "./fs-shared.js"; import { createModelFileReader, createReadFileTool } from "./fs-read.js"; import { createEditFileTool, createWriteFileTool, createNotebookEditTool, createSaveToolResultTool, writeContainmentOf } from "./fs-write.js"; import { createGrepTool, createGlobTool } from "./fs-search-tools.js"; import { createBashTool, createBashReadonlyTool } from "./fs-bash.js"; import { callScopeOf } from "../../core/isolation-scope.js"; export function handsWriteHalfMounts(opts) { return opts.readOnly !== true; } export function backgroundOutputReadExemption(registry, seat, env) { if (registry === undefined) return undefined; return (canonicalKey, c) => registry.isBackgroundOutputFile(canonicalKey, { owner: c?.taskId ?? seat.taskOwner, scope: callScopeOf(c, { scope: seat.taskScope }), ...(seat.sessionId !== undefined ? { sessionId: seat.sessionId } : {}), ...callOccupant(c, seat) }, env); } export function createHandsToolkit(env, readFileState, rootCanonical, opts = {}) { const { modelShell, readOnly = false, bashReadonlyAllow, commitCoAuthor = false, mountBackgroundTaskTools = true, additionalRoots, additionalReadRoots, } = opts; if (Object.prototype.hasOwnProperty.call(opts, "includeShell")) throw new TypeError("createHandsToolkit: options.includeShell is retired — options.modelShell takes its place: the mounted reading readModelShell(env) answers for this environment mounts the shell tools; without it none mount"); const carriedFace = opts.readDenyHomes !== undefined ? carriedReadFaceOf(opts.readDenyHomes) : undefined; const readFaceRoots = carriedFace?.readRoots ?? (additionalReadRoots === undefined ? additionalRoots : () => (additionalReadRoots.length === 0 ? additionalRoots : [...(additionalRoots ?? []), ...additionalReadRoots])); const outsideRemedy = carriedFace?.outsideReadRemedy; const cwdRef = opts.cwdRef ?? { current: rootCanonical }; const bgOutput = backgroundOutputReadExemption(opts.taskRegistry, opts, env); const readAdmission = opts.readAdmission; const bgOutputReadExemption = bgOutput === undefined && readAdmission === undefined ? undefined : (canonicalKey, c) => readAdmission?.(c.toolCallId, canonicalKey) === true || (bgOutput?.(canonicalKey, c) ?? false); const { readDeny, writeDeny, afterPlacement } = carriedFace !== undefined ? { readDeny: carriedFace.readDeny, writeDeny: carriedFace.writeDeny, afterPlacement: (tool) => tool } : bandOwnTables(env, opts, rootCanonical); const readFloor = readFloorSeat(readDeny); const floorRequired = screenReadDenyFloorRequired(opts.readDenyFloorRequired, "HandsToolkitOptions.readDenyFloorRequired") === true; if (carriedFace === undefined) judgeReadFloorKept({ env, table: readDeny, floor: readFloor?.(undefined), required: floorRequired, deployment: [], onNotice: opts.onNotice }); const readFace = resolveContainmentFace({ kind: "read", depsFace: opts.readFace, readOnlyMount: readOnly, orgGoverned: false, fullShellReachable: modelShell !== undefined && !readOnly, onDeploymentClamp: (cause) => deliverEngineNotice(opts.onNotice, deploymentFaceClampNotice("read", cause)), }); const writeFace = resolveContainmentFace({ kind: "write", depsFace: opts.writeFace, readOnlyMount: readOnly, orgGoverned: false, fullShellReachable: modelShell !== undefined && !readOnly, onDeploymentClamp: (cause) => deliverEngineNotice(opts.onNotice, deploymentFaceClampNotice("write", cause)), }); const writeFaceOf = opts.writeFaceLive ?? (() => writeFace); const readCwd = readOnly ? undefined : cwdRef; const readerOptions = { env, state: readFileState, rootCanonical, ...(readCwd !== undefined ? { cwdRef: readCwd } : {}), ...(readFaceRoots !== undefined ? { additionalRoots: readFaceRoots } : {}), imageProcessor: opts.imageProcessor, ...(opts.pdfModelCapabilities !== undefined ? { pdfCapabilities: opts.pdfModelCapabilities } : {}), ...(bgOutputReadExemption !== undefined ? { bgOutputReadExemption } : {}), ...(readDeny !== undefined ? { readDeny } : {}), ...(readFace !== undefined ? { readFace } : {}), ...(outsideRemedy !== undefined ? { outsideRemedy } : {}), ...(opts.reminderMark !== undefined ? { reminderMark: opts.reminderMark } : {}), ...(opts.reminderDisclosureCounts !== undefined ? { reminderDisclosureCounts: opts.reminderDisclosureCounts } : {}), ...(opts.contextRoom !== undefined ? { contextRoom: opts.contextRoom } : {}), disclosureWindows: new Map(), }; const reader = createModelFileReader(readerOptions); if (opts.modelFileReaderSeat !== undefined) opts.modelFileReaderSeat.current = reader; const readToolDeny = carriedFace?.structuredReadDeny ?? readDeny; const readToolReader = readToolDeny === readDeny ? reader : createModelFileReader({ ...readerOptions, readDeny: readToolDeny }); const tools = [ afterPlacement(createReadFileTool(env, readFileState, rootCanonical, readCwd, readFaceRoots, opts.imageProcessor, opts.pdfModelCapabilities, bgOutputReadExemption, readToolDeny, readFace, opts.reminderMark, opts.reminderDisclosureCounts, readToolReader)), ]; if (handsWriteHalfMounts({ readOnly })) { tools.push(afterPlacement(createEditFileTool(env, readFileState, opts.writeRoot ?? rootCanonical, cwdRef, additionalRoots, opts.beforeWrite, opts.trackFileEdit, opts.onFileEdited, writeFaceOf, writeDeny, readDeny, opts.readFirstWaiver)), afterPlacement(createWriteFileTool(env, readFileState, opts.writeRoot ?? rootCanonical, cwdRef, additionalRoots, opts.beforeWrite, opts.trackFileEdit, opts.onFileEdited, writeFaceOf, writeDeny, opts.readFirstWaiver)), afterPlacement(createNotebookEditTool(env, readFileState, opts.writeRoot ?? rootCanonical, cwdRef, additionalRoots, opts.beforeWrite, opts.trackFileEdit, opts.onFileEdited, writeFaceOf, writeDeny))); const keptBytes = opts.toolResultBytes; if (opts.writeContainmentSeat !== undefined) opts.writeContainmentSeat.current = writeContainmentOf(env, opts.writeRoot ?? rootCanonical, cwdRef, additionalRoots, writeDeny, writeFaceOf); if (keptBytes?.bytesOf !== undefined) tools.push(afterPlacement(createSaveToolResultTool(env, keptBytes, opts.writeRoot ?? rootCanonical, cwdRef, additionalRoots, opts.beforeWrite, opts.trackFileEdit, opts.onFileEdited, writeFaceOf, writeDeny))); } tools.push(afterPlacement(createGrepTool(env, rootCanonical, readFaceRoots, readDeny, readFace, cwdRef, readAdmission, outsideRemedy)), afterPlacement(createGlobTool(env, rootCanonical, readFaceRoots, readDeny, readFace, cwdRef, readAdmission, outsideRemedy)), afterPlacement(createRepoMapTool(env, rootCanonical, readFaceRoots, readDeny, readFace, cwdRef, readAdmission, outsideRemedy))); if (modelShell !== undefined) { tools.push(afterPlacement(readOnly ? createBashReadonlyTool(env, rootCanonical, new Set(bashReadonlyAllow ?? BASH_READONLY_DEFAULT_ALLOW), { modelShell, ...(opts.bashDefaultTimeoutMs !== undefined ? { bashDefaultTimeoutMs: opts.bashDefaultTimeoutMs } : {}), ...(opts.bashMaxTimeoutMs !== undefined ? { bashMaxTimeoutMs: opts.bashMaxTimeoutMs } : {}), ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}), ...(opts.shellReadAdmission !== undefined ? { shellReadAdmission: opts.shellReadAdmission } : {}), ...(readFloor !== undefined ? { readFloor } : {}), ...(opts.commandSandbox !== undefined ? { commandSandbox: opts.commandSandbox } : {}), ...(opts.imageProcessor !== undefined ? { imageProcessor: opts.imageProcessor } : {}), ...(opts.onToolProgress !== undefined ? { onToolProgress: opts.onToolProgress } : {}), ...(opts.onEnvRefusal !== undefined ? { onEnvRefusal: opts.onEnvRefusal } : {}), }) : createBashTool(env, rootCanonical, commitCoAuthor, cwdRef, { modelShell, taskRegistry: opts.taskRegistry, taskOwner: opts.taskOwner, taskScope: opts.taskScope, ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}), ...(opts.occupant !== undefined ? { occupant: opts.occupant } : {}), ...(opts.retainBackgroundProcesses !== undefined ? { retainBackgroundProcesses: opts.retainBackgroundProcesses } : {}), onTaskNotification: opts.taskNotification, detachHub: opts.detachHub, ...(opts.autoBackgroundOnTimeout !== undefined ? { autoBackgroundOnTimeout: opts.autoBackgroundOnTimeout } : {}), ...(opts.onToolProgress !== undefined ? { onToolProgress: opts.onToolProgress } : {}), ...(opts.onEnvRefusal !== undefined ? { onEnvRefusal: opts.onEnvRefusal } : {}), ...(opts.queuedHumanInput !== undefined ? { queuedHumanInput: opts.queuedHumanInput } : {}), ...(opts.turnCutMovesCommandAside !== undefined ? { turnCutMovesCommandAside: opts.turnCutMovesCommandAside } : {}), ...(opts.oneShot !== undefined ? { oneShot: opts.oneShot } : {}), ...(additionalRoots !== undefined ? { additionalRoots } : {}), ...(opts.shellReadAdmission !== undefined ? { shellReadAdmission: opts.shellReadAdmission } : {}), ...(readFloor !== undefined ? { readFloor } : {}), ...(opts.commandSandbox !== undefined ? { commandSandbox: opts.commandSandbox } : {}), ...(opts.imageProcessor !== undefined ? { imageProcessor: opts.imageProcessor } : {}), ...(opts.bashDefaultTimeoutMs !== undefined ? { bashDefaultTimeoutMs: opts.bashDefaultTimeoutMs } : {}), ...(opts.bashMaxTimeoutMs !== undefined ? { bashMaxTimeoutMs: opts.bashMaxTimeoutMs } : {}), ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}), ...(opts.monitorToolActive !== undefined ? { monitorToolActive: opts.monitorToolActive } : {}), ...(opts.reminderMark !== undefined ? { reminderMark: opts.reminderMark } : {}), }))); if (!readOnly && mountBackgroundTaskTools && modelShell.background.launch && opts.taskRegistry !== undefined) { const sessionAxis = opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}; tools.push(createTaskStopTool({ registry: opts.taskRegistry, owner: opts.taskOwner, scope: opts.taskScope, ...sessionAxis, ...(opts.occupant !== undefined ? { occupant: opts.occupant } : {}) })); } } return tools; } function bandOwnTables(env, opts, rootCanonical) { const readDenyAdditions = (opts.readDenyPatterns ?? []).map((e) => (typeof e === "object" && e !== null ? { ...e } : e)); const readDenyRules = opts.pathDenyRules === undefined ? undefined : [...opts.pathDenyRules]; const readDenyBuiltinCfg = readDenyBuiltinConfigOf({ tiers: opts.readDenyBuiltinTiers, exclude: opts.readDenyBuiltinExclude }); const readDenyHomes = opts.readDenyHomes === undefined ? undefined : [...checkedReadDenyHomes(opts.readDenyHomes)]; const compileAt = (homes, linked) => compileReadDeny(readDenyAdditions, "HandsToolkitOptions.readDenyPatterns", readDenyBuiltinCfg, readDenyRules, homes, linked); const unplaced = compileAt([]); const carried = readDenyHomes !== undefined && opts.readDenyHomeLinks !== undefined; const carriedViews = carried ? placementViewsOf(opts.readDenyHomes) : undefined; if (carried && carriedViews === undefined) sayPlacementLost(opts.onNotice); const placesNothing = !unplaced.entries.some((e) => readDenyRowAnchor(e.pattern) !== "none"); const late = carried || placesNothing ? undefined : readDenyPlacedLater(carryHomeViews(unplaced, homeViewsAt(env, [])), () => placeReadDenyAtHome(env, compileAt, readDenyHomes, undefined, { workspaceRoot: rootCanonical })); const readDeny = late?.matcher ?? (carried ? carriedViews !== undefined ? carryHomeViews(compileAt(readDenyHomes, opts.readDenyHomeLinks), carriedViews) : carryHomeViews(unplaced, homeViewsAt(env, [])) : carryHomeViews(unplaced, homeViewsAt(env, readDenyHomes ?? []))); const afterPlacement = (tool) => late === undefined ? tool : { ...tool, execute: async (...args) => { await withGateTimeout(late.ready(), undefined, args[2], "readDenyPlacement").catch(() => undefined); return await tool.execute(...args); }, }; const writeDenyCompiled = compileWriteDeny(readDeny); const writeDeny = writeDenyCompiled.hasRows ? carryHomeViews(writeDenyCompiled, readDeny.homeViews) : undefined; return { readDeny, writeDeny, afterPlacement }; }