@sema-agent/core
Version:
Stateless, task-oriented AI agent core
609 lines (608 loc) • 24.2 kB
JavaScript
import { types } from "node:util";
import { isRedactionMark, isSensitiveRecordKey, REDACTION_MARKS, redactionMarkerSpans, renderSecrets, renderWithheld, scanSecrets, urlOfAnySchemePattern } from "@sema-agent/primitives";
import { delimitUntrusted, foldPlaces, foldToOneLine, INLINE_TRUNCATION_MARK, neutralizeForFence } from "./untrusted-text.js";
import { markSafeCut, notRecordedMark } from "./redaction-marks.js";
import { isErrorLike, readMember, thrownText } from "./thrown-value.js";
import { sliceHeadSafe } from "./surrogate-safe-slice.js";
export function summarizeRedactions(findings) {
if (findings.length === 0)
return "no redactions";
const counts = new Map();
for (const f of findings) {
const label = `${f.kind} (${f.confidence})`;
counts.set(label, (counts.get(label) ?? 0) + 1);
}
const parts = [...counts].map(([label, n]) => `${label} x${n}`);
return `${findings.length} redaction${findings.length === 1 ? "" : "s"}: ${parts.join(", ")}`;
}
const EGRESS_POLICY = Object.freeze({
grade: "wide",
readings: Object.freeze([Object.freeze({ kind: "raw" }), Object.freeze({ kind: "format-free" })]),
urlUserinfo: "keep-username",
onUnresolvedReading: "secret",
});
const FS_PATH_OF_TWO_SEGMENTS_OR_MORE = /\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+[A-Za-z0-9_./-]*?(?=\/(?![A-Za-z0-9_.-])|[^A-Za-z0-9_./-]|$)/g;
const HOST_LEAK_PASSES = Object.freeze([
{ kind: "url", confidence: "medium", marker: REDACTION_MARKS.url, source: "untrusted-egress", re: urlOfAnySchemePattern(), replace: REDACTION_MARKS.url },
{ kind: "fs-path", confidence: "low", marker: REDACTION_MARKS.path, source: "untrusted-egress", re: FS_PATH_OF_TWO_SEGMENTS_OR_MORE, replace: REDACTION_MARKS.path },
]);
const TIER_PASSES = { "same-principal": Object.freeze([]), human: HOST_LEAK_PASSES };
export function egressText(tier, text, report) {
if (report !== undefined && report.preexistingMarkers === undefined)
report.preexistingMarkers = redactionMarkerSpans(text).length;
return renderSecrets(text, EGRESS_POLICY, { passes: TIER_PASSES[tier], report });
}
export function egressCredentialReading(text) {
const report = { findings: [] };
const rendered = egressText("same-principal", text, report);
return { rendered, spans: report.findings.map(({ span: [from, end], marker }) => [...(marker === REDACTION_MARKS.oversized ? [from, end] : withheldOf(text, from, end)), marker]) };
}
const AFTER_HIT = /^(?:\\*["']|[^\s"']{1,64})/;
function withheldOf(text, from, end) {
const found = text.slice(from, end);
const after = AFTER_HIT.exec(text.slice(end, end + 128))?.[0] ?? "";
const withAfter = after === "" ? undefined : egressText("same-principal", found + after);
const rendered = withAfter !== undefined && withAfter.endsWith(after) ? withAfter.slice(0, withAfter.length - after.length) : egressText("same-principal", found);
let head = 0;
while (head < found.length && head < rendered.length && found[head] === rendered[head])
head++;
let tail = 0;
while (tail < found.length - head && tail < rendered.length - head && found[found.length - 1 - tail] === rendered[rendered.length - 1 - tail])
tail++;
return head + tail >= found.length ? [from, end] : [from + head, end - tail];
}
export function egressCredentialFinds(text) {
return credentialFindsOf(text).map(({ start, end }) => [start, end]);
}
function credentialFindsOf(text) {
const scanned = scanSecrets(text, EGRESS_POLICY).spans;
return [...scanned.map(({ start, end }) => ({ start, end, mark: REDACTION_MARKS.bare })), ...egressCredentialReading(text).spans.map(([start, end, mark]) => ({ start, end, mark }))];
}
export function egressSafeCut(text, from, final) {
const finds = [...oneLineFinds(text).map(([start, end]) => ({ start, end, mark: REDACTION_MARKS.bare })), ...credentialFindsOf(text)];
const cut = final ? text.length : heldCut(text, from, finds);
const within = finds.filter((f) => f.end > from && f.start < cut).map((f) => ({ start: Math.max(f.start, from) - from, end: Math.min(f.end, cut) - from, mark: f.mark }));
const open = finds.filter((f) => f.end >= text.length).reduce((at, f) => (at === undefined || f.start < at ? f.start : at), undefined);
return { cut, shown: egressText("same-principal", renderWithheld(text.slice(from, cut), within)), open };
}
function heldCut(text, from, finds) {
const lastLine = text.length < 2 ? 0 : text.lastIndexOf("\n", text.length - 2) + 1;
let at = text.length;
for (const f of finds)
if (f.end > lastLine)
at = Math.min(at, f.start);
for (;;) {
if (at <= from)
return from;
at = Math.max(from, text.lastIndexOf("\n", at - 1) + 1);
const across = finds.filter((f) => f.start < at && at < f.end);
if (across.length === 0)
return at;
at = Math.min(...across.map((f) => f.start));
}
}
function firstAtOrAfter(places, n, at) {
let lo = 0;
let hi = n;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (places[mid] < at)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
export function oneLineFinds(text) {
const folded = foldToOneLine(text);
if (folded === text)
return [];
const places = foldPlaces(text);
const at = (place) => firstAtOrAfter(places, text.length, place);
const changed = scannedSpans(folded)
.map(([start, end]) => [at(start), at(end), start, end])
.filter(([from, to, start, end]) => to > from && text.slice(at(Math.max(0, start - 1)), to) !== folded.slice(Math.max(0, start - 1), end));
if (changed.length === 0)
return [];
const held = mergedSpans(scannedSpans(text));
const starts = Int32Array.from(held, ([start]) => start);
return changed
.filter(([from, to]) => {
const k = firstAtOrAfter(starts, held.length, from + 1) - 1;
return k < 0 || to > held[k][1];
})
.map(([from, to]) => [from, to]);
}
function scannedSpans(text) {
return scanSecrets(text, EGRESS_POLICY).spans.map(({ start, end }) => [start, end]);
}
function mergedSpans(spans) {
const out = [];
for (const [s, e] of [...spans].sort((a, b) => a[0] - b[0])) {
const last = out[out.length - 1];
if (last !== undefined && s <= last[1])
last[1] = Math.max(last[1], e);
else
out.push([s, e]);
}
return out;
}
export function egressThrownText(tier, err) {
return egressForeignText(tier, thrownText(err));
}
export function egressForeignText(tier, text) {
const extra = oneLineFinds(text);
if (extra.length === 0)
return egressText(tier, text);
const own = egressCredentialReading(text).spans.map(([start, end, mark]) => ({ start, end, mark }));
return egressText(tier, renderWithheld(text, [...extra.map(([start, end]) => ({ start, end, mark: REDACTION_MARKS.bare })), ...own]));
}
export function redactSecrets(s, report) {
return egressText("same-principal", s, report);
}
export function cutAt(line, max) {
if (line.length <= max)
return line;
let at = markSafeCut(line, max);
const lead = line.charCodeAt(at - 1);
if (at > 0 && lead >= 0xd800 && lead <= 0xdbff)
at -= 1;
return line.slice(0, at);
}
export function redactThenCut(s, max) {
const { words, dropped } = boundedForeignReading(s, max, (part) => egressForeignText("same-principal", part));
return dropped && max > 0 ? `${cutAt(words, max - 1)}${INLINE_TRUNCATION_MARK}` : cutAt(words, max);
}
export const FOREIGN_WINDOW_MARGIN = 32_768;
export const FOREIGN_WHOLE_MAX = 262_144;
function unreadWords(text) {
return `${REDACTION_MARKS.oversized} (${text.length} characters)`;
}
export function pastWholeReading(text) {
return text.length > FOREIGN_WHOLE_MAX ? unreadWords(text) : undefined;
}
export function boundedForeignReading(text, shown, read) {
const reach = Math.max(0, shown) + 2 * FOREIGN_WINDOW_MARGIN;
if (text.length <= reach)
return { words: read(text), dropped: false };
const window = read(sliceHeadSafe(text, reach));
const near = read(sliceHeadSafe(text, reach - FOREIGN_WINDOW_MARGIN));
let alike = 0;
while (alike < window.length && alike < near.length && window.charCodeAt(alike) === near.charCodeAt(alike))
alike++;
if (alike < window.length && !/\s/.test(window[alike]))
while (alike > 0 && !/\s/.test(window[alike - 1]))
alike--;
const head = cutAt(window, alike);
return /\S/.test(head) ? { words: head, dropped: true } : { words: unreadWords(text), dropped: false };
}
export function wholeForeignReading(text, read) {
return pastWholeReading(text) ?? read(text);
}
export function redactHostLeaks(s, report) {
return egressText("human", s, report);
}
const VALUE_DEPTH_MAX = 32;
const VALUE_MEMBERS_MAX = 2_000;
const PAST_THE_DEPTH = notRecordedMark("nested past the depth bound");
const PAST_THE_BOUND = notRecordedMark("past the member bound");
const NOT_LISTED = notRecordedMark("its members could not be listed");
const TO_JSON_THREW = notRecordedMark("its toJSON threw");
const LATER = Symbol("read after the data");
const slotOf = (key) => {
const n = Number(key);
return Number.isInteger(n) && n >= 0 && n < 4_294_967_295 && String(n) === key ? n : undefined;
};
const lengthOf = (read) => (typeof read === "number" && Number.isInteger(read) && read >= 0 && read <= 4_294_967_295 ? read : 0);
const CYCLE = notRecordedMark("cycle");
class SnapshotMap extends Map {
revisits = 0;
get(key) {
const read = super.get(key);
if (read !== undefined)
this.revisits += 1;
return read;
}
}
function holeCut(keys, length) {
const slots = [];
for (const key of keys) {
const slot = slotOf(key);
if (slot !== undefined)
slots.push(slot);
}
slots.sort((a, b) => a - b);
let reached = 0;
let holes = 0;
for (const slot of [...slots, length]) {
const gap = slot - reached;
if (gap > 0) {
if (holes + gap > VALUE_MEMBERS_MAX)
return { at: reached + (VALUE_MEMBERS_MAX - holes), length };
holes += gap;
}
reached = Math.max(reached, slot + 1);
}
return undefined;
}
function closeArray(snapshot, length) {
const cut = holeCut(Object.keys(snapshot), length);
if (cut === undefined) {
snapshot.length = length;
return;
}
snapshot.length = cut.at;
Object.defineProperty(snapshot, String(cut.at), { value: notRecordedMark(`length ${cut.length}`), enumerable: true, writable: true, configurable: true });
}
function cutCycles(root) {
if (typeof root !== "object" || root === null)
return;
const open = new Set([root]);
const done = new Set();
const stack = [{ node: root, keys: Reflect.ownKeys(root), next: 0 }];
while (stack.length > 0) {
const frame = stack[stack.length - 1];
const key = frame.keys[frame.next++];
if (key === undefined) {
open.delete(frame.node);
done.add(frame.node);
stack.pop();
continue;
}
const d = Object.getOwnPropertyDescriptor(frame.node, key);
const child = d !== undefined && "value" in d ? d.value : undefined;
if (typeof child !== "object" || child === null)
continue;
if (open.has(child)) {
Object.defineProperty(frame.node, key, { value: CYCLE, enumerable: d?.enumerable ?? true, writable: true, configurable: true });
continue;
}
if (done.has(child))
continue;
open.add(child);
stack.push({ node: child, keys: Reflect.ownKeys(child), next: 0 });
}
}
export function egressValue(tier, value) {
const snapshots = new SnapshotMap();
const out = foreignValue(tier, value, snapshots);
if (snapshots.revisits > 0)
cutCycles(out);
return out;
}
function foreignValue(tier, value, snapshots) {
let budget = VALUE_MEMBERS_MAX;
const spend = () => (budget > 0 ? (budget--, true) : false);
const listed = (o) => {
try {
return Reflect.ownKeys(o);
}
catch {
return undefined;
}
};
const prototypeOf = (o) => {
try {
return Object.getPrototypeOf(o);
}
catch {
return Object.prototype;
}
};
const readOwn = (o, key, all) => {
try {
const d = Reflect.getOwnPropertyDescriptor(o, key);
if (d === undefined || (!all && d.enumerable !== true))
return undefined;
return { value: "value" in d ? d.value : d.get?.call(o), enumerable: d.enumerable ?? true };
}
catch {
return { value: undefined, enumerable: true };
}
};
const define = (snapshot, key, value, enumerable) => {
Object.defineProperty(snapshot, key, { value, enumerable, writable: true, configurable: true });
};
const nameOf = (key) => (typeof key === "string" ? egressText(tier, key) : key);
const member = (read, depth, name) => {
const out = pass(read, depth + 1, name);
return typeof out === "string" && isSensitiveRecordKey(name) && !isRedactionMark(out) ? REDACTION_MARKS.bare : out;
};
const fillRecord = (o, depth, keys, snapshot, all) => {
for (const key of keys) {
if (!all && typeof key === "symbol")
continue;
if (!spend())
return (define(snapshot, nameOf(key), PAST_THE_BOUND, true), true);
const read = readOwn(o, key, all);
if (read !== undefined)
define(snapshot, nameOf(key), member(read.value, depth, typeof key === "string" ? key : ""), read.enumerable);
}
return false;
};
const fillArray = (o, depth, keys, snapshot) => {
let reached = 0;
const cut = () => define(snapshot, String(reached), PAST_THE_BOUND, true);
const reach = (upTo) => {
const cost = upTo - reached;
if (cost <= 0)
return true;
if (cost > budget)
return ((reached += budget), (budget = 0), false);
return ((budget -= cost), (reached = upTo), true);
};
if (!spend())
return cut();
const length = lengthOf(readOwn(o, "length", true)?.value);
const named = [];
for (const key of keys) {
if (typeof key === "symbol" || key === "length")
continue;
const slot = slotOf(key);
if (slot === undefined) {
named.push(key);
continue;
}
if (slot < reached ? !spend() : !reach(slot + 1))
return cut();
const read = readOwn(o, key, false);
if (read !== undefined)
define(snapshot, key, member(read.value, depth, key), true);
}
if (!reach(length))
return cut();
snapshot.length = reached;
for (const key of named) {
if (!spend())
return define(snapshot, nameOf(key), PAST_THE_BOUND, true);
const read = readOwn(o, key, false);
if (read !== undefined)
define(snapshot, nameOf(key), member(read.value, depth, key), true);
}
};
const errorSnapshot = (o, depth) => {
const keys = listed(o);
if (keys === undefined)
return (snapshots.set(o, NOT_LISTED), NOT_LISTED);
const snapshot = new Error();
for (const key of Reflect.ownKeys(snapshot))
Reflect.deleteProperty(snapshot, key);
snapshots.set(o, snapshot);
if (fillRecord(o, depth, keys, snapshot, true))
return snapshot;
for (const key of ["name", "message", "code", "stack"]) {
if (Object.prototype.hasOwnProperty.call(snapshot, key))
continue;
if (!spend())
return (define(snapshot, key, PAST_THE_BOUND, true), snapshot);
const read = readMember(o, key);
if (read !== undefined && typeof read !== "function")
define(snapshot, key, member(read, depth, key), false);
}
return snapshot;
};
function pass(v, depth, key) {
if (typeof v === "string")
return egressText(tier, v);
if (typeof v === "function")
return undefined;
if (typeof v !== "object" || v === null)
return v;
const known = snapshots.get(v);
if (known !== undefined)
return known;
if (depth >= VALUE_DEPTH_MAX)
return PAST_THE_DEPTH;
if (isErrorLike(v))
return errorSnapshot(v, depth);
const toJSON = readMember(v, "toJSON");
if (typeof toJSON === "function") {
let reading;
try {
reading = toJSON.call(v, key);
}
catch {
return TO_JSON_THREW;
}
if (reading !== v) {
const out = pass(reading, depth + 1, key);
snapshots.set(v, out);
return out;
}
}
const array = (() => {
try {
return Array.isArray(v);
}
catch {
return false;
}
})();
const keys = listed(v);
if (keys === undefined)
return (snapshots.set(v, NOT_LISTED), NOT_LISTED);
if (array) {
const snapshot = [];
snapshots.set(v, snapshot);
fillArray(v, depth, keys, snapshot);
return snapshot;
}
const snapshot = prototypeOf(v) === null ? Object.create(null) : {};
snapshots.set(v, snapshot);
fillRecord(v, depth, keys, snapshot, false);
return snapshot;
}
return pass(value, 0, "");
}
export function egressAccount(tier, value) {
const snapshots = new SnapshotMap();
const fromElsewhere = [];
const arrays = [];
const elsewhere = (answer) => (typeof answer === "object" && answer !== null ? (snapshots.get(answer) ?? LATER) : foreignValue(tier, answer, snapshots));
const plainShape = (o) => {
try {
if (types.isProxy(o))
return undefined;
if (Array.isArray(o))
return "array";
const proto = Object.getPrototypeOf(o);
return proto === Object.prototype || proto === null ? "record" : undefined;
}
catch {
return undefined;
}
};
function pass(v, depth) {
if (typeof v === "string")
return egressText(tier, v);
if (typeof v === "function")
return undefined;
if (typeof v !== "object" || v === null)
return v;
const known = snapshots.get(v);
if (known !== undefined)
return known;
if (depth >= VALUE_DEPTH_MAX)
return PAST_THE_DEPTH;
const shape = plainShape(v);
if (shape === undefined)
return LATER;
let keys;
try {
keys = Object.keys(v);
}
catch {
return LATER;
}
const snapshot = shape === "array" ? [] : prototypeIsNull(v) ? Object.create(null) : {};
snapshots.set(v, snapshot);
if (shape === "array" && Array.isArray(snapshot))
arrays.push({ snapshot, length: lengthOf(v.length) });
for (const key of keys) {
let answer;
let read;
try {
const d = Reflect.getOwnPropertyDescriptor(v, key);
if (d === undefined)
continue;
const isData = "value" in d;
answer = isData ? d.value : d.get?.call(v);
if (typeof answer === "function" || (!isData && answer === undefined))
continue;
read = isData ? pass(answer, depth + 1) : elsewhere(answer);
}
catch {
continue;
}
if (read === LATER)
fromElsewhere.push({ holder: snapshot, key, value: answer });
Object.defineProperty(snapshot, key, { value: read === LATER ? undefined : read, enumerable: true, writable: true, configurable: true });
}
return snapshot;
}
const prototypeIsNull = (o) => {
try {
return Object.getPrototypeOf(o) === null;
}
catch {
return false;
}
};
const read = pass(value, 0);
const account = read === LATER ? foreignValue(tier, value, snapshots) : read;
for (const later of fromElsewhere) {
const reading = foreignValue(tier, later.value, snapshots);
if (reading === undefined)
Reflect.deleteProperty(later.holder, later.key);
else
Object.defineProperty(later.holder, later.key, { value: reading, enumerable: true, writable: true, configurable: true });
}
for (const a of arrays)
closeArray(a.snapshot, a.length);
if (snapshots.revisits > 0)
cutCycles(account);
return account;
}
function countRedactionMarkers(s) {
return redactionMarkerSpans(s).length;
}
function safeEllipsisTruncate(s, max) {
if (max < 1)
return "";
const budget = max - 1;
let out = "";
for (const codePoint of s) {
if (out.length + codePoint.length > budget)
break;
out += codePoint;
}
return s.slice(0, markSafeCut(s, out.length)) + "…";
}
function boundedString(value, max, redact) {
let s;
try {
s = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
}
catch {
s = "[unserializable result]";
}
s = redact(s);
if (s.length <= max)
return s;
const totalMarkers = countRedactionMarkers(s);
const plainSuffix = (kept) => `…[+${s.length - kept.length} chars]`;
const enrichedSuffix = (kept) => {
const lost = totalMarkers - countRedactionMarkers(kept);
return lost > 0 ? `…[+${s.length - kept.length} chars, ${lost} redaction marker(s) among them]` : plainSuffix(kept);
};
const converge = (suffixFor) => {
let keep = max;
let out = "";
for (let i = 0; i < 4; i++) {
const kept = sliceHeadSafe(s, markSafeCut(s, keep));
out = `${kept}${suffixFor(kept)}`;
if (out.length <= max)
return out;
if (keep === 0)
return undefined;
keep = Math.max(0, keep - (out.length - max));
}
return out.length <= max ? out : undefined;
};
const out = (totalMarkers > 0 ? converge(enrichedSuffix) : undefined) ?? converge(plainSuffix);
if (out === undefined) {
return safeEllipsisTruncate(s, max);
}
if (out.length >= s.length)
return s;
return out;
}
export function boundedRedactedSummary(value, max) {
return boundedString(value, max, (s) => egressText("same-principal", s));
}
export function untrustedEgressForHuman(value, opts) {
const source = boundedString(value, Number.POSITIVE_INFINITY, (s) => egressText("human", s));
const probe = (budget) => {
const bounded = boundedString(source, budget, (s) => s);
return { bounded, overflow: [...neutralizeForFence(bounded)].length - opts.max };
};
let chosen = probe(opts.max);
if (chosen.overflow > 0) {
let fits;
let lo = 0;
let hi = opts.max;
while (hi - lo > 1) {
const mid = lo + Math.floor((hi - lo) / 2);
const p = probe(mid);
if (p.overflow <= 0) {
lo = mid;
fits = p;
}
else {
hi = mid;
}
}
chosen = fits ?? probe(lo);
}
return delimitUntrusted(opts.label, chosen.bounded, opts.max);
}