UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

96 lines (95 loc) • 6.45 kB
import { wrapApprover } from "../tool-policy.js"; import { readArtifactHostCapabilities } from "../artifact-host.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { RosterBuilder } from "../tool-roster.js"; import { defineTool } from "../tools.js"; import { inlineUntrusted } from "../untrusted-text.js"; import { foreignLine } from "../protocol-http-auth.js"; import { physicalPathOfExisting } from "../physical-path.js"; import { resolveKey, rootAdmittingArtifactStore, violationDetails, violationText } from "../../tools/fs/safety.js"; import { readObjectAt, readWithin, sameKeyAgain } from "../../tools/fs/bound-open.js"; import { assembleArtifactTool } from "../../tools/artifact/artifact-tool.js"; import { announceSharedArtifactReads, resolveSharedArtifactReads, sharedArtifactReadsLayersOf } from "../shared-artifact-reads.js"; import { heldWhileClassifying } from "../auto-mode.js"; import { sharedReadClassifier } from "./shared-read-classifier.js"; import { frozenApproverRoute } from "../wiring-manifest.js"; import { thrownText } from "../thrown-value.js"; export function prepareArtifact(input) { const { deps, announce, runId, taskId, sessionId, agentName, binding, onAsk: approver, toolOccurrences, permissionMode, autoMode, executionEnv, rootCanonical, additionalRootsCanonical, outsideReadRemedy, readDenyMatcher, resolvedReadFace, handsCwdRef, roster, firstPartyOffload, artifactStoreRef } = input; const host = deps.artifactHost; if (host === undefined) return { artifactPlane: undefined }; const refuse = (problem) => { roster.mounts.know({ "artifact.verdict": false }); deliverEngineNotice(deps.onNotice, { code: "config.artifact_host_invalid", message: `RunnerDeps.artifactHost is wired but unusable, so no Artifact tool is mounted for this task: ${problem}`, detail: { problem, sessionId, runId }, }); return { artifactPlane: undefined }; }; const verdict = readArtifactHostCapabilities(host); if (!verdict.ok) return refuse(verdict.problem); const storageDir = verdict.capabilities.storageDir; const storePhysical = storageDir !== undefined && rootCanonical !== undefined ? physicalPathOfExisting(storageDir) : undefined; if (artifactStoreRef !== undefined) artifactStoreRef.current = storePhysical; if (storePhysical !== undefined && rootCanonical !== undefined) { const overlapping = rootAdmittingArtifactStore(storePhysical, [rootCanonical, ...additionalRootsCanonical()]); if (overlapping !== undefined) return refuse(`the local artifact store ${storageDir} and a root this run may reach through its file tools (${overlapping}) overlap — the store lies inside a root, or the root inside the store; put the store outside every task root and additional directory`); } try { host.onMount?.(runId); } catch (err) { return refuse(`artifactHost.onMount threw: ${thrownText(err)}`); } const readLocalFile = async (path, maxBytes, signal) => { if (rootCanonical === undefined) return { ok: false, reason: "refused", text: "Error (Artifact): this task has no filesystem root, so a local file cannot be published." }; await additionalRootsCanonical.ready(signal); const cwd = handsCwdRef?.current; const judge = (s) => resolveKey(executionEnv, rootCanonical, path, s, cwd, additionalRootsCanonical, undefined, readDenyMatcher, resolvedReadFace, outsideReadRemedy); const rk = await judge(signal); if (!rk.ok) return { ok: false, reason: "refused", text: violationText("Artifact", rk.violation), details: violationDetails(rk.violation) }; const opened = await readObjectAt(executionEnv, rk.key, sameKeyAgain((s) => judge(s ?? signal), rk.key), signal); if (!opened.ok) return { ok: false, reason: "refused", text: `Error (Artifact): cannot ${opened.step === "open" ? "read" : "stat"} ${inlineUntrusted(path, 200)} (${foreignLine(opened.error.code, 40)}).` }; try { if (opened.value.kind !== "file") return { ok: false, reason: "not_a_file", kind: opened.value.kind }; const r = await readWithin(opened.value, maxBytes, signal); if (r.kind === "over") return { ok: false, reason: "too_large", size: r.size, limit: maxBytes, judgedOn: r.on === "size" ? "metadata" : "bytes" }; if (r.kind === "failed") return { ok: false, reason: "refused", text: `Error (Artifact): cannot read ${inlineUntrusted(path, 200)} (${foreignLine(r.error.code, 40)}).` }; return { ok: true, key: rk.key, bytes: r.bytes }; } finally { await opened.value.close(); } }; const onAsk = wrapApprover(approver, (inner) => (req, signal) => toolOccurrences.whileHeld(req.toolCallId, "approval", () => inner(req, signal))); const classifySharedRead = sharedReadClassifier({ decider: () => { const d = autoMode.decider(); return d === undefined ? undefined : heldWhileClassifying(d, (toolCallId, judge) => toolOccurrences.whileHeld(toolCallId, "classifier", judge)); }, tracking: autoMode.tracking, mode: () => permissionMode.current, route: frozenApproverRoute(onAsk), }); const inherited = input.sharedReads.current; const sharedReads = inherited ?? (input.sharedReads.current = resolveSharedArtifactReads(sharedArtifactReadsLayersOf(deps.sharedArtifactReads))); const artifactSpec = assembleArtifactTool({ host, runId, taskId, sessionId, ...(agentName !== undefined ? { agentName } : {}), binding, readLocalFile, ...(onAsk !== undefined ? { onAsk } : {}), permissionMode: () => permissionMode.current, classifySharedRead, sharedReads }, verdict.capabilities, deps.onNotice); roster.mounts.know({ "artifact.verdict": true }); if (roster.mounts.judge("artifact")) { roster.mount(firstPartyOffload(defineTool(artifactSpec)), { source: "builtin", mountedBy: "optional" }); if (inherited === undefined) announceSharedArtifactReads(sharedReads, { ...(deps.onNotice !== undefined ? { onNotice: deps.onNotice } : {}), oncePerSession: announce.oncePerSession, legNotice: announce.legNotice, runId }); } return { artifactPlane: verdict.capabilities.plane }; }