@sema-agent/core
Version:
Stateless, task-oriented AI agent core
109 lines (108 loc) • 7.21 kB
JavaScript
import { legNoticeTaskId } from "../mods/stations.js";
import { deliverEngineNotice } from "../types.js";
import { READ_ROOT_CANDIDATE_DIR_MAX } from "../read-root-candidate.js";
import { DEFAULT_GATE_AWAIT_TIMEOUT_MS } from "../gate-bounded-await.js";
import { thrownText } from "../thrown-value.js";
import { rootAdmittingArtifactStore } from "../../tools/fs/safety.js";
import { envErrorDetail } from "../../tools/fs/env-error-detail.js";
export function readRootGrantOver(seats) {
const { env, writeRoots, readRoots, artifactStore, session } = seats;
const lastsFor = (candidate) => (candidate.covers !== "exact" && session?.kept() === true ? "session" : "run");
const forTheRun = (root, kept) => {
if (!writeRoots.includes(root) && !readRoots.includes(root))
readRoots.push(root);
return { ok: true, root, lasts: "run", ...(kept !== undefined ? { kept } : {}) };
};
return {
lastsFor,
apply: async (candidate, lasts, card, signal, onWriting) => {
const c = await env.canonicalPath(candidate.dir);
if (signal.aborted)
return { ok: false, reason: "unresolvable", cause: "the lookup was cut" };
if (!c.ok)
return { ok: false, reason: "unresolvable", cause: `${c.error.code}: ${envErrorDetail(c.error.message)}` };
if (c.value !== candidate.dir)
return { ok: false, reason: "resolves_elsewhere", cause: `it resolves to ${c.value}` };
const store = artifactStore.current;
if (store !== undefined && rootAdmittingArtifactStore(store, [c.value]) !== undefined)
return { ok: false, reason: "admits_artifact_store", cause: "the Artifact tool's ledger and stored files stay outside every root the file tools reach" };
if (lasts !== "session" || session === undefined)
return forTheRun(c.value);
if (signal.aborted)
return { ok: false, reason: "unresolvable", cause: "the call ended before the session rule was written" };
onWriting?.();
const written = await session.write(c.value, card, signal).catch((err) => ({ landed: false, reason: thrownText(err), committed: "unknown" }));
if (written.landed)
return { ok: true, root: c.value, lasts: "session" };
if (written.committed === "no") {
if (signal.aborted)
return { ok: false, reason: "unresolvable", cause: "the call ended before the session rule was written" };
return forTheRun(c.value, `the session rule could not be written (${written.reason})`);
}
return { ...forTheRun(c.value, `the session rule's write could not be confirmed (${written.reason}) — if it landed, the directory stays readable for the rest of the session`), unconfirmed: true };
},
};
}
const NARROWED = {
not_offered: "this card offered the directory for this run only",
not_a_person: "a session-long grant takes a person's answer, and a policy answered",
};
export function settleReadRootGrant(screen, grant, at) {
if (screen === undefined)
return undefined;
const ids = { toolName: at.toolName, toolCallId: at.toolCallId, checkpointId: at.checkpointId, sessionId: at.sessionId, runId: at.runId, ...legNoticeTaskId(at) };
const reject = (reason, offered, requested, why) => deliverEngineNotice(at.onNotice, {
code: "approval.read_root_grant_rejected",
message: `the approval for "${at.toolName}" asked to add a read directory, and nothing was added: ${why}. The approval's own verdict is unchanged.`,
detail: { reason, ...(offered !== undefined ? { offered } : {}), ...(requested !== undefined ? { requested: requested.slice(0, READ_ROOT_CANDIDATE_DIR_MAX) } : {}), ...ids },
});
if (screen.verdict === "rejected") {
const why = {
not_a_string: "the grant is not a string",
lasts_invalid: 'how long a directory grant lasts is exactly "session" or "run", and it rides a directory grant',
no_candidate: "this approval card offered no directory",
mismatch: "the grant is not the directory the card offered (it must be sent back exactly as offered)",
}[screen.reason];
reject(screen.reason, screen.offered, screen.requested, why);
return undefined;
}
const { candidate } = screen;
if (grant === undefined) {
reject("no_read_roots", candidate.dir, candidate.dir, "this run has no read directories to widen");
return undefined;
}
const cut = AbortSignal.any([...(at.signal !== undefined ? [at.signal] : []), AbortSignal.timeout(DEFAULT_GATE_AWAIT_TIMEOUT_MS)]);
let writing = false;
const cutShort = new Promise((resolve) => {
const onCut = () => {
const when = at.signal?.aborted === true ? "the call ended before it resolved" : `it did not resolve within ${DEFAULT_GATE_AWAIT_TIMEOUT_MS}ms`;
resolve({ ok: false, reason: "unresolvable", cause: writing ? `${when}, while the session rule was being written — if that write lands, the directory stays readable for the rest of the session` : when });
};
if (cut.aborted)
onCut();
else
cut.addEventListener("abort", onCut, { once: true });
});
const card = { toolCallId: at.toolCallId, ...(at.boundInputHash !== undefined ? { boundInputHash: at.boundInputHash } : {}) };
const attempt = grant.apply(candidate, screen.lasts, card, cut, () => void (writing = true)).catch((err) => ({ ok: false, reason: "unresolvable", cause: thrownText(err) }));
return Promise.race([attempt, cutShort]).then((applied) => {
if (!applied.ok) {
const why = {
unresolvable: `the directory could not be resolved (${applied.cause})`,
resolves_elsewhere: `the offered path no longer resolves to itself (${applied.cause})`,
admits_artifact_store: `the directory would admit the artifact store (${applied.cause})`,
}[applied.reason];
reject(applied.reason, candidate.dir, candidate.dir, why);
return;
}
const what = `${candidate.covers === "exact" ? "the path" : "the directory"} ${candidate.dir}`;
const kept = applied.kept ?? (screen.narrowed !== undefined ? NARROWED[screen.narrowed] : undefined);
deliverEngineNotice(at.onNotice, {
code: "approval.read_root_granted",
message: applied.lasts === "session"
? `the approval for "${at.toolName}" made ${what} readable for the rest of this session (reads only; a session rule, which the session's later runs read too).`
: `the approval for "${at.toolName}" added ${what} to this run's read directories (reads only; for the rest of this run${kept !== undefined ? ` — ${kept}` : ""}).`,
detail: { dir: candidate.dir, ...(candidate.covers !== undefined ? { covers: candidate.covers } : {}), root: applied.root, lasts: applied.lasts, ...(applied.unconfirmed === true ? { sessionUnconfirmed: true } : {}), ...ids },
});
});
}