@sema-agent/core
Version:
Stateless, task-oriented AI agent core
568 lines (567 loc) • 21.3 kB
JavaScript
import { types } from "node:util";
import { shellWordsOf } from "../shell/shell-words.js";
import { ENGINE_TOOLS } from "./tool-catalog-entries.js";
const objectFreeze = Object.freeze;
const objectPrototype = Object.prototype;
const arrayPrototype = Array.prototype;
const objectGetPrototypeOf = Object.getPrototypeOf;
const objectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const objectHasOwn = Object.hasOwn;
const objectKeys = Object.keys;
const reflectOwnKeys = Reflect.ownKeys;
const arrayIsArray = Array.isArray;
const numberIsInteger = Number.isInteger;
const isProxy = types.isProxy;
const callBind = Function.prototype.bind.bind(Function.prototype.call);
const strCharCodeAt = callBind(String.prototype.charCodeAt);
const strIndexOf = callBind(String.prototype.indexOf);
const strLastIndexOf = callBind(String.prototype.lastIndexOf);
const strIncludes = callBind(String.prototype.includes);
const strSlice = callBind(String.prototype.slice);
const strStartsWith = callBind(String.prototype.startsWith);
const strEndsWith = callBind(String.prototype.endsWith);
const strTrim = callBind(String.prototype.trim);
const strToLowerCase = callBind(String.prototype.toLowerCase);
const arrPush = callBind(Array.prototype.push);
const arrJoin = callBind(Array.prototype.join);
const setHas = callBind(Set.prototype.has);
const mapGet = callBind(Map.prototype.get);
function snapshotOwnKeys(proto) {
const raw = reflectOwnKeys(proto);
const copy = [];
for (let i = 0; i < raw.length; i++) {
copy[i] = raw[i];
}
return objectFreeze(copy);
}
const OBJECT_PROTO_KEYS = snapshotOwnKeys(objectPrototype);
const ARRAY_PROTO_KEYS = snapshotOwnKeys(arrayPrototype);
export const HOOK_CONDITION_EVENTS = objectFreeze([
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
"PermissionRequest",
"PermissionDenied",
]);
export const HOOK_CONDITION_UNTESTED_REASONS = objectFreeze([
"not_a_tool_event",
"condition_unreadable",
"name_unjudged",
"content_unjudged",
"invalid_input",
]);
function frozenUntested(reason, detail) {
return objectFreeze({ verdict: "untested", reason, detail });
}
const MATCHED = objectFreeze({ verdict: "matched" });
const INVALID_REALM_PROTOTYPES = frozenUntested("invalid_input", "the own-key lists of the realm's base prototypes differ from those at load");
const INVALID_UNREADABLE = frozenUntested("invalid_input", "the input is not plain data");
const INVALID_ENVELOPE_KEY = frozenUntested("invalid_input", "the input carries an unrecognized member");
const INVALID_EVENT = frozenUntested("invalid_input", "event must be a string");
const INVALID_TOOL_NAME = frozenUntested("invalid_input", "toolName must be a string");
const INVALID_TOOL_NAME_REQUIRED = frozenUntested("invalid_input", "toolName must be a non-empty string for tool events");
const INVALID_ENGINE_OWNED = frozenUntested("invalid_input", "engineOwned must be true when present");
const INVALID_TOOL_INPUT_DATA = frozenUntested("invalid_input", "toolInput is not plain data");
const INVALID_BASH_KEY = frozenUntested("invalid_input", "toolInput carries an unrecognized Bash parameter");
const INVALID_BASH_COMMAND = frozenUntested("invalid_input", "Bash toolInput.command must be a string");
const INVALID_BASH_TYPE = frozenUntested("invalid_input", "Bash toolInput carries a parameter of the wrong type");
const CONDITION_UNREADABLE = frozenUntested("condition_unreadable", "condition is not a readable unescaped string");
const NOT_A_TOOL_EVENT = frozenUntested("not_a_tool_event", "event is not one of the five tool hook events");
const NAME_MISMATCH = frozenUntested("name_unjudged", "condition tool name does not match call tool name");
const NAME_OUTSIDE_CATALOG = frozenUntested("name_unjudged", "tool name is outside the engine tool catalog");
const NAME_MONITOR = frozenUntested("name_unjudged", "Monitor hook conditions depend on outer routing context");
const CONTENT_REQUIRES_ENGINE_OWNED = frozenUntested("content_unjudged", "a condition with content requires engineOwned: true");
const CONTENT_NON_BASH = frozenUntested("content_unjudged", "content matching is only judged for Bash in v1");
const CONTENT_ABSENT_TOOL_INPUT = frozenUntested("content_unjudged", "toolInput is absent for Bash content condition");
const CONTENT_TIMEOUT_RANGE = frozenUntested("content_unjudged", "Bash toolInput.timeout is outside the judged integer range");
const CONTENT_CONFIG_DEPENDENT_KEY = frozenUntested("content_unjudged", "Bash toolInput carries run_in_background or dangerouslyDisableSandbox, whose schema membership depends on reference configuration");
const CONTENT_TOO_LONG = frozenUntested("content_unjudged", "condition content exceeds the 1000-character ceiling");
const CONTENT_NOT_FLAT = frozenUntested("content_unjudged", "Bash command is not strictly flat");
const CONTENT_NOT_MATCHED = frozenUntested("content_unjudged", "Bash command did not match the condition pattern");
const ENVELOPE_KEYS = objectFreeze(new Set(["condition", "event", "toolName", "toolInput", "engineOwned"]));
const TOOL_EVENT_SET = objectFreeze(new Set(HOOK_CONDITION_EVENTS));
const FORMER_NAMES = new Map([
["Task", "Agent"],
["KillShell", "TaskStop"],
["KillBash", "TaskStop"],
["Brief", "SendUserMessage"],
]);
const CATALOG_NAMES = objectFreeze(new Set(ENGINE_TOOLS.map((e) => e.name)));
const CATALOG_ALIASES = new Map(ENGINE_TOOLS.flatMap((e) => (e.aliases ?? []).map((alias) => [alias, e.name])));
const BASH_INPUT_KEYS = new Map([
["command", "string"],
["timeout", "number"],
["description", "string"],
["run_in_background", "boolean"],
["dangerouslyDisableSandbox", "boolean"],
]);
const BASH_RESERVED_WORDS = objectFreeze(new Set(shellWordsOf("rule_reserved")));
const WRAPPER_WORDS = objectFreeze(new Set(["timeout", "env", "nice", "sudo", "xargs"]));
const MAX_COMMAND_CHARS = 10_000;
const MAX_CONTENT_CHARS = 1_000;
const MAX_TIMEOUT_MS = 600_000;
function protoKeysUnchanged(proto, expected) {
const current = reflectOwnKeys(proto);
if (current.length !== expected.length)
return false;
for (let i = 0; i < expected.length; i++) {
if (current[i] !== expected[i])
return false;
}
return true;
}
function admitPlainRecord(v) {
try {
if (typeof v === "function")
return false;
if (isProxy(v))
return false;
if (v === null || typeof v !== "object" || arrayIsArray(v))
return false;
const proto = objectGetPrototypeOf(v);
if (proto !== objectPrototype && proto !== null)
return false;
const keys = reflectOwnKeys(v);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
if (typeof k === "symbol")
return false;
const desc = objectGetOwnPropertyDescriptor(v, k);
if (desc === undefined || !objectHasOwn(desc, "value") || desc.enumerable !== true) {
return false;
}
}
return true;
}
catch {
return false;
}
}
function validateBashInputShape(toolInput) {
const inputKeys = objectKeys(toolInput);
for (let i = 0; i < inputKeys.length; i++) {
const k = inputKeys[i];
const expectedType = mapGet(BASH_INPUT_KEYS, k);
if (expectedType === undefined) {
return INVALID_BASH_KEY;
}
const val = toolInput[k];
if (k === "command") {
if (typeof val !== "string") {
return INVALID_BASH_COMMAND;
}
}
else if (val !== undefined && typeof val !== expectedType) {
return INVALID_BASH_TYPE;
}
}
if (!objectHasOwn(toolInput, "command") || typeof toolInput.command !== "string") {
return INVALID_BASH_COMMAND;
}
return undefined;
}
function splitCondition(s) {
const o = strIndexOf(s, "(");
const c = strLastIndexOf(s, ")");
if (o <= 0 || c <= o || c !== s.length - 1) {
return { name: s, content: undefined };
}
const name = strSlice(s, 0, o);
if (strIncludes(name, "(") || strIncludes(name, ")")) {
return { name: s, content: undefined };
}
const inner = strSlice(s, o + 1, c);
if (inner === "" || inner === "*") {
return { name, content: undefined };
}
return { name, content: inner };
}
function canonicalName(n) {
const afterFormer = mapGet(FORMER_NAMES, n) ?? n;
return mapGet(CATALOG_ALIASES, afterFormer) ?? afterFormer;
}
function isAllowedCommandChar(code) {
if (code >= 0x30 && code <= 0x39)
return true;
if (code >= 0x41 && code <= 0x5a)
return true;
if (code >= 0x61 && code <= 0x7a)
return true;
if (code === 0x20)
return true;
return (code === 0x5f ||
code === 0x2e ||
code === 0x2f ||
code === 0x3d ||
code === 0x3a ||
code === 0x2c ||
code === 0x40 ||
code === 0x25 ||
code === 0x2b ||
code === 0x2d);
}
function isAssignmentWord(word) {
const len = word.length;
if (len < 2)
return false;
const c0 = strCharCodeAt(word, 0);
const firstOk = (c0 >= 0x41 && c0 <= 0x5a) || (c0 >= 0x61 && c0 <= 0x7a) || c0 === 0x5f;
if (!firstOk)
return false;
let i = 1;
while (i < len) {
const c = strCharCodeAt(word, i);
if ((c >= 0x41 && c <= 0x5a) ||
(c >= 0x61 && c <= 0x7a) ||
(c >= 0x30 && c <= 0x39) ||
c === 0x5f) {
i++;
continue;
}
break;
}
if (i >= len)
return false;
const op = strCharCodeAt(word, i);
if (op === 0x3d)
return true;
if (op === 0x2b && i + 1 < len && strCharCodeAt(word, i + 1) === 0x3d)
return true;
return false;
}
function flatWords(command) {
const len = command.length;
if (len === 0 || len > MAX_COMMAND_CHARS)
return undefined;
if (strCharCodeAt(command, 0) === 0x20 || strCharCodeAt(command, len - 1) === 0x20) {
return undefined;
}
const words = [];
let wordStart = 0;
let prevCode = -1;
for (let i = 0; i < len; i++) {
const code = strCharCodeAt(command, i);
if (!isAllowedCommandChar(code))
return undefined;
if (code === 0x20) {
if (prevCode === 0x20)
return undefined;
arrPush(words, strSlice(command, wordStart, i));
wordStart = i + 1;
}
prevCode = code;
}
arrPush(words, strSlice(command, wordStart, len));
if (words.length === 0)
return undefined;
if (setHas(BASH_RESERVED_WORDS, words[0]))
return undefined;
for (let i = 0; i < words.length; i++) {
const w = words[i];
if (w.length === 0)
return undefined;
if (strCharCodeAt(w, 0) === 0x3d)
return undefined;
if (isAssignmentWord(w))
return undefined;
if (setHas(WRAPPER_WORDS, w))
return undefined;
}
return words;
}
function collapseBlanks(s) {
let out = "";
let inBlank = false;
for (let i = 0; i < s.length; i++) {
const code = strCharCodeAt(s, i);
if (code === 0x20 || code === 0x09) {
if (!inBlank) {
out += " ";
inBlank = true;
}
}
else {
out += strSlice(s, i, i + 1);
inBlank = false;
}
}
return out;
}
function colonStarPrefix(content) {
if (content.length < 3 || !strEndsWith(content, ":*"))
return undefined;
if (strIndexOf(content, "\n") >= 0 ||
strIndexOf(content, "\r") >= 0 ||
strIndexOf(content, "\u2028") >= 0 ||
strIndexOf(content, "\u2029") >= 0) {
return undefined;
}
return strSlice(content, 0, content.length - 2);
}
function referenceWildcardMatch(pattern, value, ignoreCase = false, foldBlanks = false) {
if (strIncludes(pattern, "\u0000"))
return false;
const l = strTrim(pattern);
const c0 = foldBlanks ? collapseBlanks(l) : l;
const g0 = foldBlanks ? collapseBlanks(value) : value;
const c = ignoreCase ? strToLowerCase(c0) : c0;
const g = ignoreCase ? strToLowerCase(g0) : g0;
const chars = [];
const isUnescapedStar = [];
let starCount = 0;
for (let i = 0; i < c.length; i++) {
const ch = strSlice(c, i, i + 1);
if (ch === "\\" && i + 1 < c.length) {
const next = strSlice(c, i + 1, i + 2);
if (next === "*") {
arrPush(chars, "*");
arrPush(isUnescapedStar, false);
i++;
continue;
}
if (next === "\\") {
arrPush(chars, "\\");
arrPush(isUnescapedStar, false);
i++;
continue;
}
}
arrPush(chars, ch);
const star = ch === "*";
arrPush(isUnescapedStar, star);
if (star)
starCount++;
}
const tokens = [];
let litBuf = "";
const flushLit = () => {
if (litBuf.length > 0) {
arrPush(tokens, { kind: "lit", text: litBuf });
litBuf = "";
}
};
let pos = 0;
while (pos < chars.length) {
if (chars[pos] === "/" && !isUnescapedStar[pos]) {
let p = pos + 1;
let groups = 0;
while (p + 2 < chars.length &&
isUnescapedStar[p] &&
isUnescapedStar[p + 1] &&
chars[p + 2] === "/" &&
!isUnescapedStar[p + 2]) {
groups++;
p += 3;
}
if (groups > 0) {
flushLit();
arrPush(tokens, { kind: "globstar" });
pos = p;
continue;
}
}
if (isUnescapedStar[pos]) {
flushLit();
arrPush(tokens, { kind: "star" });
pos++;
continue;
}
litBuf += chars[pos];
pos++;
}
flushLit();
if (starCount === 1 && tokens.length >= 2) {
const last = tokens[tokens.length - 1];
const prev = tokens[tokens.length - 2];
if (last.kind === "star" && prev.kind === "lit" && strEndsWith(prev.text, " ")) {
const trimmedPrev = strSlice(prev.text, 0, prev.text.length - 1);
if (trimmedPrev.length > 0) {
tokens[tokens.length - 2] = { kind: "lit", text: trimmedPrev };
tokens[tokens.length - 1] = { kind: "optSpaceStar" };
}
else {
tokens[tokens.length - 2] = { kind: "optSpaceStar" };
tokens.length = tokens.length - 1;
}
}
}
const n = g.length;
let dp = [];
for (let i = 0; i <= n; i++)
dp[i] = i === 0;
for (let t = 0; t < tokens.length; t++) {
const tok = tokens[t];
const next = [];
for (let i = 0; i <= n; i++)
next[i] = false;
if (tok.kind === "lit") {
const tlen = tok.text.length;
for (let j = 0; j + tlen <= n; j++) {
if (dp[j] && strSlice(g, j, j + tlen) === tok.text) {
next[j + tlen] = true;
}
}
}
else if (tok.kind === "star") {
let first = -1;
for (let j = 0; j <= n; j++) {
if (dp[j]) {
first = j;
break;
}
}
if (first >= 0) {
for (let p = first; p <= n; p++)
next[p] = true;
}
}
else if (tok.kind === "globstar") {
let firstSlash = -1;
for (let j = 0; j < n; j++) {
if (dp[j] && strCharCodeAt(g, j) === 0x2f) {
firstSlash = j;
break;
}
}
if (firstSlash >= 0) {
for (let p = firstSlash; p < n; p++) {
if (strCharCodeAt(g, p) === 0x2f) {
next[p + 1] = true;
}
}
}
}
else {
let firstAfterSpace = -1;
for (let j = 0; j <= n; j++) {
if (!dp[j])
continue;
next[j] = true;
if (firstAfterSpace < 0 && j < n && strCharCodeAt(g, j) === 0x20) {
firstAfterSpace = j + 1;
}
}
if (firstAfterSpace >= 0) {
for (let p = firstAfterSpace; p <= n; p++)
next[p] = true;
}
}
dp = next;
}
return dp[n] === true;
}
export function judgeHookCondition(input) {
try {
if (!protoKeysUnchanged(objectPrototype, OBJECT_PROTO_KEYS) ||
!protoKeysUnchanged(arrayPrototype, ARRAY_PROTO_KEYS)) {
return INVALID_REALM_PROTOTYPES;
}
if (!admitPlainRecord(input)) {
return INVALID_UNREADABLE;
}
const keys = objectKeys(input);
for (let i = 0; i < keys.length; i++) {
if (!setHas(ENVELOPE_KEYS, keys[i])) {
return INVALID_ENVELOPE_KEY;
}
}
const event = objectHasOwn(input, "event") ? input.event : undefined;
if (typeof event !== "string") {
return INVALID_EVENT;
}
const hasToolName = objectHasOwn(input, "toolName") && input.toolName !== undefined;
const toolName = hasToolName ? input.toolName : undefined;
if (hasToolName && typeof toolName !== "string") {
return INVALID_TOOL_NAME;
}
const hasEngineOwned = objectHasOwn(input, "engineOwned") && input.engineOwned !== undefined;
if (hasEngineOwned && input.engineOwned !== true) {
return INVALID_ENGINE_OWNED;
}
const hasToolInput = objectHasOwn(input, "toolInput") && input.toolInput !== undefined;
const toolInput = hasToolInput ? input.toolInput : undefined;
if (hasToolInput && !admitPlainRecord(toolInput)) {
return INVALID_TOOL_INPUT_DATA;
}
if (hasToolInput && typeof toolName === "string" && canonicalName(toolName) === "Bash") {
const bashErr = validateBashInputShape(toolInput);
if (bashErr !== undefined) {
return bashErr;
}
}
const condition = objectHasOwn(input, "condition") ? input.condition : undefined;
if (typeof condition !== "string" || strIncludes(condition, "\\")) {
return CONDITION_UNREADABLE;
}
if (condition === "") {
return MATCHED;
}
if (!setHas(TOOL_EVENT_SET, event)) {
return NOT_A_TOOL_EVENT;
}
if (typeof toolName !== "string" || toolName.length === 0) {
return INVALID_TOOL_NAME_REQUIRED;
}
const { name: rawCondName, content } = splitCondition(condition);
const condName = canonicalName(rawCondName);
const callName = canonicalName(toolName);
if (condName !== callName) {
return NAME_MISMATCH;
}
if (!setHas(CATALOG_NAMES, condName)) {
return NAME_OUTSIDE_CATALOG;
}
if (condName === "Monitor") {
return NAME_MONITOR;
}
if (content === undefined) {
return MATCHED;
}
if (!hasEngineOwned) {
return CONTENT_REQUIRES_ENGINE_OWNED;
}
if (condName !== "Bash") {
return CONTENT_NON_BASH;
}
if (content.length > MAX_CONTENT_CHARS) {
return CONTENT_TOO_LONG;
}
if (!hasToolInput) {
return CONTENT_ABSENT_TOOL_INPUT;
}
const bashInput = toolInput;
if (objectHasOwn(bashInput, "run_in_background") ||
objectHasOwn(bashInput, "dangerouslyDisableSandbox")) {
return CONTENT_CONFIG_DEPENDENT_KEY;
}
if (objectHasOwn(bashInput, "timeout") && bashInput.timeout !== undefined) {
const timeout = bashInput.timeout;
if (!numberIsInteger(timeout) || timeout < 0 || timeout > MAX_TIMEOUT_MS) {
return CONTENT_TIMEOUT_RANGE;
}
}
const words = flatWords(bashInput.command);
if (words === undefined) {
return CONTENT_NOT_FLAT;
}
const w = arrJoin(words, " ");
const prefix = colonStarPrefix(content);
if (prefix !== undefined) {
if (w === prefix ||
strStartsWith(w, prefix + " ") ||
w === "xargs " + prefix ||
strStartsWith(w, "xargs " + prefix + " ")) {
return MATCHED;
}
return CONTENT_NOT_MATCHED;
}
if (referenceWildcardMatch(content, w, false, true) ||
referenceWildcardMatch("xargs " + content, w, false, true)) {
return MATCHED;
}
return CONTENT_NOT_MATCHED;
}
catch {
return INVALID_UNREADABLE;
}
}