@sema-agent/core
Version:
Stateless, task-oriented AI agent core
177 lines (176 loc) • 9.7 kB
JavaScript
import { isAbsoluteForFamily, pathFamilyOf } from "../tools/fs/safety.js";
import { thrownText } from "./thrown-value.js";
export const ARTIFACT_ACTIONS = Object.freeze(["publish", "list", "read", "list_files", "read_file"]);
export const ARTIFACT_PLANES = Object.freeze(["hosted", "local-stub"]);
export const ARTIFACT_COMMIT_CERTAINTIES = Object.freeze(["throw_means_uncommitted", "uncertain"]);
export const ARTIFACT_COMMIT_THROW_OUTCOME = {
throw_means_uncommitted: "not_executed",
uncertain: "unknown",
};
export const ARTIFACT_PUBLISH_CONTEXTS = Object.freeze(["pr_review", "workshop", "whiteboard", "prototype", "plain"]);
export const ARTIFACT_LIST_SCOPES = Object.freeze(["mine", "shared", "all"]);
export const ARTIFACT_OWNERSHIP_WORDS = Object.freeze({
by: Object.freeze(["identity", "run"]),
people: Object.freeze(["one", "many"]),
unrecorded: Object.freeze(["never", "possible"]),
sharing: Object.freeze(["none", "marked"]),
});
export const ARTIFACT_PLANE_CONTENT_ORIGIN = {
hosted: "external",
"local-stub": "local",
};
export const ARTIFACT_ACTION_HOST_METHOD = {
publish: "publish",
list: "list",
read: "read",
list_files: "listFiles",
read_file: "readFile",
};
export const ARTIFACT_ACTION_CONCURRENCY_SAFE = {
publish: false,
list: true,
read: true,
list_files: true,
read_file: true,
};
export const ARTIFACT_HOST_FAILURE_CODES = Object.freeze(["conflict", "url_foreign", "forbidden", "payload_too_large", "not_found", "force_refused", "refused"]);
export const ARTIFACT_FAILURE_RESULT_CODE = {
conflict: "artifact.publish_conflict",
url_foreign: "artifact.url_foreign",
forbidden: "artifact.forbidden",
payload_too_large: "artifact.payload_too_large",
not_found: "artifact.not_found",
force_refused: "artifact.force_refused",
refused: "artifact.refused",
};
export const ARTIFACT_HOST_ERROR_CODE = "artifact.host_error";
const isPositiveInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
const wordOf = (set, v) => typeof v === "string" && set.includes(v);
const ARTIFACT_LIBRARIES_MAX = 32;
const SRI_TOKEN = /^(?:sha256-[A-Za-z0-9+/]{43}=|sha384-[A-Za-z0-9+/]{64}|sha512-[A-Za-z0-9+/]{86}==)$/;
const LINE_BREAKERS = /[\p{Cc}\p{Zl}\p{Zp}]/u;
function readLibraries(raw) {
if (raw === undefined)
return [];
if (!Array.isArray(raw))
return "capabilities.libraries must be an array when present";
if (raw.length > ARTIFACT_LIBRARIES_MAX)
return `capabilities.libraries declares ${raw.length} entries; at most ${ARTIFACT_LIBRARIES_MAX}`;
const seen = new Set();
const out = [];
for (const [i, e] of raw.entries()) {
const at = `capabilities.libraries[${i}]`;
if (e === null || typeof e !== "object" || Array.isArray(e))
return `${at} must be an object { url, sri, hint }`;
const { url, sri, hint } = e;
const parsed = typeof url === "string" && url.length <= 2048 && !/\s/.test(url) && !LINE_BREAKERS.test(url) && URL.canParse(url) ? new URL(url) : undefined;
if (parsed?.protocol !== "https:")
return `${at}.url must be an https: URL of at most 2048 characters with no whitespace`;
if (parsed.username !== "" || parsed.password !== "")
return `${at}.url must carry no user name or password`;
parsed.hash = "";
if (seen.has(parsed.href))
return `${at}.url declares a library already declared`;
seen.add(parsed.href);
if (typeof sri !== "string" || !sri.split(" ").every((t) => SRI_TOKEN.test(t)))
return `${at}.sri must be a Subresource Integrity value: sha256- / sha384- / sha512- tokens with the digest's base64 at its exact length, separated by single spaces`;
if (typeof hint !== "string" || hint.trim().length === 0 || [...hint].length > 200 || LINE_BREAKERS.test(hint))
return `${at}.hint must be one line of 1 – 200 characters`;
out.push(Object.freeze({ url: url, sri, hint }));
}
return Object.freeze(out);
}
export function readArtifactHostCapabilities(host) {
if (host === null || typeof host !== "object")
return { ok: false, problem: "artifactHost is not an object" };
const h = host;
if (typeof h.capabilities !== "function")
return { ok: false, problem: "artifactHost.capabilities is not a function" };
let raw;
try {
raw = h.capabilities.call(host);
}
catch (err) {
return { ok: false, problem: `artifactHost.capabilities() threw: ${thrownText(err)}` };
}
if (raw === null || typeof raw !== "object")
return { ok: false, problem: "artifactHost.capabilities() did not return an object" };
const c = raw;
const plane = c["plane"];
if (!wordOf(ARTIFACT_PLANES, plane))
return { ok: false, problem: `capabilities.plane must be one of ${ARTIFACT_PLANES.join(" | ")}` };
const actions = c["actions"];
if (!Array.isArray(actions) || actions.length === 0)
return { ok: false, problem: "capabilities.actions must be a non-empty array" };
for (const a of actions)
if (!wordOf(ARTIFACT_ACTIONS, a))
return { ok: false, problem: `capabilities.actions carries a word outside ${ARTIFACT_ACTIONS.join(" | ")}` };
if (new Set(actions).size !== actions.length)
return { ok: false, problem: "capabilities.actions carries a duplicate" };
if (!actions.includes("publish"))
return { ok: false, problem: 'capabilities.actions must include "publish"' };
if (plane === "local-stub" && (actions.length !== 1 || actions[0] !== "publish"))
return { ok: false, problem: 'a "local-stub" plane must declare exactly ["publish"]' };
const commit = c["commit"];
if (!wordOf(ARTIFACT_COMMIT_CERTAINTIES, commit))
return { ok: false, problem: `capabilities.commit must be one of ${ARTIFACT_COMMIT_CERTAINTIES.join(" | ")}` };
if (c["defaultVisibility"] !== "private")
return { ok: false, problem: 'capabilities.defaultVisibility must be "private"' };
if (!isPositiveInt(c["maxFileBytes"]))
return { ok: false, problem: "capabilities.maxFileBytes must be a positive integer" };
if (!isPositiveInt(c["maxTotalBytes"]))
return { ok: false, problem: "capabilities.maxTotalBytes must be a positive integer" };
if (typeof c["multiFile"] !== "boolean")
return { ok: false, problem: "capabilities.multiFile must be a boolean" };
const storageDir = c["storageDir"];
if (plane === "local-stub" && (typeof storageDir !== "string" || storageDir.length === 0 || !isAbsoluteForFamily(pathFamilyOf({ root: storageDir }), storageDir)))
return { ok: false, problem: 'a "local-stub" plane must declare its absolute storageDir' };
if (storageDir !== undefined && typeof storageDir !== "string")
return { ok: false, problem: "capabilities.storageDir must be a string when present" };
for (const a of actions) {
const method = ARTIFACT_ACTION_HOST_METHOD[a];
if (typeof host[method] !== "function")
return { ok: false, problem: `capabilities.actions declares "${a}" but artifactHost.${method} is not a function` };
}
const ownership = readOwnership(c["ownership"]);
if (typeof ownership === "string")
return { ok: false, problem: ownership };
if (ownership.by === "identity" && !actions.includes("read")) {
return { ok: false, problem: 'capabilities.ownership.by: "identity" must declare "read" in capabilities.actions (and serve artifactHost.read): the engine reads a page to judge whose it is before it writes to it, and a host that cannot be read would receive writes to pages the engine never judged — declare "read", or declare by: "run" if only what a run minted is the caller\'s' };
}
let libraries;
try {
libraries = readLibraries(c["libraries"]);
}
catch (err) {
libraries = `capabilities.libraries could not be read: ${thrownText(err)}`;
}
if (typeof libraries === "string")
return { ok: false, problem: libraries };
return {
ok: true,
capabilities: Object.freeze({
plane,
actions: Object.freeze([...actions]),
commit,
defaultVisibility: "private",
maxFileBytes: c["maxFileBytes"],
maxTotalBytes: c["maxTotalBytes"],
multiFile: c["multiFile"],
...(typeof storageDir === "string" ? { storageDir } : {}),
ownership,
...(libraries.length > 0 ? { libraries } : {}),
}),
};
}
const OWNERSHIP_WAY_OUT = `declare capabilities.ownership as { by: ${ARTIFACT_OWNERSHIP_WORDS.by.join(" | ")}, people: ${ARTIFACT_OWNERSHIP_WORDS.people.join(" | ")}, unrecorded: ${ARTIFACT_OWNERSHIP_WORDS.unrecorded.join(" | ")}, sharing: ${ARTIFACT_OWNERSHIP_WORDS.sharing.join(" | ")} }, and hand back the page's owner record (ownerIdentity, the call's binding.identity as recorded) on every answer — see the ArtifactHost ownership contract`;
function readOwnership(raw) {
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
return `capabilities.ownership is missing or not an object: ${OWNERSHIP_WAY_OUT}`;
const o = raw;
for (const member of Object.keys(ARTIFACT_OWNERSHIP_WORDS)) {
if (!wordOf(ARTIFACT_OWNERSHIP_WORDS[member], o[member]))
return `capabilities.ownership.${member} must be one of ${ARTIFACT_OWNERSHIP_WORDS[member].join(" | ")}: ${OWNERSHIP_WAY_OUT}`;
}
return Object.freeze({ by: o["by"], people: o["people"], unrecorded: o["unrecorded"], sharing: o["sharing"] });
}