@sema-agent/core
Version:
Stateless, task-oriented AI agent core
771 lines (770 loc) • 48.7 kB
JavaScript
import { arbitrateByMode, askClassMembersOf, classifyAsk } from "../../core/ask-origin.js";
import { deliverEngineNotice } from "../../core/engine-notice.js";
import { modeReleaseOf } from "../../core/gate-outcome.js";
import { attestationOf } from "../../core/engine-attestation.js";
import { createHash } from "node:crypto";
import { Type } from "typebox";
import { ARTIFACT_ACTION_CONCURRENCY_SAFE, ARTIFACT_COMMIT_THROW_OUTCOME, ARTIFACT_FAILURE_RESULT_CODE, ARTIFACT_HOST_ERROR_CODE, ARTIFACT_LIST_SCOPES, ARTIFACT_PLANE_CONTENT_ORIGIN, ARTIFACT_PUBLISH_CONTEXTS, readArtifactHostCapabilities, } from "../../core/artifact-host.js";
import { BOUNDARY_LEGS } from "../../core/cross-boundary-taint.js";
const ARTIFACT_ACTION_LEGS = {
hosted: { publish: ["env", "outside_write"], list: ["outside_read"], read: ["outside_read"], list_files: ["outside_read"], read_file: ["outside_read"] },
"local-stub": { publish: ["env"], list: [], read: [], list_files: [], read_file: [] },
};
import { ARTIFACT_TOOL_NAME, mountRuleFace, toolFace } from "../../core/tool-catalog-entries.js";
import { attest, resolveAskFor } from "../../core/tool-policy.js";
import { mintCheckpointId } from "../../core/checkpoint-store.js";
import { NOT_BINDABLE } from "../../core/skill-grant-binding.js";
import { approvalCardOf } from "../../core/tool-roster.js";
import { errorResult } from "../../core/tools.js";
import { inlineUntrusted } from "../../core/untrusted-text.js";
import { foreignLine } from "../../core/protocol-http-auth.js";
import { actionDescription, artifactDescription, PARAM_TEXT, urlDescription } from "./artifact-text.js";
import { ARTIFACT_REJECT_BREAKER_THRESHOLD, artifactRejectBannerFor, artifactRejectKeyOf, createArtifactRejectBreaker } from "./reject-breaker.js";
import { thrownText } from "../../core/thrown-value.js";
import { identityReadVerdict, ownerIdentityOf, recordedOwnerIdentityOf } from "../../core/owner-identity.js";
import { readPrincipal } from "../../core/principal-name.js";
const ARTIFACT_OWNER_REFUSAL_REASONS = Object.freeze(["other_identity", "no_identity", "owner_unreadable", "no_owner", "own_page_marked_shared"]);
export const MAX_FILES_PER_PUBLISH = 255;
const LIST_LIMIT_DEFAULT = 25;
const LIST_LIMIT_MAX = 100;
const SHARED_READ_SCOPE = "approving covers re-reads of it for the rest of this run.";
const BINARY_NOTE_MEDIA = new Set(["application/json", "application/javascript", "text/javascript", "image/svg+xml", "application/xml"]);
const MEDIA_BY_EXT = new Map(Object.entries({
html: "text/html", htm: "text/html", css: "text/css", js: "text/javascript", mjs: "text/javascript", json: "application/json",
md: "text/markdown", txt: "text/plain", csv: "text/csv", xml: "application/xml", svg: "image/svg+xml", png: "image/png",
jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", ico: "image/x-icon", woff: "font/woff",
woff2: "font/woff2", ttf: "font/ttf", wasm: "application/wasm", pdf: "application/pdf", mp3: "audio/mpeg", mp4: "video/mp4",
}));
export function mediaTypeOf(path) {
const dot = path.lastIndexOf(".");
return (dot >= 0 ? MEDIA_BY_EXT.get(path.slice(dot + 1).toLowerCase()) : undefined) ?? "application/octet-stream";
}
export function isTextMedia(mediaType) {
if (mediaType === undefined)
return false;
const essence = mediaType.split(";")[0].trim().toLowerCase();
return essence.startsWith("text/") || BINARY_NOTE_MEDIA.has(essence);
}
export function artifactAttemptId(runId, toolCallId, occurrence = 0) {
const h = createHash("sha256").update(runId).update("|").update(toolCallId).update("|").update(String(occurrence)).digest("hex");
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
}
const basenameOf = (p) => {
const i = Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"));
return i >= 0 ? p.slice(i + 1) : p;
};
const hostFolded = (url) => url.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#@]*@)?([^/?#:]*)/, (_m, scheme, user, host) => `${scheme.toLowerCase()}${user ?? ""}${host.toLowerCase()}`);
export function normalizePublishedPath(raw) {
if (raw.length === 0)
return { ok: false, reason: "is empty" };
if (raw.includes("\0"))
return { ok: false, reason: "contains a NUL byte" };
if (raw.includes("\\"))
return { ok: false, reason: "contains a backslash (use forward slashes)" };
if (raw.startsWith("/"))
return { ok: false, reason: "is root-relative (no leading slash)" };
const path = raw.normalize("NFC");
for (const seg of path.split("/"))
if (seg === "" || seg === "." || seg === "..")
return { ok: false, reason: "contains an empty, `.` or `..` segment" };
return { ok: true, path };
}
function renderSnapshotMeta(s) {
const meta = ["title", "description", "favicon", "label"].filter((k) => s[k] !== undefined).map((k) => `${k}: ${foreignLine(s[k], 200)}`);
return meta.length === 0 ? "" : `${meta.join("\n")}\n`;
}
function renderFile(f) {
const head = `--- ${inlineUntrusted(f.path, 200)} (${inlineUntrusted(f.mediaType ?? "application/octet-stream", 80)}, ${String(f.content.byteLength).slice(0, 20)} bytes) ---`;
return isTextMedia(f.mediaType) ? `${head}\n${Buffer.from(f.content).toString("utf8")}` : `${head}\n[binary content, not shown]`;
}
const isRecord = (x) => x !== null && typeof x === "object";
const withDefaultAction = (args) => (isRecord(args) && args["action"] === undefined ? { ...args, action: "publish" } : args);
const everyItem = (x, pred) => Array.isArray(x) && x.every(pred);
const optString = (v) => v === undefined || typeof v === "string";
const isRef = (x) => isRecord(x) && typeof x["url"] === "string" && typeof x["slug"] === "string" && typeof x["version"] === "string" && optString(x["title"]);
const isFile = (x) => isRecord(x) && typeof x["path"] === "string" && x["content"] instanceof Uint8Array && optString(x["mediaType"]);
const isSnapshot = (x) => isRecord(x) && everyItem(x["files"], isFile) && optString(x["title"]) && optString(x["description"]) && optString(x["favicon"]) && optString(x["label"]);
const failureWord = (x, allowed) => isRecord(x) && typeof x["code"] === "string" && allowed.includes(x["code"]);
const OUTCOME_SHAPE = {
publish: (o) => isRecord(o) &&
(o["ok"] === true
? isRef(o["ref"])
: o["ok"] === false &&
(o["code"] === "conflict"
? typeof o["currentVersion"] === "string" && (o["current"] === "reread" || isSnapshot(o["current"]))
: failureWord(o, ["url_foreign", "forbidden", "payload_too_large", "not_found", "force_refused", "refused"]) && typeof o["message"] === "string")),
list: (o) => isRecord(o) &&
(o["ok"] === true
? everyItem(o["rows"], (r) => isRef(r) && isRecord(r) && (r["owner"] === undefined || r["owner"] === "shared") && typeof r["updatedAt"] === "string") && typeof o["truncated"] === "boolean"
: o["ok"] === false && failureWord(o, ["refused"]) && typeof o["message"] === "string"),
read: (o) => isRecord(o) && (o["ok"] === true ? isRef(o["ref"]) && typeof o["content"] === "string" && typeof o["isolatedSummary"] === "boolean" : o["ok"] === false && failureWord(o, ["not_found", "forbidden"]) && typeof o["message"] === "string"),
list_files: (o) => isRecord(o) && (o["ok"] === true ? everyItem(o["entries"], (e) => isRecord(e) && typeof e["path"] === "string" && typeof e["bytes"] === "number" && optString(e["mediaType"])) : o["ok"] === false && failureWord(o, ["not_found", "forbidden"]) && typeof o["message"] === "string"),
read_file: (o) => isRecord(o) && (o["ok"] === true ? isFile(o["file"]) : o["ok"] === false && failureWord(o, ["not_found", "forbidden"]) && typeof o["message"] === "string"),
};
function callHost(action, fn, signal) {
if (signal?.aborted)
return Promise.resolve({ ok: false, kind: "aborted", message: "the call was aborted before the host was reached" });
return new Promise((resolve) => {
const onAbort = () => resolve({ ok: false, kind: "aborted", message: "the call was aborted while the host was working" });
signal?.addEventListener("abort", onAbort, { once: true });
let p;
try {
p = Promise.resolve(fn());
}
catch (err) {
signal?.removeEventListener("abort", onAbort);
resolve({ ok: false, kind: "threw", message: thrownText(err) });
return;
}
p.then((value) => resolve(OUTCOME_SHAPE[action](value) ? { ok: true, value } : { ok: false, kind: "malformed", message: `the ${action} answer was outside the host contract` }), (err) => resolve({ ok: false, kind: "threw", message: thrownText(err) })).finally(() => signal?.removeEventListener("abort", onAbort));
});
}
function buildSchema(caps) {
const has = (a) => caps.actions.includes(a);
const props = {
action: Type.Optional(Type.Unsafe({ type: "string", enum: [...caps.actions], description: actionDescription(caps.actions) })),
file_path: Type.Optional(Type.String({ description: PARAM_TEXT.filePath })),
url: Type.Optional(Type.String({ maxLength: 2048, description: urlDescription(caps.actions) })),
title: Type.Optional(Type.String({ maxLength: 200, description: PARAM_TEXT.title })),
description: Type.Optional(Type.String({ maxLength: 1000, description: PARAM_TEXT.description })),
favicon: Type.Optional(Type.String({ maxLength: 32, description: PARAM_TEXT.favicon })),
label: Type.Optional(Type.String({ maxLength: 60, description: PARAM_TEXT.label })),
baseVersion: Type.Optional(Type.String({ maxLength: 200, description: PARAM_TEXT.baseVersion })),
force: Type.Optional(Type.Boolean({ description: PARAM_TEXT.force })),
publishContext: Type.Optional(Type.Unsafe({ type: "string", enum: [...ARTIFACT_PUBLISH_CONTEXTS], description: PARAM_TEXT.publishContext })),
};
if (caps.multiFile) {
props["files"] = Type.Optional(Type.Array(Type.Object({ path: Type.String(), file_path: Type.String() }), { maxItems: MAX_FILES_PER_PUBLISH, description: PARAM_TEXT.files }));
}
if (has("list")) {
props["scope"] = Type.Optional(Type.Unsafe({ type: "string", enum: [...ARTIFACT_LIST_SCOPES], description: PARAM_TEXT.scope }));
props["limit"] = Type.Optional(Type.Integer({ minimum: 1, maximum: LIST_LIMIT_MAX, description: PARAM_TEXT.limit }));
}
if (has("read_file"))
props["path"] = Type.Optional(Type.String({ maxLength: 1024, description: PARAM_TEXT.path }));
return Type.Object(props);
}
function readArtifactCallBinding(raw) {
const refuse = (what) => {
throw new TypeError(`createArtifactTool: the binding ${what}`);
};
if (!isRecord(raw))
return refuse("must be an object carrying `identity` and `root`");
const identity = raw["identity"];
if (!isRecord(identity) || Array.isArray(identity))
return refuse("must carry an `identity` object (`{ principal: null }` is the anonymous identity)");
const given = identity["principal"];
const principal = given === null ? undefined : given;
const named = readPrincipal(principal);
if (named.kind === "invalid")
return refuse(`identity's principal must be a principal name, null (the anonymous identity) or absent (got ${named.fault})`);
const scope = identity["isolationScope"];
const scoped = readPrincipal(scope);
if (scoped.kind === "invalid")
return refuse(`identity's isolationScope must be a name or absent (got ${scoped.fault})`);
const root = raw["root"];
if (!isRecord(root))
return refuse("must carry a `root` with a string `sessionId` (the delegation tree's root conversation)");
const sessionId = root["sessionId"];
if (typeof sessionId !== "string")
return refuse("must carry a `root` with a string `sessionId` (the delegation tree's root conversation)");
const occupant = root["occupant"];
if (occupant !== undefined && typeof occupant !== "string")
return refuse("root's occupant must be a string when present");
const owner = ownerIdentityOf({ ...(typeof principal === "string" ? { principal } : {}), ...(typeof scope === "string" ? { isolationScope: scope } : {}) });
return Object.freeze({ identity: Object.freeze(owner), root: Object.freeze({ sessionId, ...(typeof occupant === "string" ? { occupant } : {}) }) });
}
const invalid = (text) => errorResult(`Error (Artifact): ${text}`, { type: "artifact", invalidArguments: true });
const typed = (code, text, extra = {}) => errorResult(`Error (Artifact): ${text}`, { type: "artifact", code: ARTIFACT_FAILURE_RESULT_CODE[code], ...extra });
const SHARED_READ_REFUSED = { mode: "was refused by the permission mode", classifier: "was refused by auto mode's classifier", ask_resolution: "was not approved" };
const sharedReadRefused = (url, target, refusal, withheld) => typed("refused", `reading the shared artifact ${target} ${SHARED_READ_REFUSED[refusal.deniedBy]} (${foreignLine(refusal.reason, 200)}); its ${withheld} ${withheld === "files" ? "were" : "was"} not delivered.`, { url, sharedRead: "not_approved", deniedBy: refusal.deniedBy, ...(refusal.settlement !== undefined ? { settlement: refusal.settlement } : {}) });
export function createArtifactTool(opts) {
const verdict = readArtifactHostCapabilities(opts.host);
if (!verdict.ok)
throw new TypeError(`createArtifactTool: ${verdict.problem}`);
return assembleArtifactTool(opts, verdict.capabilities);
}
export function assembleArtifactTool(opts, caps, onNotice) {
const { host, runId, taskId, sessionId, agentName, readLocalFile, onAsk, permissionMode, classifySharedRead } = opts;
const setting = opts.sharedReads;
const settingLayer = setting?.value === "allow" ? setting.decidedBy : undefined;
const settingAllows = settingLayer === "managed" || settingLayer === "user" ? settingLayer : undefined;
const binding = readArtifactCallBinding(opts.binding);
const versions = new Map();
const bindings = new Map();
const occurrences = new Map();
const breaker = createArtifactRejectBreaker();
const ownUrls = new Set();
const sharedUrls = new Map();
const sharedReadApproved = new Set();
const consentInFlight = new Map();
const askedCalls = new Map();
const releasedCalls = new Map();
const settingCalls = new Set();
const activeTargets = new Map();
const ownerAccounts = new Map();
const hasAction = (a) => caps.actions.includes(a);
const rememberRef = (ref) => {
versions.set(ref.url, ref.version);
};
const rememberOwn = (url) => {
ownUrls.add(url);
};
const rejudged = new Set();
const forgetOwn = (url) => {
ownUrls.delete(url);
versions.delete(url);
for (const [path, bound] of bindings)
if (bound === url)
bindings.delete(path);
};
const judgeAgain = (url) => {
if (hasAction("read") && ownUrls.delete(url))
rejudged.add(url);
};
const asKnown = (url) => {
const known = [...ownUrls, ...rejudged, ...sharedUrls.keys(), ...versions.keys()];
if (known.includes(url))
return url;
const folded = hostFolded(url);
return known.find((u) => hostFolded(u) === folded) ?? url;
};
const accountOf = (ctx) => {
const account = ownerAccounts.get(ctx.toolCallId) ?? { reasons: new Set(), count: 0, write: "none" };
ownerAccounts.set(ctx.toolCallId, account);
return account;
};
const noteOwner = (ctx, reason) => {
const account = accountOf(ctx);
account.reasons.add(reason);
account.count += 1;
};
const noteWriteUnknown = (ctx) => {
accountOf(ctx).write = "unknown";
};
const tellOwnerAccount = (toolCallId, action) => {
const account = ownerAccounts.get(toolCallId);
if (account === undefined)
return;
ownerAccounts.delete(toolCallId);
const reasons = ARTIFACT_OWNER_REFUSAL_REASONS.filter((r) => account.reasons.has(r));
const onlyContradiction = reasons.length === 1 && reasons[0] === "own_page_marked_shared";
const outcome = account.write === "unknown" ? "the model was told the host's answer to the publish was withheld, and whether the host wrote is not known" : "the model was answered as if the page were not there, and nothing was updated";
deliverEngineNotice(onNotice, {
code: "artifact.owner_refused",
message: onlyContradiction
? `the artifact host (${caps.plane}) marked this run's own page as shared; the page's owner record decided and it was treated as the run's own (${action})`
: `the artifact host (${caps.plane}) handed back ${account.count} owner record(s) that do not name this run's identity (${reasons.join(", ")}); ${outcome} (${action})`,
detail: { action, reasons, count: account.count, write: account.write, plane: caps.plane, toolCallId, ...(sessionId !== undefined ? { sessionId } : {}), runId },
});
};
const judgeOwner = (recordOf, marker, url, ctx) => {
let record;
let verdict;
rejudged.delete(url);
try {
record = recordOf();
verdict = identityReadVerdict(record, binding.identity);
}
catch {
verdict = "owner_unreadable";
}
if (verdict === "readable") {
if (marker === true)
noteOwner(ctx, "own_page_marked_shared");
rememberOwn(url);
return "mine";
}
forgetOwn(url);
if (verdict === "other_identity" && caps.ownership.sharing === "marked" && marker !== false) {
const owner = recordedOwnerIdentityOf(record);
const judged = sharedUrls.get(url) ?? [];
const known = typeof owner === "object" && judged.some((o) => identityReadVerdict(owner, o) === "readable");
if (marker === true && typeof owner === "object") {
if (!known)
sharedUrls.set(url, [...judged, Object.freeze(owner)]);
return "shared";
}
if (known)
return "shared";
}
noteOwner(ctx, verdict);
return "refused";
};
const refView = (r) => ({ url: r.url, slug: r.slug, version: r.version, ...(r.title !== undefined ? { title: r.title } : {}) });
const notThere = (url, publishing) => typed("not_found", `no artifact at ${foreignLine(url ?? "", 200)}${publishing ? "; nothing was published" : ""}.`, { url });
const notThisRuns = (url, publishing) => typed("url_foreign", `${foreignLine(url, 200)} is not an artifact this run published; ${publishing ? "nothing was published" : "its files were not delivered"}.`, { url });
const sharedReadOnly = (url) => typed("forbidden", `${foreignLine(url, 200)} is an artifact shared with the user: shared artifacts can be read but never updated — updating requires an artifact the user owns; nothing was published.`, { url });
const nextContext = (ctx) => {
const n = occurrences.get(ctx.toolCallId) ?? 0;
occurrences.set(ctx.toolCallId, n + 1);
return {
taskId,
...(sessionId !== undefined ? { sessionId } : {}),
...(agentName !== undefined ? { agentName } : {}),
runId,
attemptId: artifactAttemptId(runId, ctx.toolCallId, n),
binding,
};
};
const hostError = (verb, fault, url) => {
const outcome = fault.kind === "threw" ? ARTIFACT_COMMIT_THROW_OUTCOME[caps.commit] : "unknown";
const details = { type: "artifact", code: ARTIFACT_HOST_ERROR_CODE, outcome, plane: caps.plane, commit: caps.commit };
if (outcome === "not_executed") {
return errorResult(`Error (Artifact): the artifact host failed before committing (${foreignLine(fault.message, 200)}). Nothing was published; the call can be repeated.`, details);
}
const verifiable = hasAction("read") && url !== "";
return errorResult(`Error (Artifact): the artifact host did not answer the ${verb.slice(0, 20)} (${foreignLine(fault.message, 200)}). Whether it was applied is not known: it may already have been committed, so do not simply repeat the call.${verifiable ? ` Verify with action: "read" on ${url.slice(0, 200)} first.` : ""}`, details);
};
const pageRefused = (code, url, message) => {
forgetOwn(url);
return code === "not_found" ? notThere(url, false) : typed(code, `${foreignLine(url, 200)} is not accessible to this session (${foreignLine(message, 200)}).`, { url });
};
const readRefusal = (path, r) => {
switch (r.reason) {
case "refused":
return errorResult(r.text.slice(0, 4000), r.details);
case "too_large":
return typed("payload_too_large", `${inlineUntrusted(path, 200)} is ${String(r.size).slice(0, 20)} bytes; this host accepts at most ${String(r.limit).slice(0, 20)} bytes for it${r.judgedOn === "metadata" ? " (the file was not read)" : " (it grew past its declared size while being read)"}.`, { limit: r.limit, measured: r.size, judgedOn: r.judgedOn });
case "not_a_file":
return invalid(`${inlineUntrusted(path, 200)} is a ${foreignLine(r.kind, 20)}, not a regular file.`);
default: {
const _exhaustive = r;
return _exhaustive;
}
}
};
const manifestOf = (a) => {
const mainNorm = normalizePublishedPath(basenameOf(a.file_path));
if (!mainNorm.ok)
return { ok: false, result: invalid(`the published name of ${inlineUntrusted(a.file_path, 200)} ${mainNorm.reason.slice(0, 80)}.`) };
const entries = [];
if (a.files === undefined || (Array.isArray(a.files) && a.files.length === 0))
return { ok: true, main: mainNorm.path, entries };
if (!caps.multiFile)
return { ok: false, result: invalid("this artifact host publishes single files only; `files` is not accepted.") };
if (!Array.isArray(a.files))
return { ok: false, result: invalid("`files` must be an array of { path, file_path } entries.") };
if (a.files.length > MAX_FILES_PER_PUBLISH)
return { ok: false, result: invalid(`\`files\` carries ${String(a.files.length).slice(0, 20)} entries; at most ${MAX_FILES_PER_PUBLISH} supporting files are accepted per publish.`) };
const seen = new Set([mainNorm.path.toLowerCase()]);
for (const entry of a.files) {
if (!isRecord(entry) || typeof entry["path"] !== "string" || typeof entry["file_path"] !== "string")
return { ok: false, result: invalid("every `files` entry must carry a string `path` and a string `file_path`.") };
const norm = normalizePublishedPath(entry["path"]);
if (!norm.ok)
return { ok: false, result: invalid(`files entry ${inlineUntrusted(entry["path"], 120)} ${norm.reason.slice(0, 80)}.`) };
const fold = norm.path.toLowerCase();
if (seen.has(fold))
return { ok: false, result: invalid(`files entry ${inlineUntrusted(norm.path, 120)} collides with another published path.`) };
seen.add(fold);
entries.push({ path: norm.path, file_path: entry["file_path"] });
}
return { ok: true, main: mainNorm.path, entries };
};
async function publish(a, ctx) {
if (typeof a.file_path !== "string")
return invalid("`file_path` is required to publish.");
const manifest = manifestOf(a);
if (!manifest.ok)
return manifest.result;
const files = [];
const budget = Math.min(caps.maxFileBytes, caps.maxTotalBytes);
const first = await readLocalFile(a.file_path, budget, ctx.signal);
if (!first.ok)
return readRefusal(a.file_path, first);
files.push({ path: manifest.main, content: first.bytes, mediaType: mediaTypeOf(manifest.main) });
let total = first.bytes.byteLength;
const url = a.url ?? bindings.get(first.key);
if (url === undefined && (a.force === true || a.baseVersion !== undefined)) {
return invalid("`force` and `baseVersion` only apply to an update — pass `url`, or republish the same file path this session already published.");
}
if (url !== undefined && sharedUrls.has(url) && !ownUrls.has(url) && !rejudged.has(url))
return sharedReadOnly(url);
if (url !== undefined && !ownUrls.has(url)) {
const judged = await ownerBeforeWrite(url, ctx);
if (judged !== undefined)
return judged;
}
for (const entry of manifest.entries) {
const left = caps.maxTotalBytes - total;
if (left <= 0)
return typed("payload_too_large", `the files already total ${String(total).slice(0, 20)} bytes; this host accepts at most ${String(caps.maxTotalBytes).slice(0, 20)} bytes per version.`, { limit: caps.maxTotalBytes, measured: total });
const r = await readLocalFile(entry.file_path, Math.min(caps.maxFileBytes, left), ctx.signal);
if (!r.ok)
return readRefusal(entry.file_path, r);
total += r.bytes.byteLength;
files.push({ path: entry.path, content: r.bytes, mediaType: mediaTypeOf(entry.path) });
}
const baseVersion = a.baseVersion ?? (url !== undefined ? versions.get(url) : undefined);
const req = {
...(url !== undefined ? { url } : {}),
files,
...(a.title !== undefined ? { title: a.title } : {}),
...(a.description !== undefined ? { description: a.description } : {}),
...(a.favicon !== undefined ? { favicon: a.favicon } : {}),
...(a.label !== undefined ? { label: a.label } : {}),
...(baseVersion !== undefined ? { baseVersion } : {}),
...(a.force === true ? { force: true } : {}),
publishContext: a.publishContext ?? "plain",
};
const call = await callHost("publish", () => host.publish(req, nextContext(ctx)), ctx.signal);
if (!call.ok)
return hostError("publish", call, foreignLine(url ?? "", 200));
const out = call.value;
if (out.ok) {
if (judgeOwner(() => out.ref.ownerIdentity, false, out.ref.url, ctx) !== "mine") {
if (url !== undefined)
forgetOwn(url);
noteWriteUnknown(ctx);
return errorResult("Error (Artifact): the artifact host answered the publish with an owner record that does not name this run, so its answer was withheld. Whether anything was written is not known: do not simply repeat the call.", { type: "artifact", code: ARTIFACT_HOST_ERROR_CODE, outcome: "unknown", plane: caps.plane, commit: caps.commit });
}
rememberRef(out.ref);
bindings.set(first.key, out.ref.url);
const title = out.ref.title !== undefined ? ` — ${inlineUntrusted(out.ref.title, 120)}` : "";
return {
content: `Published ${inlineUntrusted(out.ref.url, 300)} (version ${inlineUntrusted(out.ref.version, 60)})${title}.`,
details: { type: "artifact", action: "publish", plane: caps.plane, ref: refView(out.ref), update: url !== undefined },
};
}
if (out.code === "conflict") {
let snapshot = out.current;
if (snapshot !== "reread") {
const held = snapshot;
const withheld = url === undefined || judgeOwner(() => held.ownerIdentity, false, url, ctx) !== "mine" || (await filesOwnership(url, ctx)) !== undefined;
const unconsented = url !== undefined && sharedUrls.has(url) && !sharedReadApproved.has(url);
if (withheld || (unconsented && settingAllows === undefined))
snapshot = "reread";
else if (unconsented)
settingCalls.add(ctx.toolCallId);
}
if (snapshot !== "reread" && url !== undefined)
versions.set(url, out.currentVersion);
const handedBack = snapshot === "reread"
? hasAction("read")
? `The current content was not handed back; read it with action: "read" on ${foreignLine(url ?? "", 200)}.`
: "The current content was not handed back by the host."
: `Current content follows.\n${renderSnapshotMeta(snapshot)}${snapshot.files.map(renderFile).join("\n")}`;
const current = snapshot === "reread" ? "reread" : (({ ownerIdentity: _owner, ...meta }) => ({ ...meta, files: meta.files.map((f) => ({ path: f.path, bytes: f.content.byteLength, mediaType: f.mediaType })) }))(snapshot);
return errorResult(`Error (Artifact): publish conflict — ${foreignLine(url ?? "", 200)} is at version ${foreignLine(out.currentVersion, 60)}, this publish was based on ${foreignLine(baseVersion ?? "", 60)}. Merge your changes onto the current content and publish again. ${handedBack}`, { type: "artifact", code: ARTIFACT_FAILURE_RESULT_CODE.conflict, url, currentVersion: out.currentVersion, current });
}
return publishRefused(out.code, url, out.message);
}
function publishRefused(code, url, message) {
if (url !== undefined && (code === "url_foreign" || code === "forbidden" || code === "not_found"))
forgetOwn(url);
switch (code) {
case "url_foreign":
return typed(code, `${foreignLine(url ?? "", 200)} is not an artifact this host (or this run) published; nothing was published (${foreignLine(message, 200)}).`, { url });
case "forbidden":
return typed(code, `${foreignLine(url ?? "", 200)} is not this session's to update; nothing was published (${foreignLine(message, 200)}).`, { url });
case "payload_too_large":
return typed(code, `the host refused the payload as too large; nothing was published (${foreignLine(message, 200)}).`);
case "not_found":
return notThere(url, true);
case "force_refused":
return typed(code, `the host refused to overwrite with force; nothing was published (${foreignLine(message, 200)}). Merge onto the current version instead.`, { url });
case "refused":
return typed(code, `the host refused the publish; nothing was published (${foreignLine(message, 200)}).`);
default: {
const _exhaustive = code;
return _exhaustive;
}
}
}
async function ownerBeforeWrite(url, ctx) {
if (!hasAction("read"))
return notThisRuns(url, true);
const probe = await callHost("read", () => host.read({ url }, nextContext(ctx)), ctx.signal);
if (!probe.ok || (probe.value.ok && probe.value.ref.url !== url)) {
const why = probe.ok ? "read.ref.url does not match the requested target" : probe.message;
return errorResult(`Error (Artifact): the artifact host did not answer the read that establishes whose ${foreignLine(url, 200)} is (${foreignLine(why, 200)}); nothing was published.`, { type: "artifact", code: ARTIFACT_HOST_ERROR_CODE, outcome: "not_executed", plane: caps.plane, commit: caps.commit });
}
const answer = probe.value;
if (!answer.ok)
return publishRefused(answer.code, url, answer.message);
const owner = judgeOwner(() => answer.ref.ownerIdentity, answer.isolatedSummary, url, ctx);
if (owner === "refused")
return notThere(url, true);
if (owner === "shared")
return sharedReadOnly(url);
return undefined;
}
async function list(a, ctx) {
const scope = a.scope ?? "mine";
const limit = a.limit ?? LIST_LIMIT_DEFAULT;
const call = await callHost("list", () => host.list({ scope, limit }, nextContext(ctx)), ctx.signal);
if (!call.ok)
return hostError("list", call, "");
const out = call.value;
if (!out.ok)
return typed("refused", `the host refused the listing (${foreignLine(out.message, 200)}).`);
const rows = [];
for (const r of out.rows) {
const owner = judgeOwner(() => r.ownerIdentity, r.owner === "shared", r.url, ctx);
if (owner === "refused")
continue;
rows.push({ ...refView(r), owner, updatedAt: r.updatedAt });
}
const lines = rows.map((r) => `${inlineUntrusted(r.url, 300)} v${inlineUntrusted(r.version, 40)} ${inlineUntrusted(r.updatedAt, 40)} (${r.owner})${r.title !== undefined ? ` ${inlineUntrusted(r.title, 120)}` : ""}`);
const body = lines.length === 0 ? "nothing listed" : lines.join("\n");
return { content: `${body}${out.truncated ? "\n(more artifacts exist; raise `limit` to see them)" : ""}`, details: { type: "artifact", action: "list", plane: caps.plane, scope, rows, truncated: out.truncated } };
}
const sharedReadConsent = (url, ref, ctx) => {
if (sharedReadApproved.has(url))
return Promise.resolve({ ok: true });
if (settingAllows !== undefined) {
settingCalls.add(ctx.toolCallId);
return Promise.resolve({ ok: true });
}
const title = ref?.title !== undefined ? ` (${inlineUntrusted(ref.title, 120)})` : "";
const version = ref !== undefined ? `, version ${inlineUntrusted(ref.version, 60)}` : "";
const question = `Read a shared artifact: ${inlineUntrusted(url, 300)}${title}${version} — an artifact another person shared with this user`;
if (permissionMode === undefined)
return askPerson(url, question, ctx);
if (askedCalls.has(ctx.toolCallId))
return Promise.resolve({ ok: true });
const call = { toolCallId: ctx.toolCallId, toolName: ARTIFACT_TOOL_NAME };
const byMode = (also) => {
const classification = classifyAsk(attest({ action: "ask", requiresRealApproval: true }, call, { guards: ["artifact_shared_read"], ...(also !== undefined ? { foldedClasses: [also] } : {}) }), { call, contentQuestion: false, markedUnresolvable: false, org: undefined, tightened: undefined, mandateMarks: {} });
const verdict = arbitrateByMode(permissionMode(), classification);
if (verdict.kind === "released") {
releasedCalls.set(ctx.toolCallId, modeReleaseOf(verdict));
return { ok: true };
}
if (verdict.kind === "denied_by_mode")
return { ok: false, reason: `the ${verdict.mode} permission mode refuses to read another person's artifact without approval`, deniedBy: "mode" };
return undefined;
};
const first = byMode();
if (first !== undefined)
return Promise.resolve(first);
const classification = classifyAsk(attest({ action: "ask", requiresRealApproval: true }, call, { guards: ["artifact_shared_read"] }), { call, contentQuestion: false, markedUnresolvable: false, org: undefined, tightened: undefined, mandateMarks: {} });
if (permissionMode() !== "auto" || !classification.row.classifierEligible || classifySharedRead === undefined)
return askPerson(url, question, ctx);
return classifySharedRead({ ...call, args: { action: "read", url }, message: question }, ctx.signal).then((judged) => {
if (judged.kind === "allow") {
askedCalls.set(ctx.toolCallId, askClassMembersOf(classification));
return { ok: true };
}
if (judged.kind === "deny")
return { ok: false, reason: judged.reason, deniedBy: "classifier" };
return byMode(judged.also) ?? askPerson(url, question, ctx, judged.settle, judged.request);
});
};
const askPerson = (url, question, ctx, settle, minted) => {
const pending = consentInFlight.get(url);
if (pending !== undefined) {
return settle === undefined ? pending : pending.then((r) => (settle(r.ok), r));
}
const ask = (async () => {
const put = minted?.();
const said = put?.message, fallback = put?.denialLimitFallback, cause = put?.classifierNoRuling;
const resolved = await resolveAskFor({
toolName: ARTIFACT_TOOL_NAME,
toolCallId: ctx.toolCallId,
checkpointId: mintCheckpointId(),
args: { action: "read", url },
message: typeof said === "string" ? `${said}\n\nFor this artifact, ${SHARED_READ_SCOPE}` : `${question}; ${SHARED_READ_SCOPE}`,
requiresRealApproval: true,
approvalCard: approvalCardOf({ toolName: ARTIFACT_TOOL_NAME }, toolFace("artifact").renderHints?.approvalCard),
...NOT_BINDABLE,
...(typeof fallback === "object" && fallback !== null && !Array.isArray(fallback) ? { denialLimitFallback: fallback } : {}),
...(typeof cause === "string" ? { classifierNoRuling: cause } : {}),
}, onAsk, ctx.signal, undefined, undefined, undefined, undefined, undefined, "close");
const allowed = resolved.action === "allow" && resolved.updatedInput === undefined;
settle?.(allowed);
const settlement = attestationOf(resolved, { toolCallId: ctx.toolCallId, toolName: ARTIFACT_TOOL_NAME })?.settlement?.kind;
const byResolution = { deniedBy: "ask_resolution", ...(settlement !== undefined ? { settlement } : {}) };
if (resolved.action !== "allow")
return { ok: false, reason: resolved.message ?? "not approved", ...byResolution };
if (resolved.updatedInput !== undefined)
return { ok: false, reason: "the approval edited the request; an edited approval does not authorize the original target", ...byResolution };
sharedReadApproved.add(url);
return { ok: true };
})().finally(() => {
if (!activeTargets.has(url))
consentInFlight.delete(url);
});
consentInFlight.set(url, ask);
return ask;
};
const filesOwnership = async (url, ctx) => {
if (!ownUrls.has(url) && !sharedUrls.has(url)) {
if (!hasAction("read"))
return notThisRuns(url, false);
const probe = await callHost("read", () => host.read({ url }, nextContext(ctx)), ctx.signal);
if (!probe.ok)
return hostError("read", probe, foreignLine(url, 200));
const answer = probe.value;
if (!answer.ok)
return pageRefused(answer.code, url, answer.message);
if (answer.ref.url !== url)
return hostError("read", { kind: "malformed", message: "read.ref.url does not match the requested target" }, foreignLine(url, 200));
if (judgeOwner(() => answer.ref.ownerIdentity, answer.isolatedSummary, url, ctx) === "refused")
return notThere(url, false);
}
if (!sharedUrls.has(url))
return undefined;
const consent = await sharedReadConsent(url, undefined, ctx);
return consent.ok ? undefined : sharedReadRefused(url, foreignLine(url, 200), consent, "files");
};
async function read(a, ctx) {
if (a.url === undefined)
return invalid("`url` is required to read an artifact.");
const call = await callHost("read", () => host.read({ url: a.url }, nextContext(ctx)), ctx.signal);
if (!call.ok)
return hostError("read", call, inlineUntrusted(a.url, 200));
const out = call.value;
if (!out.ok)
return pageRefused(out.code, a.url, out.message);
if (out.ref.url !== a.url)
return hostError("read", { kind: "malformed", message: "read.ref.url does not match the requested target" }, inlineUntrusted(a.url, 200));
const owner = judgeOwner(() => out.ref.ownerIdentity, out.isolatedSummary, a.url, ctx);
if (owner === "refused")
return notThere(a.url, false);
if (sharedUrls.has(a.url)) {
const consent = await sharedReadConsent(a.url, out.ref, ctx);
if (!consent.ok)
return sharedReadRefused(a.url, inlineUntrusted(a.url, 200), consent, "content");
}
rememberRef(out.ref);
const head = owner === "shared" ? `[isolated summary of a shared artifact — ${inlineUntrusted(out.ref.url, 300)}, version ${inlineUntrusted(out.ref.version, 60)}]\n` : "";
return { content: `${head}${out.content}`, details: { type: "artifact", action: "read", plane: caps.plane, ref: refView(out.ref), isolatedSummary: owner === "shared" } };
}
async function listFiles(a, ctx) {
if (a.url === undefined)
return invalid("`url` is required to list an artifact's files.");
const gated = await filesOwnership(a.url, ctx);
if (gated !== undefined)
return gated;
const call = await callHost("list_files", () => host.listFiles({ url: a.url }, nextContext(ctx)), ctx.signal);
if (!call.ok)
return hostError("list_files", call, inlineUntrusted(a.url, 200));
const out = call.value;
if (!out.ok)
return pageRefused(out.code, a.url, out.message);
if (judgeOwner(() => out.ownerIdentity, "established", a.url, ctx) === "refused")
return notThere(a.url, false);
if (sharedUrls.has(a.url)) {
const denied = await filesOwnership(a.url, ctx);
if (denied !== undefined)
return denied;
}
const lines = out.entries.map((e) => `${inlineUntrusted(e.path, 200)} ${String(e.bytes).slice(0, 20)} bytes${e.mediaType !== undefined ? ` ${inlineUntrusted(e.mediaType, 80)}` : ""}`);
return { content: lines.length === 0 ? "no files" : lines.join("\n"), details: { type: "artifact", action: "list_files", plane: caps.plane, url: a.url, entries: out.entries } };
}
async function readFile(a, ctx) {
if (a.url === undefined || a.path === undefined)
return invalid("`url` and `path` are required to read a published file.");
const gated = await filesOwnership(a.url, ctx);
if (gated !== undefined)
return gated;
const call = await callHost("read_file", () => host.readFile({ url: a.url, path: a.path }, nextContext(ctx)), ctx.signal);
if (!call.ok)
return hostError("read_file", call, inlineUntrusted(a.url, 200));
const out = call.value;
if (!out.ok) {
if (out.code !== "not_found")
return pageRefused(out.code, a.url, out.message);
judgeAgain(a.url);
return typed("not_found", `no file ${inlineUntrusted(a.path, 200)} in the artifact at ${foreignLine(a.url, 200)}.`, { url: a.url });
}
if (judgeOwner(() => out.ownerIdentity, "established", a.url, ctx) === "refused")
return notThere(a.url, false);
if (sharedUrls.has(a.url)) {
const denied = await filesOwnership(a.url, ctx);
if (denied !== undefined)
return denied;
}
return { content: renderFile(out.file), details: { type: "artifact", action: "read_file", plane: caps.plane, url: a.url, path: out.file.path, bytes: out.file.content.byteLength, mediaType: out.file.mediaType } };
}
return {
name: ARTIFACT_TOOL_NAME,
...toolFace("artifact"),
ruleFace: mountRuleFace("artifact"),
contentOrigin: ARTIFACT_PLANE_CONTENT_ORIGIN[caps.plane],
description: artifactDescription(caps),
parameters: buildSchema(caps),
prepareArguments: withDefaultAction,
isConcurrencySafe: (args) => isRecord(args) && typeof args["action"] === "string" && ARTIFACT_ACTION_CONCURRENCY_SAFE[args["action"]] === true,
boundaryLegsFor: (args) => {
const action = isRecord(args) ? (args["action"] ?? "publish") : undefined;
const legs = ARTIFACT_ACTION_LEGS[caps.plane];
return { legs: typeof action === "string" && Object.hasOwn(legs, action) ? legs[action] : BOUNDARY_LEGS };
},
execute: async (args, ctx) => {
const read = withDefaultAction(args);
const known = typeof read.url === "string" ? asKnown(read.url) : undefined;
const a = known !== undefined && known !== read.url ? { ...read, url: known } : read;
const action = a.action;
const target = typeof a.url === "string" ? a.url : undefined;
if (target !== undefined)
activeTargets.set(target, (activeTargets.get(target) ?? 0) + 1);
let result;
let released;
let asked;
let bySetting = false;
try {
result = await dispatch(action, a, ctx);
}
finally {
tellOwnerAccount(ctx.toolCallId, action);
released = releasedCalls.get(ctx.toolCallId);
releasedCalls.delete(ctx.toolCallId);
asked = askedCalls.get(ctx.toolCallId);
askedCalls.delete(ctx.toolCallId);
bySetting = settingCalls.delete(ctx.toolCallId);
if (target !== undefined) {
const left = activeTargets.get(target) - 1;
if (left > 0)
activeTargets.set(target, left);
else {
activeTargets.delete(target);
consentInFlight.delete(target);
}
}
}
if (released !== undefined && typeof result !== "string")
result = { ...result, details: { ...(isRecord(result.details) ? result.details : {}), released } };
if (asked !== undefined && typeof result !== "string")
result = { ...result, details: { ...(isRecord(result.details) ? result.details : {}), asked } };
if (bySetting && settingAllows !== undefined && typeof result !== "string")
result = { ...result, details: { ...(isRecord(result.details) ? result.details : {}), allowedBySetting: { setting: "sharedArtifactReads", layer: settingAllows } } };
if (typeof result === "string" || result.isError !== true) {
breaker.clear();
return result;
}
const details = isRecord(result.details) ? result.details : {};
const reason = typeof details["code"] === "string" ? details["code"] : details["invalidArguments"] === true ? "invalid_arguments" : "error";
const text = typeof result.content === "string" ? result.content : "";
const count = breaker.hit(artifactRejectKeyOf(a), reason, text);
if (count < ARTIFACT_REJECT_BREAKER_THRESHOLD || typeof result.content !== "string")
return result;
return { ...result, content: `${artifactRejectBannerFor(reason)}\n\n${result.content}`, details: { ...details, rejectStreak: count } };
},
};
function dispatch(action, a, ctx) {
if (!hasAction(action))
return invalid(`action ${inlineUntrusted(String(action), 40)} is not available on this artifact host.`);
if (caps.ownership.people === "many" && binding.identity.principal === null) {
return typed("refused", "this artifact host serves many people and this run carries no identity, so no artifact action is available to it; nothing was sent to the host.");
}
switch (action) {
case "publish":
return publish(a, ctx);
case "list":
return list(a, ctx);
case "read":
return read(a, ctx);
case "list_files":
return listFiles(a, ctx);
case "read_file":
return readFile(a, ctx);
default: {
const _exhaustive = action;
return _exhaustive;
}
}
}
}