UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

477 lines (476 loc) • 18.4 kB
export const RECEIPT_FAULTS = Object.freeze(["proxy", "accessor", "hidden", "getter-threw", "prototype-moved", "not-data", "cycle", "too-deep", "uncopyable"]); export function isPlainRecord(v) { if (typeof v !== "object" || v === null || Array.isArray(v)) return false; const proto = Object.getPrototypeOf(v); return proto === Object.prototype || proto === null; } function isIndexName(k) { const n = Number(k); return String(n >>> 0) === k && n !== 4_294_967_295; } function isOrdinaryArray(v) { return Array.isArray(v) && Object.getPrototypeOf(v) === Array.prototype; } const DATE_TO_JSON = Date.prototype.toJSON; const DATE_TIME = Date.prototype.getTime; const DATE_ISO = Date.prototype.toISOString; const TYPED_ARRAY_PROTO = Object.getPrototypeOf(Uint8Array.prototype); const TYPED_ARRAY_NAME = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTO, Symbol.toStringTag).get; const TYPED_ARRAY_LENGTH = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTO, "length").get; const TYPED_ARRAY_SET = TYPED_ARRAY_PROTO.set; const FLOAT64_ARRAY = Float64Array; const ARRAY = Array; const ARRAY_PROTOTYPE = Array.prototype; const ARRAY_SLICE = Array.prototype.slice; const OBJECT_PROTOTYPE = Object.prototype; const HAS_OWN = Object.hasOwn; const OWN_KEYS_ENUMERABLE = Object.keys; const SET_PROTOTYPE = Object.setPrototypeOf; const DEFINE = Reflect.defineProperty; export function dataMember(value) { const d = Object.create(null); d.value = value; d.writable = true; d.enumerable = true; d.configurable = true; return d; } export function appendOwn(list, value) { DEFINE(list, list.length, dataMember(value)); } function listOnNoPrototype(list = []) { return SET_PROTOTYPE(list, null); } const recordOnNoPrototype = () => Object.create(null); function typedArrayIndices(v, name, length) { const out = recordOnNoPrototype(); if (name === "BigInt64Array" || name === "BigUint64Array") return out; const copy = new FLOAT64_ARRAY(length); Reflect.apply(TYPED_ARRAY_SET, copy, [v]); for (let i = 0; i < length; i++) out[i] = copy[i]; return out; } function readOwnMember(v, key, cell) { try { cell.value = v[key]; return true; } catch { return false; } } const NO_MEMBERS = Object.freeze(Object.create(null)); const NO_KEYS = Object.freeze([]); function denseList(v, length) { let holes = 0; for (let i = 0; i < length; i++) if (!HAS_OWN(v, i) && ++holes > 64 && holes * 2 > i + 1) return false; return true; } export function receive(value, mode, held) { const seen = new Map(); const path = listOnNoPrototype(); const pathTo = (below) => { const names = Reflect.apply(ARRAY_SLICE, path, []); if (below !== undefined) appendOwn(names, below); return Object.freeze(names); }; const open = new Set(); const heights = new Map(); const faults = []; const refusedAt = new Map(); const stack = listOnNoPrototype(); const refusals = new Set(); const refuse = (kind) => { const fault = Object.freeze({ kind, path: pathTo() }); refusals.add(fault); throw fault; }; const faultOf = (err) => typeof err === "object" && err !== null && refusals.has(err) ? err : Object.freeze({ kind: "uncopyable", path: pathTo() }); const clones = new Map(); const leafOf = (v) => { if (!clones.has(v)) { let own = v; try { if (typeof v !== "function") own = structuredClone(v); } catch { } clones.set(v, own); } return clones.get(v); }; const other = (v, kind) => { if (mode.others !== "as-is") return refuse(kind); return mode.leaves !== undefined && kind === "not-data" && v !== null && (typeof v === "object" || typeof v === "function") ? leafOf(v) : v; }; const wireForm = (v) => { for (let o = v; o !== null; o = Object.getPrototypeOf(o)) { if (o !== v && mode.isProxy?.(o) === true) return refuse("proxy"); const d = Object.getOwnPropertyDescriptor(o, "toJSON"); if (d === undefined) continue; if (!Object.hasOwn(d, "value")) return refuse("not-data"); if (typeof d.value !== "function") return v; if (d.value !== DATE_TO_JSON) return refuse("not-data"); try { return Number.isFinite(Reflect.apply(DATE_TIME, v, [])) ? Reflect.apply(DATE_ISO, v, []) : null; } catch { return refuse("not-data"); } } return v; }; const refuseContainer = (v, kind) => { if (mode.contain === true) { refusedAt.set(v, kind); open.delete(v); } return refuse(kind); }; const memberOf = (v, d) => { if (Object.hasOwn(d, "value")) { if (mode.accessors === "refuse" && d.enumerable !== true) refuse("hidden"); return d.value; } if (mode.accessors === "refuse") refuse("accessor"); const get = Object.hasOwn(d, "get") ? d.get : undefined; try { return get === undefined ? undefined : Reflect.apply(get, v, []); } catch { return refuse("getter-threw"); } }; const measured = mode.past === "refuse" || mode.others !== "as-is"; const heightOf = (v) => heights.get(v) ?? (open.has(v) || (held?.has(v) === true && mode.isProxy?.(v) !== true && (isOrdinaryArray(v) || isPlainRecord(v))) ? 1 : 0); const pastDepth = (v, level) => measured && level + heightOf(v) > mode.depth; const meet = (v, level) => { if (v === null || v === undefined || typeof v === "string" || typeof v === "number" || typeof v === "boolean") return v; if (typeof v !== "object") return other(v, "not-data"); if (held?.has(v) === true) return pastDepth(v, level) ? refuse("too-deep") : v; if (seen.has(v)) { if (refusedAt.has(v)) return refuse(refusedAt.get(v)); if (open.has(v) && mode.others !== "as-is") return refuse("cycle"); return pastDepth(v, level) ? refuse("too-deep") : seen.get(v); } if (level >= mode.depth && mode.past === "refuse") { if (mode.isProxy?.(v) === true) return refuse("proxy"); if (isOrdinaryArray(v) || isPlainRecord(v)) return refuse("too-deep"); } if (level >= mode.depth) return other(v, "too-deep"); if (mode.isProxy?.(v) === true) return refuse("proxy"); if (mode.wire === true) { const form = wireForm(v); if (form !== v) return form; const name = Reflect.apply(TYPED_ARRAY_NAME, v, []); if (typeof name === "string") { const length = Reflect.apply(TYPED_ARRAY_LENGTH, v, []); let out; try { out = typedArrayIndices(v, name, length); } catch { out = recordOnNoPrototype(); } const captured = Object.create(null); const names = Object.keys(v); let first = names.length; while (first > 0 && !isIndexName(names[first - 1])) first--; for (const k of names.slice(first)) { const d = Object.getOwnPropertyDescriptor(v, k); if (d !== undefined) captured[k] = d; } seen.set(v, out); open.add(v); stack[stack.length] = { v, out, list: false, proto: Object.getPrototypeOf(v), captured, keys: Object.keys(captured), level, next: 0, height: 1, key: "", member: undefined }; return out; } } const list = isOrdinaryArray(v) || (mode.others === "copy" && Array.isArray(v)); if (!list && !isPlainRecord(v) && mode.others !== "copy") return other(v, "not-data"); if (mode.wire === true && (!list || denseList(v, v.length))) return readInOnePass(v, list, level); const proto = Object.getPrototypeOf(v); const captured = Object.getOwnPropertyDescriptors(v); const out = list ? listOnNoPrototype() : recordOnNoPrototype(); seen.set(v, out); open.add(v); if (mode.accessors === "refuse") { const symbols = Object.getOwnPropertySymbols(captured); if (symbols.length > 0 && mode.contain !== true) refuseContainer(v, "hidden"); for (const s of symbols) appendOwn(faults, Object.freeze({ kind: "hidden", path: pathTo(String(s)) })); } const names = Object.getOwnPropertyNames(captured); const keys = mode.wire !== true ? names : names.filter((k) => (list ? isIndexName(k) : captured[k].enumerable === true)); stack[stack.length] = { v, out, list, proto, captured, keys, level, next: 0, height: 1, key: "", member: undefined }; return out; }; const readInOnePass = (v, list, level) => { const names = list ? undefined : OWN_KEYS_ENUMERABLE(v); const count = list ? v.length : names.length; const out = (list ? listOnNoPrototype(new ARRAY(count)) : recordOnNoPrototype()); seen.set(v, out); open.add(v); const f = { v, out, list, proto: Object.getPrototypeOf(v), captured: NO_MEMBERS, keys: NO_KEYS, live: { names, count, pending: undefined }, level, next: 0, height: 1, key: "", member: undefined }; f.live.pending = primitivesUpToAnObject(f); if (f.live.pending === undefined) return finish(f); stack[stack.length] = f; return out; }; const read = { value: undefined }; const primitivesUpToAnObject = (f) => { const { names, count } = f.live; const v = f.v; const into = f.out; while (f.next < count) { const key = names === undefined ? f.next : names[f.next]; f.next++; if (!HAS_OWN(v, key)) continue; if (!readOwnMember(v, key, read)) { memberLeftOut(String(key), "getter-threw"); continue; } const member = read.value; read.value = undefined; if (member === null || member === undefined || typeof member === "string" || typeof member === "number" || typeof member === "boolean") into[key] = member; else if (typeof member === "object") { into[key] = undefined; return { key: String(key), member }; } else memberLeftOut(String(key), "not-data"); } return undefined; }; const memberLeftOut = (key, kind) => { if (mode.contain !== true) { path[path.length] = key; refuse(kind); } appendOwn(faults, Object.freeze({ kind, path: pathTo(key) })); }; const land = (f, key, copy, member) => { if (measured && typeof member === "object" && member !== null) f.height = Math.max(f.height, heightOf(member) + 1); f.out[key] = copy; path.length = f.level; }; const finish = (f) => { heights.set(f.v, f.height); if (mode.accessors === "call-once" && mode.others !== "copy" && Object.getPrototypeOf(f.v) !== f.proto) refuseContainer(f.v, "prototype-moved"); if (Array.isArray(f.out)) { const length = f.captured["length"]?.value; if (typeof length === "number") f.out.length = length; } SET_PROTOTYPE(f.out, Array.isArray(f.out) ? ARRAY_PROTOTYPE : OBJECT_PROTOTYPE); if (mode.freeze === true) Object.freeze(f.out); open.delete(f.v); return f.out; }; const received = (copy) => (mode.contain === true ? { ok: true, value: copy, faults: Object.freeze(faults) } : { ok: true, value: copy }); try { const copy = meet(value, 0); if (stack.length === 0) return received(copy); } catch (err) { return { ok: false, fault: faultOf(err) }; } for (;;) { const f = stack[stack.length - 1]; let key; let captured; let member; if (f.live !== undefined) { let next = f.live.pending; f.live.pending = undefined; if (next === undefined) { try { next = primitivesUpToAnObject(f); } catch (err) { return { ok: false, fault: faultOf(err) }; } } if (next !== undefined) ({ key, member } = next); } else if (f.next < f.keys.length) { key = f.keys[f.next++]; if (f.list && key === "length") continue; captured = f.captured[key]; if (f.level === 0 && !f.list && mode.live?.includes(key) === true && !Object.hasOwn(captured, "value")) { const get = Object.hasOwn(captured, "get") ? captured.get : undefined; const holder = f.v; const d = Object.create(null); d.get = get === undefined ? () => undefined : () => Reflect.apply(get, holder, []); d.enumerable = true; d.configurable = true; DEFINE(f.out, key, d); continue; } } if (key !== undefined) { path[path.length] = key; try { if (captured !== undefined) member = memberOf(f.v, captured); const frames = stack.length; const copy = meet(member, f.level + 1); if (stack.length > frames) { f.key = key; f.member = member; } else land(f, key, copy, member); } catch (err) { if (mode.contain !== true) return { ok: false, fault: faultOf(err) }; appendOwn(faults, faultOf(err)); delete f.out[key]; path.length = f.level; } continue; } let copy; try { copy = finish(f); } catch (err) { stack.length -= 1; const holder = stack[stack.length - 1]; if (mode.contain !== true || holder === undefined) return { ok: false, fault: faultOf(err) }; appendOwn(faults, faultOf(err)); delete holder.out[holder.key]; path.length = holder.level; continue; } stack.length -= 1; const holder = stack[stack.length - 1]; if (holder === undefined) return received(copy); land(holder, holder.key, copy, holder.member); } } export const MODS_PAYLOAD_MODE = Object.freeze({ accessors: "refuse", depth: Infinity, others: "as-is", freeze: true }); export function describeFault(fault) { const at = fault.path.length > 0 ? ` at ${fault.path.join(".")}` : ""; switch (fault.kind) { case "proxy": return `a Proxy${at}`; case "accessor": return `an accessor${at} (a getter is never run)`; case "hidden": return `a member that is not an enumerable data property${at}`; case "getter-threw": return `a getter that threw${at}`; case "prototype-moved": return `a prototype that moved while it was read${at}`; case "not-data": return `a value that is not data${at}`; case "cycle": return `a cycle${at}`; case "too-deep": return `a value nested too deep${at}`; case "uncopyable": return `a value that could not be copied whole${at}`; } } export function sealedObjects(roots) { const holders = new WeakMap(); const met = new Set(); const unsealed = []; const stack = [...roots]; while (stack.length > 0) { const v = stack.pop(); if (typeof v !== "object" || v === null || met.has(v)) continue; met.add(v); const container = isPlainRecord(v) || (Array.isArray(v) && Object.getPrototypeOf(v) === Array.prototype); if (!container) { unsealed.push(v); continue; } if (!Object.isFrozen(v)) unsealed.push(v); const descriptors = Object.getOwnPropertyDescriptors(v); if (Object.getOwnPropertySymbols(descriptors).length > 0) unsealed.push(v); for (const k of Object.getOwnPropertyNames(descriptors)) { if (Array.isArray(v) && k === "length") continue; const d = descriptors[k]; if (!Object.hasOwn(d, "value") || d.enumerable !== true) { unsealed.push(v); continue; } const m = d.value; if (typeof m === "bigint" || typeof m === "symbol" || typeof m === "function") unsealed.push(v); else if (typeof m === "object" && m !== null) { const by = holders.get(m); if (by === undefined) holders.set(m, [v]); else by.push(v); stack.push(m); } } } return withoutUnsealed(met, unsealed, holders); } function withoutUnsealed(objects, unsealed, holders) { const bad = new Set(); while (unsealed.length > 0) { const v = unsealed.pop(); if (bad.has(v)) continue; bad.add(v); for (const h of holders.get(v) ?? []) unsealed.push(h); } const sealed = new Set(); for (const v of objects) if (!bad.has(v)) sealed.add(v); return sealed; }