UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

381 lines (380 loc) • 14.3 kB
import { createHash } from "node:crypto"; import { types } from "node:util"; import { describeFault, receive } from "./mods/kernel/receive.js"; export function canonicalize(value, standsAt = 0) { try { return encode(value, standsAt); } catch { return UNCANONICALIZABLE; } } export const UNCANONICALIZABLE = "<uncanonicalizable>"; export function boundInputHashOf(value) { return createHash("sha256").update(canonicalize(value), "utf8").digest("hex"); } export function sha16(text) { return createHash("sha256").update(text).digest("hex").slice(0, 16); } const SHA16_SHAPE = /^[0-9a-f]{16}$/; export function isSha16(value) { return typeof value === "string" && SHA16_SHAPE.test(value); } export function textContentHashOf(text) { return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`; } const TEXT_CONTENT_HASH_SHAPE = /^sha256:[0-9a-f]{64}$/; export function isTextContentHash(value) { return typeof value === "string" && TEXT_CONTENT_HASH_SHAPE.test(value); } export function exactBoundInputHashOf(tool, input) { const captured = capturedJsonOf(input); if (!captured.ok) return undefined; const form = canonicalize({ tool, input: captured.value }, -1); return form === UNCANONICALIZABLE ? undefined : createHash("sha256").update(form, "utf8").digest("hex"); } export function editOfAnswer(tool, shown, updatedInput) { if (updatedInput === undefined) return undefined; const edit = exactBoundInputHashOf(tool, updatedInput); return edit !== undefined && edit === shown ? undefined : updatedInput; } export function bindableValueOf(value, top = "record") { const received = receive(value, BINDING_RECEIPT); if (!received.ok) return received; const copy = received.value; const topOk = top === "list" ? Array.isArray(copy) : typeof copy === "object" && copy !== null && !Array.isArray(copy); if (!topOk) return { ok: false, fault: { kind: "not-container", path: [] } }; const fault = jsonFaultIn(copy, [], new Set()); return fault === undefined ? { ok: true, value: received.value } : { ok: false, fault }; } export function capturedJsonOf(value, top = "record") { const bound = bindableValueOf(value, top); return bound.ok ? { ok: true, value: jsonFormOf(bound.value) } : bound; } function jsonFormOf(value) { if (Object.is(value, -0)) return 0; if (typeof value !== "object" || value === null) return value; if (Array.isArray(value)) return value.map(jsonFormOf); const out = {}; for (const [key, member] of Object.entries(value)) if (member !== undefined) Object.defineProperty(out, key, { value: jsonFormOf(member), enumerable: true, writable: true, configurable: true }); return out; } function jsonFaultIn(v, path, met) { if (typeof v === "number") return Number.isFinite(v) ? undefined : { kind: "not-finite", path: [...path] }; if (typeof v !== "object" || v === null) return undefined; if (met.has(v)) return { kind: "shared", path: [...path] }; met.add(v); const members = []; if (Array.isArray(v)) { for (let i = 0; i < v.length; i++) { if (!Object.hasOwn(v, i)) return { kind: "hole", path: [...path, String(i)] }; if (v[i] === undefined) return { kind: "undefined-element", path: [...path, String(i)] }; members.push([String(i), v[i]]); } const named = Object.keys(v).find((k) => !isIndexBelow(k, v.length)); if (named !== undefined) return { kind: "list-member", path: [...path, named] }; } else for (const entry of Object.entries(v)) members.push(entry); for (const [key, member] of members) { path.push(key); const fault = jsonFaultIn(member, path, met); path.pop(); if (fault !== undefined) return fault; } return undefined; } export function describeBindingFault(value, fault) { const path = ["args", ...fault.path]; const at = ` at ${path.join(".")}`; switch (fault.kind) { case "not-container": return `a value that is not a record${at}`; case "not-finite": return `a number that is not finite${at}`; case "hole": return `a hole in a list${at}`; case "list-member": return `a named member on a list${at}`; case "undefined-element": return `an undefined list element${at}`; case "shared": return `one object met twice${at} (a shared reference)`; case "too-deep": return `containers nested deeper than ${MAX_DEPTH} levels`; case "not-data": return `${kindOfValueAt(value, fault.path)}${at}`; default: return describeFault({ ...fault, path }); } } function kindOfValueAt(value, path) { let at = value; for (const key of path) at = typeof at === "object" && at !== null ? at[key] : undefined; if (typeof at === "function" || typeof at === "symbol" || typeof at === "bigint") return `a ${typeof at}`; return typeof at === "object" && at !== null ? "an object that is not a plain record or list" : "a value that is not data"; } export const MAX_DEPTH = 256; const BINDING_RECEIPT = Object.freeze({ accessors: "refuse", depth: MAX_DEPTH, past: "refuse", others: "refuse", freeze: true, isProxy: (v) => types.isProxy(v) }); const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/; function segment(text) { if (!LONE_SURROGATE.test(text)) return `${Buffer.byteLength(text, "utf8")}:${text}`; const spelled = JSON.stringify(text); return `S${Buffer.byteLength(spelled, "utf8")}:${spelled}`; } function encode(value, depth = 0) { if (value === null) return "N"; if (value === undefined) return "U"; switch (typeof value) { case "boolean": return value ? "b1" : "b0"; case "number": return `n:${encodeNumber(value)}`; case "bigint": return `i:${value.toString()}`; case "string": return `s${segment(value)}`; case "function": return "fn"; case "symbol": return `y:${value.description ?? ""}`; case "object": { if (depth >= MAX_DEPTH) return "<max-depth>"; try { if (Array.isArray(value)) { let out = `a${value.length}:[`; for (const el of value) out += encode(el, depth + 1); return `${out}]`; } const branded = encodeBranded(value, depth); if (branded !== undefined) return branded; return encodeOwnKeys(value, depth); } catch { return "<unserializable>"; } } default: return "U"; } } function encodeOwnKeys(source, depth, skipIndicesBelow = 0) { const obj = source; const all = Object.keys(obj); const keys = (skipIndicesBelow > 0 ? all.filter((k) => !isIndexBelow(k, skipIndicesBelow)) : all).sort(); let out = `o${keys.length}:{`; for (const k of keys) { let encoded; try { encoded = encode(obj[k], depth + 1); } catch { encoded = "<unreadable-property>"; } out += `${segment(k)}=${encoded}`; } return `${out}}`; } function isIndexBelow(key, limit) { const n = Number(key); return Number.isInteger(n) && n >= 0 && n < limit && String(n) === key; } function brandOf(value) { try { const s = Object.prototype.toString.call(value); return s.startsWith("[object ") && s.endsWith("]") ? s.slice(8, -1) : "Object"; } catch { return "Object"; } } function encodeBranded(value, depth) { const brand = brandOf(value); if (brand === "Object") return undefined; if (ArrayBuffer.isView(value)) { try { const { buffer, byteOffset, byteLength, elements, family } = viewRange(value); const bytesToken = digestBytes(new Uint8Array(buffer, byteOffset, byteLength)); return `V:${family}:${segment(brand)}:${byteLength}:${bytesToken}${encodeOwnKeys(value, depth, elements)}`; } catch { } } const own = encodeOwnKeys(value, depth); try { switch (brand) { case "Date": { const t = Date.prototype.getTime.call(value); return `D:${Number.isNaN(t) ? "Invalid" : encodeNumber(t)}${own}`; } case "Map": { const size = Number(mapSizeGetter.call(value)); let out = `m${size}:{`; let seen = 0; for (const [k, v] of mapEntries.call(value)) { if (seen++ >= size) break; out += `${encode(k, depth + 1)}=${encode(v, depth + 1)}`; } return `${out}}${own}`; } case "Set": { const size = Number(setSizeGetter.call(value)); let out = `t${size}:[`; let seen = 0; for (const v of setValues.call(value)) { if (seen++ >= size) break; out += encode(v, depth + 1); } return `${out}]${own}`; } case "RegExp": { const source = String(regexpSourceGetter.call(value)); const flags = String(regexpFlagsGetter.call(value)); return `r${segment(source)}/${flags}${own}`; } case "Error": { const name = String(value.name); const message = String(value.message); return `E${segment(name)}:${segment(message)}${own}`; } case "URL": { const href = String(urlHrefGetter.call(value)); return `L${segment(href)}${own}`; } case "Boolean": case "Number": case "String": case "BigInt": case "Symbol": { const unboxed = boxedValueOf[brand].call(value); return `B:${encode(unboxed, depth + 1)}${own}`; } case "ArrayBuffer": case "SharedArrayBuffer": { const byteLength = Number((brand === "ArrayBuffer" ? arrayBufferByteLengthGetter : sharedArrayBufferByteLengthGetter).call(value)); return `A:${brand}:${byteLength}:${digestBytes(new Uint8Array(value))}${own}`; } default: break; } } catch { } return `x${segment(brand)}${own}`; } function primordialGetter(proto, key) { const get = Object.getOwnPropertyDescriptor(proto, key)?.get; if (!get) { return () => { throw new Error(`no primordial getter for ${key}`); }; } return get; } const mapEntries = Map.prototype.entries; const setValues = Set.prototype.values; const mapSizeGetter = primordialGetter(Map.prototype, "size"); const setSizeGetter = primordialGetter(Set.prototype, "size"); const regexpSourceGetter = primordialGetter(RegExp.prototype, "source"); const regexpFlagsGetter = primordialGetter(RegExp.prototype, "flags"); const urlHrefGetter = primordialGetter(URL.prototype, "href"); const arrayBufferByteLengthGetter = primordialGetter(ArrayBuffer.prototype, "byteLength"); const sharedArrayBufferByteLengthGetter = typeof SharedArrayBuffer !== "undefined" ? primordialGetter(SharedArrayBuffer.prototype, "byteLength") : primordialGetter({}, "byteLength"); const boxedValueOf = { Boolean: Boolean.prototype.valueOf, Number: Number.prototype.valueOf, String: String.prototype.valueOf, BigInt: BigInt.prototype.valueOf, Symbol: Symbol.prototype.valueOf, }; const typedArrayProto = Object.getPrototypeOf(Uint8Array.prototype); const typedArrayLengthGetter = primordialGetter(typedArrayProto, "length"); const viewGetters = { typed: { buffer: primordialGetter(typedArrayProto, "buffer"), byteOffset: primordialGetter(typedArrayProto, "byteOffset"), byteLength: primordialGetter(typedArrayProto, "byteLength"), }, dataView: { buffer: primordialGetter(DataView.prototype, "buffer"), byteOffset: primordialGetter(DataView.prototype, "byteOffset"), byteLength: primordialGetter(DataView.prototype, "byteLength"), }, }; function viewRange(view) { for (const family of ["typed", "dataView"]) { const g = viewGetters[family]; try { const range = { buffer: g.buffer.call(view), byteOffset: Number(g.byteOffset.call(view)), byteLength: Number(g.byteLength.call(view)), elements: 0, family, }; if (family === "typed") range.elements = Number(typedArrayLengthGetter.call(view)); return range; } catch { continue; } } throw new Error("not a readable ArrayBuffer view"); } function digestBytes(bytes) { return createHash("sha256").update(bytes).digest("hex"); } function encodeNumber(n) { if (Number.isNaN(n)) return "NaN"; if (n === Infinity) return "Inf"; if (n === -Infinity) return "-Inf"; if (n === 0) return "0"; return String(n); } export function canonicalJsonStringify(value) { if (Array.isArray(value)) return `[${value.map((v) => (v === undefined || typeof v === "function" || typeof v === "symbol" ? "null" : canonicalJsonStringify(v))).join(",")}]`; if (value !== null && typeof value === "object") { const rec = value; const keys = Object.keys(rec) .filter((k) => rec[k] !== undefined) .sort(); return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJsonStringify(rec[k])}`).join(",")}}`; } return JSON.stringify(value); }